text:
/* Meet & Eat
 * Tirza Soute (10761977)
 * Programmeerproject
 *
 * This class handles the database actions. This includes reading the database, writing new dinners
 * to the database, retrieving specific data from the database (such as dinners hosted by the
 * current user or dinners joined by the current user), deleting dinners from the database, updating
 * dates, titles and ingredients of dinners, updating the amount of free spaces for dinners and
 * saving users to the database when they create an account. The database is a Firebase database.
 */

package nl.mprog.meeteat;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.net.Uri;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;

class DatabaseHandler {

    /** Writes a new dinner to the database. */
    void writeToDatabase(Dinner dinner) {
        DatabaseReference database = FirebaseDatabase.getInstance().getReference();
        database.child("dinners").push().setValue(dinner);
    }

    /** Reads the database based on the user's input area. */
    void readDatabase(String area, final ArrayList<Dinner> dinners, final DinnerAdapter adapter,
                      final DinnerResultFragment fragment, final View view) {
        DatabaseReference database = FirebaseDatabase.getInstance().getReference();
        Query areaQuery = database.child("dinners").orderByChild("area").equalTo(area);

        areaQuery.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                replaceTextInView(dataSnapshot.getChildrenCount(), view);

                for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
                    Dinner dinner = snapshot.getValue(Dinner.class);
                    dinners.add(dinner);
                    adapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                Toast.makeText(fragment.getActivity(), R.string.dbReadFail, Toast.LENGTH_SHORT)
                        .show();
            }
        });
    }

    /** Replaces the loading text with no results if necessary. */
    private void replaceTextInView(long amountResults, View view) {
        TextView loadingText = (TextView) view.findViewById(R.id.loading);

        if (amountResults != 0) {
            loadingText.setVisibility(View.INVISIBLE);
        } else {
            loadingText.setText(R.string.noResults);
        }
    }

    /**
     * The push key of the dinner is retrieved and the list of guests is updated if the user who
     * wants to join the dinner is not the host of the dinner.
     */
    void updateFreeSpaces(final Context context, final Dinner dinner, final int position,
                          final DinnerAdapter adapter, final ArrayList<Dinner> dinners,
                          final int amountJoining) {
        String dinnerId = dinner.getId();
        final DatabaseReference database = FirebaseDatabase.getInstance().getReference();
        Query findKey = database.child("dinners").orderByChild("id").equalTo(dinnerId);

        findKey.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
                    String databaseKey = snapshot.getKey();
                    ArrayList<String> userInfo = getUserInfo(context);

                    if (!userInfo.get(0).equals(dinner.getHostId())) {
                        updateFirebaseGuests(userInfo, databaseKey, position, adapter, dinners,
                                context, amountJoining);
                    } else {
                        Toast.makeText(context, R.string.notJoinOwnDinner, Toast.LENGTH_SHORT)
                                .show();
                    }
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                Toast.makeText(context, R.string.failedJoin, Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * Retrieves the user's ID and name.
     */
    private ArrayList<String> getUserInfo(Context context) {
        SharedPreferences sharedPrefs = context.getSharedPreferences("userInfo",
                Context.MODE_PRIVATE);
        String username = sharedPrefs.getString("username", "");
        String userId = sharedPrefs.getString("userId", "");
        return new ArrayList<>(Arrays.asList(userId, username));
    }

    /**
     * Searches for the first "null" occurrence in the guests array and replaces this with the
     * guest's name. After that, the Dinner entry in the database is updated.
     */
    private void updateFirebaseGuests(ArrayList<String> userInfo, String databaseKey, int position,
                                      DinnerAdapter adapter, ArrayList<Dinner> dinners,
                                      Context context, int amountJoining) {
        Dinner dinner = dinners.get(position);
        ArrayList<String> guestNames = dinner.getGuestNames();
        ArrayList<String> guestIds = dinner.getGuestIds();

        guestIds = updateGuestList(userInfo.get(0), guestIds, amountJoining);
        guestNames = updateGuestList(userInfo.get(1), guestNames, amountJoining);

        dinner.setGuestIds(guestIds);
        dinner.setGuestNames(guestNames);
        dinners.set(position, dinner);
        adapter.notifyDataSetChanged();

        DatabaseReference database = FirebaseDatabase.getInstance().getReference();
        database.child("dinners").child(databaseKey).setValue(dinner);
        getHostEmail(userInfo.get(1), dinner, context);

        Toast.makeText(context, R.string.successJoin, Toast.LENGTH_SHORT).show();
    }

    /**
     * Updates the first occurrence of "null" in an array with the new guest name or ID for the
     * amount of people that the user specified they want to join the dinner with.
     */
    private ArrayList<String> updateGuestList(String newGuest, ArrayList<String> guestList,
                                              int amountJoining) {

        for (int i = 0; i < amountJoining; i++) {
            int firstFreeSpace = guestList.indexOf("null");
            guestList.set(firstFreeSpace, newGuest);
        }
        return guestList;
    }

    /** Finds the e-mail address of the host of the dinner and sends them an e-mail if someone
     * has joined their dinner. */
    private void getHostEmail(final String username, final Dinner dinner, final Context context) {
        DatabaseReference database = FirebaseDatabase.getInstance().getReference().child("users")
                .child(dinner.getHostId());

        database.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                User host = dataSnapshot.getValue(User.class);
                String hostMail = host.getEmail();
                String email = joinEmail(username, dinner, context);
                sendEmail(email, hostMail, context.getResources().getString(R.string.notifyHost),
                        context.getResources().getString(R.string.successJoin), context);
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                Toast.makeText(context, R.string.failHostEmail, Toast.LENGTH_SHORT).show();
            }
        });
    }

    /** Sends an e-mail to the host of the dinner that will be joined to ask for details. */
    private void sendEmail(String body, String recipientEmail, String title, String subject,
                           Context context) {
        Intent mailIntent = new Intent(Intent.ACTION_SENDTO);
        mailIntent.setType("message/rfc822");
        mailIntent.setData(Uri.parse("mailto:"));
        mailIntent.putExtra(Intent.EXTRA_EMAIL, new String[]{recipientEmail});
        mailIntent.putExtra(Intent.EXTRA_SUBJECT, subject);
        mailIntent.putExtra(Intent.EXTRA_TEXT, body);

        try {
            context.startActivity(Intent.createChooser(mailIntent, title));
        } catch (android.content.ActivityNotFoundException e){
            Toast.makeText(context, R.string.noEmailClients, Toast.LENGTH_SHORT).show();
        }
    }

    /** Returns the predefined e-mail string to join a dinner.  */
    private String joinEmail(String username, Dinner dinner, Context context) {
        Resources resources = context.getResources();

        return String.format(resources.getString(R.string.joinEmail), dinner.getTitle(),
                dinner.getDate(), username);
    }

    /** Retrieves the dinners that the user is hosting from Firebase. */
    void getHostingDinners(final SavedAdapter adapter, final ArrayList<Dinner> dinners,
                           final Activity activity, final View view) {
        FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();

        if (user != null) {
            final String userId = user.getUid();
            DatabaseReference database = FirebaseDatabase.getInstance().getReference();
            Query findHosting = database.child("dinners").orderByChild("hostId").equalTo(userId);

            findHosting.addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    replaceTextInView(dataSnapshot.getChildrenCount(), view);

                    for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                        Dinner dinner = snapshot.getValue(Dinner.class);
                        dinners.add(dinner);
                        adapter.notifyDataSetChanged();
                    }
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {
                    Toast.makeText(activity, R.string.failedRetrieveDinners, Toast.LENGTH_SHORT)
                            .show();
                }
            });
        }
    }

    /** Retrieves the dinners that the user has joined from Firebase. */
    void getJoinedDinners(final SavedAdapter adapter, final ArrayList<Dinner> dinners,
                          final Activity activity, final View view) {
        final FirebaseUser user  = FirebaseAuth.getInstance().getCurrentUser();

        if (user != null) {
            final String userId = user.getUid();
            DatabaseReference database = FirebaseDatabase.getInstance().getReference();
            Query findJoined = database.child("dinners").orderByChild("guestIds");

            findJoined.addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
                        Dinner dinner = snapshot.getValue(Dinner.class);
                        ArrayList<String> guestIds = dinner.getGuestIds();

                        if (guestIds.contains(userId)) {
                            dinners.add(dinner);
                            adapter.notifyDataSetChanged();
                        }
                        replaceTextInView(dinners.size(), view);
                    }
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {
                    Toast.makeText(activity, R.string.failedRetrieveDinners, Toast.LENGTH_SHORT)
                            .show();
                }
            });
        }
    }

    /** Saves a user in Firebase under his user ID. */
    void saveUser(User user, Context context) {
        final DatabaseReference database = FirebaseDatabase.getInstance().getReference();
        database.child("users").child(user.getUserId()).setValue(user);

        SharedPreferences.Editor editor = context.getSharedPreferences("userInfo",
                Context.MODE_PRIVATE).edit();
        editor.putString("userId", user.getUserId());
        editor.putString("username", user.getUsername());
        editor.putString("userEmail", user.getEmail()).apply();
    }

    /** Saves the user's name and ID in SharedPreferences. */
    void getUsername(final String userId, final Context context) {
        DatabaseReference database = FirebaseDatabase.getInstance().getReference();
        Query findName = database.child("users").orderByChild("userId").equalTo(userId);

        findName.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                    User user = snapshot.getValue(User.class);
                    String username = user.getUsername();

                    SharedPreferences.Editor editor = context.getSharedPreferences("userInfo",
                            Context.MODE_PRIVATE).edit();
                    editor.putString("username", username);
                    editor.putString("userId", userId).apply();
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                Toast.makeText(context, R.string.failedSaveName, Toast.LENGTH_SHORT).show();
            }
        });
    }

    /** Updates a dinner in the database. */
    void updateDinner(final Dinner dinner, final Activity activity) {
        final DatabaseReference database = FirebaseDatabase.getInstance().getReference();
        Query updateDinner = database.child("dinners").orderByChild("id").equalTo(dinner.getId());

        updateDinner.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
                    String databaseKey = snapshot.getKey();
                    database.child("dinners").child(databaseKey).setValue(dinner);
                    Toast.makeText(activity, R.string.successUpdate, Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                Toast.makeText(activity, R.string.failUpdate, Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * Finds a dinner in the database according to its ID and removes the current user from the
     * list of guests.
     */
    void removeGuest(final Dinner dinner, final Activity activity, final ArrayList<Dinner> dinners,
                    final SavedAdapter adapter, final int position) {
        final DatabaseReference database = FirebaseDatabase.getInstance().getReference();
        Query findDinner = database.child("dinners").orderByChild("id").equalTo(dinner.getId());

        findDinner.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
                    String databaseKey = snapshot.getKey();
                    removeUser(databaseKey, dinners, adapter, position, activity);
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                Toast.makeText(activity, R.string.failFind, Toast.LENGTH_SHORT).show();
            }
        });
    }

    /** Removes the current user from a dinner in the database. */
    private void removeUser(String key, ArrayList<Dinner> dinners, SavedAdapter adapter,
                            int position, Activity activity) {
        FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();

        if (user != null) {
            DatabaseReference database = FirebaseDatabase.getInstance().getReference();
            Dinner dinner = dinners.get(position);

            ArrayList<String> guestIds = dinner.getGuestIds();
            String userId = user.getUid();
            int lastOccurrence = guestIds.lastIndexOf(userId);

            if (lastOccurrence != -1) {
                dinner = removeFromDinner(dinner, lastOccurrence);
                adapter.notifyDataSetChanged();
                adapter.setData(dinners);

                database.child("dinners").child(key).setValue(dinner);
                String email = unjoinEmail(dinner, activity);
                Resources resources = activity.getResources();

                sendEmail(email, dinner.getHostEmail(), resources.getString(R.string.notifyHost),
                        resources.getString(R.string.removeGuest), activity);
            } else {
                Toast.makeText(activity, R.string.removedAlready, Toast.LENGTH_SHORT).show();
            }
        }
    }

    /** Removes the user's name and ID from the guest list. */
    private Dinner removeFromDinner(Dinner dinner, int lastOccurrence) {
        ArrayList<String> guestIds = dinner.getGuestIds();
        ArrayList<String> guestNames = dinner.getGuestNames();

        guestIds.set(lastOccurrence, "null");
        guestNames.set(lastOccurrence, "null");
        return dinner;
    }

    /** Body of an email when a user is no longer joining a dinner. */
    private String unjoinEmail(Dinner dinner, Activity activity) {
        Resources resources = activity.getResources();
        String name = activity.getSharedPreferences("userInfo", Context.MODE_PRIVATE)
                .getString("username", "");

        return String.format(resources.getString(R.string.unjoinEmail), dinner.getTitle(),
                dinner.getDate(), name);
    }

    /** Removes a dinner from the database. */
    void deleteDinner(final Dinner dinner, final Activity activity, final SavedAdapter adapter,
                              final ArrayList<Dinner> dinners) {
        final DatabaseReference database = FirebaseDatabase.getInstance().getReference();
        Query findDinner = database.child("dinners").orderByChild("id").equalTo(dinner.getId());

        findDinner.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
                    String databaseKey = snapshot.getKey();
                    emailGuests(dinner, activity);
                    database.child("dinners").child(databaseKey).removeValue();
                    dinners.remove(dinner);
                    adapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                Toast.makeText(activity, R.string.failDelete, Toast.LENGTH_SHORT).show();
            }
        });
    }

    /** Notifies the guests of that the host has cancelled their dinner. */
    private void emailGuests(Dinner dinner, Activity activity) {
        HashSet<String> uniqueGuests = new HashSet<>(dinner.getGuestIds());
        uniqueGuests.remove("null");
        ArrayList<String> uniqueArray = new ArrayList<>(uniqueGuests);

        for (int i = 0; i < uniqueArray.size(); i++) {
            String guestId = uniqueArray.get(i);
            findGuestEmail(guestId, dinner, activity);
        }
    }

    /** Finds the email of a user given their ID and sends them an e-mail. */
    private void findGuestEmail(String userId, final Dinner dinner, final Activity activity) {
        DatabaseReference database = FirebaseDatabase.getInstance().getReference().child("users")
                .child(userId);

        database.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                User user = dataSnapshot.getValue(User.class);
                String email = user.getEmail();
                String body = cancelMail(dinner, activity);

                Resources resources = activity.getResources();
                sendEmail(body, email, resources.getString(R.string.notifyGuest),
                        resources.getString(R.string.cancelDinner), activity);
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                Toast.makeText(activity, R.string.failFindEmailGuest, Toast.LENGTH_SHORT).show();
            }
        });
    }

    /** Body of an email when the host cancels the dinner. */
    private String cancelMail(Dinner dinner, Activity activity) {
        Resources resources = activity.getResources();
        String name = activity.getSharedPreferences("userInfo", Context.MODE_PRIVATE)
                .getString("username", "");

        return String.format(resources.getString(R.string.cancelEmail), dinner.getTitle(),
                dinner.getDate(), name);
    }
}


