text:
package org.apache.camel.component.aws.sns;

import java.nio.ByteBuffer;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import com.amazonaws.services.sns.model.MessageAttributeValue;
import com.amazonaws.services.sns.model.PublishRequest;
import com.amazonaws.services.sns.model.PublishResult;
import org.apache.camel.Endpoint;
import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.spi.HeaderFilterStrategy;
import org.apache.camel.support.DefaultProducer;
import org.apache.camel.util.URISupport;

import static org.apache.camel.component.aws.common.AwsExchangeUtil.getMessageForResponse;

/**
 * A Producer which sends messages to the Amazon Web Service Simple Notification Service
 * AWS SNS
 */
public class SnsProducer extends DefaultProducer {

    private transient String snsProducerToString;

    public SnsProducer(Endpoint endpoint) {
        super(endpoint);
    }

    public void process(Exchange exchange) throws Exception {
        PublishRequest request = new PublishRequest();

        request.setTopicArn(getConfiguration().getTopicArn());
        request.setSubject(determineSubject(exchange));
        request.setMessageStructure(determineMessageStructure(exchange));
        request.setMessage(exchange.getIn().getBody(String.class));
        request.setMessageAttributes(this.translateAttributes(exchange.getIn().getHeaders(), exchange));

        log.trace("Sending request [{}] from exchange [{}]...", request, exchange);

        PublishResult result = getEndpoint().getSNSClient().publish(request);

        log.trace("Received result [{}]", result);

        Message message = getMessageForResponse(exchange);
        message.setHeader(SnsConstants.MESSAGE_ID, result.getMessageId());
    }

    private String determineSubject(Exchange exchange) {
        String subject = exchange.getIn().getHeader(SnsConstants.SUBJECT, String.class);
        if (subject == null) {
            subject = getConfiguration().getSubject();
        }

        return subject;
    }

    private String determineMessageStructure(Exchange exchange) {
        String structure = exchange.getIn().getHeader(SnsConstants.MESSAGE_STRUCTURE, String.class);
        if (structure == null) {
            structure = getConfiguration().getMessageStructure();
        }

        return structure;
    }

    Map<String, MessageAttributeValue> translateAttributes(Map<String, Object> headers, Exchange exchange) {
        Map<String, MessageAttributeValue> result = new HashMap<>();
        HeaderFilterStrategy headerFilterStrategy = getEndpoint().getHeaderFilterStrategy();
        for (Entry<String, Object> entry : headers.entrySet()) {
            // only put the message header which is not filtered into the message attribute
            if (!headerFilterStrategy.applyFilterToCamelHeaders(entry.getKey(), entry.getValue(), exchange)) {
                Object value = entry.getValue();
                if (value instanceof String && !((String)value).isEmpty()) {
                    MessageAttributeValue mav = new MessageAttributeValue();
                    mav.setDataType("String");
                    mav.withStringValue((String)value);
                    result.put(entry.getKey(), mav);
                } else if (value instanceof ByteBuffer) {
                    MessageAttributeValue mav = new MessageAttributeValue();
                    mav.setDataType("Binary");
                    mav.withBinaryValue((ByteBuffer)value);
                    result.put(entry.getKey(), mav);
                } else if (value instanceof Date) {
                    MessageAttributeValue mav = new MessageAttributeValue();
                    mav.setDataType("String");
                    mav.withStringValue(value.toString());
                    result.put(entry.getKey(), mav);
                } else {
                    // cannot translate the message header to message attribute value
                    log.warn("Cannot put the message header key={}, value={} into Sns MessageAttribute", entry.getKey(), entry.getValue());
                }
            }
        }
        return result;
    }

    protected SnsConfiguration getConfiguration() {
        return getEndpoint().getConfiguration();
    }

    @Override
    public String toString() {
        if (snsProducerToString == null) {
            snsProducerToString = "SnsProducer[" + URISupport.sanitizeUri(getEndpoint().getEndpointUri()) + "]";
        }
        return snsProducerToString;
    }

    @Override
    public SnsEndpoint getEndpoint() {
        return (SnsEndpoint) super.getEndpoint();
    }

}


text:
require 'spec_helper'

describe ActiveRecord::Relation do
  describe '#percentage' do
    let(:error_number) { 1 }
    let(:success_number) { 1 }

    before do
      Document.all.each(&:destroy)
      error_number.times { Document.create(status: :error) }
      success_number.times { Document.create(status: :success) }
    end

    context 'when there are 50% documents with error' do
      it do
        expect(Document.all.percentage(status: :error)).to eq(0.5)
      end
    end

    context 'when there are 25% documents with error' do
      let(:success_number) { 3 }

      it do
        expect(Document.all.percentage(status: :error)).to eq(0.25)
      end
    end

    context 'when passing a sub scope' do
      before do
        Document.create(status: :on_going)
      end

      it 'does the math inside the scope' do
        expect(Document.where(status: [:error, :success]).percentage(status: :error)).to eq(0.5)
      end
    end

    context 'when passing a scope name instead of query' do
      it 'does the math inside the scope' do
        expect(Document.all.percentage(:with_error)).to eq(0.5)
      end
    end
  end

  describe '#pluck_as_json' do
    let(:json) { Document.all.pluck_as_json(:id, :status) }
    let(:expected) do
      [ { id: 1, status: 'error' }, { id: 2, status: 'success' } ]
    end

    before do
      Document.all.each(&:destroy)
      Document.create(id: 1, status: :error)
      Document.create(id: 2, status: :success)
    end

    it 'returns an array of hashes' do
      expect(json).to eq(expected)
    end

    context 'when no arguments are given' do
      let(:keys) do
        Document.all.pluck_as_json.first.keys
      end
      let(:expected) {%w(id status updated_at created_at)}

      it 'returns all keys' do
        expect(keys).to match_array(expected)
      end
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
<!doctype html>

	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<title>Logless | Bespoken Tools</title>
	<meta name="description" content="">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<link rel="stylesheet" href="../assets/css/main.css">

						Search
						<input id="tsd-search-field" type="text" />

Preparing search index...

The search index is not available

					Bespoken Tools

						Options

								All

Public

Public/Protected

All

							<input type="checkbox" id="tsd-filter-inherited" checked />
							Inherited

					Menu

					Globals

					Logless

Class Logless

Logless will automatically capture logs and diagnostics for your Node.js Lambda.

To use it, simply wrap your function handler, like so:

    var bst = require('bespoken-tools');

    exports.handler = bst.Logless.capture("<SOURCE_ID>", function (event, context) {
        // Lambda code goes here
        context.done(null, "Hello World");
    });

That's all there is to it. Then you can see all your logs through our handy dashboard!

We will effortlessly capture and format:

Request and response payloads

Console output (including instrumentation for timing and all debug levels)

Error and stack traces

Hierarchy

						Logless

Index

Properties

Domain

Methods

capture

Properties

Static Domain

Domain: string = "logless.bespoken.tools"

Defined in logless/logless.ts:28

Methods

Static capture

capture(source: string, handler: LambdaFunction): LambdaFunction

Defined in logless/logless.ts:30

Parameters

source: string

handler: LambdaFunction

Returns LambdaFunction

						Globals

						Audio<wbr>Item

						Audio<wbr>Item<wbr>Stream

						BSTAlexa

						BSTAlexa<wbr>Events

						BSTEncode

						Lambda<wbr>Server

						Logless

								Domain

								capture

						AWSEncoder<wbr>Config

						Lambda<wbr>Function

Legend

Module

Object literal

Variable

Function

Function with type parameter

Index signature

Type alias

Enumeration

Enumeration member

Property

Method

Interface

Interface with type parameter

Constructor

Property

Method

Index signature

Class

Class with type parameter

Constructor

Property

Method

Accessor

Index signature

Inherited constructor

Inherited property

Inherited method

Inherited accessor

Protected property

Protected method

Protected accessor

Private property

Private method

Private accessor

Static property

Static method

Generated using TypeDoc


text:
local jdtls    = require("jdtls")
local handlers = require("lsp.handlers")

local function on_init(client)
  if client.config.settings then
    client.notify("workspace/didChangeConfiguration", { settings = client.config.settings })
  end
end

local home = os.getenv("HOME")
local share_dir = home .. "/.local/share"
local infra_dir = home .. "/dev/nvim-infra"
local project_name = vim.fn.fnamemodify(vim.fn.getcwd(), ":p:h:t")
local workspace_dir = share_dir .. "/eclipse/" .. project_name

local jar_patterns = {
  infra_dir .. '/java-debug/com.microsoft.java.debug.plugin/target/com.microsoft.java.debug.plugin-*.jar',
  -- TODO   '/dev/dgileadi/vscode-java-decompiler/server/*.jar',
  infra_dir .. '/vscode-java-test/server/*.jar'
}
local bundles = {}
for _, jar_pattern in ipairs(jar_patterns) do
  for _, bundle in ipairs(vim.split(vim.fn.glob(jar_pattern), '\n')) do
    -- exclude this jar as it is not a bundle
    --if not vim.endswith(bundle, 'com.microsoft.java.test.runner.jar') then
    if not bundle:find('java.test.runner', 1, true) then
      table.insert(bundles, bundle)
    end
  end
end

local function on_attach(client, bufnr)
  handlers.on_attach(client, bufnr)
  if client.name == "jdtls" then
    jdtls = require("jdtls")
    jdtls.setup_dap({ hotcodereplace = "auto" })
    jdtls.setup.add_commands()
    -- Auto-detect main and setup dap config
    require("jdtls.dap").setup_dap_main_class_configs({ config_overrides = {
      vmArgs = "-Dspring.profiles.active=local",
    } })
  end
end

local config = {
  cmd = {
    '/home/collin/.sdkman/candidates/java/17.0.2-open/bin/java', -- use whichever java is on the path (use sdkman)
    '-Declipse.application=org.eclipse.jdt.ls.core.id1',
    '-Dosgi.bundles.defaultStartLevel=4',
    '-Declipse.product=org.eclipse.jdt.ls.core.product',
    '-Dlog.protocol=true',
    '-Dlog.level=ALL',
    '-Xms256m',
    '-Xmx2048m',
    '--add-modules=ALL-SYSTEM',
    '--add-opens', 'java.base/java.util=ALL-UNNAMED',
    '--add-opens', 'java.base/java.lang=ALL-UNNAMED',
    '-jar', LSP_ROOT_PATH .. '/jdtls/plugins/org.eclipse.equinox.launcher_1.6.400.v20210924-0641.jar',
    '-configuration', LSP_ROOT_PATH .. '/jdtls/config_linux',
    '-data', workspace_dir
  },

  flags = {
    debounce_text_changes = 150,
    allow_incremental_sync = true
  },
  root_dir = jdtls.setup.find_root({ ".project", ".git" }),

  on_init = on_init,
  init_options = {
    bundles = bundles
  },
  capabilities = handlers.capabilities,
  on_attach = on_attach,
  settings = {
    java = {
      format = {
        settings = {
          url = home .. "/dev/work/codestyle/sonatype-eclipse.xml"
        }
      },
      settings = {
        url = home .. "/dev/work/org.eclipse.jdt.core.prefs"
      },
      signatureHelp = {
        enabled = true
      },
      saveActions = {
        organizeImports = true
      },
      completion = {
        maxResults = 20,
        favoriteStaticMembers = {
          "org.hamcrest.MatcherAssert.assertThat",
          "org.hamcrest.Matchers.*",
          "org.hamcrest.CoreMatchers.*",
          "org.junit.jupiter.api.Assertions.*",
          "java.util.Objects.requireNonNull",
          "java.util.Objects.requireNonNullElse",
          "org.mockito.Mockito.*"
        }
      },
      sources = {
        organizeImports = {
          starThreshold = 9999,
          staticStarThreshold = 9999
        }
      },
      codeGeneration = {
        toString = {
          template = "${object.className}{${member.name()}=${member.value}, ${otherMembers}}"
        }
      },
      configuration = {
        -- See https://github.com/eclipse/eclipse.jdt.ls/wiki/Running-the-JAVA-LS-server-from-the-command-line#initialize-request
        -- And search for `interface RuntimeOption`
        -- The `name` is NOT arbitrary, but must match one of the elements from `enum ExecutionEnvironment` in the link above
        runtimes = {
          {
            name = "JavaSE-1.8",
            path = "/home/collin/.sdkman/candidates/java/8.0.345-tem",
          },
          {
            name = "JavaSE-11",
            path = "/home/collin/.sdkman/candidates/java/11.0.12-open/",
          },
          {
            name = "JavaSE-17",
            path = "/home/collin/.sdkman/candidates/java/17.0.2-open/",
          },
        }
      }
    }
  }
}

