text:
package io.gravitee.rest.api.model.configuration.application;

import java.util.List;

public class ApplicationTypeEntity {

    private String id;
    private String name;
    private String description;
    private Boolean requires_redirect_uris;
    private List<ApplicationGrantTypeEntity> allowed_grant_types;
    private List<ApplicationGrantTypeEntity> default_grant_types;
    private List<ApplicationGrantTypeEntity> mandatory_grant_types;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public Boolean getRequires_redirect_uris() {
        return requires_redirect_uris;
    }

    public void setRequires_redirect_uris(Boolean requires_redirect_uris) {
        this.requires_redirect_uris = requires_redirect_uris;
    }

    public List<ApplicationGrantTypeEntity> getAllowed_grant_types() {
        return allowed_grant_types;
    }

    public void setAllowed_grant_types(List<ApplicationGrantTypeEntity> allowed_grant_types) {
        this.allowed_grant_types = allowed_grant_types;
    }

    public List<ApplicationGrantTypeEntity> getDefault_grant_types() {
        return default_grant_types;
    }

    public void setDefault_grant_types(List<ApplicationGrantTypeEntity> default_grant_types) {
        this.default_grant_types = default_grant_types;
    }

    public List<ApplicationGrantTypeEntity> getMandatory_grant_types() {
        return mandatory_grant_types;
    }

    public void setMandatory_grant_types(List<ApplicationGrantTypeEntity> mandatory_grant_types) {
        this.mandatory_grant_types = mandatory_grant_types;
    }
}


text:
<module  rename-to='SlideEffectsSample'>
	<inherits name='com.google.gwt.query.Query' />
	<entry-point
		class="gwtquery.samples.client.effects.SlideEffectsSample">
	</entry-point>
</module>

redpajama_set_name: RedPajamaGithub


text:
using System.ComponentModel.DataAnnotations;
using System.Data.Entity.ModelConfiguration;

namespace Cats.Models.Hubs.Mapping
{
    public class sysdiagramMap : EntityTypeConfiguration<sysdiagram>
    {
        public sysdiagramMap()
        {
            // Primary Key
            this.HasKey(t => t.diagram_id);

            // Properties
            this.Property(t => t.name)
                .IsRequired()
                .HasMaxLength(128);

            // Table & Column Mappings
            this.ToTable("sysdiagrams");
            this.Property(t => t.name).HasColumnName("name");
            this.Property(t => t.principal_id).HasColumnName("principal_id");
            this.Property(t => t.diagram_id).HasColumnName("diagram_id");
            this.Property(t => t.version).HasColumnName("version");
            this.Property(t => t.definition).HasColumnName("definition");
        }
    }
}


text:
package org.apache.hadoop.mapreduce.v2.app.local;

import java.io.IOException;
import java.util.ArrayList;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.JobCounter;
import org.apache.hadoop.mapreduce.MRJobConfig;
import org.apache.hadoop.mapreduce.v2.api.records.TaskType;
import org.apache.hadoop.mapreduce.v2.app.AppContext;
import org.apache.hadoop.mapreduce.v2.app.client.ClientService;
import org.apache.hadoop.mapreduce.v2.app.job.event.JobCounterUpdateEvent;
import org.apache.hadoop.mapreduce.v2.app.job.event.JobEvent;
import org.apache.hadoop.mapreduce.v2.app.job.event.JobEventType;
import org.apache.hadoop.mapreduce.v2.app.job.event.TaskAttemptContainerAssignedEvent;
import org.apache.hadoop.mapreduce.v2.app.rm.ContainerAllocator;
import org.apache.hadoop.mapreduce.v2.app.rm.ContainerAllocatorEvent;
import org.apache.hadoop.mapreduce.v2.app.rm.RMCommunicator;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.yarn.api.protocolrecords.AllocateRequest;
import org.apache.hadoop.yarn.api.protocolrecords.AllocateResponse;
import org.apache.hadoop.yarn.api.records.Container;
import org.apache.hadoop.yarn.api.records.ContainerId;
import org.apache.hadoop.yarn.api.records.NodeId;
import org.apache.hadoop.yarn.api.records.ResourceRequest;
import org.apache.hadoop.yarn.api.records.Token;
import org.apache.hadoop.yarn.client.ClientRMProxy;
import org.apache.hadoop.yarn.event.EventHandler;
import org.apache.hadoop.yarn.exceptions.ApplicationAttemptNotFoundException;
import org.apache.hadoop.yarn.exceptions.ApplicationMasterNotRegisteredException;
import org.apache.hadoop.yarn.exceptions.YarnRuntimeException;
import org.apache.hadoop.yarn.factories.RecordFactory;
import org.apache.hadoop.yarn.factory.providers.RecordFactoryProvider;
import org.apache.hadoop.yarn.security.AMRMTokenIdentifier;

/**
 * Allocates containers locally. Doesn't allocate a real container;
 * instead sends an allocated event for all requests.
 */
public class LocalContainerAllocator extends RMCommunicator
    implements ContainerAllocator {

  private static final Log LOG =
      LogFactory.getLog(LocalContainerAllocator.class);

  @SuppressWarnings("rawtypes")
  private final EventHandler eventHandler;
  private long retryInterval;
  private long retrystartTime;
  private String nmHost;
  private int nmPort;
  private int nmHttpPort;
  private ContainerId containerId;
  protected int lastResponseID;

  private final RecordFactory recordFactory =
      RecordFactoryProvider.getRecordFactory(null);

  public LocalContainerAllocator(ClientService clientService,
    AppContext context, String nmHost, int nmPort, int nmHttpPort
    , ContainerId cId) {
    super(clientService, context);
    this.eventHandler = context.getEventHandler();
    this.nmHost = nmHost;
    this.nmPort = nmPort;
    this.nmHttpPort = nmHttpPort;
    this.containerId = cId;
  }

  @Override
  protected void serviceInit(Configuration conf) throws Exception {
    super.serviceInit(conf);
    retryInterval =
        getConfig().getLong(MRJobConfig.MR_AM_TO_RM_WAIT_INTERVAL_MS,
            MRJobConfig.DEFAULT_MR_AM_TO_RM_WAIT_INTERVAL_MS);
    // Init startTime to current time. If all goes well, it will be reset after
    // first attempt to contact RM.
    retrystartTime = System.currentTimeMillis();
  }

  @SuppressWarnings("unchecked")
  @Override
  protected synchronized void heartbeat() throws Exception {
    AllocateRequest allocateRequest =
        AllocateRequest.newInstance(this.lastResponseID,
          super.getApplicationProgress(), new ArrayList<ResourceRequest>(),
        new ArrayList<ContainerId>(), null);
    AllocateResponse allocateResponse = null;
    try {
      allocateResponse = scheduler.allocate(allocateRequest);
      // Reset retry count if no exception occurred.
      retrystartTime = System.currentTimeMillis();
    } catch (ApplicationAttemptNotFoundException e) {
      LOG.info("Event from RM: shutting down Application Master");
      // This can happen if the RM has been restarted. If it is in that state,
      // this application must clean itself up.
      eventHandler.handle(new JobEvent(this.getJob().getID(),
        JobEventType.JOB_AM_REBOOT));
      throw new YarnRuntimeException(
        "Resource Manager doesn't recognize AttemptId: "
            + this.getContext().getApplicationID(), e);
    } catch (ApplicationMasterNotRegisteredException e) {
      LOG.info("ApplicationMaster is out of sync with ResourceManager,"
          + " hence resync and send outstanding requests.");
      this.lastResponseID = 0;
      register();
    } catch (Exception e) {
      // This can happen when the connection to the RM has gone down. Keep
      // re-trying until the retryInterval has expired.
      if (System.currentTimeMillis() - retrystartTime >= retryInterval) {
        LOG.error("Could not contact RM after " + retryInterval + " milliseconds.");
        eventHandler.handle(new JobEvent(this.getJob().getID(),
                                         JobEventType.INTERNAL_ERROR));
        throw new YarnRuntimeException("Could not contact RM after " +
                                retryInterval + " milliseconds.");
      }
      // Throw this up to the caller, which may decide to ignore it and
      // continue to attempt to contact the RM.
      throw e;
    }

    if (allocateResponse != null) {
      this.lastResponseID = allocateResponse.getResponseId();
      Token token = allocateResponse.getAMRMToken();
      if (token != null) {
        updateAMRMToken(token);
      }
    }
  }

  private void updateAMRMToken(Token token) throws IOException {
    org.apache.hadoop.security.token.Token<AMRMTokenIdentifier> amrmToken =
        new org.apache.hadoop.security.token.Token<AMRMTokenIdentifier>(token
          .getIdentifier().array(), token.getPassword().array(), new Text(
          token.getKind()), new Text(token.getService()));
    UserGroupInformation currentUGI = UserGroupInformation.getCurrentUser();
    currentUGI.addToken(amrmToken);
    amrmToken.setService(ClientRMProxy.getAMRMTokenService(getConfig()));
  }

  @SuppressWarnings("unchecked")
  @Override
  public void handle(ContainerAllocatorEvent event) {
    if (event.getType() == ContainerAllocator.EventType.CONTAINER_REQ) {
      LOG.info("Processing the event " + event.toString());
      // Assign the same container ID as the AM
      ContainerId cID =
          ContainerId.newContainerId(getContext().getApplicationAttemptId(),
            this.containerId.getContainerId());
      Container container = recordFactory.newRecordInstance(Container.class);
      container.setId(cID);
      NodeId nodeId = NodeId.newInstance(this.nmHost, this.nmPort);
      container.setNodeId(nodeId);
      container.setContainerToken(null);
      container.setNodeHttpAddress(this.nmHost + ":" + this.nmHttpPort);
      // send the container-assigned event to task attempt

      if (event.getAttemptID().getTaskId().getTaskType() == TaskType.MAP) {
        JobCounterUpdateEvent jce =
            new JobCounterUpdateEvent(event.getAttemptID().getTaskId()
                .getJobId());
        // TODO Setting OTHER_LOCAL_MAP for now.
        jce.addCounterUpdate(JobCounter.OTHER_LOCAL_MAPS, 1);
        eventHandler.handle(jce);
      }
      eventHandler.handle(new TaskAttemptContainerAssignedEvent(
          event.getAttemptID(), container, applicationACLs));
    }
  }

}


text:
<!DOCTYPE html>
<html>
<head>
    <title>History示例的JavaScript页面</title>
</head>
<body>
<script src="../../src/kernel.js"></script>
<script src="h3.js"></script>
</body>
</html>


text:
const path = require('path');
const settings = require('../../stryker.parent.conf');
const moduleName = __dirname.split(path.sep).pop();
settings.plugins = settings.plugins.map(p => path.resolve(p));
settings.mochaOptions.spec = ['dist/test/**/*.js'];
settings.dashboard.module = moduleName;
module.exports = settings;


text:
"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
// Whether we should call fused ops.
exports.shouldFuse = function (gradientDepth, activation) {
    var gradientMode = gradientDepth > 0;
    return !gradientMode || activation === 'linear';
};
//# sourceMappingURL=fused_util.js.map


text:
using LiteDB;
using MZBlog.Core.Documents;

namespace MZBlog.Core.Commands.Posts
{
    public class DeletePostCommand
    {
        public string PostId { get; set; }
    }

    public class DeletePostCommandInvoker : ICommandInvoker<DeletePostCommand, CommandResult>
    {
        private readonly Config _dbConfig;

        public DeletePostCommandInvoker(Config dbConfig)
        {
            _dbConfig = dbConfig;
        }

        public CommandResult Execute(DeletePostCommand command)
        {
            using (var db = new LiteDatabase(_dbConfig.DbPath))
            {
                var posts = db.GetCollection<BlogPost>(DBTableNames.BlogPosts);
                var post = posts.FindById(command.PostId);
                if (post != null)
                {
                    var tags = db.GetCollection<Tag>(DBTableNames.Tags);
                    foreach (var slug in post.Tags)
                    {
                        string slug1 = slug;
                        var tagEntry = tags.FindOne(x => x.Slug.Equals(slug1));
                        if (tagEntry != null)
                        {
                            tagEntry.PostCount--;
                            tags.Update(tagEntry);
                        }
                    }
                }

                // remove
                posts.Delete(x => x.Id == command.PostId);

                var comments = db.GetCollection<BlogComment>(DBTableNames.BlogComments);
                comments.Delete(x => x.PostId == command.PostId);

                return CommandResult.SuccessResult;
            }
        }
    }
}


