text:
var constructRangeQuery = function(lowerBound, upperBound){
  return {
    $gte:lowerBound,
    $lte:upperBound
  };
};

var constructFloorRangeQuery = function(val){
  if(val <= 0){
    return constructRangeQuery(val, 0);
  } else {
    return constructRangeQuery(0, val);
  }
};

// var constructAxisQuery = function(axis){
//   //TODO check this function
//   var range = 30;
//
//   if(axis + range > 180){
//     return {$or:[constructRangeQuery(0,(axis + range) % 180),
//       constructRangeQuery(axis - range,180)]};
//   }
//
//   if(axis - range < 0){
//     return {$or:[constructRangeQuery(0,axis + range),
//       constructRangeQuery(180 + (axis - range),180)]};
//   }
//   return constructRangeQuery((axis - range) % 180, (axis + range) % 180);
// };

var constructGlassesQuery = function(glasses){
  // var query = {$or:['leftRx.axis':constructAxisQuery()]};
  var range = 30;

  var query = {};

  if(glasses["leftRx.axis"] + range > 180){
    query.$or = [{'leftRx.axis':constructRangeQuery(0,(glasses["leftRx.axis"] + range) % 180)},
      {'leftRx.axis':constructRangeQuery(glasses["leftRx.axis"] - range,180)}];
  }
  else if(glasses["leftRx.axis"] - range < 0){
    query.$or = [{'leftRx.axis':constructRangeQuery(0,glasses["leftRx.axis"] + range)},
      {'leftRx.axis':constructRangeQuery(180 + (glasses["leftRx.axis"] - range), 180)}];
  } else{
    query['leftRx.axis'] = constructRangeQuery(glasses["leftRx.axis"] - range, glasses["leftRx.axis"]+ range);
  }

  query['leftRx.sphere'] = constructFloorRangeQuery(glasses['leftRx.sphere']);
  query['leftRx.cylinder'] = constructFloorRangeQuery(glasses['leftRx.cylinder']);

  query['rightRx.sphere'] = constructFloorRangeQuery(glasses['rightRx.sphere']);
  query['rightRx.cylinder'] = constructFloorRangeQuery(glasses['rightRx.cylinder']);

  if(glasses["rightRx.axis"] + range > 180){
    query.$or = [{'rightRx.axis':constructRangeQuery(0,(glasses["rightRx.axis"] + range) % 180)},
      {'rightRx.axis':constructRangeQuery(glasses["rightRx.axis"] - range,180)}];
  }
  else if(glasses["rightRx.axis"] - range < 0){
    query.$or = [{'rightRx.axis':constructRangeQuery(0,glasses["rightRx.axis"] + range)},
      {'rightRx.axis':constructRangeQuery(180 + (glasses["rightRx.axis"] - range), 180)}];
  } else{
    query['rightRx.axis'] = constructRangeQuery(glasses["rightRx.axis"] - range, glasses["rightRx.axis"]+ range);
  }

  return query;
}

if(Meteor.isServer){
  Meteor.startup(function(){
    Glasses.remove({'leftRx.sphere':0,'leftRx.cylinder':0,'leftRx.axis':0,
                    'rightRx.sphere':0,'rightRx.cylinder':0,'rightRx.axis':0});
  });

  glassesQuery = {};
  Meteor.methods({
    searchGlasses:function(query,idealGlasses){
      // inner product
      function innerProduct(a, b){
        return a.dot(b.trans()).data[0][0];
      }

      // norm function
      function norm(matrix) {
        m = matrix.data;
        var squared_sum = 0;
        for (i = 0; i < m[0].length; i++) {
          squared_sum += Math.pow(m[0][i], 2);
        }
        return Math.sqrt(squared_sum);
      }

      // calculates innerProduct(ideal, actual) / (norm(actual)*norm(ideal))
      function calcCosSim(idealMatrix, actualMatrix) {
        var innerProductValue = innerProduct(idealMatrix, actualMatrix);
        var idealMatrixNorm = norm(idealMatrix);
        var actualMatrixNorm = norm(actualMatrix);
        // avoids the edge case where denominator = 0;
        if (idealMatrixNorm == 0 && actualMatrixNorm == 0) {
          return 1;
        }
        else if (idealMatrixNorm == 0){
          return actualMatrixNorm;
        }
        // ignoring the glasses with all 0s parameters
        else if (actualMatrixNorm == 0) {
          return 0;
        }
        else {
          var cosSim = innerProductValue / (idealMatrixNorm * actualMatrixNorm);
          return Math.round(cosSim * 10000) / 10000;
        }
      }

      var linearAlgebra = Meteor.npmRequire('linear-algebra')(),     // initialise it
          Vector = linearAlgebra.Vector,
          Matrix = linearAlgebra.Matrix;

      var res = Glasses.find(query,{limit:10}).fetch();

      const SPH_WEIGHT = 100;
      const CYL_WEIGHT = 10;
      const AXIS_WEIGHT = 1;

      function getSimScore(actualGlasses) {
      	var weights = new Matrix([SPH_WEIGHT, SPH_WEIGHT, CYL_WEIGHT, CYL_WEIGHT, AXIS_WEIGHT, AXIS_WEIGHT]);

      	var idealMatrix = new Matrix(weights.mul(new Matrix([idealGlasses["rightRx.sphere"], idealGlasses["leftRx.sphere"], idealGlasses["rightRx.cylinder"], idealGlasses["leftRx.cylinder"], idealGlasses["rightRx.axis"], idealGlasses["leftRx.axis"]])).data[0]);
      	// var actualMatrix = new Matrix(weights.mul(new Matrix([actualGlasses["rightRx.sphere"], actualGlasses["leftRx.sphere"], actualGlasses["rightRx.cylinder"], actualGlasses["leftRx.cylinder"], actualGlasses["rightRx.axis"], actualGlasses["leftRx.axis"]])).data[0]);
        var actualMatrix = new Matrix(weights.mul(new Matrix([actualGlasses.rightRx.sphere, actualGlasses.leftRx.sphere, actualGlasses.rightRx.cylinder, actualGlasses.leftRx.cylinder, actualGlasses.rightRx.axis, actualGlasses.leftRx.axis])).data[0]);

        actualGlasses.cosSim = calcCosSim(idealMatrix, actualMatrix);

      	return actualGlasses;
      }

      res = res.map(getSimScore);
      res.sort(function(a,b) { return b.cosSim - a.cosSim});

      console.log(res);

      return res;
    }
  });
}

if (Meteor.isClient) {
  Session.set('glasses',[]);
  AutoForm.hooks({
    findGlass:{
      before:{
        update:function(doc){
          // We have to call the server bc minimongo derps out here
          // TODO fix when meteor gets updated
          var searchQuery = constructGlassesQuery(doc.$set);

          // console.log(query);

          Meteor.call('searchGlasses', searchQuery, doc.$set, function(err,res){
            console.log(res);
            Session.set('glasses',res);
          });

          this.result(false);
        }
      }
    }
  });

  Template.possibleGlasses.helpers({
    glasses:function(){
      return Session.get('glasses');
    },
    decimalToPercent:function(decimal) {
      console.log(decimal);
      return String(Math.round(decimal * 100)) + '%';
    }
  });

}

redpajama_set_name: RedPajamaGithub


text:
title 'Alpine Linux release'

alpine_version = input('alpine_version')
alpine_version_id = input('alpine_version_id')

control 'alpine-01' do
  impact 1.0
  title 'Check the Alpine Linux release'
  desc 'Ensure that the correct release of Alpine Linux is used.'

  describe os.name do
    it { should eq 'alpine' }
  end

  describe os.family do
    it { should eq 'linux' }
  end

  describe os.release do
    it { should eq alpine_version_id }
  end
end

# control 'alpine-02' do
#   impact 0.5
#   title 'Check the system is using a 64-bit kernel'
#   desc 'Ensure that Alpine Linux is running with a 64-bit kernel.'
#
#   describe os.arch do
#     it { should eq 'x86_64' }
#   end
#
#   describe command('uname -a | grep -o x86_64') do
#     its('exit_status') { should eq 0 }
#     its('stdout') { should match /^x86_64$/ }
#     its('stderr') { should eq '' }
#   end
# end

control 'alpine-03' do
  impact 1.0
  title 'The /etc/os-release file must exist'
  desc 'Check periodically the owner and permissions for /etc/os-release.'

  describe file('/etc/os-release') do
    it { should exist }
  end
end

control 'alpine-04' do
  impact 1.0
  title 'The /etc/os-release file must be the correct type'
  desc 'Check periodically the owner and permissions for /etc/os-release.'

  describe file('/etc/os-release') do
    it { should be_file }
  end

  describe file('/etc/os-release') do
    it { should_not be_pipe }
    it { should_not be_socket }
    it { should_not be_symlink }
    it { should_not be_mounted }
    it { should_not be_directory }
    it { should_not be_block_device }
    it { should_not be_character_device }
  end
end

control 'alpine-05' do
  impact 1.0
  title 'The /etc/os-release file must be owned by root'
  desc 'Ensure the owner of /etc/os-release is correctly set to root.'

  describe file('/etc/os-release') do
    it { should be_owned_by 'root' }
    its('owner') { should eq 'root' }
  end
end

control 'alpine-06' do
  impact 1.0
  title 'The /etc/os-release file must be group-owned by root'
  desc 'Ensure the group of /etc/os-release is correctly set to root.'

  describe file('/etc/os-release') do
    its('group') { should eq 'root' }
  end
end

control 'alpine-07' do
  impact 1.0
  title 'The /etc/os-release file must have mode 0644 or less permissive'
  desc 'Check periodically the owner and permissions for /etc/os-release.'

  describe file('/etc/os-release') do
    it { should be_writable.by 'owner' }
    it { should be_readable.by 'owner' }
    it { should be_readable.by 'group' }
    it { should be_readable.by 'other' }
    it { should_not be_writable.by 'group' }
    it { should_not be_writable.by 'other' }
    it { should_not be_executable.by 'owner' }
    it { should_not be_executable.by 'group' }
    it { should_not be_executable.by 'other' }
    its('mode') { should cmp '0644' }
  end
end