local M = {}

M.start = function()
  jdtls.start_or_attach(config)
end

return M


text:
package com.mossle.bpm.data;

import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import com.mossle.bpm.persistence.domain.BpmConfBase;
import com.mossle.bpm.persistence.domain.BpmConfListener;
import com.mossle.bpm.persistence.domain.BpmConfNode;
import com.mossle.bpm.persistence.manager.BpmConfBaseManager;
import com.mossle.bpm.persistence.manager.BpmConfListenerManager;
import com.mossle.bpm.persistence.manager.BpmConfNodeManager;

import com.mossle.core.csv.CsvCallback;

import org.apache.commons.lang3.StringUtils;

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

public class ProcessListenerCallback implements CsvCallback {
    private static Logger logger = LoggerFactory
            .getLogger(ProcessListenerCallback.class);
    private BpmConfBaseManager bpmConfBaseManager;
    private BpmConfListenerManager bpmConfListenerManager;
    private BpmConfNodeManager bpmConfNodeManager;
    private String defaultTenantId = "1";

    public void process(List<String> list, int lineNo) throws Exception {
        String processDefinitionKey = list.get(0);
        String activityId = list.get(1);
        String type = list.get(2);
        String value = list.get(3);

        BpmConfNode bpmConfNode = this.findBpmConfNode(processDefinitionKey,
                activityId);

        if (bpmConfNode == null) {
            logger.info("cannot find bpm conf node : {} {}, skip",
                    processDefinitionKey, activityId);

            return;
        }

        Integer typeValue = this.findType(type);

        // 1 enable 2 disable
        int status = 1;

        BpmConfListener bpmConfListener = new BpmConfListener();
        bpmConfListener.setValue(value);
        bpmConfListener.setType(typeValue);
        bpmConfListener.setStatus(status);
        bpmConfListener.setPriority(0);
        bpmConfListener.setBpmConfNode(bpmConfNode);
        bpmConfListenerManager.save(bpmConfListener);
    }

    public BpmConfNode findBpmConfNode(String processDefinitionKey,
            String activityId) {
        BpmConfBase bpmConfBase = this.findBpmConfBase(processDefinitionKey);

        if (bpmConfBase == null) {
            logger.info("cannot find bpm conf base : {}, skip",
                    processDefinitionKey);

            return null;
        }

        String hql = "from BpmConfNode where code=? and bpmConfBase=?";
        BpmConfNode bpmConfNode = bpmConfNodeManager.findUnique(hql,
                activityId, bpmConfBase);

        return bpmConfNode;
    }

    public BpmConfBase findBpmConfBase(String processDefinitionKey) {
        String hql = "from BpmConfBase where processDefinitionKey=? order by processDefinitionVersion desc";
        BpmConfBase bpmConfBase = bpmConfBaseManager.findUnique(hql,
                processDefinitionKey);

        return bpmConfBase;
    }

    public Integer findType(String code) {
        if ("start".equals(code)) {
            return 0;
        } else if ("end".equals(code)) {
            return 1;
        } else if ("take".equals(code)) {
            return 2;
        } else if ("create".equals(code)) {
            return 3;
        } else if ("assign".equals(code)) {
            return 4;
        } else if ("complete".equals(code)) {
            return 5;
        } else if ("delete".equals(code)) {
            return 6;
        } else if ("approve".equals(code)) {
            return 11;
        } else if ("reject".equals(code)) {
            return 12;
        } else if ("process-draft".equals(code)) {
            return 21;
        } else if ("process-start".equals(code)) {
            return 22;
        } else if ("process-close".equals(code)) {
            return 23;
        } else if ("process-end".equals(code)) {
            return 24;
        }

        return -1;
    }

    // ~
    public void setBpmConfBaseManager(BpmConfBaseManager bpmConfBaseManager) {
        this.bpmConfBaseManager = bpmConfBaseManager;
    }

    public void setBpmConfNodeManager(BpmConfNodeManager bpmConfNodeManager) {
        this.bpmConfNodeManager = bpmConfNodeManager;
    }

    public void setBpmConfListenerManager(
            BpmConfListenerManager bpmConfListenerManager) {
        this.bpmConfListenerManager = bpmConfListenerManager;
    }
}


text: lovefunc = lambda flower1, flower2: (flower1 + flower2) & 1


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.toscana.helper.parsing;

/**
 *
 * @author arandilopez
 */
public class ToscanaParseUtility {

    public static String toString(Double doubleToParse){
        return String.valueOf(doubleToParse);
    }

    public static String toString(Integer integerToParse){
        return String.valueOf(integerToParse);
    }

    public static Double stringToDouble(String stringToParse){
        return Double.parseDouble(stringToParse);
    }

    public static int stringToInt(String stringToParse){
        return Integer.parseInt(stringToParse);
    }

}


text:
(function (window, document, undefined) {

    // Edit page script
    function promptText(title, placeholder, callback) {
        var $modal = $("#prompt-text");
        $modal.find("h4").html(title);
        $modal.find("input").val(placeholder);
        $modal.modal();
        // Weirdly written code but it prevents multiple event handlers attached to the same button
        $modal.find(".accept").off("click").on("click", function () {
            callback($modal.find("input").val());
        });
    }

    function promptTextarea(title, placeholder, callback) {
        var $modal = $("#prompt-textarea");
        $modal.find("h4").html(title);
        $modal.find("textarea").html(placeholder);
        $modal.modal();
        // Weirdly written code but it prevents multiple event handlers attached to the same button
        $modal.find(".accept").off("click").on("click", function () {
            callback($modal.find("textarea").html());
        });
    }

    $("#student-name").on("click", function () {
        var title = "Edit your name";
        var text = $(this).html();
        var target = this;
        promptText(title, text, function (input) {
            $(target).html(input);
        });
    });

    $("#student-quote, #student-about").on("click", function () {
        // Lazy developer code follows
        var titles = {
            quote: "Edit your smartass quote",
            about: "Edit your bio"
        };
        var index = $(this).attr("id").split("-")[1];
        var text = $(this).html();
        var target = this;
        promptTextarea(titles[index], text, function (input) {
            $(target).html(input);
        });
    });

    // Script to update all data
    $("#save-changes").click(function () {
        var formData = {};
        formData.name = $("#student-name").html();
        formData.quote = $("#student-quote").html();
        formData.about = $("#student-about").html();
        $.post("/edit.php", formData, function (response) {
            response = JSON.parse(response);
            var $modal = $("#alert");
            $modal.find("h4").html(response.status);
            $modal.find("p").html(response.message);
            $modal.modal();
        });

    });
})(window, document);


text:
require 'spec_helper'

require 'mv/sqlite/validation/builder/trigger/length'

describe Mv::Sqlite::Validation::Builder::Trigger::Length do
  def length(opts = {})
    Mv::Core::Validation::Length.new(:table_name,
                                    :column_name,
                                    { with: /exp/, message: 'has invalid length' }.merge(opts))
  end

  describe "#conditions" do
    subject { described_class.new(length(opts)).conditions }

    describe "when :in is defined" do
      describe "as array" do
        let(:opts) { { in: [1, 3] } }

        it { is_expected.to eq([{
          statement: 'NEW.column_name IS NOT NULL AND LENGTH(NEW.column_name) IN (1, 3)',
          message: 'column_name has invalid length'
        }]) }
      end
    end
  end
end


text:
const path = require('path');
const spies = require('chai-spies');
const chai = require('chai');
const should = chai.should(); // eslint-disable-line no-unused-vars
chai.use(spies);
const expect = chai.expect;
const _ = require('lodash');
const test = require('ava');
const TestUtils = require('fountain-generator').TestUtils;

let context;

test.before(() => {
  context = TestUtils.mock('app');
  require('../../generators/app/index');
  process.chdir(path.resolve(__dirname, '../../'));
});

test.beforeEach(() => {
  context.mergeJson['package.json'] = null;
});

const pkg = {
  devDependencies: {
    'webpack': '^2.2.1',
    'html-webpack-plugin': '^2.28.0',
    'style-loader': '^0.13.1',
    'css-loader': '^0.26.1',
    'postcss-loader': '^1.3.1',
    'autoprefixer': '^6.7.3',
    'json-loader': '^0.5.4',
    'extract-text-webpack-plugin': '^2.0.0-rc.3'
  }
};

test('Configuring package.json with react/babel/css', t => {
  const expected = _.merge({}, pkg, {
    devDependencies: {
      'webpack-dev-middleware': '^1.10.1',
      'webpack-hot-middleware': '^2.17.0',
      'react-hot-loader': '^1.3.1'
    }
  });
  TestUtils.call(context, 'configuring.package', {framework: 'react', js: 'babel', css: 'css'});
  t.deepEqual(context.mergeJson['package.json'], expected);
});

test('Configuring package.json with angular1/babel/css', t => {
  const expected = _.merge({}, pkg, {
    devDependencies: {
      'ng-annotate-loader': '^0.2.0',
      'html-loader': '^0.4.4'
    }
  });
  TestUtils.call(context, 'configuring.package', {framework: 'angular1', js: 'babel', css: 'css'});
  t.deepEqual(context.mergeJson['package.json'], expected);
});

test('Configuring package.json with angular2/typescript/css', t => {
  const expected = _.merge({}, pkg, {
    devDependencies: {
      'ts-loader': '^2.0.0',
      'html-loader': '^0.4.4'
    }
  });
  TestUtils.call(context, 'configuring.package', {framework: 'angular2', js: 'typescript', css: 'css'});
  t.deepEqual(context.mergeJson['package.json'], expected);
});

test('Configuring package.json with angular2/babel/scss', t => {
  const expected = _.merge({}, pkg, {
    devDependencies: {
      'sass-loader': '^6.0.1',
      'node-sass': '^4.5.0',
      'html-loader': '^0.4.4'
    }
  });
  TestUtils.call(context, 'configuring.package', {framework: 'angular2', js: 'babel', css: 'scss'});
  t.deepEqual(context.mergeJson['package.json'], expected);
});

test('Configuring package.json with angular2/babel/less', t => {
  const expected = _.merge({}, pkg, {
    devDependencies: {
      'less-loader': '^2.2.3',
      'less': '^2.7.2',
      'html-loader': '^0.4.4'
    }
  });
  TestUtils.call(context, 'configuring.package', {framework: 'angular2', js: 'babel', css: 'less'});
  t.deepEqual(context.mergeJson['package.json'], expected);
});

test('Configuring package.json with angular2/babel/styl', t => {
  const expected = _.merge({}, pkg, {
    devDependencies: {
      'stylus-loader': '^2.5.0',
      'stylus': '^0.54.5',
      'html-loader': '^0.4.4'
    }
  });
  TestUtils.call(context, 'configuring.package', {framework: 'angular2', js: 'babel', css: 'styl'});
  t.deepEqual(context.mergeJson['package.json'], expected);
});

test('Configuring package.json with vue/babel/styl', t => {
  const expected = _.merge({}, pkg, {
    devDependencies: {
      'stylus-loader': '^2.5.0',
      'stylus': '^0.54.5',
      'vue-loader': '^11.1.0',
      'vue-template-compiler': '^2.1.10'
    }
  });
  TestUtils.call(context, 'configuring.package', {framework: 'vue', js: 'babel', css: 'styl'});
  t.deepEqual(context.mergeJson['package.json'], expected);
});

test('Copy webpack conf with correct options', t => {
  context.copyTemplate = (a, b, opts) => {
    context.copyTemplate[b] = _.clone(opts);
  };
  const spy = chai.spy.on(context, 'copyTemplate');
  const base = {framework: 'angular2', js: 'babel', css: 'styl', modules: 'webpack', sample: 'techs', router: 'router'};
  TestUtils.call(context, 'configuring.conf', base);
  expect(spy).to.have.been.called.exactly(3);
  t.is(context.copyTemplate['conf/webpack.conf.js'].test, false);
  t.is(context.copyTemplate['conf/webpack.conf.js'].dist, false);
  t.is(context.copyTemplate['conf/webpack-test.conf.js'].test, true);
  t.is(context.copyTemplate['conf/webpack-test.conf.js'].dist, false);
  t.is(context.copyTemplate['conf/webpack-dist.conf.js'].test, false);
  t.is(context.copyTemplate['conf/webpack-dist.conf.js'].dist, true);
});