text:
package org.apache.camel.api.management.mbean;

public interface ManagedStepMBean extends ManagedProcessorMBean {

    // noop
}


text:
'use strict';

var gulp = require('gulp'),
    changed = require('gulp-changed'),
    sass = require('gulp-sass'),
    csso = require('gulp-csso'),
    autoprefixer = require('gulp-autoprefixer'),
    browserify = require('browserify'),
    watchify = require('watchify'),
    source = require('vinyl-source-stream'),
    buffer = require('vinyl-buffer'),
    babelify = require('babelify'),
    uglify = require('gulp-uglify'),
    del = require('del'),
    notify = require('gulp-notify'),
    browserSync = require('browser-sync'),
    sourcemaps = require('gulp-sourcemaps'),
    reload = browserSync.reload,
    p = {
      jsx: './scripts/app.jsx',
      scss: ['styles/main.scss', 'styles/components/*.scss'],
      bundle: 'app.js',
      distJs: 'dist/js',
      distCss: 'dist/css'
    };

gulp.task('clean', function(cb) {
  del(['dist'], cb);
});

gulp.task('browserSync', function() {
  browserSync({
    server: {
      baseDir: './'
    }
  });
});

gulp.task('watchify', function() {
  var bundler = watchify(browserify(p.jsx, watchify.args));

  function rebundle() {
    return bundler
      .bundle()
      .on('error', notify.onError())
      .pipe(source(p.bundle))
      .pipe(gulp.dest(p.distJs))
      .pipe(reload({stream: true}));
  }

  bundler.transform("babelify", {presets: ["es2015", "react"]})
  .on('update', rebundle);
  return rebundle();
});

gulp.task('browserify', function() {
  browserify(p.jsx)
    .transform("babelify", {presets: ["es2015", "react"]})
    .bundle()
    .pipe(source(p.bundle))
    .pipe(buffer())
    .pipe(sourcemaps.init({loadMaps: true}))
    .pipe(uglify())
    .pipe(sourcemaps.write('./'))
    .pipe(gulp.dest(p.distJs));
});

gulp.task('styles', function() {
  return gulp.src(p.scss)
    .pipe(changed(p.distCss))
    .pipe(sass({errLogToConsole: true}))
    .on('error', notify.onError())
    .pipe(autoprefixer('last 1 version'))
    .pipe(csso())
    .pipe(gulp.dest(p.distCss))
    .pipe(reload({stream: true}));
});

gulp.task('fonts', function() {
  return gulp.src('node_modules/font-awesome/fonts/*')
    .pipe(gulp.dest('dist/fonts'));
});

gulp.task('watchTask', function() {
  gulp.watch(p.scss, ['styles']);
});

gulp.task('watch', ['clean', 'browserSync', 'watchTask', 'watchify', 'styles', 'fonts'], function() {
  //gulp.start(['browserSync', 'watchTask', 'watchify', 'styles', 'fonts']);
});

gulp.task('build', function() {
  process.env.NODE_ENV = 'production';
  gulp.start(['clean', 'browserify', 'styles']);
});

gulp.task('default', function() {
  console.log('Run "gulp watch or gulp build"');
});


text:
**Cutaneous** _adj._ Of the skin.

Cutaneous is a Ruby (1.9+) templating engine designed for flexibility and simplicity.

