text:
package android.test;

@com.francetelecom.rd.stubs.annotation.ClassDone(0)
public abstract class ActivityInstrumentationTestCase<T extends android.app.Activity>
  extends ActivityTestCase{
  // Constructors

  @com.francetelecom.rd.stubs.annotation.CallBackRegister("onCreate")
  public ActivityInstrumentationTestCase(java.lang.String arg1, @com.francetelecom.rd.stubs.annotation.FieldSet("clazz") java.lang.Class<T> arg2){
    super();
  }
  @com.francetelecom.rd.stubs.annotation.CallBackRegister("onCreate")
  public ActivityInstrumentationTestCase(java.lang.String arg1, @com.francetelecom.rd.stubs.annotation.FieldSet("clazz") java.lang.Class<T> arg2, boolean arg3){
    super();
  }
  // Methods

  @com.francetelecom.rd.stubs.annotation.Code("try { return clazz.newInstance(); } catch (Exception e) { return null; }")
  public T getActivity(){
    return null;
  }
  @com.francetelecom.rd.stubs.annotation.CallBack("onCreate")
  protected void tearDown() throws java.lang.Exception{
  }
  @com.francetelecom.rd.stubs.annotation.CallBack("onCreate")
  protected void setUp() throws java.lang.Exception{
  }
  public void testActivityTestCaseSetUpProperly() throws java.lang.Exception{
  }
}


text:
<?xml version="1.0"?>
<messages>
    <message>
        Hello, World!
    </message>
    <message>
        I'm a file (in level3!) please replace stuff in me (Planet)!
    </message>
</messages>

redpajama_set_name: RedPajamaGithub


text: class Test { async() {} }