text:
import React from 'react';
import { render, screen } from '@testing-library/react';
import { DataLinksContextMenu } from './DataLinksContextMenu';
import { selectors } from '@grafana/e2e-selectors';

const fakeAriaLabel = 'fake aria label';
describe('DataLinksContextMenu', () => {
  it('renders context menu when there are more than one data links', () => {
    render(
      <DataLinksContextMenu
        links={() => [
          {
            href: '/link1',
            title: 'Link1',
            target: '_blank',
            origin: {},
          },
          {
            href: '/link2',
            title: 'Link2',
            target: '_blank',
            origin: {},
          },
        ]}
        config={{
          links: [
            {
              title: 'Link1',
              url: '/link1',
            },
            {
              title: 'Link2',
              url: '/link2',
            },
          ],
        }}
      >
        {() => {
          return
;
        }}
      </DataLinksContextMenu>
    );

    expect(screen.getByLabelText(fakeAriaLabel)).toBeInTheDocument();
    expect(screen.queryAllByLabelText(selectors.components.DataLinksContextMenu.singleLink)).toHaveLength(0);
  });

  it('renders link when there is a single data link', () => {
    render(
      <DataLinksContextMenu
        links={() => [
          {
            href: '/link1',
            title: 'Link1',
            target: '_blank',
            origin: {},
          },
        ]}
        config={{
          links: [
            {
              title: 'Link1',
              url: '/link1',
            },
          ],
        }}
      >
        {() => {
          return
;
        }}
      </DataLinksContextMenu>
    );

    expect(screen.getByLabelText(fakeAriaLabel)).toBeInTheDocument();
    expect(screen.getByLabelText(selectors.components.DataLinksContextMenu.singleLink)).toBeInTheDocument();
  });
});

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.IO;
using Microsoft.Extensions.DependencyInjection;
using Xunit;

