text:
package io.skysail.core.utils;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.junit.Assert.assertThat;

import java.util.Optional;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.restlet.Request;

import io.skysail.core.utils.CookiesUtils;

@RunWith(MockitoJUnitRunner.class)
public class CookiesUtilsTest {

    @Mock
    private Request request;

    @Before
    public void setUp()  {
    }

    @Test
    public void createCookie()  {

    }

    @Test
    public void getThemeFromCookie_is_null_if_request_does_not_have_any_cookies()  {
        Optional<String> themeFromCookie = CookiesUtils.getThemeFromCookie(request);
        assertThat(themeFromCookie.isPresent(),is(false));
    }

//    @Test
//    public void getThemeFromCookie_is_null_if_request_does_not_have_theme_cookies()  {
//        when(request.getCookies()).thenReturn(cookies);
//        String themeFromCookie = CookiesUtils.getThemeFromCookie(request);
//        assertThat(themeFromCookie,is(nullValue()));
//    }

    @Test
    public void getModeFromCookie()  {

    }

    @Test
    public void getMainPageFromCookie()  {

    }

    @Test
    public void getInstallationFromCookie()  {

    }

    @Test
    public void getEntriesPerPageFromCookie()  {

    }

    @Test
    public void getReferrerFromCookie()  {

    }

}


text:
from django.contrib import admin

from .models import Teacher, Course, Rating

admin.site.register(Teacher)
admin.site.register(Course)
admin.site.register(Rating)

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using Visio = Microsoft.Office.Interop.Visio;
using Office = Microsoft.Office.Core;

namespace VSTO_Diagram
{
    public partial class ThisAddIn
    {
        private void ThisAddIn_Startup(object sender, System.EventArgs e)
        {
            //Create Visio Application Object
            Visio.Application vsdApp = Application;

            //Make Visio Application Invisible
            vsdApp.Visible = false;

            //Create a document object and load a diagram
            Visio.Document vsdDoc = vsdApp.Documents.Open("Drawing.vsd");

            //Save the VDX diagram
            vsdDoc.SaveAs("Drawing1.vdx");

            //Save as PDF file
            vsdDoc.ExportAsFixedFormat(Visio.VisFixedFormatTypes.visFixedFormatPDF,
                "Drawing1.pdf", Visio.VisDocExIntent.visDocExIntentScreen,
                Visio.VisPrintOutRange.visPrintAll, 1, vsdDoc.Pages.Count, false, true,
                true, true, true, System.Reflection.Missing.Value);

            Visio.Page vsdPage = vsdDoc.Pages[1];

            //Save as JPEG Image
            vsdPage.Export("Drawing1.jpg");

            //Quit Visio Object
            vsdApp.Quit();
        }

        private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
        {
        }

        #region VSTO generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InternalStartup()
        {
            this.Startup += new System.EventHandler(ThisAddIn_Startup);
            this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
        }

        #endregion
    }
}


text:
using Loki.Common.Events;
using Loki.Interfaces.Connections;
using Loki.Interfaces.Dependency;
using Loki.Interfaces.Logging;
using Loki.Server.Attributes;
using Loki.Server.Data;

namespace Loki.Example.Logging
{
    [ConnectionRoute("/")]
    public class DefaultRoute : WebSocketDataHandler
    {
        public DefaultRoute(IDependencyUtility dependencyUtility) : base(dependencyUtility)
        {
        }

        public override void OnText(IWebSocketConnection sender, TextFrameEventArgs args)
        {
            Logger.Info($"{sender.ClientIdentifier}/{sender.UniqueIdentifier} sent {args.Message.Length * 2} bytes");

            base.OnText(sender, args);
        }
    }
}


text:
The examples of Areal-level MS-HBM contain several tasks:
1. Generating diffusion embedding matrices of RSFC gradients
2. Generating profiles, initialization parameters, and spatial radius masks
3. Group priors estimation
4. Individual-level parcellation generation

Note that for simplicity, we use the same example data (two CoRR-HNU subjects) for all tasks. However, the initialization parameters estimated in task 2 **won't** be used in task 3, the group priors estimated in task 3 **won't** be used in task 4. We will use the initialization parameters and group priors pre-generated by HCP dataset (40 subjects, 4 sessions).

----

References
==========
+ Kong R, Yang Q, Gordon E, et al. [Individual-Specific Areal-Level Parcellations Improve Functional Connectivity Prediction of Behavior](https://doi.org/10.1093/cercor/bhab101). Cerebral Cortex. In press.

----

Data
====
In this example, we will perform the algorithms on fsaverage6 surface data of CoRR-HNU datasets:
+ **CoRR-HNU:**

  `$CBIG_CODE_DIR/data/example_data/CoRR_HNU/subj0?/subj0?_sess?`

----

Run
====

### **Generating input data**
----

In the terminal, specify the output directory and call the example data generation script:
```
$CBIG_CODE_DIR/stable_projects/brain_parcellation/Kong2022_ArealMSHBM/examples/CBIG_ArealMSHBM_create_example_input_data.sh <output_dir>
```
Note that in your `<output_dir>`, there will be four folders corresponding to four different tasks:
+ `<output_dir>/generate_gradients`
+ `<output_dir>/generate_profiles_and_ini_params`
+ `<output_dir>/estimate_group_priors`
+ `<output_dir>/generate_individual_parcellations`

We will then provide examples for each task separately.

----

### **Example1: generating diffusion embedding matrices of RSFC gradients**
----

This step is mainly needed for gradient-based MSHBM (gMSHBM). If you are only interested in dMSHBM or cMSHBM, you can skip this example.

After [**Generating input data**](#generating-input-data):

+ `<output_dir>/generate_gradients/data_list/fMRI_list/?h_sub?_sess?.txt`

contains the left and right hemisphere fMRI data in `fsaverage6` for subject 1 session 1. Note that our example data only has 1 run for each session, if there are multiple runs, then the corresponding `?h_sub?_sess?.txt` should have multiple columns, where each column corresponds to each run, the columns should be separated by white space.

+ `<output_dir>/generate_gradients/data_list/censor_list/sub?_sess?.txt`

contains the censor lists for subject 1 session 1. The outlier frames will be denoted as 0s. Again, if there are multiple runs, `sub?_sess?.txt` should have multiple columns.

Note that the example data does not have individual surface template files. Therefore, there is no `<output_dir>/generate_gradients/data_list/surface_list`. However, for dataset such as HCP, they do provide the individual surface templates files (e.g. `100206.L.midthickness.32k_fs_LR.surf.gii`). In this case, the user should have a `surface_list` folder. Check the README.md file under `step0_generate_gradient_prior` for more details.

#### 1.1 Generating gradients

In the terminal:
```
cd $CBIG_CODE_DIR/stable_projects/brain_parcellation/Kong2022_ArealMSHBM/step0_generate_gradient_prior
```

Start Matlab, in Matlab command window, run the following commands to generate gradients for subject 1 session 1, the fMRI data are in `fsaverage6`.

```
project_dir = '<output_dir>/generate_gradients';
CBIG_ArealMSHBM_generate_gradient('fsaverage6',project_dir,'1','1');
```
The diffusion embedding matrices of gradients will be saved into `gradients` folder:

+ `<output_dir>/generate_gradients/gradients/sub1/?h_emb_100_distance_matrix.mat`

----

### **Example2: generating profiles, initialization parameters, and spatial radius masks**
----

After [**Generating input data**](#generating-input-data):

+ `<output_dir>/generate_profiles_and_ini_params/data_list/fMRI_list/?h_sub?_sess?.txt`

contains the left and right hemisphere fMRI data in `fsaverage6` for each subject and each session. Note that our example data only has 1 run for each session, if there are multiple runs, then the corresponding `?h_sub?_sess?.txt` should have multiple columns, where each column corresponds to each run, the columns should be separated by white space.

+ `<output_dir>/generate_profiles_and_ini_params/data_list/censor_list/sub?_sess?.txt`

contains the censor lists for each subject and each session. The outlier frames will be denoted as 0s. Again, if there are multiple runs, `sub?_sess?.txt` should have multiple columns. Furthermore, if the user don't want to mask out the outliers in computing profiles, just leave the `censor_list` folder empty.

#### 2.1 Generating profiles

In the terminal:
```
cd $CBIG_CODE_DIR/stable_projects/brain_parcellation/Kong2022_ArealMSHBM/step1_generate_profiles_and_ini_params
```

Start Matlab, in Matlab command window, run the following commands to generate profiles for each session of the 2 subjects, the fMRI data are in `fsaverage6`, the ROIs are defined by `fsaverage3`.

```
project_dir = '<output_dir>/generate_profiles_and_ini_params';
for sub = 1:2
    for sess = 1:2
        CBIG_ArealMSHBM_generate_profiles('fsaverage3','fsaverage6',project_dir,num2str(sub),num2str(sess),'0');
    end
end
```
The profiles will be saved into `profiles` folder:

+ `<output_dir>/generate_profiles_and_ini_params/profiles/sub?/sess?/?h.sub?_sess?_fsaverage6_roifsaverage3.surf2surf_profile.nii.gz`

If the user only has 1 session and would like to apply it on Areal-level MSHBM, the user need to split the session into multiple sub-sessions to make Areal-level MSHBM work. In practice, to estimate better individual-level areal-level parcellation, we also find it's better to split a scan into multiple sub-sessions if the subject has less than 4 runs of data. We suggest each sub-session have ~5 min data.

In this example, we split session 1 of CoRR-HNU subject 1 into 2 sub-sessions. To do that, run the following commands to generate 2 profiles for each sub-session:

```
project_dir = '<output_dir>/generate_profiles_and_ini_params';
CBIG_ArealMSHBM_generate_profiles('fsaverage3','fsaverage6',project_dir,'1','1','1');
```

The profiles will be saved into `profiles` folder:

+ `<output_dir>/generate_profiles_and_ini_params/profiles/sub?/sess?/?h.sub?_sess?_fsaverage6_roifsaverage3.surf2surf_profile_1.nii.gz`

+ `<output_dir>/generate_profiles_and_ini_params/profiles/sub?/sess?/?h.sub?_sess?_fsaverage6_roifsaverage3.surf2surf_profile_2.nii.gz`

#### 2.2 Generating initialization parameters

To generate the initialization parameters, we need to obtain group averaged profiles of the training set. In this example, we use 2 CoRR-HNU subjects with 2 sessions as the training set. Note that the profiles of split sub-sessions will be ignored during averaging. In practice, if the subject has different number of sessions, please set the `num_sess` to be the maximum number of sessions.

```
project_dir = '<output_dir>/generate_profiles_and_ini_params';
num_sub = '2';
num_sess = '2';
CBIG_ArealMSHBM_avg_profiles('fsaverage3','fsaverage6',project_dir,num_sub,num_sess);
```

The results will be saved into `profiles/avg_profile` folder:

+ `<output_dir>/generate_profiles_and_ini_params/profiles/avg_profile/?h_fsaverage6_roifsaverage3_avg_profile.nii.gz`

Next, we will use Schaefer 400-area group-level parcellation to generate the initialization parameters with the group average profiles:

```
project_dir = '<output_dir>/generate_profiles_and_ini_params';
num_parcels = '400';
CBIG_ArealMSHBM_generate_ini_params_Schaefer('fsaverage3','fsaverage6',num_parcels, project_dir);
```

The results will be saved into `group` folder:

+ `<output_dir>/generate_profiles_and_ini_params/group/group.mat`

contains the estimated initialization parameter `mtc`, which is the group-level functional connectivity profile of parcels. `group.mat` also contains the group-level parcellation `lh_labels` and `rh_labels`.

Please also note that we **will not** use the results generated in this step in the following sections. Instead, we will use a pre-computed initialization parameters from 40 HCP subjects for the next steps.

#### 2.3 Generating spatial radius mask

In the areal-level MS-HBM model, we introduce spatial radius mask so that the individual-level parcels should be within the radius mask of group-level parcels. In our paper, we use 30mm radius mask.

In this example, we show how to generate radius mask for Schaefer 400-area parcellation in `fsaverage5` for simplicity. Run the following commands to generate the spatial mask in this example:

```
project_dir = '<output_dir>/generate_profiles_and_ini_params';
num_parcels = '400';
CBIG_ArealMSHBM_generate_radius_mask_Schaefer(num_parcels, 'fsaverage5', project_dir);
```

The results will be saved into `spatial_mask` folder:

+ `<output_dir>/generate_profiles_and_ini_params/spatial_mask/spatial_mask_fsaverage5.mat`

Note that in this example we don't do it in `fsaverage6` is because it's very slow (~40min). However, we released the pre-computed spatial radius masks for Schaefer parcellations in `fsaverage6` and `fs_LR_32k` here:

+ `$CBIG_CODE_DIR/stable_projects/brain_parcellation/Kong2022_ArealMSHBM/lib/spatial_mask`

----

### **Example3: Group priors estimation**
----

Note that we will use pre-computed functional connectivity profiles of 2 CoRR-HNU subject with 2 sessions. There is no need to re-generate the profiles. We will also use pre-computed initialization parameters and spatial radius masks for Schaefer 400-area parcellation.

**Important Note:**

In practice, we use ~40 subjects as training set to estimate group priors. To speed things up, our group prior estimation scripts were written as parent-child relationship. This means that if there are `S` training subjects, the user need to run 1 parent script and `S` children scripts in parallel. If the user would like to train their own group priors with their own data, they need to have a multi-core server which can submit `1+S` jobs which can run in parallel.

In this example, we will estimate group priors with 2 subjects and stop the estimation procedure at the 2nd iteration to save time. In practice, we suggest user to specify the maximum iteration as 10 or leave it empty, the script normally will stop when it converges.

Please also note that we have released our pre-estimated group priors for Schaefer parcellations in `fsaverage6` and `fs_LR_32k` spaces. We suggest the user directly use our pre-estimated group priors to avoid high computational cost in the training step. These group-priors were estimated by 40 HCP subjects. We have tested them in Midnight Scnanning Club (MSC) dataset for `fs_LR_32k` and Adolescent Brain Cognitive Development (ABCD) dataset for `fsaverage6`.

After [**Generating input data**](#generating-input-data),

the `group` folder under `<output_dir>/estimate_group_priors`:
+ `<output_dir>/estimate_group_priors/group/group.mat`

contains the **pre-computed** initialization parameters for Schaefer 400-area parcellation.

The `spatial_mask` folder under `<output_dir>/estimate_group_priors`:
+ `<output_dir>/estimate_group_priors/spatial_mask/spatial_mask_fsaverage6.mat`

contains the **pre-computed** 30mm spatial radius mask for Schaefer 400-area parcellation.

The `profile_list/training_set` folder under `<output_dir>/estimate_group_priors`:
+ `<output_dir>/estimate_group_priors/profile_list/training_set/lh_sess?.txt`
+ `<output_dir>/estimate_group_priors/profile_list/training_set/rh_sess?.txt`

contain functional connectivity profiles of 2 CoRR-HNU subjects with 2 sessions. These files are also **pre-generated**.

The `gradient_list/training_set` folder under `<output_dir>/estimate_group_priors`:
+ `<output_dir>/estimate_group_priors/gradient_list/training_set/gradient_list_lh.txt`
+ `<output_dir>/estimate_group_priors/gradient_list/training_set/gradient_list_rh.txt`

contain diffusion embedding matrices of RSFC gradients of 2 CoRR-HNU subjects generated by 2 sessions. These files are also **pre-generated**.

There is a hyperparameter `beta` for gMSHBM and cMSHBM, which is the weight for the gradient-based/xyz coordinates prior. Larger `beta` indicates stronger weight for the gradient-based/xyz coordinates prior. In practice, the user needs to train model with different `beta` and use validation set to find the optimal `beta`. In this example, we set `beta` to be `5` and we will train with gMSHBM.

The user need to open 3 Matlab sessions to run 1 parent script and 2 chilren scripts. For each Matlab session:

```
cd $CBIG_CODE_DIR/stable_projects/brain_parcellation/Kong2022_ArealMSHBM/step2_estimate_priors
```

In the first Matlab session, run the parent script:
```
project_dir = '<output_dir>/estimate_group_priors';
tmp_dir = '<output_dir>/estimate_group_priors/tmp_results';
beta = '5';
CBIG_ArealMSHBM_gMSHBM_estimate_group_priors_parent(project_dir,'fsaverage6','2','2','400',beta,tmp_dir,'2');
```

In the second Matlab session, run the child script for subject 1:
```
project_dir = '<output_dir>/estimate_group_priors';
tmp_dir = '<output_dir>/estimate_group_priors/tmp_results';
CBIG_ArealMSHBM_gMSHBM_estimate_group_priors_child('1', 'fsaverage6', tmp_dir);
```

In the third Matlab session, run the child script for subject 2:
```
project_dir = '<output_dir>/estimate_group_priors';
tmp_dir = '<output_dir>/estimate_group_priors/tmp_results';
CBIG_ArealMSHBM_gMSHBM_estimate_group_priors_child('2', 'fsaverage6', tmp_dir);
```

The results of each iteration will be saved into `priors` folder, the results of each iteration will be saved as `Params_iteration?.mat`, which contains a struct variable `Params`. The final estimated group priors should be saved as `Params_Final.mat`.

+ `<output_dir>/estimate_group_priors/priors`

The estimated group priors include:
1) Inter-subject functional connectivity variability -- `Params.epsil`
2) Group-level connectivity profiles for each network -- `Params.mu`
3) Intra-subject functional connectivity variability -- `Params.sigma`
4) Spatial prior which denotes the probability of each network occurring at each location -- `Params.theta`