test('gulp(): call this.fs.copyTpl', () => {
  context.templatePath = context.destinationPath = path => path;
  context.fs = {
    copyTpl: () => {}
  };
  const spy = chai.spy.on(context.fs, 'copyTpl');
  TestUtils.call(context, 'writing.gulp');
  expect(spy).to.have.been.called.once();
});


text:
function ThumbsAside(runtime, element, block_element, init_args) {
    return new ThumbsBlock(runtime, element, init_args);
}

function ThumbsBlock(runtime, element, init_args) {
    function updateVotes(votes) {
        $('.upvote .count', element).text(votes.up);
        $('.downvote .count', element).text(votes.down);
    }

    var handlerUrl = runtime.handlerUrl(element, 'vote');

    $('.upvote', element).click(function(eventObject) {
        $.ajax({
            type: "POST",
            url: handlerUrl,
            data: JSON.stringify({voteType: 'up'}),
            success: updateVotes
        });
    });

    $('.downvote', element).click(function(eventObject) {
        $.ajax({
            type: "POST",
            url: handlerUrl,
            data: JSON.stringify({voteType: 'down'}),
            success: updateVotes
        });
    });

    return {};
};


text:
void gtaRwTexDictionary::Initialise(gtaRwUInt16 NumTextures)
{
	memset(this, 0, sizeof(gtaRwTexDictionary));
	_zero = 0;
	deviceId = 2;
	numTextures = NumTextures;
	if(numTextures > 0)
		textures = (gtaRwTextureNative *)gtaMemAlloc(sizeof(gtaRwTextureNative) * NumTextures);
}

void gtaRwTexDictionary::Destroy()
{
	if(textures)
	{
		for(gtaRwInt32 i = 0; i < numTextures; i++)
			textures[i].Destroy();
		free(textures);
	}
}

gtaRwTexDictionary::gtaRwTexDictionary()
{
	memset(this, 0, sizeof(gtaRwTexDictionary));
}

gtaRwBool gtaRwTexDictionary::StreamRead(gtaRwStream *stream)
{
	memset(this, 0, sizeof(gtaRwTexDictionary));
	if(!gtaRwStreamFindChunk(stream, rwID_TEXDICTIONARY, NULL, &version, &build))
		return false;
	if(!gtaRwStreamFindChunk(stream, rwID_STRUCT, NULL, NULL))
		return false;
	if(gtaRwStreamRead(stream, &numTextures, 4) != 4)
		return false;
	if(numTextures > 0)
	{
		textures = (gtaRwTextureNative *)gtaMemAlloc(sizeof(gtaRwTextureNative) * numTextures);
		for(gtaRwInt32 i = 0; i < numTextures; i++)
		{
			if(!textures[i].StreamRead(stream))
			{
				Destroy();
				return false;
			}
		}
	}
	//if(!gtaRwStreamFindChunk(stream, rwID_EXTENSION, NULL, NULL))
	//	return false;
	return true;
}

gtaRwBool gtaRwTexDictionary::StreamWrite(gtaRwStream *stream)
{
	if(!gtaRwStreamWriteVersionedChunkHeader(stream, rwID_TEXDICTIONARY, GetStreamSize() - 12, gtaRwVersion, gtaRwBuild))
		return false;
	if(!gtaRwStreamWriteVersionedChunkHeader(stream, rwID_STRUCT, 4, gtaRwVersion, gtaRwBuild))
		return false;
	if(!gtaRwStreamWrite(stream, &numTextures, 4))
		return false;
	for(gtaRwInt32 i = 0; i < numTextures; i++)
	{
		if(!textures[i].StreamWrite(stream))
			return false;
	}
	if(!gtaRwStreamWriteVersionedChunkHeader(stream, rwID_EXTENSION, 0, gtaRwVersion, gtaRwBuild))
		return false;
	return true;
}

gtaRwUInt32 gtaRwTexDictionary::GetStreamSize()
{
	gtaRwUInt32 size = 40;
	for(gtaRwInt32 i = 0; i < numTextures; i++)
		size += textures[i].GetStreamSize();
	return size;
}


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

namespace AlwaysMoveForward.PointChart.BusinessLayer.Services
{
    public interface IServiceManager
    {
        UserService UserService { get; }
        ChartService Charts { get; }
        TaskService Tasks { get; }
        CompletedTaskService CompletedTaskService { get; }
        PointService PointService { get; }
    }
}


text:
typedef unsigned __int32 TUINT32;
typedef __int64 TINT64;
typedef unsigned __int64 TUINT64;

#elif defined(MACOSX)

#include <stdint.h>

#define TINT32 int32_t
typedef uint32_t TUINT32;
typedef int64_t TINT64;
typedef uint64_t TUINT64;

#elif defined(__LP64__) && (!defined(LINUX))

#define TINT32 \
	;          \
	__int32
typedef unsigned __int32 TSINT32;
typedef __int64 TINT64;
typedef unsigned __int64 TUINT64;

#elif defined(__sgi)

#define TINT32 __int32_t
typedef unsigned __int32_t TUINT32;
typedef __int64_t TINT64;
typedef unsigned __int64_t TUINT64;

#elif defined(LINUX)
#include <stdint.h>
#define TINT32 __int32_t
typedef uint32_t TUINT32;
typedef int64_t TINT64;
typedef uint64_t TUINT64;
#endif

#endif


text:
<!DOCTYPE HTML>

    <canvas id="myCanvas" width="578" height="500">
        This text is displayed if your browser
        does not support HTML5 Canvas.
    </canvas>

Back to Index


text:
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/err.h>
#include <linux/string.h>
#include <linux/platform_device.h>
#include <sound/soc.h>
#include <sound/pcm_params.h>
#include <sound/dmaengine_pcm.h>
#include <uapi/sound/asound.h>
#include <sound/asoundef.h>
#include <sound/omap-pcm.h>
#include <sound/omap-hdmi-audio.h>
#include <video/omapdss.h>

#define DRV_NAME "omap-hdmi-audio"

struct hdmi_audio_data {
	struct snd_soc_card *card;

	const struct omap_hdmi_audio_ops *ops;
	struct device *dssdev;
	struct snd_dmaengine_dai_dma_data dma_data;
	struct omap_dss_audio dss_audio;
	struct snd_aes_iec958 iec;
	struct snd_cea_861_aud_if cea;

	struct mutex current_stream_lock;
	struct snd_pcm_substream *current_stream;
};

static
struct hdmi_audio_data *card_drvdata_substream(struct snd_pcm_substream *ss)
{
	struct snd_soc_pcm_runtime *rtd = ss->private_data;

	return snd_soc_card_get_drvdata(rtd->card);
}

static void hdmi_dai_abort(struct device *dev)
{
	struct hdmi_audio_data *ad = dev_get_drvdata(dev);

	mutex_lock(&ad->current_stream_lock);
	if (ad->current_stream && ad->current_stream->runtime &&
	    snd_pcm_running(ad->current_stream)) {
		dev_err(dev, "HDMI display disabled, aborting playback\n");
		snd_pcm_stream_lock_irq(ad->current_stream);
		snd_pcm_stop(ad->current_stream, SNDRV_PCM_STATE_DISCONNECTED);
		snd_pcm_stream_unlock_irq(ad->current_stream);
	}
	mutex_unlock(&ad->current_stream_lock);
}

static int hdmi_dai_startup(struct snd_pcm_substream *substream,
			    struct snd_soc_dai *dai)
{
	struct hdmi_audio_data *ad = card_drvdata_substream(substream);
	int ret;
	/*
	 * Make sure that the period bytes are multiple of the DMA packet size.
	 * Largest packet size we use is 32 32-bit words = 128 bytes
	 */
	ret = snd_pcm_hw_constraint_step(substream->runtime, 0,
					 SNDRV_PCM_HW_PARAM_PERIOD_BYTES, 128);
	if (ret < 0) {
		dev_err(dai->dev, "Could not apply period constraint: %d\n",
			ret);
		return ret;
	}
	ret = snd_pcm_hw_constraint_step(substream->runtime, 0,
					 SNDRV_PCM_HW_PARAM_BUFFER_BYTES, 128);
	if (ret < 0) {
		dev_err(dai->dev, "Could not apply buffer constraint: %d\n",
			ret);
		return ret;
	}

	snd_soc_dai_set_dma_data(dai, substream, &ad->dma_data);

	mutex_lock(&ad->current_stream_lock);
	ad->current_stream = substream;
	mutex_unlock(&ad->current_stream_lock);

	ret = ad->ops->audio_startup(ad->dssdev, hdmi_dai_abort);

	if (ret) {
		mutex_lock(&ad->current_stream_lock);
		ad->current_stream = NULL;
		mutex_unlock(&ad->current_stream_lock);
	}

	return ret;
}

static int hdmi_dai_hw_params(struct snd_pcm_substream *substream,
			      struct snd_pcm_hw_params *params,
			      struct snd_soc_dai *dai)
{
	struct hdmi_audio_data *ad = card_drvdata_substream(substream);
	struct snd_aes_iec958 *iec = &ad->iec;
	struct snd_cea_861_aud_if *cea = &ad->cea;

	WARN_ON(ad->current_stream != substream);

	switch (params_format(params)) {
	case SNDRV_PCM_FORMAT_S16_LE:
		ad->dma_data.maxburst = 16;
		break;
	case SNDRV_PCM_FORMAT_S24_LE:
		ad->dma_data.maxburst = 32;
		break;
	default:
		dev_err(dai->dev, "format not supported!\n");
		return -EINVAL;
	}

	ad->dss_audio.iec = iec;
	ad->dss_audio.cea = cea;
	/*
	 * fill the IEC-60958 channel status word
	 */
	/* initialize the word bytes */
	memset(iec->status, 0, sizeof(iec->status));

	/* specify IEC-60958-3 (commercial use) */
	iec->status[0] &= ~IEC958_AES0_PROFESSIONAL;

	/* specify that the audio is LPCM*/
	iec->status[0] &= ~IEC958_AES0_NONAUDIO;

	iec->status[0] |= IEC958_AES0_CON_NOT_COPYRIGHT;

	iec->status[0] |= IEC958_AES0_CON_EMPHASIS_NONE;

	iec->status[1] = IEC958_AES1_CON_GENERAL;

	iec->status[2] |= IEC958_AES2_CON_SOURCE_UNSPEC;

	iec->status[2] |= IEC958_AES2_CON_CHANNEL_UNSPEC;

	switch (params_rate(params)) {
	case 32000:
		iec->status[3] |= IEC958_AES3_CON_FS_32000;
		break;
	case 44100:
		iec->status[3] |= IEC958_AES3_CON_FS_44100;
		break;
	case 48000:
		iec->status[3] |= IEC958_AES3_CON_FS_48000;
		break;
	case 88200:
		iec->status[3] |= IEC958_AES3_CON_FS_88200;
		break;
	case 96000:
		iec->status[3] |= IEC958_AES3_CON_FS_96000;
		break;
	case 176400:
		iec->status[3] |= IEC958_AES3_CON_FS_176400;
		break;
	case 192000:
		iec->status[3] |= IEC958_AES3_CON_FS_192000;
		break;
	default:
		dev_err(dai->dev, "rate not supported!\n");
		return -EINVAL;
	}

	/* specify the clock accuracy */
	iec->status[3] |= IEC958_AES3_CON_CLOCK_1000PPM;

	/*
	 * specify the word length. The same word length value can mean
	 * two different lengths. Hence, we need to specify the maximum
	 * word length as well.
	 */
	switch (params_format(params)) {
	case SNDRV_PCM_FORMAT_S16_LE:
		iec->status[4] |= IEC958_AES4_CON_WORDLEN_20_16;
		iec->status[4] &= ~IEC958_AES4_CON_MAX_WORDLEN_24;
		break;
	case SNDRV_PCM_FORMAT_S24_LE:
		iec->status[4] |= IEC958_AES4_CON_WORDLEN_24_20;
		iec->status[4] |= IEC958_AES4_CON_MAX_WORDLEN_24;
		break;
	default:
		dev_err(dai->dev, "format not supported!\n");
		return -EINVAL;
	}