namespace FluentRest.Fake.Tests
{
    public class FileMessageStoreTests
    {
        public IServiceProvider ServiceProvider { get; }

        public FileMessageStoreTests()
        {
            var storePath = Path.Combine(AppContext.BaseDirectory, "Data");
            if (!Directory.Exists(storePath))
                Directory.CreateDirectory(storePath);

            var services = new ServiceCollection();

            services.AddSingleton<IContentSerializer, JsonContentSerializer>();
            services.AddSingleton<IFakeMessageStore>(s => new FileMessageStore(storePath));

            services
                .AddHttpClient<EchoClient>(c => c.BaseAddress = new Uri("http://httpbin.org/"))
                .AddHttpMessageHandler(s => new FakeMessageHandler(s.GetService<IFakeMessageStore>(), FakeResponseMode.Fake));

            ServiceProvider = services.BuildServiceProvider();
        }

        [Fact]
        public async void Register()
        {
            var client = ServiceProvider.GetService<EchoClient>();

            var result = await client.PostAsync<EchoResult>(b => b
                .AppendPath("post")
                .FormValue("Test", "Fake")
                .FormValue("key", "value")
                .QueryString("page", 10)
            ).ConfigureAwait(false);

            Assert.NotNull(result);
            Assert.Equal("http://httpbin.org/post?page=10", result.Url);
            Assert.Equal("Fake", result.Form["Test"]);
            Assert.Equal("value", result.Form["key"]);
        }

    }
}


