text:
RELEASE 2:

This example shows the relationsihp between a student and their address.  This information, in certain circumstances, may be maintained better if it was seperate, like we see here.  In this case, we create a one-to-one schema in which the Student table holds the primary key and Address holds the foreign key.  This relaitonship is one to one because we don't have any othr tables involved, and the information as it stands is only being accessed from one to the other.  Even if there were more tables linked up, if two tables have specific ids to reference each other and that's the only way THOSE tables interact, then they have a one to one relationship.

What is a one-to-one database?
A one-to-one relationship relates two tables of informtion uniqueley.

When would you use a one-to-one database? (Think generally, not in terms of the example you created).
Whenever you wanted to have a unique relatinship between tables of information.

What is a many-to-many database?
Many-to-many relationships basically allow information to flow between tables in several different ways.  You can think of books an authors for this one.  Books can be created by several authors, auhors can create several books.

When would you use a many-to-many database? (Think generally, not in terms of the example you created).
Whenever you have information that can be contributed to, taken from, and able to create/take from something else.

What is confusing about database schemas? What makes sense?
They're not confusing conceptually but i'm still having a hard time being able to define them when asked to write about them.  Also, seeing practical uses of one to ones...

redpajama_set_name: RedPajamaGithub


text:
(function(exports) {
  'use strict';

  /*
    This code is in charge of loading the basic UI, and then lazy loading the rest
    of elements needed
  */

  var _title, _callStatusInfo, _remoteVideo, _remoteImage;

  var _; // l10n get

  var CallScreenUIMinified = {
    init: function() {

      _ = navigator.mozL10n.get;
      // Cache just the basic elements. The rest will be added by
      // lazy loading.
      _title = document.getElementById('contact-name-details');
      _callStatusInfo = document.getElementById('call-status-info');
      _remoteVideo = document.getElementById('remote-video');
      _remoteImage = document.getElementById('fullscreen-image');

      // Get params from URL. For the basic layout we are expecting
      // the type/layout of the call, identities and if it's a video
      // call or not.
      var query = window.location.search.slice(1);
      var urlParams = query.split('&');
      var callParams = {};

      for (var i=0; i < urlParams.length; i++) {
        var keyValue = urlParams[i].split('=');
        callParams[keyValue[0]] = decodeURIComponent(keyValue[1]);
      }

      var _fakeScreenDisabledPanel = document.getElementById('fake-disabled-screen');
      window.addEventListener('userproximity', function onProximityEvent(event) {
        if (event.near) {
          _fakeScreenDisabledPanel.classList.add('on');
        } else {
          _fakeScreenDisabledPanel.classList.remove('on');
        }
      });

      // Update the layout of the HTML based on the dataset
      document.body.dataset.callStatus = callParams.layout;

      // Based on the type of the call, we are going to render the maximum
      // info available
      if (callParams.layout === 'incoming') {
        LazyLoader.load(
          ['js/ringer.js'],
          function onRingerLoaded() {
            Ringer.play();
          }
        );
      } else {
        if (callParams.token) {
          _callStatusInfo.textContent = _('retrieving');
        } else {
          _callStatusInfo.textContent = _('calling');
          var identities = callParams.identities.split(',');
          CallScreenUIMinified.updateIdentityInfo(identities);
        }
      }

      // Once all basics are loaded, we are goint to lazy load the rest of functions needed
      // for handling the UI.
      var files = [
        '../js/helpers/tone_player_helper.js',
        '../js/helpers/audio_competing_helper.js',
        'js/countdown.js',
        'js/ringer.js',
        'js/call_manager.js',
        'js/call_screen_ui.js'
      ];

      if (Config.performanceLog.enabled) {
        files.push('../js/helpers/performance_log_helper.js');
      }

      LazyLoader.load(
        files,
        function onCallScreen() {
          CallScreenUI.init(
            callParams.layout && callParams.layout === 'incoming',
            callParams.video && callParams.video === 'true',
            callParams.frontCamera && callParams.frontCamera === 'true'
          );
        }
      );
    },
    updateIdentityInfo: function(identities) {
      LazyLoader.load(
        ['../js/helpers/contacts_helper.js'],
        function onContactHelperLoaded() {
          ContactsHelper.find(
            {
              identities: identities
            },
            function onContact(result) {
              if (!result) {
                 _title.textContent = identities[0];
                return;
              }
              // We don't want to show the whole list of contacts in the call screen
              // so we just take the first one.
              _title.textContent = result.contacts[0].name[0];

              if (result.contacts[0] &&
                  result.contacts[0].photo &&
                  result.contacts[0].photo[0]) {
                var url = URL.createObjectURL(result.contacts[0].photo[0]);
                var urlString = 'url(' + url + ')';
                _remoteVideo.innerHTML = '';
                _remoteVideo.style.backgroundImage = urlString;
                _remoteImage.style.backgroundImage = urlString;
              }
            },
            function onError() {
               _title.textContent = identities[0];
            }
          );
        }
      );
    }
  };

  exports.CallScreenUIMinified = CallScreenUIMinified;

}(this));

CallScreenUIMinified.init();


text:
namespace boxutil {

enum class Platform {Linux, Win32, Win64};

Platform GetPlatform();

class SysTime final {
public:

    SysTime();
    SysTime(const SysTime &other);
    SysTime(const SysTime &&other);
    ~SysTime();

    SysTime& operator= (const SysTime &other);
    SysTime& operator= (const SysTime &&other) = delete;
    bool operator== (const SysTime &other);
    std::string ToString();

    void Copy(const SysTime &other);

    int m_box_seconds;
    int m_box_minutes;
    int m_box_hours;
    int m_box_monthday;
    int m_box_month;
    int m_box_year;

};

bool FileExists(const std::string &strFileName);
bool FileDelete(const std::string &strFileName);
bool FileSize(const std::string &strFileName, unsigned int &filesize);
bool GetFileContents(const std::string &strFileName, std::string &strContents);
bool SaveFileContents(const std::string &strFileName, const std::string &strContents);

bool DirExists(const std::string &strDirName, bool &answer);
bool HasWritePermission(const std::string &strDirName);
bool HasReadPermission(const std::string &strDirName);

bool GetAppWorkingDir(std::string &output);
std::string GetSysTmpDir();
std::string GetUserHomeFolder();

bool BuildFileList(const std::string &strPath, const std::string &strInputExt, StrVecCont &svcFilelist);

SysTime GetSystemTime();
void GetTimeStampString(char **pstrBuf);
void GetTimeStampString(std::string &strTimestamp);

} // ns: boxutil

#endif // __BOXUTIL_SYSUTIL_H__


text:
package org.mifos.calendar;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.when;

import java.util.Arrays;
import java.util.List;

import org.joda.time.DateTime;
import org.joda.time.Days;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mifos.application.holiday.business.Holiday;
import org.mifos.schedule.ScheduledEvent;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

@RunWith(MockitoJUnitRunner.class)
public class BasicHolidayStrategyTest {

    private BasicHolidayStrategy holidayStrategy;

    @Mock
    private ScheduledEvent scheduledEvent;

    @Mock
    private Holiday holiday;

    @Mock
    private Holiday holiday2;

    private List<Days> workingDays;

    @Before
    public void setupAndInjectDependencies() {

        workingDays = Arrays.asList(DayOfWeek.mondayAsDay(), DayOfWeek.tuesdayAsDay(), DayOfWeek.wednesdayAsDay(),
                DayOfWeek.thursdayAsDay(), DayOfWeek.fridayAsDay());
    }

    @Test
    public void whenAHolidayFallsOnDateTheDateShouldBeAdjusted() {

        // setup
        List<Holiday> upcomingHolidays = Arrays.asList(holiday);
        holidayStrategy = new BasicHolidayStrategy(upcomingHolidays, workingDays, scheduledEvent);

        DateTime firstOfNextMonth = new DateTime().plusMonths(1).withDayOfMonth(1).toDateMidnight().toDateTime();

        // stubbing
        when(holiday.encloses(firstOfNextMonth.toDate())).thenReturn(true);
        when(holiday.adjust(firstOfNextMonth, workingDays, scheduledEvent)).thenReturn(firstOfNextMonth.plusDays(1));

        // exercise test
        DateTime adjustedDate = holidayStrategy.adjust(firstOfNextMonth);

        assertThat(adjustedDate, is(firstOfNextMonth.plusDays(1)));
    }

    @Test
    public void whenAHolidayAdjustmentCausesAdjustedDateToFallOnAnotherHolidayTheDateShouldAgainBeAdjustedForSubsequentHoliday() {

        // setup
        List<Holiday> upcomingHolidays = Arrays.asList(holiday, holiday2);
        holidayStrategy = new BasicHolidayStrategy(upcomingHolidays, workingDays, scheduledEvent);

        DateTime firstOfNextMonth = new DateTime().plusMonths(1).withDayOfMonth(1).toDateMidnight().toDateTime();
        DateTime secondOfNextMonth = firstOfNextMonth.plusDays(1);

        when(holiday.encloses(firstOfNextMonth.toDate())).thenReturn(true);
        when(holiday.adjust(firstOfNextMonth, workingDays, scheduledEvent)).thenReturn(secondOfNextMonth);

        when(holiday2.encloses(secondOfNextMonth.toDate())).thenReturn(true);
        when(holiday2.adjust(secondOfNextMonth, workingDays, scheduledEvent)).thenReturn(secondOfNextMonth.plusDays(1));

        DateTime adjustedDate = holidayStrategy.adjust(firstOfNextMonth);

        assertThat(adjustedDate, is(secondOfNextMonth.plusDays(1)));
    }
}


text:
package com.example.prateek.spotmate;

import android.Manifest;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.ListActivity;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.location.Location;
import android.media.audiofx.BassBoost;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.location.LocationManager;
import android.location.LocationListener;
import android.location.LocationProvider;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkError;
import com.android.volley.NoConnectionError;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigInteger;
import java.nio.charset.StandardCharsets;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TooManyListenersException;