	/*
	 * Fill the CEA-861 audio infoframe (see spec for details)
	 */

	cea->db1_ct_cc = (params_channels(params) - 1)
		& CEA861_AUDIO_INFOFRAME_DB1CC;
	cea->db1_ct_cc |= CEA861_AUDIO_INFOFRAME_DB1CT_FROM_STREAM;

	cea->db2_sf_ss = CEA861_AUDIO_INFOFRAME_DB2SF_FROM_STREAM;
	cea->db2_sf_ss |= CEA861_AUDIO_INFOFRAME_DB2SS_FROM_STREAM;

	cea->db3 = 0; /* not used, all zeros */

	if (params_channels(params) == 2)
		cea->db4_ca = 0x0;
	else if (params_channels(params) == 6)
		cea->db4_ca = 0xb;
	else
		cea->db4_ca = 0x13;

	if (cea->db4_ca == 0x00)
		cea->db5_dminh_lsv = CEA861_AUDIO_INFOFRAME_DB5_DM_INH_PERMITTED;
	else
		cea->db5_dminh_lsv = CEA861_AUDIO_INFOFRAME_DB5_DM_INH_PROHIBITED;

	/* the expression is trivial but makes clear what we are doing */
	cea->db5_dminh_lsv |= (0 & CEA861_AUDIO_INFOFRAME_DB5_LSV);

	return ad->ops->audio_config(ad->dssdev, &ad->dss_audio);
}

static int hdmi_dai_trigger(struct snd_pcm_substream *substream, int cmd,
			    struct snd_soc_dai *dai)
{
	struct hdmi_audio_data *ad = card_drvdata_substream(substream);
	int err = 0;

	WARN_ON(ad->current_stream != substream);

	switch (cmd) {
	case SNDRV_PCM_TRIGGER_START:
	case SNDRV_PCM_TRIGGER_RESUME:
	case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
		err = ad->ops->audio_start(ad->dssdev);
		break;
	case SNDRV_PCM_TRIGGER_STOP:
	case SNDRV_PCM_TRIGGER_SUSPEND:
	case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
		ad->ops->audio_stop(ad->dssdev);
		break;
	default:
		err = -EINVAL;
	}
	return err;
}

static void hdmi_dai_shutdown(struct snd_pcm_substream *substream,
			      struct snd_soc_dai *dai)
{
	struct hdmi_audio_data *ad = card_drvdata_substream(substream);

	WARN_ON(ad->current_stream != substream);

	ad->ops->audio_shutdown(ad->dssdev);

	mutex_lock(&ad->current_stream_lock);
	ad->current_stream = NULL;
	mutex_unlock(&ad->current_stream_lock);
}

static const struct snd_soc_dai_ops hdmi_dai_ops = {
	.startup	= hdmi_dai_startup,
	.hw_params	= hdmi_dai_hw_params,
	.trigger	= hdmi_dai_trigger,
	.shutdown	= hdmi_dai_shutdown,
};

static const struct snd_soc_component_driver omap_hdmi_component = {
	.name = "omapdss_hdmi",
};

static struct snd_soc_dai_driver omap5_hdmi_dai = {
	.name = "omap5-hdmi-dai",
	.playback = {
		.channels_min = 2,
		.channels_max = 8,
		.rates = (SNDRV_PCM_RATE_32000 | SNDRV_PCM_RATE_44100 |
			  SNDRV_PCM_RATE_48000 | SNDRV_PCM_RATE_88200 |
			  SNDRV_PCM_RATE_96000 | SNDRV_PCM_RATE_176400 |
			  SNDRV_PCM_RATE_192000),
		.formats = SNDRV_PCM_FMTBIT_S16_LE,
	},
	.ops = &hdmi_dai_ops,
};

static struct snd_soc_dai_driver omap4_hdmi_dai = {
	.name = "omap4-hdmi-dai",
	.playback = {
		.channels_min = 2,
		.channels_max = 8,
		.rates = (SNDRV_PCM_RATE_32000 | SNDRV_PCM_RATE_44100 |
			  SNDRV_PCM_RATE_48000 | SNDRV_PCM_RATE_88200 |
			  SNDRV_PCM_RATE_96000 | SNDRV_PCM_RATE_176400 |
			  SNDRV_PCM_RATE_192000),
		.formats = SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_S24_LE,
	},
	.ops = &hdmi_dai_ops,
};

static int omap_hdmi_audio_probe(struct platform_device *pdev)
{
	struct omap_hdmi_audio_pdata *ha = pdev->dev.platform_data;
	struct device *dev = &pdev->dev;
	struct hdmi_audio_data *ad;
	struct snd_soc_dai_driver *dai_drv;
	struct snd_soc_card *card;
	int ret;

	if (!ha) {
		dev_err(dev, "No platform data\n");
		return -EINVAL;
	}

	ad = devm_kzalloc(dev, sizeof(*ad), GFP_KERNEL);
	if (!ad)
		return -ENOMEM;
	ad->dssdev = ha->dev;
	ad->ops = ha->ops;
	ad->dma_data.addr = ha->audio_dma_addr;
	ad->dma_data.filter_data = "audio_tx";
	ad->dma_data.addr_width = DMA_SLAVE_BUSWIDTH_4_BYTES;
	mutex_init(&ad->current_stream_lock);

	switch (ha->dss_version) {
	case OMAPDSS_VER_OMAP4430_ES1:
	case OMAPDSS_VER_OMAP4430_ES2:
	case OMAPDSS_VER_OMAP4:
		dai_drv = &omap4_hdmi_dai;
		break;
	case OMAPDSS_VER_OMAP5:
		dai_drv = &omap5_hdmi_dai;
		break;
	default:
		return -EINVAL;
	}
	ret = snd_soc_register_component(ad->dssdev, &omap_hdmi_component,
					 dai_drv, 1);
	if (ret)
		return ret;

	ret = omap_pcm_platform_register(ad->dssdev);
	if (ret)
		return ret;

	card = devm_kzalloc(dev, sizeof(*card), GFP_KERNEL);
	if (!card)
		return -ENOMEM;

	card->name = devm_kasprintf(dev, GFP_KERNEL,
				    "HDMI %s", dev_name(ad->dssdev));
	card->owner = THIS_MODULE;
	card->dai_link =
		devm_kzalloc(dev, sizeof(*(card->dai_link)), GFP_KERNEL);
	card->dai_link->name = card->name;
	card->dai_link->stream_name = card->name;
	card->dai_link->cpu_dai_name = dev_name(ad->dssdev);
	card->dai_link->platform_name = dev_name(ad->dssdev);
	card->dai_link->codec_name = "snd-soc-dummy";
	card->dai_link->codec_dai_name = "snd-soc-dummy-dai";
	card->num_links = 1;
	card->dev = dev;

	ret = snd_soc_register_card(card);
	if (ret) {
		dev_err(dev, "snd_soc_register_card failed (%d)\n", ret);
		snd_soc_unregister_component(ad->dssdev);
		return ret;
	}

	ad->card = card;
	snd_soc_card_set_drvdata(card, ad);

	dev_set_drvdata(dev, ad);

	return 0;
}

static int omap_hdmi_audio_remove(struct platform_device *pdev)
{
	struct hdmi_audio_data *ad = platform_get_drvdata(pdev);

	snd_soc_unregister_card(ad->card);
	snd_soc_unregister_component(ad->dssdev);
	return 0;
}

static struct platform_driver hdmi_audio_driver = {
	.driver = {
		.name = DRV_NAME,
	},
	.probe = omap_hdmi_audio_probe,
	.remove = omap_hdmi_audio_remove,
};

module_platform_driver(hdmi_audio_driver);

MODULE_AUTHOR("Jyri Sarha <jsarha@ti.com>");
MODULE_DESCRIPTION("OMAP HDMI Audio Driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:" DRV_NAME);


text:
// Copyright (c) Christof Senn. All rights reserved. See license.txt in the project root for license information.

namespace Remote.Linq.DynamicQuery
{
    using System;

    /// <summary>
    /// Denotes annotated methods as query marker functions to prevent local evaluation (i.e. execution of the method) when translating expressions.
    /// </summary>
    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
    public class QueryMarkerFunctionAttribute : Attribute
    {
    }
}


text:
import six

from django.contrib.gis.geos import Point
from rest_framework import generics, views, status
from rest_framework import settings as rest_settings
from rest_framework.permissions import DjangoModelPermissions
from rest_framework.compat import OrderedDict

from facilities.models import Facility
from common.views import AuditableDetailViewMixin
from common.utilities import CustomRetrieveUpdateDestroyView

from .models import (
    GeoCodeSource,
    GeoCodeMethod,
    FacilityCoordinates,
    WorldBorder,
    CountyBoundary,
    ConstituencyBoundary,
    WardBoundary,
    DrilldownView
)
from .filters import (
    GeoCodeSourceFilter,
    GeoCodeMethodFilter,
    FacilityCoordinatesFilter,
    WorldBorderFilter,
    CountyBoundaryFilter,
    ConstituencyBoundaryFilter,
    WardBoundaryFilter
)
from .serializers import (
    GeoCodeSourceSerializer,
    GeoCodeMethodSerializer,
    FacilityCoordinatesListSerializer,
    FacilityCoordinatesDetailSerializer,
    WorldBorderSerializer,
    WorldBorderDetailSerializer,
    CountyBoundarySerializer,
    ConstituencyBoundarySerializer,
    WardBoundarySerializer,
    CountyBoundaryDetailSerializer,
    ConstituencyBoundaryDetailSerializer,
    WardBoundaryDetailSerializer,
    FacilityCoordinateSimpleSerializer,
    CountyBoundSerializer,
    ConstituencyBoundSerializer,
    BufferCooridinatesMixin,
    DrillCountyBoundarySerializer,
    DrillConstituencyBoundarySerializer,
    DrillWardBoundarySerializer
)
from .pagination import GISPageNumberPagination
from .generics import GISListCreateAPIView

class GeoCodeSourceListView(generics.ListCreateAPIView):

    """
    List and creates Geo-Code sources

    name -- Name of the Geo Code Source
    description -- The description of the Geo Code Source
    abbreviation -- The abbreviation of the Geo-Code source
    Created --  Date the record was Created
    Updated -- Date the record was Updated
    Created_by -- User who created the record
    Updated_by -- User who updated the record
    active  -- Boolean is the record active
    deleted -- Boolean is the record deleted
    """
    queryset = GeoCodeSource.objects.all()
    serializer_class = GeoCodeSourceSerializer
    ordering_fields = ('name', 'abbreviation',)
    filter_class = GeoCodeSourceFilter

class GeoCodeSourceDetailView(
        AuditableDetailViewMixin, CustomRetrieveUpdateDestroyView):

    """
    Retrieves a particular Geo Code Source
    """
    queryset = GeoCodeSource.objects.all()
    serializer_class = GeoCodeSourceSerializer
    pagination_class = GISPageNumberPagination

class GeoCodeMethodListView(GISListCreateAPIView):

    """
    Lists and creates Geo-Code collection methods

    name -- Name of the Geo-Code Collectiom method
    description -- Description of the Geo-Code collection method
    Created --  Date the record was Created
    Updated -- Date the record was Updated
    Created_by -- User who created the record
    Updated_by -- User who updated the record
    active  -- Boolean is the record active
    deleted -- Boolean is the record deleted
    """
    queryset = GeoCodeMethod.objects.all()
    serializer_class = GeoCodeMethodSerializer
    filter_class = GeoCodeMethodFilter
    ordering_fields = ('name', )

class GeoCodeMethodDetailView(
        AuditableDetailViewMixin, CustomRetrieveUpdateDestroyView):

    """
    Retrieves a particular Geo-Code Collectiom method
    """
    queryset = GeoCodeMethod.objects.all()
    serializer_class = GeoCodeMethodSerializer
    pagination_class = GISPageNumberPagination