The user can compare their estimated `Params_iteration?.mat` with
+ `$CBIG_CODE_DIR/stable_projects/brain_parcellation/Kong2022_MSHBM/examples/ref_results/estimate_group_priors/priors/gMSHBM/beta5/Params_iteration?.mat`

----

### **Example4: Individual-level parcellations generation**
----

Note that the group priors estimated in [**Group priors estimation**](#Example3:-Group-priors-estimation) won't be used to generate individual parcellations. We will use the group priors pre-computed by using HCP dataset (40 subjects, 4 sessions), which are saved in:

+ `<output_dir>/generate_individual_parcellations/priors/gMSHBM/beta5/Params_Final.mat`

After [**Generating input data**](#generating-input-data),

the `priors` folder under `<output_dir>/generate_individual_parcellations`:
+ `<output_dir>/generate_individual_parcellations/priors/gMSHBM/beta5/Params_Final.mat`

contains the **pre-computed** group priors for Schaefer 400-area parcellation with `beta = 5`.

The `spatial_mask` folder under `<output_dir>/generate_individual_parcellations`:
+ `<output_dir>/generate_individual_parcellations/spatial_mask/spatial_mask_fsaverage6.mat`

contains the **pre-computed** 30mm spatial radius mask for Schaefer 400-area parcellation.

The `profile_list/validation_set` and `profile_list/test_set` folder under `<output_dir>/generate_individual_parcellations`:
+ `<output_dir>/generate_individual_parcellations/profile_list/validation_set/lh_sess?.txt`
+ `<output_dir>/generate_individual_parcellations/profile_list/validation_set/rh_sess?.txt`
+ `<output_dir>/generate_individual_parcellations/profile_list/test_set/lh_sess?.txt`
+ `<output_dir>/generate_individual_parcellations/profile_list/test_set/rh_sess?.txt`

contain functional connectivity profiles of 2 CoRR-HNU subjects with 4 sub-sessions. These files are also **pre-generated**.

The `gradient_list/validation_set` and `gradient_list/test_set` folder under `<output_dir>/generate_individual_parcellations`:
+ `<output_dir>/generate_individual_parcellations/gradient_list/validation_set/gradient_list_lh.txt`
+ `<output_dir>/generate_individual_parcellations/gradient_list/validation_set/gradient_list_rh.txt`
+ `<output_dir>/generate_individual_parcellations/gradient_list/test_set/gradient_list_lh.txt`
+ `<output_dir>/generate_individual_parcellations/gradient_list/test_set/gradient_list_rh.txt`

The `data_list/validation_set` folder under `<output_dir>/generate_individual_parcellations`:
+ `<output_dir>/generate_individual_parcellations/data_list/validation_set/fMRI_list/?h_sub1.txt`

contain fMRI data of CoRR-HNU subject 1. These fMRI files will be used to evaludate parcellation quality during validation.

#### 4.1 Validation set

We will still use gMSHBM as an example. This algorithm contains three parameters:

+ `beta`: The weight of gradient-based prior.
+ `w`: The weight of group spatial prior `Params.theta`.
+ `c`: The weight of MRF smoothness prior.

These three parameters can be selected by validation set. Assuming subjects in validation set has `T` sessions, we normally use `T1` sessions to generate the individual parcellations for each validation subject, and apply the parcellations on the remaining `T-T1` sessions to compute homogeneity. We will do a grid search for `beta`, `w` and `c`, and compute homogeneity for all validation subjects. We then average the homogeneity across the validation subjects, the set of `beta`, `w` and `c` gives the highest averaged homogeneity will be selected to generate individual parcellations for the test set.

In this example, we will use the CoRR-HNU subjects 1 as the validation set. We use session 1 (i.e., sub-session 1 and 2) to estimate parcellation and use session 2 to compute the homogeneity.

In the terminal:
```
cd $CBIG_CODE_DIR/stable_projects/brain_parcellation/Kong2022_ArealMSHBM/step3_generate_ind_parcellations
```

Start Matlab, in Matlab command window, run the following commands:

```
project_dir = '<output_dir>/generate_individual_parcellations';

% Generate individual parcellation for validation subjects using 2 sub-sessions of session 1 and compute homogeneity using fMRI data of session 2
% Do a grid search for w and c for a specific beta
curr_beta = '5';
w_set = [40 50 60];
c_set = [40 50 60];
for i = 1:length(w_set)
    curr_w = num2str(w_set(i));
    for j = 1:length(c_set)
        curr_c = num2str(c_set(j));
        for sub = 1
            homo_with_weight(sub,:) = CBIG_ArealMSHBM_parameters_validation(project_dir,'fsaverage6','2','400',num2str(sub), curr_w, curr_c, curr_beta, 'gMSHBM');
        end
        homo(i,j) = mean(mean(homo_with_weight));
    end
end

```
The set of `w`, `c` and `beta` with the highest `homo` should be selected as the parameters for test set. If `w = 50`, `c = 50`, for subject 1, `homo_with_weight = 0.6042`.

The individual parcellation of validation set will be saved into

+ `<output_dir>/generate_individual_parcellations/ind_parcellation_gMSHBM/validation_set/2_sess/beta5/Ind_parcellation_MSHBM_sub1_w50_MRF50_beta5.mat`

The relevant homogeneity results will be saved into

+ `<output_dir>/generate_individual_parcellations/homogeneity_gMSHBM/validation_set/2_sess/beta5/Ind_homogeneity_ArealMSHBM_sub1_w50_MRF50_beta5.mat`

#### 4.2 Test set

We will still use gMSHBM as an example. Assuming `w = 50`, `c = 50` and `beta = 5` is the set of parameters give the highest homogeneity. We then apply them on the test set to generate parcellations. In this example, we use CoRR-HNU subject 2 as the test subject.

The `profile_list/test_set` folder under `<output_dir>/generate_individual_parcellations`:
+ `<output_dir>/generate_individual_parcellations/profile_list/test_set/lh_sess?.txt`
+ `<output_dir>/generate_individual_parcellations/profile_list/test_set/rh_sess?.txt`

contain functional connectivity profiles of 2 CoRR-HNU subjects with 2 sessions.

```
project_dir = '<output_dir>/generate_individual_parcellations';

% Generate individual parcellation for subject 2 using 4 sub-sessions
[lh_labels, rh_labels] = CBIG_ArealMSHBM_gMSHBM_generate_individual_parcellation(project_dir,'fsaverage6','4','400','2','50','50','5','test_set');

% Visualize the parcellation of subject 2
CBIG_DrawSurfaceMaps(lh_labels,rh_labels, 'fsaverage6', 'inflated', 1, 400, rand(401,3));
```

The generated individual parcellations will be saved under:
+ `<output_dir>/generate_individual_parcellations/ind_parcellation/test_set/4_sess/beta5/Ind_parcellation_MSHBM_sub2_w50_MRF50_beta5.mat`

### Check example results
----

+ We provide a script which checks user's example results with our reference results:

   `$CBIG_CODE_DIR/stable_projects/brain_parcellation/Kong2022_ArealMSHBM/examples/CBIG_ArealMSHBM_check_example_results.m`

   Assume your example results are saved in `out_dir`. Please run the following command to check your results:
   ```
   cd $CBIG_CODE_DIR/stable_projects/brain_parcellation/Kong2022_ArealMSHBM/examples
   CBIG_ArealMSHBM_check_example_results(out_dir)
   ```

----

Bugs and Questions
====
Please contact Ru(by) Kong at roo.cone@gmail.com.


text:
<!DOCTYPE html>
<script src="/js-test-resources/gc.js"></script>
<script src="/js-test-resources/js-test.js"></script>
<script>
jsTestIsAsync = true;

var numberOfDocumentsBefore, numberOfDocumentsAfter;
function checkDocumentLeakAndFinishTest() {
    numberOfDocumentsAfter = internals.numberOfLiveDocuments();
    shouldBe("numberOfDocumentsAfter", "numberOfDocumentsBefore");
    finishJSTest();
}

function runTest() {
    numberOfDocumentsBefore = internals.numberOfLiveDocuments();

    var xhr = new XMLHttpRequest();
    xhr.responseType = 'document';
    xhr.overrideMimeType("text/html");
    xhr.onreadystatechange = function () {
        if (this.readyState == XMLHttpRequest.HEADERS_RECEIVED) {
            testPassed("this reached HEADERS_RECEIVED state.");
            this.abort();
            asyncGC(checkDocumentLeakAndFinishTest);
        } else if (this.readyState == XMLHttpRequest.LOADING) {
            testFailed("this reached LOADING state, but it should not reach here after abort().");
        } else if (this.readyState == XMLHttpRequest.DONE) {
            testPassed("this reached DONE state.");
        }
    }

    xhr.open("GET", "resources/get.txt", true);
    xhr.send(null);
    xhr = null;
}

// run GC before test to avoid document count being flaky.
asyncGC(runTest);
</script>


text:
Idea Fight is a web application for helping you prioritize a list of ideas.
For details on why I wrote this on how it works, check out this
[blog post](http://hoelz.ro/blog/idea-fight).

## Installation

Idea Fight is a client-side-only web application, so you don't need to install
anything if you don't want to!  There's a version that you can use at
http://idea-fight.hoelz.ro.

If you want to install your own version in order to make changes, you'll need
to install the [Elm compiler](http://elm-lang.org) version 0.17.1 (the most
current as of this writing).  After you have Elm installed, you can build
the JavaScript file using `elm-make`:

    elm-make --output js/idea-fight.js Main.elm

Copy the `js/`, `css/`, and `index.html` files to wherever you want to host your
version, or simply open `index.html` in your browser.

# How to Use It

To use Idea Fight, just enter a list of ideas into the provided text box, one per line:

![Input your ideas](screenshots/idea-list.jpg)

Once you're done, hit the "Continue" button, and you'll be presented with two
ideas among the ideas you entered in:

![Choose the better idea](screenshots/choice.jpg)

Click the idea you prefer between the choices.  As Idea Fight determines which
ideas are the best, it will present them to you; keep making selections until
you have as many good ideas as you want!

![Full example](screenshots/example.gif)


text:
package com.android.common.content;

import android.accounts.Account;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.provider.SyncStateContract;

/**
 * Extends the schema of a ContentProvider to include the _sync_state table
 * and implements query/insert/update/delete to access that table using the
 * authority "syncstate". This can be used to store the sync state for a
 * set of accounts.
 */
public class SyncStateContentProviderHelper {
    private static final String SELECT_BY_ACCOUNT =
            SyncStateContract.Columns.ACCOUNT_NAME + "=? AND "
                    + SyncStateContract.Columns.ACCOUNT_TYPE + "=?";

    private static final String SYNC_STATE_TABLE = "_sync_state";
    private static final String SYNC_STATE_META_TABLE = "_sync_state_metadata";
    private static final String SYNC_STATE_META_VERSION_COLUMN = "version";

    private static long DB_VERSION = 1;

    private static final String[] ACCOUNT_PROJECTION =
            new String[]{SyncStateContract.Columns.ACCOUNT_NAME,
                    SyncStateContract.Columns.ACCOUNT_TYPE};

    public static final String PATH = "syncstate";

    private static final String QUERY_COUNT_SYNC_STATE_ROWS =
            "SELECT count(*)"
                    + " FROM " + SYNC_STATE_TABLE
                    + " WHERE " + SyncStateContract.Columns._ID + "=?";

    public void createDatabase(SQLiteDatabase db) {
        db.execSQL("DROP TABLE IF EXISTS " + SYNC_STATE_TABLE);
        db.execSQL("CREATE TABLE " + SYNC_STATE_TABLE + " ("
                + SyncStateContract.Columns._ID + " INTEGER PRIMARY KEY,"
                + SyncStateContract.Columns.ACCOUNT_NAME + " TEXT NOT NULL,"
                + SyncStateContract.Columns.ACCOUNT_TYPE + " TEXT NOT NULL,"
                + SyncStateContract.Columns.DATA + " TEXT,"
                + "UNIQUE(" + SyncStateContract.Columns.ACCOUNT_NAME + ", "
                + SyncStateContract.Columns.ACCOUNT_TYPE + "));");

        db.execSQL("DROP TABLE IF EXISTS " + SYNC_STATE_META_TABLE);
        db.execSQL("CREATE TABLE " + SYNC_STATE_META_TABLE + " ("
                + SYNC_STATE_META_VERSION_COLUMN + " INTEGER);");
        ContentValues values = new ContentValues();
        values.put(SYNC_STATE_META_VERSION_COLUMN, DB_VERSION);
        db.insert(SYNC_STATE_META_TABLE, SYNC_STATE_META_VERSION_COLUMN, values);
    }

    public void onDatabaseOpened(SQLiteDatabase db) {
        long version = DatabaseUtils.longForQuery(db,
                "SELECT " + SYNC_STATE_META_VERSION_COLUMN + " FROM " + SYNC_STATE_META_TABLE,
                null);
        if (version != DB_VERSION) {
            createDatabase(db);
        }
    }

    public Cursor query(SQLiteDatabase db, String[] projection,
            String selection, String[] selectionArgs, String sortOrder) {
        return db.query(SYNC_STATE_TABLE, projection, selection, selectionArgs,
                null, null, sortOrder);
    }

    public long insert(SQLiteDatabase db, ContentValues values) {
        return db.replace(SYNC_STATE_TABLE, SyncStateContract.Columns.ACCOUNT_NAME, values);
    }

    public int delete(SQLiteDatabase db, String userWhere, String[] whereArgs) {
        return db.delete(SYNC_STATE_TABLE, userWhere, whereArgs);
    }

    public int update(SQLiteDatabase db, ContentValues values,
            String selection, String[] selectionArgs) {
        return db.update(SYNC_STATE_TABLE, values, selection, selectionArgs);
    }

    public int update(SQLiteDatabase db, long rowId, Object data) {
        if (DatabaseUtils.longForQuery(db, QUERY_COUNT_SYNC_STATE_ROWS,
                new String[]{Long.toString(rowId)}) < 1) {
            return 0;
        }
        db.execSQL("UPDATE " + SYNC_STATE_TABLE
                + " SET " + SyncStateContract.Columns.DATA + "=?"
                + " WHERE " + SyncStateContract.Columns._ID + "=" + rowId,
                new Object[]{data});
        // assume a row was modified since we know it exists
        return 1;
    }

    public void onAccountsChanged(SQLiteDatabase db, Account[] accounts) {
        Cursor c = db.query(SYNC_STATE_TABLE, ACCOUNT_PROJECTION, null, null, null, null, null);
        try {
            while (c.moveToNext()) {
                final String accountName = c.getString(0);
                final String accountType = c.getString(1);
                Account account = new Account(accountName, accountType);
                if (!contains(accounts, account)) {
                    db.delete(SYNC_STATE_TABLE, SELECT_BY_ACCOUNT,
                            new String[]{accountName, accountType});
                }
            }
        } finally {
            c.close();
        }
    }

    /**
     * Checks that value is present as at least one of the elements of the array.
     * @param array the array to check in
     * @param value the value to check for
     * @return true if the value is present in the array
     */
    private static <T> boolean contains(T[] array, T value) {
        for (T element : array) {
            if (element == null) {
                if (value == null) return true;
            } else {
                if (value != null && element.equals(value)) return true;
            }
        }
        return false;
    }
}


text:
start_service do
end


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-sransitional.dtd">

	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
	<title>Opscode - 405 Method Not Allowed</title>
	<link media="all" rel="stylesheet" type="text/css" href="css/all.css" />

405 - Method Not Allowed

Sorry, the method you request is not available for this resource.

			Opscode

				© 2009 Opscode, Inc. All Rights Reserved


text:
This directory contains a number of components built for a project where a number of sensors
communicating over a IEEE802.15.4 network needed to send data to Byteport.

## Directories:
 /byteport-stomp-client
  C implementation of the STOMP client connecting to the Byteport RABBITMQ message broker (up and down).

 /i8-transceiver
  This program acts as a bridge between a ieee802.15.4 network and the Byteport STOMP client.

 /libs/apr
  ?

 /libs/libipc
  Packet definitions for the integrating with the byteport-stomp-client

 /libs/liblog
  Shared library used to log data to log server.

 /libs/libstomp
  C implementation of the STOMP protocol, see also /lib/libstomp/README.txt

## TODO
 - SSL encryption for STOMP client.
 - HTTP/HTTPS client implementation.


text:
package org.orekit.files.ccsds.utils.parsing;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.hipparchus.exception.LocalizedCoreFormats;
import org.orekit.data.DataSource;
import org.orekit.errors.OrekitException;
import org.orekit.errors.OrekitInternalError;
import org.orekit.files.ccsds.utils.FileFormat;
import org.orekit.files.ccsds.utils.lexical.LexicalAnalyzerSelector;
import org.orekit.files.ccsds.utils.lexical.MessageParser;
import org.orekit.files.ccsds.utils.lexical.MessageVersionXmlTokenBuilder;
import org.orekit.files.ccsds.utils.lexical.ParseToken;
import org.orekit.files.ccsds.utils.lexical.XmlTokenBuilder;

/** Parser for CCSDS messages.
 *

 * Note than starting with Orekit 11.0, CCSDS message parsers are
 * mutable objects that gather the data being parsed, until the
 * message is complete and the {@link #parseMessage(org.orekit.data.DataSource)
 * parseMessage} method has returned. This implies that parsers
 * should not be used in a multi-thread context. The recommended
 * way to use parsers is to either dedicate one parser for each message
 * and drop it afterwards, or to use a single-thread loop.
 *

 * @param <T> type of the file
 * @author Luc Maisonobe
 * @since 11.0
 */
public abstract class AbstractMessageParser<T> implements MessageParser<T> {

    /** Safety limit for loop over processing states. */
    private static final int MAX_LOOP = 100;

    /** Root element for XML files. */
    private final String root;

    /** Key for format version. */
    private final String formatVersionKey;

    /** Anticipated next processing state. */
    private ProcessingState next;

    /** Current processing state. */
    private ProcessingState current;

    /** Fallback processing state. */
    private ProcessingState fallback;

    /** Format of the file ready to be parsed. */
    private FileFormat format;

    /** Flag for XML end tag. */
    private boolean endTagSeen;

    /** Simple constructor.
     * @param root root element for XML files
     * @param formatVersionKey key for format version
     */
    protected AbstractMessageParser(final String root, final String formatVersionKey) {
        this.root             = root;
        this.formatVersionKey = formatVersionKey;
        this.current          = null;
        setFallback(new ErrorState());
    }

    /** Set fallback processing state.
     *

     * The fallback processing state is used if anticipated state fails
     * to parse the token.
     *

     * @param fallback processing state to use if anticipated state does not work
     */
    public void setFallback(final ProcessingState fallback) {
        this.fallback = fallback;
    }

    /** Reset parser to initial state before parsing.
     * @param fileFormat format of the file ready to be parsed
     * @param initialState initial processing state
     */
    protected void reset(final FileFormat fileFormat, final ProcessingState initialState) {
        format     = fileFormat;
        current    = initialState;
        endTagSeen = false;
        anticipateNext(fallback);
    }

    /** Set the flag for XML end tag.
     * @param endTagSeen if true, the XML end tag has been seen
     */
    public void setEndTagSeen(final boolean endTagSeen) {
        this.endTagSeen = endTagSeen;
    }

    /** Check if XML end tag has been seen.
     * @return true if XML end tag has been seen
     */
    public boolean wasEndTagSeen() {
        return endTagSeen;
    }

    /** Get the current processing state.
     * @return current processing state
     */
    public ProcessingState getCurrent() {
        return current;
    }

    /** Get the file format.
     * @return file format
     */
    protected FileFormat getFileFormat() {
        return format;
    }

    /** {@inheritDoc} */
    @Override
    public T parseMessage(final DataSource source) {
        try {
            return LexicalAnalyzerSelector.select(source).accept(this);
        } catch (IOException ioe) {
            throw new OrekitException(ioe, LocalizedCoreFormats.SIMPLE_MESSAGE,
                                      ioe.getLocalizedMessage());
        }
    }

    /** {@inheritDoc} */
    @Override
    public String getFormatVersionKey() {
        return formatVersionKey;
    }

    /** {@inheritDoc} */
    @Override
    public Map<String, XmlTokenBuilder> getSpecialXmlElementsBuilders() {

        final HashMap<String, XmlTokenBuilder> builders = new HashMap<>();

        if (formatVersionKey != null) {
            // special handling of root tag that contains the format version
            builders.put(root, new MessageVersionXmlTokenBuilder());
        }

        return builders;

    }

    /** Anticipate what next processing state should be.
     * @param anticipated anticipated next processing state
     */
    public void anticipateNext(final ProcessingState anticipated) {
        this.next = anticipated;
    }

    /** {@inheritDoc} */
    @Override
    public void process(final ParseToken token) {

        // loop over the various states until one really processes the token
        for (int i = 0; i < MAX_LOOP; ++i) {
            if (current.processToken(token)) {
                return;
            }
            current = next;
            next    = fallback;
        }

        // this should never happen
        throw new OrekitInternalError(null);

    }

}


text:
module Mongoid
  module Association
    module Referenced

      class HasOne

        class Eager < Association::Referenced::Eager::Base

          private

          def preload
            @docs.each do |d|
              set_relation(d, nil)
            end

            each_loaded_document do |doc|
              id = doc.send(key)
              set_on_parent(id, doc)
            end
          end

          def group_by_key
            @association.primary_key
          end

          def key
            @association.foreign_key
          end

        end
      end
    end
  end
end


text:
<!DOCTYPE html>

		<title>WiFi Connect</title>
		<meta name="viewport" content="width=device-width, initial-scale=1">

		<link rel="stylesheet" href="css/bootstrap.min.css">

		<link rel="shortcut icon" href="/img/favicon.png">

					resin.io

Hi! Please choose your wifi from the list.

					<form class="form form-horizontal" id='connect-form' action='/connect' method='post'>

							SSID

								<select id='ssid-select' class="form-control" name='ssid'></select>

							password

								<input type='password' class="form-control" name='password'></input>

							<button type='submit' class='btn btn-success col-lg-3 col-lg-offset-3'>Connect</button>

					</form>

Applying changes...

Your device will soon be online. If connection is unsuccessful, the Access Point will be back up in a few minutes, and reloading this page will allow you to try again.

No wifi networks available

Please ensure there is a network within range and reboot the device.


text:
require 'spec_helper'

describe ExampleController, type: :controller do
  before(:each) do
    PersistCampaign.configure { |c| c.keys = %w{alpha beta} }
  end
  let(:params) { { alpha: '1', beta: '2' } }

  it 'should persist specified params' do
    get 'foo', params
    expect(response).to redirect_to('/example/bar?alpha=1&beta=2')
  end

  it 'does not overwrite existing params' do
    get 'action_with_params', params
    expect(response).to redirect_to('/example/bar?hello=world&alpha=1&beta=2')
  end

  it 'ignores unconfigured params' do
    get 'foo', params.merge(colour: 'red')
    expect(response).to redirect_to('/example/bar?alpha=1&beta=2')
  end

  context 'with no params to persist' do
    it 'redirects normally' do
      get 'foo'
      expect(response).to redirect_to('/example/bar')
    end
  end
end


text:
package cn.xishan.oftenporter.porter.core.annotation.deal;

import cn.xishan.oftenporter.porter.core.annotation.sth.PorterParamGetter;
import cn.xishan.oftenporter.porter.core.base.PortMethod;

/**
 * Created by chenyg on 2017-04-26.
 */
public class _SyncPorterOption
{
    PortMethod method;
    private String pathWithContext;
    PorterParamGetter porterParamGetter;

    public _SyncPorterOption(PorterParamGetter porterParamGetter)
    {
        this.porterParamGetter = porterParamGetter;
    }

    public void setMethod(PortMethod method)
    {
        this.method = method;
    }

    public PortMethod getMethod()
    {
        return method;
    }

    public String getPathWithContext()
    {
        return pathWithContext;
    }

    public void setOk()
    {
        pathWithContext = "/" + porterParamGetter.getContext() + "/" + porterParamGetter
                .getClassTied() + "/" + porterParamGetter.getFunTied();
        porterParamGetter = null;
    }
}


text:
<?php defined('BX_DOL') or die('hack attempt');

bx_import('BxDolModuleDb');

/*
 * Module database queries
 */
class BxBaseModGeneralDb extends BxDolModuleDb
{
    protected $_oConfig;

    public function __construct(&$oConfig)
    {
        parent::__construct($oConfig);
        $this->_oConfig = $oConfig;
    }
}

/** @} */


text:
using System;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using SharpDomain.Business;
using SharpDomain.EventSourcing;
using TechTalk.SpecFlow;

namespace SharpDomain.Specs.Business.Steps
{
    [Binding]
    public class AggregateSteps
    {

        #region [ Aggregate factory setup ]

        [Given(@"a new reflection-based aggregate factory instance")]
        public void GivenANewAggregateFactoryInstance()
        {
            var factory = new ReflectionAggregateFactory();
            ScenarioContext.Current.Set<IAggregateFactory>(factory);
        }

        #endregion

        #region [ Aggregate creation setup ]

        [Given(@"a new aggregate is obtained from the aggregate factory")]
        [When(@"a new aggregate is obtained from the aggregate factory")]
        public void WhenANewAggregateIsObtainedFromTheAggregateFactory()
        {
            var factory = ScenarioContext.Current.Get<IAggregateFactory>();
            var aggregate = factory.Create<Aggregate>();
            ScenarioContext.Current.Set<IAggregate>(aggregate);
        }

        [Given(@"a new stateful aggregate is obtained from the aggregate factory")]
        public void GivenANewStatefulAggregateIsObtainedFromTheAggregateFactory()
        {
            var factory = ScenarioContext.Current.Get<IAggregateFactory>();
            var aggregate = factory.Create<StatefulTestAggregate>();
            ScenarioContext.Current.Set<IAggregate>(aggregate);
        }

        #endregion

        #region [ Aggregate event applying setup ]

        [When(@"a null is applied to the aggregate")]
        public void WhenANullIsAppliedToTheAggregate()
        {
            var aggregate = ScenarioContext.Current.Get<IAggregate>();
            CommonSteps.RunExceptionControlledStep(() => aggregate.ApplyEvent(null));
        }

        [When(@"a new event ""(.*)"" of type TestAggregateCreated is applied to the aggregate with id ""(.*)""")]
        public void WhenANewEventEOfTypeTestAggregateCreatedIsAppliedToTheAggregateWithId(string @eventName, Guid aggregateId)
        {
            var createdEvent = new TestAggregateCreatedEvent(aggregateId);
            ScenarioContext.Current.Set<IEvent>(createdEvent, @eventName);

            var aggregate = ScenarioContext.Current.Get<IAggregate>();
            CommonSteps.RunExceptionControlledStep(() => aggregate.ApplyEvent(createdEvent));
        }

        [When(@"a new event ""(.*)"" of type TestAggregateModified is applied to the aggregate with value ""(.*)""")]
        public void WhenANewEventOfTypeTestAggregateModifiedIsAppliedToTheAggregateWithId(string @eventName, string value)
        {
            var modifiedEvent = new TestAggregateModifiedEvent() { Value = value };
            ScenarioContext.Current.Set<IEvent>(modifiedEvent, @eventName);

            var aggregate = ScenarioContext.Current.Get<IAggregate>();
            CommonSteps.RunExceptionControlledStep(() => aggregate.ApplyEvent(modifiedEvent));
        }

        [When(@"a new event ""(.*)"" of type TestAggregateModified version two is applied to the aggregate with value ""(.*)"" and int value (.*)")]
        public void WhenANewEventOfTypeTestAggregateModifiedVersionTwoIsAppliedToTheAggregateWithValue(string @eventName, string value, int intValue)
        {
            var modifiedEvent = new TestAggregateModifiedEvent_V2() { Value = value, IntValue = intValue };
            ScenarioContext.Current.Set<IEvent>(modifiedEvent, @eventName);

            var aggregate = ScenarioContext.Current.Get<IAggregate>();
            CommonSteps.RunExceptionControlledStep(() => aggregate.ApplyEvent(modifiedEvent));
        }

        [When(@"a new event ""(.*)"" of type TestAggregateOther is applied to the aggregate")]
        public void WhenANewEventOfTypeTestAggregateOtherIsAppliedToTheAggregate(string @eventName)
        {
            var otherEvent = new TestAggregateOtherEvent();
            ScenarioContext.Current.Set<IEvent>(otherEvent, @eventName);

            var aggregate = ScenarioContext.Current.Get<IAggregate>();
            CommonSteps.RunExceptionControlledStep(() => aggregate.ApplyEvent(otherEvent));
        }
        #endregion

        #region [ Aggregate assertions ]

        [Then(@"the aggregate is not null")]
        public void ThenTheAggregateIsNotNull()
        {
            var aggregate = ScenarioContext.Current.Get<IAggregate>();

            Assert.That(aggregate, Is.Not.Null);
        }

        [Then(@"the aggregate type is Aggregate class")]
        public void ThenTheAggregateTypeIsAggregateClass()
        {
            var aggregate = ScenarioContext.Current.Get<IAggregate>();

            Assert.That(aggregate, Is.InstanceOf<Aggregate>());
        }

        [Then(@"the aggregate type is StatefulTestAggregate class")]
        public void ThenTheAggregateTypeIsStatefulTestAggregateClass()
        {
            var aggregate = ScenarioContext.Current.Get<IAggregate>();

            Assert.That(aggregate, Is.InstanceOf<StatefulTestAggregate>());
        }

        [Then(@"the aggregate has (.*) uncommitted events")]
        public void ThenTheAggregateHasUncommittedEvents(int uncommittedEventsCount)
        {
            var aggregate = ScenarioContext.Current.Get<IAggregate>();

            Assert.That(aggregate.UncommittedEvents.Count(), Is.EqualTo(uncommittedEventsCount));
        }

        [Then(@"the aggregate uncommitted event number (.*) is ""(.*)""")]
        public void ThenTheAggregateUncommittedEventNumberIs(int eventNumber, string @eventName)
        {
            var aggregate = ScenarioContext.Current.Get<IAggregate>();
            var @event = ScenarioContext.Current.Get<IEvent>(@eventName);

            Assert.That(aggregate.UncommittedEvents.ElementAt(eventNumber - 1), Is.SameAs(@event));
        }

        [Then(@"the aggregate has no uncommitted events")]
        public void ThenTheAggregateHasNoUncommittedEvents()
        {
            var aggregate = ScenarioContext.Current.Get<IAggregate>();

            Assert.That(aggregate.UncommittedEvents, Is.Not.Null);
            CollectionAssert.IsEmpty(aggregate.UncommittedEvents);
        }

        [Then(@"the aggregate has (.*) explicitly applied events")]
        public void ThenTheAggregateHasExplicitlyAppliedEvents(int count)
        {
            var aggregate = (StatefulTestAggregate)ScenarioContext.Current.Get<IAggregate>();

            Assert.That(aggregate.AppliedEvents.Count, Is.EqualTo(count));
        }

        [Then(@"the aggregate applied event number (.*) is ""(.*)""")]
        public void ThenTheAggregateAppliedEventNumberIs(int eventNumber, string eventName)
        {
            var aggregate = (StatefulTestAggregate)ScenarioContext.Current.Get<IAggregate>();
            var @event = ScenarioContext.Current.Get<IEvent>(eventName);

            Assert.That(aggregate.AppliedEvents[eventNumber - 1], Is.SameAs(@event));
        }
        #endregion [ Aggregate assertions ]

    }

    #region [ Test types ]

    internal class StatefulTestAggregate : StatefulAggregate
    {
        public List<IEvent> AppliedEvents = new List<IEvent>();

        private void Apply(TestAggregateCreated e)
        {
            AppliedEvents.Add(e);
        }
        private void Apply(TestAggregateModified e)
        {
            AppliedEvents.Add(e);
        }
    }

    internal interface TestAggregateCreated : IEvent
    {

    }

    internal class TestAggregateCreatedEvent : TestAggregateCreated
    {
        public TestAggregateCreatedEvent(Guid sourceId)
        {
            SourceId = sourceId;
        }

        public Guid SourceId { get; set; }
        public int Version { get; set; }
    }

    internal interface TestAggregateModified : IEvent
    {
        string Value { get; set; }
    }

    internal class TestAggregateModifiedEvent : TestAggregateModified
    {
        public string Value { get; set; }
        public Guid SourceId { get; set; }
        public int Version { get; set; }
    }

    internal interface TestAggregateModified_V2 : TestAggregateModified
    {
        int IntValue { get; set; }
    }

    internal class TestAggregateModifiedEvent_V2 : TestAggregateModifiedEvent, TestAggregateModified_V2
    {
        public int IntValue { get; set; }
    }

    internal interface TestAggregateOther : IEvent
    {
    }

    internal class TestAggregateOtherEvent : TestAggregateOther
    {
        public Guid SourceId { get; set; }
        public int Version { get; set; }
    }

    #endregion
}


text:
package com.zuoxiaolong.niubi.job.service.impl;

import com.zuoxiaolong.niubi.job.core.helper.LoggerHelper;
import com.zuoxiaolong.niubi.job.persistent.BaseDao;
import com.zuoxiaolong.niubi.job.persistent.entity.Role;
import com.zuoxiaolong.niubi.job.persistent.entity.User;
import com.zuoxiaolong.niubi.job.persistent.shiro.HashHelper;
import com.zuoxiaolong.niubi.job.service.DatabaseInitializationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/**
 * 数据库初始化服务实现类
 *
 * @author Xiaolong Zuo
 * @since 0.9.3
 */
@Component
public class DatabaseInitializationServiceImpl implements DatabaseInitializationService {

    @Autowired
    private BaseDao baseDao;

    /**
     * 本方法先检查数据库是否有admin为username的用户,如果没有则会插入一条,并且赋予权限.
     */
    @Override
    public void initialize() {
        String adminUsername = "admin";
        String adminPassword = "123456";

        User param = new User();
        param.setUserName(adminUsername);
        User admin = baseDao.getUnique(User.class, param);
        if (admin != null) {
            LoggerHelper.info("database has been initialized.");
            return;
        }
        LoggerHelper.info("begin init database.");
        admin = new User();
        admin.setUserName(adminUsername);
        admin.setUserPassword(HashHelper.getHashedPassword(adminPassword, adminUsername));
        admin.setPasswordSalt(adminUsername);

        Role role = new Role();
        role.setRoleName("ROLE_ADMIN");
        role.setRoleDescription("Administrator");
        baseDao.save(role);

        admin.setRoleList(Arrays.asList(role));
        baseDao.save(admin);

        LoggerHelper.info("init database successfully.");
    }

}


text:
package reductions

import org.scalameter._
import common._

object LineOfSightRunner {

  val standardConfig = config(
    Key.exec.minWarmupRuns -> 40,
    Key.exec.maxWarmupRuns -> 80,
    Key.exec.benchRuns -> 100,
    Key.verbose -> true
  ) withWarmer(new Warmer.Default)

  def main(args: Array[String]) {
    val length = 10000000
    val input = (0 until length).map(_ % 100 * 1.0f).toArray
    val output = new Array[Float](length + 1)
    val seqtime = standardConfig measure {
      LineOfSight.lineOfSight(input, output)
    }
    println(s"sequential time: $seqtime ms")

    val partime = standardConfig measure {
      LineOfSight.parLineOfSight(input, output, 10000)
    }
    println(s"parallel time: $partime ms")
    println(s"speedup: ${seqtime / partime}")
  }
}

object LineOfSight {

  def max(a: Float, b: Float): Float = if (a > b) a else b

  def lineOfSight(input: Array[Float], output: Array[Float]): Unit = {
    downsweepSequential(input, output, 0.0f, 0, input.length)
  }

  sealed abstract class Tree {
    def maxPrevious: Float
  }

  case class Node(left: Tree, right: Tree) extends Tree {
    val maxPrevious = max(left.maxPrevious, right.maxPrevious)
  }

  case class Leaf(from: Int, until: Int, maxPrevious: Float) extends Tree

  /** Traverses the specified part of the array and returns the maximum angle.
   */
  def upsweepSequential(input: Array[Float], from: Int, until: Int): Float = {
    var m = 0.0f
    for(x <- from until until){
      m =  max(m, input(x) / x)
    }
    m
  }

  /** Traverses the part of the array starting at `from` and until `end`, and
   *  returns the reduction tree for that part of the array.
   *
   *  The reduction tree is a `Leaf` if the length of the specified part of the
   *  array is smaller or equal to `threshold`, and a `Node` otherwise.
   *  If the specified part of the array is longer than `threshold`, then the
   *  work is divided and done recursively in parallel.
   */
  def upsweep(input: Array[Float], from: Int, end: Int,
    threshold: Int): Tree = {
      if(end -from <= threshold){
        Leaf(from, end, upsweepSequential(input, from, end))
      }else
        {
          val middle = from +  ((end-from)/2)
          val (tL, tR) = parallel( upsweep(input, from, middle, threshold),
                                   upsweep(input, middle, end, threshold))
          Node(tL, tR)
        }
    }

  /** Traverses the part of the `input` array starting at `from` and until
   *  `until`, and computes the maximum angle for each entry of the output array,
   *  given the `startingAngle`.
   */
  def downsweepSequential(input: Array[Float], output: Array[Float],
    startingAngle: Float, from: Int, until: Int): Unit = {
    var currentMax = startingAngle

    for(x <- from until until){
      var angle = 0.0f
      if(x != 0)
        angle = input(x)/x
      currentMax = max(currentMax, angle)
      output(x) = currentMax
    }
  }

  /** Pushes the maximum angle in the prefix of the array to each leaf of the
   *  reduction `tree` in parallel, and then calls `downsweepTraverse` to write
   *  the `output` angles.
   */
  def downsweep(input: Array[Float], output: Array[Float], startingAngle: Float,
    tree: Tree): Unit = {
   downsweepSequential(input, output, startingAngle, 0, input.length)
  }

  /** Compute the line-of-sight in parallel. */
  def parLineOfSight(input: Array[Float], output: Array[Float],
    threshold: Int): Unit = {
    lineOfSight(input, output)
  }
}


text:
/**
 * Data types for leaderboard data retrieved from backend through API call.
 */

import { Achievement } from './achievements';
import { CourseUserListData } from './courseUsers';

export interface LeaderboardSettings {
  leaderboardTitle?: string;
  groupleaderboardTitle?: string;
}
export interface LeaderboardData extends LeaderboardSettings {
  leaderboardByExpPoints: LeaderboardPoints[];
  leaderboardByAchievementCount?: LeaderboardAchievement[];
  groupleaderboardByExpPoints?: GroupLeaderboardPoints[];
  groupleaderboardByAchievementCount?: GroupLeaderboardAchievement[];
}

export interface LeaderboardAchievement extends CourseUserListData {
  achievementCount: number;
  achievements: Achievement[];
}
export interface LeaderboardPoints extends CourseUserListData {
  level: number;
  experience: number;
}

export interface GroupLeaderboardAchievement {
  id: number;
  name: string;
  averageAchievementCount: number;
  group: CourseUserListData[];
}

export interface GroupLeaderboardPoints {
  id: number;
  name: string;
  averageExperiencePoints: number;
  group: CourseUserListData[];
}

/**
 * Data types for leaderboard data used in frontend that are converted from
 * received backend data.
 */

export interface LeaderboardPointsEntity extends CourseUserListData {
  level: number;
  experience: number;
}

export interface LeaderboardAchievementEntity extends CourseUserListData {
  achievementCount: number;
  achievements: Achievement[];
}

export interface GroupLeaderboardAchievementEntity {
  id: number;
  name: string;
  averageAchievementCount: number;
  group: CourseUserListData[];
}

export interface GroupLeaderboardPointsEntity {
  id: number;
  name: string;
  averageExperiencePoints: number;
  group: CourseUserListData[];
}


text:
package simcity.KRestaurant;

import simcity.interfaces.KCustomer;
import simcity.interfaces.KWaiter;

public class KRestaurantOrder {
	KWaiterRole w;
	String choice;
	int table;

	public KRestaurantOrder(KWaiterRole w, String choice, int table) {
		this.w = w;
		this.choice = choice;
		this.table = table;
	}

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<metadata modelVersion="1.1.0">
  <groupId>com.googlecode.gwtupload</groupId>
  <artifactId>gwtupload-project</artifactId>
  <version>1.0.4-SNAPSHOT</version>
  <versioning>
    <snapshot>
      <timestamp>20150113.173159</timestamp>
      <buildNumber>1</buildNumber>
    </snapshot>
    <lastUpdated>20150113173159</lastUpdated>
    <snapshotVersions>
      <snapshotVersion>
        <extension>pom</extension>
        <value>1.0.4-20150113.173159-1</value>
        <updated>20150113173159</updated>
      </snapshotVersion>
    </snapshotVersions>
  </versioning>
</metadata>


text:
package com.github.pfichtner.fsltree.visitor;

import com.github.pfichtner.fsltree.Directory;
import com.github.pfichtner.fsltree.File;

public interface Visitor {

	boolean visit(Directory subdir);

	boolean visit(File file);

}


text:
namespace RawRabbit.Enrichers.GlobalExecutionId
{
	public class PropertyHeaders
	{
		public static readonly string GlobalExecutionId = "global_execution_id";
	}
}


text:
/* eslint-env mocha */
/* eslint-disable no-unused-expressions, no-underscore-dangle, import/no-duplicates */

import { expect } from 'chai';
import { spy } from 'sinon';
import proxyquire from 'proxyquire';
import { mail } from 'sendgrid';
import mockEsmodule from '../../../test/mockEsmodule';

const proxyquireStrict = proxyquire.noCallThru();

describe('mailers/transporter', () => {
  let emptyRequestSpy;
  let transporter;
  beforeEach(() => {
    emptyRequestSpy = spy();
    transporter = proxyquireStrict('../transporter', {
      sendgrid: mockEsmodule({
        default: () => ({
          emptyRequest: emptyRequestSpy,
          API: () => {}
        }),
        mail
      }),
      '../config': mockEsmodule({
        auth: {
          sendgrid: {
            secret: '12345'
          }
        },
        hostname: 'lunch.pink'
      })
    }).default;
  });

  describe('sendMail', () => {
    describe('when sending to an individual user', () => {
      beforeEach(() => {
        transporter.sendMail({
          name: 'Jeffrey',
          email: 'j@l.com',
          subject: 'Hello',
          text: 'Hi!'
        });
      });

      it('contains the to email in the tos value', () => {
        const body = emptyRequestSpy.lastCall.args[0].body;
        expect(body.subject).to.eq('Hello');
        expect(body.personalizations[0].to[0]).to.deep.eq({
          name: 'Jeffrey',
          email: 'j@l.com'
        });
      });
    });

    describe('when sending to a list of recipients', () => {
      beforeEach(() => {
        transporter.sendMail({
          recipients: [
            {
              name: 'Jeffrey',
              email: 'j@l.com'
            },
            {
              name: 'Matt',
              email: 'm@l.com'
            }
          ],
          subject: 'Hello',
          text: 'Hi!'
        });
      });

      it('makes Lunch the sender and sendee', () => {
        const body = emptyRequestSpy.lastCall.args[0].body;

        expect(body.from).to.deep.eq({
          name: 'Lunch',
          email: 'noreply@lunch.pink'
        });
        expect(body.personalizations[0].to[0]).to.deep.eq({
          name: 'Lunch',
          email: 'noreply@lunch.pink'
        });
      });

      it('contains the emails in the bccs value', () => {
        const body = emptyRequestSpy.lastCall.args[0].body;
        expect(body.personalizations[0].bcc).to.deep.contain.members([
          {
            name: 'Jeffrey',
            email: 'j@l.com'
          },
          {
            name: 'Matt',
            email: 'm@l.com'
          }
        ]);
      });
    });
  });
});


text:
package edu.rice.cs.caper.bayou.application.api_synthesis_server.synthesis_logging;

import java.util.List;
import java.util.UUID;

/**
 * Records the input and solutions to a code synthesis request.
 */
public interface SynthesisLogger
{
    /**
     * Logs a synthesis input and solutions for a given request.
     *
     * @param requestId a unique identifier for the request.
     * @param searchCode the input code of the request.
     * @param results the generated synthesis solutions for the request.
     */
    void log(UUID requestId, String searchCode, Iterable<String> results);
}


text:
/**
 *
 */
package org.openntf.domino.xsp;

import java.io.IOException;
import java.security.Principal;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;

import org.openntf.domino.xsp.helpers.NSA;

/**
 * @author Nathan T. Freeman
 *
 */
public class OpenntfServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * Constructor
	 */
	public OpenntfServlet() {
		super();
		// System.out.println("Constructing OpenntfServlet");
		// IndexDatabase index = new IndexDatabase();
	}

	@Override
	public void init() throws ServletException {
		// System.out.println("Initting OpenntfServlet");
		super.init();
	}

	@Override
	public void destroy() {
		// System.out.println("Destroying OpenntfServlet");
		super.destroy();
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see javax.servlet.http.HttpServlet#service(javax.servlet.ServletRequest, javax.servlet.ServletResponse)
	 */
	@Override
	public void service(final ServletRequest servletRequest, final ServletResponse servletResponse) throws ServletException, IOException {
		super.service(servletRequest, servletResponse);
		String username = "";
		if (servletRequest instanceof HttpServletRequest) {
			HttpServletRequest request = (HttpServletRequest) servletRequest;
			Principal principal = request.getUserPrincipal();
			username = principal.getName();
		}
		servletResponse.getWriter().write(
				"
This IBM Domino server is using the " + org.openntf.domino.utils.Factory.getTitle() + " Version: "
						+ org.openntf.domino.utils.Factory.getVersion() + ".

Find out more at OpenNTF

" + "Request Principal: " + username + "
"
						+ NSA.INSTANCE.getReport() + "");
	}

}


text:
cask 'race-into-space' do
  version '1.1.0.286'
  sha256 'f22838888be4f456b107fd4d527474fdeae96ce5c3f3cfda623e736411e8c33c'

  # downloads.sourceforge.net/raceintospace/ was verified as official when first introduced to the cask
  url "https://downloads.sourceforge.net/raceintospace/Race_Into_Space_#{version}.dmg"
  appcast 'https://sourceforge.net/projects/raceintospace/rss'
  name 'Race Into Space'
  homepage 'https://www.raceintospace.org/'

  app 'Race Into Space.app'
end


text:
// SampSharp.Streamer
// Copyright 2018 Tim Potze
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using SampSharp.GameMode;
using SampSharp.GameMode.Definitions;
using SampSharp.GameMode.Events;
using SampSharp.GameMode.World;

namespace SampSharp.Streamer.Events
{
    public class PlayerShootEventArgs : PlayerEventArgs
    {
        public PlayerShootEventArgs(BasePlayer player, Weapon weapon, Vector3 position)
            : base(player)
        {
            Weapon = weapon;
            Position = position;
        }

        public bool PreventDamage { get; set; }

        public Weapon Weapon { get; }

        public Vector3 Position { get; }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- <color name="primaryColor">#2196F3</color>
    <color name="primaryColorDark">#1976D2</color>
    <color name="accentColor">#F44336</color>-->
    <color name="primary">#2196F3</color>
    <color name="primary_dark">#1976D2</color>
    <color name="accent">#ffc400</color>
    <color name="text_primary">#D9FFFFFF</color>
    <color name="text_secondary">#D9000000</color>
</resources>


text:
<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Home extends MY_Controller
{
	function __construct()
    {
        // Call the Model constructor
        parent::__construct();
        $this->load->model('m_home');
    }

	function index()
	{
		$this->load->view('home');
	}

  public function enter_comment(){
        $this->load->library('form_validation');

        $this->form_validation->set_rules('email','Email Address','trim|required|min_length[6]|max_length[50]|valid_email|xss_clean');

        if($this->form_validation->run()==FALSE){
          echo "There was a problem with submitting your comment 1";
        }else{
           $this->load->model('m_home');

           $result = $this->m_home->insert_comment();
           $this->load->view('v_home');
        }
      }

  public function services(){
    $this->load->view('services');
  }

   public function contacts(){
    $this->load->view('contacts');
  }

  public function market(){
    $this->load->view('marketability');
  }

   public function programs(){
    $this->load->view('programs');
  }

   public function about(){
    $this->load->view('about');
  }

  public function preamble(){
    $this->load->view('preamble');
  }

  public function exceltest()
  {
    $data[0] = array();
    $filename = 'myname';
    $form = 'pdf';
    $this->export->generate($data, $filename, $form,$identifier='');
  }

}


text:
/* eslint consistent-return:0 */

const express = require('express');
const logger = require('./logger');

const argv = require('./argv');
const port = require('./port');
const setup = require('./middlewares/frontendMiddleware');
const resolve = require('path').resolve;
const app = express();

// In production we need to pass these values in instead of relying on webpack
setup(app, {
  outputPath: resolve(process.cwd(), 'build'),
  publicPath: '/',
});

// get the intended host and port number, use localhost and port 3000 if not provided
const customHost = argv.host || process.env.HOST;
const host = customHost || null; // Let http.Server use its default IPv6/4 host
const prettyHost = customHost || 'localhost';

// Start your app.
app.listen(port, host, (err) => {
  if (err) {
    return logger.error(err.message);
  }

  logger.appStarted(port, prettyHost);
});


text:
Tag Formatter
=============
**Tag Formatter** (for a lack of a better name) is—of course—a basic templating system that takes in text input with "tags", and replaces those tags with text as defined by the programmer.

Installation
------------

### Installation via `gem`
    gem install tag_formatter

### Installation via GIT
    git clone git://github.com/mseymour/tag_formatter.git
    cd tag_formatter/
    gem build tag_formatter.gemspec
    gem install tag_formatter-0.0.3.gem

Usage
-----
Valid option symbols for configuring an instance of `TagFormatter`:

* `tags` (`Hash`)
* `tag_start` (`String`)
* `tag_end` (`String`)
* `inline_comment_delimiter` (`String`)
* `block_comment_start` (`String`)
* `block_comment_end` (`String`)

Formatting a block of text using the default options:

    text = <<-HEREDOC
    Hello, I am {firstname} {lastname}.
    I like {something}. #Something can be anything.
    /*I do not know about you,
    but block comments are pretty rad.*/
    HEREDOC

    tf = TagFormatter.new text, tags: {firstname: "Mark", lastname: "Seymour", something: "listening to music"}

    puts tf.parse #=> Hello, I am Mark Seymour.\nI like listening to music.

Formatting a block of text using user-supplied options:

    tf = TagFormatter.new "I like to %verb% it, %verb% it!", tags: {verb: "move"}, tag_start: '%', tag_end: '%'
    puts tf.parse #=> I like to move it, move it!

Contribute
----------
Any and all issues should be reported via the Issues tab in Github.

Fixes, additions, patches, etc. are greatly welcome.

Author information
------------------
* Mark Seymour ('Azure')
* Email: mark.seymour.ns@gmail.com
* WWW: http://lain.rustedlogic.net/
* IRC: #shakesoda @ irc.freenode.net


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="DataSourceManagerImpl" format="xml" hash="1075503906">
    <data-source source="LOCAL" name="MySQL - 61694_android@pdb10.agilityhoster.com" uuid="3a2f1a7c-4046-46ec-9c5f-2766c973819a">
      <driver-ref>mysql</driver-ref>
      <synchronize>true</synchronize>
      <jdbc-driver>com.mysql.jdbc.Driver</jdbc-driver>
      <jdbc-url>jdbc:mysql://pdb10.agilityhoster.com:3306/61694_android</jdbc-url>
      <driver-properties>
        <property name="zeroDateTimeBehavior" value="convertToNull" />
        <property name="tinyInt1isBit" value="false" />
        <property name="characterEncoding" value="utf8" />
        <property name="characterSetResults" value="utf8" />
        <property name="yearIsDateType" value="false" />
      </driver-properties>
      <libraries />
    </data-source>
  </component>
</project>


text:
using System;

namespace StackExchange.DataExplorer
{
    [AttributeUsage(AttributeTargets.Property)]
    internal sealed class DefaultAttribute : Attribute
    {
        public DefaultAttribute(object defaultValue)
        {
            DefaultValue = defaultValue;
        }

        public object DefaultValue { get; private set; }
    }
}


text:
var should = require('chai').should()
  , angular = require('angular')
  , sinon  = require('sinon')
  , sinonAsPromised = require('sinon-as-promised')
  , mocks = require('../../mocks');

require('angular-mocks');

describe('CacheListingController tests', function() {

  var CacheService
    , scope
    , $rootScope
    , ctrl
    , $location
    , $timeout;

  var sandbox;

  beforeEach(function() {
    sandbox = sinon.sandbox.create();
  });

  afterEach(function() {
    sandbox.restore();
  });

  beforeEach(angular.mock.module('mapcache'));

  beforeEach(inject(function(_CacheService_, $injector){
    $timeout = $injector.get('$timeout');
    $location = $injector.get('$location');
    CacheService = sandbox.mock(_CacheService_);
  }));

  beforeEach(inject(function(_$rootScope_, $controller){
    $rootScope = _$rootScope_;
    scope = $rootScope.$new();
    scope.options = {};
    ctrl = $controller('CacheListingController', {$scope: scope});
    scope.$apply();
  }));

  beforeEach(angular.mock.inject(function ($q) {
    sinonAsPromised($q);
  }));

  it('should create the CacheListingController', function() {
    should.exist(ctrl);
  });

  it('should emit generate format', function() {
    var spy = sandbox.spy(scope, '$emit');
    scope.generateFormat(mocks.cacheMocks.xyzCache, 'xyz');

    spy.calledOnce.should.be.equal(true);
    spy.alwaysCalledWithExactly('generateFormat', mocks.cacheMocks.xyzCache, 'xyz').should.be.equal(true);
  });

  it('should emit show cache extent events', function() {
    var spy = sandbox.spy($rootScope, '$broadcast');
    scope.mouseOver(mocks.cacheMocks.xyzCache);
    $timeout.flush(501);
    spy.calledOnce.should.be.equal(true);
    spy.calledWith('showCacheExtent', mocks.cacheMocks.xyzCache).should.be.equal(true);
  });

  it('should emit hide cache extent events', function() {
    var spy = sandbox.spy($rootScope, '$broadcast');
    scope.mouseOut(mocks.cacheMocks.xyzCache);
    spy.calledOnce.should.be.equal(true);
    spy.calledWith('hideCacheExtent', mocks.cacheMocks.xyzCache).should.be.equal(true);
  });

  it('should emit show cache events', function() {
    var spy = sandbox.spy($rootScope, '$broadcast');
    scope.mouseClick(mocks.cacheMocks.xyzCache);
    $timeout.flush(501);
    spy.calledOnce.should.be.equal(true);
    spy.calledWith('showCache', mocks.cacheMocks.xyzCache).should.be.equal(true);
  });

  it('should emit hide cache extent events', function() {
    var spy = sandbox.spy($rootScope, '$broadcast');
    scope.mouseClick(mocks.cacheMocks.xyzCache);
    $timeout.flush(501);
    scope.mouseClick(mocks.cacheMocks.xyzCache);
    spy.calledTwice.should.be.equal(true);
    spy.calledWith('showCache', mocks.cacheMocks.xyzCache).should.be.equal(true);
    spy.calledWith('hideCache', mocks.cacheMocks.xyzCache).should.be.equal(true);
  });

  it('should set the map filter', function() {
    $rootScope.$broadcast('cacheFootprintPopupOpen', mocks.cacheMocks.xyzCache);
    scope.$apply();
    scope.mapFilter.should.be.equal(mocks.cacheMocks.xyzCache.id);
  });

  it('should unset the map filter', function() {
    $rootScope.$broadcast('cacheFootprintPopupClose');
    scope.$apply();
    should.not.exist(scope.mapFilter);
  });

  it('should emit the cache filter changed', function() {
    var spy = sandbox.spy(scope, '$emit');
    scope.cacheFilter = '5';
    scope.mapFilter = '6';
    scope.$apply();

    spy.calledOnce.should.be.equal(true);
    spy.alwaysCalledWithExactly('cacheFilterChange', {cacheFilter: '5', mapFilter: '6'}).should.be.equal(true);
  });

  it('should create tiles', function() {
    var cache = JSON.parse(JSON.stringify(mocks.cacheMocks.xyzCache));
    var spy = sandbox.spy(scope, '$emit');

    CacheService.expects('createCacheFormat').yields({}).alwaysCalledWith(mocks.cacheMocks.xyzCache, 'xyz');
    scope.createTiles(cache, 0, 1);
    cache.minZoom.should.be.equal(0);
    cache.maxZoom.should.be.equal(1);
    cache.formats.xyz.generating.should.be.equal(true);
    spy.calledOnce.should.be.equal(true);
    spy.alwaysCalledWithExactly('refreshCaches').should.be.equal(true);
  });

  it('should calculate cache size', function() {
    var cache = JSON.parse(JSON.stringify(mocks.cacheMocks.xyzCache));

    scope.calculateCacheSize(cache, 0, 1);
    cache.totalCacheTiles.should.be.equal(5);
    cache.totalCacheSize.should.be.equal(5*cache.source.tileSize/cache.source.tileSizeCount);
  });

});


text:
package org.wildfly.security.http.oidc;

import static org.wildfly.security.http.oidc.ElytronMessages.log;
import static org.wildfly.security.http.oidc.Oidc.SSLRequired;
import static org.wildfly.security.http.oidc.Oidc.TokenStore;

import java.io.IOException;
import java.io.InputStream;
import java.security.PublicKey;
import java.util.concurrent.Callable;

import org.apache.http.client.HttpClient;
import org.wildfly.common.iteration.CodePointIterator;
import org.wildfly.security.jose.util.SystemPropertiesJsonParserFactory;
import org.wildfly.security.pem.Pem;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * Builder for the OpenID Connect (OIDC) configuration for a client application. This class is based on
 * {@code org.keycloak.adapters.KeycloakDeploymentBuilder}.
 *
 * @author Bill Burke
 * @author Brad Culley
 * @author John D. Ament
 * @author Farah Juma
 */
public class OidcClientConfigurationBuilder {

    protected OidcClientConfiguration oidcClientConfiguration = new OidcClientConfiguration();

    protected OidcClientConfigurationBuilder() {
    }

    protected OidcClientConfiguration internalBuild(final OidcJsonConfiguration oidcJsonConfiguration) {
        if (oidcJsonConfiguration.getAuthServerUrl() != null && oidcJsonConfiguration.getRealm() == null) {
            throw log.keycloakRealmMissing();
        }
        if (oidcJsonConfiguration.getRealm() != null) {
            oidcClientConfiguration.setRealm(oidcJsonConfiguration.getRealm());
        }
        String resource = oidcJsonConfiguration.getResource();
        String clientId = oidcJsonConfiguration.getClientId();
        if (resource == null && clientId == null) {
            throw log.resourceOrClientIdMustBeSet();
        }
        oidcClientConfiguration.setResource(resource);
        oidcClientConfiguration.setClientId(clientId);

        String realmKeyPem = oidcJsonConfiguration.getRealmKey();
        if (realmKeyPem != null) {
            PublicKey realmKey;
            try {
                realmKey = Pem.parsePemPublicKey(CodePointIterator.ofString(realmKeyPem));
                HardcodedPublicKeyLocator pkLocator = new HardcodedPublicKeyLocator(realmKey);
                oidcClientConfiguration.setPublicKeyLocator(pkLocator);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        } else {
            JWKPublicKeyLocator pkLocator = new JWKPublicKeyLocator();
            oidcClientConfiguration.setPublicKeyLocator(pkLocator);
        }

        if (oidcJsonConfiguration.getSslRequired() != null) {
            oidcClientConfiguration.setSSLRequired(SSLRequired.valueOf(oidcJsonConfiguration.getSslRequired().toUpperCase()));
        } else {
            oidcClientConfiguration.setSSLRequired(SSLRequired.EXTERNAL);
        }

        if (oidcJsonConfiguration.getConfidentialPort() != -1) {
            oidcClientConfiguration.setConfidentialPort(oidcJsonConfiguration.getConfidentialPort());
        }

        if (oidcJsonConfiguration.getTokenStore() != null) {
            oidcClientConfiguration.setTokenStore(TokenStore.valueOf(oidcJsonConfiguration.getTokenStore().toUpperCase()));
        } else {
            oidcClientConfiguration.setTokenStore(TokenStore.SESSION);
        }
        if (oidcJsonConfiguration.getTokenCookiePath() != null) {
            oidcClientConfiguration.setOidcStateCookiePath(oidcJsonConfiguration.getTokenCookiePath());
        }
        if (oidcJsonConfiguration.getPrincipalAttribute() != null) oidcClientConfiguration.setPrincipalAttribute(oidcJsonConfiguration.getPrincipalAttribute());

        oidcClientConfiguration.setResourceCredentials(oidcJsonConfiguration.getCredentials());
        oidcClientConfiguration.setClientAuthenticator(ClientCredentialsProviderUtils.bootstrapClientAuthenticator(oidcClientConfiguration));

        oidcClientConfiguration.setPublicClient(oidcJsonConfiguration.isPublicClient());
        oidcClientConfiguration.setUseResourceRoleMappings(oidcJsonConfiguration.isUseResourceRoleMappings());
        oidcClientConfiguration.setUseRealmRoleMappings(oidcJsonConfiguration.isUseRealmRoleMappings());

        oidcClientConfiguration.setExposeToken(oidcJsonConfiguration.isExposeToken());

        if (oidcJsonConfiguration.isCors()) {
            oidcClientConfiguration.setCors(true);
            oidcClientConfiguration.setCorsMaxAge(oidcJsonConfiguration.getCorsMaxAge());
            oidcClientConfiguration.setCorsAllowedHeaders(oidcJsonConfiguration.getCorsAllowedHeaders());
            oidcClientConfiguration.setCorsAllowedMethods(oidcJsonConfiguration.getCorsAllowedMethods());
            oidcClientConfiguration.setCorsExposedHeaders(oidcJsonConfiguration.getCorsExposedHeaders());
        }

        // https://tools.ietf.org/html/rfc7636
        if (oidcJsonConfiguration.isPkce()) {
            oidcClientConfiguration.setPkce(true);
        }

        oidcClientConfiguration.setBearerOnly(oidcJsonConfiguration.isBearerOnly());
        oidcClientConfiguration.setAutodetectBearerOnly(oidcJsonConfiguration.isAutodetectBearerOnly());
        oidcClientConfiguration.setEnableBasicAuth(oidcJsonConfiguration.isEnableBasicAuth());
        oidcClientConfiguration.setAlwaysRefreshToken(oidcJsonConfiguration.isAlwaysRefreshToken());
        oidcClientConfiguration.setRegisterNodeAtStartup(oidcJsonConfiguration.isRegisterNodeAtStartup());
        oidcClientConfiguration.setRegisterNodePeriod(oidcJsonConfiguration.getRegisterNodePeriod());
        oidcClientConfiguration.setTokenMinimumTimeToLive(oidcJsonConfiguration.getTokenMinimumTimeToLive());
        oidcClientConfiguration.setMinTimeBetweenJwksRequests(oidcJsonConfiguration.getMinTimeBetweenJwksRequests());
        oidcClientConfiguration.setPublicKeyCacheTtl(oidcJsonConfiguration.getPublicKeyCacheTtl());
        oidcClientConfiguration.setIgnoreOAuthQueryParameter(oidcJsonConfiguration.isIgnoreOAuthQueryParameter());
        oidcClientConfiguration.setRewriteRedirectRules(oidcJsonConfiguration.getRedirectRewriteRules());
        oidcClientConfiguration.setVerifyTokenAudience(oidcJsonConfiguration.isVerifyTokenAudience());

        if (realmKeyPem == null && oidcJsonConfiguration.isBearerOnly()
                && (oidcJsonConfiguration.getAuthServerUrl() == null && oidcJsonConfiguration.getProviderUrl() == null)) {
            throw log.invalidConfigurationForBearerAuth();
        }
        if ((oidcJsonConfiguration.getAuthServerUrl() == null && oidcJsonConfiguration.getProviderUrl() == null) && (!oidcClientConfiguration.isBearerOnly() || realmKeyPem == null)) {
            throw log.authServerUrlOrProviderUrlMustBeSet();
        }
        oidcClientConfiguration.setClient(createHttpClientProducer(oidcJsonConfiguration));
        oidcClientConfiguration.setAuthServerBaseUrl(oidcJsonConfiguration);
        oidcClientConfiguration.setProviderUrl(oidcJsonConfiguration.getProviderUrl());
        if (oidcJsonConfiguration.getTurnOffChangeSessionIdOnLogin() != null) {
            oidcClientConfiguration.setTurnOffChangeSessionIdOnLogin(oidcJsonConfiguration.getTurnOffChangeSessionIdOnLogin());
        }

        oidcClientConfiguration.setTokenSignatureAlgorithm(oidcJsonConfiguration.getTokenSignatureAlgorithm());

        return oidcClientConfiguration;
    }

    private Callable<HttpClient> createHttpClientProducer(final OidcJsonConfiguration oidcJsonConfiguration) {
        return new Callable<HttpClient>() {
            private HttpClient client;
            @Override
            public HttpClient call() {
                if (client == null) {
                    synchronized (oidcClientConfiguration) {
                        if (client == null) {
                            client = new HttpClientBuilder().build(oidcJsonConfiguration);
                        }
                    }
                }
                return client;
            }
        };
    }

    public static OidcClientConfiguration build(InputStream is) {
        OidcJsonConfiguration oidcJsonConfiguration = loadOidcJsonConfiguration(is);
        return new OidcClientConfigurationBuilder().internalBuild(oidcJsonConfiguration);
    }

    public static OidcJsonConfiguration loadOidcJsonConfiguration(InputStream is) {
        ObjectMapper mapper = new ObjectMapper(new SystemPropertiesJsonParserFactory());
        mapper.setSerializationInclusion(JsonInclude.Include.NON_DEFAULT);
        OidcJsonConfiguration adapterConfig;
        try {
            adapterConfig = mapper.readValue(is, OidcJsonConfiguration.class);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return adapterConfig;
    }

    public static OidcClientConfiguration build(OidcJsonConfiguration oidcJsonConfiguration) {
        return new OidcClientConfigurationBuilder().internalBuild(oidcJsonConfiguration);
    }
}


text:
export const defaultTemplate = require('../templates/index.mustache');
export const searchDisabled = require('../templates/searchDisabled.mustache');
export const layoutTemplate = require('../templates/layout.mustache');
export const dependenciesTemplate = require('../templates/dependency.mustache');
export const traceTemplate = require('../templates/trace.mustache');
export const traceViewerTemplate = require('../templates/traceViewer.mustache');


text:
/**
 * Includes all models into one place
 *
 * @module models
 * @author Denis Maslennikov <mrdenniska@gmail.com> (nofach.com)
 * @license MIT
 */

module.exports = {
  UserChatInline: require('./userChatInline.js'),
  Supercategory: require('./supercategory.js'),
  Category: require('./category.js'),
  Report: require('./report.js'),
  Review: require('./review.js'),
  User: require('./user.js'),
  Job: require('./job.js'),
  Language: require('./language.js'),
};


text:
import { setPropertiesFromJSON } from '../../json-helper';

import BodyHeight from './BodyHeight';

/**
 * Generated class for shr.vital.BodyLength.
 * @extends BodyHeight
 */
class BodyLength extends BodyHeight {

  /**
   * Get the entry information.
   * @returns {Entry} The shr.base.Entry
   */
  get entryInfo() {
    return this._entryInfo;
  }

  /**
   * Set the entry information.
   * @param {Entry} entryInfo - The shr.base.Entry
   */
  set entryInfo(entryInfo) {
    this._entryInfo = entryInfo;
  }

  /**
   * Get the ObservationCode.
   * @returns {ObservationCode} The shr.finding.ObservationCode
   */
  get observationCode() {
    return this._observationCode;
  }

  /**
   * Set the ObservationCode.
   * @param {ObservationCode} observationCode - The shr.finding.ObservationCode
   */
  set observationCode(observationCode) {
    this._observationCode = observationCode;
  }

  /**
   * Deserializes JSON data to an instance of the BodyLength class.
   * The JSON must be valid against the BodyLength JSON schema, although this is not validated by the function.
   * @param {object} json - the JSON data to deserialize
   * @returns {BodyLength} An instance of BodyLength populated with the JSON data
   */
  static fromJSON(json={}) {
    const inst = new BodyLength();
    setPropertiesFromJSON(inst, json);
    return inst;
  }
}
export default BodyLength;


text:
#include "Obstacle.h"

class Logs :
	public Obstacle
{
public:
	enum LOG_TYPE { turtle1, log1, log2, turtle2, log3 };
	Logs(){}
	Logs(LOG_TYPE type, float speed, Vector2D& startPos, Vector2D& size);
	~Logs();

	void Update();

	float GetSpeed() { return speed; } // Vitesse des logs et turtles

private:
	static std::string TURTLE1_PATH;
	static std::string LOG1_PATH;
	static std::string LOG2_PATH;
	static std::string TURTLE2_PATH;
	static std::string LOG3_PATH;

	// size des logs et turtles
	static const int TURTLE_SQUARED_SIZE = 30;
	static const int LOG1_SIZE_X = 50;
	static const int LOG1_SIZE_Y = 30;
	static const int LOG2_SIZE_X = 150;
	static const int LOG2_SIZE_Y = 30;
	static const int LOG3_SIZE_X = 100;
	static const int LOG3_SIZE_Y = 30;

	float speed;
};


text:
package net.meisen.general.sbconfigurator.config;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import net.meisen.general.sbconfigurator.ConfigurationCoreSettings;
import net.meisen.general.sbconfigurator.api.IConfiguration;
import net.meisen.general.sbconfigurator.test.sampleplugin.SamplePojo;

import org.junit.Test;

/**
 * Tests the implementation of {@code PropertyInjection} during configuration.
 *
 * @author pmeisen
 *
 */
public class TestPropertyInjection {

	/**
	 * Tests the implementation of {@code PropertyInjection} during
	 * configuration.
	 */
	@Test
	public void testExtendedConfiguration() {
		final ConfigurationCoreSettings configCore = ConfigurationCoreSettings
				.loadCoreSettings("propertyInjection-core.xml", getClass());
		final IConfiguration config = configCore.getConfiguration();

		final SamplePojo module = config.getModule("testPojo");
		assertNotNull(module);
		assertEquals("replacement", module.getReplacedValue());
	}
}


text:
@implementation NSObject(EmitterBlocks)

- (NSMutableDictionary *)eventListeners
{
    @synchronized(self)
    {
        NSMutableDictionary *_eventListeners = objc_getAssociatedObject(self, @"eventListeners");

        if (!_eventListeners) {
            _eventListeners = [[NSMutableDictionary alloc] init];

            objc_setAssociatedObject(self, @"eventListeners", _eventListeners, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        }

        return _eventListeners;
    }
}

- (void)addListener:(id)event listener:(id)listener once:(BOOL)once
{
    if (!self.eventListeners[event]) {
        self.eventListeners[event] = [[NSMutableDictionary alloc] init];
    }

    self.eventListeners[event][listener] = @(once);
}

- (void)addListener:(id)event listener:(id)listener
{
    [self addListener:event listener:listener once:NO];
}

- (void)on:(id)event listener:(id)listener
{
    [self addListener:event listener:listener once:NO];
}

- (void)once:(id)event listener:(id)listener
{
    [self addListener:event listener:listener once:YES];
}

- (void)removeListener:(id)event listener:(id)listener
{
    if (!listener) {
        return;
    }

    [self.eventListeners[event] removeObjectForKey:listener];
}

- (void)removeAllListeners:(id)event
{
    for (id listener in [self.eventListeners[event] copy]) {
        [self removeListener:event listener:listener];
    }
}

- (void)removeAllListeners
{
    for (id event in [self.eventListeners copy]) {
        [self removeAllListeners:event];
    }
}

- (void)emit:(id)event, ...
{
    va_list args;
    va_start(args, event);

    [self emit:event vargs:args];

    va_end(args);
}

- (void)emit:(id)event args:(NSArray *)args
{
    NSDictionary *listeners = [self.eventListeners[event] copy];

    for (id listener in listeners) {
        A2BlockInvocation *blockInvocation = [[A2BlockInvocation alloc] initWithBlock:listener];
        NSMethodSignature *signature = blockInvocation.methodSignature;
        NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];

        for (int i=0; i < MIN(signature.numberOfArguments-2, args.count); i++) {
            id arg = args[i];

            [invocation setArgument:&arg atIndex:i+2];
        }

        [blockInvocation performSelectorOnMainThread:@selector(invokeWithInvocation:) withObject:invocation waitUntilDone:YES];

        // Remove events that are only scheduled to execute once
        if (YES == [listeners[listener] boolValue]) {
            [self removeListener:event listener:listener];
        }
    }
}

- (void)emit:(id)event vargs:(va_list)args
{
    NSDictionary *listeners = [self.eventListeners[event] copy];

    for (id listener in listeners) {
        A2BlockInvocation *blockInvocation = [[A2BlockInvocation alloc] initWithBlock:listener];
        NSMethodSignature *signature = blockInvocation.methodSignature;
        NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];

        [invocation setArgumentsFromArgumentList:args];

        [blockInvocation performSelectorOnMainThread:@selector(invokeWithInvocation:) withObject:invocation waitUntilDone:YES];

        // Remove events that are only scheduled to execute once
        if (YES == [listeners[listener] boolValue]) {
            [self removeListener:event listener:listener];
        }
    }
}

@end


text:
/**
 * @dgService ExportNamedDeclarationNodeMatcher
 * @returns {String|Null} code name from node
 */
module.exports = function ExportNamedDeclarationNodeMatcherFactory (codeNameService) {
  /**
   * @param {Node} node AST node to process
   * @returns {String|Null} code name from node
   */
  return function ExportNamedDeclarationNodeMatcher (node) {
    return codeNameService.find(node.right) || null;
  };
};