text:
#include <aws/iotwireless/model/SemtechGnssConfiguration.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace IoTWireless
{
namespace Model
{

SemtechGnssConfiguration::SemtechGnssConfiguration() :
    m_status(PositionConfigurationStatus::NOT_SET),
    m_statusHasBeenSet(false),
    m_fec(PositionConfigurationFec::NOT_SET),
    m_fecHasBeenSet(false)
{
}

SemtechGnssConfiguration::SemtechGnssConfiguration(JsonView jsonValue) :
    m_status(PositionConfigurationStatus::NOT_SET),
    m_statusHasBeenSet(false),
    m_fec(PositionConfigurationFec::NOT_SET),
    m_fecHasBeenSet(false)
{
  *this = jsonValue;
}

SemtechGnssConfiguration& SemtechGnssConfiguration::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("Status"))
  {
    m_status = PositionConfigurationStatusMapper::GetPositionConfigurationStatusForName(jsonValue.GetString("Status"));

    m_statusHasBeenSet = true;
  }

  if(jsonValue.ValueExists("Fec"))
  {
    m_fec = PositionConfigurationFecMapper::GetPositionConfigurationFecForName(jsonValue.GetString("Fec"));

    m_fecHasBeenSet = true;
  }

  return *this;
}

JsonValue SemtechGnssConfiguration::Jsonize() const
{
  JsonValue payload;

  if(m_statusHasBeenSet)
  {
   payload.WithString("Status", PositionConfigurationStatusMapper::GetNameForPositionConfigurationStatus(m_status));
  }

  if(m_fecHasBeenSet)
  {
   payload.WithString("Fec", PositionConfigurationFecMapper::GetNameForPositionConfigurationFec(m_fec));
  }

  return payload;
}

} // namespace Model
} // namespace IoTWireless
} // namespace Aws


text:
'use strict';
const Sequelize = require('sequelize');
const scheme = {
  _id: {
    type: Sequelize.INTEGER,
    primaryKey: true,
    autoIncrement: true,
  },
  name: {
    type: Sequelize.STRING,
    required: true,
  },
  title: {
    type: Sequelize.STRING,
  },
  author: {
    type: Sequelize.STRING,
  },
  content: {
    type: Sequelize.STRING,
  },
  cron_interval: {
    type: Sequelize.STRING,
    required: true,
  },
  cron_interval_pretty: {
    type: Sequelize.STRING,
    required: true,
  },
  active: {
    type: Sequelize.BOOLEAN,
  },
  container: {
    type: Sequelize.STRING,
  },
  time_zone: {
    type: Sequelize.STRING,
  },
  label: {
    type: Sequelize.STRING,
  },
  command_line_arguments: {
    type: Sequelize.STRING,
  },
  runtime_options: {
    type: Sequelize.TEXT,
    // allowNull: false,
    get() {
      return this.getDataValue('runtime_options') ? JSON.parse(this.getDataValue('runtime_options')) : {};
    },
    set(val) {
      this.setDataValue('runtime_options', JSON.stringify(val));
    },
  },
  cron_properties: {
    type: Sequelize.TEXT,
    // allowNull: false,
    get() {
      return this.getDataValue('cron_properties') ? JSON.parse(this.getDataValue('cron_properties')) : {};
    },
    set(val) {
      this.setDataValue('cron_properties', JSON.stringify(val));
    },
  },
  internal_function: {
    type: Sequelize.STRING,
  },
  inline_function: {
    type: Sequelize.STRING,
  },
  inline_test: {
    type: Sequelize.STRING,
  },
  asset_signature: {
    type: Sequelize.STRING,
  },
};
const options = {
  underscored: true,
  timestamps: true,
  indexes: [{
    fields: ['createdat',],
  },],
  createdAt: 'createdat',
  updatedAt: 'updatedat',
};
const associations = [{
  source: 'code',
  association: 'hasOne',
  target: 'asset',
  options: {
    as: 'asset_id',
  },
},];

module.exports = {
  scheme,
  options,
  associations,
  coreDataOptions: {
    docid: ['_id', 'name',],
    sort: { createdat: -1, },
    search: ['title', 'name', 'asset_signature',],
    // population: 'user_id',
  },
};

redpajama_set_name: RedPajamaGithub


text:
from django.conf.urls import patterns, url
from django.contrib import admin
from django.shortcuts import render_to_response

import citations.models as reference_models
from django.template import RequestContext

try:
    from citations.forms import BibtexUploadForm
except ImportError:
    pass

class ReferenceAdmin(admin.ModelAdmin):
    change_list_template = 'admin/updated_change_form.html'

    def get_urls(self):
        urls = super(ReferenceAdmin, self).get_urls()

        if 'BibtexUploadForm' in globals():
            new_urls = patterns('',
                url(r'^upload_bibtex/$', self.admin_site.admin_view(self.upload_bibtex_view), name='citations_reference_upload_bibtex')
            )

            return new_urls + urls

        else:
            return urls

    def upload_bibtex_view(self, request):
        if not 'BibtexUploadForm' in globals():
            return render_to_response('admin/unable_to_upload_bibtex.html', {})

        else:
            if request.method == "POST":
                form = BibtexUploadForm(request.POST, request.FILES)
                if form.is_valid():
                    records = form.save()
                    context = {"form": form, "success": True, "records": records}
                    return render_to_response("admin/imported.html", context,
                                              context_instance = RequestContext(request))
            else:
                form = BibtexUploadForm()
                context = {"form": form}
                return render_to_response("admin/imported.html", context,
                                          context_instance=RequestContext(request))

admin.site.register(reference_models.Reference, ReferenceAdmin)


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ISAAR.MSolve.Analyzers.Optimization
{
    public interface IOptimizationAlgorithm
    {
        double BestFitness
        {
            get;
        }

        double[] BestPosition
        {
            get;
        }

        int CurrentIteration
        {
            get;
        }

        double CurrentFunctionEvaluations
        {
            get;
        }

        void Solve();
    }
}


text:
package org.rapidoid.security.annotation;

import org.rapidoid.annotation.Authors;
import org.rapidoid.annotation.Since;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

@Target({TYPE, FIELD, METHOD})
@Retention(RUNTIME)
@Authors("Nikolche Mihajlovski")
@Since("2.0.0")
public @interface CanInsert {

    String[] value();

}


text:
/**
 * The interfaces provided are listed below, along with usage samples.
 *
 *
======================= AddressesClient =======================
 *
 *
Service Description: Services
 *
 *
The Addresses API.
 *
 *
Sample for AddressesClient:
 *
 *
{@code
 * // This snippet has been automatically generated and should be regarded as a code template only.
 * // It will require modifications to work:
 * // - It may require correct/in-range values for request initialization.
 * // - It may require specifying regional endpoints when creating the service client as shown in
 * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
 * try (AddressesClient addressesClient = AddressesClient.create()) {
 *   String project = "project-309310695";
 *   for (Map.Entry<String, AddressesScopedList> element :
 *       addressesClient.aggregatedList(project).iterateAll()) {
 *     // doThingsWith(element);
 *   }
 * }
 * }

 *
 *
======================= RegionOperationsClient =======================
 *
 *
Service Description: The RegionOperations API.
 *
 *
Sample for RegionOperationsClient:
 *
 *
{@code
 * // This snippet has been automatically generated and should be regarded as a code template only.
 * // It will require modifications to work:
 * // - It may require correct/in-range values for request initialization.
 * // - It may require specifying regional endpoints when creating the service client as shown in
 * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
 * try (RegionOperationsClient regionOperationsClient = RegionOperationsClient.create()) {
 *   String project = "project-309310695";
 *   String region = "region-934795532";
 *   String operation = "operation1662702951";
 *   Operation response = regionOperationsClient.get(project, region, operation);
 * }
 * }

 */
@Generated("by gapic-generator-java")
package com.google.cloud.compute.v1small;

import javax.annotation.Generated;


text:
<?php

namespace Demo\FrontendBundle\Twig\Extension;

use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Bundle\TwigBundle\Loader\FilesystemLoader;

class DemoExtension extends \Twig_Extension
{
    protected $loader;
    protected $controller;

    public function __construct(FilesystemLoader $loader)
    {
        $this->loader = $loader;
    }

    public function setController($controller)
    {
        $this->controller = $controller;
    }

    /**
     * {@inheritdoc}
     */
    public function getFunctions()
    {
        return array(
            'demo_code' => new \Twig_Function_Method($this, 'getCode', array('is_safe' => array('html'))),
        );
    }

    public function getCode($template)
    {
        $controller = htmlspecialchars($this->getControllerCode(), ENT_QUOTES, 'UTF-8');
        $template = htmlspecialchars($this->getTemplateCode($template), ENT_QUOTES, 'UTF-8');

        // remove the code block
        $template = str_replace('{% set code = code(_self) %}', '', $template);

        return <<<EOF

Controller Code

$controller

Template Code

$template

EOF;
    }

    protected function getControllerCode()
    {
        $r = new \ReflectionClass($this->controller[0]);
        $m = $r->getMethod($this->controller[1]);

        $code = file($r->getFilename());

		$code = implode('', $code);
        //return '    '.$m->getDocComment()."\n".implode('', array_slice($code, $m->getStartline() - 1, $m->getEndLine() - $m->getStartline() + 1));

		//$uses        = array();
		//$classHeader = array();
		//for($i = 0; $i < $r->getStartline() - 1; $i++)
		//{
		//	if(false !== strpos(($line = $code[$i]), 'use'))
		//		$uses[]  = $line;
		//}
		//for($i = $r->getStartline() - 1; $i < $r->getEndline(); $i++)
		//{
		//	$line = $classHeader[] = $code[$i];
		//	if(false !== strpos($line, '{'))
		//		break;
		//
		//}
        //$code =
		//	'// '.$r->getName()."\n".
		//	implode('', $uses).
		//	$r->getDocComment()."\n".
		//	implode('', $classHeader).
		//	'    '.
		//	$m->getDocComment()."\n".
		//	implode('', array_slice($code, $m->getStartline() - 1, $m->getEndLine() - $m->getStartline() + 1)).
		//	implode('', array_slice($code, $r->getEndline() - 1, 2))
		//;
		return preg_replace('/    /', "\t", $code);
    }

    protected function getTemplateCode($template)
    {
        return $this->loader->getSource($template->getTemplateName());
    }

    /**
     * Returns the name of the extension.
     *
     * @return string The extension name
     */
    public function getName()
    {
        return 'demo_demo';
    }
}


text:
General setup.
Started to read though the basic documentation.
Added a very basic elm file.
Started to read https://dev.to/rtfeldman/tour-of-an-open-source-elm-spa as a reference.

## May 14 2017 - 11:09 to 11:24
Having difficulty with html-to-elm.
Getting error messages about how node is not setup correctly.
Was related to not having a variable assigned

## May 14 2017 - 11:24 to 11:39
Ran into bug because my views directory was named Views.elm.
Added the basic layout and got it working in Main.elm.
Started to try to get the contents of the layout working

## May 15 2017 - 10:02 to 10:17
Started to look into Routing.
Ran into elm-reactor error with intalling a library.
Going to do it according to an elm guide instead

## May 15 2017 - 10:18 to 10:33
Got a little farther but routing is such a hassle in Elm.
Got the basic framework up but still not the basic routing of going to a different url

## May 15 2017 - 10:33 to 10:48
Some links to help with future dealing with routing since I am not taking the time to deeply understand.

https://www.elm-tutorial.org/en/07-routing/02-routing.html
http://package.elm-lang.org/packages/evancz/url-parser/2.0.1

Also think there is some way to use elm-route but it keeps breaking my repo

## May 15 2017 - 10:52 to 11:07
Starting to look around to resolve the elm-http issue...
Nothing jumps out.
I will have to report an issue tomorrow