class FacilityCoordinatesListView(GISListCreateAPIView):

    """
    Lists and creates facility coordinates

    ward -- A list of comma separated ward pks
    constituency -- A list of comma separated constituency pks
    county -- A list of comma separated county pks
    Created --  Date the record was Created
    Updated -- Date the record was Updated
    Created_by -- User who created the record
    Updated_by -- User who updated the record
    active  -- Boolean is the record active
    deleted -- Boolean is the record deleted
    """
    # The list serializer omits many fields for size reasons
    # This data is controlled access
    # Do not change the permission_classes without good reason
    permission_classes = (DjangoModelPermissions,)
    queryset = FacilityCoordinates.objects.all()
    serializer_class = FacilityCoordinatesListSerializer
    filter_class = FacilityCoordinatesFilter
    ordering_fields = (
        'facility', 'latitude', 'longitude', 'source', 'method',)
    pagination_class = GISPageNumberPagination

    def get(self, *args, **kwargs):
        queryset = self.queryset
        ward = self.request.query_params.get('ward', None)
        county = self.request.query_params.get('county', None)
        constituency = self.request.query_params.get('constituency', None)
        if ward:
            queryset = queryset.filter(facility__ward=ward)
        if county:
            queryset = queryset.filter(
                facility__ward__constituency__county=county)
        if constituency:
            queryset = queryset.filter(
                facility__ward__constituency=constituency)

        result = [fc.json_features for fc in queryset]
        return views.Response(data=result)

class FacilityCoordinatesDetailView(
        AuditableDetailViewMixin, CustomRetrieveUpdateDestroyView):

    """
    Retrieves a particular facility coordinates details
    """
    # The detail serializer has all fields
    # This data is controlled access
    # Do not change the permission classes without good reason
    permission_classes = (DjangoModelPermissions,)
    queryset = FacilityCoordinates.objects.all()
    serializer_class = FacilityCoordinatesDetailSerializer

class FacilityCoordinatesCreationAndListing(
        BufferCooridinatesMixin, GISListCreateAPIView):

    """
    Lists and creates facility coordinates

    ward -- A list of comma separated ward pks
    constituency -- A list of comma separated constituency pks
    county -- A list of comma separated county pks
    Created --  Date the record was Created
    Updated -- Date the record was Updated
    Created_by -- User who created the record
    Updated_by -- User who updated the record
    active  -- Boolean is the record active
    deleted -- Boolean is the record deleted
    """
    # The list serializer omits many fields for size reasons
    # This data is controlled access
    # Do not change the permission_classes without good reason
    permission_classes = (DjangoModelPermissions,)
    queryset = FacilityCoordinates.objects.all()
    serializer_class = FacilityCoordinateSimpleSerializer
    filter_class = FacilityCoordinatesFilter
    ordering_fields = (
        'facility', 'latitude', 'longitude', 'source', 'method',)
    pagination_class = GISPageNumberPagination

    def create(self, request, *args, **kwargs):
        request.data['created_by'] = request.user.id
        request.data['updated_by'] = request.user.id
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        facility_id = request.data.get('facility')
        facility = Facility.objects.get(id=facility_id)
        if facility.approved:
            self.buffer_coordinates(facility, request.data)
        else:
            self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return views.Response(
            serializer.data, status=status.HTTP_201_CREATED, headers=headers)

class FacilityCoordinatesCreationAndDetail(
        BufferCooridinatesMixin, CustomRetrieveUpdateDestroyView):

    """
    Lists and creates facility coordinates

    ward -- A list of comma separated ward pks
    constituency -- A list of comma separated constituency pks
    county -- A list of comma separated county pks
    Created --  Date the record was Created
    Updated -- Date the record was Updated
    Created_by -- User who created the record
    Updated_by -- User who updated the record
    active  -- Boolean is the record active
    deleted -- Boolean is the record deleted
    """
    # The list serializer omits many fields for size reasons
    # This data is controlled access
    # Do not change the permission_classes without good reason
    permission_classes = (DjangoModelPermissions,)
    queryset = FacilityCoordinates.objects.all()
    serializer_class = FacilityCoordinateSimpleSerializer

class WorldBorderListView(GISListCreateAPIView):

    """
    Lists and creates ward borders

    name -- A list of comma separated ward names
    code -- A  list of comma separated ward codes
    Created --  Date the record was Created
    Updated -- Date the record was Updated
    Created_by -- User who created the record
    Updated_by -- User who updated the record
    active  -- Boolean is the record active
    deleted -- Boolean is the record deleted
    """
    queryset = WorldBorder.objects.all()
    serializer_class = WorldBorderSerializer
    filter_class = WorldBorderFilter
    ordering_fields = ('name', 'code',)
    pagination_class = GISPageNumberPagination

class WorldBorderDetailView(
        AuditableDetailViewMixin, CustomRetrieveUpdateDestroyView):

    """
    Retrieves a particular ward border details
    """
    queryset = WorldBorder.objects.all()
    serializer_class = WorldBorderDetailSerializer

class CountyBoundaryListView(GISListCreateAPIView):

    """
    Lists and creates county boundaries

    name --  A list of comma separated county names
    code  -- A list of comma separated county codes
    area -- A list of comma separated area pks
    Created --  Date the record was Created
    Updated -- Date the record was Updated
    Created_by -- User who created the record
    Updated_by -- User who updated the record
    active  -- Boolean is the record active
    deleted -- Boolean is the record deleted
    """
    queryset = CountyBoundary.objects.all()
    serializer_class = CountyBoundarySerializer
    filter_class = CountyBoundaryFilter
    ordering_fields = ('name', 'code',)
    pagination_class = GISPageNumberPagination

class CountyBoundaryDetailView(
        AuditableDetailViewMixin, CustomRetrieveUpdateDestroyView):

    """
    Retrieves a particular county boundary detail
    """
    queryset = CountyBoundary.objects.all()
    serializer_class = CountyBoundaryDetailSerializer

class CountyBoundView(
        AuditableDetailViewMixin, CustomRetrieveUpdateDestroyView):

    """
    Retrieves a particular county boundary detail
    """
    queryset = CountyBoundary.objects.all()
    serializer_class = CountyBoundSerializer

class ConstituencyBoundaryListView(GISListCreateAPIView):

    """
    Lists and creates constituency boundaries

    name --  A list of comma separated constituency names
    code  -- A list of comma separated constituency codes
    area -- A list of comma separated area pks
    Created --  Date the record was Created
    Updated -- Date the record was Updated
    Created_by -- User who created the record
    Updated_by -- User who updated the record
    active  -- Boolean is the record active
    deleted -- Boolean is the record deleted
    """
    queryset = ConstituencyBoundary.objects.all()
    serializer_class = ConstituencyBoundarySerializer
    filter_class = ConstituencyBoundaryFilter
    ordering_fields = ('name', 'code',)
    pagination_class = GISPageNumberPagination

class ConstituencyBoundaryDetailView(
        AuditableDetailViewMixin, CustomRetrieveUpdateDestroyView):

    """
    Retrieves a particular constituency boundary detail
    """
    queryset = ConstituencyBoundary.objects.all()
    serializer_class = ConstituencyBoundaryDetailSerializer

class ConstituencyBoundView(
        AuditableDetailViewMixin, CustomRetrieveUpdateDestroyView):

    """
    Retrieves a particular constituency boundary detail
    """
    queryset = ConstituencyBoundary.objects.all()
    serializer_class = ConstituencyBoundSerializer

class WardBoundaryListView(GISListCreateAPIView):

    """
    Lists and creates ward boundaries

    name --  A list of comma separated ward names
    code  -- A list of comma separated ward codes
    area -- A list of comma separated area pks
    Created --  Date the record was Created
    Updated -- Date the record was Updated
    Created_by -- User who created the record
    Updated_by -- User who updated the record
    active  -- Boolean is the record active
    deleted -- Boolean is the record deleted
    """
    queryset = WardBoundary.objects.all()
    serializer_class = WardBoundarySerializer
    filter_class = WardBoundaryFilter
    ordering_fields = ('name', 'code',)
    pagination_class = GISPageNumberPagination

class WardBoundaryDetailView(
        AuditableDetailViewMixin, CustomRetrieveUpdateDestroyView):

    """
    Retrieves a particular ward boundary detail
    """
    queryset = WardBoundary.objects.all()
    serializer_class = WardBoundaryDetailSerializer

class IkoWapi(views.APIView):

    """
    A utility service to determine administrative unit based on geocoordinates.
    """

    def _validate_lat_long(self, lat, lng):
        err_dict = {}

        if not isinstance(lng, six.integer_types + (float, )):
            err_dict["longitude"] = ["Invalid longitude provided"]

        if not isinstance(lat, six.integer_types + (float, )):
            err_dict["latitude"] = ["Invalid latitude provided"]

        return err_dict

    def post(self, request, *args, **kwargs):
        lng, lat = request.data.get('longitude'), request.data.get('latitude')

        err = self._validate_lat_long(lat, lng)
        if err:
            return views.Response(err, status=400)

        try:
            point = Point(x=lng, y=lat)
        except TypeError:   # pragma: no cover
            # this is one wiered edgecase
            return views.Response({
                rest_settings.api_settings.NON_FIELD_ERRORS_KEY: [
                    "Invalid value given for longitude or latitude",
                ],
            }, status=400)

        try:
            data = WardBoundary.objects.values(
                'area', 'area__name', 'area__code',
                'area__constituency', 'area__constituency__name',
                'area__constituency__code',
                'area__constituency__county',
                'area__constituency__county__name',
                'area__constituency__county__code',
            ).get(mpoly__contains=point)

            return views.Response(OrderedDict([
                ('ward', data['area']),
                ('ward_name', data['area__name']),
                ('ward_code', data['area__code']),
                ('constituency', data['area__constituency']),
                ('constituency_name', data['area__constituency__name']),
                ('constituency_code', data['area__constituency__code']),
                ('county', data['area__constituency__county']),
                ('county_name', data['area__constituency__county__name']),
                ('county_code', data['area__constituency__county__code']),
            ]))
        except WardBoundary.DoesNotExist:
            return views.Response({
                rest_settings.api_settings.NON_FIELD_ERRORS_KEY: [
                    "No ward contains the coordinates ({}, {})".format(
                        lng, lat
                    )
                ]
            }, status=400)

class DrillFacilityCoords(views.APIView):

    """Gets all facility geocoordinates (highly slimmed down)
    """

    def get(self, request, *args, **kwargs):
        qset = DrilldownView.objects.values_list(
            'name', 'lat', 'lng', 'county', 'constituency', 'ward',
        )
        return views.Response(qset)

class DrillBorderBase(generics.ListAPIView):
    lookup_field = 'code'
    pagination_class = GISPageNumberPagination

    def _get_meta(self):
        return {}

    def _get_code(self):
        return self.kwargs.get(self.lookup_field)

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return views.Response({
            "meta": self._get_meta(),
            "geojson": serializer.data
        })

class DrillCountryBorders(DrillBorderBase):
    model = CountyBoundary
    serializer_class = DrillCountyBoundarySerializer

    def _get_meta(self):
        return {"name": "KENYA"}

    def get_queryset(self):
        return self.model.objects.all()

class DrillCountyBorders(DrillBorderBase):
    model = ConstituencyBoundary
    serializer_class = DrillConstituencyBoundarySerializer
    parent_model = CountyBoundary

    def _get_meta(self):
        v = self.parent_model.objects.get(area__code=self._get_code())
        return {
            "area_id": v.area.id,
            "name": v.area.name,
            "code": v.area.code,
            "bound": v.bound
        }

    def get_queryset(self):
        return self.model.objects.filter(
            area__county__code=self._get_code()
        )

class DrillConstituencyBorders(DrillCountyBorders):
    model = WardBoundary
    serializer_class = DrillWardBoundarySerializer
    parent_model = ConstituencyBoundary

    def _get_meta(self):
        v = self.parent_model.objects.get(area__code=self._get_code())
        return {
            "area_id": v.area.id,
            "name": v.area.name,
            "code": v.area.code,
            "bound": v.bound,
            "county_name": v.area.county.name,
            "county_code": v.area.county.code
        }

    def get_queryset(self):
        return self.model.objects.filter(
            area__constituency__code=self._get_code()
        )

class DrillWardBorders(WardBoundaryDetailView):
    lookup_field = 'area__code'
    lookup_url_kwarg = 'code'
    serializer_class = DrillWardBoundarySerializer


text:
require 'active_model/serializer'