text:
function list_of_grms = step_4(standardized_gene_expression_sorted_by_F_value, time_points, number_of_top_DRGs_considered, output)

  global Dynamics4GenomicBigData_HOME;

  flder=pwd;

  list_of_probe_ids = table2cell(standardized_gene_expression_sorted_by_F_value(:,2));
  list_of_genes = table2cell(standardized_gene_expression_sorted_by_F_value(:,3));
  list_of_top_DRGs = table2cell(standardized_gene_expression_sorted_by_F_value(1:number_of_top_DRGs_considered,3));
  indices_of_top_DRGs_in_sd_matrix_sorted_by_F = 1:size(standardized_gene_expression_sorted_by_F_value,1)';

  indices_of_top_DRGs = cell2mat(table2cell(standardized_gene_expression_sorted_by_F_value(1:number_of_top_DRGs_considered,1)));

  %Theshold
  alpha = 0.75;

  std_data = zscore(cell2mat(table2cell(standardized_gene_expression_sorted_by_F_value(1:number_of_top_DRGs_considered,5:size(standardized_gene_expression_sorted_by_F_value,2))))')';

  [list_of_gene_clusters, rmclusters, c, list_of_cluster_means, gene_expression_by_cluster] = IHC(std_data, alpha);

  list_of_grms = [];
  for cluster_iteration_ID=1:length(list_of_gene_clusters)
    probe_ids_in_current_cluster = list_of_probe_ids(indices_of_top_DRGs_in_sd_matrix_sorted_by_F(list_of_gene_clusters{cluster_iteration_ID}));
    names_of_genes_in_current_cluster = list_of_genes(indices_of_top_DRGs_in_sd_matrix_sorted_by_F(list_of_gene_clusters{cluster_iteration_ID}));

    group = indices_of_top_DRGs(list_of_gene_clusters{cluster_iteration_ID});

    A = 1:size(time_points,1);
    A = A';
    A = strtrim(cellstr(num2str(A))');
    A = strcat('T', A);

    grm = cell2table([num2cell(group) probe_ids_in_current_cluster names_of_genes_in_current_cluster num2cell(gene_expression_by_cluster{cluster_iteration_ID})], 'VariableNames', [{'Row_index_in_GSE_matrix'} {'Probe_ID'} {'Gene_name'} A]);
    list_of_grms = [list_of_grms; {grm}];
  end

  % The following four lines sort the clusters by size.
  [uselessVariable, cluster_indexes_by_size] = sort(cellfun('size', list_of_gene_clusters, 1), 'descend');
  list_of_grms = list_of_grms(cluster_indexes_by_size);
  list_of_gene_clusters = list_of_gene_clusters(cluster_indexes_by_size);
  gene_expression_by_cluster = gene_expression_by_cluster(cluster_indexes_by_size);
  list_of_cluster_means = list_of_cluster_means(cluster_indexes_by_size,:);
  % The previous four lines sort the clusters by size.

  daSm = 0;
  maxIndex = 0;
  for kkk=1:length(list_of_gene_clusters)
    daSm = daSm + length(list_of_gene_clusters{kkk});
    currentClaster = list_of_gene_clusters{kkk};

    for qqq = 1:length(currentClaster)
      if currentClaster(qqq) > maxIndex
	maxIndex = currentClaster(qqq);
      end
    end
  end

  n_clusters   = cellfun(@(x) size(x,1),gene_expression_by_cluster,'UniformOutput', false);

  for l = 1:length(list_of_gene_clusters)
    Cluster_IDX(list_of_gene_clusters{l}) = l;
  end

  for k=1:1

    sz{k}       = cell2mat(n_clusters);

    ind         = find(sz{k}>99);

    ind1        = find(sz{k}>9 & sz{k}<100);

    ind2        = find(sz{k}>1 & sz{k}<10);

    ind3        = find(sz{k}==1);

    lrg_id{k}   = list_of_top_DRGs(vertcat(list_of_gene_clusters{ind}));

    med_id{k}   = list_of_top_DRGs(vertcat(list_of_gene_clusters{ind1}));

    smal_id{k}  = list_of_top_DRGs(vertcat(list_of_gene_clusters{ind2}));

    sin_id{k}   = list_of_top_DRGs(vertcat(list_of_gene_clusters{ind3}));

    lrg_ts{k}   = list_of_cluster_means(ind,:);

    med_ts{k}   = list_of_cluster_means(ind1,:);

    smal_ts{k}  = list_of_cluster_means(ind2,:);

    sin_ts{k}   = list_of_cluster_means(ind3,:);

    sizes{k}    = [size(sz{k},1),length(ind),length(ind1),length(ind2),length(ind3)];

  end

  if(output)

    global Dynamics4GenomicBigData_HOME;
    outputFolder = 'Step_4';
    mkdir(outputFolder);

    [s,ind]=sort(cell2mat(n_clusters),'descend');

      number_of_clusters = size(list_of_cluster_means,1);
      number_of_subplots = number_of_clusters;

      % Ideally the following two variables should be settable to any values. But for now this works only with 30 and 6.
      number_of_subplots_per_page = 30;
      number_of_columns_per_page = 6;
      number_of_rows_per_page = number_of_subplots_per_page / number_of_columns_per_page;

      number_of_pages = ceil(number_of_subplots / number_of_subplots_per_page);
      number_of_plots_in_last_page = number_of_subplots_per_page;
      if mod(number_of_subplots, number_of_subplots_per_page)~=0
	number_of_plots_in_last_page = mod(number_of_subplots, number_of_subplots_per_page);
      end

      cluster_number = 1;

      for b = 1:number_of_pages

	  number_of_plots_in_current_page = number_of_subplots_per_page;
	  if(b == number_of_pages) %i.e., if this is the last page
	    number_of_plots_in_current_page = number_of_plots_in_last_page;
	  end

	  figure('units', 'centimeters', 'position', [0, 0, 85, 50]);
	  axisLabelFontSize = 9;

	  set(gcf, 'PaperPositionMode', 'manual');
	  set(gcf, 'PaperUnits', 'centimeters');
	  set(gcf, 'PaperPosition', [0 0 75 50]);
	  set(gcf, 'PaperUnits', 'centimeters');
	  set(gcf, 'PaperSize', [75 50]);

	  for gen = 1:number_of_plots_in_current_page

	      subplot(number_of_rows_per_page,number_of_columns_per_page,gen);

	      plot(gene_expression_by_cluster{cluster_number}','-*b');

	      set(gca,'XTick', 1:size(time_points));
	      set(gca,'XTickLabel', time_points);

	      xlabel('Time', 'FontSize', axisLabelFontSize);

	      ylabel('Expression', 'FontSize', axisLabelFontSize);

	      hold on;

	      plot(list_of_cluster_means(cluster_number,:),'o-r','LineWidth',1.5);

	      xlim([0,size(list_of_cluster_means(cluster_number,:),2)]);

	      ylim([min(min(gene_expression_by_cluster{cluster_number}))-.05,max(max(gene_expression_by_cluster{cluster_number}))+.05]);

	      v = axis;

	      number_of_genes_in_current_cluster  = s(cluster_number);

	      handle=title(['M' num2str(cluster_number) ' (' num2str(number_of_genes_in_current_cluster) ' genes)' ]);

	      if(number_of_genes_in_current_cluster == 1)
		handle=title(['M' num2str(cluster_number) ' (' num2str(number_of_genes_in_current_cluster) ' gene)' ]);
	      end

	      set(handle,'Position',[2.5 v(4)*1. 0]);

	      hold off;

	      cluster_number = cluster_number + 1;

	  end

	  % The following line is necessary because otherwise MATLAB inexplicably trims the plot
	  % printing to PDF format.
	  pause(5);

	  print(gcf,'-dpdf', ['GRMs_' num2str(b) '.pdf']);
	  close all;
	  movefile(['GRMs_' num2str(b) '.pdf'], outputFolder);
      end

    GRMFigure=figure('units', 'centimeters', 'position', [0, 0, 50, 40]);

    axisLabelFontSize = 30;

    set(gcf, 'PaperPositionMode', 'manual');
    set(gcf, 'PaperUnits', 'centimeters');
    set(gcf, 'PaperPosition', [0 -2 50 40]);
    set(gcf, 'PaperUnits', 'centimeters');
    set(gcf, 'PaperSize', [60 40]);
    set(gca,'FontSize',11);

    Figure1 = subplot(2,2,1);
    set(gca,'FontSize',11);

    if(size(lrg_ts{1},1) > 0)

      if(~isempty(lrg_ts{1}));

	ribbon(lrg_ts{1}');

	ylim([1,size(lrg_ts{1},2)]);

	if size(lrg_ts{1},1) > 1
	  xlim([1,size(lrg_ts{1},1)]);
	end

	zlim([min(min(lrg_ts{1})),max(max(lrg_ts{1}))]);

	ylabel('Time (hours)', 'FontSize', axisLabelFontSize);

	xlabel('ith Cluster Center', 'FontSize', axisLabelFontSize);

	title('LSM');

      end
    end

    Figure2 = subplot(2,2,2);
    set(gca,'FontSize',11);

    if(size(med_ts{1},1) > 0)

      ribbon(med_ts{1}');

      ylim([1,size(med_ts{1},2)]);

      if size(med_ts{1},1) > 1
	xlim([1,size(med_ts{1},1)]);
      end
      zlim([min(min(med_ts{1})),max(max(med_ts{1}))]);

      ylabel('Time (hours)', 'FontSize', axisLabelFontSize);

      xlabel('ith Cluster Center', 'FontSize', axisLabelFontSize);

      title('MSM');
    end

    Figure3 = subplot(2,2,3);
    set(gca,'FontSize',11);

    if(size(smal_ts{1},1) > 0)

      ribbon(smal_ts{1}');

      ylim([1,size(smal_ts{1},2)]);

      if size(smal_ts{1},1) > 1
	xlim([1,size(smal_ts{1},1)]);
      end

%        xlim([1,size(smal_ts{1},1)]);

      zlim([min(min(smal_ts{1})),max(max(smal_ts{1}))]);

      ylabel('Time (hours)', 'FontSize', axisLabelFontSize);

      xlabel('ith Cluster Center', 'FontSize', axisLabelFontSize);

      title('SSM');
    end

    Figure4 = subplot(2,2,4);
    set(gca,'FontSize',11);

    if(size(sin_ts{1},1) > 0)

      ribbon(sin_ts{1}');

      ylim([1,size(sin_ts{1},2)]);

      if(size(sin_ts{1},1) > 1)
	xlim([1,size(sin_ts{1},1)]);
      end

      zlim([min(min(sin_ts{1})),max(max(sin_ts{1}))]);

      ylabel('Time (hours)', 'FontSize', axisLabelFontSize);

      xlabel('ith Cluster Center', 'FontSize', axisLabelFontSize);

      title('SGM');
    end

    print(GRMFigure,'-dpdf', 'GRMs.pdf');

    movefile('GRMs.pdf', outputFolder);

    close all;

    % *Table 2* provides the number of clusters for each subject and the number of clusters in each category.

    col_hed = {'No. of Modules','No. of LSM','No. of MSM','No. of SSM','No. of SGM'};

    row_hed = strcat(repmat({'Subject '},1,1),cellstr(arrayfun(@num2str, 1:1, 'UniformOutput', false))');

    tmp = round2(vertcat(sizes{:}));

    matrix_of_files_descs = [{'File name'} {'Description'}];

    matrix_of_files_descs = [matrix_of_files_descs; [{'Clusters_X.pdf'} {'Cluster plots.'}]];
    matrix_of_files_descs = [matrix_of_files_descs; [{'GRMs.pdf'} {'Clusters plotted by size.'}]];

    writetable(cell2table(matrix_of_files_descs), 'List_and_description_of_output.csv', 'WriteVariableNames', false);

    movefile('List_and_description_of_output.csv', outputFolder);

    cluster_iteration_ID = 1;
    probe_ids_in_current_cluster = list_of_probe_ids(indices_of_top_DRGs_in_sd_matrix_sorted_by_F(list_of_gene_clusters{cluster_iteration_ID}));
    names_of_genes_in_current_cluster = list_of_genes(indices_of_top_DRGs_in_sd_matrix_sorted_by_F(list_of_gene_clusters{cluster_iteration_ID}));

    mkdir([outputFolder '/GRMs']);
    cd([outputFolder '/GRMs']);

    for cluster_iteration_ID=1:length(list_of_gene_clusters)
      writetable(list_of_grms{cluster_iteration_ID}, ['M' num2str(cluster_iteration_ID) '.csv'], 'WriteVariableNames', true);
    end

    for cluster_number=1:length(list_of_cluster_means)
      number_of_genes_in_current_cluster  = s(cluster_number);
      gene_expression_plot(gene_expression_by_cluster{cluster_number}, time_points, ['M' num2str(cluster_number) ' (' num2str(number_of_genes_in_current_cluster) ' genes)' ], 'Time', 'Expression', 'Z');
      print(gcf,'-dpdf', ['M' num2str(cluster_number) '.pdf']);
      close all;
    end

    cd('../..');

  end

end

function [rx] = round2(x)
%% Round to two decimal places

rx = round(x.*100)./100;
end

function [fidxcluster, rmclusters, c, mean_clusters_mat, clusters] = IHC(data, alpha, dist, link)

tic;

n = size(data,1);

if nargin < 3, dist='Spearman'; end
if nargin < 4, link='average'; end

idxclustertmp = clusterdata(data,'criterion','distance','cutoff',1-alpha,'distance',dist,'linkage',link);

for j = 1:max(idxclustertmp)
idxcluster{1}{j}=find(idxclustertmp==j);
end

orig_idxcluster{1} = idxcluster{1};

clusters      = cell(length(idxcluster{1}),1);
rmclusters    = cell(length(idxcluster{1}),1);
for j = 1:length(idxcluster{1})
    clusters{j} = data(orig_idxcluster{1}{j},:);
end

mean_clusters_mat = cellfun(@mod_mean,clusters,'UniformOutput', false);
mean_clusters_mat = cell2mat(mean_clusters_mat);

k=2;
con =1;
crit = 0;

while(con)

     clear('idxclustertmp');

     idxclustertmp = clusterdata(mean_clusters_mat,'criterion','distance','cutoff',1-alpha,'distance',dist,'linkage',link);

     for j = 1:max(idxclustertmp)
     idxcluster{k}{j}=find(idxclustertmp==j);
     end

     clusters      = cell(length(idxcluster{k}),1);
     for j = 1:length(idxcluster{k})
         orig_idxcluster{k}{j}  = vertcat(orig_idxcluster{k-1}{idxcluster{k}{j}});
         clusters{j} = data(orig_idxcluster{k}{j},:);
     end

    %% Prune
    for j = 1:length(clusters)
        PCorR = 1-pdist2(clusters{j},mod_mean(clusters{j}),dist);
        if(any(PCorR<(alpha)))
            indrm = find(PCorR<alpha);
            rmclusters{k}{j}= clusters{j}(indrm,:);
            clusters{j}(indrm,:) = [];
            rmclustersidx{k}{j} = orig_idxcluster{k}{j}(indrm);
            orig_idxcluster{k}{j}(indrm) = [];
        end
    end

    if(~isempty(rmclusters{k}))
          orig_idxcluster{k}  = horzcat(orig_idxcluster{k},num2cell(vertcat(rmclustersidx{k}{:}))');
          clusters = vertcat(clusters,num2cell(vertcat(rmclusters{k}{:}),2));
    end

    mean_clusters_mat = cellfun(@mod_mean,clusters,'UniformOutput', false);
    mean_clusters_mat = cell2mat(mean_clusters_mat);

    %% Stopping Conditions

    %1. The indices of the clusters are identical
    %2. The number of iterations is >100
    %3. The number of jumping genes is less than 5%.

    for l = 1:length(orig_idxcluster{k})
    markov_ind(orig_idxcluster{k}{l}) = l;
    end

    for p = 1:length(orig_idxcluster{k-1})
    mcl_ind(orig_idxcluster{k-1}{p}) = p;
    end

    mem = zeros(n,1);
    mem_a = zeros(n,1);
    D = zeros(n,1);
    for i= 1:n
    ind_g_i = find(markov_ind(i)==markov_ind);
    ind_g_i_2 = find(mcl_ind(i)==mcl_ind);
    mem(ind_g_i) = 1;
    mem_a(ind_g_i_2) = 1;
    D(i) = pdist2(mem',mem_a','hamming');
    W(i) = sum(mem)+sum(mem_a);
    end

    c(k) = sum(1 - (D'*n)./W)./n;

    if(k>3)

    m = mean(abs(diff(c((k-3):k))));

    if((k>100) || m<0.02)

         con1 = 1;
         while(con1)

             k=k+1;

             idxclustertmp = clusterdata(mean_clusters_mat,'criterion','distance','cutoff',1-alpha,'distance',dist,'linkage',link);

             for j = 1:max(idxclustertmp)
             idxcluster{k}{j}=find(idxclustertmp==j);
             end

             clusters      = cell(length(idxcluster{k}),1);
             for j = 1:length(idxcluster{k})
                 orig_idxcluster{k}{j}  = vertcat(orig_idxcluster{k-1}{idxcluster{k}{j}});
                 clusters{j} = data(orig_idxcluster{k}{j},:);
             end
             mean_clusters_mat = cellfun(@mod_mean,clusters,'UniformOutput', false);
             mean_clusters_mat = cell2mat(mean_clusters_mat);

             C = 1-pdist(mean_clusters_mat,dist);

             con1 = max(max(C))>(alpha);

         end
         break;
    end

    end

     %display(['No of cycles: ',num2str(k)]);

     k=k+1;

end

fidxcluster = orig_idxcluster{k};

end

function[y] = mod_mean(x)

if(size(x,1)>1)
    y = mean(x);
else
    y = x ;
end

end


text:
namespace { namespace local
{
    // C1. 18 = 9 positive + 9 negative numbers with the number of digits from 1 to 9.
    //     Even though INT_MAX(32) = 2147483647, i.e. 10 digits (not to mention long int)
    //     we only test up to 9 digits as Spirit does not handle more than 9.

    typedef boost::array<my_string, 18> strings; //C1
    ///////////////////////////////////////////////////////////////////////////
    // Generate a random number string with N digits
    std::string
    gen_int(int digits, bool negative)
    {
        std::string result;

        if (negative)                       // Prepend a '-'
            result += '-';

        result += '1' + (std::rand()%9);         // The first digit cannot be '0'

        for (int i = 1; i < digits; ++i)    // Generate the remaining digits
            result += '0' + (std::rand()%10);
        return result;
    }

    local::strings const&
    get_strs()
    {
        static local::strings strings;
        static bool            filled;
        static bool          negative = true;

        if (!filled)
        {
            // Seed the random generator
            std::srand(std::time(0));

            for (size_t k = 0; k < strings.size(); ++k)
                strings[k] = local::gen_int(k/2 + 1, negative = !negative).c_str();

            filled = true;
        }
        return strings;
    }
}}

#endif // BOOST_CONVERT_TEST_PREPARE_HPP


text:
package net.fortytwo.smsn.brain.model;

import net.fortytwo.smsn.brain.BrainTestBase;
import net.fortytwo.smsn.brain.model.entities.EntityList;
import net.fortytwo.smsn.brain.model.entities.KeyValueTree;
import net.fortytwo.smsn.brain.model.entities.Link;
import net.fortytwo.smsn.brain.model.entities.Page;
import net.fortytwo.smsn.brain.model.entities.Topic;
import net.fortytwo.smsn.brain.model.pg.PGPage;
import net.fortytwo.smsn.brain.model.pg.PGTopic;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;

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

public class TopicsAndPagesTest extends BrainTestBase {

    private Topic arthurTopic, fordTopic, zaphodTopic, friendTopic, earthTopic, teaTopic;
    private Link friendsLink, arthurLink, fordLink, zaphodLink, earthLink, teaLink;

    @Override
    protected TopicGraph createAtomGraph() throws IOException {
        return createNeo4jAtomGraph();
    }

    @Before
    @Override
    public void setUp() throws Exception {
        super.setUp();

        arthurTopic = topicGraph.createTopic("arthur");
        fordTopic = topicGraph.createTopic("ford");
        zaphodTopic = topicGraph.createTopic("zaphod");
        friendTopic = topicGraph.createTopic("friend");
        earthTopic = topicGraph.createTopic("earth");
        teaTopic = topicGraph.createTopic("tea");

        friendsLink = topicGraph.createLink(friendTopic, "friends");
        arthurLink = topicGraph.createLink(arthurTopic, "Arthur P. Dent");
        fordLink = topicGraph.createLink(fordTopic, "Ford Prefect");
        zaphodLink = topicGraph.createLink(zaphodTopic, "Zaphod Beeblebrox");
        earthLink = topicGraph.createLink(earthTopic, "The Earth");
        teaLink = topicGraph.createLink(teaTopic, "Tea");
    }

    @Test
    public void ordinaryPageAndTopicTreeAreAllowed() {
        Page page = topicGraph.createPage(arthurLink);
        page.setText("a page about Arthur");

        assertEquals("a page about Arthur", page.getText());
        assertEquals("Arthur P. Dent", page.getContent().getKey().getLabel());

        KeyValueTree<Link, EntityList<Link>> tree = page.getContent();
        EntityList<Link> parentLinks = topicGraph.createListOfLinks(earthLink, teaLink);
        tree.setValue(parentLinks);

        Link secondLink = EntityList.toJavaList(page.getContent().getValue()).get(1);
        assertEquals("Tea", secondLink.getLabel());
        assertEquals("tea", secondLink.getTarget().getId());

        KeyValueTree<Link, EntityList<Link>> friendsTree = topicGraph.createTopicTree(friendsLink);
        EntityList<Link> childLinks = topicGraph.createListOfLinks(fordLink, zaphodLink);
        friendsTree.setValue(childLinks);
        EntityList<KeyValueTree<Link, EntityList<Link>>> children = topicGraph.createListOfTrees(friendsTree);
        tree.setChildren(children);

        assertEquals("friends", page.getContent().getChildren().getFirst().getKey().getLabel());
        assertEquals("Ford Prefect", page.getContent().getChildren().getFirst().getValue().getFirst().getLabel());

        page.destroy();

    }

    @Test(expected = IllegalArgumentException.class)
    public void linkWithoutTargetIsNotAllowed() {
        topicGraph.createLink(null, "nowhere");
    }

    @Test(expected = IllegalArgumentException.class)
    public void linkWithoutLabelIsNotAllowed() {
        topicGraph.createLink(arthurTopic, null);
    }

    @Test(expected = IllegalArgumentException.class)
    public void settingPageTreeToNullIsNotAllowed() {
        Page page = topicGraph.createPage(arthurLink);
        page.setText("a page about Arthur");
        page.setContent(null);
    }

    @Test(expected = IllegalArgumentException.class)
    public void treeWithoutKeyIsNotAllowed() {
        topicGraph.createTopicTree(null);
    }

    @Test(expected = IllegalArgumentException.class)
    public void emptyListOfLinksIsNotAllowed() {
        topicGraph.createListOfLinks();
    }

    @Test(expected = IllegalArgumentException.class)
    public void emptyListOfSubtreesIsNotAllowed() {
        topicGraph.createListOfTrees();
    }

    @Test
    public void treeWithoutChildrenOrLinksIsAllowed() {
        Page page = topicGraph.createPage(arthurLink);
        KeyValueTree<Link, EntityList<Link>> tree = page.getContent();

        tree.setChildren(null);
        tree.setValue(null);

        page.destroy();
    }

    @Test(expected = IllegalArgumentException.class)
    public void settingTreeTopicToNullIsNotAllowed() {
        KeyValueTree<Link, EntityList<Link>> tree = topicGraph.createTopicTree(arthurLink);
        tree.setKey(null);
    }

    @Test
    public void topicDAGIsDestroyedGracefully() {
        Page page = topicGraph.createPage(arthurLink);

        Object arthurId = ((PGTopic) arthurTopic).asVertex().id();
        assertTrue(graph.traversal().V(arthurId).hasNext());
        Object pageId = ((PGPage) page).asVertex().id();
        assertTrue(graph.traversal().V(pageId).hasNext());

        page.getContent().setValue(
                topicGraph.createListOfLinks(
                        topicGraph.createLink(arthurTopic, "Arthur as a top-level link")));

        page.getContent().setChildren(
                topicGraph.createListOfTrees(
                        topicGraph.createTopicTree(
                                topicGraph.createLink(arthurTopic, "Arthur as a header"))));
        page.getContent().getChildren().getFirst().setValue(
                topicGraph.createListOfLinks(
                        topicGraph.createLink(arthurTopic, "Arthur as a second-level link")));

        assertEquals(arthurTopic, page.getContent().getKey().getTarget());
        assertEquals("Arthur P. Dent", page.getContent().getKey().getLabel());
        assertEquals(arthurTopic, page.getContent().getValue().getFirst().getTarget());
        assertEquals("Arthur as a top-level link", page.getContent().getValue().getFirst().getLabel());
        assertEquals(arthurTopic, page.getContent().getChildren().getFirst().getKey().getTarget());
        assertEquals("Arthur as a header", page.getContent().getChildren().getFirst().getKey().getLabel());
        assertEquals(arthurTopic, page.getContent().getChildren().getFirst().getValue().getFirst().getTarget());
        assertEquals("Arthur as a second-level link",
                page.getContent().getChildren().getFirst().getValue().getFirst().getLabel());

        // before destroying the page, create another page about Arthur
        Page page2 = topicGraph.createPage(topicGraph.createLink(arthurTopic, "Arthur Philip Dent"));
        Object page2Id = ((PGPage) page2).asVertex().id();

        assertTrue(graph.traversal().V(arthurId).hasNext());
        assertTrue(graph.traversal().V(pageId).hasNext());
        assertTrue(graph.traversal().V(page2Id).hasNext());

        page.destroy();

        // Arthur is still here, as it is also referenced by page2
        assertTrue(graph.traversal().V(arthurId).hasNext());
        assertFalse(graph.traversal().V(pageId).hasNext());
        assertTrue(graph.traversal().V(page2Id).hasNext());

        page2.destroy();

        assertFalse(graph.traversal().V(arthurId).hasNext());
        assertFalse(graph.traversal().V(pageId).hasNext());
        assertFalse(graph.traversal().V(page2Id).hasNext());
    }
}


text:
giza-example
============

Example using the Giza framework in NodeJS

Specific details about how to execute each example can be found inside each directory mentioned below.

### Hotel

An example of using Giza to store a hotel, floors, and rooms hierarchically with a real-time client which uses events and triggers to update.


text:
/// <reference types="@stdlib/types"/>

import { ndarray } from '@stdlib/types/ndarray';
import gswap = require( './index' );

/**
* Returns an ndarray object.
*
* @returns ndarray object
*/
function createArray(): ndarray {
	const arr: ndarray = {
		'byteLength': null,
		'BYTES_PER_ELEMENT': null,
		'data': [ 1, 2, 3 ],
		'dtype': 'generic',
		'flags': {
			'ROW_MAJOR_CONTIGUOUS': true,
			'COLUMN_MAJOR_CONTIGUOUS': false
		},
		'length': 3,
		'ndims': 1,
		'offset': 0,
		'order': 'row-major',
		'shape': [ 3 ],
		'strides': [ 1 ],
		'get': ( i: number ): any => {
			return arr.data[ i ];
		},
		'set': ( i: number, v: any ): ndarray => {
			arr.data[ i ] = v;
			return arr;
		}
	};
	return arr;
}

// TESTS //

// The function returns an ndarray or array-like object...
{
	gswap( [ 1, 2, 3 ], [ 4, 5, 6 ] ); // $ExpectType ndarray | ArrayLike<any>
	gswap( createArray(), createArray() ); // $ExpectType ndarray | ArrayLike<any>
}

// The compiler throws an error if the function is provided a first argument which is not an ndarray or array-like object...
{
	const y: ndarray = createArray();

	gswap( 10, y ); // $ExpectError
	gswap( true, y ); // $ExpectError
	gswap( false, y ); // $ExpectError
	gswap( null, y ); // $ExpectError
	gswap( undefined, y ); // $ExpectError
	gswap( {}, y ); // $ExpectError
}

// The compiler throws an error if the function is provided a second argument which is not an ndarray or array-like object...
{
	const x: ndarray = createArray();

	gswap( x, 10 ); // $ExpectError
	gswap( x, true ); // $ExpectError
	gswap( x, false ); // $ExpectError
	gswap( x, null ); // $ExpectError
	gswap( x, undefined ); // $ExpectError
	gswap( x, {} ); // $ExpectError
}

// The compiler throws an error if the function is provided an unsupported number of arguments...
{
	const x: ndarray = createArray();
	const y: ndarray = createArray();

	gswap(); // $ExpectError

	gswap( x ); // $ExpectError
	gswap( [ 1, 2, 3 ] ); // $ExpectError

	gswap( x, y, {} ); // $ExpectError
	gswap( [ 1, 2, 3 ], [ 4, 5, 6 ], {} ); // $ExpectError
}


text:
require_relative 'response_parser'
require_relative 'word_reference_api'

module WordReference
  class Dictionary
    include WordReference
    include WordReference::Configurable

    attr_reader :name, :api_key

    BASE_URL = "http://api.wordreference.com"

    def initialize(dictionary_name)
      @name = dictionary_name
      config
    end

    def change_language(dictionary_name)
      @name = dictionary_name
    end

    def query(term)
      response = word_reference_api.query(url(term))
      response_parser = ResponseParser.new(response.body)
      response_parser.run
    end

    private

    def config
      WordReference::Configurable.keys.each do |key|
        instance_variable_set(
          :"@#{key}",
          WordReference.instance_variable_get(:"@#{key}")
        )
      end
    end

    def url(term)
      "#{BASE_URL}/0.8/#{api_key}/json/#{name}/#{term}"
    end

    def word_reference_api
      @word_reference_api ||= WordReferenceApi.new
    end
  end
end


text:
(function($){
  $(function(){

    $('.parallax').parallax();

  }); // end of document ready
})(jQuery); // end of jQuery name space

 $(document).ready(function(){
    $('.tooltipped').tooltip({delay: 50});
  });
        $(document).ready(function(){
    $('.tooltipped').tooltip({delay: 50});
  });

    $(document).ready(function(){
      $('.slider').slider();
    });


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.11"/>
<title>CS 250 Project 3: Binary Search Tree: Member List</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

CS 250 Project 3: Binary Search Tree

Main Page

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Class List

Class Index

Class Hierarchy

Class Members

Tester Member List

This is the complete list of members for Tester, including all inherited members.

Test_Contains()	Tester	private

Test_Delete()	Tester	private

Test_FindNode()	Tester	private

Test_FindParentOfNode()	Tester	private

Test_GetCount()	Tester	private

Test_GetHeight()	Tester	private

Test_GetInOrder()	Tester	private

Test_GetMax()	Tester	private

Test_GetPostOrder()	Tester	private

Test_GetPreOrder()	Tester	private

Test_Push()	Tester	private

Tester()	Tester	inline

<address class="footer">
Generated by

 1.8.11
</address>


text:
package mmvdump

import (
	"errors"
	"fmt"
	"math"
	"sync"
	"unsafe"
)

func readHeader(data []byte) (*Header, error) {
	if uint64(len(data)) < HeaderLength {
		return nil, errors.New("file too small to contain a valid Header")
	}

	header := (*Header)(unsafe.Pointer(&data[0]))

	if m := header.Magic[:3]; string(m) != "MMV" {
		return nil, fmt.Errorf("Bad Magic: %v", string(m))
	}

	if header.G1 != header.G2 {
		return nil, fmt.Errorf("Mismatched version numbers, %v and %v", header.G1, header.G2)
	}

	return header, nil
}

func readToc(data []byte, offset uint64) (*Toc, error) {
	if uint64(len(data)) < offset+TocLength {
		return nil, errors.New("Incomplete/Partially Written TOC")
	}

	return (*Toc)(unsafe.Pointer(&data[offset])), nil
}

type itemReaderFunc func([]byte, uint64, int32) (interface{}, error)

func readInstance(data []byte, offset uint64, version int32) (interface{}, error) {
	var InstanceLength = Instance1Length
	if version == 2 {
		InstanceLength = Instance2Length
	}

	if uint64(len(data)) < offset+InstanceLength {
		return nil, errors.New("Incomplete/Partially Written Instance")
	}

	if version == 1 {
		return (*Instance1)(unsafe.Pointer(&data[offset])), nil
	}

	return (*Instance2)(unsafe.Pointer(&data[offset])), nil
}

func readInstanceDomain(data []byte, offset uint64, version int32) (interface{}, error) {
	if uint64(len(data)) < offset+InstanceDomainLength {
		return nil, errors.New("Incomplete/Partially Written InstanceDomain")
	}

	return (*InstanceDomain)(unsafe.Pointer(&data[offset])), nil
}

func readMetric(data []byte, offset uint64, version int32) (interface{}, error) {
	var MetricLength = Metric1Length
	if version == 2 {
		MetricLength = Metric2Length
	}

	if uint64(len(data)) < offset+MetricLength {
		return nil, errors.New("Incomplete/Partially Written Metric")
	}

	if version == 1 {
		return (*Metric1)(unsafe.Pointer(&data[offset])), nil
	}

	return (*Metric2)(unsafe.Pointer(&data[offset])), nil
}

func readValue(data []byte, offset uint64, version int32) (interface{}, error) {
	if uint64(len(data)) < offset+ValueLength {
		return nil, errors.New("Incomplete/Partially Written Value")
	}

	return (*Value)(unsafe.Pointer(&data[offset])), nil
}

func readString(data []byte, offset uint64, version int32) (interface{}, error) {
	if uint64(len(data)) < offset+StringLength {
		return nil, errors.New("Incomplete/Partially Written String")
	}

	return (*String)(unsafe.Pointer(&data[offset])), nil
}

func readTocs(data []byte, count int32) ([]*Toc, error) {
	tocs := make([]*Toc, count)

	for i := int32(0); i < count; i++ {
		t, err := readToc(data, HeaderLength+uint64(i)*TocLength)
		if err != nil {
			return nil, err
		}
		tocs[i] = t
	}

	return tocs, nil
}

func readItems(data []byte, offset uint64, count int32, itemlength uint64, readItem itemReaderFunc, version int32) (map[uint64]interface{}, error) {
	var wg sync.WaitGroup
	wg.Add(int(count))

	items := make(map[uint64]interface{})

	var (
		err error
		m   sync.Mutex
	)

	for i := int32(0); i < count; i, offset = i+1, offset+itemlength {
		go func(offset uint64) {
			if err == nil {
				item, ierr := readItem(data, offset, version)
				if ierr == nil {
					m.Lock()
					items[offset] = item
					m.Unlock()
				} else {
					err = ierr
				}
			}
			wg.Done()
		}(offset)
	}

	wg.Wait()

	if err != nil {
		return nil, err
	}

	return items, nil
}

func readInstances(data []byte, offset uint64, count int32, version int32) (map[uint64]Instance, error) {
	InstanceLength := Instance1Length
	if version == 2 {
		InstanceLength = Instance2Length
	}

	i, err := readItems(data, offset, count, InstanceLength, readInstance, version)
	if err != nil {
		return nil, err
	}

	instances := make(map[uint64]Instance)
	for off, val := range i {
		instances[off] = val.(Instance)
	}

	return instances, nil
}

func readInstanceDomains(data []byte, offset uint64, count int32, version int32) (map[uint64]*InstanceDomain, error) {
	i, err := readItems(data, offset, count, InstanceDomainLength, readInstanceDomain, version)
	if err != nil {
		return nil, err
	}

	indoms := make(map[uint64]*InstanceDomain)
	for off, val := range i {
		indoms[off] = val.(*InstanceDomain)
	}

	return indoms, nil
}

func readMetrics(data []byte, offset uint64, count int32, version int32) (map[uint64]Metric, error) {
	var MetricLength = Metric1Length
	if version == 2 {
		MetricLength = Metric2Length
	}

	m, err := readItems(data, offset, count, MetricLength, readMetric, version)
	if err != nil {
		return nil, err
	}

	metrics := make(map[uint64]Metric)
	for off, val := range m {
		metrics[off] = val.(Metric)
	}

	return metrics, nil
}

func readValues(data []byte, offset uint64, count int32, version int32) (map[uint64]*Value, error) {
	v, err := readItems(data, offset, count, ValueLength, readValue, version)
	if err != nil {
		return nil, err
	}

	values := make(map[uint64]*Value)
	for off, val := range v {
		values[off] = val.(*Value)
	}

	return values, nil
}

func readStrings(data []byte, offset uint64, count int32, version int32) (map[uint64]*String, error) {
	s, err := readItems(data, offset, count, StringLength, readString, version)
	if err != nil {
		return nil, err
	}

	strings := make(map[uint64]*String)
	for off, val := range s {
		strings[off] = val.(*String)
	}

	return strings, nil
}

func readComponents(data []byte, tocs []*Toc, version int32) (
	metrics map[uint64]Metric,
	values map[uint64]*Value,
	instances map[uint64]Instance,
	indoms map[uint64]*InstanceDomain,
	strings map[uint64]*String,
	ierr, inerr, merr, verr, serr error,
) {
	var wg sync.WaitGroup
	wg.Add(len(tocs))

	for _, toc := range tocs {
		switch toc.Type {
		case TocInstances:
			go func(offset uint64, count int32) {
				instances, ierr = readInstances(data, offset, count, version)
				wg.Done()
			}(toc.Offset, toc.Count)
		case TocIndoms:
			go func(offset uint64, count int32) {
				indoms, inerr = readInstanceDomains(data, offset, count, version)
				wg.Done()
			}(toc.Offset, toc.Count)
		case TocMetrics:
			go func(offset uint64, count int32) {
				metrics, merr = readMetrics(data, offset, count, version)
				wg.Done()
			}(toc.Offset, toc.Count)
		case TocValues:
			go func(offset uint64, count int32) {
				values, verr = readValues(data, offset, count, version)
				wg.Done()
			}(toc.Offset, toc.Count)
		case TocStrings:
			go func(offset uint64, count int32) {
				strings, serr = readStrings(data, offset, count, version)
				wg.Done()
			}(toc.Offset, toc.Count)
		}
	}

	wg.Wait()

	return
}

// Dump creates a data dump from the passed data
func Dump(data []byte) (
	h *Header,
	tocs []*Toc,
	metrics map[uint64]Metric,
	values map[uint64]*Value,
	instances map[uint64]Instance,
	indoms map[uint64]*InstanceDomain,
	strings map[uint64]*String,
	err error,
) {
	h, err = readHeader(data)
	if err != nil {
		return nil, nil, nil, nil, nil, nil, nil, err
	}

	tocs, err = readTocs(data, h.Toc)
	if err != nil {
		return nil, nil, nil, nil, nil, nil, nil, err
	}

	var ierr, inerr, merr, verr, serr error

	metrics, values, instances, indoms, strings, ierr, inerr, merr, verr, serr = readComponents(data, tocs, h.Version)

	switch {
	case ierr != nil:
		return nil, nil, nil, nil, nil, nil, nil, ierr
	case inerr != nil:
		return nil, nil, nil, nil, nil, nil, nil, inerr
	case merr != nil:
		return nil, nil, nil, nil, nil, nil, nil, merr
	case verr != nil:
		return nil, nil, nil, nil, nil, nil, nil, verr
	case serr != nil:
		return nil, nil, nil, nil, nil, nil, nil, serr
	}

	return
}

// FixedVal will infer a fixed size value from the passed data
func FixedVal(data uint64, t Type) (interface{}, error) {
	switch t {
	case Int32Type:
		return int32(data), nil
	case Uint32Type:
		return uint32(data), nil
	case Int64Type:
		return int64(data), nil
	case Uint64Type:
		return data, nil
	case FloatType:
		return math.Float32frombits(uint32(data)), nil
	case DoubleType:
		return math.Float64frombits(data), nil
	}

	return nil, errors.New("invalid type")
}


text:
Glim framework natively supports rdb abstraction by its [SQLAlchemy](http://docs.sqlalchemy.org/en/rel_0_9/) integration. SQLAlchemy is great a rdb abstraction kit with connection layer & object relational layer abstractions. In glim, the DB API won't require Orm features if it's not enabled. However, ORM is dependent on DB API naturally. It is highly suggested to read an introduction to sqlalchemy before going further.

So, let's make configuration!
[block:api-header]
{
  "type": "basic",
  "title": "Configuration & Connection Aliasing"
}
[/block]
An rdb configuration is quite simple in glim framework. Simply add these lines to enable db api & orm components;
[block:code]
{
  "codes": [
    {
      "code": "# app/config/development.py\n{\n    # ...\n  \n    'db': {\n\t      'default': {\n\t\t\t\t    'driver': 'mysql',\n\t\t\t\t\t\t'host': 'localhost',\n\t\t\t\t\t\t'schema': 'test',\n\t\t\t\t\t\t'user': 'root',\n\t\t\t\t\t\t'password': ''\n        }\n    },\n  \n    'orm': True,\n\n    # ...\n}",
      "language": "python"
    }
  ]
}
[/block]
You might notice that we need a "default" key in this configuration. The reason why default exists is that glim can provide multiple database connections. The "default" key is here instructing glim to make database calls without having to give schema name. You can add more database connections by adding more keys inside the "db" dictionary;
[block:code]
{
  "codes": [
    {
      "code": "# app/config/development.py\n{\n    # ...\n  \n    'db': {\n\t      'default': {\n\t\t\t\t    # ...\n        },\n        'analytics': {\n           'driver': 'mysql',\n\t\t\t\t\t 'host': 'localhost',\n\t\t\t\t\t 'schema': 'analytics',\n\t\t\t\t\t 'user': 'root',\n\t\t\t\t\t 'password': ''\n        }\n    },\n  \n    'orm': True,\n\n    # ...\n}",
      "language": "python"
    }
  ]
}
[/block]
Now, we have an aliased database connection called "analytics". An aliased connection could be reached in DB API like the following;
[block:code]
{
  "codes": [
    {
      "code": "from glim.db import Database as DB\n# returns the connection\nDB.connection('analytics') # returns the \"analytics\" connection.\nDB.connection() # returns the default connection",
      "language": "python"
    }
  ]
}
[/block]

[block:api-header]
{
  "type": "basic",
  "title": "Defining Models & Mapping"
}
[/block]
Glim has a Model class inside glim.db module. The Model class is simply an alias of `declarative_base()` in SQLAlchemy. Defining a simple User model would be the following;
[block:code]
{
  "codes": [
    {
      "code": "# app/models.py\nfrom glim.db import Model\nfrom sqlalchemy import Column, Integer, String\n\nclass User(Model):\n    __tablename__ = 'users'\n    id = Column(Integer, primary_key=True)\n    name = Column(String(255))\n    fullname = Column(String(255))\n    password = Column(String(255))",
      "language": "python"
    }
  ]
}
[/block]
This model maps to a users database table given the properties. As you noticed, the table name is mapped using `__tablename__` variable. In other words, this table is mapped as if there exists a table with the following sql;
[block:code]
{
  "codes": [
    {
      "code": "CREATE TABLE `users` (\n  `id` int(11) NOT NULL,\n  `name` varchar(255) DEFAULT NULL,\n  `fullname` varchar(255) DEFAULT NULL,\n  `password` varchar(255) DEFAULT NULL,\n  PRIMARY KEY (`id`)\n);",
      "language": "mysql"
    }
  ]
}
[/block]

[block:api-header]
{
  "type": "basic",
  "title": "Defining Relations"
}
[/block]
In glim, you can define model relations with SQLAlchemy's `relationship()` function. This section provides model relation examples.

# One to One
SQLAlchemy defines one to one relations by the following statement;

"One To One is essentially a bidirectional relationship with a scalar attribute on both sides. To achieve this, the uselist flag indicates the placement of a scalar attribute instead of a collection on the "many" side of the relationship."

Consider a system where users having a phone number. In glim, you can define 2 tables namely "User" and "Phone" and provide a one to one relationship with the following;
[block:code]
{
  "codes": [
    {
      "code": "# models.py\nfrom glim.db import Model\nfrom sqlalchemy import Column, Integer, String, Text, ForeignKey\nfrom sqlalchemy.orm import relationship, backref\n\nclass User(Model):\n    __tablename__ = 'users'\n    id = Column(Integer, primary_key=True)\n    name = Column(String(255))\n    fullname = Column(String(255))\n    password = Column(String(255))\n    phone = relationship(\"Phone\", uselist=False, backref=\"phones\")\n\nclass Phone(Model):\n\t\t__tablename__ = 'phones'\n\t\tid = Column(Integer, primary_key=True)\n\t\tuser_id = Column(Integer, ForeignKey('users.id'))\n\t\tnumber = Column(String(12))\n",
      "language": "python"
    }
  ]
}
[/block]
# One to Many
SQLAlchemy defines one to many relationships by the following statement;

"A one to many relationship places a foreign key on the child table referencing the parent. `relationship()` is then specified on the parent, as referencing a collection of items represented by the child"

Consider a blog system where blog posts. This relation can be done in glim by the following;
[block:code]
{
  "codes": [
    {
      "code": "# models.py\nfrom glim.db import Model\nfrom sqlalchemy import Column, Integer, String, Text, ForeignKey\nfrom sqlalchemy.orm import relationship, backref\n\nclass Post(Model):\n\t\t__tablename__ = 'posts'\n\t\tid = Column(Integer, primary_key=True)\n\t\tcomments = relationship(\"Comment\")\n\nclass Comment(Model):\n\t\t__tablename__ = 'comments'\n\t\tid = Column(Integer, primary_key=True)\n\t\tpost_id = Column(Integer, ForeignKey('posts.id'))\n\t\ttext = Column(Text(300))",
      "language": "python"
    }
  ]
}
[/block]
You can achieve bidirectional relationship in Post using `backref` statement;
[block:code]
{
  "codes": [
    {
      "code": "class Post(Model):\n\t\t__tablename__ = 'posts'\n\t\tid = Column(Integer, primary_key=True)\n\t\tcomments = relationship(\"Comment\", backref='comments')",
      "language": "python"
    }
  ]
}
[/block]
This change will also provide a "reverse" type of one to many relationship namely "many to one".

## Many to One
SQLAlchemy defines many to one relationships by the following statement;

"Many to one places a foreign key in the parent table referencing the child. relationship() is declared on the parent, where a new scalar-holding attribute will be created"

Many to One relationships can be achieved with backref attribute. Consider a system where users can join a group. In this system, users are limited to join to only one group.
[block:code]
{
  "codes": [
    {
      "code": "# models.py\nfrom glim.db import Model\nfrom sqlalchemy import Column, Integer, String, Text, ForeignKey\nfrom sqlalchemy.orm import relationship, backref\n\nclass User(Model):\n    __tablename__ = 'user'\n    id = Column(Integer, primary_key=True)\n    group_id = Column(Integer, ForeignKey('group.id'))\n    group = relationship(\"Group\")\n\nclass Group(Model):\n\t\t__tablename__ = 'group'\n\t\tid = Column(Integer, primary_key=True)",
      "language": "python"
    }
  ]
}
[/block]
You can achieve bidirectional relationship in User using `backref` statement;
[block:code]
{
  "codes": [
    {
      "code": "class User(Model):\n    __tablename__ = 'user'\n    id = Column(Integer, primary_key=True)\n    group_id = Column(Integer, ForeignKey('group.id'))\n    group = relationship(\"Group\", backref=\"users\")",
      "language": "python"
    }
  ]
}
[/block]
## Many to Many
SQLAlchemy defines many to many relationships by the following statement;

"Many to Many adds an association table between two classes. The association table is indicated by the secondary argument to relationship(). Usually, the Table uses the MetaData object associated with the declarative base class, so that the ForeignKey directives can locate the remote tables with which to link"

Consider a system where blog posts have tags. This can be done by the following;
[block:code]
{
  "codes": [
    {
      "code": "# models.py\nfrom glim.db import Model\nfrom sqlalchemy import Column, Integer, String, Text, ForeignKey\nfrom sqlalchemy.orm import relationship, backref\n\nclass Post(Model):\n\t\t__tablename__ = 'posts'\n\t\tid = Column(Integer, primary_key=True)\n  \ttags = relationship('Tag', secondary=tags)\n\ntags = Table('tags',\n\tColumn('tag_id', Integer, ForeignKey('tag.id'),\n\tColumn('post_id', Integer, ForeignKey('post_id'))))\n\nclass Tag(Model):\n\t\tid = Column(Integer, primary_key=True)",
      "language": "python"
    }
  ]
}
[/block]
A bidirectional relationship could be established using `backref` in the Post model by the following;
[block:code]
{
  "codes": [
    {
      "code": "class Post(Model):\n\t\t__tablename__ = 'posts'\n  \tid = Columtn(Integer, primary_key=True)\n  \ttags = relationship('Tag', secondary=tags, backref='tags')",
      "language": "python"
    }
  ]
}
[/block]

[block:api-header]
{
  "type": "basic",
  "title": "Querying"
}
[/block]
After defining releations and model mappings, querying is the most important concept to learn. In glim, there are many ways to achieve querying. You can even write raw sql queries using the DB API. This section explains the orm querying part only.

# Switching between connections
In glim, it is said above that you can do connection aliasing in the "default-analytics" connection. You can switch to "analytics" database connection by the following;
[block:code]
{
  "codes": [
    {
      "code": "# app/config/<env>.py\nconfig = { \n  'db': {\n\t      'default': {\n\t\t\t\t    # ...\n        },\n        'analytics': {\n           'driver': 'mysql',\n\t\t\t\t\t 'host': 'localhost',\n\t\t\t\t\t 'schema': 'analytics',\n\t\t\t\t\t 'user': 'root',\n\t\t\t\t\t 'password': ''\n        }\n    },\n}\n\nfrom glim.db import Orm\n\nOrm.connection('analytics').blah() # performs operations on the analytics database\nOrm.blah() # performs operations on the default conncetion",
      "language": "python"
    }
  ]
}
[/block]
In this example we can infer that Orm object holds the active session object of SQLAlchemy.

# The query() function
The `query()` function takes model classes or model column names and configures itself. You can use method chaining here by the following;
[block:code]
{
  "codes": [
    {
      "code": "from glim.db import Orm\n\n# query from a class\nOrm.query(User).filter_by(name='Aras').all()\n\n# querying from a class with only one row\nOrm.query(User).filter_by(name='Aras').first()\n\n# query with multiple classes\nOrm.query(User, Phone).join('phone').filter_by(name='Aras').all()\n\n# query specific columns\nOrm.query(User.name, User.id).all()",
      "language": "python"
    }
  ]
}
[/block]
You can get much more information in the [Querying](http://docs.sqlalchemy.org/en/rel_0_9/orm/query.html) section of SQLAlchemy.
[block:api-header]
{
  "type": "basic",
  "title": "Adding new items with orm session"
}
[/block]
You can create new models and persist in the database using `add()` & `commit()` function.
[block:code]
{
  "codes": [
    {
      "code": "# services.py\nfrom glim.db import Orm\nfrom app.models import User\n\ndef add_users(user1_name, user2_name):\n\t\tuser1 = User(name=user1_name)\n  \tuser2 = User(name=user2_name)\n  \tOrm.add(user1)\n  \tOrm.add(user2)\n  \tOrm.commit() # write changes to the database",
      "language": "python"
    }
  ]
}
[/block]
You can also add the users as a list by the following
[block:code]
{
  "codes": [
    {
      "code": "Orm.add_all([user1, user2])",
      "language": "python"
    }
  ]
}
[/block]

[block:callout]
{
  "type": "warning",
  "title": "Disabled autocommit",
  "body": "Currently, it is required to write `commit()` statements to persist models to database. Although it is highly suggested to make these database changes transactional, the autocommit mode will be enabled. This issue will be addressed on the future releases."
}
[/block]

[block:api-header]
{
  "type": "basic",
  "title": "Deleting Items using orm session"
}
[/block]
You can filter and delete tuples by the following;
[block:code]
{
  "codes": [
    {
      "code": "from glim.db import Orm\n\nOrm.query(User).filter(id=7).delete()",
      "language": "python"
    }
  ]
}
[/block]

[block:api-header]
{
  "type": "basic",
  "title": "Using DB API"
}
[/block]
The DB API includes the `engine` instance of active connection. You can use SQL Expression Language that SQLAlchemy provides. It is highly recommended to read [this documentation](http://docs.sqlalchemy.org/en/rel_0_9/core/tutorial.html#) first.

# Running SQL Expression on models
The documentation above showed how to define models. SQL Expression language requires `Table` object to run chained sql statements. Consider an example of a system holding users in a model. The following example shows a simple select statemtent on defined model;
[block:code]
{
  "codes": [
    {
      "code": "# models.py\nfrom glim.db import Model\nfrom sqlalchemy import Column, Integer, String, Text, ForeignKey\nfrom sqlalchemy.orm import relationship, backref\n\nclass User(Model):\n\t\t__tablename__ = 'users'\n  \tid = Column(Integer, primary_key=True)\n  \tname = Column(String(250))\n\n# services.py\nfrom app.models import User\nfrom glim.db import Database as DB\nfrom sqlalchemy.sql import select\n\ndef select_all_users():\n\t\ts = select([User.__table__])\n  \tresult = DB.execute(s)\n  \tfor row in result:\n\t\t    print row\n  ",
      "language": "python"
    }
  ]
}
[/block]
You can notice that sql expression language can be run by using `__table__` property of a model. You can fetch one row using `fetchone()` function;
[block:code]
{
  "codes": [
    {
      "code": "# services.py\nfrom glim.db import Database as DB\nfrom app.models import User\n\n# get rows using defined column names\ndef select_first_user():\n\t\ts = select([User.__table__])\n  \tresult = DB.execute(s)\n  \trow = result.fetchone()\n  \tprint(\"name:\", row['name'], \"; fullname:\", row['fullname'])\n  \n# get rows using column name in __table__\ndef select_first_user2():\n  \ts = select([User.__table__])\n  \tresult = DB.execute(s)\n  \trow = result.fetchone()\n  \tprint(\"name:\", row[User.__table__.c.name],\n        \t\"; fullname:\", row[User.__table__.c.fullname])",
      "language": "python"
    }
  ]
}
[/block]

# Insert Expressions
Consider the example of the user model above. You can achieve insert expressions by running `Model.__table__` statement by the following;
[block:code]
{
  "codes": [
    {
      "code": "# services.py\nfrom app.models import User\nfrom glim.db import Database as DB\n\ndef insert_user(name):\n\t\tins = User.__table__\n  \t\t\t\t\t\t.insert().values(name='Aras')\n \t\tresult = DB.execute(ins)\n  \treturn result",
      "language": "python"
    }
  ]
}
[/block]
# Select Expressions
You can run selects by chaining statements;
[block:code]
{
  "codes": [
    {
      "code": "from glim.db import Database as DB\nfrom app.models import User, Address\n\nusers = User.__table__\naddresses = Address.__table__\n\n# an example of chaining multiple tables\ns = select([users, addresses])\n\t\t\t.where(users.c.id == addresses.c.user_id)\n  \n# an example of chaining more and or_ statements\ns = select([users.c.fullname + \", \" + addresses.c.email_address])\n\t\t\t.where(users.c.id == addresses.c.user_id)\n  \t\t.where(users.c.name.between('m', 'z'))\n    \t.where(\n       \tor_(\n        \taddresses.c.email_address.like('%@gmail.com')\n         \taddresses.c.email_address.like('%@yandex.com')\n        ) \n      )\n      \nrows = DB.execute(s).fetchall()",
      "language": "python"
    }
  ]
}
[/block]
# Order By, Group By
[block:code]
{
  "codes": [
    {
      "code": "from sqlalchemy import func, desc\nfrom glim.db import Database as DB\nfrom app.models import Address\n\naddresses = Address.__table__\n\nstmt = select([\n\taddresses.c.user_id,\n\tfunc.count(addresses.c.id).label('num_addresses')]).\\\n\torder_by(\"num_addresses\")\n\nDB.execute(stmt).fetchall()\n\nstmt = select([\n\t\t\t\taddresses.c.user_id,\n\t\t\t\tfunc.count(addresses.c.id).label('num_addresses')]).\\\n\t\t\t\torder_by(desc(\"num_addresses\"))\n  \nDB.execute(stmt).fetchall()",
      "language": "python"
    }
  ]
}
[/block]

# Update Expressions
You can run update statements using `update()` function by the following;
[block:code]
{
  "codes": [
    {
      "code": "from glim.db import Database as DB\nfrom app.models import User\n\nusers = User.__table__\n\nstmt = users.update().\\\n\t\t\t\twhere(users.c.name == 'Aras').\\\n\t\t\t\tvalues(fullname=\"Fullname: \" + users.c.name)\n\nresult = DB.execute(stmt)",
      "language": "python"
    }
  ]
}
[/block]
# Delete Expressions
You can run delete statements using `delete()` function by the following;
[block:code]
{
  "codes": [
    {
      "code": "from glim.db import Database as DB\nfrom app.models import Address\n\naddresses = Address.__table__\nDB.execute(addresses.delete())",
      "language": "python"
    }
  ]
}
[/block]

# Raw Queries
There are many ways of running raw sql queries
[block:code]
{
  "codes": [
    {
      "code": "from sqlalchemy.sql import text\nfrom glim.db import Database as DB\n\ns = text(\n\t\t\"SELECT users.fullname || ', ' || addresses.email_address AS title \"\n\t\t\"FROM users, addresses \"\n\t\t\"WHERE users.id = addresses.user_id \"\n\t\t\"AND users.name BETWEEN :x AND :y \"\n\t\t\"AND (addresses.email_address LIKE :e1 \"\n\t\t\"OR addresses.email_address LIKE :e2)\")\n\nDB.execute(s, x='m', y='z',\n           e1='%@gmail.com',\n           e2='%@yandex.com')\n\t.fetchall()\n  \nsql = \"INSERT INTO users (full_name, title)\" \\\n      \"VALUES ('%s','%s')\" % (full_name, title))\"\n\nresult = DB.execute(sql)\nprint result",
      "language": "python"
    }
  ]
}
[/block]

[block:api-header]
{
  "type": "basic",
  "title": "Migrations"
}
[/block]
Migrations are currenlty available by [RDB Migrations](doc:rdb-migrations) extension. You can check the docs about database migrations there.


text:
class Pistol : public Weapon {

public:

    Pistol(Projectiles* projs);
    ~Pistol();

    virtual void fire(int x, int y, int dir);

private:

};

#endif // _H_PISTOL_H_


text:
<?xml version="1.0" encoding="UTF-8"?>
<testng-results skipped="0" failed="0" total="1" passed="1">
  <reporter-output>
  </reporter-output>
  <suite name="Surefire suite" duration-ms="338" started-at="2017-07-31T19:29:34Z" finished-at="2017-07-31T19:29:35Z">
    <groups>
    </groups>
    <test name="Surefire test" duration-ms="338" started-at="2017-07-31T19:29:34Z" finished-at="2017-07-31T19:29:35Z">
      <class name="org.wso2.carbon.apimgt.rest.api.core.utils.PolicyExportManagerTest">
        <test-method status="PASS" signature="init()[pri:0, instance:org.wso2.carbon.apimgt.rest.api.core.utils.PolicyExportManagerTest@1e67b872]" name="init" is-config="true" duration-ms="15" started-at="2017-08-01T00:59:34Z" finished-at="2017-08-01T00:59:34Z">
          <reporter-output>
          </reporter-output>
        </test-method> <!-- init -->
        <test-method status="PASS" signature="testCreateArchiveFromExecutionPlans()[pri:0, instance:org.wso2.carbon.apimgt.rest.api.core.utils.PolicyExportManagerTest@1e67b872]" name="testCreateArchiveFromExecutionPlans" duration-ms="313" started-at="2017-08-01T00:59:34Z" description="testing creating archive from execution plans" finished-at="2017-08-01T00:59:35Z">
          <reporter-output>
          </reporter-output>
        </test-method> <!-- testCreateArchiveFromExecutionPlans -->
      </class> <!-- org.wso2.carbon.apimgt.rest.api.core.utils.PolicyExportManagerTest -->
    </test> <!-- Surefire test -->
  </suite> <!-- Surefire suite -->
</testng-results>


text:
package io.smalldata.ohmageomh.dpu.config;

import org.quartz.Scheduler;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.configuration.JobRegistry;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;

/**
 * @author Jared Sieling.
 */
@Configuration
public class InitializeConfiguration implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    private JobRegistry jobRegistry;

    @Autowired
    private JobLauncher jobLauncher;

    private static final Logger log = LoggerFactory.getLogger(InitializeConfiguration.class);

    @Override
    public void onApplicationEvent(final ContextRefreshedEvent event) {
        try {
            Scheduler scheduler = new StdSchedulerFactory().getScheduler();
            scheduler.start();

            // TODO: Schedule all the jobs
//            List<ChannelScheduledJob> schedules = channelScheduledJobRepository.findAll();
//            for (ChannelScheduledJob schedule : schedules) {
//                log.info("Scheduling: " + schedule.toString());
//
//                JobKey jobKey = new JobKey(schedule.getId(), "mygroup");
//                JobDataMap dataMap = new JobDataMap();
//                dataMap.put("jobName", schedule.getJobName());
//                dataMap.put("jobLocator", jobRegistry);
//                dataMap.put("jobLauncher", jobLauncher);
//                dataMap.put("channelId", schedule.getChannel().getId());
//                JobDetail mJobDetail = JobBuilder.newJob(JobLauncherDetails.class)
//                        .withIdentity(jobKey)
//                        .usingJobData(dataMap)
//                        .storeDurably(true)
//                        .build();
//
//                Trigger trigger = TriggerBuilder
//                        .newTrigger()
//                        .withIdentity(schedule.getId(), "mygroup")
//                        .forJob(mJobDetail)
//                        .withSchedule(
//                                CronScheduleBuilder.cronSchedule(schedule.getCronExpression()))
//                        .build();
//
//                scheduler.scheduleJob(mJobDetail, trigger);
//            }
        } catch (Exception ex) {
            log.info("Could not schedule jobs.");
        }
    }
}


text:
FROM python:2-onbuild
EXPOSE 5000
CMD [ "python", "./application.py" ]


text:
Get Agile
================

An open source agile storyboard built on Firebase.

http://getagile.herokuapp.com/


text:
class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception

  # for stuff we need on shared views
  before_filter :foo_function
  def foo_function
    @categories = Category.all
  end
end


text:
package com.intellij.ide.structureView.impl.java;

import com.intellij.ide.actions.ViewStructureAction;
import com.intellij.ide.structureView.StructureViewModel;
import com.intellij.ide.structureView.StructureViewTreeElement;
import com.intellij.ide.structureView.TextEditorBasedStructureViewModel;
import com.intellij.ide.util.treeView.smartTree.Filter;
import com.intellij.ide.util.treeView.smartTree.Grouper;
import com.intellij.ide.util.treeView.smartTree.NodeProvider;
import com.intellij.ide.util.treeView.smartTree.Sorter;
import com.intellij.openapi.editor.Editor;
import com.intellij.psi.*;
import com.intellij.ui.PlaceHolder;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.Arrays;
import java.util.Collection;

public class JavaFileTreeModel extends TextEditorBasedStructureViewModel implements StructureViewModel.ElementInfoProvider, PlaceHolder<String> {
  private static final Collection<NodeProvider> NODE_PROVIDERS = Arrays.<NodeProvider>asList(new JavaInheritedMembersNodeProvider(),
                                                                                new JavaAnonymousClassesNodeProvider());
  private final PsiClassOwner myFile;
  private String myPlace;

  public JavaFileTreeModel(@NotNull PsiClassOwner file, @Nullable Editor editor) {
    super(editor, file);
    myFile = file;
  }

  @Override
  @NotNull
  public Filter[] getFilters() {
    return new Filter[]{new FieldsFilter(),
                        new PublicElementsFilter()};
  }

  @NotNull
  @Override
  public Collection<NodeProvider> getNodeProviders() {
    return NODE_PROVIDERS;
  }

  @Override
  @NotNull
  public Grouper[] getGroupers() {
    return new Grouper[]{new SuperTypesGrouper(), new PropertiesGrouper()};
  }

  @Override
  @NotNull
  public StructureViewTreeElement getRoot() {
    return new JavaFileTreeElement(myFile);
  }

  @Override
  public boolean shouldEnterElement(final Object element) {
    return element instanceof PsiClass;
  }

  @Override
  @NotNull
  public Sorter[] getSorters() {
    return new Sorter[] {
      ViewStructureAction.isInStructureViewPopup(this) ? KindSorter.POPUP_INSTANCE : KindSorter.INSTANCE,
      VisibilitySorter.INSTANCE,
      AnonymousClassesSorter.INSTANCE,
      Sorter.ALPHA_SORTER};
  }

  @Override
  protected PsiFile getPsiFile() {
    return myFile;
  }

  @Override
  public boolean isAlwaysShowsPlus(StructureViewTreeElement element) {
    Object value = element.getValue();
    return value instanceof PsiClass || value instanceof PsiFile;
  }

  @Override
  public boolean isAlwaysLeaf(StructureViewTreeElement element) {
    Object value = element.getValue();
    return value instanceof PsiMethod || value instanceof PsiField;
  }

  @Override
  protected boolean isSuitable(final PsiElement element) {
    if (super.isSuitable(element)) {
      if (element instanceof PsiMethod) {
        PsiMethod method = (PsiMethod)element;
        PsiClass parent = method.getContainingClass();
        return parent != null
               && (parent.getQualifiedName() != null || parent instanceof PsiAnonymousClass);
      }

      if (element instanceof PsiField) {
        PsiField field = (PsiField)element;
        PsiClass parent = field.getContainingClass();
        return parent != null && parent.getQualifiedName() != null;
      }

      if (element instanceof PsiClass) {
        return ((PsiClass)element).getQualifiedName() != null;
      }
    }
    return false;
  }

  @Override
  @NotNull
  protected Class[] getSuitableClasses() {
    return new Class[]{PsiClass.class, PsiMethod.class, PsiField.class, PsiJavaFile.class};
  }

  @Override
  public void setPlace(String place) {
    myPlace = place;
  }

  @Override
  public String getPlace() {
    return myPlace;
  }
}


text:
package com.google.cloud.recaptchaenterprise.v1beta1;

import com.google.api.core.BetaApi;
import com.google.api.gax.grpc.testing.MockGrpcService;
import com.google.protobuf.AbstractMessage;
import io.grpc.ServerServiceDefinition;
import java.util.List;
import javax.annotation.Generated;

@BetaApi
@Generated("by gapic-generator-java")
public class MockRecaptchaEnterpriseServiceV1Beta1 implements MockGrpcService {
  private final MockRecaptchaEnterpriseServiceV1Beta1Impl serviceImpl;

  public MockRecaptchaEnterpriseServiceV1Beta1() {
    serviceImpl = new MockRecaptchaEnterpriseServiceV1Beta1Impl();
  }

  @Override
  public List<AbstractMessage> getRequests() {
    return serviceImpl.getRequests();
  }

  @Override
  public void addResponse(AbstractMessage response) {
    serviceImpl.addResponse(response);
  }

  @Override
  public void addException(Exception exception) {
    serviceImpl.addException(exception);
  }

  @Override
  public ServerServiceDefinition getServiceDefinition() {
    return serviceImpl.bindService();
  }

  @Override
  public void reset() {
    serviceImpl.reset();
  }
}


text:
package org.apache.hadoop.mapred;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.net.URL;

import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.WritableFactories;
import org.apache.hadoop.io.WritableFactory;
import org.apache.hadoop.util.StringInterner;

/**************************************************
 * A JobProfile is a MapReduce primitive.  Tracks a job,
 * whether living or dead.
 *
 **************************************************/
@InterfaceAudience.LimitedPrivate({"MapReduce"})
@InterfaceStability.Unstable
public class JobProfile implements Writable {

  static {                                      // register a ctor
    WritableFactories.setFactory
      (JobProfile.class,
       new WritableFactory() {
         public Writable newInstance() { return new JobProfile(); }
       });
  }

  String user;
  final JobID jobid;
  String jobFile;
  String url;
  String name;
  String queueName;

  /**
   * Construct an empty {@link JobProfile}.
   */
  public JobProfile() {
    jobid = new JobID();
  }

  /**
   * Construct a {@link JobProfile} the userid, jobid,
   * job config-file, job-details url and job name.
   *
   * @param user userid of the person who submitted the job.
   * @param jobid id of the job.
   * @param jobFile job configuration file.
   * @param url link to the web-ui for details of the job.
   * @param name user-specified job name.
   */
  public JobProfile(String user, org.apache.hadoop.mapreduce.JobID jobid,
                    String jobFile, String url,
                    String name) {
    this(user, jobid, jobFile, url, name, JobConf.DEFAULT_QUEUE_NAME);
  }

  /**
   * Construct a {@link JobProfile} the userid, jobid,
   * job config-file, job-details url and job name.
   *
   * @param user userid of the person who submitted the job.
   * @param jobid id of the job.
   * @param jobFile job configuration file.
   * @param url link to the web-ui for details of the job.
   * @param name user-specified job name.
   * @param queueName name of the queue to which the job is submitted
   */
  public JobProfile(String user, org.apache.hadoop.mapreduce.JobID jobid,
                    String jobFile, String url,
                    String name, String queueName) {
    this.user = user;
    this.jobid = JobID.downgrade(jobid);
    this.jobFile = jobFile;
    this.url = url;
    this.name = name;
    this.queueName = queueName;
  }

  /**
   * @deprecated use JobProfile(String, JobID, String, String, String) instead
   */
  @Deprecated
  public JobProfile(String user, String jobid, String jobFile, String url,
      String name) {
    this(user, JobID.forName(jobid), jobFile, url, name);
  }

  /**
   * Get the user id.
   */
  public String getUser() {
    return user;
  }

  /**
   * Get the job id.
   */
  public JobID getJobID() {
    return jobid;
  }

  /**
   * @deprecated use getJobID() instead
   */
  @Deprecated
  public String getJobId() {
    return jobid.toString();
  }

  /**
   * Get the configuration file for the job.
   */
  public String getJobFile() {
    return jobFile;
  }

  /**
   * Get the link to the web-ui for details of the job.
   */
  public URL getURL() {
    try {
      return new URL(url);
    } catch (IOException ie) {
      return null;
    }
  }

  /**
   * Get the user-specified job name.
   */
  public String getJobName() {
    return name;
  }

  /**
   * Get the name of the queue to which the job is submitted.
   * @return name of the queue.
   */
  public String getQueueName() {
    return queueName;
  }

  ///////////////////////////////////////
  // Writable
  ///////////////////////////////////////
  public void write(DataOutput out) throws IOException {
    jobid.write(out);
    Text.writeString(out, jobFile);
    Text.writeString(out, url);
    Text.writeString(out, user);
    Text.writeString(out, name);
    Text.writeString(out, queueName);
  }

  public void readFields(DataInput in) throws IOException {
    jobid.readFields(in);
    this.jobFile = StringInterner.weakIntern(Text.readString(in));
    this.url = StringInterner.weakIntern(Text.readString(in));
    this.user = StringInterner.weakIntern(Text.readString(in));
    this.name = StringInterner.weakIntern(Text.readString(in));
    this.queueName = StringInterner.weakIntern(Text.readString(in));
  }
}


text:
'use strict';

var jsperf = require('../lib/jsperf.js');

/*
  ======== A Handy Little Nodeunit Reference ========
  https://github.com/caolan/nodeunit

  Test methods:
    test.expect(numAssertions)
    test.done()
  Test assertions:
    test.ok(value, [message])
    test.equal(actual, expected, [message])
    test.notEqual(actual, expected, [message])
    test.deepEqual(actual, expected, [message])
    test.notDeepEqual(actual, expected, [message])
    test.strictEqual(actual, expected, [message])
    test.notStrictEqual(actual, expected, [message])
    test.throws(block, [error], [message])
    test.doesNotThrow(block, [error], [message])
    test.ifError(value)
*/

var y = (function () {/*
%start block
%%
block
	: words EOF
	{ yy.controller.dsSend($1); }
;
words
	: SYMBOL
	{ $$ = []; $$.push($1); }
	| words SYMBOL
	{ $1.push($2); $$ = $1; }
;
%%

*/}).toString().match(/[^]*\/\*([^]*)\*\/\}$/)[1];

var indata = "abc def";

var Monitor = function Monitor() {
  this.syntax = y;
  this.dataname = "test";
}
Monitor.prototype = {
};
Monitor.prototype.constructor = Monitor;

exports['awesome'] = {
  setUp: function(done) {
    // setup here
    done();
  },
  'no args': function(test) {
    test.expect(1);
    // tests here
    var controller = new jsperf.Controller(Monitor);
    controller._processdata(indata);
    controller._processclose();
    var parsed = controller.datastore.fetch({});
    test.ok(true);
    test.done();
  },
};


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

    <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
    <title>Zend_Config_Ini - Zend Framework Manual</title>

                    Theory of Operation

Zend_Config

                        Programmer's Reference Guide

Zend_Config_Json

Zend_Config_Ini

        Zend_Config_Ini ermöglicht es Entwicklern, Konfigurations-Daten in
        einem vertrauten <acronym class="acronym">INI</acronym> Format zu speichern und sie mit einer Syntax
        auszulesen, die dem Zugriff auf die Eigenschaften verschachtelter Objekte entspricht. Das
        verwendete <acronym class="acronym">INI</acronym> Format bietet einerseits die Möglichkeit, Konfigurations
        Daten hierarchisch abzulegen und andererseits Vererbung zwischen Sektionen zu
        spezifizieren. Konfigurations-Daten-Hierarchien werden durch das Trennen der
        Schlüsselwörter durch einen Punkt (.). Eine Sektion kann eine andere
        Sektion erweitern oder beerben indem man nach dem Sektionsname einen Doppelpunkt
        (:) notiert, gefolgt vom Namen der zu beerbenden Sektion.

Note: Die Ini Datei parsen

            Zend_Config_Ini verwendet die <acronym class="acronym">PHP</acronym> Funktion
            »  parse_ini_file().
            Deren Dokumentation klärt über spezielle Verhaltensweisen auf, die sich auch auf
            Zend_Config_Ini auswirken, z. B. wie die besonderen Werte
            "<tt>TRUE</tt>", "<tt>FALSE</tt>", "yes", "no" und
            "<tt>NULL</tt>" gehandhabt werden.

Note: Schlüssel Trenner

            Standardmäßig ist das Schlüssel Trennzeichen der Punkt (.). Dies
            kann geändert werden, indem der <var class="varname">$options</var> Schlüssel
            nestSeparator geändert wird, wenn das
            Zend_Config_Ini Objekt instanziert wird.
            Zum Beispiel:

$options['nestSeparator'] = ':';

$config = new Zend_Config_Ini('/path/to/config.ini',

                              'staging',

                              $options);

Example #1 Zend_Config_Ini benutzen

            Dieses Beispiel zeigt die grundlegende Nutzung von
            Zend_Config_Ini um Konfigurations-Daten aus einer
            <acronym class="acronym">INI</acronym> Datei zu laden. In diesem Beispiel gibt es Konfigurations-Daten
            für ein Produktiv- und ein Staging-System. Da sich die Daten für das Staging-System nur
            unwesentlich von denen für das Produktiv-System unterscheiden, erbt das Staging-System
            vom Produktiv-System. In diesem Fall ist die Entscheidung darüber, welche Sektion von
            welcher erben soll, willkürlich und es könnte auch anders herum gemacht werden. In
            komplexeren Fällen ist das möglicherweise nicht der Fall. Nehmen wir also an, dass sich
            die folgenden Konfigurations-Daten in der Datei
            <var class="filename">/path/to/config.ini</var> befinden:

; Konfigurations-Daten für die Produktiv-Site

[production]

webhost                  = www.example.com

database.adapter         = pdo_mysql

database.params.host     = db.example.com

database.params.username = dbuser

database.params.password = secret

database.params.dbname   = dbname

; Konfigurations-Daten für die Staging-Site, erbt von der Produktion

; und überschreibt Werte, wo nötig

[staging : production]

database.params.host     = dev.example.com

database.params.username = devuser

database.params.password = devsecret

            Nehmen wir weiterhin an, dass der Anwendungs-Entwickler die Staging-Konfiguration aus
            dieser <acronym class="acronym">INI</acronym> Datei benötigt. Es ist ein Leichtes, diese Daten zu laden,
            es muss nur die <acronym class="acronym">INI</acronym> Datei und die Staging-Sektion spezifiziert
            werden:

$config = new Zend_Config_Ini('/path/to/config.ini', 'staging');

echo $config->database->params->host;   // Ausgabe "dev.example.com"

echo $config->database->params->dbname; // Ausgabe "dbname"

Note:

Zend_Config_Ini Kontruktor Parameter

                        Parameter
                        Notizen

                        <var class="varname">$filename</var>
                        Die <acronym class="acronym">INI</acronym> Datei die geladen wird.

                        <var class="varname">$section</var>

                            Die [section] innerhalb der <acronym class="acronym">INI</acronym> Datei die geladen
                            wird. Das Setzen dieses Parameters auf <tt>NULL</tt> lädt
                            alle Sektionen. Alternativ, kann ein Array von Sektionsnamen übergeben
                            werden um mehrere Sektionen zu laden.

                            <var class="varname">$options</var> (Default <tt>FALSE</tt>)

                            Options Array. Die folgenden Schlüssel werden unterstützt:

                                        allowModifications:
                                        Auf <tt>TRUE</tt> gesetzt erlaubt es
                                        weiterführende Modifikationen der geladenen
                                        Konfigurationsdaten im Speicher. Standardmäßig auf
                                        <tt>NULL</tt> gestellt

                                        nestSeparator: Auf
                                        das Zeichen zu setzen das als Abschnitts Separator verwendet
                                        wird. Standardmäßig auf "." gestellt

                    Theory of Operation

Zend_Config

                        Programmer's Reference Guide

Zend_Config_Json

Programmer's Reference Guide

Programmer's Reference Guide

Zend Framework Reference

Zend_Config

Einleitung

Theory of Operation

Zend_Config_Ini

Zend_Config_Json

Zend_Config_Xml

Zend_Config_Yaml


text:
<?xml version="1.0" encoding="UTF-8" ?>
<locale>
    <name>cs</name>
    <displayName>Czech</displayName>
    <datetime>
        <nativeCalendar>gregoriánský kalendář</nativeCalendar>
        <shortDatePattern>d.M.yyyy</shortDatePattern>
        <longDatePattern>d. MMMM yyyy</longDatePattern>
        <dateSeparator>.</dateSeparator>
        <shortTimePattern>H:mm</shortTimePattern>
        <longTimePattern>H:mm:ss</longTimePattern>
        <timeSeparator>:</timeSeparator>
        <dayNames>
            <fullName>
                <name>neděle</name>
                <name>pondělí</name>
                <name>úterý</name>
                <name>středa</name>
                <name>čtvrtek</name>
                <name>pátek</name>
                <name>sobota</name>
            </fullName>
            <shortName>
                <name>ne</name>
                <name>po</name>
                <name>út</name>
                <name>st</name>
                <name>čt</name>
                <name>pá</name>
                <name>so</name>
            </shortName>
        </dayNames>
        <monthNames>
            <fullName>
                <name>leden</name>
                <name>únor</name>
                <name>březen</name>
                <name>duben</name>
                <name>květen</name>
                <name>červen</name>
                <name>červenec</name>
                <name>srpen</name>
                <name>září</name>
                <name>říjen</name>
                <name>listopad</name>
                <name>prosinec</name>
            </fullName>
            <shortName>
                <name>1</name>
                <name>2</name>
                <name>3</name>
                <name>4</name>
                <name>5</name>
                <name>6</name>
                <name>7</name>
                <name>8</name>
                <name>9</name>
                <name>10</name>
                <name>11</name>
                <name>12</name>
            </shortName>
        </monthNames>
    </datetime>
    <numberFormat>
        <numberDecimalDigits>2</numberDecimalDigits>
        <numberDecimalSeparator>,</numberDecimalSeparator>
        <numberGroupSeparator> </numberGroupSeparator>
        <currencySymbol>Kč</currencySymbol>
        <currencyDecimalDigits>2</currencyDecimalDigits>
        <currencyDecimalSeparator>,</currencyDecimalSeparator>
        <currencyGroupSeparator> </currencyGroupSeparator>
        <currencyNegativePattern>8</currencyNegativePattern>
        <currencyPositivePattern>3</currencyPositivePattern>
    </numberFormat>
</locale>


text:
<?php

namespace RawPHP\LaravelOptions\Commands;

use Config;
use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;

class OptionsMigrationCommand extends Command
{
    /**
     * The command name.
     *
     * @var string
     */
    protected $name = 'options:migration';

    /**
     * Command description.
     *
     * @var string
     */
    protected $description = 'Creates a migration for the options table.';

    /**
     * Actions when the command is executed.
     */
    public function fire()
    {
        $this->laravel->view->addNamespace( 'laravel-options', substr( __DIR__, 0, -8 ) . 'views' );

        $optionsTable = lcfirst( $this->getNameByOptionOrConfig() );

        $this->line( '' );
        $this->info( 'Table: ' . $optionsTable );
        $message = 'A migration that creates ' . $optionsTable . ' table will be created in the app/database/migrations directory';

        $this->comment( $message );
        $this->line( '' );

        if ( $this->confirm( 'Proceed with the migration creation? [Yes|No]' ) ) {
            $this->line( '' );
            $this->info( 'Creating migration...' );

            if ( $this->createMigration( $optionsTable ) ) {
                $this->info( 'Migration successfully created!' );
            } else {
                $this->error( "Couldn't create migration.\nCheck the write permissions within the app/database/migrations directory." );
            }

            $this->line( '' );
        }

    }

    protected function getNameByOptionOrConfig()
    {
        if ( $name = $this->option( 'table' ) ) {
            return $name;
        }

        return Config::get( 'laravel-options::options_table_name' );
    }

    /**
     * Get the console command options.
     *
     * @return array
     */
    protected function getOptions()
    {
        return [
            [ 'table', NULL, InputOption::VALUE_OPTIONAL, 'Options table name.' ],
        ];
    }

    /**
     * Creates the migration for the options table.
     *
     * @param string $optionsTable
     *
     * @return bool
     */
    protected function createMigration( $optionsTable = 'options' )
    {
        $migrationFile = $this->laravel->path . '/database/migrations/' . date( 'Y_m_d_His' ) . '_Create_Options_Table.php';
        $output = $this->laravel->view->make( 'laravel-options::generators.migration' )->with( 'table', $optionsTable )->render();

        //dd( $output );

        if ( !file_exists( $migrationFile ) && $fs = fopen( $migrationFile, 'x' ) ) {
            fwrite( $fs, $output );
            fclose( $fs );

            return TRUE;
        }

        return FALSE;
    }
}


text:
<?php
include_once("conexion.php");
include_once("cabecera.php");
$menu = "pagos";
include_once("menu.php");
$men2 = "resumen";
include_once("pagos.php");
?>

<?php
echo '
';
	echo '
';
		echo '
CONFIRMAR BONOS UNILEVEL A PAGAR
';
	echo '
';

$quer0 = "DELETE FROM repunilevelindiv WHERE 1";
$resul0 = mysql_query($quer0,$link);

foreach ($_POST as $key => $value) {
	$query = "SELECT organizacion,org_nombres,comision FROM detunilevel where id=".trim($key)." and status_bono='Pendiente'";
	$result = mysql_query($query,$link);

	$row = mysql_fetch_array($result);
	$organizacion = $row['organizacion'];
	$org_nombres = $row['org_nombres'];
	$comision = $row['comision'];

	$quer2 = "INSERT INTO repunilevelindiv VALUES ('".$organizacion."','".$org_nombres."',".$comision.",".trim($key).");";
	$resul2 = mysql_query($quer2,$link);
}

$tot_general = 0.00;
echo '<form name="gestion" method="post" action="registrounilevelindividual.php">';

$query = "SELECT organizacion,org_nombres,sum(comision) as tot_comision  FROM repunilevelindiv group by organizacion order by organizacion";
$result = mysql_query($query,$link);
while($row = mysql_fetch_array($result)) {
	$organizacion = $row['organizacion'];
	$org_nombres = $row['org_nombres'];
	$tot_comision = $row['tot_comision'];

	$tot_general += $tot_comision;

	echo '

';
	echo '
'.$organizacion." ".trim($org_nombres).'
';

	echo '

';
	echo '
'.trim(number_format($tot_comision,2,',','.')).'

';

}

echo '
'.str_repeat('=', 20)."
";
echo '
TOTAL GENERAL: '.trim(number_format($tot_general,2,',','.'))."
";

echo '
';

echo '
';
	echo '<input type="submit" value="Confirmar">';
echo '
';

/*
$cadena = 'Location: ordenes.php';
header($cadena);
*/
?>


text:
using System.Collections.ObjectModel;

namespace NsqSharp.Bus.Configuration
{
    /// <summary>
    /// Topic and channel information for the current process.
    /// </summary>
    public interface ITopicChannels
    {
        /// <summary>
        /// The topic name.
        /// </summary>
        string Topic { get; }
        /// <summary>
        /// The topic channels handled by this process.
        /// </summary>
        Collection<string> Channels { get; }
    }

    /// <summary>
    /// Topic and channel information for the current process.
    /// </summary>
    internal class TopicChannels : ITopicChannels
    {
        /// <summary>
        /// The topic name.
        /// </summary>
        public string Topic { get; set; }
        /// <summary>
        /// The topic channels handled by this process.
        /// </summary>
        public Collection<string> Channels { get; set; }
    }
}


text:
/* global MongoObject:false = from aldeed:simple-schema */

/**
 * Figure out list of entities to extend from based on the inherit() function on each entity
 * definition.
 *
 * @param  {String} type    entity type
 * @param  {String} id      entity ID
 * @param  {Object} options arbitrary options to pass to inherit() function for context
 * @return {Array}          Array of arrays, like this: [["<entity>", "<id>"], ["<entity>", "<id>"]]
 */
Configuration._resolveInheritance = function(type, id, options) {
  var requestedTypeInheritFunction = Configuration._entityTypeInherits[type];
  var whatToInherit = requestedTypeInheritFunction ? requestedTypeInheritFunction(id, options) : 'default';
  var extendList = [];
  while (whatToInherit !== 'default') {
    // whatToInherit should be [entityType, entityId]
    // TODO should support ObjectId
    // Check doesn't support [String,String] so we assert the length afterwards
    check(whatToInherit, [String]);
    if (whatToInherit.length !== 2) {
      throw new Error('Inherit function must return an array of ["<type>", "<id>"]');
    }

    extendList.push(whatToInherit);

    // Next level
    requestedTypeInheritFunction = Configuration._entityTypeInherits[whatToInherit[0]];
    whatToInherit = requestedTypeInheritFunction ? requestedTypeInheritFunction(whatToInherit[1], options) :
      'default';
  }
  return extendList;
};

/**
 * Extend an entity given a list of configuration documents to extend from.
 *
 * This is used by both Configuration.getForEntity and Configuration.getForEntities (bulk)
 *
 * @param  {String} type       The type of entity
 * @param  {String} id         The entity ID
 * @param  {Array} extendList  Result of Configuration._resolveInheritance
 * @param  {Object} cache      If provided, is expected to be key/value pairs of id:document.
 *                             Used by getForEntities to avoid multiple unnecessary queries
 * @return {Object}            The resulting document
 */
Configuration._extendEntity = function(type, id, extendList, cache) {
  // Otherwise start with default or empty
  var configDoc = Configuration.Collection.findOne('_default') || {};

  // Then extend with inherited types in reverse order
  var extendId;
  var doc;
  for (var i = extendList.length - 1; i >= 0; i--) {
    doc = null;
    extendId = extendList[i][0] + '_' + extendList[i][1];
    if (cache) {
      doc = cache[extendId];
      if (!doc) {
        console.warn('Cache provided but key %s is not in the cache!', extendId);
      }

    }

    // Failsafe here to find it if it's not in the cache
    if (!doc) {
      doc = Configuration.Collection.findOne(extendId);
      // Add it to the cache so we can reuse it later, if we need it
      if (cache) {
        cache[extendId] = doc;
      }

    }

    _.deepExtend(configDoc, doc, true);

  }

  // And finally extend with the actual requested type
  var mainDoc;
  var mainId = type + '_' + id;
  if (cache) {
    mainDoc = cache[mainId];
  }
  if (!mainDoc) {
    mainDoc = Configuration.Collection.findOne(mainId);
  }
  _.deepExtend(configDoc, mainDoc, true);

  // Because of all the extending we've done, we could not use
  // bind: true in the findOne calls or various props would be
  // bound to various doc IDs. We want all props bound to the requested
  // ID regardless of where the values came from.
  //
  // Also, the `_id` at this point should be the requested type ID, but
  // if the requested type does not exist yet, it will be some other ID,
  // so we will set it here. This is why we use specific _id instead of
  // random.
  configDoc._id = mainId;

  return configDoc;
};

/**
 * Match up the array indices for the input and output of a bulk retrieval function. Results
 * will have the same index as their entity request. If there is no result for an entity request,
 * the array's element at that index will be an empty object
 *
 * @param  {Array} entities Array of entity objects with "type" and "id" properties
 * @param  {Array} results  Documents retrieved from Configuration.Collection
 * @return {Array}          Array with potential blank ({}) elements if the config was not found
 */
var matchBulkIndices = function(entities, results) {
  var fixedArray = [];

  var result;
  entities.forEach(function(entity) {
    result = _.findWhere(results, {
      _id: entity[0] + '_' + entity[1]
    });
    if (result) {
      fixedArray.push(result.config);
    } else {
      fixedArray.push({});
    }
  });

  return fixedArray;
};

/**
 * Retrieve the configuration for multiple entities, optimized to perform minimal database queries
 *
 * @param  {Array<Object>} entities Array of entity tuples consisting of ["<type>", "<id>"] elements
 * @param  {Options} options  The `inherit: false` option will give you just the pure entity
 *                            configuration object without inheriting. Any other options you
 *                            pass are passed to the type's `inherit` function to allow
 *                            context-specific inheritance logic.
 * @return {Array}            Array of resolved configuration objects. The indices are the same as the
 *                            provided entities array.
 */
Configuration.getForEntities = function(entities, options) {
  options = options || {};
  check(entities, [
    [String]
  ]);

  var ids = entities.map(function(entity) {
    return entity[0] + '_' + entity[1];
  });

  // If inherit is explicitly false, we only want the actual configs for these entities.
  if (options.inherit === false) {
    return matchBulkIndices(entities, Configuration.Collection.find({
      _id: {
        $in: ids
      }
    }).fetch());
  }

  // Get a unique list of configuration docs to find based on the resolved inheritance trees for each
  // of the provided entities
  var inheritanceTrees = [];
  var docsToFindById = [];
  entities.forEach(function(entity) {
    var extendList = Configuration._resolveInheritance(entity[0], entity[1], options);
    inheritanceTrees.push(extendList);
    // We want to find this one, in addition to all the things it needs to inherit from.
    docsToFindById.push(entity[0] + '_' + entity[1]);
    extendList.forEach(function(extend) {
      docsToFindById.push(extend[0] + '_' + extend[1]);
    });
  });

  // Find all the inherited docs and store them by ID in a map to pass to _extendEntity as the cache
  var documentCache = {};
  Configuration.Collection.find({
    _id: {
      $in: docsToFindById
    }
  }).forEach(function(doc) {
    documentCache[doc._id] = doc;
  });

  // If they don't exist, still put them in a cache as an empty object so we don't do unnecessary finds
  docsToFindById.forEach(function(docId) {
    if (!documentCache[docId]) {
      documentCache[docId] = {};
    }
  });

  // Now we can do the same stuff as the Configuration.getForEntity. Index
  // of entities will be the same as index in inheritanceTrees, so we'll use
  // that value in the call to Configuration._extendEntity
  var results = [];
  entities.forEach(function(entity, index) {
    results.push(Configuration._extendEntity(entity[0], entity[1], inheritanceTrees[index], documentCache).config);
  });

  // The above already did the same thing as matchBulkIndices, so no need to run that here.
  return results;
};

Configuration.getForEntity = function(type, id, options, fullDoc) {
 options = options || {};

  // If inherit is explicitly false, we only want the actual config for this entity.
  var configDoc;
  if (options.inherit === false) {
    configDoc = Configuration.Collection.findOne(type + '_' + id);
  } else {
    var extendList = Configuration._resolveInheritance(type, id, _.omit(options, 'inherit'));
    configDoc = Configuration._extendEntity(type, id, extendList, null);
  }

  return fullDoc ? configDoc : (configDoc ? configDoc.config : {});
};

/**
 * Sets the full configuration document for an entity.
 *
 * This function has two valid signatures:
 * 1) Configuration.setForEntity(type, id, props)
 * 2) Configuration.setForEntity(type, id, props, overwrite)
 *
 *
 * @param {String} type         Entity type
 * @param {String} id           Entity _id
 * @param {Object} props        Config properties, or entire doc if overwrite is true.
 *                              Must be valid according to your schema.
 * @param {Boolean} overwrite   Whether to override all existing config with provided props,
 *                              or to just update the provided props. Applies only when there is an
 *                              existing document
 */
Configuration.setForEntity = function(type, id, props, overwrite) {
  // Are we overwriting? Or just updating individual props?
  var modifier = {};

  if (overwrite) {
    modifier.$set = {
      config: props
    };
  } else {

    // Idea here is we want to unset anything set to `null` so it will be inherited
    var mongoObj = new MongoObject({
      config:props
    });

    var flat = mongoObj.getFlatObject({
      keepArrays:true
    });

    var nulls = reportNulls(flat, true);

    var nullKeys = _.keys(nulls);
    flat = _.omit(flat, nullKeys);
    modifier.$set = flat;

    if(nullKeys.length) {
      modifier.$unset = nulls;
    }
  }

  modifier.$set.entityType = type;
  modifier.$set.entityId = id;

  const _id = type + '_' + id;
  const result = Configuration.Collection.update({
    _id,
  }, modifier, {
    upsert: true,
    filter: false
  });

  Configuration.emit('afterUpdate', {
    userId: getUserId(),
    _id,
    modifier,
    result,
  });

  return result;
};

Configuration._setDefault = function (set) {
  const modifier = {
    $set: set,
  };

  const result = Configuration.Collection.update({
    _id: '_default',
    entityType: '_default',
    entityId: '_default',
  }, modifier, {
    upsert: true,
    filter: false,
  });

  Configuration.emit('afterUpdate', {
    userId: getUserId(),
    _id: '_default',
    modifier,
    result,
  });

  return result;
};

/**
 * Sets the default configuration document.
 *
 * Note that this is not an upsert because we want to be able to run it on the client
 * as well, so we need to check if it exists already. A tiny optimization could be to
 * run an upsert only on server.
 *
 * @param {Object} doc Config doc. Must be valid according to your schema.
 */
Configuration.setDefault = function (doc) {
  return Configuration._setDefault({
    config: doc,
  });
};

/**
 * Set the configuration defaults for a particular prefix. Useful for packages
 * that register their own unique configuration
 * @param {String}   prefix   The prefix
 * @param {Object}   data     The default data
 */
Configuration.setDefaultForPrefix = function (prefix, data) {
  var set = {};
  set['config.' + prefix] = data;

  return Configuration._setDefault(set);
};

// Get userId only if the function exists (account-base pkg is used) and ignore errors
function getUserId() {
  let userId;
  try {
    userId = typeof Meteor.userId === 'function' ? Meteor.userId() : null;
  } catch (error) {}
  return userId;
}

/** BELOW CODE IS TAKEN FROM ALDEED:AUTOFORM UNTIL HE PUBLISHES THE MONGO OBJECT BY ITSELF */

/* Tests whether "obj" is an Object as opposed to
 * something that inherits from Object
 *
 * @param {any} obj
 * @returns {Boolean}
 */
var isBasicObject = function(obj) {
  return _.isObject(obj) && Object.getPrototypeOf(obj) === Object.prototype;
};

/**
 * @private
 * @param {Object} doc - Source object
 * @returns {Object}
 *
 * Returns an object in which all properties with null, undefined, or empty
 * string values have been removed, recursively.
 */
function cleanNulls(doc, isArray, keepEmptyStrings) {
  var newDoc = isArray ? [] : {};
  _.each(doc, function(val, key) {
    if (!_.isArray(val) && isBasicObject(val)) {
      val = cleanNulls(val, false, keepEmptyStrings); //recurse into plain objects
      if (!_.isEmpty(val)) {
        newDoc[key] = val;
      }
    } else if (_.isArray(val)) {
      val = cleanNulls(val, true, keepEmptyStrings); //recurse into non-typed arrays
      if (!_.isEmpty(val)) {
        newDoc[key] = val;
      }
    } else if (!isNullUndefinedOrEmptyString(val)) {
      newDoc[key] = val;
    } else if (keepEmptyStrings && typeof val === "string" && val.length === 0) {
      newDoc[key] = val;
    }
  });
  return newDoc;
}

/**
 * @param {Object} flatDoc - An object with no properties that are also objects.
 * @returns {Object} An object in which the keys represent the keys in the
 * original object that were null, undefined, or empty strings, and the value
 * of each key is "".
 */
function reportNulls(flatDoc, keepEmptyStrings) {
  var nulls = {};
  // Loop through the flat doc
  _.each(flatDoc, function(val, key) {
    // If value is undefined, null, or an empty string, report this as null so it will be unset
    if (val === null) {
      nulls[key] = "";
    } else if (val === void 0) {
      nulls[key] = "";
    } else if (!keepEmptyStrings && typeof val === "string" && val.length === 0) {
      nulls[key] = "";
    }
    // If value is an array in which all the values recursively are undefined, null, or an empty string,
    // report this as null so it will be unset
    else if (_.isArray(val) && cleanNulls(val, true, keepEmptyStrings).length === 0) {
      nulls[key] = "";
    }
  });
  return nulls;
}

/**
 * @param  {Any} val
 * @return {Boolean}
 *
 * Returns `true` if the value is null, undefined, or an empty string
 */
function isNullUndefinedOrEmptyString(val) {
  return (val === void 0 || val === null || (typeof val === "string" && val.length === 0));
}