text:
module Lyft
  class Client
    module Api
      VERSION = ENV['LYFT_API_VERSION'] || 'v1'
      BASE_URL = 'https://api.lyft.com'
    end
  end
end


text:
'use babel';

module.exports = {
  addInfo: val => atom.notifications.addInfo(val),
  addError: val => atom.notifications.addError(val),
  addSuccess: val => atom.notifications.addSuccess(val)
};


text:
package ru.barashko.simplerefalplugin.psi;

import java.util.List;
import org.jetbrains.annotations.*;
import com.intellij.psi.PsiElement;

public interface SimpleRefalNameList extends PsiElement {

}


text:
#region Copyright

#endregion

#region

using Autodesk.DesignScript.Runtime;
using Dynamo.Models;
using System.Collections.Generic;
using Dynamo.Nodes;
using Kodestruct.Steel.AISC.AISC360v10.Composite;
using Analysis.Section;
using Kodestruct.Common.Section.Interfaces;
using System;

#endregion

namespace Steel.AISC.Composite
{

/// <summary>
///     Positive moment flexural strength
///     Category:   Kodestruct.Steel.AISC_10.Composite
/// </summary>
///

    public partial class Flexure
    {
        /// <summary>
        ///    Calculates Positive moment flexural strength for composite beam (kip - in unit system for all inputs and outputs)
        /// </summary>
        /// <param name="Shape">  Steel shape instance (must be of CompositeSteelShape type) </param>
        /// <param name="b_eff">  Effective width of concrete slab in composite beam design </param>
        /// <param name="h_solid">  Depth of solid portion of concrete slab on metal deck (fill above deck) </param>
        /// <param name="h_rib">  Depth of ribs for corrugated metal deck </param>
        /// <param name="F_y">  Specified minimum yield stress </param>
        /// <param name="fc_prime">  Specified compressive strength of concrete   </param>
        /// <param name="SumQ_n">  Sum of the nominal strengths of steel anchors between the point of maximum positive moment and the point of zero moment to either side </param>
        /// <param name="Code"> Applicable version of code/standard</param>
        /// <returns name="phiM_n"> Moment strength </returns>

        [MultiReturn(new[] { "phiM_n" })]
        public static Dictionary<string, object> PositiveMomentFlexuralStrength(CustomProfile Shape, double b_eff, double h_solid, double h_rib, double F_y, double fc_prime,
            double SumQ_n, string Code = "AISC360-10")
        {
            //Default values
            double phiM_n = 0;

            //Calculation logic:
            if (Shape.Section is ISliceableShapeProvider)
            {
                ISliceableShapeProvider prov = Shape.Section as ISliceableShapeProvider;
                ISliceableSection sec = prov.GetSliceableShape();
                CompositeBeamSection cs = new CompositeBeamSection(sec, b_eff, h_solid, h_rib, F_y, fc_prime);
                phiM_n = cs.GetFlexuralStrength(SumQ_n);
            }
            else
            {
                if (Shape.Section is ISliceableSection)
                {
                    ISliceableSection sec = Shape.Section as ISliceableSection;
                    CompositeBeamSection cs = new CompositeBeamSection(sec, b_eff, h_solid, h_rib, F_y, fc_prime);
                    phiM_n = cs.GetFlexuralStrength(SumQ_n);
                }
                else
                {
                    throw new Exception("Shape type not supported. Please provide a shape object of standard geometry");
                }

            }

            return new Dictionary<string, object>
            {
                { "phiM_n", phiM_n }

            };
        }

    }
}


text:
<?php

/**
 *
 * @author Hudhaifa Shatnawi <hudhaifa.shatnawi@gmail.com>
 * @version 1.0, Jan 21, 2017 - 4:07:38 PM
 */
class FiguresPage
        extends DataObjectPage {

    public function canCreate($member = false) {
        if (!$member || !(is_a($member, 'Member')) || is_numeric($member)) {
            $member = Member::currentUserID();
        }

        return (DataObject::get($this->owner->class)->count() > 0) ? false : true;
    }

}