module Spree
  module Hub
    class OrderSerializer < ActiveModel::Serializer

      attributes :id, :status, :channel, :email, :currency, :placed_on, :updated_at, :totals,
        :adjustments, :token

      has_many :line_items,  serializer: Spree::Hub::LineItemSerializer
      has_many :payments, serializer: Spree::Hub::PaymentSerializer

      has_one :shipping_address, serializer: Spree::Hub::AddressSerializer
      has_one :billing_address, serializer: Spree::Hub::AddressSerializer

      def id
        object.number
      end

      def status
        object.state
      end

      def updated_at
        object.updated_at.getutc.try(:iso8601)
      end

      def placed_on
        if object.completed_at?
          object.completed_at.getutc.try(:iso8601)
        else
          object.created_at.getutc.try(:iso8601)
        end
      end

      def totals
        {
          item: object.item_total.to_f,
          adjustment: object.adjustment_total.to_f,
          tax: tax_total,
          shipping: shipping_total,
          payment: object.payments.completed.sum(:amount).to_f,
          order: object.total.to_f
        }
      end

      def adjustments
        [
          { name: "tax", value: tax_total },
          { name: "shipping", value: shipping_total }
        ]
      end

      private
        def shipping_total
          object.shipment_total.to_f
        end

        def tax_total
          (object.included_tax_total + object.additional_tax_total).to_f
        end
    end
  end
end


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class jcuda.runtime.cudaDeviceProp (jcuda-windows64 6.5 API)</title>
<meta name="date" content="2014-12-23">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
jcuda.runtime.cudaDeviceProp

Packages that use cudaDeviceProp

Package
Description

jcuda.runtime

Contains the classes related to the JCuda runtime API.

Uses of cudaDeviceProp in jcuda.runtime

Methods in jcuda.runtime with parameters of type cudaDeviceProp

Modifier and Type
Method and Description

static int
JCuda.cudaChooseDevice(int[] device,
                cudaDeviceProp prop)

Select compute-device which best matches criteria.

static int
JCuda.cudaGetDeviceProperties(cudaDeviceProp prop,
                       int device)

Returns information about the compute-device.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2014. All Rights Reserved.


text:
package alluxio.cli.fs.command;

import alluxio.AlluxioURI;
import alluxio.annotation.PublicApi;
import alluxio.cli.CommandUtils;
import alluxio.client.file.FileSystemContext;
import alluxio.exception.AlluxioException;
import alluxio.exception.status.InvalidArgumentException;

import org.apache.commons.cli.CommandLine;

import java.io.IOException;
import javax.annotation.concurrent.ThreadSafe;

/**
 * Creates a 0 byte file specified by argv. The file will be written to UnderFileSystem.
 */
@ThreadSafe
@PublicApi
public final class TouchCommand extends AbstractFileSystemCommand {

  /**
   * @param fsContext the filesystem of Alluxio
   */
  public TouchCommand(FileSystemContext fsContext) {
    super(fsContext);
  }

  @Override
  public String getCommandName() {
    return "touch";
  }

  @Override
  public void validateArgs(CommandLine cl) throws InvalidArgumentException {
    CommandUtils.checkNumOfArgsEquals(this, cl, 1);
  }

  @Override
  protected void runPlainPath(AlluxioURI inputPath, CommandLine cl)
      throws AlluxioException, IOException {
    mFileSystem.createFile(inputPath).close();
    System.out.println(inputPath + " has been created");
  }

  @Override
  public int run(CommandLine cl) throws AlluxioException, IOException {
    String[] args = cl.getArgs();
    AlluxioURI inputPath = new AlluxioURI(args[0]);
    runWildCardCmd(inputPath, cl);
    return 0;
  }

  @Override
  public String getUsage() {
    return "touch <path>";
  }

  @Override
  public String getDescription() {
    return "Creates a 0 byte file. The file will be written to the under file system.";
  }
}


text:
from dream3d import simpl
from dream3d import simpl_helpers as sc
from dream3d import simpl_test_dirs as sd
from dream3d import simplpy
from dream3d import orientationanalysispy
from dream3d import genericpy
from dream3d import statisticspy
from dream3d import syntheticbuildingpy as syntheticbuilding
from dream3d import transformationphasepy

def insert_transformation_phase():
    # Create Data Container Array
    dca = simpl.DataContainerArray.New()

     # Using the GenerateStatsData and CreateDynamicTableData functions
    euler_dynamic_table_data = sc.CreateDynamicTableData([[0, 0, 0, 0, 0]],
                                                      ["Euler 1", "Euler 2", "Euler 3", "Weight", "Sigma"], ["0"])
    axis_dynamic_table_data = sc.CreateDynamicTableData([[0, 0, 0, 0, 0]],
                                                     ["Angle(w)", "Axis (h)", "Axis (k)", "Axis (l)", "Weight (MRD)"],
                                                     ["0"])
    err = syntheticbuilding.generate_primary_stats_data(dca, "Primary", 0, 1, 0,
                               1, 2.3, 0.4, 4, 3, 10.5,
                               True, "StatsGeneratorDataContainer",
                               "CellEnsembleData", False,
                               simpl.DataArrayPath("", "", ""),
                               euler_dynamic_table_data,
                               axis_dynamic_table_data,
                               euler_dynamic_table_data)

    if err < 0:
        print("Primary StatsData ErrorCondition: %d" % err)

     # Initialize Synthetic Volume
    err = syntheticbuilding.initialize_synthetic_volume(dca, "SyntheticVolumeDataContainer", "CellData",
                                                        "CellEnsembleMatrixName",
                                                        6,
                                                        simpl.IntVec3Type([128, 128, 128]),
                                                        simpl.FloatVec3Type([0.5, 0.5, 0.5]),
                                                        simpl.FloatVec3Type([0, 0, 0]),
                                                        simpl.DataArrayPath("StatsGeneratorDataContainer",
                                                                            "CellEnsembleData", "Statistics"),
                                                        simpl.DataArrayPath("StatsGeneratorDataContainer",
                                                                            "CellEnsembleData", "PhaseTypes"),
                                                        simpl.DataArrayPath("StatsGeneratorDataContainer",
                                                                            "CellEnsembleData", "PhaseName"),
                                                        False)
    if err < 0:
        print("InitializeSyntheticVolume ErrorCondition: %d" % err)

    # Establish Shape Types
    err = syntheticbuilding.establish_shape_types(dca,
                                                    simpl.DataArrayPath("StatsGeneratorDataContainer",
                                                                        "CellEnsembleData", "PhaseTypes"),
                                                    "ShapeTypes", [simpl.ShapeType.Ellipsoid])
    if err < 0:
        print("EstablishShapeTypes ErrorCondition: %d" % err)

    # Pack Primary Phases
    err = syntheticbuilding.pack_primary_phases(dca,
                                                  simpl.DataArrayPath("SyntheticVolumeDataContainer", "CellData",
                                                                      ""),
                                                  "CellFeatureData", "CellEnsembleData", "FeatureIds", "Phases",
                                                  "Phases", "NumFeatures",
                                                  simpl.DataArrayPath("StatsGeneratorDataContainer",
                                                                      "CellEnsembleData", "Statistics"),
                                                  simpl.DataArrayPath("StatsGeneratorDataContainer",
                                                                      "CellEnsembleData", "PhaseTypes"),
                                                  simpl.DataArrayPath("StatsGeneratorDataContainer",
                                                                      "CellEnsembleData", "PhaseName"),
                                                  simpl.DataArrayPath("StatsGeneratorDataContainer",
                                                                      "CellEnsembleData", "ShapeTypes"),
                                                  simpl.DataArrayPath("", "", ""), False, 0, "", "", False,
                                                  False, False,
                                                  simpl.DataArrayPath("", "", ""),
                                                  simpl.DataArrayPath("", "", ""))
    if err < 0:
        print("PackPrimaryPhases ErrorCondition: %d" % err)

    # Find Feature Neighbors
    err = statisticspy.find_neighbors(dca, simpl.DataArrayPath("SyntheticVolumeDataContainer", "CellFeatureData", ""),
                                      "SharedSurfaceAreaList", "NeighborList",
                                      simpl.DataArrayPath("SyntheticVolumeDataContainer", "CellData",
                                                          "FeatureIds"),
                                      "", "NumNeighbors", "SurfaceFeatures", False, True)
    if err < 0:
        print("FindNeighbors ErrorCondition: %d" % err)

    # Match Crystallography
    err = syntheticbuilding.match_crystallography(dca, simpl.DataArrayPath("StatsGeneratorDataContainer",
                                                                             "CellEnsembleData", "Statistics"),
                                                    simpl.DataArrayPath("StatsGeneratorDataContainer",
                                                                        "CellEnsembleData", "CrystalStructures"),
                                                    simpl.DataArrayPath("StatsGeneratorDataContainer",
                                                                        "CellEnsembleData", "PhaseTypes"),
                                                    simpl.DataArrayPath("SyntheticVolumeDataContainer",
                                                                        "CellData", "FeatureIds"),
                                                    simpl.DataArrayPath("SyntheticVolumeDataContainer",
                                                                        "CellFeatureData", "Phases"),
                                                    simpl.DataArrayPath("SyntheticVolumeDataContainer",
                                                                        "CellFeatureData", "SurfaceFeatures"),
                                                    simpl.DataArrayPath("SyntheticVolumeDataContainer",
                                                                        "CellFeatureData", "NeighborList"),
                                                    simpl.DataArrayPath("SyntheticVolumeDataContainer",
                                                                        "CellFeatureData", "SharedSurfaceAreaList"),
                                                    simpl.DataArrayPath("SyntheticVolumeDataContainer",
                                                                        "CellEnsembleData", "NumFeatures"),
                                                    "EulerAngles", "Volumes", "EulerAngles", "AvgQuats", 100000)
    if err < 0:
        print("MatchCrystallography ErrorCondition: %d" % err)

    # Find Feature Centroids
    err = genericpy.find_feature_centroids(dca,
                                           simpl.DataArrayPath("SyntheticVolumeDataContainer",
                                                               "CellData", "FeatureIds"),
                                           simpl.DataArrayPath("SyntheticVolumeDataContainer",
                                                               "CellFeatureData", "Centroids"))
    if err < 0:
        print("FindFeatureCentroids ErrorCondition: %d" % err)

    # Find Feature Sizes #1
    err = statisticspy.find_sizes(dca, simpl.DataArrayPath("SyntheticVolumeDataContainer", "CellFeatureData", ""),
                                  simpl.DataArrayPath("SyntheticVolumeDataContainer",
                                                      "CellData", "FeatureIds"),
                                  "Volumes2", "EquivalentDiameters", "NumElements", False)
    if err < 0:
        print("FindSizes #1 ErrorCondition %d" % err)

    # Insert Transformation Phases
    # Possible candidate for a helper function
    # Possible enums: trans_crystal_struct
    # May want to use a "dictionary" for the numerical portion in helper function
    err = transformationphasepy.insert_transformation_phases(dca,
                                                             1, 1, 60, simpl.FloatVec3Type([1, 1, 1]), True, True, 1, 0.2, 1,
                                                             0,
                                                             simpl.DataArrayPath("StatsGeneratorDataContainer",
                                                                                "CellEnsembleData", ""),
                                                             simpl.DataArrayPath("SyntheticVolumeDataContainer",
                                                                                "CellFeatureData", ""),
                                                             simpl.DataArrayPath("SyntheticVolumeDataContainer",
                                                                                "CellData", "FeatureIds"),
                                                             simpl.DataArrayPath("SyntheticVolumeDataContainer",
                                                                                "CellData", "EulerAngles"),
                                                             simpl.DataArrayPath("SyntheticVolumeDataContainer",
                                                                                "CellData", "Phases"),
                                                             simpl.DataArrayPath("SyntheticVolumeDataContainer",
                                                                                "CellFeatureData", "AvgQuats"),
                                                             simpl.DataArrayPath("SyntheticVolumeDataContainer",
                                                                                "CellFeatureData", "Centroids"),
                                                             simpl.DataArrayPath("SyntheticVolumeDataContainer",
                                                                                "CellFeatureData",
                                                                                "EquivalentDiameters"),
                                                             simpl.DataArrayPath("SyntheticVolumeDataContainer",
                                                                                "CellFeatureData", "EulerAngles"),
                                                             simpl.DataArrayPath("SyntheticVolumeDataContainer",
                                                                                "CellFeatureData", "Phases"),
                                                             "ParentIds",
                                                             simpl.DataArrayPath("SyntheticVolumeDataContainer",
                                                                                "CellEnsembleData",
                                                                                "NumFeaturesPerParent"),
                                                             simpl.DataArrayPath("StatsGeneratorDataContainer",
                                                                                "CellEnsembleData",
                                                                                "CrystalStructures"),
                                                             simpl.DataArrayPath("StatsGeneratorDataContainer",
                                                                                "CellEnsembleData", "PhaseTypes"),
                                                             simpl.DataArrayPath("StatsGeneratorDataContainer",
                                                                                "CellEnsembleData", "ShapeTypes"),
                                                             simpl.DataArrayPath("SyntheticVolumeDataContainer",
                                                                                "CellEnsembleData", "NumFeatures"))
    if err < 0:
        print("InsertTransformationPhases ErrorCondition %d" % err)

    # Delete Data (using helper function)
    sc.RemoveArrays(dca, [("SyntheticVolumeDataContainer", "CellFeatureData", "AvgQuats"),
                          ("SyntheticVolumeDataContainer", "CellFeatureData", "Centroids"),
                          ("SyntheticVolumeDataContainer", "CellFeatureData", "EquivalentDiameters"),
                          ("SyntheticVolumeDataContainer", "CellFeatureData", "EulerAngles"),
                          ("SyntheticVolumeDataContainer", "CellFeatureData", "NeighborList"),
                          ("SyntheticVolumeDataContainer", "CellFeatureData", "NumElements"),
                          ("SyntheticVolumeDataContainer", "CellFeatureData", "NumFeaturesPerParent"),
                          ("SyntheticVolumeDataContainer", "CellFeatureData", "NumNeighbors"),
                          ("SyntheticVolumeDataContainer", "CellFeatureData", "SharedSurfaceAreaList"),
                          ("SyntheticVolumeDataContainer", "CellFeatureData", "SurfaceFeatures"),
                          ("SyntheticVolumeDataContainer", "CellFeatureData", "Volumes"),
                          ("SyntheticVolumeDataContainer", "CellFeatureData", "Volumes2")])

    # Generate IPF Colors
    err = orientationanalysispy.generate_ipf_colors(dca, simpl.FloatVec3Type([0, 0, 1]),
                                                    simpl.DataArrayPath("SyntheticVolumeDataContainer",
                                                                        "CellData", "Phases"),
                                                    simpl.DataArrayPath("SyntheticVolumeDataContainer",
                                                                        "CellData", "EulerAngles"),
                                                    simpl.DataArrayPath("StatsGeneratorDataContainer",
                                                                        "CellEnsembleData", "CrystalStructures"),
                                                    False,
                                                    simpl.DataArrayPath("", "", ""), "IPFColor")
    if err < 0:
        print("GenerateIPFColors ErrorCondition: %d" % err)

    # Find Feature Sizes #2
    err = statisticspy.find_sizes(dca, simpl.DataArrayPath("SyntheticVolumeDataContainer", "CellFeatureData", ""),
                                  simpl.DataArrayPath("SyntheticVolumeDataContainer",
                                                      "CellData", "FeatureIds"),
                                  "Volumes2", "EquivalentDiameters", "NumElements", False)
    if err < 0:
        print("FindSizes #2 ErrorCondition %d" % err)

    # Convert Orientation Representation
    err = orientationanalysispy.convert_orientations(dca, 0, 2,
                                                     simpl.DataArrayPath("SyntheticVolumeDataContainer", "CellData",
                                                                         "EulerAngles"),
                                                     "Quats")
    if err < 0:
        print("Convert Orientations ErrorCondition %d" % err)

    # Find Feature Average Orientations
    err = orientationanalysispy.find_avg_orientations(dca,
                                                      simpl.DataArrayPath("SyntheticVolumeDataContainer", "CellData",
                                                                          "FeatureIds"),
                                                      simpl.DataArrayPath("SyntheticVolumeDataContainer", "CellData",
                                                                          "Phases"),
                                                      simpl.DataArrayPath("SyntheticVolumeDataContainer", "CellData",
                                                                          "Quats"),
                                                      simpl.DataArrayPath("SyntheticVolumeDataContainer",
                                                                          "CellEnsembleData", "CrystalStructures"),
                                                      simpl.DataArrayPath("SyntheticVolumeDataContainer",
                                                                          "CellFeatureData", "AvgQuats"),
                                                      simpl.DataArrayPath("SyntheticVolumeDataContainer",
                                                                          "CellFeatureData", "AvgEulers"))
    if err < 0:
        print("FindAvgOrientations ErrorCondition: %d" % err)

    # Find Feature Centroids
    err = genericpy.find_feature_centroids(dca, simpl.DataArrayPath("SyntheticVolumeDataContainer", "CellData",
                                                                    "FeatureIds"),
                                           simpl.DataArrayPath("SyntheticVolumeDataContainer", "CellFeatureData",
                                                               "Centroids"))
    if err < 0:
        print("FindFeatureCentroids ErrorCondition: %d" % err)

    # Find Feature Neighborhoods
    err = statisticspy.find_neighborhoods(dca, "NeighborhoodList", 1,
                                          simpl.DataArrayPath("SyntheticVolumeDataContainer", "CellFeatureData",
                                                              "EquivalentDiameters"),
                                          simpl.DataArrayPath("SyntheticVolumeDataContainer", "CellFeatureData",
                                                              "Phases"),
                                          simpl.DataArrayPath("SyntheticVolumeDataContainer", "CellFeatureData",
                                                              "Centroids"),
                                          "Neighborhoods")
    if err < 0:
        print("FindNeighborhoods ErrorCondition: %d" % err)

    # Find Feature Neighbors #2
    err = statisticspy.find_neighbors(dca, simpl.DataArrayPath("SyntheticVolumeDataContainer", "CellFeatureData", ""),
                                      "SharedSurfaceAreaList", "NeighborList",
                                      simpl.DataArrayPath("SyntheticVolumeDataContainer", "CellData", "FeatureIds"),
                                      "", "NumNeighbors", "SurfaceFeatures", False, False)
    if err < 0:
        print("FindNeighbors #2 ErrorCondition: %d" % err)

    # Write to DREAM3D file
    err = sc.WriteDREAM3DFile(
        sd.GetBuildDirectory() + "/Data/Output/TransformationPhase/InsertTransformationPhases.dream3d",
        dca)
    if err < 0:
        print("WriteDREAM3DFile ErrorCondition: %d" % err)

    # Export Feature Data as CSV File
    err = simplpy.feature_data_csv_writer(dca,
                                          simpl.DataArrayPath("SyntheticVolumeDataContainer", "CellFeatureData", ""),
                                          sd.GetBuildDirectory() +
                                          "/Data/Output/TransformationPhase/InsertTransformationPhases.csv",
                                          False, simpl.DelimiterTypes.Comma, True)
    if err < 0:
        print("FeatureDataCsvWriter ErrorCondition: %d" % err)