It supports having multiple output formats, multiple syntaxes and borrows a template inheritance mechanism from Python template engines such as  [Django's](https://docs.djangoproject.com/en/dev/topics/templates/), [Jinja](http://jinja.pocoo.org/) and [Mako](http://www.makotemplates.org/).

Cutaneous is the template engine designed for and used by [Spontaneous CMS](http://spontaneouscms.org).

## Quickstart

<script src="https://gist.github.com/3169319.js"> </script>

<script src="https://gist.github.com/3169327.js"> </script>

The `Cutaneous::Engine` class provides two core methods:

- `Cutaneous::Engine#render(template_path, context, format)`

  This renders the template at `template_path` using the context `context` (which must be an instance of Cutaneous::Context (or a subclass)) and the format `format`.

  `template_path` should be specified as either a relative path which will be resolved using a search through the template roots specified in the engine's initialisation call. See below for more information about how templates are specified & resolved.

- `Cutaneous::Engine#render_string(template, context, format)`

  This takes the input string as the template and renders it. If this string references other templates through includes (see below) these are resolved as if you had made a call to `Engine#render`.

### Template Naming & Resolution

By default Cutaneous templates should be given a `.cut` file extension.

Cutaneous generally relies upon relative template names. If we consider the following code:

```ruby

engine  = Cutaneous::Engine.new([
	"/home/user/templates",
	"/home/user/shared_templates"
])

context = Cutaneous::Context.new(Object.new, title: "Welcome")

result  = engine.render("welcome", context, "html")
```

The `#render` call will look for a file called `welcome.html.cut` under each of the supplied template roots & return the first one it finds:

```ruby

# The template resolution is equivalent to the following Ruby code:
search_paths =  [
	"/home/user/templates/welcome.html.cut",
	"/home/user/shared_templates/welcome.html.cut"
]

template_path = search_paths.detect { |path| File.exist?(path) }

```

Template filenames are derived from `[template_relative_path, format, "cut"].join(".")`.

If you specified a different format for the render call, e.g. `engine.render("welcome", context, "txt")` then the engine would instead look for a file named `welcome.txt.cut`.

If you want to organise your templates into subdirectories then you are completely free to do so, you just need to add the subdirectory name onto the relative path:

```ruby

result  = engine.render("layouts/welcome", context, "html")

#=> Renders the file "/home/user/templates/layouts/welcome.html.cut"
```

#### Includes

To include one template file into another you use the `include` directive within your template:

    %{ include 'partial/header' }

This will include the output of rendering the file "/home/user/templates/partial/header.html.cut" directly in your original template's output (assuming you're rendering the "html" format).

Note that Cutaneous has no special treatment of "partials", there is no special `partial` command and no preceeding underscore in the template name.

#### Passing a Proc as a Template

If you want to switch between rendering file based & string based templates then Cutaneous provides a way of using the same `Engine#render` call by passing a Proc as the template path:

```ruby

# This
template = "Hello ${ name }!"
engine.render(Proc.new { template }, context)

# is the same as:
engine.render_string(template, context)

```

This allows us to use simple strings as template paths and still use a consistent calling mechanism.

## Features

### Template Inheritance

Cutaneous features a block based template inheritance mechanism.

Including a `%{ extends "parent" }` tag at the start of a template
makes it inherit from the named template ("parent" in this case).

Parent templates define a series of blocks using a `%{ block :block_name}
... %{ endblock}` syntax. Child templates can then override any of
these individual blocks with their own content.

Calling `%{ blocksuper }` within a child template's block allows you
to insert the code from the parent template (much like calling `super`
in an object subclass).

So for example using the following templates:

<script src="https://gist.github.com/3169196.js"> </script>

<script src="https://gist.github.com/3169203.js"> </script>

`engine.render("child", context, "html")` would result in the following output:

    Title

    Template inheritance is great!
    Template inheritance is great!

    Do it like this...

    And like this...

The template hierarchy can be as long as you need/like. Template 'd' could extend 'c' which extends 'b' which extends 'a' etc..

### Formats

Cutaneous allows templates for multiple formats to exist alongside each other. In the examples above the `html` format is exclsuively used but instead of this I could render the same template as `txt`

    result = engine.render("quickstart", context, "txt")

This would look for a `quickstart.txt.cut` template under the template roots. The format used is maintained across both `include` and `extend` calls so when using these you should reference them without any extension.

If your standard format isn't "html" then you can set a new default when creating your template engine instance:

    engine = Cutaneous::Engine.new("/template/root", Cutaneous::FirstPassSyntax, "txt")

### Whitespace

If you want to remove trailing whitespace after a tag, then suffix it with a `-` character, e.g.

    %{ include "something" -}

### Caching

If you create an instance of `Cutaneous::CachingEngine` instead of the default `Engine` class then the compiled templates will be cached in-memory for the lifetime of the engine. In order to render templates Cutaneous converts them to simple Ruby code. As part of the caching this generated code will be written to disk alongside the original template with the extension `.format.rb`.

If you want to turn off the writing of the compiled Ruby files (such as in a development environment), set `write_compiled_scripts` to false:

    engine.write_compiled_scripts = false

The cached ruby will only be used if it is fresher than the template it was compiled from so updating the template will re-write the `.rb` equivalent.

### Syntaxes

Cutaneous supports the concept of syntaxes. This is used by Spontaneous to provide a two-stage rendering process (first-pass templates output second-pass templates which are rendered on demand -- in this way you can create a very responsive dynamic site because you have precached 99% of the page).

The two syntaxes are:

#### First-pass

- Statements: `%{ ruby code... }`
- Expressions: `${ value }`
- Escaped expressions: `$${ unsafe value }`
- Comments: `!{ comment... }`

#### Second-pass

- Statements: `{% ruby code... %}`
- Expressions: `{{ value }}`
- Escaped expressions: `{$ unsafe value $}`
- Comments: `!{ comment... }`

You choose which one of these you wish to use when you create your `Cutaneous::Engine` instance:

    engine = Cutaneous::Engine.new("/template/root", Cutaneous::SecondPassSyntax)

## Contexts

Cutaneous doesn't try to remove code from your templates it instead allows you to write as much Ruby as you want directly in-place. This is done in order to make the development of your front-end code as quick as possible. If you later want to clean up your template code you can instead use helper methods either on the context you pass to the renderer or the object you wrap that context around.

If you want to add features to your context, or `helpers` as they would be known in Rails-land then create a new Context class and include your helper methods there:

```ruby

module MyHelperMethods
 def my_helpful_method
	 # ... do something complex that you want to keep out of the template
 end
end

# You *must* inherit from Cutaneous::Context!
class MyContext < Cutaneous::Context
	include MyHelperMethods
end

context = MyContext.new(instance, parameter: "value")

result  = engine.render("template", context)
```

### Errors

Cutaneous silently swallows errors about missing expressions in templates. If you want to instead report these errors override the `__handle_error` context method:

```ruby
class MyContext < Cutaneous::Context
	def __handle_error(e)
		logger.warn(e)
	end
end
```

Cutaneous will do its best to keep the line numbers consistent between templates and the generated code (although see "Bugs" below...). This will hopefully make debugging easier.

## Bugs/TODO

- Make the Syntax more powerful and capable of dealing with any syntax (e.g. implement an ERB like syntax). At the moment they only deal with brace-based syntaxes and brace counting is built into the Lexer.
- Using template inheritance messes up the line numbers of errors... Not sure what to do about that...

## License

Cutaneous is released under an MIT license (see LICENSE).


text:
namespace FluentPipeline.Core
{

    using System;
    public class RandomBackoffPolicy : IBackoffPolicy
    {
        private readonly Random random = new Random();
        private readonly int min;
        private readonly int max;

        public RandomBackoffPolicy(int min = 0, int max = 1000)
        {
            this.min = min;
            this.max = max;
        }

        public int Delay()
        {
            return random.Next(0, 1000);
        }

        public void RecordAttempt(bool success = false)
        {
            throw new NotImplementedException();
        }
    }
}


text:
class SUColorPopup : protected SUPopupWindow
{
	public:
		static SInt32		DoColorPopup( Point inTopLeft, CTabHandle, SInt32 defaultItem = -1 );

	protected:
		CTabHandle			mColorTable;

							SUColorPopup( CTabHandle inTable );
		virtual				~SUColorPopup();

		virtual void		Prepare( Point inTopLeft );
		virtual void		DrawInitialState();
		virtual void		DrawOneCell( SInt32 inIndex, Boolean inHilited = false );
};


text:
@javax.xml.bind.annotation.XmlSchema(namespace = KimApiConstants.Namespaces.KIM_NAMESPACE_2_0, elementFormDefault = XmlNsForm.QUALIFIED)
package org.kuali.rice.kim.api.role;

import javax.xml.bind.annotation.XmlNsForm;

import org.kuali.rice.kim.api.KimApiConstants;


text:
<?php

namespace Froiden\RestAPI\Middleware;

use Closure;
use Froiden\RestAPI\ApiResponse;
use Froiden\RestAPI\Exceptions\UnauthorizedException;
use Illuminate\Support\Str;
use Symfony\Component\HttpFoundation\StreamedResponse;

class ApiMiddleware
{

    public function handle($request, Closure $next)
    {
        // Add CORS headers
        $response = $next($request);

        if ($response->getStatusCode() == 403 && ($response->getContent() == "Forbidden" || Str::contains($response->getContent(), ['HttpException', 'authorized']))) {
            $response = ApiResponse::exception(new UnauthorizedException());
        }

        if (config("api.cors") && !$response instanceof StreamedResponse) {
            $response->header('Access-Control-Allow-Origin', '*')
                ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE, OPTIONS')
                ->header('Access-Control-Allow-Headers', implode(',', config('api.cors_headers')));
        }

        return $response;
    }
}


text:
using System;
using System.Text;

namespace NextCallerApi.Authorization
{
	internal class BasicAuthorization
	{

		private const string TokenTemplate = "Basic {0}";

		public static string GetToken(string username, string password)
		{
			string tokenValue = Convert.ToBase64String(Encoding.UTF8.GetBytes(username + ":" + password));
			return string.Format(TokenTemplate, tokenValue);
		}

	}
}


text:
using System;
using System.Windows;
using System.Windows.Shell;

namespace GitHubUpdater.WPF.ViewModel
{
  public class ProcessViewModel : BaseViewModel, IProcess
  {
    private double percent;
    private ConvertState state;
    private string status;
    private ProgressState progressState;
    private TaskbarItemProgressState taskbarItemProgressState;
    private string title;

    public event EventHandler<ConvertState> StateChanged;

    public double Percent
    {
      get { return percent; }
      set
      {
        if (value > 1 || value < 0)
          throw new ArgumentOutOfRangeException(nameof(Percent), "Select percent from 0 to 1.");

        percent = value;
        OnPropertyChanged();
      }
    }

    public bool IsIndeterminate
    {
      get { return this.ProgressState == ProgressState.Indeterminate; }
    }

    public ProgressState ProgressState
    {
      get { return progressState; }
      set
      {
        progressState = value;
        OnPropertyChanged();
        OnPropertyChanged(nameof(IsIndeterminate));
        Enum.TryParse(value.ToString(), out taskbarItemProgressState);
        OnPropertyChanged(nameof(TaskbarItemProgressState));
      }
    }

    public TaskbarItemProgressState TaskbarItemProgressState { get { return taskbarItemProgressState; } }

    public string Status
    {
      get { return status; }
      set
      {
        status = value;
        OnPropertyChanged();
      }
    }

    public ConvertState State
    {
      get { return state; }
      set
      {
        state = value;
        OnPropertyChanged();
        OnStateChanged(value);
      }
    }

    public string Title
    {
      get { return title; }
      set
      {
        title = value;
        OnPropertyChanged();
      }
    }

    public ProcessViewModel()
    {
      this.Percent = 0;
      this.ProgressState = ProgressState.Indeterminate;
      this.Status = string.Empty;
      this.State = ConvertState.None;
    }

    protected virtual void OnStateChanged(ConvertState newState)
    {
      if (Application.Current.Dispatcher.CheckAccess())
        StateChanged?.Invoke(this, newState);
      else
        Application.Current.Dispatcher.InvokeAsync(() => StateChanged?.Invoke(this, newState));
    }
  }

  public enum ConvertState
  {
    None,
    Started,
    Completed
  }

  /// <summary>
  /// Определяет состояние индикатора хода выполнения на панели задач Windows.
  /// </summary>
  public enum ProgressState
  {
    None,
    Indeterminate,
    Normal,
    Error,
    Paused,
  }

  public interface IProcess
  {
    double Percent { get; set; }

    ProgressState ProgressState { get; set; }

    string Status { get; set; }

    ConvertState State { get; set; }

    event System.EventHandler<ConvertState> StateChanged;

    string Title { get; set; }
  }
}


text:
exports.Boundary = Boundary;

function Boundary() {
  this.id;
  this.data;
  this.sections = {};
};


text:
<FindBugsFilter>
    <Match>
        <Package name="~^net\.sinofool\.wechat\.thirdparty\..*"/>
    </Match>
    <Match>
        <Class name="net.sinofool.wechat.pay.WeChatPayResponseData"/>
        <Method name="getBoolean"/>
        <Bug pattern="NP_BOOLEAN_RETURN_NULL"/>
    </Match>
    <Match>
        <Or>
            <Class name="net.sinofool.wechat.miniapp.WeChatMiniAppUserInfo"/>
            <Class name="net.sinofool.wechat.WeChatUserInfo"/>
        </Or>
        <Bug pattern="NM_CONFUSING"/>
    </Match>
</FindBugsFilter>


text:
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**accessToken** | **String** | Access token |  [optional]
**tokenScopes** | **List<String>** | Valid scopes for the access token |  [optional]
**validityTime** | **Long** | Maximum validity time for the access token |  [optional]


text:
namespace onnxruntime {
namespace ml {

ONNX_CPU_OPERATOR_ML_KERNEL(
    SVMRegressor,
    1,
    KernelDefBuilder().TypeConstraint("T", DataTypeImpl::GetTensorType<float>()),
    SVMRegressor<float>);

template <typename T>
SVMRegressor<T>::SVMRegressor(const OpKernelInfo& info)
    : OpKernel(info),
      SVMCommon(info),
      vector_count_(info.GetAttrOrDefault<int64_t>("n_supports", 0)),
      support_vectors_(info.GetAttrsOrDefault<float>("support_vectors")),
      post_transform_(MakeTransform(info.GetAttrOrDefault<std::string>("post_transform", "NONE"))) {
  ORT_ENFORCE(info.GetAttrs<float>("rho", rho_).IsOK());
  ORT_ENFORCE(info.GetAttrs<float>("coefficients", coefficients_).IsOK());
  ORT_ENFORCE(!coefficients_.empty());

  auto onec = info.GetAttrOrDefault<int64_t>("one_class", 0);
  one_class_ = (onec != 0);

  if (vector_count_ > 0) {
    feature_count_ = support_vectors_.size() / vector_count_;  //length of each support vector
    mode_ = SVM_TYPE::SVM_SVC;
  } else {
    feature_count_ = coefficients_.size();
    mode_ = SVM_TYPE::SVM_LINEAR;
    set_kernel_type(KERNEL::LINEAR);
  }
}

template <typename T>
Status SVMRegressor<T>::Compute(OpKernelContext* ctx) const {
  const auto* X = ctx->Input<Tensor>(0);

  int64_t num_features = X->Shape().NumDimensions() == 1 ? X->Shape()[0] : X->Shape()[1];
  int64_t num_batches = X->Shape().NumDimensions() == 1 ? 1 : X->Shape()[0];
  ORT_ENFORCE(num_features == feature_count_);

  // X: [num_batches, feature_count_] where features could be coefficients or support vectors
  // coefficients_: [vector_count_]
  // support_vectors_ : [vector_count_, feature_count_]

  // Y: [num_batches, 1]
  Tensor* Y = ctx->Output(0, {num_batches, 1});  // this op outputs for one target only
  const auto x_data = X->template DataAsSpan<T>();
  auto out = Y->MutableDataAsSpan<T>();

  concurrency::ThreadPool* threadpool = ctx->GetOperatorThreadPool();

  if (mode_ == SVM_TYPE::SVM_SVC) {
    AllocatorPtr allocator;
    auto status = ctx->GetTempSpaceAllocator(&allocator);
    ORT_RETURN_IF_ERROR(status);

    auto tmp_data = IAllocator::MakeUniquePtr<T>(allocator, num_batches * SafeInt<size_t>(vector_count_));
    auto tmp_data_span = gsl::make_span<T>(tmp_data.get(), num_batches * SafeInt<size_t>(vector_count_));

    // combine the input data with the support vectors and apply the kernel type
    // output is {num_batches, vector_count_}
    batched_kernel_dot<float>(x_data, support_vectors_, num_batches, vector_count_, feature_count_, 0.f, tmp_data_span,
                              threadpool);

    static const TensorShape rho_shape({1});

    // combine with coefficients and add rho_[0]
    onnxruntime::Gemm<T>::ComputeGemm(CBLAS_TRANSPOSE::CblasNoTrans, CBLAS_TRANSPOSE::CblasTrans,
                                      num_batches, 1, vector_count_,
                                      1.f, tmp_data_span.data(), coefficients_.data(), 1.f,
                                      rho_.data(), &rho_shape,
                                      out.data(),
                                      threadpool);
  } else if (mode_ == SVM_TYPE::SVM_LINEAR) {
    // combine the coefficients with the input data and apply the kernel type
    batched_kernel_dot<float>(x_data, coefficients_, num_batches, 1, feature_count_, rho_[0], out, threadpool);
  } else {
    return ORT_MAKE_STATUS(ONNXRUNTIME, FAIL, "Unexpected mode:", static_cast<int>(mode_));
  }

  if (one_class_) {
    float* y = out.data();
    float* y_end = y + out.size();

    while (y < y_end) {
      *y = (*y > 0.f ? 1.f : -1.f);
      ++y;
    }
  }

  return Status::OK();
}
}  // namespace ml
}  // namespace onnxruntime


text:
using MasterDevs.ChromeDevTools;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;

namespace MasterDevs.ChromeDevTools.Protocol.iOS.DOM
{
	/// <summary>
	/// Highlights DOM node with given id or with the given JavaScript object wrapper. Either nodeId or objectId must be specified.
	/// </summary>
	[CommandResponse(ProtocolName.DOM.HighlightNode)]
	[SupportedBy("iOS")]
	public class HighlightNodeCommandResponse
	{
	}
}


text:
function usPerTime=SONGetusPerTime(fh)
% SONGETUSPERTIME returns the tick interval in units of SONTimeBase()
% USPERTIME=SONGETUSPERTIME(FH)
%                         FH SON file handle
%
% See also SONGETTIMEPERADC, SONCHANDIVIDE
% Author:Malcolm Lidierth
% Matlab SON library:
% Copyright 2005 © King's College London

if nargin ~= 1
    usPerTime=-1000;
    return;
end;

usPerTime=calllib('son32','SONGetusPerTime',fh);
return;


text:
package fi.imberg.juhani.ernu.interpreter.builtin;

import fi.imberg.juhani.ernu.interpreter.Environment;
import fi.imberg.juhani.ernu.interpreter.exceptions.RuntimeException;
import fi.imberg.juhani.ernu.interpreter.interfaces.Node;
import fi.imberg.juhani.ernu.interpreter.nodes.ArrayNode;
import fi.imberg.juhani.ernu.interpreter.nodes.NullNode;
import fi.imberg.juhani.ernu.interpreter.nodes.NumberNode;
import org.junit.*;
import org.junit.rules.ExpectedException;

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

public class RangeFunctionTest {
    @Rule
    public ExpectedException thrown = ExpectedException.none();
    Environment environment;
    RangeFunction rangeFunction;

    @Before
    public void init() {
        environment = new Environment(false, null, "test");
        rangeFunction = new RangeFunction();
    }

    @After
    public void destroy() {
        environment = null;
        rangeFunction = null;
    }

    @Test
    public void mustBeOneArgument() throws RuntimeException {
        thrown.expect(fi.imberg.juhani.ernu.interpreter.exceptions.RuntimeException.class);
        thrown.expectMessage("range takes at least one argument");

        rangeFunction.call(environment, new ArrayList<>());
    }

    @Test
    public void cantBeMoreThan3Arguments() throws RuntimeException {
        thrown.expect(fi.imberg.juhani.ernu.interpreter.exceptions.RuntimeException.class);
        thrown.expectMessage("range takes three arguments at most");

        List<Node> nodeList = new ArrayList<>();
        nodeList.add(new NullNode());
        nodeList.add(new NullNode());
        nodeList.add(new NullNode());
        nodeList.add(new NullNode());

        rangeFunction.call(environment, nodeList);
    }

    @Test
    public void argumentsNeedToBeNumbers() throws RuntimeException {
        thrown.expect(fi.imberg.juhani.ernu.interpreter.exceptions.RuntimeException.class);
        thrown.expectMessage("range takes number nodes as arguments");

        List<Node> nodeList = new ArrayList<>();
        nodeList.add(new NullNode());

        rangeFunction.call(environment, nodeList);
    }

    public void doRangeTest(int[] argsArray, int[] expected) throws RuntimeException {
        List<Node> args = new ArrayList<>();
        for (int arg : argsArray) {
            args.add(new NumberNode(arg));
        }
        Node node = rangeFunction.call(environment, args);
        Assert.assertTrue(node instanceof ArrayNode);
        ArrayNode arrayNode = (ArrayNode) node;
        Assert.assertEquals(expected.length, arrayNode.length());
        for (int i = 0; i < expected.length; i++) {
            Assert.assertEquals(expected[i], ((NumberNode) arrayNode.get(i)).getInteger());
        }
    }

    @Test
    public void simpleRangesWork() throws RuntimeException {
        doRangeTest(new int[]{3}, new int[]{0, 1, 2});
        doRangeTest(new int[]{1, 3}, new int[]{1, 2});
        doRangeTest(new int[]{1, 3, -1}, new int[]{3, 2});
    }
}


text:
class Dog < ActiveRecord::Base

  def to_s

     "My dogs name #{self.name} and he is a #{self.breed} and is #{self.age} years old"

  end

end


text:
#ifndef __MEM_COMM_MONITOR_HH__
#define __MEM_COMM_MONITOR_HH__

#include <fstream>
#include <iomanip>

#include "base/statistics.hh"
#include "debug/DataCommMonitor.hh"
#include "mem/mem_object.hh"
#include "params/CommMonitor.hh"
#include "sim/probe/mem.hh"

/**
 * The communication monitor is a MemObject which can monitor statistics of
 * the communication happening between two ports in the memory system.
 *
 * Currently the following stats are implemented: Histograms of read/write
 * transactions, read/write burst lengths, read/write bandwidth,
 * outstanding read/write requests, read latency and inter transaction time
 * (read-read, write-write, read/write-read/write). Furthermore it allows
 * to capture the number of accesses to an address over time ("heat map").
 * All stats can be disabled from Python.
 */
class CommMonitor : public MemObject
{

  public: // Construction & SimObject interfaces

    /** Parameters of communication monitor */
    typedef CommMonitorParams Params;
    const Params* params() const
    { return reinterpret_cast<const Params*>(_params); }

    /**
     * Constructor based on the Python params
     *
     * @param params Python parameters
     */
    CommMonitor(Params* params);

    void init() override;
    void regStats() override;
    void startup() override;
    void regProbePoints() override;

  public: // MemObject interfaces
    BaseMasterPort& getMasterPort(const std::string& if_name,
                                  PortID idx = InvalidPortID) override;

    BaseSlavePort& getSlavePort(const std::string& if_name,
                                PortID idx = InvalidPortID) override;

  private:

    std::ofstream mem_trace_fout;
    void print(PacketPtr pkt, bool is_req);

    /**
     * Sender state class for the monitor so that we can annotate
     * packets with a transmit time and receive time.
     */
    class CommMonitorSenderState : public Packet::SenderState
    {

      public:

        /**
         * Construct a new sender state and store the time so we can
         * calculate round-trip latency.
         *
         * @param _transmitTime Time of packet transmission
         */
        CommMonitorSenderState(Tick _transmitTime)
            : transmitTime(_transmitTime)
        { }

        /** Destructor */
        ~CommMonitorSenderState() { }

        /** Tick when request is transmitted */
        Tick transmitTime;

    };

    /**
     * This is the master port of the communication monitor. All recv
     * functions call a function in CommMonitor, where the
     * send function of the slave port is called. Besides this, these
     * functions can also perform actions for capturing statistics.
     */
    class MonitorMasterPort : public MasterPort
    {

      public:

        MonitorMasterPort(const std::string& _name, CommMonitor& _mon)
            : MasterPort(_name, &_mon), mon(_mon)
        { }

      protected:

        void recvFunctionalSnoop(PacketPtr pkt)
        {
            mon.recvFunctionalSnoop(pkt);
        }

        Tick recvAtomicSnoop(PacketPtr pkt)
        {
            return mon.recvAtomicSnoop(pkt);
        }

        bool recvTimingResp(PacketPtr pkt)
        {
            return mon.recvTimingResp(pkt);
        }

        void recvTimingSnoopReq(PacketPtr pkt)
        {
            mon.recvTimingSnoopReq(pkt);
        }

        void recvRangeChange()
        {
            mon.recvRangeChange();
        }

        bool isSnooping() const
        {
            return mon.isSnooping();
        }

        void recvReqRetry()
        {
            mon.recvReqRetry();
        }

        void recvRetrySnoopResp()
        {
            mon.recvRetrySnoopResp();
        }

      private:

        CommMonitor& mon;

    };

    /** Instance of master port, facing the memory side */
    MonitorMasterPort masterPort;

    /**
     * This is the slave port of the communication monitor. All recv
     * functions call a function in CommMonitor, where the
     * send function of the master port is called. Besides this, these
     * functions can also perform actions for capturing statistics.
     */
    class MonitorSlavePort : public SlavePort
    {

      public:

        MonitorSlavePort(const std::string& _name, CommMonitor& _mon)
            : SlavePort(_name, &_mon), mon(_mon)
        { }

      protected:

        void recvFunctional(PacketPtr pkt)
        {
            mon.recvFunctional(pkt);
        }

        Tick recvAtomic(PacketPtr pkt)
        {
            return mon.recvAtomic(pkt);
        }

        bool recvTimingReq(PacketPtr pkt)
        {
            return mon.recvTimingReq(pkt);
        }

        bool recvTimingSnoopResp(PacketPtr pkt)
        {
            return mon.recvTimingSnoopResp(pkt);
        }

        AddrRangeList getAddrRanges() const
        {
            return mon.getAddrRanges();
        }

        void recvRespRetry()
        {
            mon.recvRespRetry();
        }

      private:

        CommMonitor& mon;

    };

    /** Instance of slave port, i.e. on the CPU side */
    MonitorSlavePort slavePort;

    void recvFunctional(PacketPtr pkt);

    void recvFunctionalSnoop(PacketPtr pkt);

    Tick recvAtomic(PacketPtr pkt);

    Tick recvAtomicSnoop(PacketPtr pkt);

    bool recvTimingReq(PacketPtr pkt);

    bool recvTimingResp(PacketPtr pkt);

    void recvTimingSnoopReq(PacketPtr pkt);

    bool recvTimingSnoopResp(PacketPtr pkt);

    void recvRetrySnoopResp();

    AddrRangeList getAddrRanges() const;

    bool isSnooping() const;

    void recvReqRetry();

    void recvRespRetry();

    void recvRangeChange();

    /** Stats declarations, all in a struct for convenience. */
    struct MonitorStats
    {

        /** Disable flag for burst length historgrams **/
        bool disableBurstLengthHists;

        /** Histogram of read burst lengths */
        Stats::Histogram readBurstLengthHist;

        /** Histogram of write burst lengths */
        Stats::Histogram writeBurstLengthHist;

        /** Disable flag for the bandwidth histograms */
        bool disableBandwidthHists;

        /**
         * Histogram for read bandwidth per sample window. The
         * internal counter is an unsigned int rather than a stat.
         */
        unsigned int readBytes;
        Stats::Histogram readBandwidthHist;
        Stats::Formula averageReadBW;
        Stats::Scalar totalReadBytes;

        /**
         * Histogram for write bandwidth per sample window. The
         * internal counter is an unsigned int rather than a stat.
         */
        unsigned int writtenBytes;
        Stats::Histogram writeBandwidthHist;
        Stats::Formula averageWriteBW;
        Stats::Scalar totalWrittenBytes;

        /** Disable flag for latency histograms. */
        bool disableLatencyHists;

        /** Histogram of read request-to-response latencies */
        Stats::Histogram readLatencyHist;

        /** Histogram of write request-to-response latencies */
        Stats::Histogram writeLatencyHist;

        /** Disable flag for ITT distributions. */
        bool disableITTDists;

        /**
         * Inter transaction time (ITT) distributions. There are
         * histograms of the time between two read, write or arbitrary
         * accesses. The time of a request is the tick at which the
         * request is forwarded by the monitor.
         */
        Stats::Distribution ittReadRead;
        Stats::Distribution ittWriteWrite;
        Stats::Distribution ittReqReq;
        Tick timeOfLastRead;
        Tick timeOfLastWrite;
        Tick timeOfLastReq;

        /** Disable flag for outstanding histograms. */
        bool disableOutstandingHists;

        /**
         * Histogram of outstanding read requests. Counter for
         * outstanding read requests is an unsigned integer because
         * it should not be reset when stats are reset.
         */
        Stats::Histogram outstandingReadsHist;
        unsigned int outstandingReadReqs;

        /**
         * Histogram of outstanding write requests. Counter for
         * outstanding write requests is an unsigned integer because
         * it should not be reset when stats are reset.
         */
        Stats::Histogram outstandingWritesHist;
        unsigned int outstandingWriteReqs;

        /** Disable flag for transaction histograms. */
        bool disableTransactionHists;

        /** Histogram of number of read transactions per time bin */
        Stats::Histogram readTransHist;
        unsigned int readTrans;

        /** Histogram of number of timing write transactions per time bin */
        Stats::Histogram writeTransHist;
        unsigned int writeTrans;

        /** Disable flag for address distributions. */
        bool disableAddrDists;

        /**
         * Histogram of number of read accesses to addresses over
         * time.
         */
        Stats::SparseHistogram readAddrDist;

        /**
         * Histogram of number of write accesses to addresses over
         * time.
         */
        Stats::SparseHistogram writeAddrDist;

        /**
         * Create the monitor stats and initialise all the members
         * that are not statistics themselves, but used to control the
         * stats or track values during a sample period.
         */
        MonitorStats(const CommMonitorParams* params) :
            disableBurstLengthHists(params->disable_burst_length_hists),
            disableBandwidthHists(params->disable_bandwidth_hists),
            readBytes(0), writtenBytes(0),
            disableLatencyHists(params->disable_latency_hists),
            disableITTDists(params->disable_itt_dists),
            timeOfLastRead(0), timeOfLastWrite(0), timeOfLastReq(0),
            disableOutstandingHists(params->disable_outstanding_hists),
            outstandingReadReqs(0), outstandingWriteReqs(0),
            disableTransactionHists(params->disable_transaction_hists),
            readTrans(0), writeTrans(0),
            disableAddrDists(params->disable_addr_dists)
        { }

    };

    /** This function is called periodically at the end of each time bin */
    void samplePeriodic();

    /** Periodic event called at the end of each simulation time bin */
    EventWrapper<CommMonitor, &CommMonitor::samplePeriodic> samplePeriodicEvent;

    /**
     *@{
     * @name Configuration
     */

    /** Length of simulation time bin*/
    const Tick samplePeriodTicks;
    /** Sample period in seconds */
    const double samplePeriod;

    /** Address mask for sources of read accesses to be captured */
    const Addr readAddrMask;

    /** Address mask for sources of write accesses to be captured */
    const Addr writeAddrMask;

    /** @} */

    /** Instantiate stats */
    MonitorStats stats;

  protected: // Probe points
    /**
     * @{
     * @name Memory system probe points
     */

    /** Successfully forwarded request packet */
    ProbePoints::PacketUPtr ppPktReq;

    /** Successfully forwarded response packet */
    ProbePoints::PacketUPtr ppPktResp;

    /** @} */
};

#endif //__MEM_COMM_MONITOR_HH__


text:
#include <linux/module.h>
#include <linux/linkage.h>
#include <linux/sched.h>
#include <linux/string.h>
#include <linux/mm.h>
#include <linux/user.h>
#include <linux/elfcore.h>
#include <linux/in6.h>
#include <linux/interrupt.h>
#include <linux/config.h>

#include <asm/setup.h>
#include <asm/pgalloc.h>
#include <asm/irq.h>
#include <asm/io.h>
#include <asm/semaphore.h>
#include <asm/checksum.h>
#include <asm/current.h>
#include <asm/gpio.h>

//asmlinkage long long __ashrdi3 (long long, int);
//asmlinkage long long __lshrdi3 (long long, int);
extern char h8300_debug_device[];

/* platform dependent support */

EXPORT_SYMBOL(strnlen);
EXPORT_SYMBOL(strrchr);
EXPORT_SYMBOL(strstr);
EXPORT_SYMBOL(strchr);
EXPORT_SYMBOL(strcat);
EXPORT_SYMBOL(strlen);
EXPORT_SYMBOL(strcmp);
EXPORT_SYMBOL(strncmp);

EXPORT_SYMBOL(ip_fast_csum);

EXPORT_SYMBOL(kernel_thread);
EXPORT_SYMBOL(enable_irq);
EXPORT_SYMBOL(disable_irq);

/* Networking helper routines. */
EXPORT_SYMBOL(csum_partial_copy);

/* The following are special because they're not called
   explicitly (the C compiler generates them).  Fortunately,
   their interface isn't gonna change any time soon now, so
   it's OK to leave it out of version control.  */
//EXPORT_SYMBOL(__ashrdi3);
//EXPORT_SYMBOL(__lshrdi3);
EXPORT_SYMBOL(memcpy);
EXPORT_SYMBOL(memset);
EXPORT_SYMBOL(memcmp);
EXPORT_SYMBOL(memscan);
EXPORT_SYMBOL(memmove);

EXPORT_SYMBOL(get_wchan);

/*
 * libgcc functions - functions that are used internally by the
 * compiler...  (prototypes are not correct though, but that
 * doesn't really matter since they're not versioned).
 */
extern void __gcc_bcmp(void);
extern void __ashldi3(void);
extern void __ashrdi3(void);
extern void __cmpdi2(void);
extern void __divdi3(void);
extern void __divsi3(void);
extern void __lshrdi3(void);
extern void __moddi3(void);
extern void __modsi3(void);
extern void __muldi3(void);
extern void __mulsi3(void);
extern void __negdi2(void);
extern void __ucmpdi2(void);
extern void __udivdi3(void);
extern void __udivmoddi4(void);
extern void __udivsi3(void);
extern void __umoddi3(void);
extern void __umodsi3(void);

        /* gcc lib functions */
EXPORT_SYMBOL(__gcc_bcmp);
EXPORT_SYMBOL(__ashldi3);
EXPORT_SYMBOL(__ashrdi3);
EXPORT_SYMBOL(__cmpdi2);
EXPORT_SYMBOL(__divdi3);
EXPORT_SYMBOL(__divsi3);
EXPORT_SYMBOL(__lshrdi3);
EXPORT_SYMBOL(__moddi3);
EXPORT_SYMBOL(__modsi3);
EXPORT_SYMBOL(__muldi3);
EXPORT_SYMBOL(__mulsi3);
EXPORT_SYMBOL(__negdi2);
EXPORT_SYMBOL(__ucmpdi2);
EXPORT_SYMBOL(__udivdi3);
EXPORT_SYMBOL(__udivmoddi4);
EXPORT_SYMBOL(__udivsi3);
EXPORT_SYMBOL(__umoddi3);
EXPORT_SYMBOL(__umodsi3);

EXPORT_SYMBOL(h8300_reserved_gpio);
EXPORT_SYMBOL(h8300_free_gpio);
EXPORT_SYMBOL(h8300_set_gpio_dir);


text:
import React, { useState, useContext } from 'react'
import { compose } from 'redux'
import PropTypes from 'prop-types'
import { asField } from 'informed'
import { ThemeContext } from 'styled-components'
import { Input as BaseInput } from '@rebass/forms/styled-components'
import { extractSpaceProps } from 'themes/util'
import { withInputValidation } from 'hocs'
import { useAutoFocus } from 'hooks'
import Field from './Field'
import { mapDefaultBorderColor, mapFocusBorderColor } from './util'

const Input = props => {
  const {
    className,
    description,
    field,
    fieldApi,
    fieldState,
    forwardedRef,
    hasMessage,
    hasMessageSpacer,
    initialValue,
    isDisabled,
    isReadOnly,
    isRequired,
    justifyContent,
    label,
    maxLength,
    minLength,
    onChange,
    onBlur,
    onFocus,
    prefix,
    suffix,
    sx,
    tooltip,
    type,
    variant,
    willAutoFocus,
    ...rest
  } = props
  const [hasFocus, setFocus] = useState(false)
  const [spaceProps, otherProps] = extractSpaceProps(rest)
  const theme = useContext(ThemeContext)
  const { setValue, setTouched } = fieldApi
  const { value, maskedValue, error, asyncError } = fieldState

  useAutoFocus(forwardedRef, willAutoFocus)

  const getValue = () => {
    if (typeof value === 'undefined') {
      return initialValue
    }
    return !maskedValue && maskedValue !== 0 ? '' : maskedValue
  }

  const isHidden = type !== 'hidden'
  const fieldDescription = isHidden && description
  const fieldLabel = isHidden && label
  const fieldError = isHidden && hasMessage && (error || asyncError)

  return (
    <Field
      {...spaceProps}
      className={className}
      description={fieldDescription}
      error={fieldError}
      field={field}
      hasFocus={hasFocus}
      hasMessageSpacer={hasMessageSpacer}
      isDisabled={isDisabled}
      isReadOnly={isReadOnly}
      isRequired={isRequired}
      justifyContent={justifyContent}
      label={fieldLabel}
      tooltip={tooltip}
    >
      {prefix}
      <BaseInput
        disabled={isDisabled}
        maxLength={maxLength}
        minLength={minLength}
        name={field}
        onBlur={e => {
          // set touched to true to enforce validity highlight
          setTouched(true)
          // Make the state aware that the element is no longer focused.
          setFocus(false)
          if (onBlur) {
            onBlur(e)
          }
        }}
        onChange={e => {
          setValue(e.target.value)
          if (onChange) {
            onChange(e)
          }
        }}
        onFocus={e => {
          // Make the state aware that the element is now focused.
          setFocus(true)
          if (onFocus) {
            onFocus(e)
          }
        }}
        pl={prefix ? 35 : null}
        readOnly={isReadOnly}
        required={isRequired}
        sx={{
          borderColor: mapDefaultBorderColor(props, theme),
          '&:not([read-only]):not([disabled]):focus': {
            borderColor: mapFocusBorderColor(props, theme),
          },
          ...sx,
        }}
        type={type}
        value={getValue()}
        {...otherProps}
        ref={forwardedRef}
        tx="forms.input"
        variant={variant}
      />
      {suffix}
    </Field>
  )
}

Input.propTypes = {
  className: PropTypes.string,
  description: PropTypes.node,
  field: PropTypes.string.isRequired,
  fieldApi: PropTypes.object.isRequired,
  fieldState: PropTypes.object.isRequired,
  forwardedRef: PropTypes.object,
  hasMessage: PropTypes.bool,
  hasMessageSpacer: PropTypes.bool,
  highlightOnValid: PropTypes.bool,
  initialValue: PropTypes.string,
  isDisabled: PropTypes.bool,
  isReadOnly: PropTypes.bool,
  isRequired: PropTypes.bool,
  justifyContent: PropTypes.string,
  label: PropTypes.node,
  maxLength: PropTypes.number,
  minLength: PropTypes.number,
  onBlur: PropTypes.func,
  onChange: PropTypes.func,
  onFocus: PropTypes.func,
  prefix: PropTypes.node,
  suffix: PropTypes.node,
  sx: PropTypes.object,
  tooltip: PropTypes.string,
  type: PropTypes.string,
  variant: PropTypes.string,
  willAutoFocus: PropTypes.bool,
}

Input.defaultProps = {
  hasMessage: true,
  highlightOnValid: true,
  initialValue: '',
  variant: 'normal',
}

const BasicInput = Input

export { BasicInput }

export default compose(withInputValidation, asField)(BasicInput)


text:
source /etc/profile

# use grub2
cat <<DATAEOF >> "$chroot/etc/portage/package.keywords"
sys-boot/grub:2
DATAEOF

# install grub
chroot "$chroot" emerge grub

# tweak timeout
chroot "$chroot" sed -i "s/GRUB_TIMEOUT=.*/GRUB_TIMEOUT=1/g" /etc/default/grub

# make the disk bootable
chroot "$chroot" /bin/bash <<DATAEOF
source /etc/profile && \
env-update && \
grep -v rootfs /proc/mounts > /etc/mtab && \
mkdir /boot/grub2 && \
grub2-mkconfig -o /boot/grub2/grub.cfg && \
grub2-install --no-floppy /dev/sda
DATAEOF


text:
package org.wte4j.examples.showcase.client;

import com.google.gwt.resources.client.ClientBundle;
import com.google.gwt.resources.client.ImageResource;

public interface Wte4jShowcaseResources extends ClientBundle {
	@Source("images/loading-spinner.gif")
	ImageResource loadingSpinner();
}


text:
package com.machinomy.bergae

import java.util.UUID

import cats.data.Xor
import com.machinomy.bergae.crypto._
import com.machinomy.bergae.storage.Storage
import io.circe._
import io.circe.generic.JsonCodec
import io.circe.syntax._

import scala.util.Try

private[bergae] object Messaging {
  @JsonCodec
  sealed trait Payload
  case class Nop(height: Long, approve: Set[Sha256Hash] = Set.empty[Sha256Hash]) extends Payload
  case class Update(height: Long, uuid: UUID, operation: String, approve: Set[Sha256Hash] = Set.empty[Sha256Hash]) extends Payload

  object Payload

  case class Signed(payload: Payload, pub: ECPub, signature: ECSignature) {
    lazy val txid: Sha256Hash = Digest[Sha256Hash](jsonString)
    lazy val jsonString: String = toJsonString(this)
  }

  def signed(crypto: Crypto, payload: Payload, key: ECKey): Signed = {
    val payloadBytes = payload.asJson.noSpaces.getBytes
    val signature = crypto.sign(payloadBytes, key)
    Signed(payload, key.pub, signature)
  }

  def toJsonString(signed: Signed): String = {
    signed.asJson.noSpaces
  }

  def fromJsonString(string: String): Option[Signed] = {
    parser.decode[Signed](string).toOption
  }

  implicit val encodeUUID: Encoder[UUID] = Encoder.encodeString.contramap { uuid =>
    uuid.toString
  }

  implicit val decodeUUID: Decoder[UUID] = Decoder.decodeString.map { string =>
    UUID.fromString(string)
  }

  implicit val encodedSha256Hash: Encoder[Sha256Hash] = Encoder.encodeString.contramap { hash =>
    Hex.encode(hash.bytes)
  }

  implicit val decodeSha256Hash: Decoder[Sha256Hash] = Decoder.decodeString.map { string =>
    Sha256Hash(Hex.decode(string).toArray)
  }

  implicit val encodeSigned = new Encoder[Signed] {
    override def apply(a: Signed): Json = {
      val fields: Map[String, Json] = Map(
        "payload" -> a.payload.asJson,
        "pub" -> implicitly[Encoder[ECPub]].apply(a.pub),
        "sig" -> implicitly[Encoder[ECSignature]].apply(a.signature)
      )
      Json.fromFields(fields)
    }
  }

  implicit val decodeSigned: Decoder[Signed] = Decoder.decodeJsonObject.emapTry { jsonObject =>
    val fields = jsonObject.toMap
    val payloadTry: Try[Payload] = fields("payload").as[Payload].toTry
    val pubTry: Try[ECPub] = fields("pub").as[String].toTry.map(s => ECPub(Base58Check.decode(s)._2))
    val sigTry: Try[ECSignature] = fields("sig").as[String].toTry.map(s => ECSignature.decode(Base58Check.decode(s)._2))
    for {
      payload <- payloadTry
      pub <- pubTry
      sig <- sigTry
    } yield Signed(payload, pub, sig)
  }

  implicit val encodeECPub: Encoder[ECPub] = Encoder.encodeString.contramap { pub =>
    Base58Check.encode(Base58Check.Prefix.PublicKey, pub.toByteArray)
  }

  implicit val decodeECPub: Decoder[ECPub] = Decoder.decodeString.emap { string =>
    Xor.catchNonFatal(ECPub(Base58Check.decode(string)._2)).leftMap(_ => "ECPub")
  }

  implicit val encodeECSignature: Encoder[ECSignature] = Encoder.encodeString.contramap { signature =>
    val bytes = ECSignature.encode(signature)
    Base58Check.encode(Base58Check.Prefix.Signature, bytes)
  }

  implicit val decodeECSignature: Decoder[ECSignature] = Decoder.decodeString.emap { string =>
    Xor.catchNonFatal(ECSignature.decode(Base58Check.decode(string)._2)).leftMap(_ => "ECSignature")
  }
}


text:
package fi.ozzi.tapsudraft.resource.model;

import fi.ozzi.tapsudraft.model.OwnershipType;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.NonNull;

import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import java.util.List;

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class OwnershipAddRequest {

  @NonNull
  private String username;
  @NonNull
  private String division;
  @NonNull
  @Enumerated(EnumType.STRING)
  private OwnershipType type;
  @NonNull
  private List<OwnershipDto> ownerships;

}


text:
<?php
/**
 * Created by PhpStorm.
 * User: hebidu
 * Date: 15/7/24
 * Time: 16:32
 */

namespace Bluenow\Api;

use Bluenow\Model\BicyleDataModel;
use Common\Api\Api;

class BicyleDataApi extends Api {

    /**
     *
     * 运动天数
     */
    const SPORTS_DAY = "Bluenow/BicyleData/sportsDay";
    /**
     *
     * 累加里程
     */
    const SUM_DISTANCE = "Bluenow/BicyleData/sum_distance";
    /**
     *
     * 累加时间
     */
    const SUM_TIME = "Bluenow/BicyleData/sum_time";

    /**
     *
     * 累加卡路里
     */
    const SUM_CALORIE = "Bluenow/BicyleData/sum_calorie";

    /**
     *
     * 统计最好的3个成绩
     */
    const BEST_RESULT = "Bluenow/BicyleData/bestResult";
    /**
     *
     * 统计最大
     */
    const MAX = "Bluenow/BicyleData/max";
    /**
     *
     * 每月数据
     */
    const MONTHLY_DATA = "Bluenow/BicyleData/monthlyData";
    /**
     *
     * 统计数目
     */
    const COUNT = "Bluenow/BicyleData/count";
    /**
     *
     * 删除
     */
    const DELETE = "Bluenow/BicyleData/delete";
    /**
     *
     * 新增一条数据,根据ID
     */
    const ADD = "Bluenow/BicyleData/add";
    /**
     *
     * 获取一条数据,根据ID
     */
    const GET_INFO = "Bluenow/BicyleData/getInfo";
    /**
     *
     * 保存,根据ID
     */
    const SAVE_BY_ID = "Bluenow/BicyleData/saveByID";
    /**
     *
     * 保存
     */
    const SAVE = "Bluenow/BicyleData/save";
    /**
     *
     * 分页获取
     */
    const QUERY = "Bluenow/BicyleData/query";
    /**
     *
     * 不分页获取
     */
    const QUERY_NO_PAGING = "Bluenow/BicyleData/queryNoPaging";

    /**
     * 抽象方法,用于设置模型实例
     */
    protected function _init()
    {
        $this->model = new BicyleDataModel();
    }

    public function query($map = null, $page = array('curpage'=>0,'size'=>10), $order = false) {
        $query = $this->model;
        if(!is_null($map)){
            $query = $query->where($map);
        }
        if(!($order === false)){
            $query = $query->order($order);
        }
        if(!($fields === false)){
            $query = $query->field($fields);
        }
        $list = $query -> page($page['curpage'] . ',' . $page['size']) -> select();

        if ($list === false) {
            $error = $this -> model -> getDbError();
            return $this -> apiReturnErr($error);
        }

        $count = $this -> model -> where($map) -> count();

        return $this -> apiReturnSuc(array("count" => $count, "list" => $list));
    }

    public function sportsDay($uid){
        $result = $this->model->query("select count(*) as sportsday from(SELECT upload_year FROM itboye_bicyle_data where `uid` = ".$uid." group by upload_year,upload_month,upload_day) as tmp");
        if($result === false){
            return $this->apiReturnErr($this->model->getDbError());
        }else{
            return $this->apiReturnSuc($result);
        }
    }

    public function sum_distance($uid){
        $result = $this->model->query("select sum(sum_max_distance) as sum_max_distance from ( SELECT max(total_distance) as sum_max_distance FROM itboye_bicyle_data where `uid` = ".$uid." group by upload_day,upload_year,upload_month ) as tmp");
        if($result === false){
            return $this->apiReturnErr($this->model->getDbError());
        }else{
            return $this->apiReturnSuc($result);
        }
    }

    public function sum_time($uid){
        $result = $this->model->query("select sum(sum_max_time) as sum_max_time from ( SELECT max(cost_time) as sum_max_time FROM itboye_bicyle_data where `uid` = ".$uid." group by upload_day,upload_year,upload_month ) as tmp");
        if($result === false){
            return $this->apiReturnErr($this->model->getDbError());
        }else{
            return $this->apiReturnSuc($result);
        }
    }

    public function sum_calorie($uid){
        $result = $this->model->query("select sum(sum_max_calorie) as sum_max_calorie from ( SELECT max(calorie) as sum_max_calorie FROM itboye_bicyle_data where `uid` = ".$uid." group by upload_day,upload_year,upload_month ) as tmp");
        if($result === false){
            return $this->apiReturnErr($this->model->getDbError());
        }else{
            return $this->apiReturnSuc($result);
        }
    }

    public function bestResult($where){
        $result = $this->model->field('max(total_distance) as best_distance,max(calorie) as best_calorie,max(cost_time) as best_cost_time')->where($where)->select();
//        addLog("bestResult",$this->model->getLastSql(),"post", json_encode($where));

        if($result === false){
            return $this->apiReturnErr($this->model->getDbError());
        }else{
            return $this->apiReturnSuc($result);
        }
    }

    public function max($where,$field){
        $result = $this->model->where($where)->max($field);

        if($result === false){
            return $this->apiReturnErr($this->model->getDbError());
        }else{
            return $this->apiReturnSuc($result);
        }
    }

    public function monthlyData($where){

        $list = $this->model->field("max(calorie) as max_calorie,upload_day")->where($where)->group("upload_day")->order("upload_day asc")->select();
//        dump($list);
//        exit();
        if($list === false){
           return $this->apiReturnErr($this->model->getDbError());
        }else{
           return $this->apiReturnSuc($list);
        }
    }

}


text:
//
//  TTNetworkInstance.h
//  TTArchitecture
//
//  Created by jyzx101 on 2017/8/28.
//  Copyright © 2017年 elliot. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface TTNetworkInstance : NSObject

+ (instancetype)sharedInstance;

/**
 禁止使用init初始化
 */
- (instancetype)init __attribute__((unavailable("请使用sharedInstance初始化网络工具单例")));

/**取消所有网络请求*/
+ (void)cancelAllOperations;

/**
 *   监听网络状态的变化
 */
+ (void)startNetworkStatusMonitor;

/**
 在主线程实时获取是否有网络
 */
+ (BOOL)isNetReachable;

+ (BOOL)isWWANNetwork;

+ (BOOL)isWiFiNetwork;

/**
 GET请求

 @param url 请求接口
 @param parameters 请求参数
 @param success 请求成功block
 @param failure 请求失败block
 */
- (void)GET:(NSString *)url
 Parameters:(NSDictionary *)parameters
    Success:(void (^)(id responseObj))success
    Failure:(void (^)(NSError *error))failure;

/**
 *  GET请求,添加laoding hud
 */
- (void)hudGET:(NSString *)url
    Parameters:(NSDictionary *)parameters
       Success:(void(^)(id responseObj))success
       Failure:(void (^)(NSError *error))failure;

/**
 POST 请求

 @param url 请求接口
 @param parameters 请求参数
 @param success 请求成功block
 @param failure 请求失败block
 */
- (void)POST:(NSString *)url
  Parameters:(NSDictionary *)parameters
     Success:(void (^)(id responseObj))success
     Failure:(void (^)(NSError *error))failure;

/**
 *  POST请求,添加laoding hud
 */
- (void)hudPOST:(NSString *)url
     Parameters:(NSDictionary *)parameters
        Success:(void(^)(id responseObj))success
        Failure:(void(^)(NSError *error))failure;

/**
 POST JSON字符串请求

 @param url 请求接口
 @param body 请求json
 @param success 请求成功block
 @param failure 请求失败block
 */
- (void)postJsonStringUrl:(NSString *)url
                     body:(NSDictionary *)body
                  Success:(void(^)(NSURLResponse *response, id responseObj))success
                  Failure:(void(^)(NSError *error))failure;

/**
 *  POST JSON字符串请求,添加laoding hud
 */
- (void)hudPostJsonStringUrl:(NSString *)url
                        body:(NSDictionary *)body
                     Success:(void(^)(NSURLResponse *response, id responseObject))success
                     Failure:(void(^)(NSError *error))failure;

/**
 下载文件

 @param downloadUrl 下载地址
 @param filePath 下载成功后文件存储路径
 @param completion 下载完成block
 @param failure 下载失败blcok
 */
- (void)hudDownloadFileWithUrl:(NSString *)downloadUrl
                      filePath:(NSString *)filePath
                    completion:(void(^)(NSString *filePath))completion
                       Failure:(void(^)(NSError *error))failure;

/**
 下载JSON数据

 @param downloadUrl 下载地址
 @param success 下载成功block
 @param failure 下载失败blcok
 */
- (void)downloadDataFromUrl:(NSString *)downloadUrl
                    Success:(void (^)(id responseObj))success
                    Failure:(void (^)(NSError *error))failure;

@end


text:
title: "Pretty sunset"
excerpt: "PaperFaces portrait of @hergimerc drawn with Paper by 53 on an iPad."
image:
  path: &image /assets/images/paperfaces-hergimerc-twitter-lg.jpg
  feature: *image
  thumb: /assets/images/paperfaces-hergimerc-twitter-150.jpg
tags: [portrait, illustration, Paper by 53]
---

PaperFaces portrait of [@hergimerc](http://twitter.com/hergimerc).

{% include boilerplate/paperfaces.md %}


text:
using namespace DirectX;
using namespace std;

extern "C" {
	LPBYTE g_cameraStructAddress = nullptr;
	LPBYTE g_ownCoordinates = nullptr;
	LPBYTE g_ownAngles = nullptr;
}

namespace IGCS::GameSpecific::CameraManipulator
{
	static DWORD _originalLookData[3];	// game uses 3 shorts, aligned on dword addresses.
	static float _originalCoordsData[3];
	static DWORD _originalCinematicsLookData[3];	// game uses 3 shorts, aligned on dword addresses.
	static float _originalCinematicsCoordsData[3];
	static DWORD _ownLookData[3];
	static float _ownCoordsData[3];

	// Resets the FOV to the default
	void resetFoV()
	{
		float* fovInMemory = reinterpret_cast<float*>(g_cameraStructAddress + FOV_IN_CAMERA_STRUCT_OFFSET);
		*fovInMemory = DEFAULT_FOV_DEGREES;
		g_fovValue = DEFAULT_FOV_DEGREES;
	}

	// changes the FoV with the specified amount
	void changeFoV(float amount)
	{
		float* fovInMemory = reinterpret_cast<float*>(g_cameraStructAddress + FOV_IN_CAMERA_STRUCT_OFFSET);
		*fovInMemory += amount;
		g_fovValue += amount;
	}

	XMFLOAT3 getCurrentCameraCoords()
	{
		// read from our own struct.
		return XMFLOAT3(_ownCoordsData[0], _ownCoordsData[1], _ownCoordsData[2]);
	}

	// newCoords are the new coordinates for the camera in worldspace. Angles given are the rotation angles stored in the camera struct
	void writeNewCameraValuesToGameData(XMFLOAT3 newCoords, float pitch, float yaw, float roll)
	{
		g_ownCoordinates = (uint8_t*)(float*)_ownCoordsData;
		g_ownAngles = (uint8_t*)(DWORD*)_ownLookData;

		_ownCoordsData[0] = newCoords.x;
		_ownCoordsData[1] = newCoords.y;
		_ownCoordsData[2] = newCoords.z;

		// angles in the game are a ushort. Angles in our camera are 0-2PI. So 2PI is 0x65535. They're aligned on DWORD boundaries.
		_ownLookData[0] = DWORD(((pitch / XM_2PI) * 65535.0f) + 0.5) & 0x0000FFFF;
		_ownLookData[1] = DWORD(((yaw / XM_2PI) * 65535.0f) + 0.5) & 0x0000FFFF;
		_ownLookData[2] = DWORD(((roll / XM_2PI) * 65535.0f) + 0.5) & 0x0000FFFF;
	}

	// Waits for the interceptor to pick up the camera struct address. Should only return if address is found
	void waitForCameraStructAddresses(LPBYTE hostImageAddress)
	{
		Console::WriteLine("Waiting for camera struct interception...");
		while (nullptr == g_cameraStructAddress)
		{
			Sleep(100);
		}
		Console::WriteLine("Camera found.");

#ifdef _DEBUG
		cout << "Camera struct address: " << hex << (void*)g_cameraStructAddress << endl;
#endif
	}

	// should restore the camera values in the camera structures to the cached values. This assures the free camera is always enabled at the original camera location.
	void restoreOriginalCameraValues()
	{
		DWORD* lookInMemory = (DWORD*)(g_cameraStructAddress + LOOK_DATA_IN_CAMERA_STRUCT_OFFSET);
		float* coordsInMemory = reinterpret_cast<float*>(g_cameraStructAddress + CAMERA_COORDS_IN_CAMERA_STRUCT_OFFSET);
		memcpy(lookInMemory, _originalLookData, 3 * sizeof(DWORD));
		memcpy(coordsInMemory, _originalCoordsData, 3 * sizeof(float));
	}

	void cacheOriginalCameraValues()
	{
		DWORD* lookInMemory = (DWORD*)(g_cameraStructAddress + LOOK_DATA_IN_CAMERA_STRUCT_OFFSET);
		float* coordsInMemory = reinterpret_cast<float*>(g_cameraStructAddress + CAMERA_COORDS_IN_CAMERA_STRUCT_OFFSET);
		memcpy(_originalLookData, lookInMemory, 3 * sizeof(DWORD));
		memcpy(_originalCoordsData, coordsInMemory, 3 * sizeof(float));
		// copy the coordinates also in our own coordinates struct as we're going to read / write to that, not to main mem.
		memcpy(_ownCoordsData, coordsInMemory, 3 * sizeof(float));
	}
}


text:
@interface PodsDummy_XTWebView : NSObject
@end
@implementation PodsDummy_XTWebView
@end


text:
<?php
namespace universal;

/**
 * Adaptable class consuming properties and methods of given classes,
 * giving option to combine more classes toghether as multi-inheritance in one
 * generation
 *
 * @author Jaroslav Týc
 */
class MorphClass extends IterableTycClass {

	public function __construct(){

	}

	public function addPatternClass($classInstance){
		if (!is_object($classInstance)) {
			throw new Exception('Pattern class has to be an instance of class');
		}
		var_dump($classInstance); //public only or all variables and methods?
		parent::__construct(array());
	}
}


text:
package org.apache.harmony.crypto.tests.javax.crypto;

import java.security.AlgorithmParameters;
import java.security.Key;
import java.security.SecureRandom;
import java.util.Arrays;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;

public class Cipher_Impl1Test extends junit.framework.TestCase {

    static Key cipherKey;
    final static String algorithm = "DESede";
    final static int keyLen = 168;

    static {
        try {
            KeyGenerator kg = KeyGenerator.getInstance(algorithm);
            kg.init(keyLen, new SecureRandom());
            cipherKey = kg.generateKey();
        } catch (Exception e) {
            fail("No key " + e);
        }
    }

    /**
     * @tests javax.crypto.Cipher#getIV()
     * @tests javax.crypto.Cipher#init(int, java.security.Key,
     *        java.security.AlgorithmParameters)
     */
    public void test_getIV() throws Exception {
        /*
         * If this test is changed, implement the following:
         * test_initILjava_security_KeyLjava_security_AlgorithmParameters()
         */

        SecureRandom sr = new SecureRandom();
        Cipher cipher = null;

        byte[] iv = new byte[8];
        sr.nextBytes(iv);
        AlgorithmParameters ap = AlgorithmParameters.getInstance(algorithm);
        ap.init(iv, "RAW");

        cipher = Cipher.getInstance(algorithm + "/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, cipherKey, ap);

        byte[] cipherIV = cipher.getIV();

        assertTrue("IVs differ", Arrays.equals(cipherIV, iv));
    }

    /**
     * @tests javax.crypto.Cipher#getParameters()
     * @tests javax.crypto.Cipher#init(int, java.security.Key,
     *        java.security.AlgorithmParameters, java.security.SecureRandom)
     */
    public void test_getParameters() throws Exception {

        /*
         * If this test is changed, implement the following:
         * test_initILjava_security_KeyLjava_security_AlgorithmParametersLjava_security_SecureRandom()
         */

        SecureRandom sr = new SecureRandom();
        Cipher cipher = null;

        byte[] apEncoding = null;

        byte[] iv = new byte[8];
        sr.nextBytes(iv);

        AlgorithmParameters ap = AlgorithmParameters.getInstance("DESede");
        ap.init(iv, "RAW");
        apEncoding = ap.getEncoded("ASN.1");

        cipher = Cipher.getInstance(algorithm + "/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, cipherKey, ap, sr);

        byte[] cipherParmsEnc = cipher.getParameters().getEncoded("ASN.1");
        assertTrue("Parameters differ", Arrays.equals(apEncoding,
                cipherParmsEnc));
    }
}


text:
package fiskinfoo.no.sintef.fiskinfoo.View.MaterialExpandableList;

import android.support.v7.widget.RecyclerView;
import android.view.View;

public class ChildViewHolder extends RecyclerView.ViewHolder {

    private View mClickableView;
    /**
     * Default constructor.
     *
     * @param itemView
     */
    public ChildViewHolder(View itemView) {
        super(itemView);
        mClickableView = itemView;
    }
}


text:
#ifndef __TURNPICTURES_H__
#define __TURNPICTURES_H__

//#include <e32def.h>
#include "RouteEnums.h"
#include "RouteInfo.h"

//Enum for possible turn actions
enum TPictures{
   E3WayLeft,
   E3WayRight,
   E3WayTeeLeft,
   E3WayTeeRight,
   E4WayLeft,
   E4WayRight,
   E4WayStraight,
   EEnterHighWay,
   EEnterMainRoad,
   EExitHighWay,
   EExitHighWayRight,
   EExitHighWayLeft,
   EExitMainRoad,
   EExitMainRoadRight,
   EExitMainRoadLeft,
   EFerry,
   EFinishArrow,
   EFinishFlag,
   EHighWayStraight,
   EKeepLeft,
   EKeepRight,
   ELeftArrow,
   EMultiWayRdb,
   EOffTrack,
   EWrongDirection,
   EPark,
   ERdbLeft,
   ERdbRight,
   ERdbStraight,
   ERdbUTurn,
   ERightArrow,
   EStart,
   EStraight,
   EStraightArrow,
   EUTurn,
   EDetour,
   ESpeedCam,
   ENoPicture
};

/**
 * @class TTurnPictures
 *
 * @discussion Class for finding the right turn picture to display.
 */
class TTurnPictures
{

public:

   /**
    * Returns the correct action to display,
    * depending of the values
    */
   static TPictures GetPicture( const enum isab::RouteAction aAction,
                                const enum isab::RouteCrossing aCrossing,
                                const TUint aDistance,
                                const TBool aHighway );

   /**
    * Returns the index in the mbm file
    * for the picture of the next action.
    */
   static TInt GetTurnPicture( const TPictures aTurn,
                               const TBool aLeftSide );

   /**
    * Returns the index in the mbm file
    * for the picture of the following action.
    */
   static TInt GetMediumTurnPicture( const TPictures aTurn,
                                     const TBool aLefSide );

   /**
    * Returns the index in the mbm file
    * for the picture of the following action.
    */
   static void GetSmallTurnPicture( const TPictures aTurn,
                                    const TBool aLefSide,
                                    TInt &mbmIndex,
                                    TInt &mbmMaskIndex );

   /**
    * Returns the index in the mbm file
    * for the picture of the exit number.
    */
   static TInt GetExit( const TInt exit );

   static TInt GetExitMask( const TInt exit );

};

#endif // __TURNPICTURES_H__


text:
package com.ap.github.kishorsutar.androidsinganturepad.utils;

/**
 * Represent a point as it would be in the generated SVG document.
 */
class SvgPoint {

    final Integer x, y;

    public SvgPoint(TimedPoint point) {
        // one optimisation is to get rid of decimals as they are mostly non-significant in the
        // produced SVG image
        x = Math.round(point.x);
        y = Math.round(point.y);
    }

    public SvgPoint(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public String toAbsoluteCoordinates() {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(x);
        if (y >= 0) {
            stringBuilder.append(" ");
        }
        stringBuilder.append(y);
        return stringBuilder.toString();
    }

    public String toRelativeCoordinates(final SvgPoint referencePoint) {
        return (new SvgPoint(x - referencePoint.x, y - referencePoint.y)).toString();
    }

    @Override
    public String toString() {
        return toAbsoluteCoordinates();
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        SvgPoint svgPoint = (SvgPoint) o;

        if (!x.equals(svgPoint.x)) return false;
        return y.equals(svgPoint.y);

    }

    @Override
    public int hashCode() {
        int result = x.hashCode();
        result = 31 * result + y.hashCode();
        return result;
    }
}


text:
{% extends "base.html" %}
{% load i18n %}
{% block title %}{% trans "Instance Admin Password" %}{% endblock %}

{% block main %}
  {% include "admin/instances/_decryptpassword.html" %}
{% endblock %}


text:
<?php

namespace PhpGitHooks\Module\PhpUnit\Infrastructure\Tool;

use PhpGitHooks\Module\PhpUnit\Model\GuardCoverageFileWriterInterface;

class GuardCoverageFileWriter implements GuardCoverageFileWriterInterface
{
    /**
     * @param float $data
     */
    public function write($data)
    {
        file_put_contents('.guard_coverage', $data);
    }
}


text:
title: Community
---

<!Doctype html>

{% include head-header.html %}

Community

 We do have a pretty strong community

{% include footer.html %}


text:
package Security.auth.demo2;
import java.io.IOException;
import java.security.Principal;
import java.util.Iterator;
import java.util.Map;
import javax.security.auth.Subject;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.auth.login.FailedLoginException;
import javax.security.auth.login.LoginException;
import javax.security.auth.spi.LoginModule;
/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Defias
 * Date: 2018-05
 */

public class DemoLoginModule implements LoginModule {
    private Subject subject;
    private CallbackHandler callbackHandler;
    private boolean success = false;
    private String user;
    private String password;

    @Override
    public void initialize(Subject subject, CallbackHandler callbackHandler, Map<String, ?> sharedState, Map<String, ?> options) {
        this.subject = subject;
        this.callbackHandler = callbackHandler;
    }

    @Override
    public boolean login() throws LoginException {
        NameCallback nameCallback = new NameCallback("请输入用户名");
        PasswordCallback passwordCallback = new PasswordCallback("请输入密码", false);
        Callback[] callbacks = new Callback[]{nameCallback, passwordCallback};
        try {
            //执行回调,回调过程中获取用户名与密码
            callbackHandler.handle(callbacks);
            //得到用户名与密码
            user = nameCallback.getName();
            password = new String(passwordCallback.getPassword());
        } catch (IOException | UnsupportedCallbackException e) {
            success = false;
            throw new FailedLoginException("用户名或密码获取失败");
        }
        //为简单起见认证条件写死
        if(user.length()>3 && password.length()>3) {
            success = true;//认证成功
        }
        return true;
    }

    @Override
    public boolean commit() throws LoginException {
        if(!success) {
            return false;
        } else {
            //如果认证成功则得subject中添加一个Principal对象
            //这样某身份用户就认证通过并登录了该应用,即表明了谁在执行该程序
            this.subject.getPrincipals().add(new DemoPrincipal(user));
            return true;
        }
    }

    @Override
    public boolean abort() throws LoginException {
        logout();
        return true;
    }

    @Override
    public boolean logout() throws LoginException {
        //退出时将相应的Principal对象从subject中移除
        Iterator<Principal> iter = subject.getPrincipals().iterator();
        while(iter.hasNext()) {
            Principal principal = iter.next();
            if(principal instanceof DemoPrincipal) {
                if(principal.getName().equals(user)) {
                    iter.remove();
                    break;
                }
            }
        }
        return true;
    }
}


text:
import { ProjectActivity } from './projectActivity';

export { ProjectActivity };


text:
/**
 * A namespace containing utils for the rest of the elasticlunr library
 */
export declare const utils: {
    warn: (message: string, ...args: any[]) => void;
    toString(obj: any): any;
};


text:
<?php get_header(); ?>

		<?php if (have_posts()): while (have_posts()) : the_post(); ?>

			<article class="collection-content" id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
				<?php the_content(); // Dynamic Content ?>

		<?php endwhile; ?>
		<?php else: ?>

<?php _e( 'Sorry, nothing to display.', 'html5blank' ); ?>

		<?php endif; ?>
		<?php while(has_sub_field("additional-content")): ?>
			<?php if(get_row_layout() == "tan-background"): // layout: Content ?>

					<?php the_sub_field("content"); ?>

				<?php endif; ?>
				<?php if(get_row_layout() == "white-background"): // layout: Content ?>

					<?php the_sub_field("content"); ?>

			<?php endif; ?>
		<?php endwhile; ?>

<?php get_footer(); ?>


text:
<?php

/**
 * @file
 * Contains \Drupal\Core\StringTranslation\Translator\TranslationInterface.
 */

namespace Drupal\Core\StringTranslation\Translator;

/**
 * Interface for objects capable of string translation.
 */
interface TranslatorInterface {

  /**
   * Retrieves English string to given language.
   *
   * @param string $langcode
   *   Language code to translate to.
   * @param string $string
   *   The source string.
   * @param string $context
   *   The string context.
   *
   * @return string|FALSE
   *   Translated string if there is a translation, FALSE if not.
   */
  public function getStringTranslation($langcode, $string, $context);

  /**
   * Resets translation cache.
   *
   * Since most translation systems implement some form of caching, this
   * provides a way to delete that cache.
   */
  public function reset();

}


text:
@interface HGFindFrameModel ()

@end

@implementation HGFindFrameModel

#pragma mark 设置广告栏的frame
-(void)setBannerModel:(HGFindBannerModel *)bannerModel
{
    _bannerModel=bannerModel;
    CGFloat bannerW=bannerModel.banner_pic.image_width;
    CGFloat bannerH=bannerModel.banner_pic.image_height;

    CGFloat logoH=cellW/bannerW*bannerH;

    _bannerF=CGRectMake(0, 0, cellW, logoH);
    _showF=_bannerF;
    _cellH=CGRectGetMaxY(_bannerF);

}
#pragma mark 设置显示商品的frame
-(void)setFindModel:(HGFindModel *)findModel
{
    _findModel=findModel;
    //1.设置图片的frame
    CGFloat imageX=0;
    CGFloat imageY=0;
    CGFloat imageW=cellW;
    CGFloat imageH=imageW;
    _imageF=CGRectMake(imageX, imageY, imageW, imageH);
    //2.设置商品的name
    CGFloat descX=VMargin;
    CGFloat descY=CGRectGetMaxY(_imageF)+VMargin;
    CGFloat descW=cellW-VMargin*2;

    NSString *shopname=[self subStrFromFitScreen:findModel.goods_name];

    CGSize finalSize=[shopname boundingRectWithSize:CGSizeMake(descW, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:HGfont(11)} context:nil].size;

    _descF=CGRectMake(descX, descY, descW, finalSize.height);
    //self.descLabel.frame=CGRectMake(descX, descY, descW, finalSize.height);
    //3.设置价格的frame
    CGFloat priceX=VMargin;
    CGFloat priceY=CGRectGetMaxY(_descF)+findLineMargin;

    CGSize priceSize=[findModel.goods_display_final_price  sizeWithAttributes:@{NSFontAttributeName:HGfont(14)}];

    _priceF=CGRectMake(priceX, priceY, priceSize.width+20, priceSize.height);

    //4.设置商品来源的位置
    CGFloat addressX=VMargin;
    CGFloat addressY=CGRectGetMaxY(_priceF)+findLineMargin;

    NSString *addressStr=[NSString stringWithFormat:@"%@ %@",findModel.group_info.country,findModel.group_info.city];
    CGSize addressSize=[addressStr sizeWithAttributes:@{NSFontAttributeName:HGfont(10)}];
    _addressF=CGRectMake(addressX, addressY,addressSize.width+20, addressSize.height);
    //5.设置showView的frame
    _cellH=CGRectGetMaxY(_addressF)+10;

    _showF=CGRectMake(0, 0, cellW, _cellH);

}

-(NSString*)subStrFromFitScreen:(NSString*)str
{
    NSString *tempStr=nil;
    if(ScreenWidth<=320){
        if(str.length>21){
            tempStr=[str substringToIndex:21];
        }else{
            tempStr=str;
        }

    }else if(ScreenWidth<=375 && ScreenWidth>320){
        if(str.length>28){
            tempStr=[str substringToIndex:28];
        }else{
            tempStr=str;
        }

    }else{
        if(str.length>32){
            tempStr=[str substringToIndex:32];
        }else{
            tempStr=str;
        }
    }

    return tempStr;
}

@end


text:
<bill session="110" type="hc" number="307" updated="2009-01-08T16:05:35-05:00">
	<status><vote2 date="1213934400" datetime="2008-06-20" where="s" result="pass" how="by Unanimous Consent" roll=""/></status>

	<introduced date="1204606800" datetime="2008-03-04"/>
	<titles>
		<title type="official" as="introduced">Expressing the sense of Congress that Members' Congressional papers should be properly maintained and encouraging Members to take all necessary measures to manage and preserve these papers.</title>
	</titles>
	<sponsor id="400047"/>
	<cosponsors>

	</cosponsors>
	<actions>
		<action date="1204606800" datetime="2008-03-04"><text>Referred to the House Committee on House Administration.</text></action>
		<action date="1204737840" datetime="2008-03-05T13:24:00-05:00"><text>Mr. Brady (PA) moved to suspend the rules and agree to the resolution.</text></action>
		<action date="1204737840" datetime="2008-03-05T13:24:00-05:00"><text>Considered under suspension of the rules.</text><reference label="consideration" ref="CR H1254-1255"/></action>
		<action date="1204737840" datetime="2008-03-05T13:24:00-05:00"><text>DEBATE - The House proceeded with forty minutes of debate on H. Con. Res. 307.</text></action>
		<vote date="1204738080" how="by voice vote" datetime="2008-03-05T13:28:00-05:00" where="h" type="vote" result="pass" ><text>On motion to suspend the rules and agree to the resolution Agreed to by voice vote.</text><reference label="text" ref="CR H1254"/></vote>
		<action date="1204779600" datetime="2008-03-06"><text>Received in the Senate and referred to the Committee on Homeland Security and Governmental Affairs.</text></action>
		<action date="1206676800" datetime="2008-03-28"><text>Committee on Homeland Security and Governmental Affairs referred to Subcommittee on Federal Financial Management, Government Information, Federal Services, and International Security.</text></action>
		<calendar date="1207800000" datetime="2008-04-10" ><text>Committee on Homeland Security and Governmental Affairs. Ordered to be reported without amendment favorably.</text></calendar>
		<action date="1208836800" datetime="2008-04-22"><text>Committee on Homeland Security and Governmental Affairs. Reported by Senator Lieberman without amendment and with a preamble. Without written report.</text></action>
		<calendar under="General Orders" number="705" date="1208836800" datetime="2008-04-22" calendar="Senate Legislative" ><text>Placed on Senate Legislative Calendar under General Orders. Calendar No. 705.</text></calendar>
		<vote date="1213934400" how="by Unanimous Consent" datetime="2008-06-20" where="s" type="vote2" result="pass" ><text>Resolution agreed to in Senate without amendment and with a preamble by Unanimous Consent.</text><reference label="consideration" ref="CR S5947"/></vote>
		<action date="1214193600" datetime="2008-06-23"><text>Message on Senate action sent to the House.</text></action>
	</actions>
	<committees>

	</committees>
	<relatedbills>

	</relatedbills>
	<subjects>

	</subjects>
	<amendments>

	</amendments>
	<summary>
	6/20/2008--Passed Senate without amendment. (This measure has not been amended since it was introduced. The summary of that version is repeated here.) Declares that it is the sense of Congress that: (1) Members' congressional papers should be properly maintained; (2) each Member of Congress should take all necessary measures to manage and preserve the Member's own congressional papers; and (3) each Member of Congress should be encouraged to arrange for the deposit or donation of the Member's own noncurrent congressional papers with a research institution properly equipped to care for them, and to make these papers available for educational purposes at a time the Member considers appropriate.<br/>
	</summary>
</bill>


text:
package at.dru.wicketblog.wicket.component;

import at.dru.wicketblog.model.AbstractEntity;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.IModel;

import javax.annotation.Nonnull;

public class EntityFormPanel<T extends AbstractEntity> extends Panel {

    private static final long serialVersionUID = 1L;

    private final Class<T> entityClass;
    private final IModel<T> entityFormModel;

    public EntityFormPanel(@Nonnull String id, @Nonnull IModel<T> entityFormModel, @Nonnull Class<T> entityClass) {
        super(id, entityFormModel);

        this.entityFormModel = entityFormModel;
        this.entityClass = entityClass;
    }

    @Override
    protected void onInitialize() {
        super.onInitialize();

        EntityForm<T> entityForm = new EntityForm<T>("form", entityFormModel, entityClass);
        composeForm(entityForm);
        add(entityForm);
    }

    protected void composeForm(@Nonnull EntityForm<T> entityForm) {
    }

}


text:
class TriggersController < ApplicationController

  def index

  end

  def destroy
    Trigger.find(params[:trigger_id]).destroy
    render nothing: true
  end

  def update
    puts trigger_params
    puts trigger_params
    @trigger = Trigger.find(params[:id])
    @trigger.message_text = trigger_params[:message_text]
    @trigger.save
    render partial: 'show.html'
  end

  def new
    @trigger = Trigger.new
  end

  def edit
    @trigger = Trigger.find(params[:id])
    render partial: 'edit.html'
  end

  def create
    @trigger = Trigger.new(trigger_params)
    @trigger.user_id = current_user.id
    @trigger.task = Task.find_by_method(params[:method])
    if @trigger.save
      render partial: "triggers/show.html", formats: :html
    else
      @error = "Looks like that trigger wasn't valid!"
      render partial: 'errors.html'
    end
  end

  def increase_durations
    @trigger = Trigger.find(params[:trigger_id])
    @trigger.duration_in_hours += 1
    @trigger.save
    render nothing: true
  end

  def decrease_durations
    @trigger = Trigger.find(params[:trigger_id])
    @trigger.duration_in_hours -= 1 unless @trigger.duration_in_hours < 2
    @trigger.save
    render nothing: true
  end

  private
  def trigger_params
    params.require(:trigger).permit(:id, :message_text, :duration_in_hours)
  end

end


text:
package org.sistcoop.socio.models;

import java.util.List;

import javax.ejb.Local;

import org.sistcoop.socio.provider.Provider;

@Local
public interface TitularProvider extends Provider {

    TitularModel create(CuentaPersonalModel cuentaPersonal, String tipoDocumento, String numeroDocumento);

    boolean remove(TitularModel titular);

    TitularModel findById(String id);

    List<TitularModel> findAll(CuentaPersonalModel cuentaPersonal);

}


text:
using System;
using System.Collections.Immutable;
using System.Linq;
using System.Reactive.Linq;
using Toggl.Core.Suggestions;
using Toggl.Core.UI.Collections;
using Toggl.Core.UI.ViewModels.MainLog;
using Toggl.Core.UI.ViewModels.MainLog.Identity;
using Toggl.Shared;

namespace Toggl.Core.UI.Extensions
{
    using MainLogSection = AnimatableSectionModel<MainLogSectionViewModel, MainLogItemViewModel, IMainLogKey>;

    public static class MainLogSectionExtensions
    {
        public static IObservable<IImmutableList<MainLogSection>> MergeToMainLogSections(
            this IObservable<IImmutableList<MainLogSection>> timeEntries,
            IObservable<IImmutableList<Suggestion>> suggestions,
            IObservable<bool> shouldShowRatingView,
            MainLogSection userFeedbackMainLogSection
        )
            => timeEntries
                .CombineLatest(suggestions, shouldShowRatingView, (te, s, r) => mergeMainLogItems(te, s, r, userFeedbackMainLogSection));

        private static IImmutableList<MainLogSection> mergeMainLogItems(
            IImmutableList<MainLogSection> timeEntries,
            IImmutableList<Suggestion> suggestions,
            bool shouldShowRatingView,
            MainLogSection userFeedbackMainLogSection)
        {
            if (suggestions.Count <= 0)
            {
                return shouldShowRatingView
                    ? timeEntries.Prepend(userFeedbackMainLogSection).ToImmutableList()
                    : timeEntries.ToImmutableList();
            }

            var suggestionList = suggestions.Select(suggestionToMainLogItem);
            var suggestionsHeaderViewModel = new SuggestionsHeaderViewModel(suggestions.Count > 1 ? Resources.WorkingOnThese : Resources.WorkingOnThis);
            var suggestionsSection = new MainLogSection(suggestionsHeaderViewModel, suggestionList);
            return shouldShowRatingView
                ? timeEntries.Prepend(userFeedbackMainLogSection).Prepend(suggestionsSection).ToImmutableList()
                : timeEntries.Prepend(suggestionsSection).ToImmutableList();
        }

        private static MainLogItemViewModel suggestionToMainLogItem(Suggestion suggestion, int position)
            => new SuggestionLogItemViewModel(position, suggestion);
    }
}