control 'alpine-08' do
  impact 1.0
  title 'The /etc/os-release file must contain the correct release'
  desc 'Check for the correct version of Alpine Linux from /etc/os-release.'

  describe file('/etc/os-release') do
    its('content') { should match /^NAME="Alpine Linux"$/ }
    its('content') { should match /^ID=alpine$/ }
    its('content') { should match /^VERSION_ID=#{alpine_version_id}$/ }
    its('content') { should match /^PRETTY_NAME="Alpine Linux v#{alpine_version}"$/ }
  end
end

control 'alpine-09' do
  impact 1.0
  title 'The /etc/alpine-release file must exist'
  desc 'Ensure that the correct release of Alpine Linux is used.'

  describe file('/etc/alpine-release') do
    it { should exist }
  end
end

control 'alpine-10' do
  impact 1.0
  title 'The /etc/alpine-release file must be the correct type'
  desc 'Ensure that the correct release of Alpine Linux is used.'

  describe file('/etc/alpine-release') do
    it { should be_file }
  end

  describe file('/etc/alpine-release') do
    it { should_not be_pipe }
    it { should_not be_socket }
    it { should_not be_symlink }
    it { should_not be_mounted }
    it { should_not be_directory }
    it { should_not be_block_device }
    it { should_not be_character_device }
  end
end

control 'alpine-11' do
  impact 1.0
  title 'The /etc/alpine-release file must be owned by root'
  desc 'Ensure the owner of /etc/alpine-release is correctly set to root.'

  describe file('/etc/alpine-release') do
    it { should be_owned_by 'root' }
    its('owner') { should eq 'root' }
  end
end

control 'alpine-12' do
  impact 1.0
  title 'The /etc/alpine-release file must be group-owned by root'
  desc 'Ensure the group of /etc/alpine-release is correctly set to root.'

  describe file('/etc/alpine-release') do
    its('group') { should eq 'root' }
  end
end

control 'alpine-13' do
  impact 1.0
  title 'The /etc/alpine-release file must have mode 0644 or less permissive'
  desc 'Check periodically the owner and permissions for /etc/alpine-release.'

  describe file('/etc/alpine-release') do
    it { should be_writable.by 'owner' }
    it { should be_readable.by 'owner' }
    it { should be_readable.by 'group' }
    it { should be_readable.by 'other' }
    it { should_not be_writable.by 'group' }
    it { should_not be_writable.by 'other' }
    it { should_not be_executable.by 'owner' }
    it { should_not be_executable.by 'group' }
    it { should_not be_executable.by 'other' }
    its('mode') { should cmp '0644' }
  end
end

control 'alpine-14' do
  impact 1.0
  title 'The /etc/alpine-release file must contain the correct release'
  desc 'Check for the correct version of Alpine Linux from /etc/alpine-release.'

  describe file('/etc/alpine-release') do
    its('content') { should match /^#{alpine_version_id}$/ }
  end
end

control 'alpine-15' do
  impact 1.0
  title 'The /etc/apk/repositories file must exist'
  desc 'Check periodically the owner and permissions for /etc/apk/repositories.'

  describe file('/etc/apk/repositories') do
    it { should exist }
  end
end

control 'alpine-16' do
  impact 1.0
  title 'The /etc/apk/repositories file must be the correct type'
  desc 'Check periodically the owner and permissions for /etc/apk/repositories.'

  describe file('/etc/apk/repositories') do
    it { should be_file }
  end

  describe file('/etc/apk/repositories') do
    it { should_not be_pipe }
    it { should_not be_socket }
    it { should_not be_symlink }
    it { should_not be_mounted }
    it { should_not be_directory }
    it { should_not be_block_device }
    it { should_not be_character_device }
  end
end

control 'alpine-17' do
  impact 1.0
  title 'The /etc/apk/repositories file must be owned by root'
  desc 'Check periodically the owner and permissions for /etc/apk/repositories.'

  describe file('/etc/apk/repositories') do
    it { should be_owned_by 'root' }
    its('owner') { should eq 'root' }
  end
end

control 'alpine-18' do
  impact 1.0
  title 'The /etc/apk/repositories file must be group-owned by root'
  desc 'Check periodically the owner and permissions for /etc/apk/repositories.'

  describe file('/etc/apk/repositories') do
    its('group') { should eq 'root' }
  end
end

control 'alpine-19' do
  impact 1.0
  title 'The /etc/apk/repositories file must have mode 0644 or less permissive'
  desc 'Check periodically the owner and permissions for /etc/apk/repositories.'

  describe file('/etc/apk/repositories') do
    it { should be_writable.by 'owner' }
    it { should be_readable.by 'owner' }
    it { should be_readable.by 'group' }
    it { should be_readable.by 'other' }
    it { should_not be_writable.by 'group' }
    it { should_not be_writable.by 'other' }
    it { should_not be_executable.by 'owner' }
    it { should_not be_executable.by 'group' }
    it { should_not be_executable.by 'other' }
    its('mode') { should cmp '0644' }
  end
end

control 'alpine-20' do
  impact 1.0
  title 'Check for the correct Alpine Linux repositories'
  desc 'Check for the correct Alpine Linux repositories.'

  describe file('/etc/apk/repositories') do
    its('content') {
      should match /^https:\/\/dl-cdn.alpinelinux.org\/alpine\/v#{alpine_version}\/main$/
    }

    its('content') {
      should match /^https:\/\/dl-cdn.alpinelinux.org\/alpine\/v#{alpine_version}\/community$/
    }
  end
end


text:
FROM alpine:3.3

RUN apk add --no-cache ca-certificates
COPY abaci-config-server /server

EXPOSE 8080

ENV PORT=8080 RAW_URL=https://github.com LOCAL_VOL=false

CMD /server -port=$PORT -url="$RAW_URL" -local=$LOCAL_VOL


text:
code: true
type: page
title: msetnx
---

# msetnx

Sets the provided keys to their respective values, only if they do not exist. If a key exists, then the whole operation is aborted and no key is set.

[[_Redis documentation_]](https://redis.io/commands/msetnx)

---

## Query Syntax

### HTTP

```http
URL: http://kuzzle:7512/ms/_msetnx
Method: POST
Body:
```

```js
{
  "entries": [
    {"key": "<key1>", "value": "<value1>"},
    {"key": "<key2>", "value": "<value2>"},
    {"key": "...", "value": "..."}
  ]
}
```

### Other protocols

```js
{
  "controller": "ms",
  "action": "msetnx",
  "body": {
    "entries": [
      {"key": "<key1>", "value": "<value1>"},
      {"key": "<key2>", "value": "<value2>"},
      {"key": "...", "value": "..."}
    ]
  }
}
```

---

## Body properties

- `entries`: an array of objects. Each object describes a new key-value pair to set, using the following properties:
  - `key`: key identifier
  - `value`: new value

---

## Response

Returns either `0` (command failed), or `1` (command succeeded).

```js
{
  "requestId": "<unique request identifier>",
  "status": 200,
  "error": null,
  "controller": "ms",
  "action": "msetnx",
  "collection": null,
  "index": null,
  "result": 1
}
```


text:
import yaml
import argparse
import simplejson as json
from kong_wrapper.utils import read_conf
from pygments import highlight, lexers, formatters

class Command:

    def __init__(self, file_path):
        self.info_file = self.parser_file(file_path)
        # print(self.info_file)

    @staticmethod
    def show_json(json):
        colorful_json = highlight(json.encode('UTF-8'), lexers.JsonLexer(), formatters.TerminalFormatter())
        print(colorful_json)

    @staticmethod
    def parser_file(file_path):
        with open(file_path) as command_file:
            info = yaml.load(command_file)
            return info

    @staticmethod
    def extract_defines(ref, defines):
        args = []
        for define in defines:
            if ref in define:
                for arg in define[ref]['arguments']:
                    args.append(arg)
        return args

    def load_program(self):
        parser = argparse.ArgumentParser(description=self.info_file['description'])
        subparser = parser.add_subparsers(help="Commands")

        for arg in self.info_file['arguments']:
            parser.add_argument(arg['name'], help=arg['help'])

        for command in self.info_file['commands']:
            object_actions_ = command['actions'].__class__()
            aux_parser = subparser.add_parser(command['name'], help=command['help'])
            aux_sub_parser = aux_parser.add_subparsers(help='Commands')

            for sub_command in command['subcommands']:
                aux_sub_command = aux_sub_parser.add_parser(sub_command['name'], help=sub_command['help'])

                if {"arguments"}.issubset(sub_command):
                    for arg in sub_command['arguments']:
                        if 'define' in arg:
                            args_defines = self.extract_defines(arg['define'], self.info_file['define'])
                            for arg_define in args_defines:
                                aux_sub_command.add_argument(arg_define['name'], **arg_define['params'])
                        else:
                            aux_sub_command.add_argument(arg['name'], **arg['params'])

                if {"exec"}.issubset(sub_command):
                    func_exec = getattr(object_actions_, sub_command['exec'])
                else:
                    func_exec = getattr(object_actions_, sub_command['name'])
                aux_sub_command.set_defaults(func=func_exec)

        args = parser.parse_args()

        try:
            cli_conf = read_conf('default')
            if not args.host or not args.port:
                if cli_conf and cli_conf["host"] and cli_conf["port"]:
                    args.host = cli_conf["host"]
                    args.port = cli_conf["port"]

                    try:
                        result_request = args.func(args)
                        result_request = json.dumps(result_request, sort_keys=True, indent=True)
                        # print(result_request)
                        self.show_json(result_request)
                    except Exception as error:
                        raise error

                else:
                    raise argparse.ArgumentError(subparser, "host and port values have not been defined.")
        except FileNotFoundError:
            print('The file ".kong" not found in directory "home" of user!')
        except Exception as error:
            raise error

if __name__ == "__main__":
    command = Command("command.yaml")
    command.load_program()


text:
using System;
using System.Numerics;

class CalculateNK
{
    static void Main()
    {
        int n = int.Parse(Console.ReadLine());
        int k = int.Parse(Console.ReadLine());

        BigInteger factorial = 1;

        for (int i = (k + 1); i <= n; i++)
        {
            factorial = factorial * i;
        }

        Console.WriteLine(factorial);
    }
}


text:
package org.apache.dubbo.common.model.person;

public enum PersonStatus {
    ENABLED,
    DISABLED
}


text:
Roads Module
============

.. automodule:: Roads
    :members:
    :undoc-members:
    :show-inheritance:


text:
describe RuboCop::Cop::VariableForce::Scope do
  include RuboCop::AST::Sexp

  describe '.new' do
    context 'when lvasgn node is passed' do
      it 'accepts that as top level scope' do
        node = s(:lvasgn)
        expect { described_class.new(node) }.not_to raise_error
      end
    end

    context 'when begin node is passed' do
      it 'accepts that as top level scope' do
        node = s(:begin)
        expect { described_class.new(node) }.not_to raise_error
      end
    end
  end

  let(:ast) do
    RuboCop::ProcessedSource.new(source, ruby_version).ast
  end

  let(:scope_node) { ast.each_node(scope_node_type).first }

  subject(:scope) { described_class.new(scope_node) }

  describe '#name' do
    context 'when the scope is instance method definition' do
      let(:source) { <<-END }
        def some_method
        end
      END

      let(:scope_node_type) { :def }

      it 'returns the method name' do
        expect(scope.name).to eq(:some_method)
      end
    end

    context 'when the scope is singleton method definition' do
      let(:source) { <<-END }
        def self.some_method
        end
      END

      let(:scope_node_type) { :defs }

      it 'returns the method name' do
        expect(scope.name).to eq(:some_method)
      end
    end
  end

  describe '#body_node' do
    shared_examples 'returns the body node' do
      it 'returns the body node' do
        expect(scope.body_node.children[1]).to eq(:this_is_target)
      end
    end

    context 'when the scope is instance method' do
      let(:source) do
        <<-END
          def some_method
            this_is_target
          end
        END
      end

      let(:scope_node_type) { :def }

      include_examples 'returns the body node'
    end

    context 'when the scope is singleton method' do
      let(:source) do
        <<-END
          def self.some_method
            this_is_target
          end
        END
      end

      let(:scope_node_type) { :defs }

      include_examples 'returns the body node'
    end

    context 'when the scope is module' do
      let(:source) do
        <<-END
          module SomeModule
            this_is_target
          end
        END
      end

      let(:scope_node_type) { :module }

      include_examples 'returns the body node'
    end

    context 'when the scope is class' do
      let(:source) do
        <<-END
          class SomeClass
            this_is_target
          end
        END
      end

      let(:scope_node_type) { :class }

      include_examples 'returns the body node'
    end

    context 'when the scope is singleton class' do
      let(:source) do
        <<-END
          class << self
            this_is_target
          end
        END
      end

      let(:scope_node_type) { :sclass }

      include_examples 'returns the body node'
    end

    context 'when the scope is block' do
      let(:source) do
        <<-END
          1.times do
            this_is_target
          end
        END
      end

      let(:scope_node_type) { :block }

      include_examples 'returns the body node'
    end

    context 'when the scope is top level' do
      let(:source) do
        <<-END
          this_is_target
        END
      end

      let(:scope_node_type) { :send }

      include_examples 'returns the body node'
    end
  end

  describe '#each_node' do
    shared_examples 'yields' do |description|
      it "yields #{description}" do
        yielded_types = []

        scope.each_node do |node|
          yielded_types << node.type
        end

        expect(yielded_types).to eq(expected_types.map(&:to_sym))
      end
    end

    describe 'outer scope boundary handling' do
      context 'when the scope is instance method' do
        let(:source) { <<-END }
          def some_method(arg1, arg2)
            :body
          end
        END

        let(:scope_node_type) { :def }
        let(:expected_types) { %w(def args arg arg sym) }
        include_examples 'yields', 'the argument and the body nodes'
      end

      context 'when the scope is singleton method' do
        let(:source) { <<-END }
          def self.some_method(arg1, arg2)
            :body
          end
        END

        let(:scope_node_type) { :defs }
        let(:expected_types) { %w(defs args arg arg sym) }
        include_examples 'yields', 'the argument and the body nodes'
      end

      context 'when the scope is module' do
        let(:source) { <<-END }
          module SomeModule
            :body
          end
        END

        let(:scope_node_type) { :module }
        let(:expected_types) { %w(module sym) }
        include_examples 'yields', 'the body nodes'
      end

      context 'when the scope is class' do
        let(:source) { <<-END }
          some_super_class = Class.new

          class SomeClass < some_super_class
            :body
          end
        END

        let(:scope_node_type) { :class }
        let(:expected_types) { %w(sym) }
        include_examples 'yields', 'the body nodes'
      end

      context 'when the scope is singleton class' do
        let(:source) { <<-END }
          some_object = Object.new

          class << some_object
            :body
          end
        END

        let(:scope_node_type) { :sclass }
        let(:expected_types) { %w(sym) }
        include_examples 'yields', 'the body nodes'
      end

      context 'when the scope is block' do
        let(:source) { <<-END }
          1.times do |arg1, arg2|
            :body
          end
        END

        let(:scope_node_type) { :block }
        let(:expected_types) { %w(block args arg arg sym) }
        include_examples 'yields', 'the argument and the body nodes'
      end

      context 'when the scope is top level' do
        let(:source) { <<-END }
          :body
        END

        let(:scope_node_type) { :sym }
        let(:expected_types) { %w(sym) }
        include_examples 'yields', 'the body nodes'
      end
    end

    describe 'inner scope boundary handling' do
      context "when there's a method invocation with block" do
        let(:source) { <<-END }
          foo = 1

          do_something(1, 2) do |arg|
            :body
          end

          foo
        END

        let(:scope_node_type) { :begin }
        let(:expected_types) { %w(begin lvasgn int block send int int lvar) }
        include_examples 'yields', 'only the block node and the child send node'
      end

      context "when there's a singleton method definition" do
        let(:source) { <<-END }
          foo = 1

          def self.some_method(arg1, arg2)
            :body
          end

          foo
        END

        let(:scope_node_type) { :begin }
        let(:expected_types) { %w(begin lvasgn int defs self lvar) }
        include_examples 'yields', 'only the defs node and the method host node'
      end

      context 'when there are grouped nodes with a begin node' do
        let(:source) { <<-END }
          foo = 1

          if true
            do_something
            do_anything
          end

          foo
        END

        let(:scope_node_type) { :begin }
        let(:expected_types) do
          %w(begin lvasgn int if true begin send send lvar)
        end
        include_examples 'yields', 'them without confused with top level scope'
      end
    end
  end
end


text:
#ifndef GAME_H
#define GAME_H

#include <iostream>
#include <vector>
using namespace std;

class GameTest;

class Game {
public:
  /** Default constructor. Initializes an empty game.
    */
  Game();

  /** Destructor */
  virtual ~Game();

  /** Adds a single role to the game. Returns true if the game is now complete,
   * otherwise false is returned */
  bool addRoll(char ch);

  /** Returns the current score, based on what can be calculated.
   * If the trailing spare or strike can't be completly calculated yet,
   * it isn't included
   */
  virtual int getCurrentScore();

  /** Gets the current frame number
   */
  int getCurrentFrame();

  /** Gets the current roll in the current frame
   */
  int getCurrentRoll();

  /** Returns true if the game is complete, false otherwise
   */
  bool isComplete();

  /**
   * Returns the total number of pins knocked down in the game. This is
   * different from the score!
   */
  int getPinsKnockedDown();

  /**
   * Returns the numbe of strikes thrown.
   */
  int getStrikesThrown();

  /** Returns the number of rolls
   */
  int getRollCount();

  char getLastRoll();

protected:
  // Contains the raw value of the rolls
  vector<char> rolls;
  // The current frame that you are in (1 - 10)
  int currentFrame;
  // The current roll for the frame that you are in (1-2)
  int currentRoll;
  // Tracks if the game is complete or not
  bool gameComplete;
  // Was there a bonus roll awarded in the 10th frame?
  bool bonusRollAwarded;

  virtual void debug();

  int getPinValueAtPosition(const unsigned int &pos);

  friend class GameTest;
};

#endif


text:
from django import forms

from . import models

class PaymentRequestForm(forms.ModelForm):

    class Meta:
        model = models.PaymentRequest
        exclude = []

    def __remove_empty_fields(self):
        form_fields_to_remove = []
        for model_field_name, form_field in self.fields.items():
            if not getattr(self.instance, model_field_name):
                form_fields_to_remove.append(model_field_name)
        for model_field_name in form_fields_to_remove:
            self.fields.pop(model_field_name)

    def __set_all_fields_hidden(self):
        for field in self.fields.values():
            field.widget = forms.HiddenInput()

    def __init__(self, *args, **kwargs):
        super(PaymentRequestForm, self).__init__(*args, **kwargs)
        self.__remove_empty_fields()
        self.__set_all_fields_hidden()

class PaymentResponseForm(forms.ModelForm):

    class Meta:
        model = models.PaymentResponse
        exclude = []


text:
package com.intellij.openapi.extensions;

/**
 * @author AKireyev
 */
public class EPAvailabilityListenerExtension implements PluginAware {
  public static final String EXTENSION_POINT_NAME = "com.intellij.openapi.extensions.epAvailabilityListener";

  private String myExtensionPointName;
  private String myListenerClass;
  private PluginDescriptor myPluginDescriptor;

  public EPAvailabilityListenerExtension() {
  }

  public EPAvailabilityListenerExtension(String extensionPointName, String listenerClass) {
    myExtensionPointName = extensionPointName;
    myListenerClass = listenerClass;
  }

  public String getExtensionPointName() {
    return myExtensionPointName;
  }

  public void setExtensionPointName(String extensionPointName) {
    myExtensionPointName = extensionPointName;
  }

  public String getListenerClass() {
    return myListenerClass;
  }

  public void setListenerClass(String listenerClass) {
    myListenerClass = listenerClass;
  }

  public void setPluginDescriptor(PluginDescriptor pluginDescriptor) {
    myPluginDescriptor = pluginDescriptor;
  }

  public PluginDescriptor getPluginDescriptor() {
    return myPluginDescriptor;
  }

  public Class loadListenerClass() throws ClassNotFoundException {
    if (myPluginDescriptor != null && myPluginDescriptor.getPluginClassLoader() != null) {
      return Class.forName(getListenerClass(), true, myPluginDescriptor.getPluginClassLoader());
    }
    else {
      return Class.forName(getListenerClass());
    }
  }
}


text:
namespace SpotifyAPI.Web
{
  public class Device
  {
    public string Id { get; set; } = default!;
    public bool IsActive { get; set; }
    public bool IsPrivateSession { get; set; }
    public bool IsRestricted { get; set; }
    public string Name { get; set; } = default!;
    public string Type { get; set; } = default!;
    public int? VolumePercent { get; set; }
  }
}


text:
'use strict';

var PathManager        = require('./PathManager');
var FieldMap           = require('./FieldMap');
var AbstractRecord     = require('./AbstractRecord');
var SnapshotFactory       = require('./SnapshotFactory');
var util               = require('../../common');

function RecordField(fieldMap) {
  this.handlers = {};
  this.path = fieldMap.getPathManager().first();
  this._super(fieldMap, this.path.name(), this.path.url());
  if( fieldMap.getPathManager().count() !== 1 ) {
    throw new Error('RecordField must have exactly one path, but we got '+ fieldMap.getPathManager().count());
  }
  if( fieldMap.length !== 1 ) {
    throw new Error('RecordField must have exactly one field, but we found '+ fieldMap.length);
  }
  util.log.debug('RecordField created', this.getName(), this.getUrl());
}

util.inherits(RecordField, AbstractRecord, {
  makeChild: function(key) {
    var pm = new PathManager([this.path.child(key)]);
    var fm = new FieldMap(pm);
    fm.add({key: FieldMap.key(pm.first(), '$value'), alias: key});
    return new RecordField(fm);
  },

  hasChild: function(snaps, key) {
    return snaps[0].hasChild(key);
  },

  getChildSnaps: function(snaps, fieldName) {
    // there is exactly one snap and there are no aliases to deal with
    return [snaps[0].child(fieldName)];
  },

  /**
   * There is nothing to merge at this level because there is only one
   * path and no field map
   *
   * @param {Array} snaps list of snapshots to be merged
   * @param {boolean} isExport true if exportVal() was called
   * @returns {Object}
   */
  mergeData: function(snaps, isExport) {
    return isExport? snaps[0].exportVal() : snaps[0].val();
  },

  getPriority: function(snaps) {
    return snaps[0].getPriority();
  },

  /**
   * Iterates all keys of snapshot.
   *
   * Calls iterator with a {string|number} key for the next field to
   * iterate only.
   *
   * If iterator returns true, this method should abort and return true,
   * otherwise it should return false (same as Snapshot.forEach).
   *
   * @param {Array} snaps
   * @param {function} iterator
   * @param {object} [context]
   * @return {boolean} true if aborted
   * @abstract
   */
  forEachKey: function(snaps, iterator, context) {
    var firstSnap = snaps[0];
    return firstSnap.forEach(function(ss) {
      iterator.call(context, ss.key, ss.key);
    });
  },

  saveData: function(data, opts) {
    var ref = this.path.ref;
    if( opts.isUpdate ) {
      if( !util.isObject(data) ) {
        throw new Error('When using update(), the data must be an object.');
      }
      if( util.has(opts, 'priority') ) {
        data['.priority'] = opts.priority;
      }
      ref.update(data, wrapCallback(opts));
    }
    else if( util.has(opts, 'priority') ) {
      ref.setWithPriority(data, opts.priority, wrapCallback(opts));
    }
    else {
      ref.set(data, wrapCallback(opts));
    }
  },

  getClass: function() { return RecordField; },

  _start: function(event) {
    var self = this;
    this.handlers[event] = function(snap, prev) {
      self.trigger(new SnapshotFactory(event, snap.key, snap, prev));
    };
    this.path.ref.on(event, this.handlers[event], this._cancel, this);
  },

  _stop:   function(event) {
    if( this.handlers.hasOwnProperty(event) ) {
      this.path.ref.off(event, this.handlers[event], this);
    }
  }
});

function wrapCallback(opts) {
  if( opts.callback ) {
    return function() {
      opts.callback.apply(opts.context, arguments);
    };
  }
  else {
    return util.noop;
  }
}

module.exports = RecordField;


text:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto"
      xmlns:tools="http://schemas.android.com/tools"
      tools:context="com.example.toolbar.MainActivity">

    <item
        android:id="@+id/action_album_art"
        android:icon="@drawable/drawable_image"
        android:title="Sort by"
        android:visible="true"
        app:showAsAction="always">
        <menu>
            <item
                android:id="@+id/action_search_web"
                android:title="@string/search_web">
            </item>
            <item
                android:id="@+id/action_from_gallery"
                android:title="@string/from_gallery">
            </item>
        </menu>
    </item>
</menu>


text:
package com.github.haixing_hu.data.model.common;

import javax.annotation.Nullable;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;

import static com.github.haixing_hu.lang.Argument.requireNonNull;

/**
 * A {@link Name} represents the name of a person. It's a value object.
 *
 * @author Haixing Hu
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "name")
public final class Name {

  @XmlElement(required = true)
  private String given;

  @XmlElement(required = false)
  private String middle;

  @XmlElement(required = true)
  private String family;

  @XmlElement(required = false)
  private String display;

  /**
   * Constructs an empty {@link Name}.
   */
  public Name() {
    given = StringUtils.EMPTY;
    middle = null;
    display = null;
    family = StringUtils.EMPTY;
  }

  /**
   * Constructs a {@link Name}.
   *
   * @param given
   *          the given name.
   * @param family
   *          the family name.
   */
  public Name(final String given, final String family) {
    this.given = requireNonNull("given", given);
    middle = null;
    this.family = requireNonNull("family", family);
    display = null;
  }

  /**
   * Constructs a {@link Name}.
   *
   * @param given
   *          the given name.
   * @param middle
   *          the middle name, or {@code null} if it has none.
   * @param family
   *          the family name.
   */
  public Name(final String given, @Nullable final String middle,
      final String family) {
    this.given = requireNonNull("given", given);
    this.middle = middle;
    this.family = requireNonNull("family", family);
    display = null;
  }

  /**
   * Constructs a {@link Name}.
   *
   * @param given
   *          the given name.
   * @param middle
   *          the middle name, or {@code null} if it has none.
   * @param family
   *          the family name.
   * @param display
   *          the display name, or {@code null} if it has none.
   */
  public Name(final String given, @Nullable final String middle,
      final String family, final String display) {
    this.given = requireNonNull("given", given);
    this.middle = middle;
    this.family = requireNonNull("family", family);
    this.display = display;
  }

  /**
   * Gets the given name.
   *
   * @return the given name, which cannot be {@code null}.
   */
  public String getGiven() {
    return given;
  }

  /**
   * Sets the given name.
   *
   * @param given
   *          the new given name to set, which cannot be {@code null}.
   */
  public void setGiven(final String given) {
    this.given = requireNonNull("given", given);
  }

  /**
   * Gets the middle name.
   *
   * @return the middle name, or {@code null} if it has none.
   */
  public String getMiddle() {
    return middle;
  }

  /**
   * Sets the middle name.
   *
   * @param middle
   *          the new middle name to set, or {@code null} to set none.
   */
  public void setMiddle(@Nullable final String middle) {
    this.middle = middle;
  }

  /**
   * Gets the family name.
   *
   * @return the family name, which cannot be {@code null}.
   */
  public String getFamily() {
    return family;
  }

  /**
   * Sets the family.
   *
   * @param family
   *          the new family to set.
   */
  public void setFamily(final String family) {
    this.family = requireNonNull("family", family);
  }

  /**
   * Gets the display name.
   *

   * A display name specifies how the name are displayed. If it is not
   * specified, the application should use the default formating rule to format
   * name and display it.
   *
   * @return the display name, or {@code null} if it has none.
   */
  public String getDisplay() {
    return display;
  }

  /**
   * Sets the display name.
   *

   * A display name specifies how the name are displayed. If it is not
   * specified, the application should use the default formating rule to format
   * name and display it.
   *
   * @param display
   *          the new display name to set, or {@code null} to set none.
   */
  public void setDisplay(@Nullable final String display) {
    this.display = display;
  }

  @Override
  public int hashCode() {
    return new HashCodeBuilder(11, 3)
        .append(given)
        .append(middle)
        .append(family)
        .append(display)
        .build();
  }

  @Override
  public boolean equals(final Object obj) {
    if (obj == null) {
      return false;
    }
    if (obj == this) {
      return true;
    }
    if (obj.getClass() != getClass()) {
      return false;
    }
    final Name rhs = (Name) obj;
    return new EqualsBuilder()
        .append(given, rhs.given)
        .append(middle, rhs.middle)
        .append(family, rhs.family)
        .append(display, rhs.display)
        .build();
  }

  @Override
  public String toString() {
    if ((display != null) && (display.length() > 0)) {
      return display;
    }
    final StringBuilder builder = new StringBuilder();
    builder.append(given);
    if ((middle != null) && (middle.length() > 0)) {
      builder.append(' ').append(middle);
    }
    builder.append(' ').append(family);
    return builder.toString();
  }
}


text:
<?php namespace Anomaly\Streams\Platform\Addon\Module\Command;

use Anomaly\Streams\Platform\Addon\Module\Contract\ModuleRepositoryInterface;
use Anomaly\Streams\Platform\Addon\Module\Event\ModuleWasUninstalled;
use Anomaly\Streams\Platform\Addon\Module\Module;
use Anomaly\Streams\Platform\Console\Kernel;
use Illuminate\Contracts\Events\Dispatcher;

/**
 * Class UninstallModule
 *
 * @link   http://pyrocms.com/
 * @author PyroCMS, Inc. <support@pyrocms.com>
 * @author Ryan Thompson <ryan@pyrocms.com>
 */
class UninstallModule
{

    /**
     * The module to uninstall.
     *
     * @var Module
     */
    protected $module;

    /**
     * Create a new UninstallModule instance.
     *
     * @param Module $module
     */
    public function __construct(Module $module)
    {
        $this->module = $module;
    }

    /**
     * Handle the command.
     *
     * @param Kernel     $console
     * @param Dispatcher $events
     */
    public function handle(Kernel $console, Dispatcher $events, ModuleRepositoryInterface $modules)
    {
        $this->module->fire('uninstalling');

        $options = [
            '--addon' => $this->module->getNamespace(),
        ];

        $console->call('migrate:reset', $options);
        $console->call('streams:destroy', ['namespace' => $this->module->getSlug()]);
        $console->call('streams:cleanup');

        $modules->uninstall($this->module);

        $this->module->fire('uninstalled');

        $events->fire(new ModuleWasUninstalled($this->module));
    }
}


text:
function [Y,E,R,Ytrace,Etrace,Rtrace]=dim_activation_conv_recurrent(w,X,Y,iterations,v,downsample)
% w = a cell array of size {N,M}, where N is the number of distinct neuron types
%     and M is the number of input channels. Each element {i,j} of the cell
%     array is a 2-dimensional matrix (a convolution mask) specifying the
%     synaptic weights for neuron type i's RF in input channel j.
% X = a cell array of size {M}. Each element {j} of the cell array is a
%     2-dimensional matrix specifying the bottom-up input to that channel j of
%     the current processing stage (external inputs targetting the error
%     nodes). If inputs arrive from more than one source, then each source
%     provides a different cell in the array. Input values that change over
%     time can be presented using a 3-d matrix, where the 3rd dimension is time.
% Y = a cell array of size {N}. Each element {i} of the cell array is a
%     2-dimensional matrix specifying prediction node activations for type i
%     neurons.
% R = a cell array of size {M}. Each element {j} of the cell array is a
%     2-dimensional matrix specifying the reconstruction of the input channel j.
%     These values are also the top-down feedback that should modulate
%     activity in preceeding processing stages of a hierarchy.
% E = a cell array of size {M}. Each element {j} of the cell array is a
%     2-dimensional matrix specifying the error in the reconstruction of the
%     input channel j.
% downsample = an N element vector of integer values which defines which
%     prediction node values are to be set to zero, and hence, be ignored. This
%     is a method of reducing the density of prediction nodes across the image
%     (ideally, rather than performing convolution at every pixel location and
%     then setting some values to zero, it would be possible to only calulate
%     the filter outputs at certain locations). A value of 1 means keep all
%     values, 2 means keep every alternate value, 3 means keep every third
%     value, and so on. Default is 1 for each type of neuron.
% iterations = the number of iterations of the DIM algorithm to perform. Default
%     is 50.

[a,b,z]=size(X{1});
[nMasks,nChannels]=size(w);
nInputChannels=length(X);
[c,d]=size(w{1,1});

%set parameters
GP=global_parameters;
epsilon1=1e-5;
epsilon2=1e-3;

disp('dim_activation_conv_recurrent');
disp(['  epsilon1=',num2str(epsilon1),' epsilon2=',num2str(epsilon2)]);

if nargin<3 || isempty(Y), %initialise prediction neuron outputs to zero
  for i=1:nMasks
    Y{i}=zeros(a,b,'single');
  end
end

if nargin<4 || isempty(iterations), iterations=GP.iterations; end

if nargin<5 || isempty(v)
  %set feedback weights equal to feedforward weights normalized by maximum value
  for i=1:nMasks
    %calc normalisation values by taking into account all weights contributing to
    %each RF type
    maxVal=0;
    for j=1:nChannels
      maxVal=max(maxVal,max(max(w{i,j})));
    end

    %apply normalisation to calculate feedback weight values.
    for j=1:nChannels
      v{i,j}=w{i,j}./(1e-9+maxVal);
    end
  end
end

if nargin<6 || isempty(downsample), downsample=ones(1,nMasks); end
if length(downsample)<nMasks, %allow use to specify same value for multiple neuron types
  downsample(length(downsample)+1:nMasks)=downsample(length(downsample));
end

%try to speed things up
if exist('convnfft')==2 && (max(c,d)>=50-max(a,b) || (min(c,d)>10 && min(a,b)>10))
  conv_fft=1;%use fft version of convolution for large images and/or masks.  FF
  %weights are rotated versions, so that convnfft can be used to apply the
  %filtering
  for j=1:nChannels
    for i=1:nMasks
      w{i,j}=rot90(w{i,j},2);
    end
  end
else
  conv_fft=0;%use standard conv2/filter2 function for smaller images and/or masks, or if faster functions are not installed
end

%initialise error node activations
for j=1:nChannels
  E{j}=zeros(a,b,'single');
end

%iterate DIM equations to determine neural responses
fprintf(1,'dim_conv(%i): ',conv_fft);
for t=1:iterations
  fprintf(1,'.%i.',t);

  %copy previous output values to inputs, to provide recurrent input
  for i=1:nMasks
    X{nInputChannels+i}=Y{i};
  end

  %update error-detecting neuron responses
  for j=1:nChannels
    %calc predictive reconstruction of the input
    R{j}=zeros(a,b,'single');%reset reconstruction
    for i=1:nMasks
      %sum reconstruction over each RF type
      if ~(isempty(v{i,j}) || iszero(v{i,j})) %skip empty filters: they don't add anything
        if conv_fft==1
          R{j}=R{j}+convnfft(Y{i},v{i,j},'same');
        else
          R{j}=R{j}+conv2(Y{i},v{i,j},'same');
        end
      end
    end
    %calc error between reconstruction and actual input: inputs values are clipped
    %at 1 and temporally changing values are used (if these are provided)
    E{j}=min(1,X{j}(:,:,min(t,size(X{j},3))))./(epsilon2+R{j});
    if nargout>4
      Etrace{j}(:,:,t)=E{j};%record response over time
    end
    if nargout>5
      Rtrace{j}(:,:,t)=R{j};%record response over time
    end
  end

  %update prediction neuron outputs
  for i=1:nMasks
    input=single(0);
    for j=1:nChannels
      %sum inputs to prediction neurons from each channel
      if ~(isempty(w{i,j}) || iszero(w{i,j})) %skip empty filters: they don't add anything
        if conv_fft==1
          input=input+convnfft(E{j},w{i,j},'same');
        else
          input=input+filter2(w{i,j},E{j},'same');
        end
      end
    end
    Y{i}=(epsilon1+Y{i}).*input;  %modulate prediction neuron response by current input
    Y{i}=max(0,Y{i}); %ensure no negative values creep in!
    for ds=1:downsample(i)-1
      Y{i}(ds:downsample(i):a,:)=0;
      Y{i}(:,ds:downsample(i):b)=0;
    end
    if nargout>3
      Ytrace{i}(:,:,t)=Y{i};%record response over time
    end
  end
end
disp(' ');


text:
'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
  User = mongoose.model('User'),
  _ = require('lodash'),
  Busboy = require('busboy'),
  fs = require('fs'),
  path = require('path'),
  utils = require('./utils'),
  config = require('meanio').loadConfig();

/**
 * Find profile by user id
 */
exports.profile = function (req, res, next) {
  User.findOne({
    _id: req.user._id
  }).exec(function (err, user) {
    if (err) return next(err);
    if (!user) return next(new Error('Failed to load user'));
    req.profile = user.profile;
    next();
  });
};

/**
 * Update user profile
 */
exports.update = function (req, res, next) {
  req.profile = req.profile || {};
  var profile = _.extend(req.profile, req.body);

  var user = req.user;
  user.profile = profile;

  User.update({_id: user._id}, user, function (err) {
    utils.checkAndHandleError(err, 'Cannot update the profile', next);
    res.json(user.profile);
  });
};

/**
 * Update user avatar
 */
exports.uploadAvatar = function (req, res, next) {
  var busboy = new Busboy({
    headers: req.headers
  });

  busboy.on('file', function (fieldname, file, filename, encoding, mimetype) {
    var saveTo = config.root + '/packages/core/users/public/assets/img/avatar/' + req.user._id + '.' + path.basename(filename.split('.').slice(-1)[0]).toLowerCase();

    file.pipe(fs.createWriteStream(saveTo));
    req.body.avatar = config.hostname + '/users/assets/img/avatar/' + req.user._id + '.' + path.basename(filename.split('.').slice(-1)[0]).toLowerCase();
    req.file = true;
  });

  busboy.on('finish', function () {
    if (req.file)
      next();
    else
      utils.checkAndHandleError('Didn\'t find any avatar to upload', 'Didn\'t find any avatar to upload', next);
  });
  return req.pipe(busboy);
};


text:
package com.c09.GoMovie.product.controller;

import javax.validation.Valid;
import java.util.List;
import java.util.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import org.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import com.c09.GoMovie.cinema.entities.Cinema;
import com.c09.GoMovie.cinema.entities.Hall;
import com.c09.GoMovie.cinema.entities.Seat;
import com.c09.GoMovie.cinema.service.CinemaService;
import com.c09.GoMovie.movie.entities.Movie;
import com.c09.GoMovie.movie.service.MovieService;
import com.c09.GoMovie.product.entities.Screening;
import com.c09.GoMovie.product.entities.Ticket;
import com.c09.GoMovie.product.service.ProductService;
import com.c09.GoMovie.user.entities.User;
import com.c09.GoMovie.user.entities.User.ROLE;
import com.c09.GoMovie.user.service.SessionService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Api(value="Product", description="Screening、Ticket的CURD")
@RestController
@RequestMapping("/cinemas")
public class ProductController {

	@Autowired
	private ProductService productService;

	@ApiOperation(value="根据影院ID获取全部场次")
	@RequestMapping(value={"/{cinemaId}/screenings"}, method=RequestMethod.GET)
	public List<Screening> listScreeningsByCinameId(@PathVariable("cinemaId") long cinemaId) {
		return productService.listScreeningsByCinameId(cinemaId);
	}

	@ApiOperation(value="根据场次ID获取某个场次")
	@RequestMapping(value={"/{cinemaId}/screenings/{screeningId}"}, method=RequestMethod.GET)
	public Screening getScreeningById(@PathVariable("cinemaId") long cinemaId, @PathVariable("screeningId") long screeningId) {
		return productService.getScreeningById(screeningId);
	}
	//格式:\"yyyy-MM-dd hh:mm\"
	@ApiOperation(value="创建一个场次")
	@RequestMapping(value = {"/{cinemaId}/screenings"}, method = RequestMethod.POST)
    @ResponseStatus(value = HttpStatus.CREATED)
    @PreAuthorize("hasAuthority('admin')")
    public Screening createScreening(@PathVariable("cinemaId") long cinemaId, @Valid @RequestBody String jsonString) {
		JSONObject json = new JSONObject(jsonString);
		Screening screening = new Screening();
		screening.setRunningTime(json.getInt("runningTime"));

		String startTimeString = json.getString("startTime");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm");
	    Date startTimeDate;
		try {
			startTimeDate = sdf.parse(startTimeString);
			screening.setStartTime(startTimeDate);
		} catch (ParseException e) {
			e.printStackTrace();
		}

		long hallId = json.getLong("hallId");
		long movieId = json.getLong("movieId");
		return productService.createScreening(screening, hallId, movieId);
	}

	@ApiOperation(value="根据场次ID删除场次")
	@RequestMapping(value={"/{cinemaId}/screenings/{screeningId}"}, method=RequestMethod.DELETE)
    @ResponseStatus(value = HttpStatus.NO_CONTENT)
    @PreAuthorize("hasAuthority('admin')")
    public void deleteScreeningById(@PathVariable("cinemaId") long cinemaId, @PathVariable("screeningId") long screeningId) {
		productService.deleteScreeningById(screeningId);
	}

	@ApiOperation(value="根据场次ID获取所有电影票")
	@RequestMapping(value={"/{cinemaId}/screenings/{screeningId}/tickets"}, method=RequestMethod.GET)
	public List<Ticket> listTicketsByScreeningId(@PathVariable("cinemaId") long cinemaId, @PathVariable("screeningId") long screeningId) {
		return productService.listTicketsByScreeningId(screeningId);
	}

	@ApiOperation(value="根据电影票ID获取电影票")
	@RequestMapping(value={"/{cinemaId}/screenings/{screeningId}/tickets/{ticketId}"}, method=RequestMethod.GET)
	public ResponseEntity<Ticket> getTicketById(
			@PathVariable("cinemaId") long cinemaId,
			@PathVariable("screeningId") long screeningId,
			@PathVariable("ticketId") long ticketId) {
		Ticket ticket = productService.getTicketById(ticketId);
		return new ResponseEntity<Ticket>(ticket, ticket != null ? HttpStatus.OK : HttpStatus.NOT_FOUND);
	}

	@ApiOperation(value="创建一张电影票")
	@RequestMapping(value = {"/{cinemaId}/screenings/{screeningId}/tickets"}, method = RequestMethod.POST)
    @ResponseStatus(value = HttpStatus.CREATED)
    @PreAuthorize("hasAuthority('admin')")
    public Ticket createTicket(
    		@Valid @RequestBody String jsonString,
    		@PathVariable("cinemaId") long cinemaId,
    		@PathVariable("screeningId") long screeningId) {
		JSONObject json = new JSONObject(jsonString);
		Ticket ticket = new Ticket();
		ticket.setPrice(json.getDouble("price"));
		long seatId = json.getLong("seatId");
		return productService.createTicket(ticket, screeningId, seatId);
	}

	@ApiOperation(value="根据电影票ID删除电影票")
	@RequestMapping(value={"/{cinemaId}/screenings/{screeningId}/tickets/{ticketId}"}, method=RequestMethod.DELETE)
    @ResponseStatus(value = HttpStatus.NO_CONTENT)
    @PreAuthorize("hasAuthority('admin')")
    public void deleteTicketById(
    		@PathVariable("cinemaId") long cinemaId,
    		@PathVariable("screeningId") long screeningId,
    		@PathVariable("ticketId") long ticketId) {
		productService.deleteTicketById(ticketId);
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/.idea/04. Prototyp-based Inheritance.iml" filepath="$PROJECT_DIR$/.idea/04. Prototyp-based Inheritance.iml" />
    </modules>
  </component>
</project>


text:
{% extends "mail/_base.html" %}

{% block body %}

Your account has been approved.

You can now start ordering contracts!

http://cloud.rozu.co:9083/contracts

{% endblock %}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>The C Preprocessor: Diagnostics</title>

<meta name="description" content="The C Preprocessor: Diagnostics">
<meta name="keywords" content="The C Preprocessor: Diagnostics">
<meta name="resource-type" content="document">
<meta name="distribution" content="global">
<meta name="Generator" content="makeinfo">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link href="index.html#Top" rel="start" title="Top">
<link href="Index-of-Directives.html#Index-of-Directives" rel="index" title="Index of Directives">
<link href="index.html#SEC_Contents" rel="contents" title="Table of Contents">
<link href="index.html#Top" rel="up" title="Top">
<link href="Line-Control.html#Line-Control" rel="next" title="Line Control">
<link href="Deleted-Code.html#Deleted-Code" rel="prev" title="Deleted Code">

Next: Line Control, Previous: Conditionals, Up: Top   [Contents][Index]

5 Diagnostics

The directive ‘<samp>#error</samp>’ causes the preprocessor to report a fatal
error.  The tokens forming the rest of the line following ‘<samp>#error</samp>’
are used as the error message.

You would use ‘<samp>#error</samp>’ inside of a conditional that detects a
combination of parameters which you know the program does not properly
support.  For example, if you know that the program will not run
properly on a VAX, you might write

#ifdef __vax__
#error "Won't work on VAXen.  See comments at get_last_object."
#endif

If you have several configuration parameters that must be set up by
the installation in a consistent way, you can use conditionals to detect
an inconsistency and report it with ‘<samp>#error</samp>’.  For example,

#if !defined(FOO) && defined(BAR)
#error "BAR requires FOO."
#endif

The directive ‘<samp>#warning</samp>’ is like ‘<samp>#error</samp>’, but causes the
preprocessor to issue a warning and continue preprocessing.  The tokens
following ‘<samp>#warning</samp>’ are used as the warning message.

You might use ‘<samp>#warning</samp>’ in obsolete header files, with a message
directing the user to the header file which should be used instead.

Neither ‘<samp>#error</samp>’ nor ‘<samp>#warning</samp>’ macro-expands its argument.
Internal whitespace sequences are each replaced with a single space.
The line must consist of complete tokens.  It is wisest to make the
argument of these directives be a single string constant; this avoids
problems with apostrophes and the like.


text:
/*
Package testlib contains utility methods to include in unit tests to
deal with topology common tasks, like fake tablets and action loops.
*/
package testlib

import (
	"fmt"
	"net"
	"net/http"
	"testing"
	"time"

	"golang.org/x/net/context"
	"google.golang.org/grpc"

	"github.com/youtube/vitess/go/mysql/fakesqldb"
	"github.com/youtube/vitess/go/vt/mysqlctl"
	"github.com/youtube/vitess/go/vt/topo"
	"github.com/youtube/vitess/go/vt/topo/topoproto"
	"github.com/youtube/vitess/go/vt/vttablet/grpctmserver"
	"github.com/youtube/vitess/go/vt/vttablet/tabletconn"
	"github.com/youtube/vitess/go/vt/vttablet/tabletmanager"
	"github.com/youtube/vitess/go/vt/vttablet/tmclient"
	"github.com/youtube/vitess/go/vt/wrangler"

	querypb "github.com/youtube/vitess/go/vt/proto/query"
	topodatapb "github.com/youtube/vitess/go/vt/proto/topodata"

	// import the gRPC client implementation for tablet manager
	_ "github.com/youtube/vitess/go/vt/vttablet/grpctmclient"

	// import the gRPC client implementation for query service
	_ "github.com/youtube/vitess/go/vt/vttablet/grpctabletconn"
)

// This file contains utility methods for unit tests.
// We allow the creation of fake tablets, and running their event loop based
// on a FakeMysqlDaemon.

// FakeTablet keeps track of a fake tablet in memory. It has:
// - a Tablet record (used for creating the tablet, kept for user's information)
// - a FakeMysqlDaemon (used by the fake event loop)
// - a 'done' channel (used to terminate the fake event loop)
type FakeTablet struct {
	// Tablet and FakeMysqlDaemon are populated at NewFakeTablet time.
	// We also create the RPCServer, so users can register more services
	// before calling StartActionLoop().
	Tablet          *topodatapb.Tablet
	FakeMysqlDaemon *mysqlctl.FakeMysqlDaemon
	RPCServer       *grpc.Server

	// The following fields are created when we start the event loop for
	// the tablet, and closed / cleared when we stop it.
	// The Listener is used by the gRPC server.
	Agent    *tabletmanager.ActionAgent
	Listener net.Listener

	// These optional fields are used if the tablet also needs to
	// listen on the 'vt' port.
	StartHTTPServer bool
	HTTPListener    net.Listener
	HTTPServer      *http.Server
}

// TabletOption is an interface for changing tablet parameters.
// It's a way to pass multiple parameters to NewFakeTablet without
// making it too cumbersome.
type TabletOption func(tablet *topodatapb.Tablet)

// TabletKeyspaceShard is the option to set the tablet keyspace and shard
func TabletKeyspaceShard(t *testing.T, keyspace, shard string) TabletOption {
	return func(tablet *topodatapb.Tablet) {
		tablet.Keyspace = keyspace
		shard, kr, err := topo.ValidateShardName(shard)
		if err != nil {
			t.Fatalf("cannot ValidateShardName value %v", shard)
		}
		tablet.Shard = shard
		tablet.KeyRange = kr
	}
}

// ForceInitTablet is the tablet option to set the 'force' flag during InitTablet
func ForceInitTablet() TabletOption {
	return func(tablet *topodatapb.Tablet) {
		// set the force_init field into the portmap as a hack
		tablet.PortMap["force_init"] = 1
	}
}

// StartHTTPServer is the tablet option to start the HTTP server when
// starting a tablet.
func StartHTTPServer() TabletOption {
	return func(tablet *topodatapb.Tablet) {
		// set the start_http_server field into the portmap as a hack
		tablet.PortMap["start_http_server"] = 1
	}
}

// NewFakeTablet creates the test tablet in the topology.  'uid'
// has to be between 0 and 99. All the tablet info will be derived
// from that. Look at the implementation if you need values.
// Use TabletOption implementations if you need to change values at creation.
// 'db' can be nil if the test doesn't use a database at all.
func NewFakeTablet(t *testing.T, wr *wrangler.Wrangler, cell string, uid uint32, tabletType topodatapb.TabletType, db *fakesqldb.DB, options ...TabletOption) *FakeTablet {
	if uid < 0 || uid > 99 {
		t.Fatalf("uid has to be between 0 and 99: %v", uid)
	}
	mysqlPort := int32(3300 + uid)
	hostname := fmt.Sprintf("%v.%d", cell, uid)
	tablet := &topodatapb.Tablet{
		Alias:         &topodatapb.TabletAlias{Cell: cell, Uid: uid},
		Hostname:      hostname,
		MysqlHostname: hostname,
		PortMap: map[string]int32{
			"vt":   int32(8100 + uid),
			"grpc": int32(8200 + uid),
		},
		Keyspace: "test_keyspace",
		Shard:    "0",
		Type:     tabletType,
	}
	topoproto.SetMysqlPort(tablet, mysqlPort)
	for _, option := range options {
		option(tablet)
	}
	_, startHTTPServer := tablet.PortMap["start_http_server"]
	delete(tablet.PortMap, "start_http_server")
	_, force := tablet.PortMap["force_init"]
	delete(tablet.PortMap, "force_init")
	if err := wr.InitTablet(context.Background(), tablet, force, true /* createShardAndKeyspace */, false /* allowUpdate */); err != nil {
		t.Fatalf("cannot create tablet %v: %v", uid, err)
	}

	// create a FakeMysqlDaemon with the right information by default
	fakeMysqlDaemon := mysqlctl.NewFakeMysqlDaemon(db)
	fakeMysqlDaemon.MysqlPort = mysqlPort

	return &FakeTablet{
		Tablet:          tablet,
		FakeMysqlDaemon: fakeMysqlDaemon,
		RPCServer:       grpc.NewServer(),
		StartHTTPServer: startHTTPServer,
	}
}

// StartActionLoop will start the action loop for a fake tablet,
// using ft.FakeMysqlDaemon as the backing mysqld.
func (ft *FakeTablet) StartActionLoop(t *testing.T, wr *wrangler.Wrangler) {
	if ft.Agent != nil {
		t.Fatalf("Agent for %v is already running", ft.Tablet.Alias)
	}

	// Listen on a random port for gRPC.
	var err error
	ft.Listener, err = net.Listen("tcp", ":0")
	if err != nil {
		t.Fatalf("Cannot listen: %v", err)
	}
	gRPCPort := int32(ft.Listener.Addr().(*net.TCPAddr).Port)

	// If needed, listen on a random port for HTTP.
	vtPort := ft.Tablet.PortMap["vt"]
	if ft.StartHTTPServer {
		ft.HTTPListener, err = net.Listen("tcp", ":0")
		if err != nil {
			t.Fatalf("Cannot listen on http port: %v", err)
		}
		handler := http.NewServeMux()
		ft.HTTPServer = &http.Server{
			Handler: handler,
		}
		go ft.HTTPServer.Serve(ft.HTTPListener)
		vtPort = int32(ft.HTTPListener.Addr().(*net.TCPAddr).Port)
	}

	// Create a test agent on that port, and re-read the record
	// (it has new ports and IP).
	ft.Agent = tabletmanager.NewTestActionAgent(context.Background(), wr.TopoServer(), ft.Tablet.Alias, vtPort, gRPCPort, ft.FakeMysqlDaemon, nil)
	ft.Tablet = ft.Agent.Tablet()

	// Register the gRPC server, and starts listening.
	grpctmserver.RegisterForTest(ft.RPCServer, ft.Agent)
	go ft.RPCServer.Serve(ft.Listener)

	// And wait for it to serve, so we don't start using it before it's
	// ready.
	timeout := 5 * time.Second
	step := 10 * time.Millisecond
	c := tmclient.NewTabletManagerClient()
	for timeout >= 0 {
		ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
		err := c.Ping(ctx, ft.Agent.Tablet())
		cancel()
		if err == nil {
			break
		}
		time.Sleep(step)
		timeout -= step
	}
	if timeout < 0 {
		panic("StartActionLoop failed.")
	}
}

// StopActionLoop will stop the Action Loop for the given FakeTablet
func (ft *FakeTablet) StopActionLoop(t *testing.T) {
	if ft.Agent == nil {
		t.Fatalf("Agent for %v is not running", ft.Tablet.Alias)
	}
	if ft.StartHTTPServer {
		ft.HTTPListener.Close()
	}
	ft.Listener.Close()
	ft.Agent.Stop()
	ft.Agent = nil
	ft.Listener = nil
	ft.HTTPListener = nil
}

// Target returns the keyspace/shard/type info of this tablet as Target.
func (ft *FakeTablet) Target() querypb.Target {
	return querypb.Target{
		Keyspace:   ft.Tablet.Keyspace,
		Shard:      ft.Tablet.Shard,
		TabletType: ft.Tablet.Type,
	}
}

func init() {
	// enforce we will use the right protocol (gRPC) in all unit tests
	*tmclient.TabletManagerProtocol = "grpc"
	*tabletconn.TabletProtocol = "grpc"
}


text:
package com.thoughtworks.go.server.web.i18n;

import com.thoughtworks.go.domain.JobResult;
import com.thoughtworks.go.domain.ViewableStatus;

@Deprecated
public final class CurrentResult implements ViewableStatus {

    public static final CurrentResult PASSED = new CurrentResult("Passed");

    public static final CurrentResult FAILED = new CurrentResult("Failed");

    public static final CurrentResult UNKNOWN = new CurrentResult("Unknown");

    private final String result;

    public static CurrentResult getCurrentResult(JobResult result) {
        switch (result) {
            case Cancelled:
            case Failed:
                return FAILED;
            case Passed:
                return PASSED;
            default:
                return UNKNOWN;
        }
    }

    private CurrentResult(String result) {
        this.result = result;
    }

    public String getStatus() {
        return result;
    }

    public String getCruiseStatus() {
        return getStatus();
    }

    public JobResult getBuildInstanceResult() {
        if (CurrentResult.PASSED.equals(this)) {
            return JobResult.Passed;
        }
        if (CurrentResult.FAILED.equals(this)) {
            return JobResult.Failed;
        }
        return JobResult.Unknown;
    }
}


text:
package dynaml

import (
	"github.com/cloudfoundry-incubator/spiff/yaml"
)

type NilExpr struct{}

func (e NilExpr) Evaluate(Binding) (yaml.Node, bool) {
	return node(nil), true
}

func (e NilExpr) String() string {
	return "nil"
}


text:
package org.wso2.developerstudio.datamapper.diagram.custom.model.transformers;

import org.wso2.developerstudio.datamapper.DataMapperOperatorType;
import org.wso2.developerstudio.datamapper.diagram.custom.model.DMOperation;
import org.wso2.developerstudio.datamapper.diagram.custom.model.IModelTransformer;
import org.wso2.developerstudio.datamapper.impl.CustomFunctionImpl;
import org.wso2.developerstudio.datamapper.impl.OperatorImpl;

public class CustomOperatorModelTransformer implements IModelTransformer {

	@Override
	public DMOperation transform(OperatorImpl operator, int index) {
		if (operator instanceof CustomFunctionImpl) {
			CustomFunctionImpl customOperator = (CustomFunctionImpl) operator;
			DMOperation customFunctionOperatorModel = new DMOperation(DataMapperOperatorType.CUSTOM_FUNCTION,
					operator.toString(), index);
			customFunctionOperatorModel.addProperty(TransformerConstants.CUSTOM_FUNCTION_NAME,
					customOperator.getFunctionName());
			customFunctionOperatorModel.addProperty(TransformerConstants.CUSTOM_FUNCTION_DEFINITION,
					customOperator.getFunctionDefinition());
			return customFunctionOperatorModel;
		}
		throw new IllegalArgumentException("CustomFunctionImpl operator expected. Found : " + operator.toString());
	}
}


text:
/**
 *
 */
package cn.jpush.hdfs.mr.hive;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author dengjie
 * @date 2014年12月4日
 * @description 提供一个JDBC访问hive的原型,若用在实际业务中,可拓展该类。
 */
public class HiveVisit {

    static {
	// 注册jdbc驱动
	try {
	    Class.forName("org.apache.hadoop.hive.jdbc.HiveDriver");
	} catch (ClassNotFoundException e) {
	    e.printStackTrace();
	}
    }

    private static Logger log = LoggerFactory.getLogger(HiveVisit.class);

    private static Connection conn = null;
    private static Statement st = null;

    public static boolean getInstance() {
	try {
	    if (conn == null || st == null) {
		conn = DriverManager.getConnection("jdbc:hive://10.211.55.18:10000/default", "", "");
		st = conn.createStatement();
	    }
	} catch (Exception ex) {
	    ex.printStackTrace();
	    log.error("Conn Init error | " + ex.getMessage());
	    return false;
	}
	return true;
    }

    /**
     * exec crud sql
     *
     * @param hql
     */
    public static void exec(String hql) {
	try {
	    if (getInstance()) {
		st.executeQuery(hql);
	    } else {
		System.out.println("conn init failed");
	    }
	} catch (Exception ex) {
	    ex.printStackTrace();
	}
    }

    public static void create(String hql) {
	try {
	    if (getInstance()) {
		ResultSet rs = st.executeQuery(hql);
		// 显示所有的表
		String sql = "show tables";
		System.out.println("running:" + sql);
		rs = st.executeQuery(sql);
		if (rs.next()) {
		    System.out.println(rs.getString(1));
		}
	    }
	} catch (Exception ex) {
	    ex.printStackTrace();
	}
    }

    public static void list(String hql) {
	ResultSet rs = null;
	try {
	    if (getInstance()) {
		rs = st.executeQuery(hql);
		// 显示所有的表
		String sql = "show tables";
		System.out.println("running:" + sql);
		rs = st.executeQuery(sql);
		while (rs.next()) {
		    System.out.println(rs.getString(1) + "\t" + rs.getString(2));
		}
	    }
	} catch (Exception ex) {
	    ex.printStackTrace();
	}
    }

    public static void main(String[] args) throws Exception {
	// 创建连接
	System.setProperty("hadoop.home.dir", "/Users/dengjie/HDFS/hadoop-2.5.1");
	Connection conn = DriverManager.getConnection("jdbc:hive://10.211.55.18:10000/default", "", "");
	Statement st = conn.createStatement();
	String tableName = "stu";
	// 删除表
	st.executeQuery("drop table " + tableName);
	// 创建表
	ResultSet rs = st.executeQuery("create table " + tableName + "(" + "id string," + "name string," + "sex string" + ")" + "row format delimited " + "fields terminated by ',' " + "stored as textfile");
	// 显示所有的表
	String sql = "show tables";
	System.out.println("running:" + sql);
	rs = st.executeQuery(sql);
	if (rs.next()) {
	    System.out.println(rs.getString(1));
	}
	// 得到表信息
	sql = "describe " + tableName;
	System.out.println("running:" + sql);
	rs = st.executeQuery(sql);
	while (rs.next()) {
	    System.out.println(rs.getString(1) + "\t" + rs.getString(2));
	}
	// 加载hdfs的数据
	// String filePath =
	// "hdfs://10.211.55.12:9000/home/hive/warehouse/stu/people";
	// sql = "load data inpath '" + filePath + "' overwrite into table " +
	// tableName;

	// 加载本地的数据
	sql = "load data local inpath '/home/hadoop/hdfs/people' overwrite into table " + tableName;
	System.out.println("running:" + sql);
	rs = st.executeQuery(sql);
	// 查询数据
	sql = "select id as id,name as name,sex as sex from " + tableName + " limit 5";
	System.out.println("running:" + sql);
	rs = st.executeQuery(sql);
	while (rs.next()) {
	    System.out.println(rs.getString("id") + "," + rs.getString("name") + "," + rs.getString("sex"));
	}
	// 查询数量
	sql = "select count(*) as count from " + tableName;
	System.out.println("running:" + sql);
	rs = st.executeQuery(sql);
	while (rs.next()) {
	    System.out.println(rs.getString("count"));
	}
	// 关闭资源
	rs.close();
	st.close();
	conn.close();
    }

}


text:
<?php
/**
 * Created by PhpStorm.
 * User: hrustbb
 * Date: 17.10.16
 * Time: 3:59
 */

namespace common\models;

use Yii;
use yii\db\ActiveRecord;
use common\models\Project;
use common\models\Task;

class UsersProjects extends ActiveRecord
{

    const CONFIRMED = 10;
    const NOT_CONFIRMED = 20;
    const BLOCKED = 30;

    private $_project = null;

    public static function tableName()
    {
        return 'users_projects';
    }

    public function getStatus($project_id, $user_id){
        $r = UsersProjects::findOne(['project_id'=>$project_id, 'user_id'=>$user_id]);
        return $r->status;
    }

    /**
     * проект нанимает юзера
     * @param $project_id
     * @param $user_id
     */
    public function addNew($project_id, $user_id){
        $this->user_id = $user_id;
        $this->project_id = $project_id;
        $this->status = self::NOT_CONFIRMED;
        $date = new \DateTime();
        $created_at = $date->format('Y-m-d H:i:s');
        $this->created_at = $created_at;

        $this->save();

        //приглашенный получает роль сотрудника в проекте
        $role = Yii::$app->authManager->getRole('employee');
        Yii::$app->authManager->myAssign($project_id, $role, $user_id);

        return $this;
    }

    public function getProjectFromProjectId($project_id){
        if($this->_project === null){
            $project_model = new Project();
            $this->_project = $project_model->getProject($project_id);
        }
        return $this->_project;
    }

    public function confirmPart($project_id){
        $user_id = Yii::$app->user->id;
        UsersProjects::updateAll(['status' => UsersProjects::CONFIRMED], ['user_id'=>$user_id, 'project_id'=>$project_id]);
    }

    public function escapePart($project_id){
        $taskmodel = new Task();
        $user_id = Yii::$app->user->id;
        $assigmenttable = Yii::$app->authManager->assignmentTable;
        $taskmodel->unfinishedAllMyTasks($project_id);
        UsersProjects::deleteAll(['project_id'=>$project_id, 'user_id'=>$user_id]);
        $this->getDb()->createCommand()->delete($assigmenttable, ['project_id'=>$project_id, 'user_id'=>$user_id])->execute();
        return true;
    }

}


text:
package ipallowlist

import (
	"context"
	"errors"
	"fmt"

	"github.com/traefik/traefik/v2/pkg/config/dynamic"
	"github.com/traefik/traefik/v2/pkg/ip"
	"github.com/traefik/traefik/v2/pkg/log"
	"github.com/traefik/traefik/v2/pkg/middlewares"
	"github.com/traefik/traefik/v2/pkg/tcp"
)

const (
	typeName = "IPAllowListerTCP"
)

// ipAllowLister is a middleware that provides Checks of the Requesting IP against a set of Allowlists.
type ipAllowLister struct {
	next        tcp.Handler
	allowLister *ip.Checker
	name        string
}

// New builds a new TCP IPAllowLister given a list of CIDR-Strings to allow.
func New(ctx context.Context, next tcp.Handler, config dynamic.TCPIPAllowList, name string) (tcp.Handler, error) {
	logger := log.FromContext(middlewares.GetLoggerCtx(ctx, name, typeName))
	logger.Debug("Creating middleware")

	if len(config.SourceRange) == 0 {
		return nil, errors.New("sourceRange is empty, IPAllowLister not created")
	}

	checker, err := ip.NewChecker(config.SourceRange)
	if err != nil {
		return nil, fmt.Errorf("cannot parse CIDRs %s: %w", config.SourceRange, err)
	}

	logger.Debugf("Setting up IPAllowLister with sourceRange: %s", config.SourceRange)

	return &ipAllowLister{
		allowLister: checker,
		next:        next,
		name:        name,
	}, nil
}

func (al *ipAllowLister) ServeTCP(conn tcp.WriteCloser) {
	ctx := middlewares.GetLoggerCtx(context.Background(), al.name, typeName)
	logger := log.FromContext(ctx)

	addr := conn.RemoteAddr().String()

	err := al.allowLister.IsAuthorized(addr)
	if err != nil {
		logger.Errorf("Connection from %s rejected: %v", addr, err)
		conn.Close()
		return
	}

	logger.Debugf("Connection from %s accepted", addr)

	al.next.ServeTCP(conn)
}


text:
import { fromStorage } from "..";

describe('fromStorage detector', () => {
  it('should return a correct value from the local storage stored', () => {
    localStorage.setItem("lang", "es_ES")
    expect(fromStorage("lang")).toEqual("es_ES")
    localStorage.setItem("lang", null)
    expect(fromStorage("lang")).toEqual("null")
  });

  it('should return a correct value from the session storage if opts passed', () => {
    sessionStorage.setItem("lang", "en_EN")
    expect(fromStorage("lang", { useSessionStorage: true })).toEqual("en_EN")
    sessionStorage.setItem("lang", null)
    expect(fromStorage("lang", { useSessionStorage: true })).toEqual("null")
  });
});


text:
// This file is automatically generated.

package adila.db;

/*
 * Apex TM785CH
 *
 * DEVICE: tm785ch
 * MODEL: TM785CH
 */
final class tm785ch {
    public static final String DATA = "Apex|TM785CH|";
}


text:
from datetime import datetime
from twisted.internet import reactor
from twisted.web import xmlrpc
from twisted.internet.defer import inlineCallbacks, Deferred, returnValue

from vumi.message import TransportUserMessage
from vumi.transports.base import Transport
from vumi.config import (
    ConfigServerEndpoint, ConfigInt, ConfigDict, ConfigText,
    ServerEndpointFallback)
from vumi.components.session import SessionManager
from vumi.transports.httprpc.httprpc import HttpRpcHealthResource
from vumi.utils import build_web_site

class MTNRwandaUSSDTransportConfig(Transport.CONFIG_CLASS):
    """
    MTN Rwanda USSD transport configuration.
    """
    twisted_endpoint = ConfigServerEndpoint(
        "The listening endpoint that the remote client will connect to.",
        required=True, static=True,
        fallbacks=[ServerEndpointFallback()])
    timeout = ConfigInt(
        "No. of seconds to wait before removing a request that hasn't "
        "received a response yet.",
        default=30, static=True)
    redis_manager = ConfigDict(
        "Parameters to connect to redis with",
        default={}, static=True)
    session_timeout_period = ConfigInt(
        "Maximum length of a USSD session",
        default=600, static=True)
    web_path = ConfigText(
        "The path to serve this resource on.", required=True, static=True)
    health_path = ConfigText(
        "The path to serve the health resource on.", default='/health/',
        static=True)

    # TODO: Deprecate these fields when confmodel#5 is done.
    host = ConfigText(
        "*DEPRECATED* 'host' and 'port' fields may be used in place of the"
        " 'twisted_endpoint' field.", static=True)
    port = ConfigInt(
        "*DEPRECATED* 'host' and 'port' fields may be used in place of the"
        " 'twisted_endpoint' field.", static=True)

class RequestTimedOutError(Exception):
    pass

class InvalidRequest(Exception):
    pass

class MTNRwandaUSSDTransport(Transport):

    transport_type = 'ussd'
    xmlrpc_server = None

    CONFIG_CLASS = MTNRwandaUSSDTransportConfig
    ENCODING = 'UTF-8'

    @inlineCallbacks
    def setup_transport(self):
        """
        Transport specific setup - it sets up a connection.
        """
        self._requests = {}
        self._requests_deferreds = {}
        self.callLater = reactor.callLater

        config = self.get_static_config()
        self.endpoint = config.twisted_endpoint
        self.timeout = config.timeout

        r_prefix = "vumi.transports.mtn_rwanda:%s" % self.transport_name
        self.session_manager = yield SessionManager.from_redis_config(
            config.redis_manager, r_prefix,
            config.session_timeout_period)

        self.factory = build_web_site({
            config.health_path: HttpRpcHealthResource(self),
            config.web_path: MTNRwandaXMLRPCResource(self),
        })

        self.xmlrpc_server = yield self.endpoint.listen(self.factory)

    @inlineCallbacks
    def teardown_transport(self):
        """
        Clean-up of setup done in setup_transport.
        """
        self.session_manager.stop()
        if self.xmlrpc_server is not None:
            yield self.xmlrpc_server.stopListening()

    def get_health_response(self):
        return "OK"

    def set_request(self, request_id, request_args):
        self._requests[request_id] = request_args
        return request_args

    def get_request(self, request_id):
        if request_id in self._requests:
            request = self._requests[request_id]
            return request

    def remove_request(self, request_id):
        del self._requests[request_id]

    def timed_out(self, request_id):
        d = self._requests_deferreds[request_id]
        self.remove_request(request_id)
        d.errback(RequestTimedOutError(
            "Request %r timed out." % (request_id,)))

    REQUIRED_INBOUND_MESSAGE_FIELDS = set([
        'TransactionId', 'TransactionTime', 'MSISDN', 'USSDServiceCode',
        'USSDRequestString'])

    def validate_inbound_data(self, msg_params):
        missing_fields = (
                self.REQUIRED_INBOUND_MESSAGE_FIELDS - set(msg_params))
        if missing_fields:
            return False
        else:
            return True

    @inlineCallbacks
    def handle_raw_inbound_request(self, message_id, values, d):
        """
        Called by the XML-RPC server when it receives a payload that
        needs processing.
        """
        self.timeout_request = self.callLater(self.timeout,
                                              self.timed_out, message_id)
        self._requests[message_id] = values
        self._requests_deferreds[message_id] = d
        if not self.validate_inbound_data(values.keys()):
            self.timeout_request.cancel()
            self.remove_request(message_id)
            d.errback(InvalidRequest("4001: Missing Parameters"))

        else:
            session_id = values['TransactionId']
            session = yield self.session_manager.load_session(session_id)
            if session:
                session_event = TransportUserMessage.SESSION_RESUME
                content = values['USSDRequestString']
            else:
                yield self.session_manager.create_session(
                    session_id, from_addr=values['MSISDN'],
                    to_addr=values['USSDServiceCode'])
                session_event = TransportUserMessage.SESSION_NEW
                content = None

            metadata = {
                    'transaction_id': values['TransactionId'],
                    'transaction_time': values['TransactionTime'],
                    }

            res = yield self.publish_message(
                message_id=message_id,
                content=content,
                from_addr=values['MSISDN'],
                to_addr=values['USSDServiceCode'],
                session_event=session_event,
                transport_type=self.transport_type,
                transport_metadata={'mtn_rwanda_ussd': metadata}
                )

            returnValue(res)

    @inlineCallbacks
    def finish_request(self, request_id, data, session_event):
        request = self.get_request(request_id)
        del request['USSDRequestString']
        request['USSDResponseString'] = data
        request['TransactionTime'] = datetime.now().isoformat()
        if session_event == TransportUserMessage.SESSION_NEW:
            request['action'] = 'request'
        elif session_event == TransportUserMessage.SESSION_CLOSE:
            request['action'] = 'end'
            yield self.session_manager.clear_session(request['TransactionId'])
        elif session_event == TransportUserMessage.SESSION_RESUME:
            request['action'] = 'notify'
        self.set_request(request_id, request)
        d = self._requests_deferreds[request_id]
        self.remove_request(request_id)
        d.callback(request)

    def handle_outbound_message(self, message):
        """
        Read outbound message and do what needs to be done with them.
        """
        request_id = message['in_reply_to']

        if self.get_request(request_id) is None:
            return self.publish_nack(user_message_id=message['message_id'],
                    sent_message_id=message['message_id'],
                    reason='Request not found')

        self.timeout_request.cancel()
        self.finish_request(request_id,
                message.payload['content'].encode('utf-8'),
                message['session_event'])
        return self.publish_ack(user_message_id=request_id,
                sent_message_id=request_id)

class MTNRwandaXMLRPCResource(xmlrpc.XMLRPC):
    """
    A Resource object implementing XML-RPC, can be published using
    twisted.web.server.Site.
    """

    def __init__(self, transport):
        self.transport = transport
        xmlrpc.XMLRPC.__init__(self, allowNone=True)

    def xmlrpc_handleUSSD(self, request_data):
        request_id = Transport.generate_message_id()
        d = Deferred()
        self.transport.handle_raw_inbound_request(request_id, request_data, d)
        return d


text:
require "#{Dir.home}/ruby/pianoforall/section01/lesson14/slash_straight_beat"
use_synth :piano

slash_straight_half_beat_bounce(:D4, :minor)
slash_straight_half_beat_bounce(:D4, :minor, bass_note: :C3)
slash_straight_half_beat_bounce(:D4, :minor, bass_note: :B2)
slash_straight_half_beat_bounce(:D4, :minor, bass_note: :Bb2)
slash_straight_half_beat_bounce(:A3)
slash_straight_half_beat_bounce(:A3, bass_note: :G2)
slash_straight_half_beat_bounce(:A3, bass_note: :F2)
slash_straight_half_beat_bounce(:A3, bass_note: :E2)

slash_straight_half_beat_bounce(:D4, :minor, reps: 2)
slash_straight_half_beat_bounce(:C4, reps: 2)
slash_straight_half_beat_bounce(:F3, reps: 2)
slash_straight_half_beat_bounce(:C4, reps: 2)
slash_straight_half_beat_bounce(:A3)
slash_straight_half_beat_bounce(:A3, bass_note: :G2)
slash_straight_half_beat_bounce(:A3, bass_note: :F2)
slash_straight_half_beat_bounce(:A3, bass_note: :E2)
play chord(:D4, :minor)
play :D3


text:
#ifndef THREAD_H
#define THREAD_H

#include <Windows.h>

namespace Crux
{

/**
* A simple thread wrapper
*/

class Thread
{
public:
	Thread();
	virtual ~Thread() {}

public:
	bool Start();

	virtual void Run() = 0;
	virtual void Shutdown();

	bool Runnable() const;
	void SetRunnable( bool runnable );

	HANDLE CurrentThread() const;

private:
	static unsigned int __stdcall ThreadFunction( void* arg );

private:
	HANDLE m_ThreadID;
	bool m_Runnable;
};

} //namespace Crux

#endif //THREAD_H