text:
<?php
class BelongsTo extends Association {
  function __construct(&$source, $dest, $options=null) {
    parent::__construct($source, $dest, $options);
    if (!isset($options['foreign_key'])) {
      $this->foreign_key = ActiveRecordInflector::foreign_key($this->dest_class);
    }
  }

  function set($value, &$source) {
    if ($value instanceof $this->dest_class) {
      if (!$value->is_new_record())
        $source->{$this->foreign_key} = $value->{$value->get_primary_key()};
      else
        $source->{$this->foreign_key} = null;
      $this->value = $value;
    }
    else {
      throw new ActiveRecordException("Did not get expected class: {$this->dest_class}", ActiveRecordException::UnexpectedClass);
    }
  }

  function get(&$source, $force=false) {
    if ($this->value instanceof $this->dest_class && !$force) {
      return $this->value;
    }
    else {
      $this->value = call_user_func_array(
          array($this->dest_class, 'find'),
          array($source->{$this->foreign_key}) );
      return $this->value;
    }
  }

  function join() {
    $dest_table = ActiveRecordInflector::tableize($this->dest_class);
    $source_table = ActiveRecordInflector::tableize($this->source_class);
    $dest_inst = new $this->dest_class;
    $columns = $dest_inst->get_columns();
    $join = "LEFT OUTER JOIN {$dest_table} ON "
          . "$source_table.{$this->foreign_key} = $dest_table.".$dest_inst->get_primary_key();
    return array( array($dest_table => $columns), $join);
  }
  function populate_from_find($attributes) {
    // check if all attributes are NULL
    $uniq_vals = array_unique(array_values($attributes));
    if (count($uniq_vals) == 1 && is_null(current($uniq_vals))) return;

    $class = $this->dest_class;
    $item = new $class($attributes);
    $item->new_record = false;
    $this->value = $item;
  }

}
?>


text:
namespace SecureAuth.Admin.Sdk
{
    public class AdaptiveAuthRequestV2 : BaseRequest
    {
        public Models.v2.AdaptiveAuthentication AdaptiveAuth { get; set; }