"""
Main entry point for python script
"""
if __name__ == "__main__":
    insert_transformation_phase()


text:
#ifndef SkSemaphore_DEFINED
#define SkSemaphore_DEFINED

#include "include/core/SkTypes.h"
#include "include/private/SkOnce.h"
#include "include/private/SkThreadAnnotations.h"
#include <atomic>

class SkSemaphore {
public:
    constexpr SkSemaphore(int count = 0) : fCount(count), fOSSemaphore(nullptr) {}

    // Cleanup the underlying OS semaphore.
    ~SkSemaphore();

    // Increment the counter n times.
    // Generally it's better to call signal(n) instead of signal() n times.
    void signal(int n = 1);

    // Decrement the counter by 1,
    // then if the counter is < 0, sleep this thread until the counter is >= 0.
    void wait();

    // If the counter is positive, decrement it by 1 and return true, otherwise return false.
    bool try_wait();

private:
    // This implementation follows the general strategy of
    //     'A Lightweight Semaphore with Partial Spinning'
    // found here
    //     http://preshing.com/20150316/semaphores-are-surprisingly-versatile/
    // That article (and entire blog) are very much worth reading.
    //
    // We wrap an OS-provided semaphore with a user-space atomic counter that
    // lets us avoid interacting with the OS semaphore unless strictly required:
    // moving the count from >=0 to <0 or vice-versa, i.e. sleeping or waking threads.
    struct OSSemaphore;

    void osSignal(int n);
    void osWait();

    std::atomic<int> fCount;
    SkOnce           fOSSemaphoreOnce;
    OSSemaphore*     fOSSemaphore;
};

inline void SkSemaphore::signal(int n) {
    int prev = fCount.fetch_add(n, std::memory_order_release);

    // We only want to call the OS semaphore when our logical count crosses
    // from <0 to >=0 (when we need to wake sleeping threads).
    //
    // This is easiest to think about with specific examples of prev and n.
    // If n == 5 and prev == -3, there are 3 threads sleeping and we signal
    // SkTMin(-(-3), 5) == 3 times on the OS semaphore, leaving the count at 2.
    //
    // If prev >= 0, no threads are waiting, SkTMin(-prev, n) is always <= 0,
    // so we don't call the OS semaphore, leaving the count at (prev + n).
    int toSignal = SkTMin(-prev, n);
    if (toSignal > 0) {
        this->osSignal(toSignal);
    }
}

inline void SkSemaphore::wait() {
    // Since this fetches the value before the subtract, zero and below means that there are no
    // resources left, so the thread needs to wait.
    if (fCount.fetch_sub(1, std::memory_order_acquire) <= 0) {
        SK_POTENTIALLY_BLOCKING_REGION_BEGIN;
        this->osWait();
        SK_POTENTIALLY_BLOCKING_REGION_END;
    }
}

#endif//SkSemaphore_DEFINED


text:
<?php

namespace Magento\Framework\Less\File\Collector;

use Magento\Framework\View\Design\ThemeInterface;
use Magento\Framework\View\File\CollectorInterface;
use Magento\Framework\View\File\FileList\Factory;

/**
 * Source of layout files aggregated from a theme and its parents according to merging and overriding conventions
 */
class Aggregated implements CollectorInterface
{
    /**
     * @var Factory
     */
    protected $fileListFactory;

    /**
     * @var \Magento\Framework\View\File\CollectorInterface
     */
    protected $libraryFiles;

    /**
     * @var \Magento\Framework\View\File\CollectorInterface
     */
    protected $baseFiles;

    /**
     * @var \Magento\Framework\View\File\CollectorInterface
     */
    protected $overriddenBaseFiles;

    /**
     * @param Factory $fileListFactory
     * @param CollectorInterface $libraryFiles
     * @param CollectorInterface $baseFiles
     * @param CollectorInterface $overriddenBaseFiles
     */
    public function __construct(
        Factory $fileListFactory,
        CollectorInterface $libraryFiles,
        CollectorInterface $baseFiles,
        CollectorInterface $overriddenBaseFiles
    ) {
        $this->fileListFactory = $fileListFactory;
        $this->libraryFiles = $libraryFiles;
        $this->baseFiles = $baseFiles;
        $this->overriddenBaseFiles = $overriddenBaseFiles;
    }

    /**
     * Retrieve files
     *
     * Aggregate LESS files from modules and a theme and its ancestors
     *
     * @param \Magento\Framework\View\Design\ThemeInterface $theme
     * @param string $filePath
     * @return \Magento\Framework\View\File[]
     * @throws \LogicException
     */
    public function getFiles(ThemeInterface $theme, $filePath)
    {
        $list = $this->fileListFactory->create('Magento\Framework\Less\File\FileList\Collator');
        $list->add($this->libraryFiles->getFiles($theme, $filePath));
        $list->add($this->baseFiles->getFiles($theme, $filePath));

        foreach ($theme->getInheritedThemes() as $currentTheme) {
            $files = $this->overriddenBaseFiles->getFiles($currentTheme, $filePath);
            $list->replace($files);
        }
        $result = $list->getAll();
        if (empty($result)) {
            throw new \LogicException('magento_import returns empty result by path ' . $filePath);
        }
        return $result;
    }
}


text:
#!/usr/bin/python3

# Ensure enumeration is at least 3 bytes,
# to force compiler to use 32 bit int type
# for error number enumeration
category_mult = 0x10000

errno_ids = []
errno_next = 0

