text:
Contributing to Ruby on Rails
=============================

This guide covers ways in which _you_ can become a part of the ongoing development of Ruby on Rails.

After reading this guide, you will know:

* How to use GitHub to report issues.
* How to clone master and run the test suite.
* How to help resolve existing issues.
* How to contribute to the Ruby on Rails documentation.
* How to contribute to the Ruby on Rails code.

Ruby on Rails is not "someone else's framework." Over the years, hundreds of people have contributed to Ruby on Rails ranging from a single character to massive architectural changes or significant documentation - all with the goal of making Ruby on Rails better for everyone. Even if you don't feel up to writing code or documentation yet, there are a variety of other ways that you can contribute, from reporting issues to testing patches.

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

Reporting an Issue
------------------

Ruby on Rails uses [GitHub Issue Tracking](https://github.com/rails/rails/issues) to track issues (primarily bugs and contributions of new code). If you've found a bug in Ruby on Rails, this is the place to start. You'll need to create a (free) GitHub account in order to submit an issue, to comment on them or to create pull requests.

NOTE: Bugs in the most recent released version of Ruby on Rails are likely to get the most attention. Also, the Rails core team is always interested in feedback from those who can take the time to test _edge Rails_ (the code for the version of Rails that is currently under development). Later in this guide you'll find out how to get edge Rails for testing.

### Creating a Bug Report

If you've found a problem in Ruby on Rails which is not a security risk, do a search in GitHub under [Issues](https://github.com/rails/rails/issues) in case it has already been reported. If you do not find any issue addressing it you may proceed to [open a new one](https://github.com/rails/rails/issues/new). (See the next section for reporting security issues.)

Your issue report should contain a title and a clear description of the issue at the bare minimum. You should include as much relevant information as possible and should at least post a code sample that demonstrates the issue. It would be even better if you could include a unit test that shows how the expected behavior is not occurring. Your goal should be to make it easy for yourself - and others - to replicate the bug and figure out a fix.

Then, don't get your hopes up! Unless you have a "Code Red, Mission Critical, the World is Coming to an End" kind of bug, you're creating this issue report in the hope that others with the same problem will be able to collaborate with you on solving it. Do not expect that the issue report will automatically see any activity or that others will jump to fix it. Creating an issue like this is mostly to help yourself start on the path of fixing the problem and for others to confirm it with an "I'm having this problem too" comment.

### Create a Self-Contained gist for Active Record and Action Controller Issues

If you are filing a bug report, please use
[Active Record template for gems](https://github.com/rails/rails/blob/master/guides/bug_report_templates/active_record_gem.rb) or
[Action Controller template for gems](https://github.com/rails/rails/blob/master/guides/bug_report_templates/action_controller_gem.rb)
if the bug is found in a published gem, and
[Active Record template for master](https://github.com/rails/rails/blob/master/guides/bug_report_templates/active_record_master.rb) or
[Action Controller template for master](https://github.com/rails/rails/blob/master/guides/bug_report_templates/action_controller_master.rb)
if the bug happens in the master branch.

### Special Treatment for Security Issues

WARNING: Please do not report security vulnerabilities with public GitHub issue reports. The [Rails security policy page](http://rubyonrails.org/security) details the procedure to follow for security issues.

### What about Feature Requests?

Please don't put "feature request" items into GitHub Issues. If there's a new
feature that you want to see added to Ruby on Rails, you'll need to write the
code yourself - or convince someone else to partner with you to write the code.
Later in this guide you'll find detailed instructions for proposing a patch to
Ruby on Rails. If you enter a wish list item in GitHub Issues with no code, you
can expect it to be marked "invalid" as soon as it's reviewed.

Sometimes, the line between 'bug' and 'feature' is a hard one to draw.
Generally, a feature is anything that adds new behavior, while a bug is
anything that fixes already existing behavior that is misbehaving. Sometimes,
the core team will have to make a judgement call. That said, the distinction
generally just affects which release your patch will get in to; we love feature
submissions! They just won't get backported to maintenance branches.

If you'd like feedback on an idea for a feature before doing the work for make
a patch, please send an email to the [rails-core mailing
list](https://groups.google.com/forum/?fromgroups#!forum/rubyonrails-core). You
might get no response, which means that everyone is indifferent. You might find
someone who's also interested in building that feature. You might get a "This
won't be accepted." But it's the proper place to discuss new ideas. GitHub
Issues are not a particularly good venue for the sometimes long and involved
discussions new features require.

Helping to Resolve Existing Issues
----------------------------------

As a next step beyond reporting issues, you can help the core team resolve existing issues. If you check the [Everyone's Issues](https://github.com/rails/rails/issues) list in GitHub Issues, you'll find lots of issues already requiring attention. What can you do for these? Quite a bit, actually:

### Verifying Bug Reports

For starters, it helps just to verify bug reports. Can you reproduce the reported issue on your own computer? If so, you can add a comment to the issue saying that you're seeing the same thing.

If something is very vague, can you help squash it down into something specific? Maybe you can provide additional information to help reproduce a bug, or help by eliminating needless steps that aren't required to demonstrate the problem.

If you find a bug report without a test, it's very useful to contribute a failing test. This is also a great way to get started exploring the source code: looking at the existing test files will teach you how to write more tests. New tests are best contributed in the form of a patch, as explained later on in the "Contributing to the Rails Code" section.

Anything you can do to make bug reports more succinct or easier to reproduce is a help to folks trying to write code to fix those bugs - whether you end up writing the code yourself or not.

### Testing Patches

You can also help out by examining pull requests that have been submitted to Ruby on Rails via GitHub. To apply someone's changes you need first to create a dedicated branch:

```bash
$ git checkout -b testing_branch
```

Then you can use their remote branch to update your codebase. For example, let's say the GitHub user JohnSmith has forked and pushed to a topic branch "orange" located at https://github.com/JohnSmith/rails.

```bash
$ git remote add JohnSmith git://github.com/JohnSmith/rails.git
$ git pull JohnSmith orange
```

After applying their branch, test it out! Here are some things to think about:

* Does the change actually work?
* Are you happy with the tests? Can you follow what they're testing? Are there any tests missing?
* Does it have the proper documentation coverage? Should documentation elsewhere be updated?
* Do you like the implementation? Can you think of a nicer or faster way to implement a part of their change?

Once you're happy that the pull request contains a good change, comment on the GitHub issue indicating your approval. Your comment should indicate that you like the change and what you like about it. Something like:

>I like the way you've restructured that code in generate_finder_sql - much nicer. The tests look good too.

If your comment simply says "+1", then odds are that other reviewers aren't going to take it too seriously. Show that you took the time to review the pull request.

Contributing to the Rails Documentation
---------------------------------------

Ruby on Rails has two main sets of documentation: the guides, which help you
learn about Ruby on Rails, and the API, which serves as a reference.

You can help improve the Rails guides by making them more coherent, consistent or readable, adding missing information, correcting factual errors, fixing typos, or bringing it up to date with the latest edge Rails.

You can either open a pull request to [Rails](http://github.com/rails/rails) or
ask the [Rails core team](http://rubyonrails.org/core) for commit access on
docrails if you contribute regularly.
Please do not open pull requests in docrails, if you'd like to get feedback on your
change, ask for it in [Rails](http://github.com/rails/rails) instead.

Docrails is merged with master regularly, so you are effectively editing the Ruby on Rails documentation.

If you are unsure of the documentation changes, you can create an issue in the [Rails](https://github.com/rails/rails/issues) issues tracker on GitHub.

When working with documentation, please take into account the [API Documentation Guidelines](api_documentation_guidelines.html) and the [Ruby on Rails Guides Guidelines](ruby_on_rails_guides_guidelines.html).

NOTE: As explained earlier, ordinary code patches should have proper documentation coverage. Docrails is only used for isolated documentation improvements.

NOTE: To help our CI servers you should add [ci skip] to your documentation commit message to skip build on that commit. Please remember to use it for commits containing only documentation changes.

WARNING: Docrails has a very strict policy: no code can be touched whatsoever, no matter how trivial or small the change. Only RDoc and guides can be edited via docrails. Also, CHANGELOGs should never be edited in docrails.

Contributing to the Rails Code
------------------------------

### Setting Up a Development Environment

To move on from submitting bugs to helping resolve existing issues or contributing your own code to Ruby on Rails, you _must_ be able to run its test suite. In this section of the guide you'll learn how to setup the tests on your own computer.

#### The Easy Way

The easiest and recommended way to get a development environment ready to hack is to use the [Rails development box](https://github.com/rails/rails-dev-box).

#### The Hard Way

In case you can't use the Rails development box, see [this other guide](development_dependencies_install.html).

### Clone the Rails Repository

To be able to contribute code, you need to clone the Rails repository:

```bash
$ git clone git://github.com/rails/rails.git
```

and create a dedicated branch:

```bash
$ cd rails
$ git checkout -b my_new_branch
```

It doesn't matter much what name you use, because this branch will only exist on your local computer and your personal repository on GitHub. It won't be part of the Rails Git repository.

### Running an Application Against Your Local Branch

In case you need a dummy Rails app to test changes, the `--dev` flag of `rails new` generates an application that uses your local branch:

```bash
$ cd rails
$ bundle exec rails new ~/my-test-app --dev
```

The application generated in `~/my-test-app` runs against your local branch
and in particular sees any modifications upon server reboot.

### Write Your Code

Now get busy and add/edit code. You're on your branch now, so you can write whatever you want (make sure you're on the right branch with `git branch -a`). But if you're planning to submit your change back for inclusion in Rails, keep a few things in mind:

* Get the code right.
* Use Rails idioms and helpers.
* Include tests that fail without your code, and pass with it.
* Update the (surrounding) documentation, examples elsewhere, and the guides: whatever is affected by your contribution.

TIP: Changes that are cosmetic in nature and do not add anything substantial to the stability, functionality, or testability of Rails will generally not be accepted (read more about [our rationales behind this decision](https://github.com/rails/rails/pull/13771#issuecomment-32746700)).

#### Follow the Coding Conventions

Rails follows a simple set of coding style conventions:

* Two spaces, no tabs (for indentation).
* No trailing whitespace. Blank lines should not have any spaces.
* Indent after private/protected.
* Use Ruby >= 1.9 syntax for hashes. Prefer `{ a: :b }` over `{ :a => :b }`.
* Prefer `&&`/`||` over `and`/`or`.
* Prefer class << self over self.method for class methods.
* Use `MyClass.my_method(my_arg)` not `my_method( my_arg )` or `my_method my_arg`.
* Use `a = b` and not `a=b`.
* Use assert_not methods instead of refute.
* Prefer `method { do_stuff }` instead of `method{do_stuff}` for single-line blocks.
* Follow the conventions in the source you see used already.

The above are guidelines - please use your best judgment in using them.

### Benchmark Your Code

If your change has an impact on the performance of Rails, please use the
[benchmark-ips](https://github.com/evanphx/benchmark-ips) gem to provide
benchmark results for comparison.

Here's an example of using benchmark-ips:

```ruby
require 'benchmark/ips'

Benchmark.ips do |x|
  x.report('addition') { 1 + 2 }
  x.report('addition with send') { 1.send(:+, 2) }
end
```

This will generate a report with the following information:

```
Calculating -------------------------------------
            addition     69114 i/100ms
  addition with send     64062 i/100ms
-------------------------------------------------
            addition  5307644.4 (±3.5%) i/s -   26539776 in   5.007219s
  addition with send  3702897.9 (±3.5%) i/s -   18513918 in   5.006723s
```

Please see the benchmark/ips [README](https://github.com/evanphx/benchmark-ips/blob/master/README.md) for more information.

### Running Tests

It is not customary in Rails to run the full test suite before pushing
changes. The railties test suite in particular takes a long time, and even
more if the source code is mounted in `/vagrant` as happens in the recommended
workflow with the [rails-dev-box](https://github.com/rails/rails-dev-box).

As a compromise, test what your code obviously affects, and if the change is
not in railties, run the whole test suite of the affected component. If all
tests are passing, that's enough to propose your contribution. We have
[Travis CI](https://travis-ci.org/rails/rails) as a safety net for catching
unexpected breakages elsewhere.

#### Entire Rails:

To run all the tests, do:

```bash
$ cd rails
$ bundle exec rake test
```

#### For a Particular Component

You can run tests only for a particular component (e.g. Action Pack). For example,
to run Action Mailer tests:

```bash
$ cd actionmailer
$ bundle exec rake test
```

#### Running a Single Test

You can run a single test through ruby. For instance:

```bash
$ cd actionmailer
$ bundle exec ruby -w -Itest test/mail_layout_test.rb -n test_explicit_class_layout
```

The `-n` option allows you to run a single method instead of the whole
file.

##### Testing Active Record

This is how you run the Active Record test suite only for SQLite3:

```bash
$ cd activerecord
$ bundle exec rake test:sqlite3
```

You can now run the tests as you did for `sqlite3`. The tasks are respectively

```bash
test:mysql
test:mysql2
test:postgresql
```

Finally,

```bash
$ bundle exec rake test
```

will now run the four of them in turn.

You can also run any single test separately:

```bash
$ ARCONN=sqlite3 ruby -Itest test/cases/associations/has_many_associations_test.rb
```

To run a single test against all adapters, use:

```bash
$ bundle exec rake TEST=test/cases/associations/has_many_associations_test.rb
```

You can invoke `test_jdbcmysql`, `test_jdbcsqlite3` or `test_jdbcpostgresql` also. See the file `activerecord/RUNNING_UNIT_TESTS.rdoc` for information on running more targeted database tests, or the file `ci/travis.rb` for the test suite run by the continuous integration server.

### Warnings

The test suite runs with warnings enabled. Ideally, Ruby on Rails should issue no warnings, but there may be a few, as well as some from third-party libraries. Please ignore (or fix!) them, if any, and submit patches that do not issue new warnings.

If you are sure about what you are doing and would like to have a more clear output, there's a way to override the flag:

```bash
$ RUBYOPT=-W0 bundle exec rake test
```

### Updating the CHANGELOG

The CHANGELOG is an important part of every release. It keeps the list of changes for every Rails version.

You should add an entry to the CHANGELOG of the framework that you modified if you're adding or removing a feature, committing a bug fix or adding deprecation notices. Refactorings and documentation changes generally should not go to the CHANGELOG.

A CHANGELOG entry should summarize what was changed and should end with author's name and it should go on top of a CHANGELOG. You can use multiple lines if you need more space and you can attach code examples indented with 4 spaces. If a change is related to a specific issue, you should attach the issue's number. Here is an example CHANGELOG entry:

```
*   Summary of a change that briefly describes what was changed. You can use multiple
    lines and wrap them at around 80 characters. Code examples are ok, too, if needed:

        class Foo
          def bar
            puts 'baz'
          end
        end

    You can continue after the code example and you can attach issue number. GH#1234

    *Your Name*
```

Your name can be added directly after the last word if you don't provide any code examples or don't need multiple paragraphs. Otherwise, it's best to make as a new paragraph.

### Updating the Gemfile.lock

Some changes requires the dependencies to be upgraded. In these cases make sure you run `bundle update` to get the right version of the dependency and commit the `Gemfile.lock` file within your changes.

### Sanity Check

You should not be the only person who looks at the code before you submit it.
If you know someone else who uses Rails, try asking them if they'll check out
your work. If you don't know anyone else using Rails, try hopping into the IRC
room or posting about your idea to the rails-core mailing list. Doing this in
private before you push a patch out publicly is the "smoke test" for a patch:
if you can't convince one other developer of the beauty of your code, you're
unlikely to convince the core team either.

### Commit Your Changes

When you're happy with the code on your computer, you need to commit the changes to Git:

```bash
$ git commit -a
```

At this point, your editor should be fired up and you can write a message for this commit. Well formatted and descriptive commit messages are extremely helpful for the others, especially when figuring out why given change was made, so please take the time to write it.

Good commit message should be formatted according to the following example:

```
Short summary (ideally 50 characters or less)

More detailed description, if necessary. It should be wrapped to 72
characters. Try to be as descriptive as you can, even if you think that
the commit content is obvious, it may not be obvious to others. You
should add such description also if it's already present in bug tracker,
it should not be necessary to visit a webpage to check the history.

Description can have multiple paragraphs and you can use code examples
inside, just indent it with 4 spaces:

    class ArticlesController
      def index
        render json: Article.limit(10)
      end
    end

You can also add bullet points:

- you can use dashes or asterisks

- also, try to indent next line of a point for readability, if it's too
  long to fit in 72 characters
```

TIP. Please squash your commits into a single commit when appropriate. This simplifies future cherry picks, and also keeps the git log clean.

### Update Your Branch

It's pretty likely that other changes to master have happened while you were working. Go get them:

```bash
$ git checkout master
$ git pull --rebase
```

Now reapply your patch on top of the latest changes:

```bash
$ git checkout my_new_branch
$ git rebase master
```

No conflicts? Tests still pass? Change still seems reasonable to you? Then move on.

### Fork

Navigate to the Rails [GitHub repository](https://github.com/rails/rails) and press "Fork" in the upper right hand corner.

Add the new remote to your local repository on your local machine:

```bash
$ git remote add mine git@github.com:<your user name>/rails.git
```

Push to your remote:

```bash
$ git push mine my_new_branch
```

You might have cloned your forked repository into your machine and might want to add the original Rails repository as a remote instead, if that's the case here's what you have to do.

In the directory you cloned your fork:

```bash
$ git remote add rails git://github.com/rails/rails.git
```

Download new commits and branches from the official repository:

```bash
$ git fetch rails
```

Merge the new content:

```bash
$ git checkout master
$ git rebase rails/master
```

Update your fork:

```bash
$ git push origin master
```

If you want to update another branch:

```bash
$ git checkout branch_name
$ git rebase rails/branch_name
$ git push origin branch_name
```

### Issue a Pull Request

Navigate to the Rails repository you just pushed to (e.g.
https://github.com/your-user-name/rails) and click on "Pull Requests" seen in
the right panel. On the next page, press "New pull request" in the upper right
hand corner.

Click on "Edit", if you need to change the branches being compared (it compares
"master" by default) and press "Click to create a pull request for this
comparison".

Ensure the changesets you introduced are included. Fill in some details about
your potential patch including a meaningful title. When finished, press "Send
pull request". The Rails core team will be notified about your submission.

### Get some Feedback

Most pull requests will go through a few iterations before they get merged.
Different contributors will sometimes have different opinions, and often
patches will need revised before they can get merged.

Some contributors to Rails have email notifications from GitHub turned on, but
others do not. Furthermore, (almost) everyone who works on Rails is a
volunteer, and so it may take a few days for you to get your first feedback on
a pull request. Don't despair! Sometimes it's quick, sometimes it's slow. Such
is the open source life.

If it's been over a week, and you haven't heard anything, you might want to try
and nudge things along. You can use the [rubyonrails-core mailing
list](http://groups.google.com/group/rubyonrails-core/) for this. You can also
leave another comment on the pull request.

While you're waiting for feedback on your pull request, open up a few other
pull requests and give someone else some! I'm sure they'll appreciate it in
the same way that you appreciate feedback on your patches.

### Iterate as Necessary

It's entirely possible that the feedback you get will suggest changes. Don't get discouraged: the whole point of contributing to an active open source project is to tap into the knowledge of the community. If people are encouraging you to tweak your code, then it's worth making the tweaks and resubmitting. If the feedback is that your code doesn't belong in the core, you might still think about releasing it as a gem.

#### Squashing commits

One of the things that we may ask you to do is to "squash your commits", which
will combine all of your commits into a single commit. We prefer pull requests
that are a single commit. This makes it easier to backport changes to stable
branches, squashing makes it easier to revert bad commits, and the git history
can be a bit easier to follow. Rails is a large project, and a bunch of
extraneous commits can add a lot of noise.

In order to do this, you'll need to have a git remote that points at the main
Rails repository. This is useful anyway, but just in case you don't have it set
up, make sure that you do this first:

```bash
$ git remote add upstream https://github.com/rails/rails.git
```

You can call this remote whatever you'd like, but if you don't use `upstream`,
then change the name to your own in the instructions below.

Given that your remote branch is called `my_pull_request`, then you can do the
following:

```bash
$ git fetch upstream
$ git checkout my_pull_request
$ git rebase upstream/master
$ git rebase -i

< Choose 'squash' for all of your commits except the first one. >
< Edit the commit message to make sense, and describe all your changes. >

$ git push origin my_pull_request -f
```

You should be able to refresh the pull request on GitHub and see that it has
been updated.

#### Updating pull request

Sometimes you will be asked to make some changes to the code you have
already committed. This can include amending existing commits. In this
case Git will not allow you to push the changes as the pushed branch
and local branch do not match. Instead of opening a new pull request,
you can force push to your branch on GitHub as described earlier in
squashing commits section:

```bash
$ git push origin my_pull_request -f
```

This will update the branch and pull request on GitHub with your new code. Do
note that using force push may result in commits being lost on the remote branch; use it with care.

### Older Versions of Ruby on Rails

If you want to add a fix to older versions of Ruby on Rails, you'll need to set up and switch to your own local tracking branch. Here is an example to switch to the 4-0-stable branch:

```bash
$ git branch --track 4-0-stable origin/4-0-stable
$ git checkout 4-0-stable
```

TIP: You may want to [put your Git branch name in your shell prompt](http://qugstart.com/blog/git-and-svn/add-colored-git-branch-name-to-your-shell-prompt/) to make it easier to remember which version of the code you're working with.

#### Backporting

Changes that are merged into master are intended for the next major release of Rails. Sometimes, it might be beneficial for your changes to propagate back to the maintenance releases for older stable branches. Generally, security fixes and bug fixes are good candidates for a backport, while new features and patches that introduce a change in behavior will not be accepted. When in doubt, it is best to consult a Rails team member before backporting your changes to avoid wasted effort.

For simple fixes, the easiest way to backport your changes is to [extract a diff from your changes in master and apply them to the target branch](http://ariejan.net/2009/10/26/how-to-create-and-apply-a-patch-with-git).

First make sure your changes are the only difference between your current branch and master:

```bash
$ git log master..HEAD
```

Then extract the diff:

```bash
$ git format-patch master --stdout > ~/my_changes.patch
```

Switch over to the target branch and apply your changes:

```bash
$ git checkout -b my_backport_branch 3-2-stable
$ git apply ~/my_changes.patch
```

This works well for simple changes. However, if your changes are complicated or if the code in master has deviated significantly from your target branch, it might require more work on your part. The difficulty of a backport varies greatly from case to case, and sometimes it is simply not worth the effort.

Once you have resolved all conflicts and made sure all the tests are passing, push your changes and open a separate pull request for your backport. It is also worth noting that older branches might have a different set of build targets than master. When possible, it is best to first test your backport locally against the Ruby versions listed in `.travis.yml` before submitting your pull request.

And then... think about your next contribution!

Rails Contributors
------------------

All contributions, either via master or docrails, get credit in [Rails Contributors](http://contributors.rubyonrails.org).


text:
package com.speedment.runtime.core.provider;

import com.speedment.common.injector.State;
import com.speedment.common.injector.annotation.Config;
import com.speedment.common.injector.annotation.ExecuteBefore;
import com.speedment.runtime.core.component.StatisticsReporterComponent;
import com.speedment.runtime.core.component.StatisticsReporterSchedulerComponent;
import com.speedment.runtime.core.internal.component.StatisticsReporterSchedulerComponentImpl;

/**
 *
 * @author Per Minborg
 * @since 3.2.0
 */
public final class DelegateStatisticsReporterSchedulerComponent implements StatisticsReporterSchedulerComponent {

    private final StatisticsReporterSchedulerComponentImpl inner;

    public DelegateStatisticsReporterSchedulerComponent(@Config(name = "statistics.scheduler.enabled", value = "true") final boolean enabled) {
        this.inner = new StatisticsReporterSchedulerComponentImpl(enabled);
    }

    @ExecuteBefore(State.STARTED)
    public void start(StatisticsReporterComponent src) {
        inner.start(src);
    }

    @ExecuteBefore(State.STOPPED)
    public void stop(StatisticsReporterComponent src) {
        inner.stop(src);
    }

}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
	version="3.0">

	<display-name>ShoppingList</display-name>

	<welcome-file-list>
		<welcome-file>shopping-list.html</welcome-file>
	</welcome-file-list>

</web-app>


text:
[//000000001]: # (math::quasirandom \- Tcl Math Library)
[//000000002]: # (Generated from file 'quasirandom\.man' by tcllib/doctools with format 'markdown')
[//000000003]: # (math::quasirandom\(n\) 1 tcllib "Tcl Math Library")

 [ Main Table Of Contents | Table Of Contents | Keyword Index | Categories | Modules | Applications ]

# NAME

math::quasirandom \- Quasi\-random points for integration and Monte Carlo type
methods

# Table Of Contents

  - [Table Of Contents](#toc)

  - [Synopsis](#synopsis)

  - [Description](#section1)

  - [COMMANDS](#section2)

  - [TODO](#section3)

  - [References](#section4)

  - [Keywords](#keywords)

  - [Category](#category)

# SYNOPSIS

package require Tcl 8\.6
package require TclOO
package require math::quasirandom 1

[__::math::quasirandom::qrpoint create__ *NAME* *DIM* ?ARGS?](#1)
[__gen next__](#2)
[__gen set\-start__ *index*](#3)
[__gen set\-evaluations__ *number*](#4)
[__gen integral__ *func* *minmax* *args*](#5)

# DESCRIPTION

In many applications pseudo\-random numbers and pseudo\-random points in a
\(limited\) sample space play an important role\. For instance in any type of Monte
Carlo simulation\. Pseudo\-random numbers, however, may be too random and as a
consequence a large number of data points is required to reduce the error or
fluctuation in the results to the desired value\.

Quasi\-random numbers can be used as an alternative: instead of "completely"
arbitrary points, points are generated that are diverse enough to cover the
entire sample space in a more or less uniform way\. As a consequence convergence
to the limit can be much faster, when such quasi\-random numbers are well\-chosen\.

The package defines a *[class](\.\./\.\./\.\./\.\./index\.md\#class)* "qrpoint" that
creates a command to generate quasi\-random points in 1, 2 or more dimensions\.
The command can either generate separate points, so that they can be used in a
user\-defined algorithm or use these points to calculate integrals of functions
defined over 1, 2 or more dimensions\. It also holds several other common
algorithms\. \(NOTE: these are not implemented yet\)

One particular characteristic of the generators is that there are no tuning
parameters involved, which makes the use particularly simple\.

# COMMANDS

A quasi\-random point generator is created using the *qrpoint* class:

  - __::math::quasirandom::qrpoint create__ *NAME* *DIM* ?ARGS?

    This command takes the following arguments:

      * string *NAME*

        The name of the command to be created \(alternatively: the *new*
        subcommand will generate a unique name\)

      * integer/string *DIM*

        The number of dimensions or one of: "circle", "disk", "sphere" or "ball"

      * strings *ARGS*

        Zero or more key\-value pairs\. The supported options are:

          + *\-start index*: The index for the next point to be generated
            \(default: 1\)

          + *\-evaluations number*: The number of evaluations to be used by
            default \(default: 100\)

The points that are returned lie in the hyperblock \[0,1\[^n \(n the number of
dimensions\) or on the unit circle, within the unit disk, on the unit sphere or
within the unit ball\.

Each generator supports the following subcommands:

  - __gen next__

    Return the coordinates of the next quasi\-random point

  - __gen set\-start__ *index*

    Reset the index for the next quasi\-random point\. This is useful to control
    which list of points is returned\. Returns the new or the current value, if
    no value is given\.

  - __gen set\-evaluations__ *number*

    Reset the default number of evaluations in compound algorithms\. Note that
    the actual number is the smallest 4\-fold larger or equal to the given
    number\. \(The 4\-fold plays a role in the detailed integration routine\.\)

  - __gen integral__ *func* *minmax* *args*

    Calculate the integral of the given function over the block \(or the circle,
    sphere etc\.\)

      * string *func*

        The name of the function to be integrated

      * list *minmax*

        List of pairs of minimum and maximum coordinates\. This can be used to
        map the quasi\-random coordinates to the desired hyper\-block\.

        If the space is a circle, disk etc\. then this argument should be a
        single value, the radius\. The circle, disk, etc\. is centred at the
        origin\. If this is not what is required, then a coordinate
        transformation should be made within the function\.

      * strings *args*

        Zero or more key\-value pairs\. The following options are supported:

          + *\-evaluations number*: The number of evaluations to be used\. If
            not specified use the default of the generator object\.

# TODO

Implement other algorithms and variants

Implement more unit tests\.

Comparison to pseudo\-random numbers for integration\.

# References

Various algorithms exist for generating quasi\-random numbers\. The generators
created in this package are based on:
[http://extremelearning\.com\.au/unreasonable\-effectiveness\-of\-quasirandom\-sequences/](http://extremelearning\.com\.au/unreasonable\-effectiveness\-of\-quasirandom\-sequences/)

# KEYWORDS

[mathematics](\.\./\.\./\.\./\.\./index\.md\#mathematics),
[quasi\-random](\.\./\.\./\.\./\.\./index\.md\#quasi\_random)

# CATEGORY

Mathematics


text:
var SlowBuffer = require('buffer').SlowBuffer,
    crc32 = require('buffer-crc32'),
    YencFile;

/**
 * The YencFile class
 *
 * @author   Jelle De Loecker   <jelle@kipdola.be>
 * @since    0.1.0
 * @version  0.1.0
 *
 * @param    {Object}   segment   NZB segment information
 */
YencFile = function YencFile(segment) {

	// Does the next char have to be escaped?
	this.escaped = false;

	// The resulting buffer
	this.buffer = null;

	// Information on this yenc file
	this.info = {};

	// ybegin & yend flags
	this.ybegin = null;
	this.ypart = null;
	this.yend = null;

	// Have we begun received yenced data?
	this.ydata = false;

	// Does the crc check validate?
	this.intact = null;

	// The checksum of the finished buffer
	this.checksum = null;

	// At what index we're currently in the buffer
	this.index = 0;

	if (segment) {

		// Set the expected size of the *article*
		this.articlesize = segment.bytes;

		// Save the part number
		this.info.part = segment.number;
	}
};

/**
 * Decode a line containing "=" info
 *
 * @author   Jelle De Loecker   <jelle@kipdola.be>
 * @since    0.1.0
 * @version  0.1.1
 *
 * @param    {String}   line
 *
 * @return   {Object}
 */
YencFile.prototype.decodeInfo = function decodeInfo(line) {

	var result = {},
	    info = {},
	    temp,
	    type,
	    key,
	    val,
	    i;

	// Prepare line for more info
	line = line.trim().split('=');

	for (i = 0; i < line.length; i++) {

		if (i+1 == line.length && key) {
			info[key] = line[i].trim();
			break;
		}

		temp = line[i].split(' ');

		if (key) {
			info[key] = temp[0];
		} else {
			type = temp[0];
		}

		key = temp[1];
	}

	for (key in info) {
		val = info[key];

		switch (key) {

			case 'size':
				if (type == 'ybegin') {
					key = 'filesize';
				} else if (type == 'yend') {
					key = 'partsize';
				}

			case 'part':
			case 'line':
			case 'end':
			case 'begin':
				val = Number(val);
				break;

			case 'pcrc32':
				val = parseInt(val, 16).toString(16);
				break;
		}

		result[key] = val;
	}

	return result;
};

/**
 * Decode a piece of text
 *
 * @author   Jelle De Loecker   <jelle@kipdola.be>
 * @since    0.1.0
 * @version  0.1.1
 *
 * @param    {String}   piece
 * @param    {Boolean}  returnNewData
 */
YencFile.prototype.decodePiece = function decodePiece(piece, returnNewData) {

	var startIndex,
	    stopIndex,
	    oldIndex,
	    lines,
	    line,
	    temp,
	    key,
	    i;

	// Split the lines
	lines = piece.split('\n');

	// Store the current index
	oldIndex = this.index;

	// Look for the start headers
	startIndex = this.parseBegin(lines);

	// Look for the end headers
	stopIndex = this.parseEnd(lines);

	if (startIndex == null) {
		return;
	}

	// Create the buffer where the bytes will go
	if (!this.buffer) {
		this.buffer = new SlowBuffer(this.size);
	}

	// Go over every line
	for (i = startIndex; i < stopIndex; i++) {
		this.toBytes(lines[i]);
	}

	if (this.yend) {

		// Calculate the checksum
		this.checksum = crc32.unsigned(this.buffer).toString(16);

		// Compare the checksum if one was set in the pieces
		if (this.info.pcrc32) {
			this.intact = this.checksum == this.info.pcrc32;
		}
	}

	lines = null;
	piece = null;

	if (returnNewData && oldIndex != this.index) {
		return this.buffer.slice(oldIndex, this.index);
	}
};

/**
 * Look for ybegin headers
 *
 * @author   Jelle De Loecker   <jelle@kipdola.be>
 * @since    0.1.0
 * @version  0.1.0
 *
 * @param    {Array}   lines
 *
 * @return   {Number}  line number that should be used next
 */
YencFile.prototype.parseBegin = function parseBegin(lines) {

	var startIndex,
	    line,
	    temp,
	    key,
	    i;

	if (this.ybegin != null && this.ypart != null) {
		return 0;
	}

	for (i = 0; i < lines.length; i++) {
		line = lines[i];

		if (this.ybegin == null || this.ybegin && this.ypart == null) {

			// Skip junk lines at the start of the body
			if (!this.ybegin && line.indexOf('=ybegin') !== 0) {
				continue;
			}

			// If there is a ypart info line it should be right after ybegin
			if (this.ybegin && line.indexOf('=ypart') == -1) {
				this.ypart = false;
				i--;
				break;
			}

			if (this.ybegin) {
				this.ypart = true;
			}

			// Indicate we found ybegin
			this.ybegin = true;

			temp = this.decodeInfo(line);

			for (key in temp) {
				this.info[key] = temp[key];
			}

			if (this.ypart) break;
		}
	}

	i++;

	if (this.ybegin != null && this.ypart != null) {
		// Get the index of the starting line of this piece
		startIndex = i;

		// Store the size of this filepiece
		this.size = 1 + this.info.end - this.info.begin;

		if (!this.size) {
			this.size = this.info.partsize || this.info.filesize;
		}
	} else {
		startIndex = null;
	}

	return startIndex;
};

/**
 * Look for yend headers
 *
 * @author   Jelle De Loecker   <jelle@kipdola.be>
 * @since    0.1.0
 * @version  0.1.0
 *
 * @param    {Array}   lines
 *
 * @return   {Number}  line number that should be used next
 */
YencFile.prototype.parseEnd = function parseEnd(lines) {

	var stopIndex,
	    line,
	    temp,
	    key,
	    i;

	// Get the bottom line info
	for (i = lines.length-1; i > 0; i--) {

		if (lines[i].indexOf('=yend') != 0) {
			continue;
		}

		temp = this.decodeInfo(lines[i]);

		for (key in temp) {
			this.info[key] = temp[key];
		}

		this.yend = true;
		stopIndex = i;
		break;
	}

	// Return the index of the stopping line (exclusive)
	if (stopIndex == null) {
		return lines.length;
	} else {
		return stopIndex;
	}
};

/**
 * Decode a yenc string and store it in the buffer
 *
 * @author   Jelle De Loecker   <jelle@kipdola.be>
 * @since    0.1.0
 * @version  0.1.0
 *
 * @param    {String}   input
 */
YencFile.prototype.toBytes = function toBytes(input) {

	var code,
	    len,
	    i;

	len = input.length;

	for (i = 0; i < len; i++) {
		code = String.prototype.charCodeAt.call(input, i);

		// Skip newlines
		if (code == 10 || code == 13) {
			continue;
		}

		// Look for escape chars
		if (code == 61 && !this.escaped) {
			this.escaped = true;
			continue;
		}

		// Special escape handling
		if (this.escaped) {
			code -= 64;
			this.escaped = false;
		}

		if (code < 42 && code > 0) {
			code += 214;
		} else {
			code -= 42;
		}

		this.buffer[this.index++] = code;
	}
};

module.exports = YencFile;


text:
namespace BaseModUI {

	class GenericPanelList;
	class FoundGames;
	class BaseModHybridButton;

	//=============================================================================

	class FoundGroupGames : public FoundGames
	{
		DECLARE_CLASS_SIMPLE( FoundGroupGames, FoundGames );

	public:
		FoundGroupGames( vgui::Panel *parent, const char *panelName );

		virtual void PaintBackground();
		virtual void OnEvent( KeyValues *pEvent );

		virtual bool CanCreateGame() { return false; }

	protected:

		virtual void StartSearching( void );
		virtual void AddServersToList( void );
		virtual void SortListItems();
		virtual bool IsADuplicateServer( FoundGameListItem *item, FoundGameListItem::Info const &fi );

		bool ShouldAddServerToList( KeyValues *pGameSettings );
	};

};

#endif


text:
using System.Collections.Generic;

namespace Tup.Cobar4Net.Parser.Ast.Expression.Primary.Function.Info
{
    /// <author>
    ///     QIU Shuo
    /// </author>
    public class Benchmark : FunctionExpression
    {
        public Benchmark(IList<IExpression> arguments)
            : base("BENCHMARK", arguments)
        {
        }

        public override FunctionExpression ConstructFunction(IList<IExpression> arguments)
        {
            return new Benchmark(arguments);
        }
    }
}


text:
package demos.xtrans;

import com.jogamp.opengl.impl.awt.Java2D;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.geom.Rectangle2D;
import javax.media.opengl.DebugGL2;
import javax.media.opengl.GL;
import javax.media.opengl.GL2ES1;
import javax.media.opengl.GL2;
import javax.media.opengl.GLContext;
import javax.media.opengl.GLDrawableFactory;
import javax.media.opengl.GLProfile;
import javax.swing.JDesktopPane;

/** A desktop manager implementation supporting accelerated
 * transitions of the components on the desktop via OpenGL. This class
 * does not need to be instantiated by end users; it is installed
 * automatically when an XTDesktopPane is constructed.
 *
 * @author Kenneth Russell
 */
public class XTDesktopManager extends OffscreenDesktopManager {
  private GLContext j2dContext;
  private Object    j2dContextSurfaceIdentifier;
  private int       oglTextureId;
  private int       prevBackBufferWidth;
  private int       prevBackBufferHeight;

  private int textureTarget = GL.GL_TEXTURE_2D;

  /** Returns the OpenGL texture object ID associated with the
      off-screen back buffer for all of the components on the
      desktop. */
  public int getOpenGLTextureObject() {
    return oglTextureId;
  }

  /** Returns a rectangle specifying the OpenGL texture coordinates of
      the passed component in the texture object. The x and y
      coordinates of the returned rectangle specify the lower left
      corner of the component's image. */
  public Rectangle2D getOpenGLTextureCoords(Component c) {
    Rectangle rect = getBoundsOnBackBuffer(c);
    if (rect == null) {
      throw new RuntimeException("Unknown component " + c);
    }
    double offscreenWidth  = getOffscreenBackBufferWidth();
    double offscreenHeight = getOffscreenBackBufferHeight();
    return new Rectangle2D.Double(rect.x / offscreenWidth,
                                  (offscreenHeight - rect.y - rect.height) / offscreenHeight,
                                  rect.width / offscreenWidth,
                                  rect.height / offscreenHeight);
  }

  /** Updates the off-screen buffer of this desktop manager and makes
      the rendering results available to OpenGL in the form of a
      texture object. */
  public void updateOffscreenBuffer(OffscreenDesktopPane parent) {

    boolean needsCopy = needsCopyBack();
    boolean hadPrevBackBuffer = false;
    super.updateOffscreenBuffer(parent);
    Image img = getOffscreenBackBuffer();

    final boolean mustResizeOGLTexture = ((oglTextureId == 0) ||
                                          (img == null) ||
                                          (prevBackBufferWidth  != img.getWidth(null)) ||
                                          (prevBackBufferHeight != img.getHeight(null)));
    if (needsCopy) {
      final Graphics g = getOffscreenGraphics();
      // Capture off-screen buffer contents into OpenGL texture
      Java2D.invokeWithOGLContextCurrent(g, new Runnable() {
          public void run() {
            // Get valid Java2D context
            if (j2dContext == null ||
                j2dContextSurfaceIdentifier != Java2D.getOGLSurfaceIdentifier(g)) {
              GLProfile glp = GLProfile.getDefault();
              j2dContext = GLDrawableFactory.getFactory(glp).createExternalGLContext();
              j2dContext.setGL(new DebugGL2(j2dContext.getGL().getGL2()));
              j2dContextSurfaceIdentifier = Java2D.getOGLSurfaceIdentifier(g);
            }

            j2dContext.makeCurrent(); // No-op
            try {
              GL2 gl = j2dContext.getGL().getGL2();

              if (oglTextureId == 0) {
                // Set up and initialize texture
                int[] tmp = new int[1];

                gl.glGenTextures(1, tmp, 0);
                oglTextureId = tmp[0];
                if (oglTextureId == 0) {
                  throw new RuntimeException("Error generating OpenGL back buffer texture");
                }
                assert mustResizeOGLTexture : "Must know we need to resize";
              }

              gl.glBindTexture(textureTarget, oglTextureId);

              int offscreenWidth  = getOffscreenBackBufferWidth();
              int offscreenHeight = getOffscreenBackBufferHeight();

              if (mustResizeOGLTexture) {
                prevBackBufferWidth  = offscreenWidth;
                prevBackBufferHeight = offscreenHeight;

                gl.glTexImage2D(textureTarget,
                                0,
                                GL.GL_RGBA8,
                                offscreenWidth,
                                offscreenHeight,
                                0,
                                GL.GL_RGBA,
                                GL.GL_UNSIGNED_BYTE,
                                null);
              }

              // Copy texture from offscreen buffer
              // NOTE: assumes read buffer is set up
              // FIXME: could be more efficient by copying only bounding rectangle

              gl.glPixelStorei(GL2.GL_UNPACK_SWAP_BYTES, GL.GL_FALSE);
              gl.glPixelStorei(GL2.GL_PACK_SWAP_BYTES, GL.GL_FALSE);
              gl.glPixelStorei(GL2.GL_UNPACK_LSB_FIRST, GL.GL_FALSE);
              gl.glPixelStorei(GL2.GL_PACK_LSB_FIRST, GL.GL_FALSE);
              gl.glPixelStorei(GL2.GL_UNPACK_ROW_LENGTH, 0);
              gl.glPixelStorei(GL2.GL_PACK_ROW_LENGTH, 0);
              gl.glPixelStorei(GL2.GL_UNPACK_SKIP_ROWS, 0);
              gl.glPixelStorei(GL2.GL_PACK_SKIP_ROWS, 0);
              gl.glPixelStorei(GL2.GL_UNPACK_SKIP_PIXELS, 0);
              gl.glPixelStorei(GL2.GL_PACK_SKIP_PIXELS, 0);
              gl.glPixelStorei(GL2.GL_UNPACK_ALIGNMENT, 1);
              gl.glPixelStorei(GL2.GL_PACK_ALIGNMENT, 1);
              gl.glPixelTransferf(GL2.GL_RED_SCALE, 1);
              gl.glPixelTransferf(GL2.GL_GREEN_SCALE, 1);
              gl.glPixelTransferf(GL2.GL_BLUE_SCALE, 1);
              gl.glPixelTransferf(GL2.GL_ALPHA_SCALE, 1);
              gl.glPixelTransferf(GL2.GL_RED_BIAS, 0);
              gl.glPixelTransferf(GL2.GL_GREEN_BIAS, 0);
              gl.glPixelTransferf(GL2.GL_BLUE_BIAS, 0);
              gl.glPixelTransferf(GL2.GL_ALPHA_BIAS, 0);

              // long start = System.currentTimeMillis();
              gl.glCopyTexSubImage2D(textureTarget,
                                     0,
                                     0,
                                     0,
                                     0,
                                     0,
                                     offscreenWidth,
                                     offscreenHeight);
              // long end = System.currentTimeMillis();
              // System.err.println("glCopyTexSubImage2D " + offscreenWidth + "x" + offscreenHeight + " took " + (end - start) + " ms");

            } finally {
              j2dContext.release();
            }
          }
        });
    }
  }

  // Ideally we would force a repaint only of the 2D bounds of the 3D
  // component projected onto the desktop. However for expedience
  // we'll currently just repaint the entire desktop to get correct
  // results.
  protected void repaintPortionOfDesktop(JDesktopPane desktop, Component comp) {
    desktop.repaint();
  }
}


text:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
  "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
  "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"
  [<!ENTITY identifiableProperties SYSTEM "classpath://org/hisp/dhis/common/identifiableProperties.hbm">]
  >
<hibernate-mapping>
  <class name="org.hisp.dhis.dataapproval.DataApprovalAudit" table="dataapprovalaudit">

    <cache usage="read-write" />

    <id name="id" column="dataapprovalauditid">
      <generator class="native" />
    </id>

    <many-to-one name="level" class="org.hisp.dhis.dataapproval.DataApprovalLevel" column="levelid" not-null="true" foreign-key="fk_dataapprovalaudit_levelid" />
    <many-to-one name="workflow" class="org.hisp.dhis.dataapproval.DataApprovalWorkflow" column="workflowid" not-null="true" foreign-key="fk_dataapprovalaudit_workflowid" />
    <many-to-one name="period" class="org.hisp.dhis.period.Period" column="periodid" not-null="true" foreign-key="fk_dataapprovalaudit_periodid" />
    <many-to-one name="organisationUnit" class="org.hisp.dhis.organisationunit.OrganisationUnit" not-null="true" column="organisationunitid" foreign-key="fk_dataapprovalaudit_organisationunitid" />
    <many-to-one name="attributeOptionCombo" class="org.hisp.dhis.dataelement.DataElementCategoryOptionCombo" not-null="true" column="attributeoptioncomboid" foreign-key="fk_dataapprovalaudit_attributeoptioncomboid" />

    <property name="action" length="100" not-null="true">
      <type name="org.hibernate.type.EnumType">
        <param name="enumClass">org.hisp.dhis.dataapproval.DataApprovalAction</param>
        <param name="useNamed">true</param>
        <param name="type">12</param>
      </type>
    </property>

    <property name="created" column="created" not-null="true" type="timestamp" />

    <many-to-one name="creator" class="org.hisp.dhis.user.User" column="creator" not-null="true" foreign-key="fk_dataapproval_creator" />

  </class>

</hibernate-mapping>


text:
#include "Song.h"
#include "Sequence.h"
#include "SequenceRow.h"
#include "Pattern.h"
#include "Sequence.h"
#include "Macro.h"
#include "PatternRow.h"
#include "FileSection.h"
#include "SectionListener.h"
#include "Debug.h"
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <strings.h>
#include <algorithm>

Song::Song()
	: patternLength(64), sequenceLength(1), mNumListeners(0)
{
	sequence = new Sequence();
	patterns = new Pattern*[SequenceRow::maxTracks];

	for (int track = 0 ; track < SequenceRow::maxTracks ; ++track)
	{
		patterns[track] = new Pattern[maxPatterns];
	}

	macros = new Macro[maxMacros];
	strcpy(name, "new song");
}

Song::~Song()
{
	for (int track = 0 ; track < SequenceRow::maxTracks ; ++track)
		delete[] patterns[track];

	delete[] patterns;
	delete[] macros;
	delete sequence;
}

Sequence& Song::getSequence()
{
	return *sequence;
}

int Song::getLastPatternUsed(int track) const
{
	int last = -1;

	for (int i = 0 ; i < maxPatterns ; ++i)
	{
		if (!patterns[track][i].isEmpty())
			last = std::max(last, i);
	}

	return last;
}

int Song::getLastMacroUsed() const
{
	int last = -1;

	for (int i = 0 ; i < maxMacros ; ++i)
	{
		if (strlen(macros[i].getName()) > 0 || !macros[i].isEmpty())
			last = std::max(last, i);
	}

	return last;
}

int Song::getPatternLength() const
{
	return patternLength;
}

int Song::getSequenceLength() const
{
	return sequenceLength;
}

Pattern& Song::getPattern(int track, int pattern)
{
	return patterns[track][pattern];
}

Macro& Song::getMacro(int macro)
{
	return macros[macro];
}

void Song::setPatternLength(int length)
{
	patternLength = length;
}

void Song::setSequenceLength(int length)
{
	sequenceLength = length;
}

FileSection* Song::pack()
{
	FileSection * song = FileSection::createSection("SONG");

	/*
	 * Basic song info
	 */

	// File format version
	song->writeByte(songVersion);
	song->writeByte(SequenceRow::maxTracks);
	song->writeByte(PatternRow::effectParams);
	song->writeString(name);
	song->writeByte(patternLength - 1);
	song->writeByte(sequenceLength - 1);

	/*
	 * Sequence data
	 */

	FileSection * sequenceData = FileSection::createSection("SEQU");
	int sequenceCount = sequence->getLastSequenceRowUsed() + 1;
	sequenceData->writeByte(sequenceCount);
	for (int track = 0 ; track < SequenceRow::maxTracks ; ++track)
	{
		for (int i = 0 ; i < sequenceCount ; ++i)
		{
			SequenceRow& sequenceRow = sequence->getRow(i);
			sequenceData->writeByte(sequenceRow.pattern[track]);
		}
	}
	song->writeSection(*sequenceData);
	delete sequenceData;

	/*
	 * Patterns
	 */

	FileSection * patternData = FileSection::createSection("PATT");
	for (int track = 0 ; track < SequenceRow::maxTracks ; ++track)
	{
		int patternCount = getLastPatternUsed(track) + 1;
		patternData->writeByte(patternCount);
		for (int i = 0 ; i < patternCount ; ++i)
		{
			Pattern& pattern = getPattern(track, i);
			patternData->writePattern(pattern);
		}
	}
	song->writeSection(*patternData);
	delete patternData;

	/*
	 * Macros
	 */

	FileSection * macroData = FileSection::createSection("MACR");
	int macroCount = getLastMacroUsed() + 1;
	//printf("Saving %d macros\n", macroCount);
	macroData->writeByte(macroCount);
	for (int i = 0 ; i < macroCount ; ++i)
	{
		Macro& macro = getMacro(i);
		macroData->writeString(macro.getName());
		macroData->writePattern(macro);
	}
	song->writeSection(*macroData);
	delete macroData;

	// Call SectionListeners for save

	for (int i = 0 ; i < mNumListeners ; ++i)
	{
		if (mListeners[i].flags & SectionListener::Save)
		{
			FileSection *listenerSection = FileSection::createSection(mListeners[i].sectionId);
			mListeners[i].listener->onFileSectionSave(*listenerSection);
			song->writeSection(*listenerSection);
			delete listenerSection;
		}
	}

	return song;
}

void Song::clear()
{
	sequence->clear();

	strcpy(name, "");

	for (int track = 0 ; track < SequenceRow::maxTracks ; ++track)
	{
		for (int i = 0 ; i < maxPatterns ; ++i)
		{
			patterns[track][i].clear();
		}
	}

	for (int i = 0 ; i < maxMacros ; ++i)
	{
		macros[i].clear();
	}

	sequenceLength = 1;
	patternLength = 64;
}

Song::UnpackError Song::unpack(const FileSection& section)
{
	if (strcmp(section.getName(), "SONG") != 0)
		return NotASong;

	clear();

	// Trigger synth reset
	for (int i = 0 ; i < mNumListeners ; ++i)
	{
		if (mListeners[i].flags & SectionListener::Load)
		{
			mListeners[i].listener->onSongClear();
		}
	}

	int offset = 0;
	int version = section.readByte(offset);

	if (version > songVersion)
	{
		// TODO: display a proper error if the version is newer than we can handle
		return ErrorVersion;
	}

	// Default trackCount for version == 0
	int trackCount = 4;

	// Default pattern set count (version >= 17 uses a separate set of patterns for each track)
	int patternSets = 1;

	if (version >= 17)
	{
		patternSets = trackCount;
	}
	// Default effect param count for version <= 16
	int effectParamCount = 1;

	if (version == FileSection::invalidRead)
		return ErrorRead;

	if (version >= 1)
	{
		trackCount = section.readByte(offset);

		if (trackCount == FileSection::invalidRead)
			return ErrorRead;
	}

	if (version >= 17)
	{
		effectParamCount = section.readByte(offset);

		if (effectParamCount == FileSection::invalidRead)
			return ErrorRead;
	}

	const char *songName = section.readString(offset);

	if (songName == NULL)
		return ErrorRead;

	strncpy(name, songName, songNameLength + 1);

	int temp = section.readByte(offset);

	if (temp == FileSection::invalidRead)
		return ErrorRead;

	patternLength = temp + 1;

	temp = section.readByte(offset);

	if (temp == FileSection::invalidRead)
		return ErrorRead;

	sequenceLength = temp + 1;

	UnpackError returnValue = Success;

	do
	{
		//printf("offset = %d\n", offset);
		FileSection *subSection = section.readSection(offset);
		int subOffset = 0;

		if (subSection == NULL)
			break;

		const char *sectionName = subSection->getName();

		if (sectionName != NULL)
		{
			//printf("Read section %s (%d bytes)\n", sectionName, subSection->getSize());

			if (strcmp(sectionName, "SEQU") == 0)
			{
				int temp = subSection->readByte(subOffset);

				if (temp == FileSection::invalidRead)
				{
					returnValue = ErrorRead;
				}
				else
				{
					int count = temp;

					//printf("Reading %d sequences\n", count);

					if (count > maxSequenceRows)
					{
						returnValue = ErrorRead;
					}
					else
					{
						for (int track = 0 ; track < trackCount && returnValue == Success ; ++track)
						{
							for (int i = 0 ; i < count ; ++i)
							{
								int temp = subSection->readByte(subOffset);

								if (temp == FileSection::invalidRead)
								{
									returnValue = ErrorRead;
									break;
								}

								// Skip tracks that can't fit in our sequence
								if (track < SequenceRow::maxTracks)
									sequence->getRow(i).pattern[track] = temp;
							}
						}
					}
				}
			}
			else if (strcmp(sectionName, "PATT") == 0)
			{
				int tempSubOffset = subOffset;

				for (int track = 0 ; track < trackCount ; ++track)
				{
					// If only one pattern set in the file, keep reading the
					// same patterns for each track
					if (patternSets == 1)
					{
						subOffset = tempSubOffset;
					}

					int temp = subSection->readByte(subOffset);

					if (temp == FileSection::invalidRead)
					{
						returnValue = ErrorRead;
						break;
					}
					else
					{
						int count = temp;

						for (int i = 0 ; i < count ; ++i)

						{
							if (!subSection->readPattern(patterns[track][i], effectParamCount, subOffset))
							{
								returnValue = ErrorRead;
								break;
							}
						}
					}
				}
			}
			else if (strcmp(sectionName, "MACR") == 0)
			{
				int temp = subSection->readByte(subOffset);

				if (temp == FileSection::invalidRead)
				{
					returnValue = ErrorRead;
				}
				else
				{
					int count = temp;

					// printf("Reading %d macros\n", count);

					for (int i = 0 ; i < count ; ++i)
					{
						const char *macroName = subSection->readString(subOffset);

						if (macroName == NULL)
						{
							returnValue = ErrorRead;
							break;
						}

						strncpy(macros[i].getName(), macroName, Macro::macroNameLength + 1);

						if (!subSection->readPattern(macros[i], effectParamCount, subOffset))
						{
							returnValue = ErrorRead;
							break;
						}
					}
				}
			}
			else
			{
				bool processed = false;

				for (int i = 0 ; i < mNumListeners ; ++i)
				{
					if ((mListeners[i].flags & SectionListener::Load) && strcmp(mListeners[i].sectionId, sectionName) == 0)
					{
						processed = true;

						if (!mListeners[i].listener->onFileSectionLoad(*subSection, subOffset))
						{
							returnValue = ErrorRead;
							break;
						}
					}
				}

				if (!processed)
				{
					debug("Skipping unknown section '%s'", sectionName);
				}
			}
		}
		else
		{
			returnValue = ErrorRead;
		}

		//offset += subOffset;

		delete subSection;
	}
	while (returnValue == Success);

	return returnValue;
}

char *Song::getSongName()
{
	return name;
}

int Song::getSize() const
{
	return 0;
}

bool Song::addSectionListener(const char *sectionId, SectionListener *sectionListener, int flags)
{
	if (mNumListeners >= maxListeners)
		return false;

	SectionListenerInfo& info = mListeners[mNumListeners];
	info.flags = flags;
	info.sectionId = sectionId;
	info.listener = sectionListener;

	mNumListeners++;

	return true;
}


text:
Developer
=========

Environment
-----------

Presuming you cloned each project under `~/lsn`:

Link `/usr/local/src/lsn` to `~/lsn`

Copy `./profile.sh` to `/etc/profile.d/livesite.sh` (or otherwise inlcude
it in your environment).

Syntax
------

Overlay `./vim` on top of your `~/.vim`.

    rsync -a vim/ ~/.vim/

Web Development
---------------

To run from sources, run `./link-to-source.sh` after you've fetched the lsn-
projects. This will mimic an installation, that is:

    /usr/lib/livesite
    /usr/share/livesite

will contain symlinks to corresponding source folders throughout the
project hierarchy.


text:
"""Tests for control_flow_v2_toggles.py."""

from tensorflow.python.ops import control_flow_util_v2
from tensorflow.python.ops import control_flow_v2_toggles
from tensorflow.python.platform import googletest
from tensorflow.python.platform import test

class ControlFlowV2TogglesTest(test.TestCase):

  def testOutputAllIntermediates(self):
    self.assertIsNone(
        control_flow_util_v2._EXPERIMENTAL_OUTPUT_ALL_INTERMEDIATES_OVERRIDE)
    control_flow_v2_toggles.output_all_intermediates(True)
    self.assertTrue(
        control_flow_util_v2._EXPERIMENTAL_OUTPUT_ALL_INTERMEDIATES_OVERRIDE)
    control_flow_v2_toggles.output_all_intermediates(False)
    self.assertFalse(
        control_flow_util_v2._EXPERIMENTAL_OUTPUT_ALL_INTERMEDIATES_OVERRIDE)
    control_flow_v2_toggles.output_all_intermediates(None)
    self.assertIsNone(
        control_flow_util_v2._EXPERIMENTAL_OUTPUT_ALL_INTERMEDIATES_OVERRIDE)

if __name__ == '__main__':
  googletest.main()


text:
from distutils.dir_util import copy_tree
from optparse import OptionParser
import os
from shutil import move
from uuid import uuid4

from mezzanine.utils.importing import path_for_import

def create_project():
    """
    Copies the contents of the project_template directory to a new
    directory specified as an argument to the command line.
    """

    parser = OptionParser(usage="usage: %prog [options] project_name")
    parser.add_option("-a", "--alternate", dest="alt", metavar="PACKAGE",
        help="Alternate package to use, containing a project_template")
    (options, args) = parser.parse_args()

    if len(args) != 1:
        parser.error("project_name must be specified")
    project_name = args[0]
    if project_name.startswith("-"):
        parser.error("project_name cannot start with '-'")
    project_path = os.path.join(os.getcwd(), project_name)

    # Ensure the given directory name doesn't clash with an existing
    # Python package/module.
    try:
        __import__(project_name)
    except ImportError:
        pass
    else:
        parser.error("'%s' conflicts with the name of an existing "
                     "Python module and cannot be used as a project "
                     "name. Please try another name." % project_name)

    # Create the list of packages to build from - at this stage it
    # should only be one or two names, mezzanine plus an alternate
    # package.
    packages = ["mezzanine"]
    if options.alt:
        packages.append(options.alt)
    for package_name in packages:
        try:
            __import__(package_name)
        except ImportError:
            parser.error("Could not import package '%s'" % package_name)

    # Build the project up copying over the project_template from
    # each of the packages. An alternate package will overwrite
    # files from Mezzanine.
    for package_name in packages:
        package_path = path_for_import(package_name)
        copy_tree(os.path.join(package_path, "project_template"), project_path)
        move(os.path.join(project_path, "local_settings.py.template"),
             os.path.join(project_path, "local_settings.py"))

    # Generate a unique SECREY_KEY for the project's setttings module.
    settings_path = os.path.join(os.getcwd(), project_name, "settings.py")
    with open(settings_path, "r") as f:
        data = f.read()
    with open(settings_path, "w") as f:
        make_key = lambda: "%s%s%s" % (uuid4(), uuid4(), uuid4())
        data = data.replace("%(SECRET_KEY)s", make_key())
        data = data.replace("%(NEVERCACHE_KEY)s", make_key())
        f.write(data)

    # Clean up pyc files.
    for (root, dirs, files) in os.walk(project_path, False):
        for f in files:
            if f.endswith(".pyc"):
                os.remove(os.path.join(root, f))

if __name__ == "__main__":
    create_project()


text:
import pytest
import os, inspect

def module_path(local_function):
    '''
    returns the module path without the use of __file__.  Requires a function defined locally in the module.
    from http://stackoverflow.com/questions/729583/getting-file-path-of-imported-module
    '''
    return os.path.abspath(inspect.getsourcefile(local_function))

# Locate test resource (data) files regardless of from where pytest was run
# Warning: requires all tests to be grandchildren of the test dir
@pytest.fixture
def testresourcepath():
    return os.path.normpath(os.path.join(
        module_path(lambda _: None), '../resource/'))


text:
namespace dukat
{
	class FontCache
	{
	private:
		const std::string resource_dir;
		TextureFilterProfile filter_profile;
		std::unordered_map<std::string, std::unique_ptr<BitmapFont>> fonts;

	public:
		FontCache(const std::string& resource_dir) : resource_dir(resource_dir), filter_profile(TextureFilterProfile::ProfileNearest) { }
		~FontCache(void) { }

		void set_texture_filter_profile(TextureFilterProfile filter_profile) { this->filter_profile = filter_profile; }

		BitmapFont* get(const std::string& font);
		void clear(void) { fonts.clear(); }
	};
}


text:
export class TimeSpanLocal {
  public begin:number;
  public end:number;
  public repeats:number;

  constructor() {
    this.begin = 8;
    this.end = 18;
    this.repeats = 1;
  }
}


text:
<!doctype html>

		<meta charset="utf-8" />
	<meta name="viewport" content="width=device-width, initial-scale=1.0" />
	<title>Search</title>
	<link rel="stylesheet" type="text/css" href="http://vacsf.org/assets/css/styles_feeling_responsive.css" />

  <meta name="google-site-verification" content="" />
	<meta name="msvalidate.01" content="" />
	<meta name="description" content="Know with certainty your salvation. To please and bear fruit to God. Learn how to walk by faith. Rest for your soul. Peace with God. Abundant life." />

	<link rel="author" href=""/>

	<link rel="icon" sizes="32x32" href="http://vacsf.org/assets/img/favicon-32x32.png" />

	<link rel="icon" sizes="192x192" href="http://vacsf.org/assets/img/touch-icon-192x192.png" />

	<link rel="apple-touch-icon-precomposed" sizes="180x180" href="http://vacsf.org/assets/img/apple-touch-icon-180x180-precomposed.png" />

	<link rel="apple-touch-icon-precomposed" sizes="152x152" href="http://vacsf.org/assets/img/apple-touch-icon-152x152-precomposed.png" />

	<link rel="apple-touch-icon-precomposed" sizes="144x144" href="http://vacsf.org/assets/img/apple-touch-icon-144x144-precomposed.png" />

	<link rel="apple-touch-icon-precomposed" sizes="120x120" href="http://vacsf.org/assets/img/apple-touch-icon-120x120-precomposed.png" />

	<link rel="apple-touch-icon-precomposed" sizes="114x114" href="http://vacsf.org/assets/img/apple-touch-icon-114x114-precomposed.png" />

	<link rel="apple-touch-icon-precomposed" sizes="76x76" href="http://vacsf.org/assets/img/apple-touch-icon-76x76-precomposed.png" />

	<link rel="apple-touch-icon-precomposed" sizes="72x72" href="http://vacsf.org/assets/img/apple-touch-icon-72x72-precomposed.png" />

	<link rel="apple-touch-icon-precomposed" href="http://vacsf.org/assets/img/apple-touch-icon-precomposed.png" />

	<meta name="msapplication-TileImage" content="http://vacsf.org/assets/img/msapplication_tileimage.png" />

	<meta name="msapplication-TileColor" content="#fabb00" />

	<meta property="og:locale" content="en_EN" />
	<meta property="og:type" content="website" />
	<meta property="og:title" content="Search" />
	<meta property="og:description" content="Know with certainty your salvation. To please and bear fruit to God. Learn how to walk by faith. Rest for your soul. Peace with God. Abundant life." />
	<meta property="og:url" content="http://vacsf.org//search/" />
	<meta property="og:site_name" content="The Whole Bible is About Jesus!" />

	<link type="text/plain" rel="author" href="http://vacsf.org/humans.txt" />

 The Whole Bible is About Jesus!

Navigation

HOME

                BIBLE STUDY

Parables

Meditations

Galatians

Romans

                Blog

Blog Archive

About

Search

<form id="search" onsubmit="google_search(); return false;">
	<input type="text" id="google-search" placeholder="Enter search term and hit enter" />
</form>

	Search Google for:

search-term site:http://vacsf.org/

        

About This Site

              Know with certainty your salvation. To please and bear fruit to God. Learn how to walk by faith. Rest for your soul. Peace with God. Abundant life.
              More ›

Contact

                    Contact

JOHN 3:16

                  For God so loved the world that he gave his one and only Son, that whoever believes in him shall not perish but have eternal life.

              Created with ♥
              by Nghi Nguyen
              with Jekyll
              based on Feeling Responsive - Thank You.

<link type="text/css" rel="stylesheet" href="https://labs.bible.org/api/NETBibleTagger/v2/netbibletagger.css" media="screen">


text:
//  Created by Monte Hurd on 11/23/13.
//  Copyright (c) 2013 Wikimedia Foundation. Provided under MIT-style license; please copy and modify!

#import "TopMenuTextField.h"
#import "Defines.h"

@implementation TopMenuTextField

@synthesize placeholder = _placeholder;

- (instancetype)init {
    self = [super init];
    if (self) {
        self.borderStyle        = UITextBorderStyleNone;
        self.layer.cornerRadius = 6.0f * MENUS_SCALE_MULTIPLIER;
        self.layer.borderWidth  = 1.0f / [UIScreen mainScreen].scale;
        self.layer.borderColor  = [UIColor lightGrayColor].CGColor;
    }
    return self;
}

// Adds left padding without messing up leftView or rightView.
// From: http://stackoverflow.com/a/14357720
- (CGRect)textRectForBounds:(CGRect)bounds {
    CGRect rect = [super textRectForBounds:bounds];
    return CGRectInset(rect, 10.0f * MENUS_SCALE_MULTIPLIER, 0);
}

- (CGRect)editingRectForBounds:(CGRect)bounds {
    return [self textRectForBounds:bounds];
}

- (void)setPlaceholder:(NSString*)placeholder {
    _placeholder               = placeholder;
    self.attributedPlaceholder = [self getAttributedPlaceholderForString:(!placeholder) ? @"" : placeholder];
}

- (NSAttributedString*)getAttributedPlaceholderForString:(NSString*)string {
    NSMutableAttributedString* str = [[NSMutableAttributedString alloc] initWithString:string];

    [str addAttributes:@{
         NSForegroundColorAttributeName: SEARCH_FIELD_PLACEHOLDER_TEXT_COLOR
     }
                 range:NSMakeRange(0, string.length)];
    return str;
}

/*
   // Draw separator line at bottom for iOS 6.

   - (void)drawRect:(CGRect)rect {
    if (NSFoundationVersionNumber <= NSFoundationVersionNumber_iOS_6_1) {
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextMoveToPoint(context, CGRectGetMinX(rect), CGRectGetMaxY(rect));
        CGContextAddLineToPoint(context, CGRectGetMaxX(rect), CGRectGetMaxY(rect));
        CGContextSetStrokeColorWithColor(context, [[UIColor lightGrayColor] CGColor] );
        CGContextSetLineWidth(context, 1.0);
        CGContextStrokePath(context);
    }
   }
 */

@end


text:
<?php

namespace backend\controllers;

use Yii;
use backend\models\Branches;
use backend\models\BranchesSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\ForbiddenHttpException;
use yii\helpers\Json;
use yii\widgets\ActiveForm;
/**
 * BranchesController implements the CRUD actions for Branches model.
 */
class BranchesController extends Controller
{
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }

    /**
     * Lists all Branches models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new BranchesSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        if(Yii::$app->request->post('hasEditable'))
        {
            $branchId = Yii::$app->request->post('editableKey');
            $branch = Branches::findOne($branchId);

            $out = Json::encode(['output'=>'','message'=>'']);
            $post= [];
            $posted = current($_POST['Branches']);
            $post['Branches'] = $posted;
            if($branch->load($post))
            {
                $branch->save();
                $output = 'my values';
                $out = Json::encode(['output'=>$output,'message'=>'']);
            }

            echo $out;
            return;
        }

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Branches model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Branches model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        if( Yii::$app->user->can( 'create-branch' ) )
        {
            $model = new Branches();

            if ($model->load(Yii::$app->request->post()))
            {
                $model->branch_created_date = date('Y-m-d h:m:s');
                if($model->save())
                {
                    echo 1;
                }
                else
                {
                    echo 0;
                }
            } else
            {
                return $this->renderAjax('create', [
                    'model' => $model,
                ]);
            }
        }else
        {
             throw new ForbiddenHttpException;
        }

    }

    public function actionValidation()
    {
        $model = new Branches;
        if(Yii::$app->request->isAjax && $model->load(Yii::$app->request->post()))
        {
            Yii::$app->response->format = 'json';
            return ActiveForm::validate($model);
        }

    }

    public function actionImportExcel()
    {
        $inputFile = 'uploads/branches_file.xlsx';
        try{
            $inputFileType = \PHPExcel_IOFactory::identify($inputFile);
            $objReader = \PHPExcel_IOFactory::createReader($inputFileType);
            $objPHPExcel = $objReader->load($inputFile);
        }catch(Exception $e)
        {
            die('Error');
        }
        $sheet = $objPHPExcel->getSheet(0);
        $highestRow = $sheet->getHighestRow();
        $highestColumn = $sheet->getHighestColumn();
        $data =[];
        for( $row = 1; $row <= $highestRow; $row++)
        {
            $rowData = $sheet->rangeToArray('A'.$row.':'.$highestColumn.$row,NULL,TRUE,FALSE);

            if($row == 1)
            {
                continue;
            }
           if(!empty($rowData[0][0])){
              $data[] = [$rowData[0][0],$rowData[0][1],$rowData[0][2],$rowData[0][3],date('Y-m-d H:i:s'),$rowData[0][4]];
           }
        }
        Yii::$app->db->createCommand()
            ->batchInsert('branches',['branch_id','companies_company_id','branch_name','branch_address','branch_created_date','branch_status'],$data)
            ->execute();
        die('okay');
    }

    /**
     * Updates an existing Branches model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->branch_id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing Branches model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    public function actionLists($id)
    {
        $countBranches = Branches::find()
                ->where(['companies_company_id' => $id])
                ->count();

        $branches = Branches::find()
                ->where(['companies_company_id' => $id])
                ->all();

        if($countBranches > 0 )
        {
            foreach($branches as $branch ){
                echo "<option value='".$branch->branch_id."'>".$branch->branch_name."</option>";
            }
        }
        else{
            echo "<option> - </option>";
        }

    }

    public function actionUpload()
    {
      $fileName = 'file';
      $uploadPath = 'uploads';

      if (isset($_FILES[$fileName])) {
          $file = \yii\web\UploadedFile::getInstanceByName($fileName);

          //Print file data
          //print_r($file);

          if ($file->saveAs($uploadPath . '/' . $file->name)) {
              //Now save file data to database

              echo \yii\helpers\Json::encode($file);
          }
      }else{
          return $this->render('upload');
      }

      return false;
    }

    /**
     * Finds the Branches model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Branches the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Branches::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}


text:
Apache ActiveMQ Artemis allows the routing of messages via wildcard addresses.

If a queue is created with an address of say `queue.news.#` then it will
receive any messages sent to addresses that match this, for instance
`queue.news.europe` or `queue.news.usa` or `queue.news.usa.sport`. If
you create a consumer on this queue, this allows a consumer to consume
messages which are sent to a *hierarchy* of addresses.

> **Note:**
>
> In JMS terminology this allows "topic hierarchies" to be created.

This functionality is enabled by default. To turn it off add the following to the `broker.xml` configuration.

```xml
<wildcard-addresses>
   <routing-enabled>false</routing-enabled>
</wildcard-addresses>
```

For more information on the wild card syntax and how to configure it, take a look at [wildcard syntax](wildcard-syntax.md) chapter,
also see the topic hierarchy example in the [examples](examples.md).


text:
export const siteConfig = {
  name: 'Breno Polanski',
  description:
    'A developer who loves to learn new programming languages, build Open Source projects and play video game :)',
  homepage: 'https://brenopolanski.com',
  color: '#232323',
  email: 'breno.polanski@gmail.com',
  resume: 'resume_brenopolanski.pdf',
  social: {
    github: 'https://github.com/brenopolanski',
    gitlab: 'https://gitlab.com/brenopolanski',
    linkedin: 'https://linkedin.com/in/brenopolanski',
    twitter: 'https://twitter.com/brenopolanski',
  },
}


text:
puts "I am the mystical magic 8 ball! Ask me anything!"

gets

answers = ['It is certain', 'It is decidedly so', 'Without a doubt', 'Cannot predict now','You may rely on it','As I see it, yes','Most likely','Outlook good','Yes','Signs point to yes','Reply hazy try again','Ask again later','Better not tell you now','Concentrate and ask again','Dont count on it',' My reply is no','My sources say no','Yes definitely','Outlook not so good','Very doubtful']

puts answers[(0..19).to_a.sample]


text:
from django.contrib.auth import BACKEND_SESSION_KEY
from django.core.exceptions import ImproperlyConfigured

from authlink.adapter import get_adapter

adapter = get_adapter()

class AuthLinkWhitelistMiddleware(object):
    """
    Only allow access to whitelisted URLs for sessions that are
    established using the authlink authentication mechanism.

    Note: if you want the user to be able to access everything
    then don't use this middleware!
    """

    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        if not hasattr(request, "session"):
            raise ImproperlyConfigured(
                "Please ensure you place AuthLinkWhitelistMiddleware "
                "middleware after your session middlware."
            )
        backend = request.session.get(BACKEND_SESSION_KEY)
        if backend and backend == "authlink.auth_backends.AuthLinkBackend":
            if not adapter.in_url_whitelist(request.path):
                return adapter.get_whitelist_failure_response(request)
        return self.get_response(request)


text:
require 'rubygems'

require_relative 'tww/base'
require_relative 'tww/configuration'
require_relative 'tww/sms'


text:
namespace MusicStore.Models
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    public class Artist
    {
        public Artist()
        {
            this.ArtistId = Guid.NewGuid();
        }
        public Guid ArtistId { get; set; }
        public string Name { get; set; }
        public Country Country { get; set; }
        public DateTime DateOfBirth { get; set; }

    }
}