        public AdaptiveAuthRequestV2()
        {
            AdaptiveAuth = new Models.v2.AdaptiveAuthentication();
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
.. _1-1-2:

1.1.2
===========================
*02/13/2018*

Graphite 1.1.2 is now available for usage. Please note that this is a bugfix release for stable Graphite 1.1.x branch and it's recommended for production usage. It also contains some improvements backported from master branch.

Source bundles are available from GitHub:

* https://github.com/graphite-project/graphite-web/archive/1.1.2.tar.gz
* https://github.com/graphite-project/carbon/archive/1.1.2.tar.gz
* https://github.com/graphite-project/whisper/archive/1.1.2.tar.gz
* https://github.com/graphite-project/carbonate/archive/1.1.2.tar.gz

Graphite can also be installed from `PyPI <http://pypi.python.org/>`_ via
`pip <http://www.pip-installer.org/en/latest/index.html>`_. PyPI bundles are here:

* http://pypi.python.org/pypi/graphite-web/
* http://pypi.python.org/pypi/carbon/
* http://pypi.python.org/pypi/whisper/
* http://pypi.python.org/pypi/carbonate/

Upgrading
---------
Please upgrade carbon and graphite-web - they contain valuable bugfixes and improvements. Whisper package was not changed.

Incompatible changes
--------------------

* REMOTE_FIND_TIMEOUT and REMOTE_FETCH_TIMEOUT are renamed to FIND_TIMEOUT and FETCH_TIMEOUT. Default FETCH_TIMEOUT increased from 3 to 6 seconds.

* Default GRAPHITE_URL is set to "http://127.0.0.1:80"

Security Notes
--------------
None

New features
------------

Graphite-Web
^^^^^^^^^^^^

* Add seasonality parameter for holt-winters functions (@LTMXcitrus, #2225)

* Percentile aggregation documentation (@wridgers, #2204)

* Clarifying documentation for storage-aggregation.conf (@wfhu, #2215)

* functions: fix groupByNode() output (@iksaif, #2213)

* Some cleanups for storage.py (@iksaif, #2181)

* Make it possible to fully disable tags (@iksaif, #2206)

* Adding Graphouse to the Tools page (@denish, #2208)

* Rename timeout settings (@DanCech, #2196)

* hashing: better performances (@iksaif, #2191)

* Added doc for nginx+gunicorn stack (configuration and deployment) (@Serphentas, #2179)

* improve efficiency of standard finder (@DanCech, #2185)

* graphite: add support for raven/sentry.io (optional) (@iksaif, #2180)

Carbon
^^^^^^

* Changing default GRAPHITE_URL to http://127.0.0.1:80 (@deniszh, #747)

* Percentile aggregation methods in aggregator (@wridgers, #696)

* fnv1a_ch and mmh3_ch hashes can be used in all routers (@iksaif, #727)

* Add support for TCP_KEEPALIVE, enabled by default (@iksaif, #722)

* log: add raven/sentry support (@iksaif, #724)

* Add a README and examples for invoking test harness by hand (@cbowman0, #2176)

Whisper
^^^^^^^

* None

Carbonate
^^^^^^^^^

* carbon-sync: expose --overwrite to copy all non-null datapoints (#89, @jehiah)

Bug Fixes
---------

Graphite-Web
^^^^^^^^^^^^

* functions: fix holtWinterAberration with multiple targets (@iksaif, #2226)

* handle case when node.fetch returns None (@DanCech, #2223)

* Propagate `now` parameter for whisper reader (@deniszh, #2207)

* Documentation fixes (@deniszh, #2201)

* Do not try merge series with different length (@deniszh, #2198)

* app_settings: append() doesn't work on tuples (@iksaif, #2190)

* Fixing build-index tool (@DanCech, #2178)

* clarify function plugin docs (@DanCech, #2177)

* Tweak function docs (@DanCech, #2172)

* fix typo in aggregate arg definition (@DanCech, #2169)

* Fix hash position computation of fnv1a_ch (@DanCech, #2168)

* fix interval end test error (@DanCech, #2164)

* ignore bogus url warnings, update INSTALLED_APPS (@DanCech, #2163)

Carbon
^^^^^^

* client: make sure the line client doesn't loose precision (@iksaif, #723)

* carbon line format float handling (@DanCech, #740)

* writers run synchronously in separate threads (@DanCech, #738)

* Fix leaks in writeForever and writeTagsForever (@cevans-uk, #733)

* run whisper and tag writers in separate threads (@DanCech, #731)

* carbon: use a generator in routers instead of returning the full set (@iksaif, #728)

* hashing: fix performance regression (@iksaif, #726)

* Don't require six in setup.py (@iksaif, #725)

* Fix hash position computation of fnv1a_ch (@DanCech, #717)

* restore droppedCreates metric (@fessyfoo, #710)

Whisper
^^^^^^^

* None

Carbonate
^^^^^^^^^

* fill: fix bugs causing some data points not to be copied (#90, @jehiah)


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

/**
 * @fileoverview Unit tests for the audio translation manager service.
 */

import { TestBed } from '@angular/core/testing';

import { AudioTranslationManagerService } from
  'pages/exploration-player-page/services/audio-translation-manager.service';
import { VoiceoverObjectFactory } from
  'domain/exploration/VoiceoverObjectFactory';

describe('Audio translation manager service', () => {
  let atms: AudioTranslationManagerService, vof: VoiceoverObjectFactory;

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [AudioTranslationManagerService, VoiceoverObjectFactory]
    });

    atms = TestBed.get(AudioTranslationManagerService);
    vof = TestBed.get(VoiceoverObjectFactory);
  });

  var testAudioTranslations;
  var testAudioTranslations2;
  beforeEach(() => {
    testAudioTranslations = {
      en: vof.createFromBackendDict({
        filename: 'audio-en.mp3',
        file_size_bytes: 0.5,
        needs_update: false,
        duration_secs: 0.5
      }),
      es: vof.createFromBackendDict({
        filename: 'audio-es.mp3',
        file_size_bytes: 0.5,
        needs_update: false,
        duration_secs: 0.5
      })
    };

    testAudioTranslations2 = {
      zh: vof.createFromBackendDict({
        filename: 'audio-zh.mp3',
        file_size_bytes: 0.5,
        needs_update: false,
        duration_secs: 0.5
      }),
      'hi-en': vof.createFromBackendDict({
        filename: 'audio-hi-en.mp3',
        file_size_bytes: 0.5,
        needs_update: false,
        duration_secs: 0.5
      })
    };
  });

  it('should properly set primary and secondary audio translations',
    () => {
      atms.setContentAudioTranslations(testAudioTranslations, '', '');
      expect(atms.getCurrentAudioTranslations()).toEqual({
        en: vof.createFromBackendDict({
          filename: 'audio-en.mp3',
          file_size_bytes: 0.5,
          needs_update: false,
          duration_secs: 0.5
        }),
        es: vof.createFromBackendDict({
          filename: 'audio-es.mp3',
          file_size_bytes: 0.5,
          needs_update: false,
          duration_secs: 0.5
        })
      });
      atms.setSecondaryAudioTranslations(testAudioTranslations2, '', '');
      expect(atms.getCurrentAudioTranslations()).toEqual({
        zh: vof.createFromBackendDict({
          filename: 'audio-zh.mp3',
          file_size_bytes: 0.5,
          needs_update: false,
          duration_secs: 0.5
        }),
        'hi-en': vof.createFromBackendDict({
          filename: 'audio-hi-en.mp3',
          file_size_bytes: 0.5,
          needs_update: false,
          duration_secs: 0.5
        })
      });
      atms.clearSecondaryAudioTranslations();
      expect(atms.getCurrentAudioTranslations()).toEqual({
        en: vof.createFromBackendDict({
          filename: 'audio-en.mp3',
          file_size_bytes: 0.5,
          needs_update: false,
          duration_secs: 0.5
        }),
        es: vof.createFromBackendDict({
          filename: 'audio-es.mp3',
          file_size_bytes: 0.5,
          needs_update: false,
          duration_secs: 0.5
        })
      });
    });
});


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title co-title co-title-suffix=" · CoreOS">CoreOS</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="../dist/bootstrap.css">
    <link rel="stylesheet" href="../dist/coreos.css">
    <link rel="stylesheet" href="../dist/font-awesome.css">

    <base href="/example">

    <co-footer-wrapper ng-cloak>
      <co-navbar logo-src="/coreos.svg/logo.svg">

          <co-navbar-link href="/example/js-modules">JS Modules</co-navbar-link>
          <co-navbar-link href="/example/css-modules">CSS Modules</co-navbar-link>
          <co-navbar-link href="/example/services">Services</co-navbar-link>

        <co-navbar-dropdown text="Navbar Dropdown">

Stuff

        </co-navbar-dropdown>
      </co-navbar>

    </co-footer-wrapper>

    <co-footer ng-cloak>
      <co-footer-link href="https://coreos.com/docs" icon-class="fa fa-book">Documentation</co-footer-link>
      <co-footer-link href="irc://irc.freenode.org:6667/#coreos/" icon-class="fa fa-comment">IRC #coreos</co-footer-link>
    </co-footer>

    <co-toast></co-toast>


text:
package com.ideaknow.api.client.model.menu;

import android.os.Parcel;
import android.os.Parcelable;

import java.util.*;

public class MenuModel implements Parcelable {

    private List<MenuOperationModel> operations;

    public MenuModel() {
    }

    public List<MenuOperationModel> getOperations() {
        return operations;
    }

    public void setOperations(List<MenuOperationModel> operations) {
        this.operations = operations;
    }

    @Override
    public String toString() {
        return "MenuModel{" +
                "operations=" + operations +
                '}';
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeTypedList(operations);
    }

    private MenuModel(Parcel in) {
        if (operations == null) {
            operations = new ArrayList<MenuOperationModel>();
        }
        in.readTypedList(operations, MenuOperationModel.CREATOR);
    }

    public static final Creator<MenuModel> CREATOR = new Creator<MenuModel>() {
        public MenuModel createFromParcel(Parcel source) {
            return new MenuModel(source);
        }

        public MenuModel[] newArray(int size) {
            return new MenuModel[size];
        }
    };
}


text:
describe('slicing', function() {
  var Join;

  beforeEach(module('angular-join'));
  beforeEach(inject(function(_Join_) {
    Join = _Join_;
  }));

  function makeNumeric(start, end) {
    var result = [];
    for (var i = start; i <= end; i++) {
      result.push({ x: i });
    }
    return result;
  }

  describe('should produce a subset of the input', function() {
    var input;

    beforeEach(function() {
      input = makeNumeric(1, 10);
    });

    it('using the slice function', function() {
      var slice = Join
        .selectFrom(input)
        .slice(1)
        .execute();
      expect(slice).toEqual(input.slice(1));

      slice = Join
        .selectFrom(input)
        .slice(1, 5)
        .execute();
      expect(slice).toEqual(input.slice(1, 5));

      slice = Join
        .selectFrom(input)
        .slice(0, input.length)
        .execute();
      expect(slice).toEqual(input);

      slice = Join
        .selectFrom(input)
        .slice(input.length)
        .execute();
      expect(slice).toEqual([]);
    });

    it('using the limit function', function() {
      var slice = Join
        .selectFrom(input)
        .limit(1)
        .execute();
      expect(slice).toEqual(input.slice(0, 1));

      slice = Join
        .selectFrom(input)
        .limit(1, 5)
        .execute();
      expect(slice).toEqual(input.slice(5, 6));

      slice = Join
        .selectFrom(input)
        .limit(input.length, 0)
        .execute();
      expect(slice).toEqual(input);

      slice = Join
        .selectFrom(input)
        .limit(0)
        .execute();
      expect(slice).toEqual([]);
    });

    it('using the offset function', function() {
      var slice = Join
        .selectFrom(input)
        .offset(1)
        .execute();
      expect(slice).toEqual(input.slice(1));

      slice = Join
        .selectFrom(input)
        .offset(0)
        .execute();
      expect(slice).toEqual(input);

      slice = Join
        .selectFrom(input)
        .offset(input.length)
        .execute();
      expect(slice).toEqual([]);
    });

  });

  describe('should produce a clone of the input', function() {
    var input;

    beforeEach(function() {
      input = makeNumeric(1, 10);
    });

    it('using the slice function', function() {
      var slice = Join
        .selectFrom(input)
        .slice(0, input.length)
        .execute();
      expect(slice).toEqual(input);
    });

    it('using the limit function', function() {
      var slice = Join
        .selectFrom(input)
        .limit(input.length, 0)
        .execute();
      expect(slice).toEqual(input);
    });

    it('using the offset function', function() {
      var slice = Join
        .selectFrom(input)
        .offset(0)
        .execute();
      expect(slice).toEqual(input);
    });

  });

  describe('should produce an empty array', function() {
    var input;

    beforeEach(function() {
      input = makeNumeric(1, 10);
    });

    it('using the slice function', function() {
      var slice = Join
        .selectFrom(input)
        .slice(input.length)
        .execute();
      expect(slice).toEqual([]);
    });

    it('using the limit function', function() {
      var slice = Join
        .selectFrom(input)
        .limit(0)
        .execute();
      expect(slice).toEqual([]);
    });

    it('using the offset function', function() {
      var slice = Join
        .selectFrom(input)
        .offset(input.length)
        .execute();
      expect(slice).toEqual([]);
    });

  });
});


text:
package se.culvertsoft.mgen.cpppack.generator.impl

import se.culvertsoft.mgen.api.model.ClassType
import se.culvertsoft.mgen.api.model.Field
import se.culvertsoft.mgen.compiler.internal.BuiltInGeneratorUtil.upFirst

object Alias {

  def get(field: Field): String = {
    s"get${upFirst(field.name())}()"
  }

  def getMutable(field: Field): String = {
    s"get${upFirst(field.name())}Mutable()"
  }

  def set(field: Field, input: String): String = {
    s"set${upFirst(field.name())}($input)"
  }

  def typeIdString(t: ClassType): String = {
    "_type_id"
  }

  def typeId16BitString(t: ClassType): String = {
    "_type_id_16bit"
  }

  def typeId16BitBase64String(t: ClassType): String = {
    "_type_id_16bit_base64"
  }

  def fieldIdString(field: Field): String = {
    s"_field_${field.name()}_id"
  }

  def fieldMetaString(field: Field, inclParan: Boolean = true): String = {
    if (inclParan)
      s"_field_${field.name()}_metadata()"
    else
      s"_field_${field.name()}_metadata"
  }

  def isSetName(f: Field): String = {
    s"_m_${f.name()}_isSet"
  }

  def setFieldSetName(f: Field): String = {
    s"_set${upFirst(f.name())}Set"
  }

  def isFieldSet(f: Field, input: String): String = {
    s"_is${upFirst(f.name())}Set($input)"
  }

  def setFieldSet(f: Field, input: String): String = {
    s"${setFieldSetName(f)}($input)"
  }

}


text:
/* istanbul ignore next: hard to test; *//* Functional Reactive Programming (frp) Tests
 *
 * Copyright (c) 2014 .decimal, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

var expect = require('chai').expect;
var frp = require('../lib/frp');

describe('frp:Accessor', function() {
    describe('Accessor#get', function() {
        it('should return the current value of the accessor', function() {
            var number_state = frp.state(1);
            var bool_state = frp.state(true);
            var string_state = frp.state('frp rocks!');
            var array_state = frp.state([1, 2, 3]);
            var obj_state = frp.state({
                one: 1,
                two: 2,
                three: 3
            });

            expect(number_state.get()).to.eql(1);
            expect(bool_state.get()).to.eql(true);
            expect(string_state.get()).to.eql('frp rocks!');
            expect(array_state.get()).to.eql([1, 2, 3]);
            expect(obj_state.get()).to.eql({
                one: 1,
                two: 2,
                three: 3
            });
        });

        it('should return undefined if the state is unresolved', function() {
            var state = frp.state();

            expect(state.get()).to.be.undefined;
        });
    });

    describe('Accessor#isGettable', function() {
        it('shoud return true if the accessor has a get method', function() {
            var state = frp.state();

            expect(state.isGettable()).to.be.true;
        });
    });

    describe('Accessor#isSettable', function() {
        it('should return true if the accessor has a set method', function() {
            var state = frp.state();

            expect(state.isSettable()).to.be.true;
        });

        it('should return true if the accessor has a set method', function() {
            var state = frp.constant(1);

            expect(state.isSettable()).to.be.false;
        });
    });

    describe('Accessor#isObject', function() {
        it('should have state true if the value is an object', function(done) {
            var state = frp.state({
                one: 1,
                two: 2,
                three: 3
            });

            state.isObject().onResolve(function(value) {
                expect(value).to.be.true;
                done();
            });
        });

        it('should have state false if the value is not an object', function(done) {
            var state = frp.state(1);

            state.isObject().onResolve(function(value) {
                expect(value).to.be.false;
                done();
            });
        });

        it('should have state false if the value is unresolved', function(done) {
            var state = frp.state({
                one: 1,
                two: 2,
                three: 3
            });

            var timeout = setTimeout(function() {
                expect(false).to.be.true;
            }, 1000);

            var triggered = false;
            state.isObject().onResolve(function(value) {
                if (value) {
                    triggered = true;
                    state._unresolve();
                } else {
                    clearTimeout(timeout);
                    expect(triggered).to.be.true;
                    done();
                }
            });
        });

        it('should propagate error trigger', function(done) {
            var state = frp.state({
                one: 1,
                two: 2,
                three: 3
            });

            var timeout = setTimeout(function() {
                expect(false).to.be.true;
            }, 1000);

            state.isObject().onResolve(function(value) {
                state._throw(new Error('An error was encountered'));
            }).onError(function(errs) {
                clearTimeout(timeout);
                expect(errs[0]).be.an.instanceof(Error);
                done();
            });
        });
    });

    describe('Accessor#isResolved', function() {
        it('should have state true if the value is resolved', function(done) {
            var state = frp.state(1);

            state.isResolved().onResolve(function(value) {
                expect(value).to.be.true;
                done();
            });
        });

        it('should have state false if the value is unresolved', function(done) {
            var state = frp.state();

            state.isResolved().onResolve(function(value) {
                expect(value).to.be.false;
                done();
            });
        });

        it('should have state false if the value becomes unresolved', function(done) {
            var state = frp.state(1);

            var timeout = setTimeout(function() {
                expect(false).to.be.true;
            }, 1000);

            var triggered = false;
            state.isResolved().onResolve(function(value) {
                if (value) {
                    triggered = true;
                    state._unresolve();
                } else {
                    clearTimeout(timeout);
                    expect(triggered).to.be.true;
                    done();
                }
            });
        });

        it('should propagate error trigger', function(done) {
            var state = frp.state(1);

            var timeout = setTimeout(function() {
                expect(false).to.be.true;
            }, 1000);

            state.isResolved().onResolve(function(value) {
                state._throw(new Error('An error was encountered'));
            }).onError(function(errs) {
                clearTimeout(timeout);
                expect(errs[0]).be.an.instanceof(Error);
                done();
            });
        });
    });

    describe('Accessor#isUndefined', function() {
        it('should have an initial state of true before the value is resolved', function(done) {
            var state = frp.state();

            var timeout = setTimeout(function() {
                expect(false).to.be.true;
            }, 1000);

            state.isUndefined().onResolve(function(value) {
                expect(value).to.be.true;
                clearTimeout(timeout);
                done();
            });
        });

        it('should return true if the resolved value is undefined', function(done) {
            var state = frp.state(void 0);

            var timeout = setTimeout(function() {
                expect(false).to.be.true;
            }, 1000);

            state.isUndefined().onResolve(function(value) {
                expect(value).to.be.true;
                clearTimeout(timeout);
                done();
            });
        });

        it('should return false if the resolved value is defined', function(done) {
            var state = frp.state(1);

            var timeout = setTimeout(function() {
                expect(false).to.be.true;
            }, 1000);

            var triggered = false;
            state.isUndefined().onResolve(function(value) {
                if (value) {
                    triggered = true;
                } else {
                    expect(triggered).to.be.true;
                    clearTimeout(timeout);
                    done();
                }
            });
        });

        it('should return true if the value becomes unresolved', function(done) {
            var state = frp.state(1);

            var timeout = setTimeout(function() {
                expect(false).to.be.true;
            }, 1000);

            var flag = 0;
            var triggered = false;
            state.isUndefined().onResolve(function(value) {
                if (flag === 2) {
                    clearTimeout(timeout);
                    expect(triggered).to.be.true;
                    done();
                } else {
                    if (flag === 1) {
                        triggered = true;
                        state._unresolve();
                    }
                    flag++;
                }
            });
        });

        it('should propagate error trigger', function(done) {
            var state = frp.state(1);

            var timeout = setTimeout(function() {
                expect(false).to.be.true;
            }, 1000);

            state.isUndefined().onResolve(function(value) {
                state._throw(new Error('An error was encountered'));
            }).onError(function(errs) {
                clearTimeout(timeout);
                expect(errs[0]).be.an.instanceof(Error);
                done();
            });
        });
    });

    describe('Accessor#at', function() {
        it('should access an array at a particular index', function(done) {
            var state_arr = frp.state([0, 1, 2]);

            state_arr.at(1).onResolve(function(value) {
                expect(value).to.eql(1);
                done();
            });
        });

        it('should access an array-like object at a particular index', function(done) {
            var state_obj = frp.state({
                '0': 0,
                '1': 1,
                '2': 2
            });

            state_obj.at(1).onResolve(function(value) {
                expect(value).to.eql(1);
                done();
            });
        });
    });

    describe('Accessor#not', function() {
        it('should return true if the value is the number 0', function(done) {
            var number_state = frp.state(0);

            number_state.not().onResolve(function(value) {
                expect(value).to.be.true;
                done();
            });
        });

        it('should return false if the value is a non-zero number', function(done) {
            var number_state = frp.state(1);

            number_state.not().onResolve(function(value) {
                expect(value).to.be.false;
                done();
            });
        });

        it('should return true if the value is a boolean false', function(done) {
            var bool_state = frp.state(false);

            bool_state.not().onResolve(function(value) {
                expect(value).to.be.true;
                done();
            });
        });

        it('should return false if the value is a boolean true', function(done) {
            var bool_state = frp.state(true);

            bool_state.not().onResolve(function(value) {
                expect(value).to.be.false;
                done();
            });
        });

        it('should return true if the value is an empty string', function(done) {
            var string_state = frp.state('');

            string_state.not().onResolve(function(value) {
                expect(value).to.be.true;
                done();
            });
        });

        it('should return false if the value is a non-empty string', function(done) {
            var string_state = frp.state('frp rocks!');

            string_state.not().onResolve(function(value) {
                expect(value).to.be.false;
                done();
            });
        });

        it('should return true if the value is null', function(done) {
            var null_state = frp.state(null);

            null_state.not().onResolve(function(value) {
                expect(value).to.be.true;
                done();
            });
        });

        it('should return true if the value is undefined', function(done) {
            var undefined_state = frp.state(undefined);

            undefined_state.not().onResolve(function(value) {
                expect(value).to.be.true;
                done();
            });
        });

        it('should return false if the value is an array', function(done) {
            var array_state = frp.state([1, 2, 3]);

            array_state.not().onResolve(function(value) {
                expect(value).to.be.false;
                done();
            });
        });

        it('should return false if the value is an array', function(done) {
            var obj_state = frp.state({
                one: 1,
                two: 2,
                three: 3
            });

            obj_state.not().onResolve(function(value) {
                expect(value).to.be.false;
                done();
            });
        });

        it('should propagate unresolved state', function(done) {
            var state = frp.state(0);

            var timeout = setTimeout(function() {
                expect(false).to.be.true;
            }, 1000);

            state.not().onResolve(function(value) {
                state._unresolve();
            }).onUnresolve(function() {
                clearTimeout(timeout);
                done();
            });
        });

        it('should propagate error trigger', function(done) {
            var state = frp.state(0);

            var timeout = setTimeout(function() {
                expect(false).to.be.true;
            }, 1000);

            state.not().onResolve(function(value) {
                state._throw(new Error('An error was encountered'));
            }).onError(function(errs) {
                clearTimeout(timeout);
                expect(errs[0]).be.an.instanceof(Error);
                done();
            });
        });
    });

    describe('Accessor#delay', function() {
        it('should delay resolution for the specified number of ms', function(done) {
            var start = +new Date();
            var state = frp.state(1).delay(1000);

            state.onResolve(function(value) {
                var timeDif = (+new Date()) - start;
                expect(timeDif).to.be.at.least(1000);
                done();
            });
        });

        it('should restart the timer if the value was reset before the first resolve', function(done) {
            var start = +new Date();
            var state_a = frp.state(1)
            var state = state_a.delay(1000);

            setTimeout(function() {
                state_a.set(2);
            }, 500);

            state.onResolve(function(value) {
                var timeDif = (+new Date()) - start;
                expect(timeDif).to.be.at.least(1500);
                expect(value).to.eql(2);
                done();
            });
        });

        it('should propagate unresolved state', function(done) {
            var start = +new Date();
            var state_a = frp.state(1)
            var state = state_a.delay(500);

            var timeout = setTimeout(function() {
                expect(false).to.be.true;
            }, 1000);

            state.onResolve(function(value) {
                state_a._unresolve();
            }).onUnresolve(function() {
                clearTimeout(timeout);
                done();
            });
        });

        it('should propagate error trigger', function(done) {
            var start = +new Date();
            var state_a = frp.state(1)
            var state = state_a.delay(500);

            var timeout = setTimeout(function() {
                expect(false).to.be.true;
            }, 1000);

            state.onResolve(function(value) {
                state_a._throw(new Error('An error was encountered'));
            }).onError(function(errs) {
                clearTimeout(timeout);
                expect(errs[0]).be.an.instanceof(Error);
                done();
            });
        });
    });

    describe('Accessor#property', function() {
        it('should return a property accessor for accessing object properties', function(done) {
            var obj_state = frp.state({
                one: 1,
                two: 2,
                three: 3
            });

            obj_state.property('.one').onResolve(function(value) {
                expect(value).to.eql(1);
                done();
            });
        });

        it('should become unresolved if the property does not exist in the object', function(done) {
            var obj_state = frp.state({
                one: 1,
                two: 2,
                three: 3
            });

            obj_state.property('.four').startWith(4).onResolve(function(value) {
                expect(false).to.be.true;
            }).onUnresolve(function() {
                done();
            });
        });

        it('should propagate unresolved state', function(done) {
            var obj_state = frp.state({
                one: 1,
                two: 2,
                three: 3
            });

            var timeout = setTimeout(function() {
                expect(false).to.be.true;
            }, 1000);

            obj_state.property('.one').onResolve(function(value) {
                obj_state._unresolve()
            }).onUnresolve(function() {
                clearTimeout(timeout);
                done();
            });
        });

        it('should propagate error trigger', function(done) {
            var obj_state = frp.state({
                one: 1,
                two: 2,
                three: 3
            });

            var timeout = setTimeout(function() {
                expect(false).to.be.true;
            }, 1000);

            obj_state.property('.one').onResolve(function(value) {
                obj_state._throw(new Error('An error was encountered'))
            }).onError(function(errs) {
                clearTimeout(timeout);
                expect(errs[0]).be.an.instanceof(Error);
                done();
            });
        });
    });

    describe('Accessor#startWith', function() {
        it('should start with a certain value', function(done) {
            var state = frp.state().startWith(1);

            state.onResolve(function(value) {
                expect(value).to.be.a('number').and.to.eql(1);
                done();
            });
        });

        it('should ignore the start value it has already been resolved', function(done) {
            var state = frp.state(2).startWith(1);

            state.onResolve(function(value) {
                expect(value).to.be.a('number').and.to.eql(2);
                done();
            });
        });
    });

    describe('Accessor#then', function() {
        it('should map state to another value', function(done) {
            var state = frp.state(1);

            state.then(function(value) {
                return value + 1;
            }).onResolve(function(value) {
                expect(value).to.eql(2);
                done();
            });
        });
    });
});

describe('frp:PropertyAccessor', function() {
    describe('PropertyAccessor#set', function() {
        it('should set a property accessor (shallow)', function(done) {
            var obj_state = frp.state({
                one: 1,
                two: 2,
                three: 3
            });

            var prop = obj_state.property('.one');

            var trigger = false;
            prop.onResolve(function(value) {
                if (value === 1) {
                    trigger = true;
                    prop.set('one');
                } else {
                    expect(value).to.eql('one');
                    expect(trigger).to.be.true;
                    done();
                }
            });
        });

        it('should set a property accessor (deep)', function(done) {
            var obj_state = frp.state({
                person: {
                    first: 'John',
                    last: 'Doe'
                }
            });

            var prop = obj_state.property('.person.first');

            var trigger = false;
            prop.onResolve(function(value) {
                if (value === 'John') {
                    trigger = true;
                    prop.set('Jane');
                } else {
                    expect(value).to.eql('Jane');
                    expect(trigger).to.be.true;
                    done();
                }
            });
        });

        it('should deeply construct the property with a value (deep)', function(done) {
            var obj_state = frp.state();

            var prop = obj_state.property('.person.first');

            prop.set('John');

            obj_state.onResolve(function(value) {
                expect(value).to.eql({ person: { first: 'John' } });
                done();
            });
        });
    });
});


text:
package xal.model.elem;

import xal.model.elem.sync.IElectromagnet;
import xal.sim.scenario.LatticeElement;
import xal.smf.impl.Magnet;

/**
 *  This class implements IElectromagnet interface for thin magnets.
 *
 */
public abstract class ThinElectromagnet extends ThinElement implements IElectromagnet {

	 /*
     *  Local Attributes
     */

    /** bending plane of dipole */
    protected int                 enmOrient = ORIENT_NONE;

    /** Field strength of the dipole magnet */
    protected double              dblField = 0.0;

	public ThinElectromagnet(String strType) {
		super(strType);

	}

	public ThinElectromagnet(String strType, String strId) {
		super(strType, strId);
	}

    /*
     *  IElectromagnet Interface
     */

    /**
     * Return the orientation enumeration code for the bending plane of the
     * associated dipole magnet.
     *
     *  @return     ORIENT_HOR  - dipole has steering action in x (horizontal) plane
     *              ORIENT_VER  - dipole has steering action in y (vertical) plane
     *              ORIENT_NONE - error
     */
    public int getOrientation() {
        return this.enmOrient;
    };

    /**
     *  Get the magnetic field strength of the associated dipole
     *
     *  @return     magnetic field (in Tesla).
     */
    public double getMagField() {
        return this.dblField;
    };

    /**
     *  Set the dipole bending plane orientation
     *
     *  @param  enmOrient   magnet orientation enumeration code
     *
     *  @see    #getOrientation
     */
    public void setOrientation(int enmOrient) {
        this.enmOrient = enmOrient;
    };

    /**
     *  Set the magnetic field strength of the dipole electromagnet.
     *
     *  @param  dblField    magnetic field (in Tesla).
     */
    public void setMagField(double dblField) {
        this.dblField = dblField;
    };

	/**
	 * Conversion method to be provided by the user
	 *
	 * @param latticeElement the SMF node to convert
	 */
    @Override
	public void initializeFrom(LatticeElement latticeElement) {
    	super.initializeFrom(latticeElement);
    	Magnet magnetNode =  (Magnet)latticeElement.getHardwareNode();
		int orientation = IElectromagnet.ORIENT_NONE;
		if (magnetNode.isHorizontal()) {
			orientation = IElectromagnet.ORIENT_HOR;
		} else if (magnetNode.isVertical()) {
			orientation = IElectromagnet.ORIENT_VER;
		} else {
		    //  This is an exceptional condition!
		    //    Something went wrong if we made it here
		    //    Let's say so

		    // CKA - we are going to skip this since skew quadrupoles (soft type = "QSC")
		    //    have no orientation and always throw this warning
//			    String    strSrc = magnetNode.getId() + "/" + magnetNode.getClass().getName();
//			    String    strMsg = "Encountered an un-oriented electromagnet hardware object";
//			    Logger    logGbl = Logger.getLogger("global");
//
//			    logGbl.log(Level.WARNING, strMsg + " : " + strSrc);
//	            System.out.println("WARNING!: " + strMsg + " : " + strSrc);
		}
		setOrientation(orientation);
		setMagField(magnetNode.getDesignField());
	}

}


text:
<?php

namespace Composer\Json;

/**
 * @author Jordi Boggiano <j.boggiano@seld.be>
 */
class JsonManipulator
{
    private static $RECURSE_BLOCKS;
    private static $JSON_VALUE;
    private static $JSON_STRING;

    private $contents;
    private $newline;
    private $indent;

    public function __construct($contents)
    {
        if (!self::$RECURSE_BLOCKS) {
            self::$RECURSE_BLOCKS = '(?:[^{}]*|\{(?:[^{}]*|\{(?:[^{}]*|\{(?:[^{}]*|\{[^{}]*\})*\})*\})*\})*';
            self::$JSON_STRING = '"(?:\\\\["bfnrt/\\\\]|\\\\u[a-fA-F0-9]{4}|[^\0-\x09\x0a-\x1f\\\\"])*"';
            self::$JSON_VALUE = '(?:[0-9.]+|null|true|false|'.self::$JSON_STRING.'|\[[^\]]*\]|\{'.self::$RECURSE_BLOCKS.'\})';
        }

        $contents = trim($contents);
        if (!preg_match('#^\{(.*)\}$#s', $contents)) {
            throw new \InvalidArgumentException('The json file must be an object ({})');
        }
        $this->newline = false !== strpos($contents, "\r\n") ? "\r\n": "\n";
        $this->contents = $contents === '{}' ? '{' . $this->newline . '}' : $contents;
        $this->detectIndenting();
    }

    public function getContents()
    {
        return $this->contents . $this->newline;
    }

    public function addLink($type, $package, $constraint)
    {
        $data = @json_decode($this->contents, true);

        // abort if the file is not parseable
        if (null === $data) {
            return false;
        }

        // no link of that type yet
        if (!isset($data[$type])) {
            return $this->addMainKey($type, array($package => $constraint));
        }

        $regex = '{^(\s*\{\s*(?:'.self::$JSON_STRING.'\s*:\s*'.self::$JSON_VALUE.'\s*,\s*)*?)'.
            '('.preg_quote(JsonFile::encode($type)).'\s*:\s*)('.self::$JSON_VALUE.')(.*)}s';
        if (!preg_match($regex, $this->contents, $matches)) {
            return false;
        }

        $links = $matches[3];

        if (isset($data[$type][$package])) {
            // update existing link
            $packageRegex = str_replace('/', '\\\\?/', preg_quote($package));
            // addcslashes is used to double up backslashes since preg_replace resolves them as back references otherwise, see #1588
            $links = preg_replace('{"'.$packageRegex.'"(\s*:\s*)'.self::$JSON_STRING.'}i', addcslashes(JsonFile::encode($package).'${1}"'.$constraint.'"', '\\'), $links);
        } else {
            if (preg_match('#^\s*\{\s*\S+.*?(\s*\}\s*)$#s', $links, $match)) {
                // link missing but non empty links
                $links = preg_replace(
                    '{'.preg_quote($match[1]).'$}',
                    addcslashes(',' . $this->newline . $this->indent . $this->indent . JsonFile::encode($package).': '.JsonFile::encode($constraint) . $match[1], '\\'),
                    $links
                );
            } else {
                // links empty
                $links = '{' . $this->newline .
                    $this->indent . $this->indent . JsonFile::encode($package).': '.JsonFile::encode($constraint) . $this->newline .
                    $this->indent . '}';
            }
        }

        $this->contents = $matches[1] . $matches[2] . $links . $matches[4];

        return true;
    }

    public function addRepository($name, $config)
    {
        return $this->addSubNode('repositories', $name, $config);
    }

    public function removeRepository($name)
    {
        return $this->removeSubNode('repositories', $name);
    }

    public function addConfigSetting($name, $value)
    {
        return $this->addSubNode('config', $name, $value);
    }

    public function removeConfigSetting($name)
    {
        return $this->removeSubNode('config', $name);
    }

    public function addSubNode($mainNode, $name, $value)
    {
        // no main node yet
        if (!preg_match('#"'.$mainNode.'":\s*\{#', $this->contents)) {
            $this->addMainKey(''.$mainNode.'', array($name => $value));

            return true;
        }

        $subName = null;
        if (false !== strpos($name, '.')) {
            list($name, $subName) = explode('.', $name, 2);
        }

        // main node content not match-able
        $nodeRegex = '#("'.$mainNode.'":\s*\{)('.self::$RECURSE_BLOCKS.')(\})#s';
        if (!preg_match($nodeRegex, $this->contents, $match)) {
            return false;
        }

        $children = $match[2];

        // invalid match due to un-regexable content, abort
        if (!@json_decode('{'.$children.'}')) {
            return false;
        }

        $that = $this;

        // child exists
        if (preg_match('{("'.preg_quote($name).'"\s*:\s*)('.self::$JSON_VALUE.')(,?)}', $children, $matches)) {
            $children = preg_replace_callback('{("'.preg_quote($name).'"\s*:\s*)('.self::$JSON_VALUE.')(,?)}', function ($matches) use ($name, $subName, $value, $that) {
                if ($subName !== null) {
                    $curVal = json_decode($matches[2], true);
                    $curVal[$subName] = $value;
                    $value = $curVal;
                }

                return $matches[1] . $that->format($value, 1) . $matches[3];
            }, $children);
        } elseif (preg_match('#[^\s](\s*)$#', $children, $match)) {
            if ($subName !== null) {
                $value = array($subName => $value);
            }

            // child missing but non empty children
            $children = preg_replace(
                '#'.$match[1].'$#',
                addcslashes(',' . $this->newline . $this->indent . $this->indent . JsonFile::encode($name).': '.$this->format($value, 1) . $match[1], '\\'),
                $children
            );
        } else {
            if ($subName !== null) {
                $value = array($subName => $value);
            }

            // children present but empty
            $children = $this->newline . $this->indent . $this->indent . JsonFile::encode($name).': '.$this->format($value, 1) . $children;
        }

        $this->contents = preg_replace($nodeRegex, addcslashes('${1}'.$children.'$3', '\\'), $this->contents);

        return true;
    }

    public function removeSubNode($mainNode, $name)
    {
        // no node
        if (!preg_match('#"'.$mainNode.'":\s*\{#', $this->contents)) {
            return true;
        }

        // empty node
        if (preg_match('#"'.$mainNode.'":\s*\{\s*\}#s', $this->contents)) {
            return true;
        }

        // no node content match-able
        $nodeRegex = '#("'.$mainNode.'":\s*\{)('.self::$RECURSE_BLOCKS.')(\})#s';
        if (!preg_match($nodeRegex, $this->contents, $match)) {
            return false;
        }

        $children = $match[2];

        // invalid match due to un-regexable content, abort
        if (!@json_decode('{'.$children.'}')) {
            return false;
        }

        $subName = null;
        if (false !== strpos($name, '.')) {
            list($name, $subName) = explode('.', $name, 2);
        }

        // try and find a match for the subkey
        if (preg_match('{"'.preg_quote($name).'"\s*:}i', $children)) {
            // find best match for the value of "name"
            if (preg_match_all('{"'.preg_quote($name).'"\s*:\s*(?:'.self::$JSON_VALUE.')}', $children, $matches)) {
                $bestMatch = '';
                foreach ($matches[0] as $match) {
                    if (strlen($bestMatch) < strlen($match)) {
                        $bestMatch = $match;
                    }
                }
                $childrenClean = preg_replace('{,\s*'.preg_quote($bestMatch).'}i', '', $children, -1, $count);
                if (1 !== $count) {
                    $childrenClean = preg_replace('{'.preg_quote($bestMatch).'\s*,?\s*}i', '', $childrenClean, -1, $count);
                    if (1 !== $count) {
                        return false;
                    }
                }
            }
        }

        // no child data left, $name was the only key in
        if (!trim($childrenClean)) {
            $this->contents = preg_replace($nodeRegex, '$1'.$this->newline.$this->indent.'}', $this->contents);

            // we have a subname, so we restore the rest of $name
            if ($subName !== null) {
                $curVal = json_decode('{'.$children.'}', true);
                unset($curVal[$name][$subName]);
                $this->addSubNode($mainNode, $name, $curVal[$name]);
            }

            return true;
        }

        $that = $this;
        $this->contents = preg_replace_callback($nodeRegex, function ($matches) use ($that, $name, $subName, $childrenClean) {
            if ($subName !== null) {
                $curVal = json_decode('{'.$matches[2].'}', true);
                unset($curVal[$name][$subName]);
                $childrenClean = substr($that->format($curVal, 0), 1, -1);
            }

            return $matches[1] . $childrenClean . $matches[3];
        }, $this->contents);

        return true;
    }

    public function addMainKey($key, $content)
    {
        $content = $this->format($content);

        // key exists already
        $regex = '{^(\s*\{\s*(?:'.self::$JSON_STRING.'\s*:\s*'.self::$JSON_VALUE.'\s*,\s*)*?)'.
            '('.preg_quote(JsonFile::encode($key)).'\s*:\s*'.self::$JSON_VALUE.')(.*)}s';
        if (preg_match($regex, $this->contents, $matches)) {
            // invalid match due to un-regexable content, abort
            if (!@json_decode('{'.$matches[2].'}')) {
                return false;
            }

            $this->contents = $matches[1] . JsonFile::encode($key).': '.$content . $matches[3];

            return true;
        }

        // append at the end of the file and keep whitespace
        if (preg_match('#[^{\s](\s*)\}$#', $this->contents, $match)) {
            $this->contents = preg_replace(
                '#'.$match[1].'\}$#',
                addcslashes(',' . $this->newline . $this->indent . JsonFile::encode($key). ': '. $content . $this->newline . '}', '\\'),
                $this->contents
            );

            return true;
        }

        // append at the end of the file
        $this->contents = preg_replace(
            '#\}$#',
            addcslashes($this->indent . JsonFile::encode($key). ': '.$content . $this->newline . '}', '\\'),
            $this->contents
        );

        return true;
    }

    public function format($data, $depth = 0)
    {
        if (is_array($data)) {
            reset($data);

            if (is_numeric(key($data))) {
                foreach ($data as $key => $val) {
                    $data[$key] = $this->format($val, $depth + 1);
                }

                return '['.implode(', ', $data).']';
            }

            $out = '{' . $this->newline;
            $elems = array();
            foreach ($data as $key => $val) {
                $elems[] = str_repeat($this->indent, $depth + 2) . JsonFile::encode($key). ': '.$this->format($val, $depth + 1);
            }

            return $out . implode(','.$this->newline, $elems) . $this->newline . str_repeat($this->indent, $depth + 1) . '}';
        }

        return JsonFile::encode($data);
    }

    protected function detectIndenting()
    {
        if (preg_match('{^(\s+)"}m', $this->contents, $match)) {
            $this->indent = $match[1];
        } else {
            $this->indent = '    ';
        }
    }
}


text:
namespace Lucene
{
    class MyCommitPoint : public IndexCommit
    {
    public:
        MyCommitPoint(SnapshotDeletionPolicyPtr deletionPolicy, IndexCommitPtr cp);
        virtual ~MyCommitPoint();

        LUCENE_CLASS(MyCommitPoint);

    protected:
        SnapshotDeletionPolicyWeakPtr _deletionPolicy;

    public:
        IndexCommitPtr cp;

    public:
        virtual String toString();

        /// Get the segments file (segments_N) associated with this commit point.
        virtual String getSegmentsFileName();

        /// Returns all index files referenced by this commit point.
        virtual HashSet<String> getFileNames();

        /// Returns the {@link Directory} for the index.
        virtual DirectoryPtr getDirectory();

        /// Delete this commit point.
        virtual void deleteCommit();

        virtual bool isDeleted();

        /// Returns the version for this IndexCommit.
        virtual int64_t getVersion();

        /// Returns the generation (the _N in segments_N) for this IndexCommit.
        virtual int64_t getGeneration();

        /// Returns userData, previously passed to {@link IndexWriter#commit(Map)} for this commit.
        virtual MapStringString getUserData();

        virtual bool isOptimized();
    };
}

#endif


text:
namespace CustomWorkoutPlanner.Controllers
{
    using Boilerplate.AspNetCore;
    using Microsoft.AspNetCore.Mvc;
    using CustomWorkoutPlanner.Constants;

    /// <summary>
    /// Provides methods that respond to HTTP requests with HTTP errors.
    /// </summary>
    [Route("[controller]")]
    public sealed class ErrorController : Controller
    {
        #region Public Methods

        /// <summary>
        /// Gets the error view for the specified HTTP error status code. Returns a <see cref="PartialViewResult"/> if
        /// the request is an Ajax request, otherwise returns a full <see cref="ViewResult"/>.
        /// </summary>
        /// <param name="statusCode">The HTTP error status code.</param>
        /// <param name="status">The name of the HTTP error status code e.g. 'notfound'. This is not used but is here
        /// for aesthetic purposes.</param>
        /// <returns>A <see cref="PartialViewResult"/> if the request is an Ajax request, otherwise returns a full
        /// <see cref="ViewResult"/> containing the error view.</returns>
        [ResponseCache(CacheProfileName = CacheProfileName.Error)]
        [HttpGet("{statusCode:int:range(400, 599)}/{status?}", Name = ErrorControllerRoute.GetError)]
        public IActionResult Error(int statusCode, string status)
        {
            this.Response.StatusCode = statusCode;

            ActionResult result;
            if (this.Request.IsAjaxRequest())
            {
                // This allows us to show errors even in partial views.
                result = this.PartialView(ErrorControllerAction.Error, statusCode);
            }
            else
            {
                result = this.View(ErrorControllerAction.Error, statusCode);
            }

            return result;
        }

        #endregion
    }
}


text:
package org.spongepowered.common.util.persistence;

import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import org.spongepowered.api.data.DataContainer;
import org.spongepowered.api.data.DataQuery;
import org.spongepowered.api.data.MemoryDataContainer;
import org.spongepowered.api.data.MemoryDataView;

import java.util.Map.Entry;

public class JsonTranslator {

    public static DataContainer translateFrom(JsonObject object) {
        return (DataContainer) convert(object);
    }

    private static Object convert(JsonElement element) {
        if (element.isJsonObject()) {
            MemoryDataView container = new MemoryDataContainer();
            for (Entry<String, JsonElement> entry : ((JsonObject) element).entrySet()) {
                Object value = convert(entry.getValue());
                if (value != null) {
                    container.set(DataQuery.of(entry.getKey()), value);
                }
            }
            return container;
        } else if (element.isJsonArray()) {
            return Lists.newArrayList(Iterables.transform((JsonArray) element, JsonTranslator::convert));
        } else if (element.isJsonPrimitive()) {
            JsonPrimitive primitive = (JsonPrimitive) element;
            if (primitive.isString()) {
                return primitive.getAsString();
            } else if (primitive.isBoolean()) {
                return primitive.getAsBoolean();
            } else if (primitive.isNumber()) {
                return primitive.getAsNumber();
            }
        }
        return null;
    }

}


text:
package org.wikipedia.settings;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Build;
import android.support.v7.preference.EditTextPreference;
import android.util.AttributeSet;

import org.wikipedia.R;

public class EditTextAutoSummarizePreference extends EditTextPreference {
    protected static final int DEFAULT_STYLE_ATTR = R.attr.editTextAutoSummarizePreferenceStyle;
    private static final int[] DEFAULT_STYLEABLE = R.styleable.EditTextAutoSummarizePreference;
    private static final int DEFAULT_STYLE = R.style.EditTextAutoSummarizePreference;
    private static final boolean DEFAULT_AUTO_SUMMARIZE = true;

    private boolean autoSummarize = DEFAULT_AUTO_SUMMARIZE;

    public EditTextAutoSummarizePreference(Context context) {
        this(context, null);
    }

    public EditTextAutoSummarizePreference(Context context, AttributeSet attrs) {
        this(context, attrs, DEFAULT_STYLE_ATTR);
    }

    public EditTextAutoSummarizePreference(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(attrs, defStyleAttr, DEFAULT_STYLE);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public EditTextAutoSummarizePreference(Context context, AttributeSet attrs, int defStyleAttr,
           int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init(attrs, defStyleAttr, defStyleRes);
    }

    public boolean isAutoSummarize() {
        return autoSummarize;
    }

    public void setAutoSummarize(boolean summarize) {
        autoSummarize = summarize;
        updateAutoSummary();
    }

    @Override
    public void onAttached() {
        super.onAttached();
        updateAutoSummary();
    }

    @Override
    protected boolean persistString(String value) {
        boolean persistent = super.persistString(value);

        updateAutoSummary(value);

        return persistent;
    }

    protected boolean isSet() {
        return shouldPersist() && getSharedPreferences().contains(getKey());
    }

    protected String getString(int id, Object... formatArgs) {
        return getContext().getString(id, formatArgs);
    }

    protected void updateAutoSummary() {
        updateAutoSummary(getPersistedString(null));
    }

    protected void updateAutoSummary(String value) {
        if (isAutoSummarize()) {
            setSummary(isSet() ? value : getNoValueSummary());
        }
    }

    protected String getNoValueSummary() {
        return getString(R.string.preference_summary_no_value);
    }

    private void setAttributes(AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        TypedArray array = getContext().obtainStyledAttributes(attrs, DEFAULT_STYLEABLE,
                defStyleAttr, defStyleRes);
        autoSummarize = array.getBoolean(R.styleable.EditTextAutoSummarizePreference_autoSummarize,
                DEFAULT_AUTO_SUMMARIZE);
        array.recycle();
    }

    private void init(AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        setAttributes(attrs, defStyleAttr, defStyleRes);
    }
}


text:
package Lev07.task0704;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/*
Переверни массив
*/

public class Solution {
    public static void main(String[] args) throws IOException {
        int[] numbers = new int[10];
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        //создаем массив
        for (int i = 0; i< numbers.length; i++){
            String s = reader.readLine();
            numbers[i] = Integer.parseInt(s);
        }
        //переворачиваем массив
        for (int i = numbers.length; i > 0; i--){
            System.out.println(numbers[i-1]);
        }
    }
}


text:
#ifndef _MAGICKCORE_LIST_H
#define _MAGICKCORE_LIST_H

#if defined(__cplusplus) || defined(c_plusplus)
extern "C" {
#endif

extern MagickExport Image
  *CloneImageList(const Image *,ExceptionInfo *),
  *CloneImages(const Image *,const char *,ExceptionInfo *),
  *DestroyImageList(Image *),
  *GetFirstImageInList(const Image *),
  *GetImageFromList(const Image *,const long),
  *GetLastImageInList(const Image *),
  *GetNextImageInList(const Image *),
  *GetPreviousImageInList(const Image *),
  **ImageListToArray(const Image *,ExceptionInfo *),
  *NewImageList(void),
  *RemoveImageFromList(Image **),
  *RemoveLastImageFromList(Image **),
  *RemoveFirstImageFromList(Image **),
  *SpliceImageIntoList(Image **,const unsigned long,const Image *),
  *SplitImageList(Image *),
  *SyncNextImageInList(const Image *);

extern MagickExport long
  GetImageIndexInList(const Image *);

extern MagickExport unsigned long
  GetImageListLength(const Image *);

extern MagickExport void
  AppendImageToList(Image **,const Image *),
  DeleteImageFromList(Image **),
  DeleteImages(Image **,const char *,ExceptionInfo *),
  InsertImageInList(Image **,Image *),
  PrependImageToList(Image **,Image *),
  ReplaceImageInList(Image **,Image *),
  ReverseImageList(Image **),
  SyncImageList(Image *);

#if defined(__cplusplus) || defined(c_plusplus)
}
#endif

#endif


text:
<?php

namespace Zelenin\yii\SemanticUI\modules;

use Yii;
use yii\helpers\ArrayHelper;
use yii\helpers\Html;
use yii\helpers\Json;
use Zelenin\yii\SemanticUI\Elements;
use Zelenin\yii\SemanticUI\Widget;

class Accordion extends Widget
{
    public $items = [];

    public $titleOptions = [];
    public $contentOptions = [];

    const TYPE_STYLED = 'styled';
    public $styled = false;

    const TYPE_FLUID = 'fluid';
    public $fluid = false;

    const TYPE_VERTICAL = 'vertical';
    public $vertical = false;

    const TYPE_INVERTED = 'inverted';
    public $inverted = false;

    public function run()
    {
        $this->registerJs();

        Html::addCssClass($this->options, 'ui accordion');
        if ($this->styled) {
            Html::addCssClass($this->options, self::TYPE_STYLED);
        }
        if ($this->fluid) {
            Html::addCssClass($this->options, self::TYPE_FLUID);
        }
        if ($this->vertical) {
            Html::addCssClass($this->options, self::TYPE_VERTICAL);
        }
        if ($this->inverted) {
            Html::addCssClass($this->options, self::TYPE_INVERTED);
            echo Elements::segment(Html::tag('div', $this->renderItems(), $this->options), ['class' => self::TYPE_INVERTED]);
        } else {
            echo Html::tag('div', $this->renderItems(), $this->options);
        }
    }

    public function renderItems()
    {
        $items = '';
        foreach ($this->items as $item) {
            $items .= $this->renderItem($this->normalizeItem($item));
        }
        return $items;
    }

    public function renderItem($item)
    {
        return $this->renderTitle($item) . $this->renderContent($item);
    }

    public function renderTitle($item)
    {
        $encode = ArrayHelper::getValue($this->titleOptions, 'encode', true);
        $title = Elements::icon('dropdown') . ($encode ? Html::encode($item['title']) : $item['title']);
        $options = $this->titleOptions;
        Html::addCssClass($options, 'title');
        if ($item['active']) {
            Html::addCssClass($options, 'active');
        }
        return Html::tag('div', $title, $options);
    }

    public function renderContent($item)
    {
        $encode = ArrayHelper::getValue($this->contentOptions, 'encode', true);
        $content = $encode ? Html::encode($item['content']) : $item['content'];
        $options = $this->contentOptions;
        Html::addCssClass($options, 'content');
        if ($item['active']) {
            Html::addCssClass($options, 'active');
        }
        return Html::tag('div', $content, $options);
    }

    public function normalizeItem($item)
    {
        $item['active'] = ArrayHelper::remove($item, 'active', false);
        return $item;
    }

    public function registerJs()
    {
        $this->registerJsAsset();
        $clientOptions = $this->clientOptions ? Json::encode($this->clientOptions) : null;
        $this->getView()->registerJs('jQuery("#' . $this->options['id'] . '").accordion(' . $clientOptions . ');');
    }
}


text:
#include "vertex.h"
#include "FGlib.h"

#include "sparse_matrix.h"
#include "generic_type.h"
#include "matrix_header.h"
#include "col_vec.h"
#include "EM_vector.h"
#include "EM_vv_store.h"

namespace fg
{

namespace detail
{

/*
 * This task performs computation on a sparse matrix in the FlashGraph format.
 */
class fg_row_compute_task: public fm::detail::compute_task
{
	fm::matrix_io io;
	off_t off;
	char *buf;
	size_t buf_size;
protected:
	// rows in the input matrix.
	fm::detail::row_portions::ptr in_row_portions;
	// rows in the output matrix.
	fm::detail::local_matrix_store::ptr out_rows;
	char *raw_out_rows;
public:
	fg_row_compute_task(fm::detail::matrix_store &output, const fm::matrix_io &_io,
			fm::detail::row_portions::ptr in_row_portions): io(_io) {
		off_t orig_off = io.get_loc().get_offset();
		off = ROUND_PAGE(orig_off);
		buf_size = ROUNDUP_PAGE(orig_off - off + io.get_size());
		buf = (char *) valloc(buf_size);

		this->in_row_portions = in_row_portions;
		this->out_rows = output.get_portion(_io.get_top_left().get_row_idx(),
				0, _io.get_num_rows(), output.get_num_cols());
		assert(out_rows);
		this->raw_out_rows = out_rows->get_raw_arr();
		assert(raw_out_rows);
	}

	~fg_row_compute_task() {
		free(buf);
	}
	virtual void run(char *buf, size_t size);
	virtual void run_on_row(const fg::ext_mem_undirected_vertex &v) = 0;
	virtual safs::io_request get_request() const {
		return safs::io_request(buf, safs::data_loc_t(io.get_loc().get_file_id(),
					off), buf_size, READ);
	}
};

/*
 * This task performs sparse matrix dense matrix multiplication
 * in the FlashGraph format.
 * We implement this method for the sake of compatibility. It doesn't
 * run very fast.
 */
template<class DenseType, class SparseType, int ROW_WIDTH>
class fg_row_spmm_task: public fg_row_compute_task
{
	fm::detail::matrix_store &output;
public:
	fg_row_spmm_task(fm::detail::row_portions::ptr in_row_portions,
			fm::detail::matrix_store &_output, const fm::matrix_io &_io): fg_row_compute_task(
				_output, _io, in_row_portions), output(_output) {
		assert(in_row_portions->get_type() == fm::get_scalar_type<DenseType>());
		assert(output.get_type() == fm::get_scalar_type<DenseType>());
		assert(in_row_portions->get_num_cols() == output.get_num_cols());
		assert(in_row_portions->get_num_cols() == (size_t) ROW_WIDTH);
	}

	void run_on_row(const fg::ext_mem_undirected_vertex &v);
};

template<class DenseType, class SparseType, int ROW_WIDTH>
void fg_row_spmm_task<DenseType, SparseType, ROW_WIDTH>::run_on_row(
		const fg::ext_mem_undirected_vertex &v)
{
	DenseType res[ROW_WIDTH];
	for (size_t i = 0; i < (size_t) ROW_WIDTH; i++)
		res[i] = 0;

	bool has_val = v.has_edge_data();
	for (size_t i = 0; i < v.get_num_edges(); i++) {
		fg::vertex_id_t id = v.get_neighbor(i);
		SparseType data = 1;
		if (has_val)
			data = v.get_edge_data<SparseType>(i);
		const DenseType *row = (const DenseType *) in_row_portions->get_row(id);
		for (size_t j = 0; j < (size_t) ROW_WIDTH; j++)
			res[j] += row[j] * data;
	}
	size_t rel_row_idx = v.get_id() - out_rows->get_global_start_row();
	assert(rel_row_idx < out_rows->get_num_rows());
	char *row = raw_out_rows + rel_row_idx * ROW_WIDTH * sizeof(DenseType);
	memcpy(row, res, sizeof(DenseType) * ROW_WIDTH);
}

template<class DenseType, class SparseType>
class fg_row_spmm_task<DenseType, SparseType, 0>: public fg_row_compute_task
{
	fm::detail::matrix_store &output;
public:
	fg_row_spmm_task(fm::detail::row_portions::ptr in_row_portions,
			fm::detail::matrix_store &_output, const fm::matrix_io &_io): fg_row_compute_task(
				_output, _io, in_row_portions), output(_output) {
		assert(in_row_portions->get_type() == fm::get_scalar_type<DenseType>());
		assert(output.get_type() == fm::get_scalar_type<DenseType>());
		assert(in_row_portions->get_num_cols() == output.get_num_cols());
	}

	void run_on_row(const fg::ext_mem_undirected_vertex &v) {
		DenseType res[in_row_portions->get_num_cols()];
		for (size_t i = 0; i < in_row_portions->get_num_cols(); i++)
			res[i] = 0;

		bool has_val = v.has_edge_data();
		for (size_t i = 0; i < v.get_num_edges(); i++) {
			fg::vertex_id_t id = v.get_neighbor(i);
			SparseType data = 1;
			if (has_val)
				data = v.get_edge_data<SparseType>(i);
			const DenseType *row = (const DenseType *) in_row_portions->get_row(id);
			for (size_t j = 0; j < in_row_portions->get_num_cols(); j++)
				res[j] += row[j] * data;
		}
		size_t rel_row_idx = v.get_id() - out_rows->get_global_start_row();
		assert(rel_row_idx < out_rows->get_num_rows());
		char *row = raw_out_rows
			+ rel_row_idx * output.get_num_cols() * sizeof(DenseType);
		memcpy(row, res, sizeof(DenseType) * output.get_num_cols());
	}
};

///////////// The code for sparse matrix of the FlashGraph format //////////////

void fg_row_compute_task::run(char *buf, size_t size)
{
	assert(this->buf == buf);
	assert(this->buf_size == size);

	char *buf_p = buf + (io.get_loc().get_offset() - off);
	fg::ext_mem_undirected_vertex *v = (fg::ext_mem_undirected_vertex *) buf_p;
	for (size_t i = 0; i < io.get_num_rows(); i++) {
		size_t vsize = v->get_size();
		assert(buf_size >= vsize);
		buf_size -= vsize;
		buf_p += vsize;
		run_on_row(*v);
		v = (fg::ext_mem_undirected_vertex *) buf_p;
	}
}

template<class DenseType, class SparseType>
class spmm_creator: public fm::detail::task_creator
{
	fm::detail::row_portions::ptr in_row_portions;
	fm::detail::matrix_store::ptr output;
	fm::detail::EM_matrix_stream::ptr output_stream;
	const fm::sparse_matrix &mat;

	spmm_creator(const fm::sparse_matrix &_mat, size_t num_in_cols): mat(_mat) {
	}

public:
	static fm::detail::task_creator::ptr create(const fm::sparse_matrix &mat,
			size_t num_in_cols) {
		return fm::detail::task_creator::ptr(new spmm_creator<DenseType, SparseType>(
					mat, num_in_cols));
	}

	virtual void complete() {
		if (output_stream) {
			fm::detail::EM_matrix_store::ptr em_out
				= std::dynamic_pointer_cast<fm::detail::EM_matrix_store>(output);
			assert(em_out);
			em_out->wait4complete();
			assert(output_stream->is_complete());
		}
	}

	virtual bool set_data(fm::detail::matrix_store::const_ptr in,
			fm::detail::matrix_store::ptr out, const fm::block_2d_size &block_size) {
		if (in->get_type() != fm::get_scalar_type<DenseType>()
				|| out->get_type() != fm::get_scalar_type<DenseType>()) {
			BOOST_LOG_TRIVIAL(error) << "wrong matrix type in spmm creator";
			return false;
		}
		this->output = out;
		this->in_row_portions = fm::detail::row_portions::create(in, block_size.get_num_cols());
		if (in_row_portions == NULL)
			return false;
		if (!output->is_in_mem())
			output_stream = fm::detail::EM_matrix_stream::create(
					std::dynamic_pointer_cast<fm::detail::EM_matrix_store>(output));
		return true;
	}

	virtual std::vector<fm::detail::EM_object *> get_EM_objs() {
		std::vector<fm::detail::EM_object *> ret;
		if (!output->is_in_mem()) {
			const fm::detail::EM_object *obj
				= dynamic_cast<const fm::detail::EM_object *>(output.get());
			ret.push_back(const_cast<fm::detail::EM_object *>(obj));
		}
		return ret;
	}

	virtual fm::detail::compute_task::ptr create(const fm::matrix_io &io) const {
		assert(in_row_portions);
		switch (output->get_num_cols()) {
			case 1: return fm::detail::compute_task::ptr(new fg_row_spmm_task<DenseType,
							SparseType, 1>(in_row_portions, *output, io));
			case 2: return fm::detail::compute_task::ptr(new fg_row_spmm_task<DenseType,
							SparseType, 2>(in_row_portions, *output, io));
			case 4: return fm::detail::compute_task::ptr(new fg_row_spmm_task<DenseType,
							SparseType, 4>(in_row_portions, *output, io));
			case 8: return fm::detail::compute_task::ptr(new fg_row_spmm_task<DenseType,
							SparseType, 8>(in_row_portions, *output, io));
			case 16: return fm::detail::compute_task::ptr(new fg_row_spmm_task<DenseType,
							 SparseType, 16>(in_row_portions, *output, io));
			default: return fm::detail::compute_task::ptr(new fg_row_spmm_task<DenseType,
							 SparseType, 0>(in_row_portions, *output, io));
		}
	}
};

namespace
{

class get_diag_apply: public fm::arr_apply_operate
{
	const fm::scalar_type &entry_type;
	size_t block_size;
public:
	get_diag_apply(const fm::scalar_type &_type,
			size_t block_size): entry_type(_type) {
		this->block_size = block_size;
	}

	virtual void run(const fm::local_vec_store &in,
			fm::local_vec_store &out) const;
	virtual size_t get_num_out_eles(size_t num_input) const {
		return block_size;
	}

	virtual const fm::scalar_type &get_input_type() const {
		return fm::get_scalar_type<char>();
	}
	virtual const fm::scalar_type &get_output_type() const {
		return entry_type;
	}
};

void get_diag_apply::run(const fm::local_vec_store &in,
		fm::local_vec_store &out) const
{
	out.resize(block_size);
	out.reset_data();
	auto v = reinterpret_cast<const fg::ext_mem_undirected_vertex *>(
			in.get_raw_arr());
	auto first_vid = v->get_id();
	size_t off = 0;
	size_t num_vertices = 0;
	for (size_t i = 0; i < block_size; i++) {
		num_vertices++;
		auto vid = v->get_id();
		for (size_t j = 0; j < v->get_num_edges(); j++) {
			if (v->get_neighbor(j) == vid && v->get_edge_data_size() == 0) {
				assert(out.get_type() == fm::get_scalar_type<bool>());
				out.set<bool>(vid - first_vid, true);
				break;
			}
			else if (v->get_neighbor(j) == vid) {
				assert(entry_type.get_size() == v->get_edge_data_size());
				memcpy(out.get(vid - first_vid), v->get_raw_edge_data(j),
						entry_type.get_size());
				break;
			}
			// We don't need to search any more.
			else if (v->get_neighbor(j) > vid)
				break;
		}
		off += v->get_size();
		// If we have explored all vertices in the row block, we can
		// jump out now.
		if (off >= in.get_length())
			break;
		v = reinterpret_cast<const fg::ext_mem_undirected_vertex *>(
				in.get_raw_arr() + off);
	}
	out.resize(num_vertices);
}

}

static fm::col_vec::ptr get_diag(const std::vector<fm::row_block> &blocks,
		safs::file_io_factory::shared_ptr factory,
		const fm::scalar_type &entry_type, size_t block_size)
{
	fm::detail::vec_store::ptr vec = fm::detail::vec_store::create(factory,
			fm::get_scalar_type<char>());
	std::vector<off_t> offs(blocks.size());
	for (size_t i = 0; i < blocks.size(); i++)
		offs[i] = blocks[i].get_offset();
	fm::vector_vector::ptr vv = fm::vector_vector::create(
			fm::detail::vv_store::create(offs, vec));
	fm::vector_vector::ptr ret = vv->apply(get_diag_apply(entry_type,
				block_size));
	return fm::col_vec::create(ret->cat());
}

/*
 * Sparse square symmetric matrix. It is partitioned in rows.
 */
class fg_sparse_sym_matrix: public fm::sparse_matrix
{
	fm::block_2d_size block_size;
	// This works like the index of the sparse matrix.
	std::vector<fm::row_block> blocks;
	safs::file_io_factory::shared_ptr factory;

	fg_sparse_sym_matrix(safs::file_io_factory::shared_ptr factory,
			size_t nrows, const fm::scalar_type *entry_type): fm::sparse_matrix(
				nrows, entry_type, true) {
		this->factory = factory;
	}
public:
	static ptr create(fg::FG_graph::ptr, const fm::scalar_type *entry_type);

	// Nothing should happen for a symmetric matrix.
	virtual fm::sparse_matrix::ptr transpose() const {
		return fm::sparse_matrix::ptr(new fg_sparse_sym_matrix(*this));
	}

	virtual safs::file_io_factory::shared_ptr get_io_factory() const {
		return factory;
	}

	virtual fm::matrix_io_generator::ptr create_io_gen(
			const fm::detail::matrix_store &in) const {
		assert(!in.is_wide());
		size_t num_rows = in.get_portion_size().first;
		size_t num_brows = std::min((size_t) fm::matrix_conf.get_rb_io_size(),
				num_rows / fm::matrix_conf.get_row_block_size());
		fm::row_block_mapper mapper(blocks, num_brows);
		return fm::matrix_io_generator::create(blocks, get_num_rows(),
				get_num_cols(), factory->get_file_id(), mapper);
	}

	virtual const fm::block_2d_size &get_block_size() const {
		return block_size;
	}

	virtual void get_block_row_offs(const std::vector<off_t> &block_row_idxs,
			std::vector<off_t> &offs) const {
		throw unsupported_exception(
				"get_block_row_offs isn't supported in fg_sparse_sym_matrix");
	}

	virtual fm::detail::block_exec_order::ptr get_multiply_order(
			size_t num_block_rows, size_t num_block_cols) const {
		return fm::detail::block_exec_order::ptr(new fm::detail::seq_exec_order());
	}

	virtual fm::detail::task_creator::ptr get_multiply_creator(
			const fm::scalar_type &type, size_t num_in_cols) const {
		if (type == fm::get_scalar_type<int>())
			return spmm_creator<int, int>::create(*this, num_in_cols);
		else if (type == fm::get_scalar_type<long>())
			return spmm_creator<long, long>::create(*this, num_in_cols);
		else if (type == fm::get_scalar_type<size_t>())
			return spmm_creator<size_t, size_t>::create(*this, num_in_cols);
		else if (type == fm::get_scalar_type<float>())
			return spmm_creator<float, float>::create(*this, num_in_cols);
		else if (type == fm::get_scalar_type<double>())
			return spmm_creator<double, double>::create(*this, num_in_cols);
		else {
			BOOST_LOG_TRIVIAL(error) << "unsupported type";
			return fm::detail::task_creator::ptr();
		}
	}
	virtual fm::col_vec::ptr get_diag() const {
		return fg::detail::get_diag(blocks, factory, get_type(),
				fm::matrix_conf.get_row_block_size());
	}
};

fm::sparse_matrix::ptr fg_sparse_sym_matrix::create(fg::FG_graph::ptr fg,
		const fm::scalar_type *entry_type)
{
	// Initialize vertex index.
	fg::vertex_index::ptr index = fg->get_index_data();
	assert(index != NULL);
	assert(!index->get_graph_header().is_directed_graph());

	if (entry_type)
		assert(entry_type->get_size()
				== (size_t) index->get_graph_header().get_edge_data_size());
	fg::vsize_t num_vertices = index->get_num_vertices();
	fg_sparse_sym_matrix *m = new fg_sparse_sym_matrix(fg->get_graph_io_factory(
				safs::REMOTE_ACCESS), num_vertices, entry_type);

	// Generate the matrix index from the vertex index.
	if (index->is_compressed()) {
		fg::in_mem_cundirected_vertex_index::ptr uindex
			= fg::in_mem_cundirected_vertex_index::create(*index);
		for (size_t i = 0; i < num_vertices;
				i += fm::matrix_conf.get_row_block_size()) {
			fg::vertex_offset off = uindex->get_vertex(i);
			m->blocks.emplace_back(off.get_off());
		}
		size_t graph_size = uindex->get_vertex(num_vertices - 1).get_off()
			+ uindex->get_size(num_vertices - 1);
		m->blocks.emplace_back(graph_size);
	}
	else {
		fg::undirected_vertex_index::ptr uindex
			= fg::undirected_vertex_index::cast(index);
		for (size_t i = 0; i < num_vertices;
				i += fm::matrix_conf.get_row_block_size()) {
			fg::ext_mem_vertex_info info = uindex->get_vertex_info(i);
			m->blocks.emplace_back(info.get_off());
		}
		m->blocks.emplace_back(uindex->get_graph_size());
	}

	return fm::sparse_matrix::ptr(m);
}

/*
 * Sparse asymmetric square matrix. It is partitioned in rows.
 */
class fg_sparse_asym_matrix: public fm::sparse_matrix
{
	fm::block_2d_size block_size;
	// These work like the index of the sparse matrix.
	// out_blocks index the original matrix.
	std::shared_ptr<std::vector<fm::row_block> > out_blocks;
	// in_blocks index the transpose of the matrix.
	std::shared_ptr<std::vector<fm::row_block> > in_blocks;
	safs::file_io_factory::shared_ptr factory;

	fg_sparse_asym_matrix(safs::file_io_factory::shared_ptr factory,
			size_t nrows, const fm::scalar_type *entry_type): fm::sparse_matrix(
				nrows, entry_type, false) {
		this->factory = factory;
		out_blocks = std::shared_ptr<std::vector<fm::row_block> >(
				new std::vector<fm::row_block>());
		in_blocks = std::shared_ptr<std::vector<fm::row_block> >(
				new std::vector<fm::row_block>());
	}
public:
	static ptr create(fg::FG_graph::ptr, const fm::scalar_type *entry_type);

	virtual safs::file_io_factory::shared_ptr get_io_factory() const {
		return factory;
	}

	virtual fm::sparse_matrix::ptr transpose() const {
		fg_sparse_asym_matrix *ret = new fg_sparse_asym_matrix(*this);
		ret->fm::sparse_matrix::_transpose();
		ret->out_blocks = this->in_blocks;
		ret->in_blocks = this->out_blocks;
		return fm::sparse_matrix::ptr(ret);
	}

	virtual fm::matrix_io_generator::ptr create_io_gen(
			const fm::detail::matrix_store &in) const {
		if (in.is_wide()) {
			BOOST_LOG_TRIVIAL(error) << boost::format(
					"The input matrix has unexpected shape: %1% x %2%")
				% in.get_num_rows() % in.get_num_cols();
			return fm::matrix_io_generator::ptr();
		}
		size_t num_rows = in.get_portion_size().first;
		size_t num_brows = std::min((size_t) fm::matrix_conf.get_rb_io_size(),
				num_rows / fm::matrix_conf.get_row_block_size());
		fm::row_block_mapper mapper(*out_blocks, num_brows);
		return fm::matrix_io_generator::create(*out_blocks, get_num_rows(),
				get_num_cols(), factory->get_file_id(), mapper);
	}

	virtual const fm::block_2d_size &get_block_size() const {
		return block_size;
	}

	virtual void get_block_row_offs(const std::vector<off_t> &block_row_idxs,
			std::vector<off_t> &offs) const {
		throw unsupported_exception(
				"get_block_row_offs isn't supported in fg_sparse_asym_matrix");
	}

	virtual fm::detail::block_exec_order::ptr get_multiply_order(
			size_t num_block_rows, size_t num_block_cols) const {
		return fm::detail::block_exec_order::ptr(new fm::detail::seq_exec_order());
	}

	virtual fm::detail::task_creator::ptr get_multiply_creator(
			const fm::scalar_type &type, size_t num_in_cols) const {
		if (type == fm::get_scalar_type<int>())
			return spmm_creator<int, int>::create(*this, num_in_cols);
		else if (type == fm::get_scalar_type<long>())
			return spmm_creator<long, long>::create(*this, num_in_cols);
		else if (type == fm::get_scalar_type<size_t>())
			return spmm_creator<size_t, size_t>::create(*this, num_in_cols);
		else if (type == fm::get_scalar_type<float>())
			return spmm_creator<float, float>::create(*this, num_in_cols);
		else if (type == fm::get_scalar_type<double>())
			return spmm_creator<double, double>::create(*this, num_in_cols);
		else {
			BOOST_LOG_TRIVIAL(error) << "unsupported type";
			return fm::detail::task_creator::ptr();
		}
	}
	virtual fm::col_vec::ptr get_diag() const {
		return fg::detail::get_diag(*in_blocks, factory, get_type(),
				fm::matrix_conf.get_row_block_size());
	}
};

fm::sparse_matrix::ptr fg_sparse_asym_matrix::create(fg::FG_graph::ptr fg,
		const fm::scalar_type *entry_type)
{
	// Initialize vertex index.
	fg::vertex_index::ptr index = fg->get_index_data();
	assert(index != NULL);
	assert(index->get_graph_header().is_directed_graph());

	if (entry_type)
		assert(entry_type->get_size()
				== (size_t) index->get_graph_header().get_edge_data_size());
	fg::vsize_t num_vertices = index->get_num_vertices();
	fg_sparse_asym_matrix *m = new fg_sparse_asym_matrix(fg->get_graph_io_factory(
				safs::REMOTE_ACCESS), num_vertices, entry_type);

	if (index->is_compressed()) {
		fg::in_mem_cdirected_vertex_index::ptr dindex
			= fg::in_mem_cdirected_vertex_index::create(*index);
		for (size_t i = 0; i < num_vertices;
				i += fm::matrix_conf.get_row_block_size()) {
			fg::directed_vertex_entry ventry = dindex->get_vertex(i);
			m->out_blocks->emplace_back(ventry.get_out_off());
			m->in_blocks->emplace_back(ventry.get_in_off());
		}
		fg::directed_vertex_entry ventry = dindex->get_vertex(num_vertices - 1);
		m->out_blocks->emplace_back(ventry.get_out_off()
				+ dindex->get_out_size(num_vertices - 1));
		m->in_blocks->emplace_back(ventry.get_in_off()
				+ dindex->get_in_size(num_vertices - 1));
	}
	else {
		fg::directed_vertex_index::ptr dindex
			= fg::directed_vertex_index::cast(index);
		// Generate the matrix index from the vertex index.
		for (size_t i = 0; i < num_vertices;
				i += fm::matrix_conf.get_row_block_size()) {
			fg::ext_mem_vertex_info info = dindex->get_vertex_info_out(i);
			m->out_blocks->emplace_back(info.get_off());

			info = dindex->get_vertex_info_in(i);
			m->in_blocks->emplace_back(info.get_off());
		}
		fg::ext_mem_vertex_info info
			= dindex->get_vertex_info_out(num_vertices - 1);
		m->out_blocks->emplace_back(info.get_off() + info.get_size());
		info = dindex->get_vertex_info_in(num_vertices - 1);
		m->in_blocks->emplace_back(info.get_off() + info.get_size());
	}

	return fm::sparse_matrix::ptr(m);
}

}

fm::sparse_matrix::ptr create_sparse_matrix(fg::FG_graph::ptr fg,
		const fm::scalar_type *entry_type)
{
	const fg::graph_header &header = fg->get_graph_header();
	if (header.is_directed_graph())
		return detail::fg_sparse_asym_matrix::create(fg, entry_type);
	else
		return detail::fg_sparse_sym_matrix::create(fg, entry_type);
}

}