## May 15 2017 - 11:14 to 11:29
Finally got the routing working.
It was easy once I started to actually pay attention.
I do think the example could be a little better.

## May 16 2017 - 8:57 to 9:12
Started to import the other views into the product.

## May 16 2017 - 9:13 to 9:28
Continued to work on setting up views.
Tried to input the editor html and it seems to have has some issues on a placeholder.
I should report that.
Also the footer seems to overlap with pages that have a large height.

## May 16 2017 - 10:14 to 10:29
Moved the routes out of Main and into Routes.
Added some data structures that will need to be used with the Views.
Started to look into Json decoding

## May 17 2017 - 6:55 to 7:10
Added a data structure for comments.
Started to use the data structures in the views for Articles.

## May 17 2017 - 8:50 to 9:05
Trying to figure out how to do requests in Elm

## May 17 2017 - 9:06 to 9:21
Figured a basic way of setting up the requests.
I realize that I don't know much about Cmd.
Read https://www.elm-tutorial.org/en/03-subs-cmds/02-commands.html

## May 17 2017 - 9:52 to 10:07
Looking into how to decode complex data types.
https://github.com/NoRedInk/elm-decode-pipeline
Seems like pipline is a better way to go than the default since they only go upto 8 props.
I wonder how you do more than that?
Started to decode the articles object

## May 17 2017 - 10:08 to 10:23
Continue work on decode.
The example docs for elm-decode pipline need to have nullable imported.
Got a basic decode of articles working! Alright!
I think next I will work on displaying those articles correctly.

## May 18 2017 - 9:38 to 9:53
Starting working and from the test server and got a null description.
Started to make templates

## May 18 2017 - 9:54 to 10:09
Got the basic data from the example app and then iterated to display static data.
Working on making it more dynamic.
Got a lot of the data working.
I am having some issues with the footer css.
I might look at the real app to see what they did.

## May 18 2017 - 10:09 to 10:24
Removed some code that was no longer needed in Views.Main.
Looked at the example app(specifically footer).
So... Apparently I cannot define the HTML for Elm.
That gets defined already...
Changed some of the artibutes but still getting the footer floating weird.

https://gist.github.com/coreytrampe/a120fac4959db7852c0f.
Maybe for external loading?

## May 18 2017 - 10:26 to 10:41
Just fixed a bunch of warnings.
I actually caught some bugs with an article not following the data format it should.
Seems like Elm automatically creates anon types.

## May 18 2017 - 10:41 to 10:56
Back to fixing that stupid footer.
I am just confused.
It must be somehow related to how I am going the head stuff and got the html messed up.
Also not super clear how to use custome html.
There is soemthing about the elm-make and one issue about the elm-reactor but I feel like it should be supported.

## May 18 2017 - 11:00 to 11:15
WHAT IS THIS?
```
@import url(http://fonts.googleapis.com/css?family=Source+Sans+Pro);
html, head, body {
  margin: 0;
  height: 100%;
}
```
It is in the head generated by Elm? Or Reactor?
This is the issue!

Fixed it in a hacky way.
I will have to refactor and figure out how to use an external html page.
Also changed the Readme a little.

## May 19 2017 - 9:57 to 10:12
Display the raw timestamp.
Started to work on loading an article from the api.

## May 19 2017 - 10:13 to 10:28
Continued work on getting data from the api for an article

## May 19 2017 - 10:28 to 10:43
Got an article basically loading.
There are some bugs still but there is at least something there.
Looked at my demo reference...
http://rtfeldman.github.io/elm-spa-example/
The description for an article is only for the short article view.
Looking into using elm-markdown... Not sure about classes.

## May 19 2017 - 10:45 to 11:00
Added elm-markdown.
It seems to be right compared to the demo app but I wonder if it works in all cases.
There are specific classes that are in the demo examples.

Look into elm-time for the time handleing.

## May 19 2017 - 11:00 to 11:15
Got a bit into time handeling libraries but elm does everything it turns out!
Just need to format.
The format does not seem to have a "th" or "st" part.
I should request that.

## May 19 2017 - 11:15 to 11:30
Looking at other apps they do it slightly differently.
Which is all different from the template.

Doing some research into how to batch calls to the server for some things.
http://stackoverflow.com/questions/39392469/how-to-perform-multiple-http-requests-tasks-in-bulk-in-elm-lang
Seems like the solution.

Fixed issue with first loading an article.

## May 20 2017 - 12:13 to 12:28
Going to try to get tags on the main page.
Got them loading in from the server.

## May 20 2017 - 12:29 to 12:42
Got tags displayig.
Have to cut the session short.

## May 20 2017 - 9:20 to 9:35
Going to take some time to refactor and reorganize the code.
Centralized the loading code for different locations.
Hide "Your Feed" if your are not logged in

## May 20 2017 - 9:35 to 9:50
Working on highlighting different parts of the app in the nav bar.
Maybe a little more complex than it needed to be but it is working.

## May 20 2017 - 9:50 to 10:05
Going to try to get profiles loading.
Got them loading and got it setup to get the data for the profile.
I will need to fillout the rest of the profile page with data.
I will also have to load the articles written and liked by the user.

## May 21 2017 - 7:06 to 7:21
Working on getting more data into the profile.
Updated the view a little and also loading in articles written by the profile.
I need to figure out a better way to deal with multiple calls when accessing a page.

## May 21 2017 - 9:10 to 9:25
Work on displaying a users articles.
Got it working I will also have to figure out a way to deal with switching between written articles and favorite articles

## May 21 2017 - 9:25 to 9:40
Fixed issue when you click on a username you get redirected to "profile.html".
Also updated the layout to use the Maybe User to display certain things on the navbar.
I think I will try to get all the non-logged in stuff done or mostly working before trying to figureout the logged in.
I will have to figure out some localstorage stuff for that.

## May 22 2017 - 7:16 to 7:31
Going to look at getting the pagination at the bottom of the main page.
They don't seem to have pagination in their templates.
Got a basic dumb display wokring.
I need to actually hook it up to real values.
I wonder how many articles per page... Maybe the api spec talks about it.

## May 22 2017 - 7:34 to 7:49
From API the default is `20`.
I also need to get the total number of articles.
Though the example app has `10` per page...
Did some minor fixes to the Sign Up and Sign in pages.
I will probably work on loading in comments on articles next.

## May 22 2017 - 7:50 to 8:05
Added the basic code and functions to decode the comments and store them.

## May 23 2017 - 8:40 to 8:55
Got the comments displaying correctly.
I am going to have to address issues in multiple places with logged in vs non-logged in user

## May 23 2017 - 8:55 to 9:10
On the article page I should hide certain things like follow and favorite post.
Also making comments.
Hide those things.

## May 23 2017 - 9:10 to 9:25
Looking at the example app I realize that I don't have tags on my article previews...
Also to the actual article.

Upto this point I have not actually been setting up certain filters like tags ot pages.
I will have to work on that now.

I also think I have been using logs completely wrong...

## May 24 2017 - 9:13 to 9:28
Worked on preventing the bubleing events when a a link is click.
Sort of a fun jounrey.
Ran into a google groups thread that lead me into looking at the internals of the html.events code.

## May 24 2017 - 9:28 to 9:43
Looking at the example app I see that there needs to be a separate tag on the main page when you click on a side tag...
I am going to work on the profile articles and switching between.

I am trying to think if I want to go though a clean up or not.
Everything is working but I do think I could do some stuff to make it easier to work on.
I am also thinking of centeralizing all strings that are displayed to a user.

## May 25 2017 - 7:08 to 7:23
Add some text if no articles are found in a user's profile.
Also got the tab highlighting working on the profile page.

## May 25 2017 - 7:32 to 7:47
Looking into adding an additional tab on the main page for when a tag is selected.
Need to make it select like it is active.
Then is is on to pagniations.
I also need to have a case for tags + pages.

I also am sort of clueless about the local storage for Elm and authentication.
Maybe I can do that late in the game.
Just keep credentials in the local memory.

## May 26 2017 - 10:12 to 10:27
Just some general clean up.
Ran elm-format
Also ran elm-analyse.
Cleaned up some issues.

## May 26 2017 - 10:28 to 10:43
Continue with using elm-analyse.
Not sure if I agree with everything it recommends(import all from namespace) but it is supercool.
Also Sum types... Maybe a little too far...

## May 27 2017 - 21:55 to 22:10
Added the ability to click a page and get something else to load.
I also need to highlight the currentPage.

## May 28 2017 - 22:22 to 22:37
Going to work on more pagniation stuff.
I think there will always be pagniation on very call.
That way pages work with tags.
I will have to do more work with this

## May 29 2017 - 22:42 to 22:57
Working on getting the paging correct.
Mostly correct I think but not certain.
I guess the next step is Sign in and sign up.
Actually I should fix some issues with a reload being forced.
And highlighting the tag tab when one is selected.

## May 29 2017 - 22:56 to 22:11
Got the tag tab highlighting correctly.
Reviewed the doc for how to log in.
I am just going to store in the elm data structure for now.
I am also going to have to add quth token to the request.

Looking at the sourcecode for elm-http
https://github.com/elm-lang/http/blob/master/src/Http.elm#L159
I will have to implement my own version to get the correct authentication headers.

Added a basic authedGet and will add more in the future.

## May 30 2017 - 22:42 to 22:57
Continue to look into how to do the post and request
https://guide.elm-lang.org/architecture/user_input/forms.html

Got some new data in the model and new events that will be useful for login

## May 31 2017 - 22:32 to 22:47
Looking more into saving to the backend.

https://github.com/mpizenberg/elm_api_test/blob/master/src/Main.elm

It seems like the data needs to be encoded like it was decoded going back to the server.
Should split the encoders and decoders into modules.

## June 1 2017 - 21:22 to 21:37
Worked on modifications for posting data.

## June 2 2017 - 22:03 to 22:18
Worked on login and got a repsonse back!
I still need to figure out how to redirect after...

## June 2 2017 - 22:20 to 22:35
Ok I am getting an error for some reason on the user login...
It is because my bio is null.

Fixed that and now I am in!
Awesome! There will be a bit of work but I think one of my first things will be to log back out.

Got log out working.
I can already tell it will be annoying login in and out.
I might have to look at the elm implementation to see how it does the ports.
I would rather learn on my own though.