# Parse input file
handle = open('errno_input.txt')
for line in handle.readlines():

    # Next category?
    if '@' in line:
        errno_ids.append(line.split('@')[1].strip())

        # Advance to next multiple - in a super lazy way
        while errno_next % category_mult != 0:
            errno_next += 1

    # Next errno?
    elif ':' in line:
        name, text = [x.strip() for x in line.split(':')]
        errno_ids.append((name.upper(), errno_next, text))
        errno_next += 1

# Autogenerate handler
def autogen(filename, cat_func, errno_func):

    # Scan in input file
    sections = [[]]
    handle = open(filename)
    for line in handle.readlines():
        if 'AUTOGENERATED CONTENT' in line:
            sections.append([])
        else:
            sections[-1].append(line)

    # Sanity check
    if len(sections) != 3:
        raise Exception('Cannot locate autogenerated content')

    # Dump output file
    handle = open(filename, 'w')

    # Dump header
    for line in sections[0]:
        handle.write(line)

    # Separator
    handle.write("/* === BEGIN AUTOGENERATED CONTENT === */\n\n")

    # Dump
    for item in errno_ids:
        if type(item) == str:
            handle.write(cat_func(item))
        else:
            handle.write(errno_func(item))

    # Separator
    handle.write("\n/* === END AUTOGENERATED CONTENT === */\n")

    # Dump footer
    for line in sections[2]:
        handle.write(line)

# Autogenerate header file
autogen('../../include/topaz/errno.h',
        lambda x: '/* %s */\n\n' % x,
        lambda x: '  /** %s */\n  TP_ERR_%-15s = 0x%08x,\n\n' % (x[2], x[0], x[1]))

# Autogenerate C data structures
autogen('../../src/topaz/errno.c',
        lambda x: '\n  /* %s */\n\n' % x,
        lambda x: '  { TP_ERR_%-15s, "%s" },\n' % (x[0], x[2]))


text:
import sqlalchemy as sa
from oslo_db.sqlalchemy import types as db_types

from nca47.db.sqlalchemy.models import base as model_base
from nca47.objects import attributes as attr

HasTenant = model_base.HasTenant
HasId = model_base.HasId
HasStatus = model_base.HasStatus
HasOperationMode = model_base.HasOperationMode

class DnsServer(model_base.BASE, HasId, HasOperationMode):
    """Represents a dns server."""

    name = sa.Column(sa.String(attr.NAME_MAX_LEN))

class Zone(model_base.BASE, HasId, HasOperationMode):
    """Represents a dns zone."""

    __tablename__ = 'dns_zone_info'

    zone_name = sa.Column(sa.String(attr.NAME_MAX_LEN))
    tenant_id = sa.Column(sa.String(attr.NAME_MAX_LEN))
    zone_id = sa.Column(sa.String(attr.NAME_MAX_LEN))
    vres_id = sa.Column(sa.String(attr.NAME_MAX_LEN))
    masters = sa.Column(db_types.JsonEncodedList)
    slaves = sa.Column(db_types.JsonEncodedList)
    renewal = sa.Column(sa.String(attr.NAME_MAX_LEN))
    default_ttl = sa.Column(sa.String(attr.NAME_MAX_LEN))
    owners = sa.Column(db_types.JsonEncodedList)
    ad_controller = sa.Column(sa.String(attr.NAME_MAX_LEN))
    comment = sa.Column(sa.String(attr.NAME_MAX_LEN))

class ZoneRecord(model_base.BASE, HasId, HasOperationMode):
    """Represents a dns zone."""

    __tablename__ = 'dns_rrs_info'
    zone_id = sa.Column(sa.String(attr.UUID_LEN))
    rrs_id = sa.Column(sa.String(attr.NAME_MAX_LEN))
    rrs_name = sa.Column(sa.String(attr.NAME_MAX_LEN))
    type = sa.Column(sa.String(attr.NAME_MAX_LEN))
    klass = sa.Column(sa.String(attr.NAME_MAX_LEN))
    ttl = sa.Column(sa.String(attr.NAME_MAX_LEN))
    rdata = sa.Column(sa.String(attr.NAME_MAX_LEN))

class HmTemplateInfo(model_base.BASE, HasId, HasOperationMode):
    """Represents a  HmTemplateInfo."""

    __tablename__ = 'hm_template_info'
    name = sa.Column(sa.String(attr.NAME_MAX_LEN))
    types = sa.Column(sa.String(attr.NAME_MAX_LEN))
    check_interval = sa.Column(sa.String(attr.FIVE_LEN))
    timeout = sa.Column(sa.String(attr.FIVE_LEN))
    max_retries = sa.Column(sa.String(attr.FIVE_LEN))
    sendstring = sa.Column(sa.String(attr.INPUT_MAX_LEN))
    recvstring = sa.Column(sa.String(attr.INPUT_MAX_LEN))
    hm_template_id = sa.Column(sa.String(attr.NAME_MAX_LEN))
    refcnt = sa.Column(sa.String(attr.TEN_LEN))
    username = sa.Column(sa.String(attr.NAME_MAX_LEN))
    password = sa.Column(sa.String(attr.NAME_MAX_LEN))
    tenant_id = sa.Column(sa.String(attr.NAME_MAX_LEN))

class GslbZoneInfo(model_base.BASE, HasId, HasOperationMode):
    """Represents a GslbZoneInfo."""

    __tablename__ = 'gslb_zone_info'
    name = sa.Column(sa.String(attr.NAME_MAX_LEN))
    devices = sa.Column(db_types.JsonEncodedList)
    syn_server = sa.Column(sa.String(attr.INPUT_MAX_LEN))
    gslb_zone_id = sa.Column(sa.String(attr.NAME_MAX_LEN))
    enable = sa.Column(sa.String(attr.INPUT_MAX_LEN),
                       default='yes')
    tenant_id = sa.Column(sa.String(attr.NAME_MAX_LEN))

class GmemberInfo(model_base.BASE, HasId, HasOperationMode):
    """Represents a GmemberInfo."""

    __tablename__ = 'gmember_info'
    name = sa.Column(sa.String(attr.NAME_MAX_LEN))
    gslb_zone_name = sa.Column(sa.String(attr.NAME_MAX_LEN))
    ip = sa.Column(sa.String(attr.IP_LEN))
    port = sa.Column(sa.String(attr.FIVE_LEN))
    enable = sa.Column(sa.String(attr.FIVE_LEN),
                       default="yes")
    refcnt = sa.Column(sa.String(attr.TEN_LEN))
    gmember_id = sa.Column(sa.String(attr.NAME_MAX_LEN))
    tenant_id = sa.Column(sa.String(attr.NAME_MAX_LEN))

class Region(model_base.BASE, HasId, HasOperationMode):
    """Represents a region info."""

    __tablename__ = 'region_info'
    tenant_id = sa.Column(sa.String(attr.NAME_MAX_LEN))
    name = sa.Column(sa.String(attr.NAME_MAX_LEN))
    region_id = sa.Column(sa.String(attr.NAME_MAX_LEN))
    refcnt = sa.Column(sa.String(attr.NAME_MAX_LEN))
    region_user = sa.Column(sa.String(attr.INPUT_MAX_LEN))

class RegionUser(model_base.BASE, HasId, HasOperationMode):
    """Represents a region user info."""

    __tablename__ = 'region_user_info'
    tenant_id = sa.Column(sa.String(attr.NAME_MAX_LEN))
    name = sa.Column(sa.String(attr.NAME_MAX_LEN))
    region_useruser_id = sa.Column(sa.String(attr.NAME_MAX_LEN))
    region_id = sa.Column(sa.String(attr.NAME_MAX_LEN))
    type = sa.Column(sa.String(attr.NAME_MAX_LEN))
    data1 = sa.Column(sa.String(attr.NAME_MAX_LEN))
    data2 = sa.Column(sa.String(attr.NAME_MAX_LEN))
    data3 = sa.Column(sa.String(attr.NAME_MAX_LEN))
    data4 = sa.Column(sa.String(attr.NAME_MAX_LEN))

class Proximity(model_base.BASE, HasId, HasOperationMode):
    """Represents a proximity info."""

    __tablename__ = 'sp_policy_info'
    tenant_id = sa.Column(sa.String(attr.NAME_MAX_LEN))
    sp_policy_id = sa.Column(sa.String(attr.NAME_MAX_LEN))
    src_type = sa.Column(sa.String(attr.NAME_MAX_LEN))
    src_logic = sa.Column(sa.String(attr.NAME_MAX_LEN))
    src_data1 = sa.Column(sa.String(attr.NAME_MAX_LEN))
    src_data2 = sa.Column(sa.String(attr.NAME_MAX_LEN))
    src_data3 = sa.Column(sa.String(attr.NAME_MAX_LEN))
    src_data4 = sa.Column(sa.String(attr.NAME_MAX_LEN))
    dst_type = sa.Column(sa.String(attr.NAME_MAX_LEN))
    dst_logic = sa.Column(sa.String(attr.NAME_MAX_LEN))
    dst_data1 = sa.Column(sa.String(attr.NAME_MAX_LEN))
    dst_data2 = sa.Column(sa.String(attr.NAME_MAX_LEN))

class Syngroup(model_base.BASE, HasId, HasOperationMode):
    """
    Represents a dns Syngroup_zone
    """
    __tablename__ = 'syngroup_info'
    syngroup_id = sa.Column(sa.String(attr.UUID_LEN))
    tenant_id = sa.Column(sa.String(attr.NAME_MAX_LEN))
    gslb_zone_names = sa.Column(db_types.JsonEncodedList)
    probe_range = sa.Column(sa.String(attr.NAME_MAX_LEN))
    name = sa.Column(sa.String(attr.NAME_MAX_LEN))
    pass_ = sa.Column(sa.String(attr.FIVE_LEN))

class GPoolInfo(model_base.BASE, HasId, HasOperationMode):
    __tablename__ = 'gpool_info'
    tenant_id = sa.Column(sa.String(attr.UUID_LEN))
    name = sa.Column(sa.String(attr.NAME_MAX_LEN))
    enable = sa.Column(sa.String(attr.FIVE_LEN))
    pass_ = sa.Column(sa.String(attr.FIVE_LEN))
    ttl = sa.Column(sa.String(attr.TTL_LEN))
    max_addr_ret = sa.Column(sa.String(attr.NAME_MAX_LEN))
    cname = sa.Column(sa.String(attr.NAME_MAX_LEN))
    first_algorithm = sa.Column(sa.String(attr.FIVE_LEN))
    second_algorithm = sa.Column(sa.String(attr.FIVE_LEN))
    fallback_ip = sa.Column(sa.String(attr.IP_LEN))
    hms = sa.Column(db_types.JsonEncodedList)
    gmember_list = sa.Column(db_types.JsonEncodedList)
    warning = sa.Column(sa.String(attr.TYPE_LEN))
    gpool_id = sa.Column(sa.String(attr.NAME_MAX_LEN))

class GMapInfo(model_base.BASE, HasId, HasOperationMode):
    __tablename__ = 'gmap_info'
    tenant_id = sa.Column(sa.String(attr.NAME_MAX_LEN))
    gmap_id = sa.Column(sa.String(attr.NAME_MAX_LEN))
    name = sa.Column(sa.String(attr.NAME_MAX_LEN))
    gpool_list = sa.Column(db_types.JsonEncodedList)
    last_resort_pool = sa.Column(sa.String(attr.NAME_MAX_LEN))
    algorithm = sa.Column(sa.String(attr.NAME_MAX_LEN))
    enable = sa.Column(sa.String(attr.TEN_LEN))


text:
docker stop $(docker ps -a -q)
docker rm $(docker ps -a -q)
echo Stopping network this may take a minute or two.
weave stop


text: All Hearthstone graphics/textures are copyright © Blizzard Entertainment.


text:
<readable><title>2059842472_f4fb61ea08</title><content>
A baby crawls next to a street against a blue sky .
A baby crawls on asphalt against a blue sky .
A little Asian boy crawls along on asphalt .
A little toddler in blue pants is crawling on the road .
An Asian baby crawling on a road .
</content></readable>


text:
<?php

/**
 * User: To Olympus
 * Date: 2017-02-11
 * Time: 6:05 PM
 */
class AssemblyRecords extends MY_Model
{
    public $data;

    // Constructor
    public function __construct()
    {
        parent::__construct('assemblyrecords','assemblyID');
    }
}