public class home extends Activity {
    String username, contactName="", contactPhone="";
    String phoneArray[], nameArray[], verNameArray[];
    private LocationManager locationManager;
    private LocationListener locationListener;
    ListView lvContact;
    public final String SERVER_ADDRESS = "http://spotmate.freeoda.com/";
    AlarmManager alarmManager;
    PendingIntent pendingIntent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //Toast.makeText(this, "3", Toast.LENGTH_SHORT).show();
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        locationListener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                Toast.makeText(home.this, location.getLatitude()+  " " + location.getLongitude(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {

            }

            @Override
            public void onProviderEnabled(String provider) {

            }

            @Override
            public void onProviderDisabled(String provider) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivity(intent);

            }
        };

        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                    && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{
                        Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION,
                        Manifest.permission.INTERNET
                }, 10 );
                return;
            }
        }else{
            locationManager.requestLocationUpdates("gps", 10000, 0, locationListener);
        }

        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED
                    && ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{
                        Manifest.permission.READ_CONTACTS,Manifest.permission.WRITE_CONTACTS,
                        Manifest.permission.INTERNET
                }, 11 );
                return;
            }
        }else{
            locationManager.requestLocationUpdates("gps", 10000, 0, locationListener);
        }
        volleyRequest();
        Intent alarmIntent = new Intent(this, AlarmReceiver.class);
        pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);
//
//        username = StoreSharePreferances.getUserName(getApplicationContext());
//        String s = StoreSharePreferances.getUserName(getApplicationContext());
//        System.out.println(s+"is the username");

//        Intent intent = new Intent();
//            intent.setClass(this, GetLocationStatus.class);
//            intent.putExtra("username", username);
//            startActivity(intent);
            nowStart();

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode){
            case 10:
                if(grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
                    locationManager.requestLocationUpdates("gps", 10000, 0, locationListener);
                return;
            case 11:
                if(grantResults.length>0 && grantResults[1] == PackageManager.PERMISSION_GRANTED)
                return;

        }
    }

    public void nowStart(){
        alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
        int interval = 10800000;

        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pendingIntent);
        //Toast.makeText(this, "Background Location update has started", Toast.LENGTH_SHORT).show();
    }

    private void showResults(){
            lvContact = (ListView) findViewById(R.id.android_list);
            ContentResolver resolver = getContentResolver();
            Cursor cursor = resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
            while (cursor.moveToNext()) {
                String name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                String phone = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                if (phone.length() > 10) {
                    phone = phone.substring(phone.length() - 10);
                }
                //System.out.println(name + "==                 " + phone);
                if(checkNumber(phone)) {
                    if (name != null) {
                        contactName += name + ",";
                        contactPhone += phone + ",";
                    }
                }
            }
            System.out.println(contactName);
            cursor.close();
            nameArray = contactName.split(",");
            phoneArray = contactPhone.split(",");
            ArrayAdapter<String> ad = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, nameArray);
            lvContact.setAdapter(ad);
            lvContact.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                   // Toast.makeText(home.this, phoneArray[position] + "and the " + position, Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent();
                    intent.setClass(getApplicationContext(), ShowsLocation.class);

                    Bundle extras = new Bundle();
                    extras.putString("number",phoneArray[position]);
                    extras.putString("name",nameArray[position]);
                    intent.putExtras(extras);
                    startActivity(intent);
                }
            });

    }

    public void volleyRequest() {

        RequestQueue queue = Volley.newRequestQueue(this);
        StringRequest stringRequest = new StringRequest(Request.Method.GET, SERVER_ADDRESS + "getContacts.php",
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        System.out.println(response);
                        int n = response.length();
                        String str = response.substring(1, n-1);
                        extractContacts(str);
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                System.out.println("That didn't work!");
            }
        });
        queue.add(stringRequest);

    }

    public void extractContacts(String str){
        verNameArray = str.split(",");
        int n = verNameArray.length;
        for (int i = 0;i<n;i++)
        {
            int l = verNameArray[i].length();
            verNameArray[i] = verNameArray[i].substring(1, l-1);
            System.out.println(verNameArray[i]);
        }
        showResults();
    }

    public boolean checkNumber(String str){
        int flag=0;
        for(int i=0;i<verNameArray.length;i++)
        {
            if(str.equals(verNameArray[i])){
                flag = 1;
                break;
            }
        }
        if(flag==1){
            return true;
        }
        else
            return false;
    }
}


text:
require 'stringio'
require 'rubygems'
require 'minitest/unit'
require 'rdoc/ri/formatter'
require 'rdoc/ri/display'
require 'rdoc/ri/driver'

class TestRDocRiDefaultDisplay < MiniTest::Unit::TestCase

  def setup
    @output = StringIO.new
    @width = 78
    @indent = '  '

    @dd = RDoc::RI::DefaultDisplay.new RDoc::RI::Formatter, @width, true,
                                       @output

    @some_method = h \
      'aliases' => [{'name' => 'some_method_alias'}],
      'block_params' => 'block_param',
      'comment' => [RDoc::Markup::Flow::P.new('some comment')],
      'full_name' => 'SomeClass#some_method',
      'is_singleton' => false,
      'name' => 'some_method',
      'params' => '(arg1, arg2) {|block_param| ...}',
      'source_path' => '/nonexistent',
      'visibility' => 'public'
  end

  def test_display_class_info
    klass = h \
      'attributes' => [
        { 'name' => 'attribute', 'rw' => 'RW',
          'comment' => [RDoc::Markup::Flow::P.new('attribute comment')] },
        { 'name' => 'attribute_no_comment', 'rw' => 'RW',
          'comment' => nil },
      ],
      'class_methods' => [
        { 'name' => 'class_method' },
      ],
      'class_method_extensions' => [
        { 'name' => 'class_method_extension' },
      ],
      'comment' => [RDoc::Markup::Flow::P.new('SomeClass comment')],
      'constants' => [
        { 'name' => 'CONSTANT', 'value' => '"value1"',
          'comment' => [RDoc::Markup::Flow::P.new('CONSTANT value')] },
        { 'name' => 'CONSTANT_NOCOMMENT', 'value' => '"value2"',
          'comment' => nil },
      ],
      'display_name' => 'Class',
      'full_name' => 'SomeClass',
      'includes' => [],
      'instance_methods' => [
        { 'name' => 'instance_method' },
        { 'name' => 'instance_method2' },
      ],
      'instance_method_extensions' => [
        { 'name' => 'instance_method_extension' },
      ],
      'superclass' => 'Object'

    @dd.display_class_info klass

    expected = <<-EOF
---------------------------------------------------- Class: SomeClass < Object
     SomeClass comment

------------------------------------------------------------------------------

Constants:
----------

     CONSTANT = "value1"
          CONSTANT value

     CONSTANT_NOCOMMENT = "value2"

Attributes:
-----------

     attribute (RW):
          attribute comment

     attribute_no_comment (RW)

Class methods:
--------------

     class_method

Class method extensions:
------------------------

     class_method_extension

Instance methods:
-----------------

     instance_method, instance_method2

Instance method extensions:
---------------------------

     instance_method_extension
    EOF

    assert_equal expected, @output.string
  end

  def test_display_flow
    flow = [RDoc::Markup::Flow::P.new('flow')]

    @dd.display_flow flow

    assert_equal "     flow\n\n", @output.string
  end

  def test_display_flow_empty
    @dd.display_flow []

    assert_equal "     [no description]\n", @output.string
  end

  def test_display_flow_nil
    @dd.display_flow nil

    assert_equal "     [no description]\n", @output.string
  end

  def test_display_method_info
    @dd.display_method_info @some_method

    expected = <<-EOF
-------------------------------------------------------- SomeClass#some_method
     some_method(arg1, arg2) {|block_param| ...}

     From /nonexistent
------------------------------------------------------------------------------
     some comment

     (also known as some_method_alias)
    EOF

    assert_equal expected, @output.string
  end

  def test_display_method_info_singleton
    method = RDoc::RI::Driver::OpenStructHash.new.update \
      'aliases' => [],
      'block_params' => nil,
      'comment' => nil,
      'full_name' => 'SomeClass::some_method',
      'is_singleton' => true,
      'name' => 'some_method',
      'params' => '(arg1, arg2)',
      'visibility' => 'public'

    @dd.display_method_info method

    expected = <<-EOF
------------------------------------------------------- SomeClass::some_method
     SomeClass::some_method(arg1, arg2)

     From
------------------------------------------------------------------------------
     [no description]
    EOF

    assert_equal expected, @output.string
  end

  def test_display_method_list
    methods = [
      RDoc::RI::Driver::OpenStructHash.new.update(
        "aliases" => [],
        "block_params" => nil,
        "comment" =>  nil,
        "full_name" => "SomeClass#some_method",
        "is_singleton" => false,
        "name" => "some_method",
        "params" => "()",
        "visibility" => "public"
      ),
      RDoc::RI::Driver::OpenStructHash.new.update(
        "aliases" => [],
        "block_params" => nil,
        "comment" => nil,
        "full_name" => "SomeClass#some_other_method",
        "is_singleton" => false,
        "name" => "some_other_method",
        "params" => "()",
        "visibility" => "public"
      ),
    ]

    @dd.display_method_list methods

    expected = <<-EOF
     More than one method matched your request.  You can refine your search by
     asking for information on one of:

SomeClass#some_method []
SomeClass#some_other_method []
    EOF

    assert_equal expected, @output.string
  end

  def test_display_params
    @dd.display_params @some_method

    expected = <<-EOF
     some_method(arg1, arg2) {|block_param| ...}

     From /nonexistent
    EOF

    assert_equal expected, @output.string
  end

  def test_display_params_multiple
    @some_method['params'] = <<-EOF
some_method(index)
some_method(start, length)
    EOF

    @dd.display_params @some_method

    expected = <<-EOF
     some_method(index)
     some_method(start, length)

     From /nonexistent
    EOF

    assert_equal expected, @output.string
  end

  def test_display_params_singleton
    @some_method['is_singleton'] = true
    @some_method['full_name'] = 'SomeClass::some_method'

    @dd.display_params @some_method

    expected = <<-EOF
     SomeClass::some_method(arg1, arg2) {|block_param| ...}

     From /nonexistent
    EOF

    assert_equal expected, @output.string
  end

  def test_list_known_classes
    klasses = %w[SomeClass SomeModule]

    @dd.list_known_classes klasses

    expected = <<-EOF