## June 3 2017 - 23:09 to 23:24
Looking into custom html page for getting localstorage working
Looked at the html in the elm-app :(
Will have to not look anymore.

## June 4 2017 - 19:56 to 20:11
Looking to how to use ports.
Not a lot of progress

## June 4 2017 - 20:11 to 20:26
Got elm code calling JS code.
I need the path back

## June 4 2017 - 20:26 to 20:41
Got very close to having localstorage done.
Just a little but more...

## June 4 2017 - 20:41 to 20:56
Finally got it working!

I am also going to clean up the issue with how I am loading css.
Then I can start to work on actually implementing logged in functionality like liking and posting.

I should also get log out working.
I wonder how much i will need to include the token in requests

## June 4 2017 - 21:01 to 21:16
Going to read the spec some more then implement logout.
Maybe I should not store the entire user object. Just the toke then call api/user

Also I have to recall getting the articles with the token so that I can figured out if I liked an article or not...

I will need to get the feed articles.

I also realize that I don't have the proper html for the new post page.
That is a low hanging fruit that can be addressed next.

## June 4 2017 - 21:16 to 21:31
Figured out why the http-to-elm does not work. There was a placeholder with a "'".
Actually took the time to submit an issue to the repo.

Noticed a bug with the session log in.
It only works when on home page(makes sense because of how I did the code.).

Going to populate data in my settings.

## June 5 2017 - 20:03 to 20:18
Started the work on getting the correct feed data

## June 5 2017 - 20:18 to 20:33
I can now get the feed(even though there is nothing in it)
I have to add an additional way of tracking the model and knowing what to highlight

## June 5 2017 - 22:14 to 22:29
Got the My Feed sort of working...Not sure about paging yet.
There are some small differences between the markup I got from the templates and what example apps are doing.
For example on an article and users page there is some indication it shows you how many people are following someone.
But in the example apps that is not there.


text:
import abc

from OnePy.constants import ActionType
from OnePy.sys_module.base_recorder import RecorderBase
from OnePy.sys_module.components.signal_generator import SignalGenerator
from OnePy.sys_module.metabase_env import OnePyEnvBase

class StrategyBase(OnePyEnvBase, abc.ABC):

    def __init__(self) -> None:
        self.name = self.__class__.__name__
        self.env.strategies.update({self.name: self})

        self.buy = SignalGenerator(ActionType.Buy, self.name).buy_or_short
        self.sell = SignalGenerator(ActionType.Sell, self.name).sell_or_cover
        self.short = SignalGenerator(ActionType.Short, self.name).buy_or_short
        self.cover = SignalGenerator(ActionType.Cover, self.name).sell_or_cover
        self.cancel_pending = SignalGenerator(
            ActionType.Cancel, self.name).cancel_pending
        self.cancel_tst = SignalGenerator(
            ActionType.Cancel, self.name).cancel_tst
        self.params: dict = None

    @property
    def recorder(self) -> RecorderBase:
        """便于在strategy中调用账户信息数据"""

        return self.env.recorder

    @abc.abstractmethod
    def handle_bar(self):
        """在这里写策略的主要逻辑"""
        raise NotImplementedError

    def run(self):
        self.handle_bar()

    def cur_price(self, ticker: str) -> float:
        return self.env.feeds[ticker].cur_price

    def set_params(self, params: dict):
        """在这里设置参数,以便参数优化"""
        self.params.update(params)


text:
Log In

    <form method="post">
        <input type="text" name="name" placeholder="Your name">
        <input type="password" name="password" placeholder="Your password">
        <input type="submit" value="Login">
    </form>


text:
package com.intellij.codeInsight.daemon.impl;

import com.intellij.codeInsight.hint.HintManager;
import com.intellij.codeInsight.intention.impl.CachedIntentions;
import com.intellij.codeInsight.intention.impl.IntentionHintComponent;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.LogicalPosition;
import com.intellij.openapi.project.Project;
import org.jetbrains.annotations.NotNull;

import java.awt.*;

public class IntentionsUIImpl extends IntentionsUI {
  private volatile IntentionHintComponent myLastIntentionHint;

  public IntentionsUIImpl(@NotNull Project project) {
    super(project);
  }

  IntentionHintComponent getLastIntentionHint() {
    return myLastIntentionHint;
  }

  @Override
  public void update(@NotNull CachedIntentions cachedIntentions, boolean actionsChanged) {
    ApplicationManager.getApplication().assertIsDispatchThread();
    Editor editor = cachedIntentions.getEditor();
    if (editor == null) return;
    if (!ApplicationManager.getApplication().isUnitTestMode() && !editor.getContentComponent().hasFocus()) return;
    if (!actionsChanged) return;

    Project project = cachedIntentions.getProject();
    LogicalPosition caretPos = editor.getCaretModel().getLogicalPosition();
    Rectangle visibleArea = editor.getScrollingModel().getVisibleArea();
    Point xy = editor.logicalPositionToXY(caretPos);

    hide();
    if (!HintManager.getInstance().hasShownHintsThatWillHideByOtherHint(false)
        && visibleArea.contains(xy)
        && editor.getSettings().isShowIntentionBulb()
        && editor.getCaretModel().getCaretCount() == 1
        && cachedIntentions.showBulb()
        // do not show bulb when the user explicitly ESCaped it away
        && !DaemonListeners.getInstance(project).isEscapeJustPressed()) {
      myLastIntentionHint = IntentionHintComponent.showIntentionHint(project, cachedIntentions.getFile(), editor, false, cachedIntentions);
    }
  }

  @Override
  public void hide() {
    ApplicationManager.getApplication().assertIsDispatchThread();
    IntentionHintComponent hint = myLastIntentionHint;
    if (hint != null && !hint.isDisposed() && hint.isVisible()) {
      hint.hide();
    }
    myLastIntentionHint = null;
  }
}


text:
Sequel.migration do
  up do
    add_column :layers, :parent_id, :uuid
  end

  down do
    drop_column :layers, :parent_id
  end
end


text:
@interface ClientProxyDelegateWrapper : NSObject

@property(nonatomic, retain, readonly) id<ClientProxyDelegate> delegate;

- (id)init __unavailable;

+ (id)wrapDelegate:(id<ClientProxyDelegate>)delegate;

@end

#endif  // REMOTING_IOS_BRIDGE_HOST_PROXY_DELEGATE_WRAPPER_H_


text:
/*
 * DO NOT EDIT.  THIS FILE IS GENERATED FROM e:/builds/moz2_slave/rel-2.0-xr-w32-bld/build/rdf/base/idl/nsIRDFXMLParser.idl
 */

#ifndef __gen_nsIRDFXMLParser_h__
#define __gen_nsIRDFXMLParser_h__

#ifndef __gen_nsISupports_h__
#include "nsISupports.h"
#endif

#ifndef __gen_nsIRDFDataSource_h__
#include "nsIRDFDataSource.h"
#endif

#ifndef __gen_nsIStreamListener_h__
#include "nsIStreamListener.h"
#endif

#ifndef __gen_nsIURI_h__
#include "nsIURI.h"
#endif

/* For IDL files that don't want to include root IDL files. */
#ifndef NS_NO_VTABLE
#define NS_NO_VTABLE
#endif

/* starting interface:    nsIRDFXMLParser */
#define NS_IRDFXMLPARSER_IID_STR "1831dd2e-1dd2-11b2-bdb3-86b7b50b70b5"

#define NS_IRDFXMLPARSER_IID \
  {0x1831dd2e, 0x1dd2, 0x11b2, \
    { 0xbd, 0xb3, 0x86, 0xb7, 0xb5, 0x0b, 0x70, 0xb5 }}

class NS_NO_VTABLE NS_SCRIPTABLE nsIRDFXMLParser : public nsISupports {
 public:

  NS_DECLARE_STATIC_IID_ACCESSOR(NS_IRDFXMLPARSER_IID)

  /**
     * Create a stream listener that can be used to asynchronously
     * parse RDF/XML.
     * @param aSink the RDF datasource the will receive the data
     * @param aBaseURI the base URI used to resolve relative
     *   references in the RDF/XML
     * @return an nsIStreamListener object to handle the data
     */
  /* nsIStreamListener parseAsync (in nsIRDFDataSource aSink, in nsIURI aBaseURI); */
  NS_SCRIPTABLE NS_IMETHOD ParseAsync(nsIRDFDataSource *aSink, nsIURI *aBaseURI, nsIStreamListener **_retval NS_OUTPARAM) = 0;

  /**
     * Parse a string of RDF/XML
     * @param aSink the RDF datasource that will receive the data
     * @param aBaseURI the base URI used to resolve relative
     *   references in the RDF/XML
     * @param aSource a UTF8 string containing RDF/XML data.
     */
  /* void parseString (in nsIRDFDataSource aSink, in nsIURI aBaseURI, in AUTF8String aSource); */
  NS_SCRIPTABLE NS_IMETHOD ParseString(nsIRDFDataSource *aSink, nsIURI *aBaseURI, const nsACString & aSource) = 0;

};

  NS_DEFINE_STATIC_IID_ACCESSOR(nsIRDFXMLParser, NS_IRDFXMLPARSER_IID)

/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSIRDFXMLPARSER \
  NS_SCRIPTABLE NS_IMETHOD ParseAsync(nsIRDFDataSource *aSink, nsIURI *aBaseURI, nsIStreamListener **_retval NS_OUTPARAM); \
  NS_SCRIPTABLE NS_IMETHOD ParseString(nsIRDFDataSource *aSink, nsIURI *aBaseURI, const nsACString & aSource);

/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSIRDFXMLPARSER(_to) \
  NS_SCRIPTABLE NS_IMETHOD ParseAsync(nsIRDFDataSource *aSink, nsIURI *aBaseURI, nsIStreamListener **_retval NS_OUTPARAM) { return _to ParseAsync(aSink, aBaseURI, _retval); } \
  NS_SCRIPTABLE NS_IMETHOD ParseString(nsIRDFDataSource *aSink, nsIURI *aBaseURI, const nsACString & aSource) { return _to ParseString(aSink, aBaseURI, aSource); }

/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSIRDFXMLPARSER(_to) \
  NS_SCRIPTABLE NS_IMETHOD ParseAsync(nsIRDFDataSource *aSink, nsIURI *aBaseURI, nsIStreamListener **_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->ParseAsync(aSink, aBaseURI, _retval); } \
  NS_SCRIPTABLE NS_IMETHOD ParseString(nsIRDFDataSource *aSink, nsIURI *aBaseURI, const nsACString & aSource) { return !_to ? NS_ERROR_NULL_POINTER : _to->ParseString(aSink, aBaseURI, aSource); }

#if 0
/* Use the code below as a template for the implementation class for this interface. */

/* Header file */
class nsRDFXMLParser : public nsIRDFXMLParser
{
public:
  NS_DECL_ISUPPORTS
  NS_DECL_NSIRDFXMLPARSER

  nsRDFXMLParser();

private:
  ~nsRDFXMLParser();

protected:
  /* additional members */
};

/* Implementation file */
NS_IMPL_ISUPPORTS1(nsRDFXMLParser, nsIRDFXMLParser)

nsRDFXMLParser::nsRDFXMLParser()
{
  /* member initializers and constructor code */
}

nsRDFXMLParser::~nsRDFXMLParser()
{
  /* destructor code */
}

/* nsIStreamListener parseAsync (in nsIRDFDataSource aSink, in nsIURI aBaseURI); */
NS_IMETHODIMP nsRDFXMLParser::ParseAsync(nsIRDFDataSource *aSink, nsIURI *aBaseURI, nsIStreamListener **_retval NS_OUTPARAM)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* void parseString (in nsIRDFDataSource aSink, in nsIURI aBaseURI, in AUTF8String aSource); */
NS_IMETHODIMP nsRDFXMLParser::ParseString(nsIRDFDataSource *aSink, nsIURI *aBaseURI, const nsACString & aSource)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* End of implementation class template. */
#endif

#endif /* __gen_nsIRDFXMLParser_h__ */


text:
 /* global UniqueID, Counter, Timer*/

$(document).ready(function() {
  var cid = UniqueID();
  var c1 = Counter(cid);
  var c2 = Counter(cid);
  var timer = Timer();
  timer.addCounter(c1);
  timer.addCounter(c2);
  timer.start();
});


text:
import './commands';
import '@frsource/cypress-plugin-visual-regression-diff';


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="timeout" content="long">
    <meta http-equiv="Content-Security-Policy" content="block-all-mixed-content">


text:
package com.google.gwt.query.client;

/**
 * All lazy interfaces must extend this baseclass. This ensures the done()
 * method exists and returns an executable function.
 *
 * @param <S>
 */
public interface LazyBase<S> {
  Function done();
}


text:
<?php
// Text
$_['text_subject']		        = '%s - Affiliate Program';
$_['text_welcome']		        = 'Thank you for joining the %s Affiliate Program!';
$_['text_login']                = 'Your account has now been created and you can log in by using your e-mail address and password by visiting our website or at the following URL:';
$_['text_approval']		        = 'Your account must be approved before you can login. Once approved you can log in by using your e-mail address and password by visiting our website or at the following URL:';
$_['text_services']		        = 'Upon logging in, you will be able to generate tracking codes, track commission payments and edit your account information.';
$_['text_thanks']		        = 'Thanks,';
$_['text_new_affiliate']        = 'New Affiliate';
$_['text_signup']		        = 'A new affiliate has signed up:';
$_['text_store']		        = 'Store:';
$_['text_firstname']	        = 'Firstname:';
$_['text_lastname']		        = 'Lastname:';
$_['text_company']		        = 'Company:';
$_['text_email']		        = 'E-Mail:';
$_['text_telephone']	        = 'Telephone:';
$_['text_website']		        = 'Web Site:';
$_['text_order_id']             = 'Order ID:';
$_['text_transaction_subject']  = '%s - Affiliate Commission';
$_['text_transaction_received'] = 'You have received %s commission!';
$_['text_transaction_total']    = 'Your total amount of commission is now %s.';


text:
from beard import pos
import base_test
import unittest

class TestPosModule(base_test.RequireTokens):

    def test_create_from_tokens(self):

        data = pos.create_from_tokens(self.tokens_01)

        w = data.get('words', {})
        p = data.get('parts_of_speech', {})

        self.assertTrue(w)
        self.assertTrue(p)

        self.assertEqual(len(w), 14)
        self.assertEqual(len(p), 7) # Don't forget the None Pos (start of paragraph)


text:
\set ECHO none
\set QUIET 1
/*
 * Postgres currently doesn't support comparing different string array types
 * (ie: varchar[] vs text[]) so this is split into 3 sections.
 *
 * KEEP ALL THREE FILES IN SYNC!
 */

\set test_types 'varchar[] varchar(10)[]'
\set baseline_type varchar(10)[]

\i test/helpers/_string_setup.sql

-- vi: expandtab sw=2 ts=2


text:
namespace metrics {

namespace {

class MetricsLogManagerTest : public testing::Test {
 public:
  MetricsLogManagerTest() : log_store_(&pref_service_, 0, std::string()) {
    MetricsLogStore::RegisterPrefs(pref_service_.registry());
    log_store()->LoadPersistedUnsentLogs();
  }
  ~MetricsLogManagerTest() override {}

  MetricsLogStore* log_store() { return &log_store_; }

  MetricsLog* CreateLog(MetricsLog::LogType log_type) {
    return new MetricsLog("id", 0, log_type, &client_);
  }

 private:
  TestMetricsServiceClient client_;
  TestingPrefServiceSimple pref_service_;
  MetricsLogStore log_store_;

  DISALLOW_COPY_AND_ASSIGN(MetricsLogManagerTest);
};

}  // namespace

TEST_F(MetricsLogManagerTest, StandardFlow) {
  MetricsLogManager log_manager;

  // Make sure a new manager has a clean slate.
  EXPECT_EQ(nullptr, log_manager.current_log());

  // Check that the normal flow works.
  MetricsLog* initial_log = CreateLog(MetricsLog::INITIAL_STABILITY_LOG);
  log_manager.BeginLoggingWithLog(base::WrapUnique(initial_log));
  EXPECT_EQ(initial_log, log_manager.current_log());

  EXPECT_FALSE(log_store()->has_unsent_logs());
  log_manager.FinishCurrentLog(log_store());
  EXPECT_EQ(nullptr, log_manager.current_log());
  EXPECT_TRUE(log_store()->has_unsent_logs());

  MetricsLog* second_log = CreateLog(MetricsLog::ONGOING_LOG);
  log_manager.BeginLoggingWithLog(base::WrapUnique(second_log));
  EXPECT_EQ(second_log, log_manager.current_log());
}

TEST_F(MetricsLogManagerTest, AbandonedLog) {
  MetricsLogManager log_manager;

  MetricsLog* dummy_log = CreateLog(MetricsLog::INITIAL_STABILITY_LOG);
  log_manager.BeginLoggingWithLog(base::WrapUnique(dummy_log));
  EXPECT_EQ(dummy_log, log_manager.current_log());

  log_manager.DiscardCurrentLog();
  EXPECT_EQ(nullptr, log_manager.current_log());
}

// Make sure that interjecting logs updates the "current" log correctly.
TEST_F(MetricsLogManagerTest, InterjectedLog) {
  MetricsLogManager log_manager;

  MetricsLog* ongoing_log = CreateLog(MetricsLog::ONGOING_LOG);
  MetricsLog* temp_log = CreateLog(MetricsLog::INITIAL_STABILITY_LOG);

  log_manager.BeginLoggingWithLog(base::WrapUnique(ongoing_log));
  EXPECT_EQ(ongoing_log, log_manager.current_log());

  log_manager.PauseCurrentLog();
  EXPECT_EQ(nullptr, log_manager.current_log());

  log_manager.BeginLoggingWithLog(base::WrapUnique(temp_log));
  EXPECT_EQ(temp_log, log_manager.current_log());
  log_manager.FinishCurrentLog(log_store());
  EXPECT_EQ(nullptr, log_manager.current_log());

  log_manager.ResumePausedLog();
  EXPECT_EQ(ongoing_log, log_manager.current_log());
}

// Make sure that when one log is interjected by another, that finishing them
// creates logs of the correct type.
TEST_F(MetricsLogManagerTest, InterjectedLogPreservesType) {
  MetricsLogManager log_manager;

  log_manager.BeginLoggingWithLog(
      base::WrapUnique(CreateLog(MetricsLog::ONGOING_LOG)));
  log_manager.PauseCurrentLog();
  log_manager.BeginLoggingWithLog(
      base::WrapUnique(CreateLog(MetricsLog::INITIAL_STABILITY_LOG)));
  log_manager.FinishCurrentLog(log_store());
  log_manager.ResumePausedLog();
  // Finishing the interjecting inital log should have stored an initial log.
  EXPECT_EQ(1U, log_store()->initial_log_count());
  EXPECT_EQ(0U, log_store()->ongoing_log_count());

  // Finishing the interjected ongoing log should store an ongoing log.
  log_manager.FinishCurrentLog(log_store());
  EXPECT_EQ(1U, log_store()->initial_log_count());
  EXPECT_EQ(1U, log_store()->ongoing_log_count());
}

}  // namespace metrics


text:
dotvim
======

Vim configuration files

## Installation

    git clone git:/github.com/sugaryourcoffee/dotvim.git ~/.vim

## Create symlink

    ln -s ~/.vim/vimrc ~/.vimrc

## Get submodule

    cd ~/.vim
    git submodule init
    git submodule udpate

Source:
[VIMCASTS](http://vimcasts.org)
[Synchronizing plugins with git submodules and pathogen](http://vimcasts.org/episodes/synchronizing-plugins-with-git-submodules-and-pathogen/)


text:
<!DOCTYPE html>

        <title>AngularJS Basic Example</title>
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
        <link rel="stylesheet" href="lib/css/bootstrap.min.css" />
        <link rel="stylesheet" href="lib/css/animate.min.css" />


text:
package com.rho.camera;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.view.OrientationEventListener;

public class OrientationListnerService extends Service{
	public static int mRotation = 0;
	private OrientationEventListener mOrientationListener;
	@Override
	public void onCreate() {
		super.onCreate();
		mOrientationListener = new OrientationEventListener(this) {
			@Override
			public void onOrientationChanged(int rotation) {
			if(rotation != -1){
				if(rotation >=315 && rotation < 45){
					mRotation = 0;
				}else if(rotation >=45 && rotation < 135){
					mRotation = 90;
				}else if(rotation >=135 && rotation < 225){
					mRotation = 180;
				}else if(rotation >=225 && rotation< 315){
					mRotation = 270;
				}else{
					mRotation = 0;
				}
			}
		}
		};
	}
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		if (mOrientationListener.canDetectOrientation()) {
            mOrientationListener.enable();
        }
		return super.onStartCommand(intent, flags, startId);
	}
	@Override
	public void onDestroy() {
		mOrientationListener.disable();
		super.onDestroy();
	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}
}


text:
define([
    './navigator.module',
    './navigator.provider',
    //'./navigator.routes',
    './navigator.controller'
], function () {
});


text:
order: 1
zh-CN:
  title: 获取主题色
  triggerText: 复制所有变量
  changePrompt: 切换到
en-US:
  title: Get theme color
  triggerText: Copy All Variables
  changePrompt: Switch to
---

```jsx
import { ColorPicker, Grid, CopyButton, Button, Icon, WindowEventHandler } from 'zent';
import { ThemeSdk, ThemeScene } from '@zent/theme-sdk';
import ThemeCssVars from 'zent/theme-css-vars.json';
import { hexToRGBString } from '@zent/theme-sdk/esm/utils';
import { useState, useMemo, useCallback, useEffect } from 'react';

const { generateTheme } = ThemeSdk;

const colors = [
	'#ed6a18',
	'#ed9f18',
	'#edd418',
	'#bad415',
	'#5bd415',
	'#15d48e',
	'#15bad4',
	'#155bd4',
	'#412ad4',
	'#8e15d4',
	'#d415ba',
	'#d42f15',
];

const defaultColor = '#155bd4';

const themeIndex = {
	'$primary-100': 0,
	'$primary-400': 1,
	'$primary-500': 2,
	'$primary-600': 3,
};

const ColorType = {
	hex: 'Hex',
	rgb: 'Rgb',
};

const ColorScene = [
	ThemeScene.DefaultHoverBackgroundColor,
	ThemeScene.PrimaryHoverBackgroundColor,
	ThemeScene.PrimaryBackgroundColor,
	ThemeScene.PrimaryActiveBackgroundColor,
];

const getThemeCommentsVars = colors => {
	return colors.filter(
		({ cssVariableName }) => ThemeCssVars.vars[cssVariableName]
	);
};

const transformToCss = theme => {
	return theme
		.map(item => `${item.cssVariableName}:  ${item.color};`)
		.join('\n');
};

const getSessionThemeColor = () => {
	// ThemeSwitcher on top-right corner sets this variable
	return window.sessionStorage.getItem('zent-theme-color') ?? defaultColor;
};

const Color = ({ colorType, setColorType }) => {
	const otherType = colorType === ColorType.hex ? ColorType.rgb : ColorType.hex;

	const changeColorType = useCallback(() => {
		setColorType(otherType);
	}, [setColorType, otherType]);

	return (
		<>
			{colorType} Color
			<Button
				className="demo-theme-color-copy-switcher"
				size="small"
				onClick={changeColorType}
			>
				{i18n.changePrompt} {otherType}
			</Button>
		</>
	);
};

const ThemeSdkComponent = () => {
	const [color, setColor] = useState(getSessionThemeColor());
	const theme = useMemo(() => {
		return generateTheme(
			{ colors: [{ baseColor: color, scene: ColorScene }] },
			ThemeCssVars
		);
	}, [color]);
	const themeComments = useMemo(() => {
		return getThemeCommentsVars(theme.colors);
	}, [theme]);
	const themeCssStr = useMemo(() => {
		return transformToCss(theme.colors);
	}, [theme]);
	const [colorType, setColorType] = useState(ColorType.hex);

	const columns = useMemo(() => {
		return [
			{
				title: 'CSS Variable',
				name: 'cssVariableName',
				bodyRender: ({ cssVariableName }) => {
					return (
						<div className="demo-theme-color-title">
							<p className="demo-theme-color-css-variable">
								{cssVariableName}
								<CopyButton text={cssVariableName}>
									<Icon className="demo-theme-color-copy-icon" type="order-o" />
								</CopyButton>
							</p>
							<p className="demo-theme-color-desc">
								{ThemeCssVars.vars[cssVariableName].comment}
							</p>
						</div>
					);
				},
			},
			{
				title: <Color colorType={colorType} setColorType={setColorType} />,
				name: 'color',
				bodyRender: ({ color }) => {
					const colorText =
						colorType === ColorType.rgb ? hexToRGBString(color) : color;
					return (
						<div className="demo-theme-color">
							<CopyButton text={colorText}>
								<p
									className="demo-theme-color-block"
									style={{ background: color }}
								></p>
							</CopyButton>
							<div className="demo-theme-color-name">{colorText}</div>
						</div>
					);
				},
				width: '300px',
			},
		];
	}, [colorType]);

	const onColorChange = useCallback(
		baseColor => {
			setColor(baseColor);
		},
		[]
	);

	const onThemeSwitch = useCallback((evt) => {
	  onColorChange(evt.detail);
	}, []);

	return (
		<>
			<div>
				<ColorPicker
					color={color}
					type="simple"
					onChange={onColorChange}
					presetColors={colors}
				/>
				<span className="demo-theme-base-color">{color}</span>
				<CopyButton text={themeCssStr}>
					<Button type="primary" className="demo-theme-copy-btn">
						{i18n.triggerText}
					</Button>
				</CopyButton>
			</div>
			<Grid
				rowKey="cssVariableName"
				className="demo-theme-colors"
				columns={columns}
				datasets={themeComments}
			/>
			<WindowEventHandler eventName="zent-theme-change" listener={onThemeSwitch} />
		</>
	);
};

ReactDOM.render(<ThemeSdkComponent />, mountNode);
```

<style>
.demo-theme-color-title {
  font-size: 14px;
  color: #333;
}

.demo-theme-color-css-variable {
  cursor: pointer;
}

.demo-theme-color-desc {
  font-size: 12px;
  color: #999;
}

.demo-theme-color {
  margin: 4px 8px 4px 4px;
  display: flex;
  align-items: center;
}

.demo-theme-color-copy-switcher {
  margin-left: 16px;
}

.demo-theme-color-block {
  width: 80px;
  height: 30px;
  margin-bottom: 4px;
  border-radius: 2px;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #000;
  cursor: pointer;
}

.demo-theme-color-copy-icon {
  margin-left: 4px;
}

.demo-theme-color-name {
  color: #333;
  text-align: center;
  margin-left: 4px;
}

.demo-theme-base-color {
  margin-left: 8px;
}

.demo-theme-copy-btn {
  float: right;
}

.demo-theme-colors {
  margin-top: 16px;
}
</style>


text:
[![build status](https://raw.github.com/draeton/deeplink/master/out/status.png)](http://draeton.github.com/deeplink/)

[Deeplink](http://draeton.github.com/deeplink/)
==========

Deeplink is a small utility for working with deeplinks.
The current version is `@VERSION@`. Documentation is available
[here](http://draeton.github.com/deeplink/deeplink/docs/deeplink.html).

## Implementation

    <script src="js/jquery-1.7.1.min.js"></script>
    <script src="js/deeplink-@VERSION@-min.js"></script>

## Usage

Each new Deeplink instance is a new object monitoring the window.onhashchange event (or a custom monitoring function for older browsers). This is the simplest way to call the constructor:

    var d = new Deeplink();

You may also specify strings for the hash equality and separator values:

    var d = new Deeplink(":", ",");

### .hashchange

Every "hashchange" event triggers a "deeplink" event on the Deeplink instance. Any functions that need information from this event should be bound to the instance. These functions receive two arguments: a jQuery Event, and a data object with the data.hash string and a data.map key-value object:

    var d = new Deeplink();

    var goto = function (e, data) {
        var hash = data.hash;
        var map = data.map;
    };

    $(d).bind("deeplink", goto);

### .hashupdate

One other method to note is "hashupdate". If your code updates the state of the page in a way that needs to be referenced by a deeplink, you may pass a key-value object into this method to update the page URL. This method has three parameters:

* **map**: The key-value object that updates the hash parameters
* **replace**: A boolean that specifies whether the entire hash should be replaced
* **fire**: A boolean that specifies whether this update should trigger a deeplink event on this instance

Sample usage:

    var d = new Deeplink();

    var changePanel = function (id) {

        // do stuff to change the panel

        d.hashupdate({"panel", id});
    };

    changePanel(4);

### Deeplink.setDelay

A final method to review is Deeplink.setDelay, which allows you to modify the timeout length between hash checks in
browsers that don't support the window.onhashchange event:

    Deeplink.setDelay(500); // in milliseconds

## Dependencies

jQuery 1.7+

## License

(The MIT License)

Copyright (c) 2013, <[Matthew Cobbs](mailto:draeton@gmail.com)>

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.


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

  angular
    .module('confirmations')
    .factory('ConfirmationsService', ConfirmationsService);

  ConfirmationsService.$inject = ['$resource'];

  function ConfirmationsService($resource) {
    return $resource('api/confirmations/:confirmationId', {
      confirmationId: '@_id'
    }, {
      update: {
        method: 'PUT'
      },
      search: {
        url: '/api/confirmations/search',
        method: 'POST',
        isArray: true
      }
    });
  }
})();


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>org.llh</groupId>
	<artifactId>shuqian</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>shuqian Maven Webapp</name>
	<url>http://maven.apache.org</url>
	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.10</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>4.1.2.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>4.1.2.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>3.0-alpha-1</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>
		<dependency>
			<groupId>taglibs</groupId>
			<artifactId>standard</artifactId>
			<version>1.1.2</version>
		</dependency>
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid</artifactId>
			<version>1.0.14</version>
		</dependency>
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>3.2.8</version>
		</dependency>
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis-spring</artifactId>
			<version>1.1.0</version>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.10</version>
		</dependency>
		<dependency>
			<groupId>c3p0</groupId>
			<artifactId>c3p0</artifactId>
			<version>0.9.1.2</version>
		</dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>apache-log4j-extras</artifactId>
			<version>1.2.17</version>
		</dependency>
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjrt</artifactId>
			<version>1.8.0</version>
		</dependency>
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjweaver</artifactId>
			<version>1.8.0</version>
		</dependency>
	</dependencies>
	<build>
		<finalName>shuqian</finalName>
	    <plugins>
	      <plugin>
	        <groupId>org.apache.maven.plugins</groupId>
	        <artifactId>maven-compiler-plugin</artifactId>
	        <version>3.2</version>
	        <configuration>
	          <source>1.8</source>
	          <target>1.8</target>
	        </configuration>
	      </plugin>
	    </plugins>
	</build>
</project>


text:
/* eslint-env node */
const chai = require('chai');
const expect = chai.expect;
const sinon = require('sinon');
const sinonChai = require('sinon-chai');
chai.use(sinonChai);

describe('Safari shim', () => {
  const shim = require('../../src/js/safari/safari_shim');

  beforeEach(() => {
    global.window = global;
    global.RTCPeerConnection = function() {};
  });

  describe('shimCallbacksAPI', () => {
    it('shimCallbacksAPI existence', () => {
      shim.shimCallbacksAPI();
      var prototype = window.RTCPeerConnection.prototype;
      expect(prototype.createOffer.length).to.equal(2);
      expect(prototype.createAnswer.length).to.equal(2);
      expect(prototype.setLocalDescription.length).to.equal(3);
      expect(prototype.setRemoteDescription.length).to.equal(3);
      expect(prototype.addIceCandidate.length).to.equal(3);
    });
  });

  ['createOffer', 'createAnswer'].forEach((method) => {
    describe('legacy ' + method + ' shim', () => {
      describe('options passing with', () => {
        let stub;
        beforeEach(() => {
          stub = sinon.stub();
          window.RTCPeerConnection.prototype[method] = stub;
          shim.shimCallbacksAPI();
        });

        it('no arguments', () => {
          var pc = new RTCPeerConnection();
          pc[method]();
          expect(stub).to.have.been.calledWith(undefined);
        });

        it('two callbacks', () => {
          var pc = new RTCPeerConnection();
          pc[method](null, null);
          expect(stub).to.have.been.calledWith(undefined);
        });

        it('a non-function first argument', () => {
          var pc = new RTCPeerConnection();
          pc[method](1);
          expect(stub).to.have.been.calledWith(1);
        });

        it('two callbacks and options', () => {
          var pc = new RTCPeerConnection();
          pc[method](null, null, 1);
          expect(stub).to.have.been.calledWith(1);
        });

        it('two callbacks and two additional arguments', () => {
          var pc = new RTCPeerConnection();
          pc[method](null, null, 1, 2);
          expect(stub).to.have.been.calledWith(1);
        });
      });
    });
  });

  describe('shimAddStream', () => {
    it('shimAddStream existence', () => {
      shim.shimAddStream();
      var prototype = window.RTCPeerConnection.prototype;
      expect(prototype.addStream.length).to.equal(1);
    });
  });
});


text:
bool is_power_of_two(int x) {
  return (x > 0) && !(x & (x-1));
}

double* region_pointer
(const PhysicalRegion &region, int rlo, int rhi, int clo, int chi) {
  Rect<2> bounds, subrect;
  bounds.lo.x[0] = rlo;
  bounds.hi.x[0] = rhi-1;
  bounds.lo.x[1] = clo;
  bounds.hi.x[1] = chi-1;
  ByteOffset offsets[2];
  //double *base = region.get_field_accessor(FIELDID_V).template typeify<double>().template raw_rect_ptr<2>(bounds, subrect, offsets);
  double *base = region.get_field_accessor(FIELDID_V).typeify<double>().raw_rect_ptr<2>(bounds, subrect, offsets);
  assert(subrect == bounds);
  assert(offsets[0].offset == sizeof(double));
  assert(size_t(rhi-rlo) == offsets[1].offset/sizeof(double));
#ifdef DEBUG_POINTERS
  printf("ptr = %p (%d, %d)\n", base, offsets[0].offset, offsets[1].offset);
#endif
  return base;
}

PtrMatrix get_raw_pointer
(const PhysicalRegion &region, int rlo, int rhi, int clo, int chi,
 bool wait) {
  Rect<2> bounds, subrect;
  bounds.lo.x[0] = rlo;
  bounds.hi.x[0] = rhi-1;
  bounds.lo.x[1] = clo;
  bounds.hi.x[1] = chi-1;
  ByteOffset offsets[2];
  //double *base = region.get_field_accessor(FIELDID_V).template typeify<double>().template raw_rect_ptr<2>(bounds, subrect, offsets);
  double *base = region.get_field_accessor(FIELDID_V).typeify<double>().raw_rect_ptr<2>(bounds, subrect, offsets);
#if 0
  printf("ptr = %p (%d, %d)\n", base, offsets[0].offset, offsets[1].offset);
#endif

#if 0
  if (wait) {
    double *base = region.get_field_accessor(FIELDID_V).typeify<double>().raw_rect_ptr<2>(bounds, subrect, offsets);
  }
#endif

  assert(base);
  assert(subrect == bounds);
  assert(offsets[0].offset == sizeof(double));
  int ld = offsets[1].offset/sizeof(double);
  assert(ld>=rhi-rlo);
  return PtrMatrix(rhi-rlo, chi-clo, ld, base);
}

PtrMatrix reduction_pointer
(const PhysicalRegion &region, int rlo, int rhi, int clo, int chi) {
  Rect<2> bounds, subrect;
  bounds.lo.x[0] = rlo;
  bounds.hi.x[0] = rhi-1;
  bounds.lo.x[1] = clo;
  bounds.hi.x[1] = chi-1;
  ByteOffset offsets[2];
  //double *base = region.get_accessor().template typeify<double>().template raw_rect_ptr<2>(bounds, subrect, offsets);
  double *base = region.get_accessor().typeify<double>().raw_rect_ptr<2>(bounds, subrect, offsets);
  assert(subrect == bounds);
  assert(offsets[0].offset == sizeof(double));
  //assert(size_t(rhi-rlo) == offsets[1].offset/sizeof(double));
#ifdef DEBUG_POINTERS
  printf("ptr = %p (%d, %d)\n", base, offsets[0].offset, offsets[1].offset);
#endif
  int ld = offsets[1].offset/sizeof(double);
  return PtrMatrix(rhi-rlo, chi-clo, ld, base);
}


text:
import unittest

from katas.beta.multiples_2 import multiples

class MultiplesTestCase(unittest.TestCase):
    def test_equals(self):
        self.assertEqual(multiples(49), 'Fizz')

    def test_equals_2(self):
        self.assertEqual(multiples(147), 'Fang')

    def test_equals_3(self):
        self.assertEqual(multiples(30), 'Foo')

    def test_equals_4(self):
        self.assertEqual(multiples(51), 'Far')


text:
'use strict';

import {resolve} from 'path';

test('returns the resolve path for a relative path', () => {
  expect(require.resolve.paths('./mod.js')).toEqual([resolve(__dirname)]);
});

test('returns the resolve paths for a node_module', () => {
  expect(require.resolve.paths('mod').slice(0, 2)).toEqual([
    resolve(__dirname, 'node_modules'),
    resolve(__dirname, '..', 'node_modules'),
  ]);
});

test('returns null for a native node module', () => {
  expect(require.resolve.paths('fs')).toBeNull();
});


text:
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Y on Il y a du thé renversé au bord de la table !</title>
    <link>https://yoric.github.io/categories/y/index.xml</link>
    <description>Recent content in Y on Il y a du thé renversé au bord de la table !</description>
    <generator>Hugo -- gohugo.io</generator>
    <language>en-us</language>
    <atom:link href="https://yoric.github.io/categories/y/index.xml" rel="self" type="application/rss+xml" />

    <item>
      <title></title>
      <link>https://yoric.github.io/tags/</link>
      <pubDate>Sat, 18 Feb 2017 11:27:12 +0100</pubDate>

      <guid>https://yoric.github.io/tags/</guid>
      <description></description>
    </item>

    <item>
      <title></title>
      <link>https://yoric.github.io/about/</link>
      <pubDate>Sat, 18 Feb 2017 11:27:08 +0100</pubDate>

      <guid>https://yoric.github.io/about/</guid>
      <description></description>
    </item>

  </channel>
</rss>


text:
package ru.pavlenov.bio.chapter.stepic;

import ru.pavlenov.bio.utils.Dump;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.Charset;

/**
 * Какой сам ☭
 * User: Павленов Семён
 * Date: 07.01.14 17:39
 */
public class C287_1 {

    public static BufferedWriter out;

    static {
        try {
            out = new BufferedWriter(new FileWriter("/home/laser13/IdeaProjects/bio/genome/answer_287_1.txt"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void start() throws IOException {

        String data = ru.pavlenov.bio.utils.File.readFile("/home/laser13/IdeaProjects/bio/genome/dataset_88_1.txt", Charset.defaultCharset());
//        data = data.substring(1, data.length()-1);
        String[] dataArr = data.split(" ");

        Integer[] p = new Integer[dataArr.length];

        for (int i = 0; i < dataArr.length; i++) {
            p[i] = Integer.valueOf(dataArr[i]);
        }

        int b = 0;
        for (int i = 0; i < p.length; i++) {

            int prev;
            if (i == 0) prev = 0;
            else prev = p[i-1];

            if (prev + 1 != p[i]) b++;

        }

        Dump.println(b);
        Dump.println("-----");

    }

}


text:
"""Tests for common notifications."""

import copy

import mock
from oslo.config import cfg

from nova.compute import flavors
from nova.compute import task_states
from nova.compute import vm_states
from nova import context
from nova import db
from nova.network import api as network_api
from nova import notifications
from nova import test
from nova.tests import fake_network
from nova.tests import fake_notifier

CONF = cfg.CONF
CONF.import_opt('compute_driver', 'nova.virt.driver')

class NotificationsTestCase(test.TestCase):

    def setUp(self):
        super(NotificationsTestCase, self).setUp()

        self.net_info = fake_network.fake_get_instance_nw_info(self.stubs, 1,
                                                               1)

        def fake_get_nw_info(cls, ctxt, instance):
            self.assertTrue(ctxt.is_admin)
            return self.net_info

        self.stubs.Set(network_api.API, 'get_instance_nw_info',
                fake_get_nw_info)
        fake_network.set_stub_network_methods(self.stubs)

        fake_notifier.stub_notifier(self.stubs)
        self.addCleanup(fake_notifier.reset)

        self.flags(compute_driver='nova.virt.fake.FakeDriver',
                   network_manager='nova.network.manager.FlatManager',
                   notify_on_state_change="vm_and_task_state",
                   host='testhost')

        self.user_id = 'fake'
        self.project_id = 'fake'
        self.context = context.RequestContext(self.user_id, self.project_id)

        self.instance = self._wrapped_create()

    def _wrapped_create(self, params=None):
        instance_type = flavors.get_flavor_by_name('m1.tiny')
        sys_meta = flavors.save_flavor_info({}, instance_type)
        inst = {}
        inst['image_ref'] = 1
        inst['user_id'] = self.user_id
        inst['project_id'] = self.project_id
        inst['instance_type_id'] = instance_type['id']
        inst['root_gb'] = 0
        inst['ephemeral_gb'] = 0
        inst['access_ip_v4'] = '1.2.3.4'
        inst['access_ip_v6'] = 'feed:5eed'
        inst['display_name'] = 'test_instance'
        inst['hostname'] = 'test_instance_hostname'
        inst['node'] = 'test_instance_node'
        inst['system_metadata'] = sys_meta
        if params:
            inst.update(params)
        return db.instance_create(self.context, inst)

    def test_send_api_fault_disabled(self):
        self.flags(notify_api_faults=False)
        notifications.send_api_fault("http://example.com/foo", 500, None)
        self.assertEqual(0, len(fake_notifier.NOTIFICATIONS))

    def test_send_api_fault(self):
        self.flags(notify_api_faults=True)
        exception = None
        try:
            # Get a real exception with a call stack.
            raise test.TestingException("junk")
        except test.TestingException as e:
            exception = e

        notifications.send_api_fault("http://example.com/foo", 500, exception)

        self.assertEqual(1, len(fake_notifier.NOTIFICATIONS))
        n = fake_notifier.NOTIFICATIONS[0]
        self.assertEqual(n.priority, 'ERROR')
        self.assertEqual(n.event_type, 'api.fault')
        self.assertEqual(n.payload['url'], 'http://example.com/foo')
        self.assertEqual(n.payload['status'], 500)
        self.assertIsNotNone(n.payload['exception'])

    def test_notif_disabled(self):

        # test config disable of the notifications
        self.flags(notify_on_state_change=None)

        old = copy.copy(self.instance)
        self.instance["vm_state"] = vm_states.ACTIVE

        old_vm_state = old['vm_state']
        new_vm_state = self.instance["vm_state"]
        old_task_state = old['task_state']
        new_task_state = self.instance["task_state"]

        notifications.send_update_with_states(self.context, self.instance,
                old_vm_state, new_vm_state, old_task_state, new_task_state,
                verify_states=True)

        notifications.send_update(self.context, old, self.instance)
        self.assertEqual(0, len(fake_notifier.NOTIFICATIONS))

    def test_task_notif(self):

        # test config disable of just the task state notifications
        self.flags(notify_on_state_change="vm_state")

        # we should not get a notification on task stgate chagne now
        old = copy.copy(self.instance)
        self.instance["task_state"] = task_states.SPAWNING

        old_vm_state = old['vm_state']
        new_vm_state = self.instance["vm_state"]
        old_task_state = old['task_state']
        new_task_state = self.instance["task_state"]

        notifications.send_update_with_states(self.context, self.instance,
                old_vm_state, new_vm_state, old_task_state, new_task_state,
                verify_states=True)

        self.assertEqual(0, len(fake_notifier.NOTIFICATIONS))

        # ok now enable task state notifications and re-try
        self.flags(notify_on_state_change="vm_and_task_state")

        notifications.send_update(self.context, old, self.instance)
        self.assertEqual(1, len(fake_notifier.NOTIFICATIONS))

    def test_send_no_notif(self):

        # test notification on send no initial vm state:
        old_vm_state = self.instance['vm_state']
        new_vm_state = self.instance['vm_state']
        old_task_state = self.instance['task_state']
        new_task_state = self.instance['task_state']

        notifications.send_update_with_states(self.context, self.instance,
                old_vm_state, new_vm_state, old_task_state, new_task_state,
                service="compute", host=None, verify_states=True)

        self.assertEqual(0, len(fake_notifier.NOTIFICATIONS))

    def test_send_on_vm_change(self):

        # pretend we just transitioned to ACTIVE:
        params = {"vm_state": vm_states.ACTIVE}
        (old_ref, new_ref) = db.instance_update_and_get_original(self.context,
                self.instance['uuid'], params)
        notifications.send_update(self.context, old_ref, new_ref)

        self.assertEqual(1, len(fake_notifier.NOTIFICATIONS))

    def test_send_on_task_change(self):

        # pretend we just transitioned to task SPAWNING:
        params = {"task_state": task_states.SPAWNING}
        (old_ref, new_ref) = db.instance_update_and_get_original(self.context,
                self.instance['uuid'], params)
        notifications.send_update(self.context, old_ref, new_ref)

        self.assertEqual(1, len(fake_notifier.NOTIFICATIONS))

    def test_no_update_with_states(self):

        notifications.send_update_with_states(self.context, self.instance,
                vm_states.BUILDING, vm_states.BUILDING, task_states.SPAWNING,
                task_states.SPAWNING, verify_states=True)
        self.assertEqual(0, len(fake_notifier.NOTIFICATIONS))

    def test_vm_update_with_states(self):

        notifications.send_update_with_states(self.context, self.instance,
                vm_states.BUILDING, vm_states.ACTIVE, task_states.SPAWNING,
                task_states.SPAWNING, verify_states=True)
        self.assertEqual(1, len(fake_notifier.NOTIFICATIONS))
        notif = fake_notifier.NOTIFICATIONS[0]
        payload = notif.payload
        access_ip_v4 = self.instance["access_ip_v4"]
        access_ip_v6 = self.instance["access_ip_v6"]
        display_name = self.instance["display_name"]
        hostname = self.instance["hostname"]
        node = self.instance["node"]

        self.assertEqual(vm_states.BUILDING, payload["old_state"])
        self.assertEqual(vm_states.ACTIVE, payload["state"])
        self.assertEqual(task_states.SPAWNING, payload["old_task_state"])
        self.assertEqual(task_states.SPAWNING, payload["new_task_state"])
        self.assertEqual(payload["access_ip_v4"], access_ip_v4)
        self.assertEqual(payload["access_ip_v6"], access_ip_v6)
        self.assertEqual(payload["display_name"], display_name)
        self.assertEqual(payload["hostname"], hostname)
        self.assertEqual(payload["node"], node)

    def test_task_update_with_states(self):
        self.flags(notify_on_state_change="vm_and_task_state")

        notifications.send_update_with_states(self.context, self.instance,
                vm_states.BUILDING, vm_states.BUILDING, task_states.SPAWNING,
                None, verify_states=True)
        self.assertEqual(1, len(fake_notifier.NOTIFICATIONS))
        notif = fake_notifier.NOTIFICATIONS[0]
        payload = notif.payload
        access_ip_v4 = self.instance["access_ip_v4"]
        access_ip_v6 = self.instance["access_ip_v6"]
        display_name = self.instance["display_name"]
        hostname = self.instance["hostname"]

        self.assertEqual(vm_states.BUILDING, payload["old_state"])
        self.assertEqual(vm_states.BUILDING, payload["state"])
        self.assertEqual(task_states.SPAWNING, payload["old_task_state"])
        self.assertIsNone(payload["new_task_state"])
        self.assertEqual(payload["access_ip_v4"], access_ip_v4)
        self.assertEqual(payload["access_ip_v6"], access_ip_v6)
        self.assertEqual(payload["display_name"], display_name)
        self.assertEqual(payload["hostname"], hostname)

    def test_update_no_service_name(self):
        notifications.send_update_with_states(self.context, self.instance,
                vm_states.BUILDING, vm_states.BUILDING, task_states.SPAWNING,
                None)
        self.assertEqual(1, len(fake_notifier.NOTIFICATIONS))

        # service name should default to 'compute'
        notif = fake_notifier.NOTIFICATIONS[0]
        self.assertEqual('compute.testhost', notif.publisher_id)

    def test_update_with_service_name(self):
        notifications.send_update_with_states(self.context, self.instance,
                vm_states.BUILDING, vm_states.BUILDING, task_states.SPAWNING,
                None, service="testservice")
        self.assertEqual(1, len(fake_notifier.NOTIFICATIONS))

        # service name should default to 'compute'
        notif = fake_notifier.NOTIFICATIONS[0]
        self.assertEqual('testservice.testhost', notif.publisher_id)

    def test_update_with_host_name(self):
        notifications.send_update_with_states(self.context, self.instance,
                vm_states.BUILDING, vm_states.BUILDING, task_states.SPAWNING,
                None, host="someotherhost")
        self.assertEqual(1, len(fake_notifier.NOTIFICATIONS))

        # service name should default to 'compute'
        notif = fake_notifier.NOTIFICATIONS[0]
        self.assertEqual('compute.someotherhost', notif.publisher_id)

    def test_payload_has_fixed_ip_labels(self):
        info = notifications.info_from_instance(self.context, self.instance,
                                                  self.net_info, None)
        self.assertIn("fixed_ips", info)
        self.assertEqual(info["fixed_ips"][0]["label"], "test1")

    def test_payload_has_vif_mac_address(self):
        info = notifications.info_from_instance(self.context, self.instance,
                                                  self.net_info, None)
        self.assertIn("fixed_ips", info)
        self.assertEqual(self.net_info[0]['address'],
                         info["fixed_ips"][0]["vif_mac"])

    def test_payload_has_cell_name_empty(self):
        info = notifications.info_from_instance(self.context, self.instance,
                                                  self.net_info, None)
        self.assertIn("cell_name", info)
        self.assertIsNone(self.instance['cell_name'])
        self.assertEqual("", info["cell_name"])

    def test_payload_has_cell_name(self):
        self.instance['cell_name'] = "cell1"
        info = notifications.info_from_instance(self.context, self.instance,
                                                  self.net_info, None)
        self.assertIn("cell_name", info)
        self.assertEqual("cell1", info["cell_name"])

    def test_payload_has_progress_empty(self):
        info = notifications.info_from_instance(self.context, self.instance,
                                                  self.net_info, None)
        self.assertIn("progress", info)
        self.assertIsNone(self.instance['progress'])
        self.assertEqual("", info["progress"])

    def test_payload_has_progress(self):
        self.instance['progress'] = 50
        info = notifications.info_from_instance(self.context, self.instance,
                                                  self.net_info, None)
        self.assertIn("progress", info)
        self.assertEqual(50, info["progress"])

    def test_send_access_ip_update(self):
        notifications.send_update(self.context, self.instance, self.instance)
        self.assertEqual(1, len(fake_notifier.NOTIFICATIONS))
        notif = fake_notifier.NOTIFICATIONS[0]
        payload = notif.payload
        access_ip_v4 = self.instance["access_ip_v4"]
        access_ip_v6 = self.instance["access_ip_v6"]

        self.assertEqual(payload["access_ip_v4"], access_ip_v4)
        self.assertEqual(payload["access_ip_v6"], access_ip_v6)

    def test_send_name_update(self):
        param = {"display_name": "new_display_name"}
        new_name_inst = self._wrapped_create(params=param)
        notifications.send_update(self.context, self.instance, new_name_inst)
        self.assertEqual(1, len(fake_notifier.NOTIFICATIONS))
        notif = fake_notifier.NOTIFICATIONS[0]
        payload = notif.payload
        old_display_name = self.instance["display_name"]
        new_display_name = new_name_inst["display_name"]

        self.assertEqual(payload["old_display_name"], old_display_name)
        self.assertEqual(payload["display_name"], new_display_name)

    def test_send_no_state_change(self):
        called = [False]

        def sending_no_state_change(context, instance, **kwargs):
            called[0] = True
        self.stubs.Set(notifications, '_send_instance_update_notification',
                       sending_no_state_change)
        notifications.send_update(self.context, self.instance, self.instance)
        self.assertTrue(called[0])

    def test_fail_sending_update(self):
        def fail_sending(context, instance, **kwargs):
            raise Exception('failed to notify')
        self.stubs.Set(notifications, '_send_instance_update_notification',
                       fail_sending)

        notifications.send_update(self.context, self.instance, self.instance)
        self.assertEqual(0, len(fake_notifier.NOTIFICATIONS))

class NotificationsFormatTestCase(test.NoDBTestCase):

    def test_state_computation(self):
        instance = {'vm_state': mock.sentinel.vm_state,
                    'task_state': mock.sentinel.task_state}
        states = notifications._compute_states_payload(instance)
        self.assertEqual(mock.sentinel.vm_state, states['state'])
        self.assertEqual(mock.sentinel.vm_state, states['old_state'])
        self.assertEqual(mock.sentinel.task_state, states['old_task_state'])
        self.assertEqual(mock.sentinel.task_state, states['new_task_state'])

        states = notifications._compute_states_payload(
            instance,
            old_vm_state=mock.sentinel.old_vm_state,
        )
        self.assertEqual(mock.sentinel.vm_state, states['state'])
        self.assertEqual(mock.sentinel.old_vm_state, states['old_state'])
        self.assertEqual(mock.sentinel.task_state, states['old_task_state'])
        self.assertEqual(mock.sentinel.task_state, states['new_task_state'])

        states = notifications._compute_states_payload(
            instance,
            old_vm_state=mock.sentinel.old_vm_state,
            old_task_state=mock.sentinel.old_task_state,
            new_vm_state=mock.sentinel.new_vm_state,
            new_task_state=mock.sentinel.new_task_state,
        )

        self.assertEqual(mock.sentinel.new_vm_state, states['state'])
        self.assertEqual(mock.sentinel.old_vm_state, states['old_state'])
        self.assertEqual(mock.sentinel.old_task_state,
                         states['old_task_state'])
        self.assertEqual(mock.sentinel.new_task_state,
                         states['new_task_state'])


text:
<?php

namespace Acme\BlogBundle\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * Description of CommentRepository
 *
 * @author Admin
 */
class CommentRepository extends EntityRepository
{
    public function fetchAll()
    {
        return $this->getEntityManager()->getRepository('AcmeBlogBundle:Comment')
            ->findBy(
                array(),
                array('id' => 'DESC')
            );
    }

    /**
    public function fetchCommentsByArticleId()
    {
        return $this->getEntityManager()->createQuery('

        ');
    }
    */

}


text:
enum GuizmoOperation
{
	TRANSLATE,
	ROTATION,
	SCALE
};

class ComponentTransform : public Component
{
public:
	ComponentTransform(ComponentType type, GameObject* game_object, math::float4x4** global_matrix);
	~ComponentTransform();

	void Update();

	void OnInspector(bool debug);

	void SetPosition(const math::float3& pos);
	void SetRotation(const math::float3 &rot_euler);
	void SetRotation(const math::Quat& rot);
	void SetScale(const math::float3& scale);
	void Set(math::float4x4 matrix);
	void SetGlobal(float4x4 global);

	math::float3 GetPosition()const;
	math::float3 GetRotationEuler()const;
	math::Quat GetRotation()const;
	math::float3 GetScale()const;

	void Rotate(const math::Quat& quaternion);

	math::float4x4 GetLocalTransformMatrix()const;
	// Returns the final transformation matrix. Not the local one!
	math::float4x4 GetTransformMatrix()const;
	math::float4x4 GetGlobalMatrix()const;

	math::float3 GetForward() const;

	void Save(Data& file)const;
	void Load(Data& conf);
	void Reset();
	void Remove();
	void SaveAsPrefab(Data& file)const;

	void UpdateMatrix();
private:
	void CalculateFinalTransform();

private:
	math::float3 position = math::float3::zero;
	math::Quat rotation = math::Quat::identity;
	math::float3 scale = math::float3::one;

	math::float3 rotation_euler = math::float3::zero;

	math::float4x4 transform_matrix = math::float4x4::identity;
	math::float4x4 final_transform_matrix = math::float4x4::identity;

	bool transform_modified = false;
};

#endif // !__COMPONENT_TRANSFORM_H__


text:
package plugin

import (
	"fmt"

	"code.cloudfoundry.org/cli/integration/helpers/servicebrokerstub"

	"code.cloudfoundry.org/cli/integration/helpers"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	. "github.com/onsi/gomega/gbytes"
	. "github.com/onsi/gomega/gexec"
)

var _ = Describe("plugin API", func() {
	BeforeEach(func() {
		installTestPlugin()
	})

	AfterEach(func() {
		uninstallTestPlugin()
	})

	Describe("AccessToken", func() {
		It("returns the access token", func() {
			confirmTestPluginOutput("AccessToken", `bearer [\w\d\.]+`)
		})
	})

	Describe("ApiEndpoint", func() {
		It("returns the API endpoint", func() {
			confirmTestPluginOutput("ApiEndpoint", apiURL)
		})
	})

	Describe("ApiVersion", func() {
		It("returns the API version", func() {
			confirmTestPluginOutput("ApiVersion", `[23]\.\d+\.\d+`)
		})
	})

	Describe("CliCommand", func() {
		It("calls the core cli command and outputs to terminal", func() {
			confirmTestPluginOutput("CliCommand", "API endpoint", "API endpoint")
		})
	})

	Describe("CliCommandWithoutTerminalOutput", func() {
		It("calls the core cli command and without outputting to the terminal", func() {
			session := helpers.CF("CliCommandWithoutTerminalOutput", "target")
			Eventually(session).Should(Say("API endpoint"))
			Consistently(session).ShouldNot(Say("API endpoint"))
			Eventually(session).Should(Exit(0))
		})
	})

	Describe("DopplerEndpoint", func() {
		It("gets Doppler Endpoint", func() {
			confirmTestPluginOutput("DopplerEndpoint", "wss://doppler")
		})
	})

	Describe("GetApp", func() {
		var appName string
		BeforeEach(func() {
			createTargetedOrgAndSpace()
			appName = helpers.PrefixedRandomName("APP")
			helpers.WithHelloWorldApp(func(appDir string) {
				Eventually(helpers.CF("push", appName, "--no-start", "-p", appDir, "-b", "staticfile_buildpack", "--no-route")).Should(Exit(0))
			})
		})

		It("gets application information", func() {
			confirmTestPluginOutputWithArg("GetApp", appName, appName)
		})
	})

	Describe("GetApps", func() {
		var appName1, appName2 string
		BeforeEach(func() {
			createTargetedOrgAndSpace()
			appName1 = helpers.PrefixedRandomName("APP")
			helpers.WithHelloWorldApp(func(appDir string) {
				Eventually(helpers.CF("push", appName1, "--no-start", "-p", appDir, "-b", "staticfile_buildpack", "--no-route")).Should(Exit(0))
			})
			appName2 = helpers.PrefixedRandomName("APP")
			helpers.WithHelloWorldApp(func(appDir string) {
				Eventually(helpers.CF("push", appName2, "--no-start", "-p", appDir, "-b", "staticfile_buildpack", "--no-route")).Should(Exit(0))
			})
		})

		It("gets information for multiple applications", func() {
			appNameRegexp := fmt.Sprintf("(?:%s|%s)", appName1, appName2)
			confirmTestPluginOutput("GetApps", appNameRegexp, appNameRegexp)
		})
	})

	Describe("GetCurrentOrg", func() {
		It("gets the current targeted org", func() {
			org, _ := createTargetedOrgAndSpace()
			confirmTestPluginOutput("GetCurrentOrg", org)
		})
	})

	Describe("GetCurrentSpace", func() {
		It("gets the current targeted Space", func() {
			_, space := createTargetedOrgAndSpace()
			confirmTestPluginOutput("GetCurrentSpace", space)
		})
	})

	Describe("GetOrg", func() {
		It("gets the given org", func() {
			org, _ := createTargetedOrgAndSpace()
			confirmTestPluginOutputWithArg("GetOrg", org, org)
		})
	})

	Describe("GetOrgs", func() {
		It("gets information for multiple orgs", func() {
			org1, _ := createTargetedOrgAndSpace()
			org2, _ := createTargetedOrgAndSpace()
			orgNameRegexp := fmt.Sprintf("(?:%s|%s)", org1, org2)
			confirmTestPluginOutput("GetOrgs", orgNameRegexp, orgNameRegexp)
		})
	})

	Describe("GetOrgUsers", func() {
		It("returns the org users", func() {
			org, _ := createTargetedOrgAndSpace()
			username, _ := helpers.GetCredentials()
			confirmTestPluginOutputWithArg("GetOrgUsers", org, username)
		})
	})

	Describe("GetOrgUsers", func() {
		It("returns the org users", func() {
			org, _ := createTargetedOrgAndSpace()
			username, _ := helpers.GetCredentials()
			confirmTestPluginOutputWithArg("GetOrgUsers", org, username)
		})
	})

	Describe("GetService and GetServices", func() {
		var (
			serviceInstance1 string
			serviceInstance2 string
			broker           *servicebrokerstub.ServiceBrokerStub
		)
		BeforeEach(func() {
			createTargetedOrgAndSpace()
			serviceInstance1 = helpers.PrefixedRandomName("SI1")
			serviceInstance2 = helpers.PrefixedRandomName("SI2")

			broker = servicebrokerstub.EnableServiceAccess()

			Eventually(helpers.CF("create-service", broker.FirstServiceOfferingName(), broker.FirstServicePlanName(), serviceInstance1)).Should(Exit(0))
			Eventually(helpers.CF("create-service", broker.FirstServiceOfferingName(), broker.FirstServicePlanName(), serviceInstance2)).Should(Exit(0))
		})

		AfterEach(func() {
			broker.Forget()
		})

		It("GetService gets the given service instance and GetServices returns a list of services instances", func() {
			confirmTestPluginOutputWithArg("GetService", serviceInstance1, serviceInstance1)

			servicesNameRegexp := fmt.Sprintf("(?:%s|%s)", serviceInstance1, serviceInstance2)
			confirmTestPluginOutput("GetServices", servicesNameRegexp, servicesNameRegexp)
		})
	})

	Describe("GetSpace", func() {
		It("gets the given space", func() {
			_, space := createTargetedOrgAndSpace()
			confirmTestPluginOutputWithArg("GetSpace", space, space)
		})
	})

	Describe("GetSpaces", func() {
		var space1, space2 string

		BeforeEach(func() {
			_, space1 = createTargetedOrgAndSpace()
			space2 = helpers.NewSpaceName()
			helpers.CreateSpace(space2)
		})

		It("gets information for multiple spaces", func() {
			spaceNameRegexp := fmt.Sprintf("(?:%s|%s)", space1, space2)
			confirmTestPluginOutput("GetSpaces", spaceNameRegexp, spaceNameRegexp)
		})
	})

	Describe("GetSpaceUsers", func() {
		It("returns the space users", func() {
			username, _ := helpers.GetCredentials()
			org, space := createTargetedOrgAndSpace()
			session := helpers.CF("GetSpaceUsers", org, space)
			Eventually(session).Should(Say(username))
			Eventually(session).Should(Exit(0))
		})
	})

	Describe("HasAPIEndpoint", func() {
		It("returns true", func() {
			confirmTestPluginOutput("HasAPIEndpoint", "true")
		})
	})

	Describe("HasOrganization", func() {
		It("returns true", func() {
			createTargetedOrgAndSpace()
			confirmTestPluginOutput("HasOrganization", "true")
		})
	})

	Describe("HasSpace", func() {
		It("returns true", func() {
			createTargetedOrgAndSpace()
			confirmTestPluginOutput("HasSpace", "true")
		})
	})

	Describe("IsLoggedIn", func() {
		It("returns a true", func() {
			confirmTestPluginOutput("IsLoggedIn", "true")
		})
	})

	Describe("IsSSLDisabled", func() {
		It("returns a true or false", func() {
			if skipSSLValidation {
				confirmTestPluginOutput("IsSSLDisabled", "true")
			} else {
				confirmTestPluginOutput("IsSSLDisabled", "false")
			}
		})
	})

	Describe("LoggregatorEndpoint", func() {
		It("gets Loggregator Endpoint", func() {
			confirmTestPluginOutput("LoggregatorEndpoint", "")
		})
	})

	Describe("UserEmail", func() {
		It("gets the current user's Email", func() {
			helpers.SkipIfClientCredentialsTestMode()
			username, _ := helpers.GetCredentials()
			confirmTestPluginOutput("UserEmail", username)
		})
	})

	Describe("UserGuid", func() {
		It("gets the current user's GUID", func() {
			helpers.SkipIfClientCredentialsTestMode()
			confirmTestPluginOutput("UserGuid", `[\w\d]+-[\w\d]+-[\w\d]+-[\w\d]+-[\w\d]+`)
		})
	})

	Describe("Username", func() {
		It("gets the current username", func() {
			username, _ := helpers.GetCredentials()
			confirmTestPluginOutput("Username", username)
		})
	})
})


text:
<?php

namespace PHPCD\Element\FunctionInfo;

use PHPCD\View\FunctionVisitor;

interface FunctionInfo
{
    public function getName();

    public function getNamespaceName();

    public function getDocComment();

    public function getParameters();

    public function getFileName();

    public function getStartLine();

    /**
     * @return array
     */
    public function getNonTrivialTypes();

    public function accept(FunctionVisitor $visitor);
}


text:
using System;
using System.Diagnostics.CodeAnalysis;
using Rainbow.Model;
// ReSharper disable VirtualMemberCallInConstructor

namespace Rainbow.Tests
{
	[ExcludeFromCodeCoverage]
	public class FakeFieldValue : ProxyFieldValue
	{
		public FakeFieldValue(string value, string fieldType = "Test", Guid fieldId = new Guid(), string nameHint = "Fake test field", Guid? blobId = null) : base(fieldId, value)
		{
			FieldType = fieldType;
			NameHint = nameHint;
			BlobId = blobId;
		}
	}
}


text:
This is something I haven't done yet, so I'm looking for community input on what works well. My current thought is to leverage existing tools such as [js-imagediff](http://humblesoftware.github.io/js-imagediff/).

### What is working well for you?

*[pull request welcome!](../#contributing-test-patterns)*


text:
import {join} from 'path';
import {getGlobalVariable} from '../../utils/env';
import {expectFileToExist} from '../../utils/fs';
import {ng, npm} from '../../utils/process';

export default function() {
  // Skip this in ejected tests.
  if (getGlobalVariable('argv').eject) {
    return Promise.resolve();
  }

  // Can't use the `ng` helper because somewhere the environment gets
  // stuck to the first build done
  return npm('install', '@angular/service-worker')
    .then(() => ng('set', 'apps.0.serviceWorker=true'))
    .then(() => ng('build', '--prod'))
    .then(() => expectFileToExist(join(process.cwd(), 'dist')))
    .then(() => expectFileToExist(join(process.cwd(), 'dist/ngsw-manifest.json')));
}


text:
using namespace qglviewer;

#include "mybitarray.h"

class VolumeOperations
{
 public :
  static void setVolData(uchar*);
  static void setMaskData(uchar*);
  static void setGridSize(int, int, int);
  static void setClip(QList<Vec>, QList<Vec>);

  static void getVolume(Vec, Vec, int);

  static void hatchConnectedRegion(int, int, int,
				   Vec, Vec,
				   int, int,
				   int, int,
				   int&, int&,
				   int&, int&,
				   int&, int&);

  static void connectedRegion(int, int, int,
			      Vec, Vec,
			      int, int,
			      int&, int&,
			      int&, int&,
			      int&, int&);

  static void resetTag(Vec, Vec, int,
		       int&, int&,
		       int&, int&,
		       int&, int&);

  static void shrinkwrap(Vec, Vec, int,
			 bool, int,
			 bool,
			 int, int, int, int,
			 int&, int&,
			 int&, int&,
			 int&, int&);

  static void setVisible(Vec, Vec,
			 int, bool,
			 int&, int&,
			 int&, int&,
			 int&, int&);

  static void mergeTags(Vec bmin, Vec bmax,
			int tag1, int tag2, bool useTF,
			int&, int&,
			int&, int&,
			int&, int&);

  static void erodeConnected(int, int, int,
			     Vec, Vec, int,
			     int,
			     int&, int&,
			     int&, int&,
			     int&, int&);

  static void dilateConnected(int, int, int,
			      Vec, Vec, int,
			      int,
			      int&, int&,
			      int&, int&,
			      int&, int&);

  static void modifyOriginalVolume(Vec, Vec, int,
				   int&, int&,
				   int&, int&,
				   int&, int&);

 private :
  static int m_depth, m_width, m_height;
  static uchar *m_volData;
  static uchar *m_maskData;

  static QList<Vec> m_cPos;
  static QList<Vec> m_cNorm;

  static void getConnectedRegion(int, int, int,
				 int, int, int,
				 int, int, int,
				 int, bool,
				 MyBitArray&);

  static void shrinkwrapSlice(uchar*, int, int);

  static void getTransparentRegion(int, int, int,
				   int, int, int,
				   MyBitArray&);

  static void dilateBitmask(int, bool,
			    qint64, qint64, qint64,
			    MyBitArray&);
};

#endif


text:
using System.Collections.Generic;
using System.ServiceModel;

using Unity;
using Unity.Registration;

using vm.Aspects.Wcf.Services;

namespace vm.Aspects.Model.PerCallContextRepositoryCallHandlerTests
{
    public class TestServiceTasksHostFactory : MessagingPatternInitializedServiceHostFactory<ITestServiceTasks, TestServiceTasks, ServiceInitializer>
    {
        protected override IUnityContainer DoRegisterDefaults(
            IUnityContainer container,
            IDictionary<RegistrationLookup, IContainerRegistration> registrations) => base.DoRegisterDefaults(container, registrations)
                                                                                .UnsafeRegister(TestService.Registrar, registrations)
                                                                                ;

        /// <summary>
        /// Gives opportunity to the service host factory to add programmatically endpoints before configuring them all.
        /// </summary>
        /// <param name="host">The host.</param>
        /// <returns>ServiceHost.</returns>
        protected override ServiceHost AddEndpoints(
            ServiceHost host)
        {
            //host.AddServiceEndpoint(
            //        typeof(IService),
            //        new NetNamedPipeBinding(),
            //        "");

            //host.AddServiceEndpoint(
            //        typeof(IService),
            //        new WSHttpBinding(WebHttpSecurityMode.Transport),
            //        "");

            host.AddServiceEndpoint(
                    typeof(ITestServiceTasks),
                    new NetTcpBinding(),
                    "TestServiceTasks.svc");

            return host;
        }
    }
}