class FiguresPage_Controller
        extends DataObjectPage_Controller {

    private static $allowed_actions = array(
        'edit',
        'show',
        'Form_EditPerson',
        'doEditPerson',
        'Form_EditSettings',
        'doEditSettings',
        'Form_AddFather',
        'doAddFather',
        'Form_ChangeFather',
        'doChangeFather',
        'Form_ChangeMother',
        'doChangeMother',
        'Form_AddSons',
        'doAddSons',
        'Form_AddDaughters',
        'doAddDaughters',
        'Form_SingleWife',
        'doSingleWife',
        'Form_AddSpouse',
        'doAddSpouse',
        'Form_DeletePerson',
        'doDeletePerson',
        'Form_IndexPerson',
        'doIndexPersonStatistics',
        'doIndexPersonDates',
        'doIndexPersonEvents',
    );
    private static $url_handlers = array(
        'edit/$ID/$form' => 'edit',
        'show/$ID' => 'show',
    );

    public function init() {
        parent::init();

        Requirements::css("genealogist/css/vendors/jquery.modal.css");
        Requirements::css("genealogist/css/profile.css");

        if ($this->isRTL()) {
            Requirements::css("genealogist/css/profile-rtl.css");
        }

        Requirements::css(THIRDPARTY_DIR . '/jquery-ui-themes/smoothness/jquery-ui.css');
        Requirements::javascript(THIRDPARTY_DIR . '/jquery-ui/jquery-ui.js');

        Requirements::javascript("genealogist/js/vendors/jquery.modal.js");
        Requirements::javascript("genealogist/js/genealogy.ajax.js");
        Requirements::javascript("genealogist/js/genealogy.forms.js");
        Requirements::customScript(<<<JS
            jQuery(document).ready(function () {
                rebindAjaxmodal();
            });
JS
        );
    }

    protected function getObjectsList() {
        if ($this->isAdmin()) {
            return DataObject::get('Gender')
                            ->sort('RAND()');
        } else {
            return DataObject::get('Gender')
                            ->filterAny(array(
                                'ClassName' => 'Branch',
                                'CanViewType' => 'Anyone',
                            ))->sort('IndexedName ASC');
        }
    }

    protected function getPageLength() {
        return 24;
    }

    protected function searchObjects($list, $keywords) {
        $pieces = GenealogistSearchHelper::explode_keywords($keywords);

        return GenealogistSearchHelper::search_objects($list, $pieces['NameSeries'], $pieces['BranchID']);
    }

    /**
     * Checks if the user is an authorized member
     * @return boolean true if the user is an authorized member
     */
    public function isAdmin() {
        return GenealogistHelper::is_genealogists();
    }

    private $formTemplates = array(
        'self' => 'Person_Edit_Self',
        'settings' => 'Person_Edit_Settings',
        'parents' => 'Person_Edit_Parents',
        'children' => 'Person_Edit_Children',
        'spouses' => 'Person_Edit_Spouses',
        'index' => 'Person_Index',
        'delete' => 'Person_Delete'
    );

    /// Actions ///
    public function edit() {
        $id = $this->getRequest()->param('ID');
        $form = $this->getRequest()->param('form');

        if ($id) {
            $person = DataObject::get_by_id('Gender', (int) $id);
        } else {
            $person = $this->getBranches()->first();
        }

        if (!$person || !$person->canEdit()) {
            return $this->httpError(404, 'That person could not be found!');
        }

        if ($person) {
            switch ($form) {
                case 'self':
                case 'settings':
                case 'parents':
                case 'children':
                case 'spouses':
                case 'index':
                case 'delete':
                    $renderer = array($this->formTemplates[$form]);
                    break;

                default:
                    $renderer = $this->getRequest()->isAjax() ?
                            array('Person_Edit') :
                            array('FiguresPage_Edit', 'Page');
                    break;
            }

            return $this
                            ->customise(array(
                                'Gender' => $person,
                                'Title' => $person->Name
                            ))
                            ->renderWith($renderer);
        } else {
            return $this->httpError(404, 'That person could not be found!');
        }
    }

    public function show() {
        $id = $this->getRequest()->param('ID');
        $single = DataObject::get('Gender')->filter(array(
                    'ID' => $id
                ))->first();

        if (!$single || !$single->canView()) {
            return $this->httpError(404, 'That person could not be found!');
        }

        $align = $this->isRTL() == 'rtl' ? 'right' : 'left';

        Requirements::customScript(<<<JS
            $(document).ready(function () {
                $('.imgBox').imgZoom({
                    boxWidth: 500,
                    boxHeight: 500,
                    marginLeft: 5,
                    align: '{$align}',
                    origin: 'data-origin'
                });
            });
JS
        );

        if ($single) {
            return $this
                            ->customise(array(
                                'Gender' => $single,
                                'Title' => $single->Title
                            ))
                            ->renderWith(array('FiguresPage_Profile', 'FiguresPage'));
        } else {
            return $this->httpError(404, 'That object could not be found!');
        }
    }

    /// Forms ///
    public function Form_EditPerson($personID) {
        if ($personID instanceof SS_HTTPRequest) {
            $id = $personID->postVar('PersonID');
        } else {
            $id = $personID;
        }

        $person = DataObject::get_by_id('Gender', (int) $id);
        $towns = DataObject::get('Town')->map();

        $items = array(
            HiddenField::create('PersonID', 'PersonID', $id), //
            TextField::create('Name', _t('Genealogist.NAME', 'Name'), $person->Name), //
            TextField::create('NickName', _t('Genealogist.NICKNAME', 'NickName'), $person->NickName), //
            TextField::create('Note', _t('Genealogist.NOTE', 'Note'), $person->Note), //
        );

        if (!$person->isClan()) {
            // Birth
            $items[] = TextField::create('BirthDate', _t('Genealogist.BIRTHDATE', 'Birth Date'), $person->BirthDate);
            $items[] = DropdownField::create(
                            'BirthPlaceID', //
                            _t('Genealogist.BIRTHPLACE', 'Birth Place'), //
                            $towns, //
                            $person->BirthPlaceID
                    )->setEmptyString(_t('Genealogist.BIRTHPLACE', 'Birth Place'));
            $items[] = CheckboxField::create('BirthDateEstimated', _t('Genealogist.BIRTHDATE_ESTIMATED', 'Birth Date Estimated'), $person->BirthDateEstimated);
            // Death
            $items[] = CheckboxField::create('IsDead', _t('Genealogist.ISDEAD', 'Is Dead'), $person->IsDead)
                    ->addExtraClass('death-options');
            $items[] = FieldGroup::create(
                            TextField::create('DeathDate', _t('Genealogist.DEATHDATE', 'Death Date'), $person->DeathDate), //
                            DropdownField::create(
                                    'DeathPlaceID', //
                                    _t('Genealogist.DEATHPLACE', 'Death Place'), //
                                    $towns, //
                                    $person->DeathPlaceID
                            )->setEmptyString(_t('Genealogist.DEATHPLACE', 'Death Place')), //
                            DropdownField::create(
                                    'BurialPlaceID', //
                                    _t('Genealogist.BURIALPLACE', 'Burial Place'), //
                                    $towns, //
                                    $person->BurialPlaceID
                            )->setEmptyString(_t('Genealogist.BURIALPLACE', 'Burial Place')), //
                            CheckboxField::create('DeathDateEstimated', _t('Genealogist.DEATHDATE_ESTIMATED', 'Death Date Estimated'), $person->DeathDateEstimated) //
                    )
                    ->setFieldHolderTemplate('FieldGroup_DefaultFieldHolder')
                    ->addExtraClass('death-fields');
            // Comments
        }
        $items[] = TextareaField::create('Comments', _t('Genealogist.COMMENTS', 'Comments'), $person->Comments);

        // Create fields
        $fields = new FieldList($items);

        // Create action
        $actions = new FieldList(
                new FormAction('doEditPerson', _t('Genealogist.SAVE', 'Save'))
        );

        // Create Validators
        $validator = new RequiredFields();

        return new Form($this, 'Form_EditPerson', $fields, $actions, $validator);
    }

    public function doEditPerson($data, $form) {
        $id = $data['PersonID'];

        $person = DataObject::get_by_id('Gender', (int) $id);

        $form->saveInto($person);
        $person->write();

        return $this->owner->redirectBack();
    }

    public function Form_EditSettings($personID) {
        if ($personID instanceof SS_HTTPRequest) {
            $id = $personID->postVar('PersonID');
        } else {
            $id = $personID;
        }

        $person = DataObject::get_by_id('Gender', (int) $id);

        // Prepare groups and members lists
        $groupsMap = array();
        foreach (Group::get() as $group) {
            // Listboxfield values are escaped, use ASCII char instead of »
            $groupsMap[$group->ID] = $group->getBreadcrumbs(' > ');
        }
        asort($groupsMap);

        $membersMap = array();
        foreach (Member::get() as $member) {
            // Listboxfield values are escaped, use ASCII char instead of »
            $membersMap[$member->ID] = $member->getTitle();
        }
        asort($membersMap);

        $viewerGroupsField = ListboxField::create("ViewerGroups", _t('Genealogist.VIEWER_GROUPS', "Viewer Groups"))
                ->setMultiple(true)
                ->setSource($groupsMap)
                ->setValue(null, $person)
                ->setAttribute('data-placeholder', _t('Genealogist.GROUP_PLACEHOLDER', 'Click to select group'))
                ->addExtraClass('viewer-fields');

        $viewerMembersField = ListboxField::create("ViewerMembers", _t('Genealogist.VIEWER_MEMBERS', "Viewer Users"))
                ->setMultiple(true)
                ->setSource($membersMap)
                ->setValue(null, $person)
                ->setAttribute('data-placeholder', _t('Genealogist.MEMBER_PLACEHOLDER', 'Click to select user'))
                ->addExtraClass('viewer-fields');

        $editorGroupsField = ListboxField::create("EditorGroups", _t('Genealogist.EDITOR_GROUPS', "Editor Groups"))
                ->setMultiple(true)
                ->setSource($groupsMap)
                ->setValue(null, $person)
                ->setAttribute('data-placeholder', _t('Genealogist.GROUP_PLACEHOLDER', 'Click to select group'))
                ->addExtraClass('editor-fields');

        $editorMembersField = ListboxField::create("EditorMembers", _t('Genealogist.EDITOR_MEMBERS', "Editor Users"))
                ->setMultiple(true)
                ->setSource($membersMap)
                ->setValue(null, $person)
                ->setAttribute('data-placeholder', _t('Genealogist.MEMBER_PLACEHOLDER', 'Click to select user'))
                ->addExtraClass('editor-fields');

        // Create fields
        $items = array(HiddenField::create('PersonID', 'PersonID', $id));
        if (!$person->isClan()) {
            $items[] = CheckboxField::create('IsPublicFigure', _t('Genealogist.PUBLIC_FIGURE', 'Is Public Figure'), $person->IsPublicFigure);
        }

        $items[] = DropdownField::create(
                        'CanViewType', //
                        _t('Genealogist.MOTHER', 'Mother'), //
                        singleton('Gender')->dbObject('CanViewType')->enumValues(), $person->CanViewType
                )
                ->addExtraClass('viewer-options');
        $items[] = $viewerGroupsField;
        $items[] = $viewerMembersField;
        $items[] = DropdownField::create(
                        'CanEditType', //
                        _t('Genealogist.MOTHER', 'Mother'), //
                        singleton('Gender')->dbObject('CanEditType')->enumValues(), $person->CanEditType
                )
                ->addExtraClass('editor-options');
        $items[] = $editorGroupsField;
        $items[] = $editorMembersField;

        $fields = new FieldList($items);

        // Create action
        $actions = new FieldList(
                new FormAction('doEditSettings', _t('Genealogist.SAVE', 'Save'))
        );

        // Create Validators
        $validator = new RequiredFields();

        return new Form($this, 'Form_EditSettings', $fields, $actions, $validator);
    }

    public function doEditSettings($data, $form) {
        $id = $data['PersonID'];

        $person = DataObject::get_by_id('Gender', (int) $id);
//        var_dump($data['CanViewType']);
        $form->saveInto($person);
//        var_dump($person->CanViewType);
        $person->write();

        return $this->owner->redirectBack();
    }

    /// Append Father int the tree ///
    public function Form_AddFather($personID = null) {
        if ($personID instanceof SS_HTTPRequest) {
            $id = $personID->postVar('PersonID');
        } else {
            $id = $personID;
        }

        // Create fields
        $fields = new FieldList(
                HiddenField::create('PersonID', 'PersonID', $id), //
                TextField::create('Name', _t('Genealogist.FATHER_NAME', 'Father Name'))
        );

        // Create action
        $actions = new FieldList(
                new FormAction('doAddFather', _t('Genealogist.ADD', 'Add'))
        );

        // Create Validators
        $validator = new RequiredFields('Name');

        return new Form($this, 'Form_AddFather', $fields, $actions, $validator);
    }

    public function doAddFather($data, $form) {
        $personID = $data['PersonID'];
        $fatherName = $data['Name'];

        GenealogistHelper::add_father($personID, $fatherName);

        return $this->owner->redirectBack();
    }

    /// Change Father ///
    public function Form_ChangeFather($personID = null) {
        if ($personID instanceof SS_HTTPRequest) {
            $id = $personID->postVar('PersonID');
        } else {
            $id = $personID;
        }

        // Create fields
        $fields = new FieldList(
                HiddenField::create('PersonID', 'PersonID', $id), //
                AutoPersonField::create(
                                'FatherID', //
                                _t('Genealogist.FATHER', 'Father'), //
                                '', //
                                null, //
                                null, //
                                'Male', //
                                array('IndexedName', 'Name', 'NickName') //
                        )
                        ->setSourceSort('CHAR_LENGTH(IndexedName) ASC')
                        ->setLimit(20)
        );

        // Create action
        $actions = new FieldList(
                new FormAction('doChangeFather', _t('Genealogist.UPDATE', 'Update'))
        );

        // Create Validators
        $validator = new RequiredFields('FatherID');

        return new Form($this, 'Form_ChangeFather', $fields, $actions, $validator);
    }

    public function doChangeFather($data, $form) {
        $personID = $data['PersonID'];
        $fatherID = $data['FatherID'];

        GenealogistHelper::change_father($personID, $fatherID);

        return $this->owner->redirectBack();
    }

    /// Change Mother ///
    public function Form_ChangeMother($personID = null) {
        if ($personID instanceof SS_HTTPRequest) {
            $id = $personID->postVar('PersonID');
        } else {
            $id = $personID;
        }

        $person = GenealogistHelper::get_gender($id);
        $mothers = array();
        if ($person->Father()->exists()) {
//            die($person->Name);
            $mothers = $person->Father()->Wives()->map();
        }
        if (count($mothers)) {
            $motherField = DropdownField::create(
                            'MotherID', //
                            _t('Genealogist.MOTHER', 'Mother'), //
                            $mothers, //
                            $person->MotherID
                    )->setEmptyString(_t('Genealogist.CHOOSE_MOTHER', 'Choose Mother'));
        } else {
            $motherField = AutoPersonField::create(
                            'MotherID', //
                            _t('Genealogist.MOTHER', 'Mother'), //
                            '', //
                            null, //
                            null, //
                            'Female', //
                            array('IndexedName', 'Name', 'NickName') //
            );
        }
        // Create fields
        $fields = new FieldList(
                HiddenField::create('PersonID', 'PersonID', $id), //
                $motherField
//                AutoPersonField::create(
//                        'MotherID', //
//                        _t('Genealogist.MOTHER', 'Mother'), //
//                        '', //
//                        null, //
//                        null, //
//                        'Female', //
//                        array('IndexedName', 'Name', 'NickName') //
//                )
        );

        // Create action
        $actions = new FieldList(
                new FormAction('doChangeMother', _t('Genealogist.UPDATE', 'Update'))
        );

        // Create Validators
        $validator = new RequiredFields('MotherID');

        return new Form($this, 'Form_ChangeMother', $fields, $actions, $validator);
    }

    public function doChangeMother($data, $form) {
        $personID = $data['PersonID'];
        $methorID = $data['MotherID'];

        GenealogistHelper::change_mother($personID, $methorID);

        return $this->owner->redirectBack();
    }

    /// Add Sons ///
    public function Form_AddSons($parentID = null) {
        if ($parentID instanceof SS_HTTPRequest) {
            $id = $parentID->postVar('ParentID');
        } else {
            $id = $parentID;
        }

        // Create fields
        $fields = new FieldList(
                HiddenField::create('ParentID', 'ParentID', $id), //
                TextField::create('Names', _t('Genealogist.SONS_NAMES', 'Sons Names (Use | to seperate the names)'))
        );

        // Create action
        $actions = new FieldList(
                new FormAction('doAddSons', _t('Genealogist.ADD', 'Add'))
        );

        // Create Validators
        $validator = new RequiredFields('Names');

        return new Form($this, 'Form_AddSons', $fields, $actions, $validator);
    }

    public function doAddSons($data, $form) {
        $id = $data['ParentID'];
        $names = $data['Names'];

        GenealogistHelper::add_sons($id, $names);

        return $this->owner->redirectBack();
    }

    /// Add Daughters ///
    public function Form_AddDaughters($parentID = null) {
        if ($parentID instanceof SS_HTTPRequest) {
            $id = $parentID->postVar('ParentID');
        } else {
            $id = $parentID;
        }

        // Create fields
        $fields = new FieldList(
                HiddenField::create('ParentID', 'ParentID', $id), //
                TextField::create('Names', _t('Genealogist.DAUGHTERS_NAMES', 'Daughters Names (Use | to seperate the names)'))
        );

        // Create action
        $actions = new FieldList(
                new FormAction('doAddDaughters', _t('Genealogist.ADD', 'Add'))
        );

        // Create Validators
        $validator = new RequiredFields('Names');

        return new Form($this, 'Form_AddDaughters', $fields, $actions, $validator);
    }

    public function doAddDaughters($data, $form) {
        $id = $data['ParentID'];
        $names = $data['Names'];

        GenealogistHelper::add_daughters($id, $names);

        return $this->owner->redirectBack();
    }

    /// Has single wife ///
    public function Form_SingleWife($personID) {
        if ($personID instanceof SS_HTTPRequest) {
            $id = $personID->postVar('PersonID');
        } else {
            $id = $personID;
        }

        // Create fields
        $fields = new FieldList(
                HiddenField::create('PersonID', 'PersonID', $id)
        );

        // Create action
        $actions = new FieldList(
                $button = new FormAction('doSingleWife', _t('Genealogist.ASSIGN_MOTHER', 'Assign Mother To All Children'))
        );
        $button->setAttribute('class', 'btn btn-danger');

        // Create Validators
        $validator = new RequiredFields();

        return new Form($this, 'Form_SingleWife', $fields, $actions, $validator);
    }

    public function doSingleWife($data, $form) {
        $id = $data['PersonID'];
        GenealogistHelper::single_wife($id);

        return $this->owner->redirectBack();
    }

    /// Add spouse ///
    public function Form_AddSpouse($personID) {
        if ($personID instanceof SS_HTTPRequest) {
            $id = $personID->postVar('PersonID');
        } else {
            $id = $personID;
        }

        // Create fields
        $fields = new FieldList(
                HiddenField::create('PersonID', 'PersonID', $id), //
                TextField::create('Name', _t('Genealogist.SPOUSE_NAME', 'Spouse Name'))
        );

        // Create action
        $actions = new FieldList(
                new FormAction('doAddSpouse', _t('Genealogist.ADD', 'Add'))
        );

        // Create Validators
        $validator = new RequiredFields('Name');

        return new Form($this, 'Form_AddSpouse', $fields, $actions, $validator);
    }

    public function doAddSpouse($data, $form) {
        $id = $data['PersonID'];
        $spouseID = null;
        $spouseName = $data['Name'];

        GenealogistHelper::add_spouse($id, $spouseID, $spouseName);

        return $this->owner->redirectBack();
    }

    /// Delete Person ///
    public function Form_DeletePerson($personID) {
        if ($personID instanceof SS_HTTPRequest) {
            $id = $personID->postVar('PersonID');
        } else {
            $id = $personID;
        }

//        $person = DataObject::get_by_id('Gender', (int) $id);
        // Create fields
        $fields = new FieldList(
                HiddenField::create('PersonID', 'PersonID', $id)
        );

        // Create action
        $actions = new FieldList(
                $button = new FormAction('doDeletePerson', _t('Genealogist.DELETE', 'Delete'))
        );
        $button->setAttribute('class', 'btn btn-danger');
        $button->useButtonTag = true;
        $button->addExtraClass('btn btn-danger');

        // Create Validators
        $validator = new RequiredFields();

        return new Form($this, 'Form_DeletePerson', $fields, $actions, $validator);
    }

    public function doDeletePerson($data, $form) {
        $id = $data['PersonID'];
        $person = DataObject::get_by_id('Gender', (int) $id);

        $parent = $person->FatherID;

        GenealogistHelper::delete_person($id);

        return $this->owner->redirect($this->Link('edit/' . $parent));
    }

    /// Delete Person ///
    public function Form_IndexPerson($personID) {
        if ($personID instanceof SS_HTTPRequest) {
            $id = $personID->postVar('PersonID');
        } else {
            $id = $personID;
        }

//        $person = DataObject::get_by_id('Gender', (int) $id);
        // Create fields
        $fields = new FieldList(
                HiddenField::create('PersonID', 'PersonID', $id)
        );

        // Create action
        $actions = new FieldList(
                new FormAction('doIndexPersonStatistics', _t('Genealogist.INDEX_STATISTICS', 'Index Statistics')), //
                new FormAction('doIndexPersonDates', _t('Genealogist.INDEX_DATES', 'Index Dates')), //
                new FormAction('doIndexPersonEvents', _t('Genealogist.INDEX_EVENTS', 'Index Events'))
        );

        // Create Validators
        $validator = new RequiredFields();

        return new Form($this, 'Form_IndexPerson', $fields, $actions, $validator);
    }

    public function doIndexPersonStatistics($data, $form) {
        $id = $data['PersonID'];
        $person = DataObject::get_by_id('Gender', (int) $id);

        GenealogistCrawlHelper::index_stats($person);

        return $this->owner->redirectBack();
    }

    public function doIndexPersonDates($data, $form) {
        $id = $data['PersonID'];
        $person = DataObject::get_by_id('Gender', (int) $id);

        GenealogistCrawlHelper::index_dates($person);

        return $this->owner->redirectBack();
    }

    public function doIndexPersonEvents($data, $form) {
        $id = $data['PersonID'];
        $person = DataObject::get_by_id('Gender', (int) $id);

        GenealogistEventsHelper::create_all_events($person);

        return $this->owner->redirectBack();
    }

    /// Utils ///
    public function getBranches() {
        return GenealogistHelper::get_all_clans_and_branches();
    }

    public function getMainClansAndBranches() {
        return GenealogistHelper::get_main_clans_and_branches();
    }

}


text:
namespace Amongst
{
    public enum MongoDBInstanceState
    {
        Stopped,
        Starting,
        Running,
        Stopping
    }
}