---------------------------------------------------- Known classes and modules

     SomeClass
     SomeModule
    EOF

    assert_equal expected, @output.string
  end

  def test_list_known_classes_empty
    @dd.list_known_classes []

    expected = <<-EOF
No ri data found

If you've installed Ruby yourself, you need to generate documentation using:

  make install-doc

from the same place you ran `make` to build ruby.

If you installed Ruby from a packaging system, then you may need to
install an additional package, or ask the packager to enable ri generation.
    EOF

    assert_equal expected, @output.string
  end

  def h(hash)
    RDoc::RI::Driver::OpenStructHash.convert hash
  end

end

MiniTest::Unit.autorun


text:
This sample shows you how to create Stripe customers when your users sign up, securely collect and store their payment details, and charge them when a new document is written to your Firestore.

### Features

- Create a customer object in Stripe when a new user signs up. ([view code](./functions/index.js#L29)).
- Securely collect a customers card details with Stripe Elements and set them up for future usage. ([view code](./public/javascript/app.js#L69)).
- Create a payment on the customer's card when a new document is written to the `payments` collection. ([view code](./functions/index.js#L75)).
  - **NOTE:** Note that this example creates the payment document on the client with an amount and currency inputted by the user. In a real application, you need to validate price details in your function, e.g. based on product information stored in your Firestore.
- Handle 3D Secure authentication if required by the card issuer. Read more about 3D Secure and SCA [here](https://stripe.com/payments/strong-customer-authentication). ([view code](./functions/index.js#L114))

#### Further reading:

- Stripe docs: https://stripe.com/docs/payments/save-and-reuse
- 3D Secure and SCA regulation: https://stripe.com/payments/strong-customer-authentication
- Firebase docs: https://firebase.google.com/docs/functions

## Demo

- https://cloud-functions-stripe-sample.web.app/

![Firebase Stripe demo gif](./demo.gif)

## Deploy and test

- Create a Firebase Project using the [Firebase Developer Console](https://console.firebase.google.com)
- Enable billing on your project by switching to the Blaze plan. See [pricing](https://firebase.google.com/pricing/) for more details. This is required to be able to do requests to non-Google services.
- Enable Google & Email sign-in in your [authentication provider settings](https://console.firebase.google.com/project/_/authentication/providers).
- Install [Firebase CLI Tools](https://github.com/firebase/firebase-tools) if you have not already and log in with `firebase login`.
- Configure this sample to use your project using `firebase use --add` and select your project.
- Install dependencies locally by running: `cd functions; npm install; cd -`
- [Add your Stripe API Secret Key](https://dashboard.stripe.com/account/apikeys) to firebase config:
  ```bash
  firebase functions:config:set stripe.secret=<YOUR STRIPE SECRET KEY>
  ```
- Set your [Stripe publishable key](https://dashboard.stripe.com/account/apikeys) for the `STRIPE_PUBLISHABLE_KEY` const in [`/public/javascript/app.js`](./public/javascript/app.js#L16)
- Deploy your project using `firebase deploy`
- Test your Stripe integration by viewing your deployed site `firebase open hosting:site`

### Run the client locally

Since this project uses Firebase Auth triggers, the functions need to be deployed. However, when making changes to your client application in the `/public` folder, you can serve it locally to quickly preview changes.

```
firebase deploy --only functions ## only needs to be run when you make changes to your functions

firebase serve --only hosting
```

## Accepting live payments

Once you're ready to go live, you will need to exchange your test keys for your live keys. See the [Stripe docs](https://stripe.com/docs/keys) for further details.

- Update your Stripe secret config:
  ```bash
  firebase functions:config:set stripe.secret=<YOUR STRIPE LIVE SECRET KEY>
  ```
- Set your [live publishable key](https://dashboard.stripe.com/account/apikeys) for the `STRIPE_PUBLISHABLE_KEY` const in [`/public/javascript/app.js`](./public/javascript/app.js#L16).
- Redeploy both functions and hosting for the changes to take effect `firebase deploy`.


text:
import {Component,
  Input,
  Output,
  EventEmitter,
  ChangeDetectionStrategy} from '@angular/core';

import {Observable} from 'rxjs/Observable';
import {Store} from '@ngrx/store';
import {AppStore} from '../app.store';

import {Project} from './project.store';
import {ProjectService} from './project.service';
import {UsersService} from '../user/users.service';
import {ProjectList} from './project-list.component';

@Component({
  selector: 'projects-preview',
  providers: [],
  template: require('./project-preview.html'),
  directives: [ProjectList],
  changeDetection: ChangeDetectionStrategy.OnPush
})

export class ProjectsPreview {
  userName: string;
  userId: string;
  projects: Observable<Array<Project>>;
  statusMessage: String;

  selectedProject: Observable<Project>;

  constructor(private projectService: ProjectService,
              private store: Store<AppStore>,
              private usersService: UsersService
            ) {

    // Bind to the `recipes` observable on `RecipeService`
    this.projects = projectService.projects;

    // `recipeService.loadRecipes` dispatches the `ADD_RECIPES` event
    // to our store which in turn updates the `recipes` collection
    projectService.loadProjects();
  }

}


text:
import sys
import django

from os.path import dirname, abspath

from django.conf import settings

if len(sys.argv) > 1 and 'postgres' in sys.argv:
    sys.argv.remove('postgres')
    db_engine = 'django.db.backends.postgresql_psycopg2'
    db_name = 'test_main'
else:
    db_engine = 'django.db.backends.sqlite3'
    db_name = ''

if not settings.configured:
    settings.configure(
        DATABASES={
            'default': {
                'ENGINE': db_engine,
                'NAME': db_name,
            }
        },
        DATABASE_ENGINE = db_engine,
        DATABASE_NAME = db_name,
        INSTALLED_APPS = [
            'django.contrib.auth',
            'django.contrib.contenttypes',
            'django.contrib.sessions',
            'ratings',
            'ratings.ratings_tests',
        ],
        MIDDLEWARE_CLASSES = (
            'django.contrib.sessions.middleware.SessionMiddleware',
            'django.contrib.auth.middleware.AuthenticationMiddleware',
            'django.middleware.locale.LocaleMiddleware',
            'django.middleware.common.CommonMiddleware',
        ),
        ROOT_URLCONF='ratings.ratings_tests.urls',
    )

if django.VERSION < (1, 6):
    app_to_test = 'ratings_tests'
else:
    app_to_test = 'ratings.ratings_tests'

try:
    from django.test.simple import run_tests
    def runtests(*test_args):
        if not test_args:
            test_args = [app_to_test]
        parent = dirname(abspath(__file__))
        sys.path.insert(0, parent)
        failures = run_tests(test_args, verbosity=1, interactive=True)
        sys.exit(failures)

    if __name__ == '__main__':
        runtests(*sys.argv[1:])

except:
    from django.test.utils import get_runner
    def runtests(*test_args):
        if not test_args:
            test_args = [app_to_test]
        parent = dirname(abspath(__file__))
        sys.path.insert(0, parent)
        TestRunner = get_runner(settings)
        test_runner = TestRunner(verbosity=1, interactive=True)
        try:
            from django import setup
            setup()
        except ImportError:
            pass
        failures = test_runner.run_tests(test_args)
        sys.exit(failures)

    if __name__ == '__main__':
        runtests(*sys.argv[1:])


text:
/*
* Need called for:
* Firefox < 11
* Opera < 10
* Safari < 4
* Chrome < 1
* IE < 10
*/

'use strict';

var elements = require('./elements');

elements.attrHooks = {};
elements.propHooks = {};

var getAttribute = elements.getAttribute;
elements.getAttribute = /** @function
                        * @param elt
                        * @param name */function (elt, name) {
    if (elements.attrHooks[name] && elements.attrHooks[name].get) {
        return elements.attrHooks[name].get(elt);
    }

    return getAttribute(elt, name);
};

var setAttribute = elements.setAttribute;
elements.setAttribute = /** @function
                        * @param elt
                        * @param name
                        * @param value */function (elt, name, value) {
    if (elements.attrHooks[name] && elements.attrHooks[name].set) {
        return elements.attrHooks[name].set(elt, value);
    }

    setAttribute(elt, name, value);
};

var removeAttribute = elements.removeAttribute;
elements.removeAttribute = /** @function
                           * @param elt
                           * @param name */function (elt, name) {
    if (elements.attrHooks[name] && elements.attrHooks[name].set) {
        return elements.attrHooks[name].set(elt, null);
    }

    removeAttribute(elt, name);
};

var getProperty = elements.getProperty;
elements.getProperty = /** @function
                       * @param elt
                       * @param name */function (elt, name) {
    if (elements.propHooks[name] && elements.propHooks[name].get) {
        return elements.propHooks[name].get(elt);
    }

    return getProperty(elt, name);
};

var setProperty = elements.setProperty;
elements.setProperty = /** @function
                       * @param elt
                       * @param name
                       * @param value */function (elt, name, value) {
    if (elements.propHooks[name] && elements.propHooks[name].set) {
        return elements.propHooks[name].set(elt, value);
    }

    setProperty(elt, name, value);
};
/*
if (!document.documentElement.classList || !document.documentElement.classList.add
                || !document.documentElement.classList.remove ||
                !(function() {
                    var div = document.createElement('div');
                    div.classList.add('test1', 'test2');
                    return div.getAttribute('class') === 'test1 test2';
                })()) {
    //console.log('Write addClass and removeClass');
    elements.addClass = function(elt, classes) {
        var _eClass = elements.getAttribute(elt, 'class') || '';
        classes.split(' ').forEach(function(_class) {
            if (!elements.hasClass(elt, _class)) {
                _eClass += ' '+_class;
            }
        });

        elements.setAttribute(elt, 'class', _eClass.trim());
    };
    elements.removeClass = function(elt, classes) {
        var _eClass = elements.getAttribute(elt, 'class') || '';
        var removed = false;
        classes.split(' ').forEach(function(_class) {
            if (elements.hasClass(elt, _class)) {
                removed = true;
                _eClass = _eClass.replace(new RegExp("(^|\\s)" + _class + "(\\s|$)"), " ").replace(/\s$/, "");
            }
        });
        if (removed) {
            elements.setAttribute(elt, 'class', _eClass);
        }
        return removed;
    };
}

if (!document.documentElement.classList || !document.documentElement.classList.contains) {
    elements.hasClass = function(elt, _class) {
        var _eClass = elements.getAttribute(elt, 'class') || '';
        if (_eClass && (' ' + _eClass + ' ').indexOf(' ' + _class + ' ') !== -1) {
            return true;
        }
        return false;
    };
}

if (!document.documentElement.classList || !document.documentElement.classList.toggle) {
    elements.toggleClass = document.documentElement.classList && document.documentElement.classList.contains
      ? function(elt, _class) {
        return !(elt.classList.contains(_class) ? elements.removeClass(elt, _class) : elements.addClass(elt, _class));
    } : function(elt, _class) {
        return !(elements.removeClass(elt, _class) || elements.addClass(elt, _class));
    };
}

if (document.documentElement.classList && !(function() {
    var div = document.createElement('div');
    div.setAttribute('class', 'test');
    div.classList.add('test1', 'test2');
    var result = div.getAttribute('class') === 'test1 test2';
    div = null;
    return result;
}())) {
    elements.addClass = function(elt, classes) {
        classes.split(' ').forEach(function(_class) {
            elt.classList.add(_class);
        });
    };
}
*/

if (!( /** @function */function () {
    var div = document.createElement('div');
    div.setAttribute('class', 'test');
    var result = div.getAttribute('class') === 'test';
    div = null;
    return result;
})()) {
    elements.attrHooks['class'] = {
        get: /** @function
             * @param elt */function get(elt) {
            return elt.className;
        },

        set: /** @function
             * @param elt
             * @param value */function set(elt, value) {
            elt.className = value || '';
        }
    };
}
//# sourceMappingURL=shim.js.map


text:
package org.springframework.cloud.stream.app.websocket.sink;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.beans.factory.annotation.Autowired;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

/**
 * Bootstraps a Netty server using the {@link WebsocketSinkServerInitializer}. Also adds
 * a {@link LoggingHandler} and uses the <tt>logLevel</tt>
 * from {@link WebsocketSinkProperties#logLevel}.
 *
 * @author Oliver Moser
 * @author Gary Russell
 */
public class WebsocketSinkServer {

	private static final Log logger = LogFactory.getLog(WebsocketSinkServer.class);

	static final List<Channel> channels = Collections.synchronizedList(new ArrayList<Channel>());

	@Autowired
	WebsocketSinkProperties properties;

	@Autowired
	WebsocketSinkServerInitializer initializer;

	private EventLoopGroup bossGroup;

	private EventLoopGroup workerGroup;

	private int port;

	public int getPort() {
		return this.port;
	}

	@PostConstruct
	public void init() {
		bossGroup = new NioEventLoopGroup(properties.getThreads());
		workerGroup = new NioEventLoopGroup();
	}

	@PreDestroy
	public void shutdown() {
		bossGroup.shutdownGracefully();
		workerGroup.shutdownGracefully();
	}

	public void run() throws InterruptedException {
		NioServerSocketChannel channel = (NioServerSocketChannel) new ServerBootstrap().group(bossGroup, workerGroup)
			.channel(NioServerSocketChannel.class)
			.handler(new LoggingHandler(nettyLogLevel()))
			.childHandler(initializer)
			.bind(properties.getPort())
			.sync()
			.channel();
		this.port = channel.localAddress().getPort();
		dumpProperties();
	}

	private void dumpProperties() {
		logger.info("███████████████████████████████████████████████████████████");
		logger.info("                >> websocket-sink config <<                ");
		logger.info("");
		logger.info(String.format("port:     %s", this.port));
		logger.info(String.format("ssl:               %s", this.properties.isSsl()));
		logger.info(String.format("path:     %s", this.properties.getPath()));
		logger.info(String.format("logLevel: %s", this.properties.getLogLevel()));
		logger.info(String.format("threads:           %s", this.properties.getThreads()));
		logger.info("");
		logger.info("████████████████████████████████████████████████████████████");
	}

	//
	// HELPERS
	//
	private LogLevel nettyLogLevel() {
		return LogLevel.valueOf(properties.getLogLevel().toUpperCase());
	}

}


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
null

#### Original name
Phialophora finlandia C.J.K. Wang & H.E. Wilcox

### Remarks
null


text:
import IconWidget from "@enhavo/app/toolbar/widget/model/IconWidget";
import AbstractFactory from "@enhavo/app/toolbar/widget/factory/AbstractFactory";
import EventDispatcher from "@enhavo/app/view-stack/EventDispatcher";
import MenuManager from "@enhavo/app/menu/MenuManager";

export default class IconWidgetFactory extends AbstractFactory
{
    private readonly eventDispatcher: EventDispatcher;
    private readonly menuManager: MenuManager;

    constructor(eventDispatcher: EventDispatcher, menuManager: MenuManager) {
        super();
        this.eventDispatcher = eventDispatcher;
        this.menuManager = menuManager;
    }

    createNew(): IconWidget {
        return new IconWidget(this.eventDispatcher, this.menuManager);
    }
}


text:
package sample.jcu.semaphore.producerandconsummer;

/**
 * Created by kanglei on 20/10/2017.
 */
public class Consummer extends Thread {
    FootList list = null;
    public Consummer(FootList list){
        this.list = list;
    }

    @Override
    public void run() {
        this.list.eat();
    }
}


text:
package com.savarese.spatial;

import java.util.*;

/**
 * A RangeSearchTree is a spatial data structure that supports the
 * retrieval of data associated with point keys as well as the
 * searching of data that occurs within a specified range of points.
 *
 *
Note: RangeSearchTree does not implement SortedMap for range
 * searching bcause the SortedMap interface is not well-suited to
 * multi-dimensional range search trees.

 */
public interface RangeSearchTree<Coord extends Comparable<? super Coord>,
                                     P extends Point<Coord>, V>
  extends Map

{
  /**
   * Returns an iterator for mappings that are contained in the
   * rectangle defined by the given lower left-hand and upper
   * right-hand corners.  The mappings returned include those occuring
   * at points on the bounding rectangle, not just those inside.
   *
   * @param lower The lower left-hand corner of the bounding
   * rectangle.  A null value can be used to specify the region is
   * unbounded in that direction.
   * @param upper The upper right-hand corner of the bounding
   * rectangle.  A null value can be used to specify the region is
   * unbounded in that direction.
   * @return An iterator for mappings that are contained in the
   * specified rectangle.
   */
  public Iterator<Map.Entry
> iterator(P lower, P upper);

}


text:
package blue.lapis.pore.impl.entity;

import static org.spongepowered.api.data.manipulator.catalog.CatalogEntityData.BREEDABLE_DATA;

import blue.lapis.pore.converter.wrapper.WrapperConverter;

import org.apache.commons.lang3.NotImplementedException;
import org.spongepowered.api.entity.living.Ageable;

public class PoreAgeable extends PoreCreature implements org.bukkit.entity.Ageable {

    public static PoreAgeable of(Ageable handle) {
        return WrapperConverter.of(PoreAgeable.class, handle);
    }

    protected PoreAgeable(Ageable handle) {
        super(handle);
    }

    @Override
    public Ageable getHandle() {
        return (Ageable) super.getHandle();
    }

    @Override
    public int getAge() {
        return getHandle().getAgeData().age().get();
    }

    @Override
    public void setAge(int age) {
        getHandle().offer(getHandle().getAgeData().age().set(age));
    }

    @Override
    public boolean getAgeLock() {
        throw new NotImplementedException("TODO");
    }

    @Override
    public void setAgeLock(boolean lock) {
        throw new NotImplementedException("TODO");
    }

    @Override
    public void setBaby() {
        getHandle().getAgeData().baby().set(true);
    }

    @Override
    public boolean isAdult() {
        return getHandle().getAgeData().adult().get();
    }

    @Override
    public void setAdult() {
        getHandle().getAgeData().adult().set(true);
    }

    @Override
    public boolean canBreed() {
        return hasData(BREEDABLE_DATA) && getHandle().get(BREEDABLE_DATA).get().breedable().get();
    }

    @Override
    public void setBreed(boolean breed) {
        if (breed != canBreed()) {
            if (breed) {
                getHandle().offer(getHandle().getOrCreate(BREEDABLE_DATA).get().breedable().set(true));
            } else {
                getHandle().remove(BREEDABLE_DATA);
            }
        }
    }

}


text:
HOMEDIR=/home/pkuksa #${HOME}

#absolute path to the bin directory
BINDIR=${HOMEDIR}/bin

#absolute path to the SPAR home directory
#SPARPATH=${BINDIR}/SPAR_github/SPAR

# (default) absolute path to the SPAR output directory
SPARDIR=${HOMEDIR}/SPAR_out

#absolute path to pre-installed STAR, samtools, AWK, etc

# MAPPING
STAR=${BINDIR}/STAR-STAR_2.4.0k/bin/Linux_x86_64/STAR # STAR

SAMTOOLS=${BINDIR}/samtools-1.2/samtools # SAMTOOLS
#BEDTOOLS=${BINDIR}/bedtools2/bin/bedtools # BEDTOOLS
BEDTOOLS=/usr/local/bin/bedtools # BEDTOOLS

GAWK=${BINDIR}/gawk-4.1.0/gawk

# UCSC tools
BGTOBIGWIG=${BINDIR}/bedGraphToBigWig
BEDTOBIGBED=${BINDIR}/bedToBigBed
BIGWIGTOBEDGRAPH=${BINDIR}/bigWigToBedGraph

# Adapter trimming
CUTADAPT=${BINDIR}/cutadapt-1.8.1/bin/cutadapt

#absolute path to the STAR genome index
genomeDir=${HOMEDIR}/datasets/hg19/star_2.4.0k/  # STAR genome index

#hg 19 chromosome information file
#chromInfo=${SPARPATH}/annot/chromInfo.txt

#mapping parameters for STAR
maxMismatchCnt=0 # maximum number of genomic mismatches
maxMapCnt=100 # maximum number of places a read can map to
minMappedLength=14 # minimum *mapped* length

RSCRIPT=/usr/local/bin/Rscript

function printT
{
  echo "`date +'%b %d %H:%M:%S'` ..... $1"
}


text:
// © Xavalon. All rights reserved.

using MonoDevelop.Ide.Gui;
using Xavalon.XamlStyler.Core.Options;

namespace Xavalon.XamlStyler.Mac.Services.XamlFormatting
{
    public interface IXamlFormattingService
    {
        bool TryFormatXamlDocument(Document document, IStylerOptions stylerOptions);

        bool TryFormatXaml(ref string xamlText, IStylerOptions stylerOptions);

        bool IsDocumentFormattable(Document document);
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">

Gen Pass!


text:
class Registrant < ApplicationRecord
  include Eligibility
  include Representable
  include CachedModel
  extend OrderAsSpecified

  after_save :touch_members
  attr_accessor :skip_organization_membership_checking
  after_commit :update_organization_membership_status, if: proc { EventConfiguration.singleton.organization_membership_config.automated_checking? }

  has_paper_trail meta: { registrant_id: :id, user_id: :user_id }

  with_options dependent: :destroy do
    has_one :contact_detail, autosave: true, inverse_of: :registrant
    has_one :organization_membership, inverse_of: :registrant
    has_one :standard_skill_routine
  end

  # may move into another object
  with_options dependent: :destroy do
    has_many :registrant_best_times, inverse_of: :registrant
    has_many :registrant_choices, inverse_of: :registrant
    has_many :registrant_event_sign_ups, inverse_of: :registrant
    has_many :registrant_expense_items, autosave: true
    has_many :payment_details, -> { includes :payment }
    has_many :additional_registrant_accesses
    has_many :registrant_group_members
    has_many :songs
    has_many :volunteer_choices, inverse_of: :registrant
  end

  has_many :signed_up_events, -> { where(signed_up: true) }, class_name: 'RegistrantEventSignUp'

  # THROUGH
  has_many :event_choices, through: :registrant_choices
  has_many :events, through: :event_choices
  has_many :categories, through: :events
  has_many :volunteer_opportunities, through: :volunteer_choices

  has_many :expense_items, through: :registrant_expense_items, source: :line_item, source_type: "ExpenseItem"

  has_many :payments, through: :payment_details
  has_many :refund_details, through: :payment_details
  has_many :refunds, through: :refund_details

  has_many :registrant_groups, through: :registrant_group_members

  # For event competitions/results
  has_many :members, dependent: :destroy
  has_many :competitors, through: :members
  has_many :competitions, through: :competitors
  has_many :competition_wheel_sizes, dependent: :destroy
  has_many :results, through: :competitors

  belongs_to :default_wheel_size, class_name: "WheelSize", foreign_key: :wheel_size_id, optional: true
  belongs_to :user

  accepts_nested_attributes_for :contact_detail
  accepts_nested_attributes_for :organization_membership
  accepts_nested_attributes_for :registrant_choices
  accepts_nested_attributes_for :registrant_event_sign_ups
  accepts_nested_attributes_for :registrant_best_times, reject_if: :no_best_time_entered, allow_destroy: true
  accepts_nested_attributes_for :volunteer_choices

  before_create :create_associated_required_expense_items

  # always present validations
  before_validation :set_bib_number, on: :create
  validates :bib_number, presence: true
  validates :bib_number, uniqueness: true
  validates :registrant_type, inclusion: { in: RegistrantType::TYPES }, presence: true
  validates :ineligible, :deleted, inclusion: { in: [true, false] } # because it's a boolean
  validate :no_payments_when_deleted
  before_validation :set_access_code
  validates :access_code, presence: true

  # Wizard status helpers

  # Status progression:
  #  'blank' - No data has been saved
  #  'base_details' - We have entered the base details
  #  'events' - Has entered the events
  #  'contact_details' - Has entered mailing address & signed waiver (if applicable)
  #  'active' - Has entered all data
  def self.statuses
    ["blank", "base_details", "events", "contact_details", "active"]
  end
  validates :status, inclusion: { in: statuses }, presence: true

  # Base details

  # necessary for all registrant types
  before_validation :set_sorted_last_name
  validates :first_name, :last_name, :sorted_last_name, presence: true
  validates :user, presence: true

  # necessary for comp/non-comp only (not spectators):
  with_options if: :comp_noncomp_past_step_1? do
    validates :birthday, :gender, presence: true
    validates :gender, inclusion: { in: %w[Male Female], message: "%{value} must be either 'Male' or 'Female'" }
    validate  :gender_present
    before_validation :set_age
    validates :age, presence: true
  end

  with_options if: %i[registrants_should_specify_default_wheel_size? comp_noncomp_past_step_1?] do
    before_validation :set_default_wheel_size
    validates :default_wheel_size, presence: true
    validate :check_default_wheel_size_for_age
  end

  # events
  validate :choices_combination_valid, if: :past_step_2?

  # waiver
  validates :online_waiver_acceptance, acceptance: { accept: true }, if: :needs_waiver?
  validates :rules_accepted, acceptance: { accept: true }, if: :needs_rules_accepted?

  # contact info
  validates_associated :contact_detail, if: :validated?
  validates_associated :registrant_best_times, if: :past_step_2?

  mount_uploader :medical_certificate, PdfOrImageUploader
  before_save :set_medical_certificate_upload_date

  # Expense items/LineItems
  validates_associated :registrant_expense_items
  validate :has_necessary_items?, if: :validated?

  # Organization Membership
  delegate :member_number, :system_member_number, :manual_member_number, :manually_confirmed?, :system_confirmed?, :system_status, to: :organization_membership, prefix: true, allow_nil: true
  validate :check_organization_membership, if: :needs_organization_membership?

  scope :active_or_incomplete, -> { not_deleted.order(:bib_number) }
  scope :active, -> { where(status: "active").active_or_incomplete }
  scope :started, -> { where.not(status: "blank").active_or_incomplete }
  scope :not_deleted, -> { where(deleted: false) }

  def validated?
    status == "active"
  end

  def to_param
    bib_number.to_s if persisted?
  end

  RegistrantType::TYPES.each do |reg_type|
    # def competitor?
    #   registrant_type == 'competitor'
    # end
    define_method "#{reg_type}?" do
      registrant_type == reg_type
    end

    # def self.competitor
    #   where(registrant_type: 'competitor')
    # end
    define_singleton_method reg_type.to_s do
      where(registrant_type: reg_type)
    end
  end

  def registrant_type_model
    RegistrantType.for(registrant_type)
  end

  # uses the CachedSetModel feature to give a key for this registrant's competitors
  def members_cache_key
    Member.cache_key_for_set(id)
  end

  # updates the members, which update the competitors, if this competitor has changed (like their age, for example)
  def touch_members
    members.each do |mem|
      mem.touch
    end
  end

  # TODO: This should be extracted into a form helper?
  def self.select_box_options
    active.competitor.map { |reg| [reg.with_id_to_s, reg.id] }
  end

  # TODO: This should be extracted into a form helper?
  def self.all_select_box_options
    started.map { |reg| [reg.with_id_to_s, reg.id] }
  end

  # ##########################################################
  # TODO: Extract the following 4 methods into a collaborator
  # #########################################################
  #
  # Add a system-managed RegistrantExpenseItem, if it doesn't already exist
  def build_registration_item(reg_item)
    unless reg_item.nil? || has_expense_item?(reg_item)
      registrant_expense_items.system_managed.build(line_item: reg_item)
    end
  end

  # Remove a system-managed RegistrantExpenseItem, if it exists
  def remove_registration_item(reg_item)
    unless reg_item.nil? || !has_expense_item?(reg_item)
      # registrant_expense_items.system_managed.find_by(expense_item_id: reg_item.id).destroy
      # use `.to_a` here so that we can use `mark_for_destruction` and it will be destroy on save
      item_to_remove = registrant_expense_items.to_a.find { |rei| rei.system_managed? && rei.line_item == reg_item }
      item_to_remove.mark_for_destruction
    end
  end

  # for use when overriding the default system-managed reg_item
  def set_registration_item_expense(expense_item, lock = true)
    return true if reg_paid?

    curr_rei = registration_item

    if curr_rei.nil?
      curr_rei = build_registration_item(expense_item)
    end
    return false if curr_rei.nil?
    return true  if curr_rei.line_item == expense_item && curr_rei.persisted?
    return true  if curr_rei.locked && !lock

    curr_rei.line_item = expense_item
    curr_rei.locked = lock
    curr_rei.save
  end

  # determine if this registrant has an unpaid (or paid) version of this expense item
  def has_expense_item?(expense_item)
    all_line_items.include?(expense_item)
  end

  # ##########################################################
  # END Extraction
  # ##########################################################

  def matching_competition_in_event(event)
    competitors.active.find { |competitor| competitor.event == event }.try(:competition)
  end

  def create_associated_required_expense_items
    RequiredExpenseItemCreator.new(self).create
  end

  def registration_item
    all_reg_items = RegistrationCost.all_registration_expense_items
    registrant_expense_items.system_managed.find_by(line_item: all_reg_items)
  end

  def wheel_size_id_for_event(event)
    competition_wheel_sizes.find { |cws| cws.event_id == event.id }.try(:wheel_size_id) || wheel_size_id
  end

  # Public: Is this registrant young enough that they may need
  # to choose a wheel size?
  #
  # return a boolean
  def young_enough_to_choose_wheel_size?
    age <= EventConfiguration.singleton.wheel_size_configuration_max_age
  end

  def external_id
    bib_number
  end

  def minor?
    return false unless EventConfiguration.singleton.request_responsible_adult?
    return false if spectator?

    age < 18
  end

  def events_with_music_allowed
    signed_up_events.joins(:event).includes(:event).merge(Event.music_uploadable).map(&:event)
  end

  # for displaying on the Registrant#Summary page
  # if this user is signed up for an event category which is now "warning" flagged
  def event_warnings
    warned_sign_ups = signed_up_events.joins(:event_category).includes(:event, :event_category).merge(EventCategory.with_warnings)
    warned_sign_ups.map { |rei| "#{rei.event} - #{rei.event_category.name} Category" }
  end

  def has_standard_skill?
    signed_up_events.where(event: Event.standard_skill_events).any?
  end

  def name
    printed_name = full_name
    printed_name += " (incomplete)" unless validated?
    display_eligibility(printed_name, ineligible?)
  end

  def full_name
    first_name + " " + last_name
  end

  def email
    contact_detail.try(:email).try(:presence) || user.email
  end

  delegate :country_code, :country, :state, :club, to: :contact_detail, allow_nil: true

  # return an object describing the best time entered by this registrant
  def best_time(event)
    registrant_best_times.find_by(event: event) || registrant_choices.joins(:event_choice).merge(EventChoice.where(cell_type: "best_time", event: event)).first
  end

  def to_s
    name + (deleted ? " (deleted)" : "")
  end

  def with_id_to_s
    "##{bib_number} - #{self}"
  end

  ###### Expenses ##########

  # Indicates that this registrant has paid their registration_fee
  def reg_paid?(include_pending: true)
    return true if spectator?

    Rails.cache.fetch("/registrant/#{id}-#{updated_at}/reg_paid/include_pending/#{include_pending}") do
      registration_cost_items = RegistrationCost.all_registration_expense_items
      if include_pending
        paid_or_pending_line_items
      else
        paid_line_items
      end.any? { |item| registration_cost_items.include?(item) }
    end
  end

  # return a list of _ALL_ of the line_items for this registrant
  #  PAID FOR or NOT
  def all_line_items
    owing_line_items + paid_line_items + pending_line_items
  end

  def amount_pending
    Rails.cache.fetch("/registrants/#{id}-#{updated_at}/amount_pending_money") do
      pending_details.inject(0.to_money) { |total, item| total + item.cost }
    end
  end

  def amount_owing
    Rails.cache.fetch("/registrants/#{id}-#{updated_at}/amount_owing_money") do
      registrant_expense_items.inject(0.to_money) { |total, item| total + item.total_cost }
    end
  end

  def expenses_total
    amount_owing + amount_paid + amount_pending
  end

  # returns a list of line_items that this registrant hasn't paid for
  # INCLUDING the registration cost
  def owing_line_items
    registrant_expense_items.map { |eid| eid.line_item }
  end

  def owing_registrant_expense_items
    registrant_expense_items
  end

  # returns a list of paid-for line_items
  def paid_line_items
    paid_details.map { |pd| pd.line_item }
  end

  def pending_line_items
    pending_details.map { |pd| pd.line_item }
  end

  def paid_or_pending_line_items
    paid_line_items + pending_line_items
  end

  def paid_or_pending_details
    payment_details.completed_or_offline.not_refunded.clone
  end

  def paid_details
    payment_details.completed.not_refunded.clone
  end

  def pending_details
    payment_details.offline_pending.not_refunded.clone
  end

  def amount_paid
    Rails.cache.fetch("/registrants/#{id}-#{updated_at}/amount_paid_money") do
      paid_details.inject(0.to_money) { |total, item| total + item.cost }
    end
  end

  ############# Events Selection ########

  def active_competitors(event)
    competitors.includes(competition: :event).active.joins(:competition).where("competitions.event_id = ?", event)
  end

  def active_competitor(event)
    active_competitors(event).first
  end

  delegate :unpaid_warnings, :describe_event, :describe_event_hash, :describe_additional_selection, to: :presenter

  def presenter
    RegistrantPresenter.new(self)
  end

  def expense_item_is_free(expense_item)
    ExpenseItemFreeChecker.new(self, expense_item).expense_item_is_free?
  end

  def create_organization_membership_record
    organization_membership || create_organization_membership
  end

  def organization_membership_confirmed?
    organization_membership.try(:organization_membership_confirmed?)
  end

  # Return a hash of categories, with values of a hash of event names
  # each event has a hash of details
  # Example:
  # {
  #   "Freestyle" => {
  #     "Individual" => {
  #       competition_name: "Individual",
  #       team_name: nil,
  #       additional_details: nil,
  #       confirmed: false,
  #       status: nil, # always 'nil' when !confirmed
  #     },
  #     "Pairs" =>
  #     {
  #       competition_name: "Novice Pairs",
  #       team_name: nil,
  #       additional_details: "Partner: Scott W",
  #       confirmed: true,
  #       status: "active", # possible values: ["active", "withdrawn", "dns", "not_qualified"]
  #     },
  #   },
  #   "Track" => {
  #     "100m" =>
  #     {
  #       competition_name: "100m",
  #       team_name: nil,
  #       additional_details: nil,
  #       confirmed: false,
  #       status: nil,
  #     }
  #   },
  # }
  def assigned_event_categories
    results = {}
    signed_up_events.includes(event: [event_choices: [:translations], category: [:translations]]).find_each do |registrant_sign_up|
      category_hash = results[registrant_sign_up.event.category.to_s] ||= {}
      event_hash = category_hash[registrant_sign_up.event.to_s] ||= {}
      event_hash[:competition_name] = registrant_sign_up.event.to_s
      event_hash[:team_name] = registrant_sign_up.event_category_name
      event_hash[:additional_details] = describe_additional_selection(registrant_sign_up.event)
      event_hash[:confirmed] = false
      event_hash[:status] = nil
    end

    competitors.includes(competition: [event: [category: [:translations]]]).find_each do |competitor|
      category_hash = results[competitor.event.category.to_s] ||= {}
      event_hash = category_hash[competitor.event.to_s] ||= {}
      event_hash[:competition_name] = competitor.competition.award_title
      event_hash[:team_name] = competitor.team_name
      event_hash[:age_group] = competitor.age_group_entry_description
      event_hash[:additional_details] = nil
      event_hash[:confirmed] = true
      event_hash[:status] = competitor.status
    end

    results
  end

  ############# Events Selection ########
  def has_event_in_category?(category)
    category.events.any? { |event| has_event?(event) }
  end

  # does this registrant have this event checked off?
  def has_event?(event)
    @has_event ||= {}
    @has_event[event] ||= signed_up_events.where(event_id: event.id).any?
  end

  ############ MEDICAL CERTIFICATE #############
  def medical_questionnaire_filled_out
    medical_questionnaire_filled_out_at.present?
  end

  def medical_questionnaire_filled_out=(value)
    if ActiveModel::Type::Boolean.new.cast(value)
      self.medical_questionnaire_filled_out_at ||= Time.current
    else
      self.medical_questionnaire_filled_out_at = nil
    end
  end

  def medical_questionnaire_attest_all_no
    medical_questionnaire_attest_all_no_at.present?
  end

  def medical_questionnaire_attest_all_no=(value)
    if ActiveModel::Type::Boolean.new.cast(value)
      self.medical_questionnaire_attest_all_no_at ||= Time.current
    else
      self.medical_questionnaire_attest_all_no_at = nil
    end
  end

  # Return true if they have submitted the required questions/certificate
  def medical_documentation_complete?
    return true if medical_certificate.present?

    if spectator? || age >= 18
      medical_certificate.present?
    else
      medical_questionnaire_filled_out && medical_questionnaire_attest_all_no
    end
  end

  private

  # Internal: Set the bib number of this registrant
  #
  def set_bib_number
    if bib_number.nil?
      matching_number = BibNumberFinder::RegistrantMatch.new(self, user).matching_registrant
      self.bib_number = matching_number || registrant_type_model.next_available_bib_number
    end
  end

  def set_age
    start_date = EventConfiguration.singleton.effective_age_calculation_base_date
    if start_date.nil? || birthday.nil?
      self.age = 99
    else
      self.age = age_at_event_date(start_date)
    end
  end

  # is the current status past the desired status
  def status_is_active?(desired_status)
    self.class.statuses.index(status) >= self.class.statuses.index(desired_status)
  end

  # this registrant is on a step subsequent to the initial step
  def past_step_1?
    status_is_active?("base_details")
  end

  # Never true for a spectator
  # Have we entered the base details?
  def comp_noncomp_past_step_1?
    !spectator? && status_is_active?("base_details")
  end

  # Never true for a spectator
  # have we entered events
  def past_step_2?
    !spectator? && status_is_active?("events")
  end

  def needs_waiver?
    EventConfiguration.singleton.online_waiver? && status_is_active?("contact_details")
  end

  def needs_rules_accepted?
    EventConfiguration.singleton.accept_rules? && status_is_active?("contact_details")
  end

  def needs_organization_membership?
    return false if spectator?
    return false unless EventConfiguration.singleton.organization_membership_config.active_membership_required?

    status_is_active?("active")
  end
  # end Wizard

  # returns true if it should be rejected
  # but returns false if it exists, and needs to be cleared.
  def no_best_time_entered(attributes)
    if attributes['source_location'].blank? && attributes['formatted_value'].blank?
      if attributes['id'].present?
        attributes['_destroy'] = 1
        false
      else
        true
      end
    else
      false
    end
  end

  # ####################################
  # Event Choices Validation
  # ####################################
  def choices_combination_valid
    ChoicesValidator.new(self).validate
  end

  # Queue a job to query the IUF/USA db for membership information
  def update_organization_membership_status
    return if skip_organization_membership_checking
    return unless previous_changes.key?(:last_name) || previous_changes.key?(:first_name) || previous_changes.key?(:birthday)

    UpdateOrganizationMembershipStatusWorker.perform_async(id)
  end

  def set_access_code
    self.access_code ||= SecureRandom.hex(4)
  end

  def age_at_event_date(event_date)
    if (birthday.month < event_date.month) || (birthday.month == event_date.month && birthday.day <= event_date.day)
      event_date.year - birthday.year
    else
      (event_date.year - 1) - birthday.year
    end
  end

  def has_necessary_items?
    expense_groups_required = registrant_type_model.required_item_from_expense_groups(age)

    expense_groups_required.each do |expense_group|
      if all_line_items.none? { |line_item| line_item.try(:expense_group) == expense_group }
        errors.add(:base, "You must choose an item from #{expense_group}")
      end
    end
  end

  def gender_present
    if gender.blank?
      errors.add(:gender_male, "") # Cause the label to be highlighted
      errors.add(:gender_female, "") # Cause the label to be highlighted
    end
  end

  def set_sorted_last_name
    self.sorted_last_name = ActiveSupport::Inflector.transliterate(last_name).downcase if last_name
  end

  def no_payments_when_deleted
    if paid_details.count.positive? && deleted?
      errors.add(:base, "Cannot delete a registration which has completed payments (refund them before deleting the registrant)")
    end
  end

  # indicate whether this registrant needs to set a default_wheel_size
  def registrants_should_specify_default_wheel_size?
    EventConfiguration.singleton.registrants_should_specify_default_wheel_size?
  end

  def set_default_wheel_size
    if default_wheel_size.nil?
      if young_enough_to_choose_wheel_size?
        self.default_wheel_size = WheelSize.find_by(description: "20\" Wheel")
      else
        self.default_wheel_size = WheelSize.find_by(description: "24\" Wheel")
      end
    end
  end

  def check_default_wheel_size_for_age
    max_config_age = EventConfiguration.singleton.wheel_size_configuration_max_age
    unless young_enough_to_choose_wheel_size?
      if default_wheel_size&.description != "24\" Wheel"
        errors.add(:base, "You must choose a wheel size of 24\" if you are > #{max_config_age} years old")
      end
    end
  end

  def check_organization_membership
    return if organization_membership.organization_membership_confirmed?

    organization_config = EventConfiguration.singleton.organization_membership_config
    errors.add(:base, "Must have a current #{organization_config.title} membership")
  end

  def set_medical_certificate_upload_date
    return unless changes.key?(:medical_certificate)
    return if medical_certificate.blank?

    self.medical_certificate_uploaded_at ||= Time.current
  end
end


text:
import React from 'react';

class FooterComponent extends React.Component {
    render() {
    return (

          Shameless plug to my twitter...

    );
  }
}
export default FooterComponent;


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

{% include "overlay.html" %}
{% from "overlay.html" import create_overlay %}

{% block head %}
<title>General Settings</title>

{% endblock %}
{% block content %}

Settings

  <button type='submit' class="swipebutton fixedbutton" id='user_profile' onclick="window.location.href='/user_profile'">User Profile</button>
  <button type='submit' class="swipebutton fixedbutton" id='tool_settings' onclick="window.location.href='/tool_settings'">Tool Settings</button>
  <button type='submit' class="swipebutton fixedbutton" id='manage_db' onclick="window.location.href='/manage_db'">Manage Database</button>
  <button type='submit' class="swipebutton fixedbutton" id='reserved1' onclick="window.location.href='/user_settings'" disabled>Reserved</button>
  <button type='submit' class="swipebutton fixedbutton" id='reserved2' onclick="window.location.href='/user_settings'" disabled>Reserved</button>
  <button type='submit' class="swipebutton fixedbutton" id='home' onclick="window.location.href='/'"></button>

{% endblock %}


text:
describe 'concurrent consumers', integration: true do
  before(:context)  { $consumer = ConcurrentConsumer }

  it 'process messages concurrently' do
    3.times { Tiki::Torch.publish $consumer.topic, sleep_time: 0.3 }
    $lines.wait_for_size 6

    expect($lines.all).to eq %w{ started started started ended ended ended }
  end
end


text:
using namespace std;

struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode(int x): val(x), left(NULL), right(NULL) {}
};

class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if (root == NULL || p == NULL || q == NULL) {
            return NULL;
        }
        else if (p -> val > root -> val && q -> val > root -> val) {
            return lowestCommonAncestor(root -> right, p, q);
        }
        else if (p -> val < root -> val && q -> val < root -> val) {
            return lowestCommonAncestor(root -> left, p, q);
        }
        return root;
    }
};


text:
JSMIX [![Build Status](https://travis-ci.org/khayll/jsmix.svg?branch=master)](https://travis-ci.org/khayll/jsmix)
========
A simple tool to easily map data onto model objects. In other words this tool helps you with deserializing data into full-fledged model objects with methods. My aim was to have a simple to use tool, that you can use to mix methods with data after you got your JSON back from a REST API.

This is a WIP project, but it's already usable. There's no minified version yet, that should be almost the next thing I'll do.

## How to use
Here's how it works in real life. First of course you need to include JSMix.

    <script type="text/javascript" src="jsmix.js"></script>

Use or create your model on the client side:

	var Employee = function() {
	}

	Employee.prototype.getName = function() {
		return this.firstName + ' ' + this.lastName;
	}

Then if you have a REST service "getAnEmployee", that returns a JSON like this:

	{
		"epmloyee": {
			"firstName": "John",
			"lastName": "Doe",
			"salary": 100000,
			"age": 33
		}
	}

you could say in AngularJS (for example):

	http.get("/getAnEmployee").then( function(result) {
		console.log(
			JSMix(result).withObject(Employee.prototype, "employee").build().getName()
		);
	});

Which will then log "John Doe" for you.

## Parameter explained

A slightly more complex example would look like:

	var result = JSMix(data)
		.withObject(Employee.prototype, "employees")
		.withObject(Pet.prototype, "employees.pet")
		.build();

	//now result has every model class mixed in
	console.log(result.epmloyees[1].getName());

 So the parameter to the JSMix(data) call, data, could be a JSON string, or an object.
 The build() just returns the object with all classes mixed.
 The withObject(prototype, path) call is the one to define class mappings.
 Here "path" can be any chain of nested objects separated with a dot. For example in this case "epmloyees.pet".
 JSMix will find out if an object is an array, and will recursively apply the remaining part of the path to every item in it.
 You can also use "*" in the path, and this will apply the remaining path to every item in the object (even if it's not an array).

     //this recursively applies the same prototype 3 levels deep
     JSMix(data).withObject(Comparable.prototype, "*.*.*").build();

 You can use playground.html as a tutorial, or just to play around with jsmix.


text:
using System;
using System.Numerics;
using FluentCassandra.Types;
using Xunit;

namespace FluentCassandra.Integration.Tests.TypesToDatabase
{

	public class IntegerTypeTest : IUseFixture<CassandraDatabaseSetupFixture>, IDisposable
	{
		private CassandraContext _db;

		public void SetFixture(CassandraDatabaseSetupFixture data)
		{
			var setup = data.DatabaseSetup();
			_db = setup.DB;
		}

		public void Dispose()
		{
			_db.Dispose();
		}

		public const string FamilyName = "StandardIntegerType";
		public const string TestKey = "Test1";

		[Fact]
		public void Save_BigInteger()
		{
			// arrange
			var family = _db.GetColumnFamily<IntegerType>(FamilyName);
			BigInteger expected = 100;

			// act
			family.InsertColumn(TestKey, expected, Math.PI);
			var actual = family.GetColumn(TestKey, expected);

			// assert
			Assert.Equal(expected, (BigInteger)actual.ColumnName);
		}

		[Fact]
		public void Save_Byte()
		{
			// arrange
			var family = _db.GetColumnFamily<IntegerType>(FamilyName);
			byte expected = 100;

			// act
			family.InsertColumn(TestKey, expected, Math.PI);
			var actual = family.GetColumn(TestKey, expected);

			// assert
			Assert.Equal(expected, (byte)actual.ColumnName);
		}

		[Fact]
		public void Save_Int16()
		{
			// arrange
			var family = _db.GetColumnFamily<IntegerType>(FamilyName);
			short expected = 100;

			// act
			family.InsertColumn(TestKey, expected, Math.PI);
			var actual = family.GetColumn(TestKey, expected);

			// assert
			Assert.Equal(expected, (short)actual.ColumnName);
		}

		[Fact]
		public void Save_Int32()
		{
			// arrange
			var family = _db.GetColumnFamily<IntegerType>(FamilyName);
			int expected = 100;

			// act
			family.InsertColumn(TestKey, expected, Math.PI);
			var actual = family.GetColumn(TestKey, expected);

			// assert
			Assert.Equal(expected, (int)actual.ColumnName);
		}

		[Fact]
		public void Save_Int64()
		{
			// arrange
			var family = _db.GetColumnFamily<IntegerType>(FamilyName);
			long expected = 100;

			// act
			family.InsertColumn(TestKey, expected, Math.PI);
			var actual = family.GetColumn(TestKey, expected);

			// assert
			Assert.Equal(expected, (long)actual.ColumnName);
		}

		[Fact]
		public void Save_SByte()
		{
			// arrange
			var family = _db.GetColumnFamily<IntegerType>(FamilyName);
			sbyte expected = 100;

			// act
			family.InsertColumn(TestKey, expected, Math.PI);
			var actual = family.GetColumn(TestKey, expected);

			// assert
			Assert.Equal(expected, (sbyte)actual.ColumnName);
		}

		[Fact]
		public void Save_UInt16()
		{
			// arrange
			var family = _db.GetColumnFamily<IntegerType>(FamilyName);
			ushort expected = 100;

			// act
			family.InsertColumn(TestKey, expected, Math.PI);
			var actual = family.GetColumn(TestKey, expected);

			// assert
			Assert.Equal(expected, (ushort)actual.ColumnName);
		}

		[Fact]
		public void Save_UInt32()
		{
			// arrange
			var family = _db.GetColumnFamily<IntegerType>(FamilyName);
			uint expected = 100;

			// act
			family.InsertColumn(TestKey, expected, Math.PI);
			var actual = family.GetColumn(TestKey, expected);

			// assert
			Assert.Equal(expected, (uint)actual.ColumnName);
		}

		[Fact]
		public void Save_UInt64()
		{
			// arrange
			var family = _db.GetColumnFamily<IntegerType>(FamilyName);
			ulong expected = 100;

			// act
			family.InsertColumn(TestKey, expected, Math.PI);
			var actual = family.GetColumn(TestKey, expected);

			// assert
			Assert.Equal(expected, (ulong)actual.ColumnName);
		}
	}
}


text:
using System;
using System.Data.Entity;
using System.Linq;
using SmartElk.Antler.Core.Common.CodeContracts;
using SmartElk.Antler.Core.Domain;
using SmartElk.Antler.EntityFramework.Internal;

namespace SmartElk.Antler.EntityFramework
{
    public class EntityFrameworkRepository<TEntity>: IRepository<TEntity> where TEntity: class
    {
        private readonly DataContext _context;
        public EntityFrameworkRepository(DataContext context)
        {
            Requires.NotNull(context, "context");
            _context = context;
        }

        public IDbSet<TEntity> DbSet
        {
            get { return _context.Set<TEntity>();}
        }

        public IQueryable<TEntity> AsQueryable()
        {
            return DbSet.AsQueryable();
        }

        public TEntity GetById<TId>(TId id)
        {
            return DbSet.Find(id);
        }

        public TEntity Insert(TEntity entity)
        {
            Requires.NotNull(entity, "entity");

            _context.Entry(entity).State = EntityState.Added;
            _context.SaveChanges();

            return entity;
        }

        public TId Insert<TId>(TEntity entity)
        {
            throw new NotSupportedException();
        }

        public TEntity Update(TEntity entity)
        {
            Requires.NotNull(entity, "entity");

            _context.Entry(entity).State = EntityState.Modified;
            _context.SaveChanges();

            return entity;
        }

        public void Delete(TEntity entity)
        {
            Requires.NotNull(entity, "entity");

            _context.Entry(entity).State = EntityState.Deleted;
            _context.SaveChanges();
        }

        public void Delete<TId>(TId id)
        {
            var entity = GetById(id);
            if (entity != null)
            {
                _context.Entry(entity).State = EntityState.Deleted;
                _context.SaveChanges();
            }
        }
    }
}


text:
<?php
namespace api\modules\v1\controllers;

use common\models\LoginForm;
use  common\models\User;
use frontend\models\ContactForm;
use yii\rest\Controller;
use Yii;
use yii\web\Response;

class UserController extends Controller
{
    function actionIndex()
    {
         $token = Yii::$app->request->get('access_token');
        $model = User::findIdentityByAccessToken($token);
        return $model;
    }

    public function actionLogin()
    {
        $model = new LoginForm();
        if ($model->load(Yii::$app->getRequest()->getBodyParams(), '') && $model->login()) {
            $now =  new \DateTime();
            $today = $now->format('Y-m-d H:i:s');
            $user = User::findOne(Yii::$app->user->id);
            $user->logged_in_ip = Yii::$app->request->getUserIP();
            $user->logged_in_at = $today;
            $user->generateAuthKey();
            $user->save();
            if($user){
                return [
                    'access_token' => Yii::$app->user->identity->getAuthKey(),
                    'lastLogin' => $today,
                    'ip' => $user->logged_in_ip,
                ];
            }else{
                throw  $user->errors;
            }
        } else {
            $model->validate();
            return $model;
        }
    }

/*    public function actionLogin()
    {
        $post = Yii::$app->request->post();
        $model = User::findOne(["username" => $post["username"]]);
        if (empty($model)) {
            throw new \yii\web\NotFoundHttpException('User not found');
        }
        if ($model->validatePassword($post["password"])) {
            $model->logged_in_at= Yii::$app->formatter->asTimestamp(date_create());
            $model->save(false);
            return $model; //return whole user model including auth_key or you can just return $model["auth_key"];
        } else {
            throw new \yii\web\ForbiddenHttpException();
        }
    }*/

    public function actionLogout()
    {
        if (Yii::$app->user->logout()) {
            return ['success' => true];
        }
    }

    public function actionDashboard()
    {
        if (!Yii::$app->user->isGuest) {
            $response = [
                'username' => Yii::$app->user->identity->username,
                'access_token' => Yii::$app->user->identity->getAuthKey(),
            ];
            return $response;
        } else {
            return [
                'error'
            ];
        }

    }

    public function actionContact()
    {
        $model = new ContactForm();
        if ($model->load(Yii::$app->getRequest()->getBodyParams(), '') && $model->validate()) {
            if ($model->sendEmail(Yii::$app->params['adminEmail'])) {
                $response = [
                    'flash' => [
                        'class' => 'success',
                        'message' => 'Thank you for contacting us. We will respond to you as soon as possible.',
                    ]
                ];
            } else {
                $response = [
                    'flash' => [
                        'class' => 'error',
                        'message' => 'There was an error sending email.',
                    ]
                ];
            }
            return $response;
        } else {
            $model->validate();
            return $model;
        }
    }

}


text:
/**
 *     This code was auto-generated by a Codezu.
 *
 *     Changes to this file may cause incorrect behavior and will be lost if
 *     the code is regenerated.
 */
package com.mozu.api.urls.commerce.carts;

import org.joda.time.DateTime;

import com.mozu.api.MozuUrl;
import com.mozu.api.utils.UrlFormatter;

public class ExtendedPropertyUrl
{

	/**
	 * Get Resource Url for GetExtendedProperties
	 * @return   String Resource Url
	 */
	public static MozuUrl getExtendedPropertiesUrl()
	{
		UrlFormatter formatter = new UrlFormatter("/api/commerce/carts/current/extendedproperties");
		return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ;
	}

	/**
	 * Get Resource Url for AddExtendedProperties
	 * @return   String Resource Url
	 */
	public static MozuUrl addExtendedPropertiesUrl()
	{
		UrlFormatter formatter = new UrlFormatter("/api/commerce/carts/current/extendedproperties");
		return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ;
	}

	/**
	 * Get Resource Url for UpdateExtendedProperty
	 * @param key Key used for metadata defined for objects, including extensible attributes, custom attributes associated with a shipping provider, and search synonyms definitions. This content may be user-defined depending on the object and usage.
	 * @param responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. For example, ) returns only the  and  items inside the  array of the specified product.This paramter should only be used to retrieve data. Attempting to update data using this parmater may cause data loss.
	 * @param upsert Any set of key value pairs to be stored in the extended properties of a cart.
	 * @return   String Resource Url
	 */
	public static MozuUrl updateExtendedPropertyUrl(String key, String responseFields, Boolean upsert)
	{
		UrlFormatter formatter = new UrlFormatter("/api/commerce/carts/current/extendedproperties/{key}?upsert={upsert}&responseFields={responseFields}");
		formatter.formatUrl("key", key);
		formatter.formatUrl("responseFields", responseFields);
		formatter.formatUrl("upsert", upsert);
		return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ;
	}

	/**
	 * Get Resource Url for UpdateExtendedProperties
	 * @param upsert Any set of key value pairs to be stored in the extended properties of a cart.
	 * @return   String Resource Url
	 */
	public static MozuUrl updateExtendedPropertiesUrl(Boolean upsert)
	{
		UrlFormatter formatter = new UrlFormatter("/api/commerce/carts/current/extendedproperties?upsert={upsert}");
		formatter.formatUrl("upsert", upsert);
		return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ;
	}

	/**
	 * Get Resource Url for DeleteExtendedProperties
	 * @return   String Resource Url
	 */
	public static MozuUrl deleteExtendedPropertiesUrl()
	{
		UrlFormatter formatter = new UrlFormatter("/api/commerce/carts/current/extendedproperties");
		return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ;
	}

	/**
	 * Get Resource Url for DeleteExtendedProperty
	 * @param key
	 * @return   String Resource Url
	 */
	public static MozuUrl deleteExtendedPropertyUrl(String key)
	{
		UrlFormatter formatter = new UrlFormatter("/api/commerce/carts/current/extendedproperties/{key}");
		formatter.formatUrl("key", key);
		return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ;
	}

}


text:
require "spec_helper"
require "robinhood"

describe "Robinhood.define" do
  it "executes a process iteratively until it ends" do
    queue = [1, 2]

    Robinhood.define do
      process :test do
        queue.pop
      end
    end

    Robinhood.run(background: true)

    sleep(3)
    expect(queue).to be_empty
  end

  it "allows setting an arbitrary throttle" do
    throttle = 0.01

    calls = []

    method_call = Proc.new do
      calls << Time.now
    end

    Robinhood.define do
      process :test, throttle: throttle do
        method_call.call
      end
    end

    Robinhood.run(background: true)

    sleep(throttle * 5)

    calls.each_with_index do |call, index|
      if (index + 1) < calls.length
        expect(calls[index + 1] - call).to be > throttle
      end
    end
  end
end


text:
package org.apereo.cas.adaptors.radius;

import org.apereo.cas.util.CollectionUtils;

import lombok.val;
import net.jradius.dictionary.Attr_ClientId;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;

import javax.security.auth.login.FailedLoginException;
import java.util.Optional;

import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;

/**
 * This is {@link RadiusUtilsTests}.
 *
 * @author Misagh Moayyed
 * @since 5.3.0
 */
@Tag("Radius")
public class RadiusUtilsTests {
    @Test
    public void verifyActionPasses() throws Exception {
        val server = mock(RadiusServer.class);
        val attribute = new Attr_ClientId("client_id");
        val response = new CasRadiusResponse(100, 100, CollectionUtils.wrapList(attribute));
        when(server.authenticate(anyString(), anyString(), any())).thenReturn(response);
        val result = RadiusUtils.authenticate("casuser", "Mellon",
            CollectionUtils.wrapList(server), true, false, Optional.empty());
        assertTrue(result.getKey());
        assertTrue(result.getRight().isPresent());
    }

    @Test
    public void verifyActionFailsWithFailOver() throws Exception {
        val server = mock(RadiusServer.class);
        when(server.authenticate(anyString(), anyString())).thenReturn(null);
        val result = RadiusUtils.authenticate("casuser", "Mellon", CollectionUtils.wrapList(server), true, false, Optional.empty());
        assertFalse(result.getKey());
    }

    @Test
    public void verifyActionFails() throws Exception {
        val server = mock(RadiusServer.class);
        when(server.authenticate(anyString(), anyString())).thenReturn(null);
        assertThrows(FailedLoginException.class,
            () -> RadiusUtils.authenticate("casuser", "Mellon", CollectionUtils.wrapList(server), false, false, Optional.empty()));
    }

    @Test
    public void verifyActionFailsWithException() throws Exception {
        val server = mock(RadiusServer.class);
        when(server.authenticate(anyString(), anyString())).thenThrow(FailedLoginException.class);
        assertThrows(FailedLoginException.class,
            () -> RadiusUtils.authenticate("casuser", "Mellon", CollectionUtils.wrapList(server), false, false, Optional.empty()));
    }
}