repo_name
stringlengths 6
101
| path
stringlengths 4
300
| text
stringlengths 7
1.31M
|
|---|---|---|
Ometria/python-sparkpost
|
test/tornado/utils.py
|
<reponame>Ometria/python-sparkpost
from __future__ import print_function
from collections import namedtuple
from responses import RequestsMock
from tornado import ioloop
from tornado.concurrent import Future
from tornado.httpclient import HTTPRequest, HTTPResponse, HTTPError
Request = namedtuple("Request", ["url", "method", "headers", "body"])
class ResponseGenerator(object):
def get_adapter(self, url):
return self
def build_response(self, request, response):
resp = HTTPResponse(request, response.status, headers=response.headers,
effective_url=request.url, error=None, buffer="")
resp._body = response.data
f = Future()
f.content = None
if response.status < 200 or response.status >= 300:
resp.error = HTTPError(response.status, response=resp)
ioloop.IOLoop().current().add_callback(f.set_exception, resp.error)
else:
ioloop.IOLoop().current().add_callback(f.set_result, resp)
return f
class AsyncClientMock(RequestsMock):
def start(self):
import mock
def unbound_on_send(client, request, callback=None, **kwargs):
if not isinstance(request, HTTPRequest):
request = Request(request,
kwargs.get("method", "GET"),
kwargs.get("headers", []),
kwargs.get("body", ""))
return self._on_request(ResponseGenerator(), request)
self._patcher = mock.patch('tornado.httpclient.AsyncHTTPClient.fetch',
unbound_on_send)
self._patcher.start()
def stop(self):
self._patcher.stop()
|
ValantIO/DevExtreme
|
testing/tests/DevExpress.exporter/jspdfParts/v3/jspdf_v3.dataGrid.verticalAlign.tests.js
|
import { exportDataGrid } from 'exporter/jspdf/v3/export_data_grid_3';
const JSPdfVerticalAlignTests = {
runTests(moduleConfig, createMockPdfDoc, createDataGrid) {
QUnit.module('Vertical align', moduleConfig, () => {
QUnit.test('1 col - 1 lines. Font size default, line height default, vertical align: top. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1' } ],
dataSource: [],
});
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => { pdfCell.verticalAlign = 'top'; };
const expectedLog = [
'text,F1,10,15,{baseline:top}',
'setLineWidth,1',
'rect,10,15,100,50'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
QUnit.test('1 col - 1 lines. Font size default, line height default, vertical align: middle. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1' } ],
dataSource: [],
});
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => { pdfCell.verticalAlign = 'middle'; };
const expectedLog = [
'text,F1,10,40,{baseline:middle}',
'setLineWidth,1',
'rect,10,15,100,50'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
QUnit.test('1 col - 1 lines. Font size default, line height default, vertical align: bottom. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1' } ],
dataSource: [],
});
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => { pdfCell.verticalAlign = 'bottom'; };
const expectedLog = [
'text,F1,10,65,{baseline:bottom}',
'setLineWidth,1',
'rect,10,15,100,50'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
QUnit.test('1 col - 1 lines. Font size 10px, line height default, vertical align: top. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1' } ],
dataSource: [],
});
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => {
pdfCell.verticalAlign = 'top';
pdfCell.font = { size: 10 };
};
const expectedLog = [
'setFontSize,10',
'text,F1,10,15,{baseline:top}',
'setLineWidth,1',
'rect,10,15,100,50',
'setFontSize,16'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
QUnit.test('1 col - 1 lines. Font size 10, line height default, vertical align: middle. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1' } ],
dataSource: [],
});
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => {
pdfCell.verticalAlign = 'middle';
pdfCell.font = { size: 10 };
};
const expectedLog = [
'setFontSize,10',
'text,F1,10,40,{baseline:middle}',
'setLineWidth,1',
'rect,10,15,100,50',
'setFontSize,16'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
QUnit.test('1 col - 1 lines. Font size 10, line height default, vertical align: bottom. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1' } ],
dataSource: [],
});
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => {
pdfCell.verticalAlign = 'bottom';
pdfCell.font = { size: 10 };
};
const expectedLog = [
'setFontSize,10',
'text,F1,10,65,{baseline:bottom}',
'setLineWidth,1',
'rect,10,15,100,50',
'setFontSize,16'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
QUnit.test('1 col - 1 lines. Font size 20px, line height default, vertical align: top. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1' } ],
dataSource: [],
});
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => {
pdfCell.verticalAlign = 'top';
pdfCell.font = { size: 20 };
};
const expectedLog = [
'setFontSize,20',
'text,F1,10,15,{baseline:top}',
'setLineWidth,1',
'rect,10,15,100,50',
'setFontSize,16'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
QUnit.test('1 col - 1 lines. Font size 20, line height default, vertical align: middle. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1' } ],
dataSource: [],
});
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => {
pdfCell.verticalAlign = 'middle';
pdfCell.font = { size: 20 };
};
const expectedLog = [
'setFontSize,20',
'text,F1,10,40,{baseline:middle}',
'setLineWidth,1',
'rect,10,15,100,50',
'setFontSize,16'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
QUnit.test('1 col - 1 lines. Font size 20, line height default, vertical align: bottom. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1' } ],
dataSource: [],
});
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => {
pdfCell.verticalAlign = 'bottom';
pdfCell.font = { size: 20 };
};
const expectedLog = [
'setFontSize,20',
'text,F1,10,65,{baseline:bottom}',
'setLineWidth,1',
'rect,10,15,100,50',
'setFontSize,16'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
QUnit.test('1 col - 1 lines. Font size default, line height 1, vertical align: top. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1' } ],
dataSource: [],
});
doc.setLineHeightFactor(1);
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => { pdfCell.verticalAlign = 'top'; };
const expectedLog = [
'setLineHeightFactor,1',
'text,F1,10,12.6,{baseline:top}',
'setLineWidth,1',
'rect,10,15,100,50'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
QUnit.test('1 col - 1 lines. Font size default, line height 1, vertical align: middle. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1' } ],
dataSource: [],
});
doc.setLineHeightFactor(1);
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => { pdfCell.verticalAlign = 'middle'; };
const expectedLog = [
'setLineHeightFactor,1',
'text,F1,10,37.6,{baseline:middle}',
'setLineWidth,1',
'rect,10,15,100,50'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
QUnit.test('1 col - 1 lines. Font size default, line height 1, vertical align: bottom. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1' } ],
dataSource: [],
});
doc.setLineHeightFactor(1);
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => { pdfCell.verticalAlign = 'bottom'; };
const expectedLog = [
'setLineHeightFactor,1',
'text,F1,10,62.6,{baseline:bottom}',
'setLineWidth,1',
'rect,10,15,100,50'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
QUnit.test('1 col - 1 lines. Font size 10px, line height 1, vertical align: top. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1' } ],
dataSource: [],
});
doc.setLineHeightFactor(1);
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => {
pdfCell.verticalAlign = 'top';
pdfCell.font = { size: 10 };
};
const expectedLog = [
'setLineHeightFactor,1',
'setFontSize,10',
'text,F1,10,13.5,{baseline:top}',
'setLineWidth,1',
'rect,10,15,100,50',
'setFontSize,16'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
QUnit.test('1 col - 1 lines. Font size 10, line height 1, vertical align: middle. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1' } ],
dataSource: [],
});
doc.setLineHeightFactor(1);
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => {
pdfCell.verticalAlign = 'middle';
pdfCell.font = { size: 10 };
};
const expectedLog = [
'setLineHeightFactor,1',
'setFontSize,10',
'text,F1,10,38.5,{baseline:middle}',
'setLineWidth,1',
'rect,10,15,100,50',
'setFontSize,16'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
QUnit.test('1 col - 1 lines. Font size 10, line height 1, vertical align: bottom. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1' } ],
dataSource: [],
});
doc.setLineHeightFactor(1);
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => {
pdfCell.verticalAlign = 'bottom';
pdfCell.font = { size: 10 };
};
const expectedLog = [
'setLineHeightFactor,1',
'setFontSize,10',
'text,F1,10,63.5,{baseline:bottom}',
'setLineWidth,1',
'rect,10,15,100,50',
'setFontSize,16'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
QUnit.test('1 col - 1 lines. Font size 20px, line height 1, vertical align: top. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1' } ],
dataSource: [],
});
doc.setLineHeightFactor(1);
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => {
pdfCell.verticalAlign = 'top';
pdfCell.font = { size: 20 };
};
const expectedLog = [
'setLineHeightFactor,1',
'setFontSize,20',
'text,F1,10,12,{baseline:top}',
'setLineWidth,1',
'rect,10,15,100,50',
'setFontSize,16'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
QUnit.test('1 col - 1 lines. Font size 20, line height 1, vertical align: middle. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1' } ],
dataSource: [],
});
doc.setLineHeightFactor(1);
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => {
pdfCell.verticalAlign = 'middle';
pdfCell.font = { size: 20 };
};
const expectedLog = [
'setLineHeightFactor,1',
'setFontSize,20',
'text,F1,10,37,{baseline:middle}',
'setLineWidth,1',
'rect,10,15,100,50',
'setFontSize,16'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
QUnit.test('1 col - 1 lines. Font size 20, line height 1, vertical align: bottom. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1' } ],
dataSource: [],
});
doc.setLineHeightFactor(1);
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => {
pdfCell.verticalAlign = 'bottom';
pdfCell.font = { size: 20 };
};
const expectedLog = [
'setLineHeightFactor,1',
'setFontSize,20',
'text,F1,10,62,{baseline:bottom}',
'setLineWidth,1',
'rect,10,15,100,50',
'setFontSize,16'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
QUnit.test('1 col - 1 lines. Font size default, line height 1.5, vertical align: top. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1' } ],
dataSource: [],
});
doc.setLineHeightFactor(1.5);
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => { pdfCell.verticalAlign = 'top'; };
const expectedLog = [
'setLineHeightFactor,1.5',
'text,F1,10,20.6,{baseline:top}',
'setLineWidth,1',
'rect,10,15,100,50'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
QUnit.test('1 col - 1 lines. Font size default, line height 1.5, vertical align: middle. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1' } ],
dataSource: [],
});
doc.setLineHeightFactor(1.5);
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => { pdfCell.verticalAlign = 'middle'; };
const expectedLog = [
'setLineHeightFactor,1.5',
'text,F1,10,45.6,{baseline:middle}',
'setLineWidth,1',
'rect,10,15,100,50'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
QUnit.test('1 col - 1 lines. Font size default, line height 1.5, vertical align: bottom. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1' } ],
dataSource: [],
});
doc.setLineHeightFactor(1.5);
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => { pdfCell.verticalAlign = 'bottom'; };
const expectedLog = [
'setLineHeightFactor,1.5',
'text,F1,10,70.6,{baseline:bottom}',
'setLineWidth,1',
'rect,10,15,100,50'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
QUnit.test('1 col - 1 lines. Font size 10px, line height 1.5, vertical align: top. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1' } ],
dataSource: [],
});
doc.setLineHeightFactor(1.5);
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => {
pdfCell.verticalAlign = 'top';
pdfCell.font = { size: 10 };
};
const expectedLog = [
'setLineHeightFactor,1.5',
'setFontSize,10',
'text,F1,10,18.5,{baseline:top}',
'setLineWidth,1',
'rect,10,15,100,50',
'setFontSize,16'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
QUnit.test('1 col - 1 lines. Font size 10, line height 1.5, vertical align: middle. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1' } ],
dataSource: [],
});
doc.setLineHeightFactor(1.5);
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => {
pdfCell.verticalAlign = 'middle';
pdfCell.font = { size: 10 };
};
const expectedLog = [
'setLineHeightFactor,1.5',
'setFontSize,10',
'text,F1,10,43.5,{baseline:middle}',
'setLineWidth,1',
'rect,10,15,100,50',
'setFontSize,16'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
QUnit.test('1 col - 1 lines. Font size 10, line height 1.5, vertical align: bottom. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1' } ],
dataSource: [],
});
doc.setLineHeightFactor(1.5);
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => {
pdfCell.verticalAlign = 'bottom';
pdfCell.font = { size: 10 };
};
const expectedLog = [
'setLineHeightFactor,1.5',
'setFontSize,10',
'text,F1,10,68.5,{baseline:bottom}',
'setLineWidth,1',
'rect,10,15,100,50',
'setFontSize,16'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
QUnit.test('1 col - 1 lines. Font size 20px, line height 1.5, vertical align: top. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1' } ],
dataSource: [],
});
doc.setLineHeightFactor(1.5);
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => {
pdfCell.verticalAlign = 'top';
pdfCell.font = { size: 20 };
};
const expectedLog = [
'setLineHeightFactor,1.5',
'setFontSize,20',
'text,F1,10,22,{baseline:top}',
'setLineWidth,1',
'rect,10,15,100,50',
'setFontSize,16'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
QUnit.test('1 col - 1 lines. Font size 20, line height 1.5, vertical align: middle. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1' } ],
dataSource: [],
});
doc.setLineHeightFactor(1.5);
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => {
pdfCell.verticalAlign = 'middle';
pdfCell.font = { size: 20 };
};
const expectedLog = [
'setLineHeightFactor,1.5',
'setFontSize,20',
'text,F1,10,47,{baseline:middle}',
'setLineWidth,1',
'rect,10,15,100,50',
'setFontSize,16'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
QUnit.test('1 col - 1 lines. Font size 20, line height 1.5, vertical align: bottom. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1' } ],
dataSource: [],
});
doc.setLineHeightFactor(1.5);
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => {
pdfCell.verticalAlign = 'bottom';
pdfCell.font = { size: 20 };
};
const expectedLog = [
'setLineHeightFactor,1.5',
'setFontSize,20',
'text,F1,10,72,{baseline:bottom}',
'setLineWidth,1',
'rect,10,15,100,50',
'setFontSize,16'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
/// -------------------------------------------------------------------------------
QUnit.test('1 col - 2 lines. Font size default, line height default, vertical align: top. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1', caption: 'f1\nf2' } ],
dataSource: [],
});
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => { pdfCell.verticalAlign = 'top'; };
const expectedLog = [
'text,f1\nf2,10,15,{baseline:top}',
'setLineWidth,1',
'rect,10,15,100,50'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
QUnit.test('1 col - 2 lines. Font size default, line height default, vertical align: middle. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1', caption: 'f1\nf2' } ],
dataSource: [],
});
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => { pdfCell.verticalAlign = 'middle'; };
const expectedLog = [
'text,f1\nf2,10,30.8,{baseline:middle}',
'setLineWidth,1',
'rect,10,15,100,50'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
QUnit.test('1 col - 2 lines. Font size default, line height default, vertical align: bottom. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1', caption: 'f1\nf2' } ],
dataSource: [],
});
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => { pdfCell.verticalAlign = 'bottom'; };
const expectedLog = [
'text,f1\nf2,10,46.6,{baseline:bottom}',
'setLineWidth,1',
'rect,10,15,100,50'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
QUnit.test('1 col - 2 lines. Font size 10px, line height default, vertical align: top. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1', caption: 'f1\nf2' } ],
dataSource: [],
});
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => {
pdfCell.verticalAlign = 'top';
pdfCell.font = { size: 10 };
};
const expectedLog = [
'setFontSize,10',
'text,f1\nf2,10,15,{baseline:top}',
'setLineWidth,1',
'rect,10,15,100,50',
'setFontSize,16'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
QUnit.test('1 col - 2 lines. Font size 10, line height default, vertical align: middle. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1', caption: 'f1\nf2' } ],
dataSource: [],
});
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => {
pdfCell.verticalAlign = 'middle';
pdfCell.font = { size: 10 };
};
const expectedLog = [
'setFontSize,10',
'text,f1\nf2,10,34.25,{baseline:middle}',
'setLineWidth,1',
'rect,10,15,100,50',
'setFontSize,16'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
QUnit.test('1 col - 2 lines. Font size 10, line height default, vertical align: bottom. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1', caption: 'f1\nf2' } ],
dataSource: [],
});
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => {
pdfCell.verticalAlign = 'bottom';
pdfCell.font = { size: 10 };
};
const expectedLog = [
'setFontSize,10',
'text,f1\nf2,10,53.5,{baseline:bottom}',
'setLineWidth,1',
'rect,10,15,100,50',
'setFontSize,16'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
QUnit.test('1 col - 2 lines. Font size 20px, line height default, vertical align: top. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1', caption: 'f1\nf2' } ],
dataSource: [],
});
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => {
pdfCell.verticalAlign = 'top';
pdfCell.font = { size: 20 };
};
const expectedLog = [
'setFontSize,20',
'text,f1\nf2,10,15,{baseline:top}',
'setLineWidth,1',
'rect,10,15,100,50',
'setFontSize,16'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
QUnit.test('1 col - 2 lines. Font size 20, line height default, vertical align: middle. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1', caption: 'f1\nf2' } ],
dataSource: [],
});
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => {
pdfCell.verticalAlign = 'middle';
pdfCell.font = { size: 20 };
};
const expectedLog = [
'setFontSize,20',
'text,f1\nf2,10,28.5,{baseline:middle}',
'setLineWidth,1',
'rect,10,15,100,50',
'setFontSize,16'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
QUnit.test('1 col - 2 lines. Font size 20, line height default, vertical align: bottom. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1', caption: 'f1\nf2' } ],
dataSource: [],
});
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => {
pdfCell.verticalAlign = 'bottom';
pdfCell.font = { size: 20 };
};
const expectedLog = [
'setFontSize,20',
'text,f1\nf2,10,42,{baseline:bottom}',
'setLineWidth,1',
'rect,10,15,100,50',
'setFontSize,16'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
QUnit.test('1 col - 2 lines. Font size default, line height 1, vertical align: top. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1', caption: 'f1\nf2' } ],
dataSource: [],
});
doc.setLineHeightFactor(1);
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => { pdfCell.verticalAlign = 'top'; };
const expectedLog = [
'setLineHeightFactor,1',
'text,f1\nf2,10,12.6,{baseline:top}',
'setLineWidth,1',
'rect,10,15,100,50'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
QUnit.test('1 col - 2 lines. Font size default, line height 1, vertical align: middle. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1', caption: 'f1\nf2' } ],
dataSource: [],
});
doc.setLineHeightFactor(1);
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => { pdfCell.verticalAlign = 'middle'; };
const expectedLog = [
'setLineHeightFactor,1',
'text,f1\nf2,10,29.6,{baseline:middle}',
'setLineWidth,1',
'rect,10,15,100,50'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
QUnit.test('1 col - 2 lines. Font size default, line height 1, vertical align: bottom. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1', caption: 'f1\nf2' } ],
dataSource: [],
});
doc.setLineHeightFactor(1);
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => { pdfCell.verticalAlign = 'bottom'; };
const expectedLog = [
'setLineHeightFactor,1',
'text,f1\nf2,10,46.6,{baseline:bottom}',
'setLineWidth,1',
'rect,10,15,100,50'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
QUnit.test('1 col - 2 lines. Font size 10px, line height 1, vertical align: top. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1', caption: 'f1\nf2' } ],
dataSource: [],
});
doc.setLineHeightFactor(1);
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => {
pdfCell.verticalAlign = 'top';
pdfCell.font = { size: 10 };
};
const expectedLog = [
'setLineHeightFactor,1',
'setFontSize,10',
'text,f1\nf2,10,13.5,{baseline:top}',
'setLineWidth,1',
'rect,10,15,100,50',
'setFontSize,16'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
QUnit.test('1 col - 2 lines. Font size 10, line height 1, vertical align: middle. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1', caption: 'f1\nf2' } ],
dataSource: [],
});
doc.setLineHeightFactor(1);
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => {
pdfCell.verticalAlign = 'middle';
pdfCell.font = { size: 10 };
};
const expectedLog = [
'setLineHeightFactor,1',
'setFontSize,10',
'text,f1\nf2,10,33.5,{baseline:middle}',
'setLineWidth,1',
'rect,10,15,100,50',
'setFontSize,16'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
QUnit.test('1 col - 2 lines. Font size 10, line height 1, vertical align: bottom. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1', caption: 'f1\nf2' } ],
dataSource: [],
});
doc.setLineHeightFactor(1);
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => {
pdfCell.verticalAlign = 'bottom';
pdfCell.font = { size: 10 };
};
const expectedLog = [
'setLineHeightFactor,1',
'setFontSize,10',
'text,f1\nf2,10,53.5,{baseline:bottom}',
'setLineWidth,1',
'rect,10,15,100,50',
'setFontSize,16'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
QUnit.test('1 col - 2 lines. Font size 20px, line height 1, vertical align: top. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1', caption: 'f1\nf2' } ],
dataSource: [],
});
doc.setLineHeightFactor(1);
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => {
pdfCell.verticalAlign = 'top';
pdfCell.font = { size: 20 };
};
const expectedLog = [
'setLineHeightFactor,1',
'setFontSize,20',
'text,f1\nf2,10,12,{baseline:top}',
'setLineWidth,1',
'rect,10,15,100,50',
'setFontSize,16'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
QUnit.test('1 col - 2 lines. Font size 20, line height 1, vertical align: middle. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1', caption: 'f1\nf2' } ],
dataSource: [],
});
doc.setLineHeightFactor(1);
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => {
pdfCell.verticalAlign = 'middle';
pdfCell.font = { size: 20 };
};
const expectedLog = [
'setLineHeightFactor,1',
'setFontSize,20',
'text,f1\nf2,10,27,{baseline:middle}',
'setLineWidth,1',
'rect,10,15,100,50',
'setFontSize,16'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
QUnit.test('1 col - 2 lines. Font size 20, line height 1, vertical align: bottom. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1', caption: 'f1\nf2' } ],
dataSource: [],
});
doc.setLineHeightFactor(1);
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => {
pdfCell.verticalAlign = 'bottom';
pdfCell.font = { size: 20 };
};
const expectedLog = [
'setLineHeightFactor,1',
'setFontSize,20',
'text,f1\nf2,10,42,{baseline:bottom}',
'setLineWidth,1',
'rect,10,15,100,50',
'setFontSize,16'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
QUnit.test('1 col - 2 lines. Font size default, line height 1.5, vertical align: top. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1', caption: 'f1\nf2' } ],
dataSource: [],
});
doc.setLineHeightFactor(1.5);
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => { pdfCell.verticalAlign = 'top'; };
const expectedLog = [
'setLineHeightFactor,1.5',
'text,f1\nf2,10,20.6,{baseline:top}',
'setLineWidth,1',
'rect,10,15,100,50'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
QUnit.test('1 col - 2 lines. Font size default, line height 1.5, vertical align: middle. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1', caption: 'f1\nf2' } ],
dataSource: [],
});
doc.setLineHeightFactor(1.5);
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => { pdfCell.verticalAlign = 'middle'; };
const expectedLog = [
'setLineHeightFactor,1.5',
'text,f1\nf2,10,33.6,{baseline:middle}',
'setLineWidth,1',
'rect,10,15,100,50'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
QUnit.test('1 col - 2 lines. Font size default, line height 1.5, vertical align: bottom. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1', caption: 'f1\nf2' } ],
dataSource: [],
});
doc.setLineHeightFactor(1.5);
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => { pdfCell.verticalAlign = 'bottom'; };
const expectedLog = [
'setLineHeightFactor,1.5',
'text,f1\nf2,10,46.6,{baseline:bottom}',
'setLineWidth,1',
'rect,10,15,100,50'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
QUnit.test('1 col - 2 lines. Font size 10px, line height 1.5, vertical align: top. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1', caption: 'f1\nf2' } ],
dataSource: [],
});
doc.setLineHeightFactor(1.5);
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => {
pdfCell.verticalAlign = 'top';
pdfCell.font = { size: 10 };
};
const expectedLog = [
'setLineHeightFactor,1.5',
'setFontSize,10',
'text,f1\nf2,10,18.5,{baseline:top}',
'setLineWidth,1',
'rect,10,15,100,50',
'setFontSize,16'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
QUnit.test('1 col - 2 lines. Font size 10, line height 1.5, vertical align: middle. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1', caption: 'f1\nf2' } ],
dataSource: [],
});
doc.setLineHeightFactor(1.5);
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => {
pdfCell.verticalAlign = 'middle';
pdfCell.font = { size: 10 };
};
const expectedLog = [
'setLineHeightFactor,1.5',
'setFontSize,10',
'text,f1\nf2,10,36,{baseline:middle}',
'setLineWidth,1',
'rect,10,15,100,50',
'setFontSize,16'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
QUnit.test('1 col - 2 lines. Font size 10, line height 1.5, vertical align: bottom. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1', caption: 'f1\nf2' } ],
dataSource: [],
});
doc.setLineHeightFactor(1.5);
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => {
pdfCell.verticalAlign = 'bottom';
pdfCell.font = { size: 10 };
};
const expectedLog = [
'setLineHeightFactor,1.5',
'setFontSize,10',
'text,f1\nf2,10,53.5,{baseline:bottom}',
'setLineWidth,1',
'rect,10,15,100,50',
'setFontSize,16'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
QUnit.test('1 col - 2 lines. Font size 20px, line height 1.5, vertical align: top. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1', caption: 'f1\nf2' } ],
dataSource: [],
});
doc.setLineHeightFactor(1.5);
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => {
pdfCell.verticalAlign = 'top';
pdfCell.font = { size: 20 };
};
const expectedLog = [
'setLineHeightFactor,1.5',
'setFontSize,20',
'text,f1\nf2,10,22,{baseline:top}',
'setLineWidth,1',
'rect,10,15,100,50',
'setFontSize,16'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
QUnit.test('1 col - 2 lines. Font size 20, line height 1.5, vertical align: middle. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1', caption: 'f1\nf2' } ],
dataSource: [],
});
doc.setLineHeightFactor(1.5);
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => {
pdfCell.verticalAlign = 'middle';
pdfCell.font = { size: 20 };
};
const expectedLog = [
'setLineHeightFactor,1.5',
'setFontSize,20',
'text,f1\nf2,10,32,{baseline:middle}',
'setLineWidth,1',
'rect,10,15,100,50',
'setFontSize,16'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
QUnit.test('1 col - 2 lines. Font size 20, line height 1.5, vertical align: bottom. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1', caption: 'f1\nf2' } ],
dataSource: [],
});
doc.setLineHeightFactor(1.5);
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => {
pdfCell.verticalAlign = 'bottom';
pdfCell.font = { size: 20 };
};
const expectedLog = [
'setLineHeightFactor,1.5',
'setFontSize,20',
'text,f1\nf2,10,42,{baseline:bottom}',
'setLineWidth,1',
'rect,10,15,100,50',
'setFontSize,16'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
QUnit.test('1 col - 3 lines. Font size default, line height default, vertical align: top. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1', caption: 'f1\nf2\nf3' } ],
dataSource: [],
});
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => { pdfCell.verticalAlign = 'top'; };
const expectedLog = [
'text,f1\nf2\nf3,10,15,{baseline:top}',
'setLineWidth,1',
'rect,10,15,100,50'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
QUnit.test('1 col - 3 lines. Font size default, line height default, vertical align: middle. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1', caption: 'f1\nf2\nf3' } ],
dataSource: [],
});
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => { pdfCell.verticalAlign = 'middle'; };
const expectedLog = [
'text,f1\nf2\nf3,10,21.6,{baseline:middle}',
'setLineWidth,1',
'rect,10,15,100,50'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
QUnit.test('1 col - 3 lines. Font size default, line height default, vertical align: bottom. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1', caption: 'f1\nf2\nf3' } ],
dataSource: [],
});
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => { pdfCell.verticalAlign = 'bottom'; };
const expectedLog = [
'text,f1\nf2\nf3,10,28.2,{baseline:bottom}',
'setLineWidth,1',
'rect,10,15,100,50'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
QUnit.test('1 col - 3 lines. Font size 10px, line height default, vertical align: top. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1', caption: 'f1\nf2\nf3' } ],
dataSource: [],
});
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => {
pdfCell.verticalAlign = 'top';
pdfCell.font = { size: 10 };
};
const expectedLog = [
'setFontSize,10',
'text,f1\nf2\nf3,10,15,{baseline:top}',
'setLineWidth,1',
'rect,10,15,100,50',
'setFontSize,16'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
QUnit.test('1 col - 3 lines. Font size 10, line height default, vertical align: middle. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1', caption: 'f1\nf2\nf3' } ],
dataSource: [],
});
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => {
pdfCell.verticalAlign = 'middle';
pdfCell.font = { size: 10 };
};
const expectedLog = [
'setFontSize,10',
'text,f1\nf2\nf3,10,28.5,{baseline:middle}',
'setLineWidth,1',
'rect,10,15,100,50',
'setFontSize,16'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
QUnit.test('1 col - 3 lines. Font size 10, line height default, vertical align: bottom. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1', caption: 'f1\nf2\nf3' } ],
dataSource: [],
});
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => {
pdfCell.verticalAlign = 'bottom';
pdfCell.font = { size: 10 };
};
const expectedLog = [
'setFontSize,10',
'text,f1\nf2\nf3,10,42,{baseline:bottom}',
'setLineWidth,1',
'rect,10,15,100,50',
'setFontSize,16'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
QUnit.test('1 col - 3 lines. Font size 20px, line height default, vertical align: top. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1', caption: 'f1\nf2\nf3' } ],
dataSource: [],
});
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => {
pdfCell.verticalAlign = 'top';
pdfCell.font = { size: 20 };
};
const expectedLog = [
'setFontSize,20',
'text,f1\nf2\nf3,10,15,{baseline:top}',
'setLineWidth,1',
'rect,10,15,100,50',
'setFontSize,16'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
QUnit.test('1 col - 3 lines. Font size 20, line height default, vertical align: middle. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1', caption: 'f1\nf2\nf3' } ],
dataSource: [],
});
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => {
pdfCell.verticalAlign = 'middle';
pdfCell.font = { size: 20 };
};
const expectedLog = [
'setFontSize,20',
'text,f1\nf2\nf3,10,17,{baseline:middle}',
'setLineWidth,1',
'rect,10,15,100,50',
'setFontSize,16'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
QUnit.test('1 col - 3 lines. Font size 20, line height default, vertical align: bottom. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1', caption: 'f1\nf2\nf3' } ],
dataSource: [],
});
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => {
pdfCell.verticalAlign = 'bottom';
pdfCell.font = { size: 20 };
};
const expectedLog = [
'setFontSize,20',
'text,f1\nf2\nf3,10,19,{baseline:bottom}',
'setLineWidth,1',
'rect,10,15,100,50',
'setFontSize,16'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
QUnit.test('1 col - 3 lines. Font size default, line height 1, vertical align: top. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1', caption: 'f1\nf2\nf3' } ],
dataSource: [],
});
doc.setLineHeightFactor(1);
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => { pdfCell.verticalAlign = 'top'; };
const expectedLog = [
'setLineHeightFactor,1',
'text,f1\nf2\nf3,10,12.6,{baseline:top}',
'setLineWidth,1',
'rect,10,15,100,50'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
QUnit.test('1 col - 3 lines. Font size default, line height 1, vertical align: middle. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1', caption: 'f1\nf2\nf3' } ],
dataSource: [],
});
doc.setLineHeightFactor(1);
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => { pdfCell.verticalAlign = 'middle'; };
const expectedLog = [
'setLineHeightFactor,1',
'text,f1\nf2\nf3,10,21.6,{baseline:middle}',
'setLineWidth,1',
'rect,10,15,100,50'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
QUnit.test('1 col - 3 lines. Font size default, line height 1, vertical align: bottom. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1', caption: 'f1\nf2\nf3' } ],
dataSource: [],
});
doc.setLineHeightFactor(1);
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => { pdfCell.verticalAlign = 'bottom'; };
const expectedLog = [
'setLineHeightFactor,1',
'text,f1\nf2\nf3,10,30.6,{baseline:bottom}',
'setLineWidth,1',
'rect,10,15,100,50'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
QUnit.test('1 col - 3 lines. Font size 10px, line height 1, vertical align: top. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1', caption: 'f1\nf2\nf3' } ],
dataSource: [],
});
doc.setLineHeightFactor(1);
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => {
pdfCell.verticalAlign = 'top';
pdfCell.font = { size: 10 };
};
const expectedLog = [
'setLineHeightFactor,1',
'setFontSize,10',
'text,f1\nf2\nf3,10,13.5,{baseline:top}',
'setLineWidth,1',
'rect,10,15,100,50',
'setFontSize,16'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
QUnit.test('1 col - 3 lines. Font size 10, line height 1, vertical align: middle. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1', caption: 'f1\nf2\nf3' } ],
dataSource: [],
});
doc.setLineHeightFactor(1);
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => {
pdfCell.verticalAlign = 'middle';
pdfCell.font = { size: 10 };
};
const expectedLog = [
'setLineHeightFactor,1',
'setFontSize,10',
'text,f1\nf2\nf3,10,28.5,{baseline:middle}',
'setLineWidth,1',
'rect,10,15,100,50',
'setFontSize,16'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
QUnit.test('1 col - 3 lines. Font size 10, line height 1, vertical align: bottom. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1', caption: 'f1\nf2\nf3' } ],
dataSource: [],
});
doc.setLineHeightFactor(1);
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => {
pdfCell.verticalAlign = 'bottom';
pdfCell.font = { size: 10 };
};
const expectedLog = [
'setLineHeightFactor,1',
'setFontSize,10',
'text,f1\nf2\nf3,10,43.5,{baseline:bottom}',
'setLineWidth,1',
'rect,10,15,100,50',
'setFontSize,16'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
QUnit.test('1 col - 3 lines. Font size 20px, line height 1, vertical align: top. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1', caption: 'f1\nf2\nf3' } ],
dataSource: [],
});
doc.setLineHeightFactor(1);
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => {
pdfCell.verticalAlign = 'top';
pdfCell.font = { size: 20 };
};
const expectedLog = [
'setLineHeightFactor,1',
'setFontSize,20',
'text,f1\nf2\nf3,10,12,{baseline:top}',
'setLineWidth,1',
'rect,10,15,100,50',
'setFontSize,16'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
QUnit.test('1 col - 3 lines. Font size 20, line height 1, vertical align: middle. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1', caption: 'f1\nf2\nf3' } ],
dataSource: [],
});
doc.setLineHeightFactor(1);
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => {
pdfCell.verticalAlign = 'middle';
pdfCell.font = { size: 20 };
};
const expectedLog = [
'setLineHeightFactor,1',
'setFontSize,20',
'text,f1\nf2\nf3,10,17,{baseline:middle}',
'setLineWidth,1',
'rect,10,15,100,50',
'setFontSize,16'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
QUnit.test('1 col - 3 lines. Font size 20, line height 1, vertical align: bottom. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1', caption: 'f1\nf2\nf3' } ],
dataSource: [],
});
doc.setLineHeightFactor(1);
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => {
pdfCell.verticalAlign = 'bottom';
pdfCell.font = { size: 20 };
};
const expectedLog = [
'setLineHeightFactor,1',
'setFontSize,20',
'text,f1\nf2\nf3,10,22,{baseline:bottom}',
'setLineWidth,1',
'rect,10,15,100,50',
'setFontSize,16'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
QUnit.test('1 col - 3 lines. Font size default, line height 1.5, vertical align: top. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1', caption: 'f1\nf2\nf3' } ],
dataSource: [],
});
doc.setLineHeightFactor(1.5);
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => { pdfCell.verticalAlign = 'top'; };
const expectedLog = [
'setLineHeightFactor,1.5',
'text,f1\nf2\nf3,10,20.6,{baseline:top}',
'setLineWidth,1',
'rect,10,15,100,50'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
QUnit.test('1 col - 3 lines. Font size default, line height 1.5, vertical align: middle. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1', caption: 'f1\nf2\nf3' } ],
dataSource: [],
});
doc.setLineHeightFactor(1.5);
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => { pdfCell.verticalAlign = 'middle'; };
const expectedLog = [
'setLineHeightFactor,1.5',
'text,f1\nf2\nf3,10,21.6,{baseline:middle}',
'setLineWidth,1',
'rect,10,15,100,50'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
QUnit.test('1 col - 3 lines. Font size default, line height 1.5, vertical align: bottom. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1', caption: 'f1\nf2\nf3' } ],
dataSource: [],
});
doc.setLineHeightFactor(1.5);
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => { pdfCell.verticalAlign = 'bottom'; };
const expectedLog = [
'setLineHeightFactor,1.5',
'text,f1\nf2\nf3,10,22.6,{baseline:bottom}',
'setLineWidth,1',
'rect,10,15,100,50'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
QUnit.test('1 col - 3 lines. Font size 10px, line height 1.5, vertical align: top. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1', caption: 'f1\nf2\nf3' } ],
dataSource: [],
});
doc.setLineHeightFactor(1.5);
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => {
pdfCell.verticalAlign = 'top';
pdfCell.font = { size: 10 };
};
const expectedLog = [
'setLineHeightFactor,1.5',
'setFontSize,10',
'text,f1\nf2\nf3,10,18.5,{baseline:top}',
'setLineWidth,1',
'rect,10,15,100,50',
'setFontSize,16'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
QUnit.test('1 col - 3 lines. Font size 10, line height 1.5, vertical align: middle. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1', caption: 'f1\nf2\nf3' } ],
dataSource: [],
});
doc.setLineHeightFactor(1.5);
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => {
pdfCell.verticalAlign = 'middle';
pdfCell.font = { size: 10 };
};
const expectedLog = [
'setLineHeightFactor,1.5',
'setFontSize,10',
'text,f1\nf2\nf3,10,28.5,{baseline:middle}',
'setLineWidth,1',
'rect,10,15,100,50',
'setFontSize,16'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
QUnit.test('1 col - 3 lines. Font size 10, line height 1.5, vertical align: bottom. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1', caption: 'f1\nf2\nf3' } ],
dataSource: [],
});
doc.setLineHeightFactor(1.5);
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => {
pdfCell.verticalAlign = 'bottom';
pdfCell.font = { size: 10 };
};
const expectedLog = [
'setLineHeightFactor,1.5',
'setFontSize,10',
'text,f1\nf2\nf3,10,38.5,{baseline:bottom}',
'setLineWidth,1',
'rect,10,15,100,50',
'setFontSize,16'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
QUnit.test('1 col - 3 lines. Font size 20px, line height 1.5, vertical align: top. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1', caption: 'f1\nf2\nf3' } ],
dataSource: [],
});
doc.setLineHeightFactor(1.5);
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => {
pdfCell.verticalAlign = 'top';
pdfCell.font = { size: 20 };
};
const expectedLog = [
'setLineHeightFactor,1.5',
'setFontSize,20',
'text,f1\nf2\nf3,10,22,{baseline:top}',
'setLineWidth,1',
'rect,10,15,100,50',
'setFontSize,16'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
QUnit.test('1 col - 3 lines. Font size 20, line height 1.5, vertical align: middle. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1', caption: 'f1\nf2\nf3' } ],
dataSource: [],
});
doc.setLineHeightFactor(1.5);
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => {
pdfCell.verticalAlign = 'middle';
pdfCell.font = { size: 20 };
};
const expectedLog = [
'setLineHeightFactor,1.5',
'setFontSize,20',
'text,f1\nf2\nf3,10,17,{baseline:middle}',
'setLineWidth,1',
'rect,10,15,100,50',
'setFontSize,16'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
QUnit.test('1 col - 3 lines. Font size 20, line height 1.5, vertical align: bottom. Cell height = 50px ', function(assert) {
const done = assert.async();
const doc = createMockPdfDoc();
const dataGrid = createDataGrid({
columns: [ { dataField: 'f1', caption: 'f1\nf2\nf3' } ],
dataSource: [],
});
doc.setLineHeightFactor(1.5);
const onRowExporting = (e) => { e.rowHeight = 50; };
const customizeCell = ({ pdfCell }) => {
pdfCell.verticalAlign = 'bottom';
pdfCell.font = { size: 20 };
};
const expectedLog = [
'setLineHeightFactor,1.5',
'setFontSize,20',
'text,f1\nf2\nf3,10,12,{baseline:bottom}',
'setLineWidth,1',
'rect,10,15,100,50',
'setFontSize,16'
];
exportDataGrid(doc, dataGrid, { topLeft: { x: 10, y: 15 }, columnWidths: [ 100 ], onRowExporting, customizeCell }).then(() => {
// doc.save(assert.test.testName + '.pdf');
assert.deepEqual(doc.__log, expectedLog);
done();
});
});
});
}
};
export { JSPdfVerticalAlignTests };
|
wowasa/x3ml
|
src/main/java/gr/forth/AuthorityPrirefThingCounter.java
|
<reponame>wowasa/x3ml<gh_stars>10-100
/*==============================================================================
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
==============================================================================*/
package gr.forth;
import static gr.forth.ics.isl.x3ml.X3MLGeneratorPolicy.CustomGenerator;
import static gr.forth.ics.isl.x3ml.X3MLGeneratorPolicy.CustomGeneratorException;
import lombok.extern.log4j.Log4j;
/**
* a date interpreter
*
* @author <NAME> <<EMAIL>>
* @author <NAME> <<EMAIL>>
*/
@Log4j
public class AuthorityPrirefThingCounter implements CustomGenerator {
private String authority;
private String priref;
private static String prirefOld;
private String thing;
private static String thingOld;
private static int counterInt = 0;
@Override
public void setArg(String name, String value) throws CustomGeneratorException {
if ("authority".equals(name)) {
authority = value;
} else if ("priref".equals(name)) {
priref = value;
} else if ("thing".equals(name)) {
thing = value;
} else {
throw new CustomGeneratorException("Unrecognized argument name: " + name);
}
}
@Override
public String getValue() throws CustomGeneratorException {
if (authority == null) {
throw new CustomGeneratorException("Missing text argument");
}
if (priref == null) {
throw new CustomGeneratorException("Missing bounds argument");
}
if (thing == null) {
throw new CustomGeneratorException("Missing text argument");
}
return getCounterObject(authority, priref, thing);
}
@Override
public String getValueType() throws CustomGeneratorException {
return "URI";
}
@Override
public void usesNamespacePrefix() {
log.debug("The "+this.getClass().getName()+" custom generator creates only URIs therefore it does not support injecting prefix");
;
}
private String getCounterObject(String authority, String priref, String thing) {
String counterObject = "";
if (counterInt == 0) {
setOldValues();
}
if (prirefOld.equals(priref) && thingOld.equals(thing)){
counterInt++;
}
else {
counterInt = 1;
setOldValues();
}
counterObject = authority + "/" + priref + "/" + thing + "/" + counterInt;
return counterObject;
}
private void setOldValues() {
prirefOld = priref;
thingOld = thing;
}
/** Returns a boolean flag (with value set to false) indicating that this
* generator DOES NOT support merging values from similar elements
* (elements having the same name).
*
* @return false*/
@Override
public boolean mergeMultipleValues(){
return false;
}
}
|
DamieFC/chromium
|
chrome/android/java/src/org/chromium/chrome/browser/externalnav/ExternalNavigationDelegateImpl.java
|
<reponame>DamieFC/chromium
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.externalnav;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import androidx.annotation.Nullable;
import org.chromium.base.ApplicationState;
import org.chromium.base.ApplicationStatus;
import org.chromium.base.ContextUtils;
import org.chromium.base.Function;
import org.chromium.base.IntentUtils;
import org.chromium.base.PackageManagerUtils;
import org.chromium.base.supplier.Supplier;
import org.chromium.chrome.browser.ChromeTabbedActivity2;
import org.chromium.chrome.browser.IntentHandler;
import org.chromium.chrome.browser.LaunchIntentDispatcher;
import org.chromium.chrome.browser.autofill_assistant.AutofillAssistantFacade;
import org.chromium.chrome.browser.instantapps.AuthenticatedProxyActivity;
import org.chromium.chrome.browser.instantapps.InstantAppsHandler;
import org.chromium.chrome.browser.tab.EmptyTabObserver;
import org.chromium.chrome.browser.tab.RedirectHandlerTabHelper;
import org.chromium.chrome.browser.tab.Tab;
import org.chromium.chrome.browser.tab.TabObserver;
import org.chromium.chrome.browser.tab.TabUtils;
import org.chromium.chrome.browser.tabmodel.TabModelSelector;
import org.chromium.chrome.browser.tabmodel.TabModelSelectorSupplier;
import org.chromium.components.external_intents.ExternalNavigationDelegate;
import org.chromium.components.external_intents.ExternalNavigationDelegate.StartActivityIfNeededResult;
import org.chromium.components.external_intents.ExternalNavigationHandler;
import org.chromium.components.external_intents.ExternalNavigationParams;
import org.chromium.components.external_intents.RedirectHandler;
import org.chromium.content_public.browser.LoadUrlParams;
import org.chromium.content_public.browser.WebContents;
import org.chromium.ui.base.WindowAndroid;
import org.chromium.url.GURL;
import org.chromium.url.Origin;
import java.util.List;
/**
* The main implementation of the {@link ExternalNavigationDelegate}.
*/
public class ExternalNavigationDelegateImpl implements ExternalNavigationDelegate {
protected final Context mApplicationContext;
private final Tab mTab;
private final TabObserver mTabObserver;
private final Supplier<TabModelSelector> mTabModelSelectorSupplier;
private boolean mIsTabDestroyed;
public ExternalNavigationDelegateImpl(Tab tab) {
mTab = tab;
mTabModelSelectorSupplier = TabModelSelectorSupplier.from(tab.getWindowAndroid());
mApplicationContext = ContextUtils.getApplicationContext();
mTabObserver = new EmptyTabObserver() {
@Override
public void onDestroyed(Tab tab) {
mIsTabDestroyed = true;
}
};
mTab.addObserver(mTabObserver);
}
@Override
public Context getContext() {
if (mTab.getWindowAndroid() == null) return null;
return mTab.getWindowAndroid().getContext().get();
}
/**
* Gets the {@link Activity} linked to this instance if it is available. At times this object
* might not have an associated Activity, in which case the ApplicationContext is returned.
* @return The activity {@link Context} if it can be reached.
* Application {@link Context} if not.
*/
protected final Context getAvailableContext() {
Activity activityContext = ContextUtils.activityFromContext(getContext());
if (activityContext == null) return ContextUtils.getApplicationContext();
return activityContext;
}
/**
* Determines whether Chrome would handle this Intent if fired immediately. Note that this does
* not guarantee that Chrome actually will handle the intent, as another app may be installed,
* or components may be enabled that provide alternative handlers for this intent before it gets
* fired.
*
* @param intent Intent that will be fired.
* @param matchDefaultOnly See {@link PackageManager#MATCH_DEFAULT_ONLY}.
* @return True if Chrome will definitely handle the intent, false otherwise.
*/
public static boolean willChromeHandleIntent(Intent intent, boolean matchDefaultOnly) {
Context context = ContextUtils.getApplicationContext();
// Early-out if the intent targets Chrome.
if (IntentUtils.intentTargetsSelf(context, intent)) return true;
// Fall back to the more expensive querying of Android when the intent doesn't target
// Chrome.
ResolveInfo info = PackageManagerUtils.resolveActivity(
intent, matchDefaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0);
return info != null && info.activityInfo.packageName.equals(context.getPackageName());
}
@Override
public boolean willAppHandleIntent(Intent intent) {
return willChromeHandleIntent(intent, false);
}
@Override
public boolean shouldDisableExternalIntentRequestsForUrl(GURL url) {
return false;
}
@Override
public boolean handlesInstantAppLaunchingInternally() {
return true;
}
/**
* Check whether the given package is a specialized handler for the given intent
*
* @param packageName Package name to check against. Can be null or empty.
* @param intent The intent to resolve for.
* @return Whether the given package is a specialized handler for the given intent. If there is
* no package name given checks whether there is any specialized handler.
*/
public static boolean isPackageSpecializedHandler(String packageName, Intent intent) {
List<ResolveInfo> handlers = PackageManagerUtils.queryIntentActivities(
intent, PackageManager.GET_RESOLVED_FILTER);
return !ExternalNavigationHandler
.getSpecializedHandlersWithFilter(handlers, packageName, true)
.isEmpty();
}
@Override
public void didStartActivity(Intent intent) {}
@Override
public @StartActivityIfNeededResult int maybeHandleStartActivityIfNeeded(
Intent intent, boolean proxy) {
return StartActivityIfNeededResult.DID_NOT_HANDLE;
}
@Override
public boolean canLoadUrlInCurrentTab() {
return !(mTab == null || mTab.isClosing() || !mTab.isInitialized());
}
@Override
public void loadUrlIfPossible(LoadUrlParams loadUrlParams) {
if (!hasValidTab()) return;
mTab.loadUrl(loadUrlParams);
}
@Override
public boolean isApplicationInForeground() {
return ApplicationStatus.getStateForApplication()
== ApplicationState.HAS_RUNNING_ACTIVITIES;
}
@Override
public void maybeSetWindowId(Intent intent) {
Context context = getAvailableContext();
if (!(context instanceof ChromeTabbedActivity2)) return;
intent.putExtra(IntentHandler.EXTRA_WINDOW_ID, 2);
}
@Override
public void closeTab() {
if (!hasValidTab()) return;
if (!mTabModelSelectorSupplier.hasValue()) return;
mTabModelSelectorSupplier.get().closeTab(mTab);
}
@Override
public boolean isIncognito() {
return mTab.isIncognito();
}
@Override
public void maybeAdjustInstantAppExtras(Intent intent, boolean isIntentToInstantApp) {
if (isIntentToInstantApp) {
intent.putExtra(InstantAppsHandler.IS_GOOGLE_SEARCH_REFERRER, true);
} else {
// Make sure this extra is not sent unless we've done the verification.
intent.removeExtra(InstantAppsHandler.IS_GOOGLE_SEARCH_REFERRER);
}
}
@Override
public void maybeSetRequestMetadata(Intent intent, boolean hasUserGesture,
boolean isRendererInitiated, @Nullable Origin initiatorOrigin) {
if (!hasUserGesture && !isRendererInitiated && initiatorOrigin == null) return;
// The intent can be used to launch Chrome itself, record the user
// gesture, whether request is renderer initiated and initiator origin here so that it can
// be used later.
IntentWithRequestMetadataHandler.RequestMetadata metadata =
new IntentWithRequestMetadataHandler.RequestMetadata(
hasUserGesture, isRendererInitiated, initiatorOrigin);
IntentWithRequestMetadataHandler.getInstance().onNewIntentWithRequestMetadata(
intent, metadata);
}
@Override
public void maybeSetPendingReferrer(Intent intent, GURL referrerUrl) {
IntentHandler.setPendingReferrer(intent, referrerUrl);
}
@Override
public void maybeSetPendingIncognitoUrl(Intent intent) {
IntentHandler.setPendingIncognitoUrl(intent);
}
@Override
public boolean maybeLaunchInstantApp(
GURL url, GURL referrerUrl, boolean isIncomingRedirect, boolean isSerpReferrer) {
if (!hasValidTab() || mTab.getWebContents() == null) return false;
InstantAppsHandler handler = InstantAppsHandler.getInstance();
RedirectHandler redirect = RedirectHandlerTabHelper.getHandlerFor(mTab);
Intent intent = redirect != null ? redirect.getInitialIntent() : null;
// TODO(mariakhomenko): consider also handling NDEF_DISCOVER action redirects.
if (isIncomingRedirect && intent != null && Intent.ACTION_VIEW.equals(intent.getAction())) {
// Set the URL the redirect was resolved to for checking the existence of the
// instant app inside handleIncomingIntent().
Intent resolvedIntent = new Intent(intent);
resolvedIntent.setData(Uri.parse(url.getSpec()));
return handler.handleIncomingIntent(getAvailableContext(), resolvedIntent,
LaunchIntentDispatcher.isCustomTabIntent(resolvedIntent), true);
} else if (!isIncomingRedirect) {
// Check if the navigation is coming from SERP and skip instant app handling.
if (isSerpReferrer) return false;
return handler.handleNavigation(getAvailableContext(), url, referrerUrl, mTab);
}
return false;
}
@Override
public WindowAndroid getWindowAndroid() {
if (mTab == null) return null;
return mTab.getWindowAndroid();
}
@Override
public WebContents getWebContents() {
if (mTab == null) return null;
return mTab.getWebContents();
}
@Override
public void dispatchAuthenticatedIntent(Intent intent) {
Intent proxyIntent = new Intent(Intent.ACTION_MAIN);
proxyIntent.setClass(getAvailableContext(), AuthenticatedProxyActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
proxyIntent.putExtra(AuthenticatedProxyActivity.AUTHENTICATED_INTENT_EXTRA, intent);
getAvailableContext().startActivity(proxyIntent);
}
/**
* Starts the autofill assistant with the given intent. Exists to allow tests to stub out this
* functionality.
*/
protected void startAutofillAssistantWithIntent(Intent targetIntent, GURL browserFallbackUrl) {
AutofillAssistantFacade.start(
TabUtils.getActivity(mTab), targetIntent.getExtras(), browserFallbackUrl.getSpec());
}
/**
* @return Whether or not we have a valid {@link Tab} available.
*/
@Override
public boolean hasValidTab() {
return mTab != null && !mIsTabDestroyed;
}
@Override
public boolean canCloseTabOnIncognitoIntentLaunch() {
return (mTab != null && !mTab.isClosing() && mTab.isInitialized());
}
@Override
public boolean isIntentForTrustedCallingApp(Intent intent) {
return false;
}
@Override
public boolean isIntentToInstantApp(Intent intent) {
return InstantAppsHandler.isIntentToInstantApp(intent);
}
@Override
public boolean isIntentToAutofillAssistant(Intent intent) {
return AutofillAssistantFacade.isAutofillAssistantByIntentTriggeringEnabled(intent);
}
@Override
public @IntentToAutofillAllowingAppResult int isIntentToAutofillAssistantAllowingApp(
ExternalNavigationParams params, Intent targetIntent,
Function<Intent, Boolean> canExternalAppHandleIntent) {
if (params.isIncognito()) {
return IntentToAutofillAllowingAppResult.NONE;
}
return AutofillAssistantFacade.shouldAllowOverrideWithApp(
targetIntent, canExternalAppHandleIntent);
}
@Override
public boolean handleWithAutofillAssistant(ExternalNavigationParams params, Intent targetIntent,
GURL browserFallbackUrl, boolean isGoogleReferrer) {
if (!browserFallbackUrl.isEmpty() && !params.isIncognito()
&& AutofillAssistantFacade.isAutofillAssistantByIntentTriggeringEnabled(
targetIntent)
&& isGoogleReferrer) {
if (mTab != null) {
startAutofillAssistantWithIntent(targetIntent, browserFallbackUrl);
}
return true;
}
return false;
}
}
|
arminn/optee_os
|
core/crypto/aes-gcm-private.h
|
/* SPDX-License-Identifier: BSD-2-Clause */
/*
* Copyright (c) 2017, Linaro Limited
*/
#include <crypto/internal_aes-gcm.h>
#include <types_ext.h>
#include <utee_defines.h>
static inline void internal_aes_gcm_xor_block(void *dst, const void *src)
{
uint64_t *d = dst;
const uint64_t *s = src;
d[0] ^= s[0];
d[1] ^= s[1];
}
static inline bool internal_aes_gcm_ptr_is_block_aligned(const void *p)
{
return !((vaddr_t)p & (TEE_AES_BLOCK_SIZE - 1));
}
void internal_aes_gcm_ghash_gen_tbl(struct internal_aes_gcm_state *state,
const struct internal_aes_gcm_key *enc_key);
void internal_aes_gcm_ghash_update_block(struct internal_aes_gcm_state *state,
const void *data);
|
Gerald-Gui/UCAS-Data-Structure
|
OJ_Assignment/Ch03-LIFO_FIFO/1018.3.21.cpp
|
<gh_stars>1-10
#include <iostream>
#include <cctype>
using namespace std;
constexpr int strlen = 100;
int val[strlen];
int top = 0;
bool IsStackEmpty() {
return top == 0;
}
int GetTop() {
if (top == 0) {
return 0;
}
return val[top - 1];
}
bool Push(int e) {
if (top == strlen) {
return false;
}
val[top++] = e;
return true;
}
int Pop() {
if (top == 0) {
return 0;
}
return val[--top];
}
bool OpLevelHigher(char op1, char op2) {
if (op1 == '(') {
return false;
}
if ((op2 == '*' || op2 == '/') && (op1 == '+' || op1 == '-')) {
return false;
}
return true;
}
int main() {
char input[strlen], rpn[strlen];
cin >> input;
int i, j = 0;
for (i = 0; input[i] != 0; ++i) {
if (isalpha(input[i])) {
rpn[j++] = input[i];
} else if (input[i] == '(') {
Push(input[i]);
} else if (input[i] == ')') {
while (!IsStackEmpty() && GetTop() != '(') {
rpn[j++] = Pop();
}
Pop();
} else {
while (!IsStackEmpty() && OpLevelHigher(GetTop(), input[i])) {
rpn[j++] = Pop();
}
Push(input[i]);
}
}
while (!IsStackEmpty()) {
rpn[j++] = Pop();
}
rpn[j] = '\0';
cout << rpn << endl;
return 0;
}
|
PeterStegemann/hermesONE
|
Main/Source/Screen/Setup/Channel.cpp
|
<filename>Main/Source/Screen/Setup/Channel.cpp
// Copyright 2008 <NAME>
#include "Channel.h"
#include "Main/Setup.h"
#include "GUI/Setup/Select.h"
#include "Signal/Processor.h"
#include "Signal/Utility.h"
#include "Text/Text.h"
#include "AVR/Source/Utility.h"
Screen_Setup_Channel::Screen_Setup_Channel( uint8_t ChannelId)
: Screen_Setup_Base( 0b11011101110101, Text::Channel)
, channelId( ChannelId)
{
channel = GLOBAL.SignalProcessor.GetChannel( channelId);
GLOBAL.SetupService.GetChannelName( channelId, channelName, SETUP_CHANNEL_NAME_SIZE + 1);
channelNameLabel.SetText_P( Text::Name);
channelNameInput.SetOptions(( GUI_Setup_TextInput::Options)
( GUI_Setup_TextInput::O_LimitAlphaNumeric));
sourceVolumeLabel.SetText_P( Text::FourDigitPercentFormat);
sourceVolumeLabel.SetOptions( GUI_Setup_Label::O_Fixed);
trimVolumeLabel.SetText_P( Text::FourDigitPercentFormat);
trimVolumeLabel.SetOptions( GUI_Setup_Label::O_Fixed);
limitVolumeLabel.SetText_P( Text::FourDigitPercentFormat);
limitVolumeLabel.SetOptions( GUI_Setup_Label::O_Fixed);
for( uint8_t PointId = 0; PointId < Setup_Channel::PV_PointVolumeCount; PointId++)
{
pointVolumeLabel[ PointId].SetOptions( GUI_Setup_Label::O_Fixed);
pointVolumeLabel[ PointId].SetText_P( Text::FourDigitPercentFormat);
}
currentGauge.SetOptions(( GUI_Setup_Gauge::Options)( GUI_Setup_Gauge::O_Percentage |
GUI_Setup_Gauge::O_DualPercentage |
GUI_Setup_Gauge::O_CenterLine |
GUI_Setup_Gauge::O_Marker));
}
void Screen_Setup_Channel::display( void)
{
// Adjust gauges to frame and set them up.
const FONT_Type* Font = FONT::GetFont( SCREEN_SETUP_BASE_MAIN_FONT);
uint16_t ContentLeft = frameLeft + 12 * Font->CellWidth;
uint16_t ContentWidth = frameWidth - ( ContentLeft - frameLeft) - 1;
uint16_t ValueLeft = menuLeft + 7 * Font->CellWidth;
uint16_t VolumeLeft = ValueLeft + ( SETUP_SOURCE_NAME_SIZE * Font->CellWidth);
uint8_t Line = 0;
GLOBAL.SetupDisplay.Print_P( menuLeft, frameTop, SCREEN_SETUP_BASE_MAIN_FONT,
LCD_65K_RGB::C_WarmYellow, LCD_65K_RGB::C_Black,
LCD::PO_Proportional, Text::Exit);
Line += 2;
channelNameLabel.SetDimensions( menuLeft, frameTop + ( Line * SCREEN_SETUP_BASE_LINE_HEIGHT));
channelNameLabel.Display();
channelNameValueLabel.SetDimensions( ValueLeft,
frameTop + ( Line * SCREEN_SETUP_BASE_LINE_HEIGHT));
channelNameInput.SetDimensions( menuLeft, frameTop + ( Line * SCREEN_SETUP_BASE_LINE_HEIGHT));
channelNameValueLabel.Display( channelName);
Line += 2;
// Source
GLOBAL.SetupDisplay.Print_P( menuLeft, frameTop + ( Line * SCREEN_SETUP_BASE_LINE_HEIGHT),
SCREEN_SETUP_BASE_MAIN_FONT, LCD_65K_RGB::C_White,
LCD_65K_RGB::C_Black, LCD::PO_Proportional, Text::Source);
sourceNameLabel.SetDimensions( ValueLeft, frameTop + ( Line * SCREEN_SETUP_BASE_LINE_HEIGHT));
SetSourceLabel( &sourceNameLabel, sourceName, channel->InputSignalSourceId);
sourceVolumeLabel.SetDimensions( VolumeLeft,
frameTop + ( Line * SCREEN_SETUP_BASE_LINE_HEIGHT));
sourceVolumeLabel.SetValue( channel->Setup.InputSource.Volume /
SIGNAL_CHANNEL_INPUT_SIGNAL_PER_VALUE);
sourceVolumeLabel.Display();
Line++;
// Trim
GLOBAL.SetupDisplay.Print_P( menuLeft, frameTop + ( Line * SCREEN_SETUP_BASE_LINE_HEIGHT),
SCREEN_SETUP_BASE_MAIN_FONT, LCD_65K_RGB::C_White,
LCD_65K_RGB::C_Black, LCD::PO_Proportional, Text::Trim);
trimNameLabel.SetDimensions( ValueLeft, frameTop + ( Line * SCREEN_SETUP_BASE_LINE_HEIGHT));
SetSourceLabel( &trimNameLabel, trimName, channel->TrimSignalSourceId);
trimVolumeLabel.SetDimensions( VolumeLeft, frameTop + ( Line * SCREEN_SETUP_BASE_LINE_HEIGHT));
trimVolumeLabel.SetValue( channel->Setup.TrimSource.Volume /
SIGNAL_CHANNEL_INPUT_SIGNAL_PER_VALUE);
trimVolumeLabel.Display();
Line++;
// Limit
GLOBAL.SetupDisplay.Print_P( menuLeft, frameTop + ( Line * SCREEN_SETUP_BASE_LINE_HEIGHT),
SCREEN_SETUP_BASE_MAIN_FONT, LCD_65K_RGB::C_White,
LCD_65K_RGB::C_Black, LCD::PO_Proportional, Text::Limit);
limitNameLabel.SetDimensions( ValueLeft, frameTop + ( Line * SCREEN_SETUP_BASE_LINE_HEIGHT));
SetSourceLabel( &limitNameLabel, limitName, channel->LimitSignalSourceId);
limitVolumeLabel.SetDimensions( VolumeLeft, frameTop + ( Line * SCREEN_SETUP_BASE_LINE_HEIGHT));
limitVolumeLabel.SetValue( channel->Setup.LimitSource.Volume /
SIGNAL_CHANNEL_INPUT_SIGNAL_PER_VALUE);
limitVolumeLabel.Display();
Line += 2;
// Graph
VolumeLeft = menuLeft + ( 16 * Font->CellWidth);
uint16_t ChartLeft = VolumeLeft + 11 * Font->CellWidth;
uint16_t ChartTop = frameTop + ( Line * SCREEN_SETUP_BASE_LINE_HEIGHT);
channelGraph.SetDimensions( ChartLeft, ChartTop,
UTILITY_Minimum( frameHeight - ChartTop, frameWidth - ChartLeft));
for( uint8_t PointId = 0; PointId < Setup_Channel::PV_PointVolumeCount; PointId++)
{
uint16_t LineTop = frameTop + ( Line * SCREEN_SETUP_BASE_LINE_HEIGHT);
const flash_char* LabelText = NULL;
switch( PointId)
{
case 0 : LabelText = Text::Bottom; break;
case 1 : LabelText = Text::Center; break;
case 2 : LabelText = Text::Top; break;
}
GLOBAL.SetupDisplay.PrintFormat_P( menuLeft, LineTop, SCREEN_SETUP_BASE_MAIN_FONT,
LCD_65K_RGB::C_WarmYellow, LCD_65K_RGB::C_Black,
LCD::PO_Proportional, LabelText);
pointVolumeLabel[ PointId].SetDimensions( VolumeLeft, LineTop);
pointVolumeLabel[ PointId].SetValue( channel->Setup.PointVolume[ PointId] /
SIGNAL_CHANNEL_SIGNAL_PER_VALUE);
pointVolumeLabel[ PointId].Display();
Line++;
}
Line++;
// Reverse
GLOBAL.SetupDisplay.Print_P( menuLeft, frameTop + ( Line * SCREEN_SETUP_BASE_LINE_HEIGHT),
SCREEN_SETUP_BASE_MAIN_FONT, LCD_65K_RGB::C_White,
LCD_65K_RGB::C_Black, LCD::PO_Proportional, Text::Reverse);
reverseCheckBox.SetDimensions( ContentLeft,
frameTop + ( Line++ * SCREEN_SETUP_BASE_LINE_HEIGHT),
ContentWidth, SCREEN_SETUP_BASE_GAUGE_THICKNESS);
reverseCheckBox.Clear();
reverseCheckBox.Display( channel->Setup.Reverse);
// Mode
GLOBAL.SetupDisplay.Print_P( menuLeft, frameTop + ( Line * SCREEN_SETUP_BASE_LINE_HEIGHT),
SCREEN_SETUP_BASE_MAIN_FONT, LCD_65K_RGB::C_White,
LCD_65K_RGB::C_Black, LCD::PO_Proportional, Text::Mode);
modeLabel.SetDimensions( ContentLeft, frameTop + ( Line++ * SCREEN_SETUP_BASE_LINE_HEIGHT));
updateMode( &modeLabel, channel->Setup.Mode);
// Result
uint16_t CurrentGaugeLeft = markerLeft;
uint16_t CurrentGaugeWidth = ChartLeft - markerLeft - Font->CellWidth;
currentGauge.SetDimensions( CurrentGaugeLeft,
frameTop + frameHeight - SCREEN_SETUP_BASE_LINE_HEIGHT + 1,
CurrentGaugeWidth, SCREEN_SETUP_BASE_GAUGE_THICKNESS);
}
void Screen_Setup_Channel::update( void)
{
Screen_Setup_Base::update();
int16_t SourceValue = Signal_Utility::GetVolumizedSourceValue(
&( GLOBAL.SignalProcessor), channel->InputSignalSourceId,
SIGNAL_CHANNEL_INPUT_100_PERCENT_VALUE, channel->Setup.InputSource.Volume);
int16_t TrimValue = Signal_Utility::GetVolumizedSourceValue(
&( GLOBAL.SignalProcessor), channel->TrimSignalSourceId,
SIGNAL_CHANNEL_INPUT_0_PERCENT_VALUE, channel->Setup.TrimSource.Volume);
int16_t LimitValue = Signal_Utility::GetVolumizedSourceValue(
&( GLOBAL.SignalProcessor), channel->LimitSignalSourceId,
SIGNAL_CHANNEL_INPUT_100_PERCENT_VALUE, channel->Setup.LimitSource.Volume);
points[ Setup_Channel::PV_Low] = Signal_Utility::VolumizeValue(
channel->Setup.PointVolume[ Setup_Channel::PV_Low], SIGNAL_CHANNEL_100_PERCENT_VALUE,
LimitValue);
points[ Setup_Channel::PV_Center] = Signal_Utility::AddValues(
channel->Setup.PointVolume[ Setup_Channel::PV_Center], TrimValue);
points[ Setup_Channel::PV_High] = Signal_Utility::VolumizeValue(
channel->Setup.PointVolume[ Setup_Channel::PV_High], SIGNAL_CHANNEL_100_PERCENT_VALUE,
LimitValue);
channelGraph.Display( SourceValue, points, Setup_Channel::PV_PointVolumeCount);
currentGauge.Display( SIGNAL_MINIMUM_VALUE, SIGNAL_MAXIMUM_VALUE,
GLOBAL.SignalProcessor.GetChannelValue( channelId));
}
bool Screen_Setup_Channel::processMenu( DoMenuResult Result)
{
switch( Result)
{
case DMR_Selected :
{
bool ValueChanged = false;
switch( currentMenuEntry)
{
case 0 : return( false);
case 2 : doChannelName(); break;
case 4 :
{
ValueChanged =
doSource( &( channel->InputSignalSourceId), &( channel->Setup.InputSource),
sourceName, &sourceNameLabel, &sourceVolumeLabel);
}
break;
case 5 :
{
ValueChanged =
doSource( &( channel->TrimSignalSourceId), &( channel->Setup.TrimSource),
trimName, &trimNameLabel, &trimVolumeLabel);
}
break;
case 6 :
{
ValueChanged =
doSource( &( channel->LimitSignalSourceId), &( channel->Setup.LimitSource),
limitName, &limitNameLabel, &limitVolumeLabel);
}
break;
case 8 :
case 9 :
case 10 :
{
currentPointId = currentMenuEntry - 8;
ValueChanged = GUI_Setup_Select::DoSelect16(
&( channel->Setup.PointVolume[ currentPointId]), SIGNAL_MINIMUM_VALUE,
SIGNAL_MAXIMUM_VALUE, SIGNAL_CHANNEL_SIGNAL_PER_VALUE, &menuMarker,
&( pointVolumeLabel[ currentPointId]), this, &staticUpdate,
&updatePointVolume);
}
break;
case 12 :
{
channel->Setup.Reverse = UTILITY::Invert( channel->Setup.Reverse);
ValueChanged = true;
reverseCheckBox.Display( channel->Setup.Reverse);
}
break;
case 13 :
{
ValueChanged = GUI_Setup_Select::DoSelect(
( int8_t*) &( channel->Setup.Mode), Setup_Channel::M_Warp,
Setup_Channel::M_Clip, 1, &menuMarker, &modeLabel, this, &staticUpdate,
&updateMode);
}
break;
}
// Store new values.
if( ValueChanged == true)
{
GLOBAL.SetupService.SetChannel( channelId, &( channel->Setup));
}
}
break;
default : break;
}
return( true);
}
void Screen_Setup_Channel::doChannelName( void)
{
channelNameValueLabel.Clear();
channelNameInput.ReadText( channelName, sizeof( channelName) - 1);
strncpy( channelName, channelNameInput.GetText(), sizeof( channelName));
channelName[ sizeof( channelName) - 1] = 0;
GLOBAL.SetupService.SetChannelName( channelId, channelName);
channelNameInput.Clear();
channelNameLabel.Display();
channelNameValueLabel.Display();
}
bool Screen_Setup_Channel::doSource( uint8_t* SignalSourceId, Setup_Source_Tupel* SourceTupel,
char SourceName[ SETUP_SOURCE_NAME_SIZE + 1],
GUI_Setup_Label* SourceNameLabel,
GUI_Setup_Label* SourceVolumeLabel)
{
// Do source.
bool SourceChanged = GUI_Setup_Select::DoSourceSelect(
SignalSourceId, &( SourceTupel->Source), &menuMarker, SourceNameLabel, NULL, SourceName,
this, &staticUpdate, true, Signal_Source_Source::L_Model);
// Do volume.
currentVolumeLabel = SourceVolumeLabel;
bool VolumeChanged = GUI_Setup_Select::DoSelect16( &( SourceTupel->Volume),
SIGNAL_MINIMUM_VALUE, SIGNAL_MAXIMUM_VALUE, SIGNAL_CHANNEL_INPUT_SIGNAL_PER_VALUE,
&menuMarker, SourceVolumeLabel, this, &staticUpdate, &updateVolume);
return( SourceChanged || VolumeChanged);
}
void Screen_Setup_Channel::updateVolume( void* Object, GUI_Setup_Label* Label, int16_t Value)
{
// Refresh label.
Label->SetValue( Value / SIGNAL_CHANNEL_INPUT_SIGNAL_PER_VALUE);
Label->Display();
}
void Screen_Setup_Channel::updatePointVolume( void* Object, GUI_Setup_Label* Label, int16_t Value)
{
(( Screen_Setup_Channel*) Object)->updatePointVolume(
(( Screen_Setup_Channel*) Object)->currentPointId, Value);
}
void Screen_Setup_Channel::updatePointVolume( uint8_t CurrentPointId, int16_t Value)
{
GUI_Setup_Label* UseLabel = &( pointVolumeLabel[ CurrentPointId]);
// Refresh label.
UseLabel->SetValue( Value / SIGNAL_CHANNEL_SIGNAL_PER_VALUE);
UseLabel->Display();
}
void Screen_Setup_Channel::updateMode( void* Object, GUI_Setup_Label* Label, int8_t Value)
{
(( Screen_Setup_Channel*) Object)->updateMode( Label, Value);
}
void Screen_Setup_Channel::updateMode( GUI_Setup_Label* Label, int8_t Value)
{
Label->Clear();
switch( Value)
{
case Setup_Channel::M_Warp :
{
Label->SetText_P( Text::Warp);
channelGraph.SetMode( GUI_Setup_Graph::COWM_Warp);
}
break;
case Setup_Channel::M_Clip :
{
Label->SetText_P( Text::Clip);
channelGraph.SetMode( GUI_Setup_Graph::COWM_Clip);
}
break;
}
Label->Display();
}
|
soumith2105/vasv-stdin-backend
|
subjects/urls.py
|
from django.urls import path
from subjects.views import SemesterMarks
urlpatterns = [
path("marks/", SemesterMarks.as_view(), name="semester_marks"),
]
|
achubai/OCE-Apps-Recipes
|
SamplesManagement/SamplesManagement/react/src/screens/DashboardScreen/StorageLocationWidget/utils.js
|
export const normalizeLocation = records =>
records.length ? records[0]['OCE__FullAddress__c'] : '';
|
Livruen/Alapo
|
src/fh/bruch/Bruch.java
|
<reponame>Livruen/Alapo
package fh.bruch;
public class Bruch
{
/**
* vorzeichen == true -> Bruch hat positives Vorzeichen (+)
* vorzeichen == false -> Bruch hat negatives Vorzeichen (-)
*/
private boolean vorzeichen;
private int zaehler, nenner;
public Bruch (boolean vz, int z, int n)
{
this.vorzeichen = vz;
this.zaehler = z;
this.nenner = n;
this.kuerzen();
}
private void kuerzen()
{
int ggt = this.ggt(this.zaehler, this.nenner);
this.zaehler /= ggt;
this.nenner /= ggt;
}
private int ggt(int a, int b)
{
if (a == 0)
return b;
int k = 0;
while (((a % 2) == 0) && ((b % 2) == 0))
{
a = a/2;
b = b/2;
k++;
}
int t;
if (a % 2 == 0)
t = a;
else
t = -b;
while (t != 0)
{
while ((t % 2) == 0)
{
t = t / 2;
}
if (t > 0)
a = t;
else
b = -t;
t = a - b;
}
return a * (1 << k);
}
public boolean getVorzeichen() {
return vorzeichen;
}
public int getZaehler() {
return zaehler;
}
public int getNenner() {
return nenner;
}
public boolean istGleich(Bruch p) {
return this.vorzeichen == p.vorzeichen &&
this.zaehler == p.zaehler &&
this.nenner == p.nenner;
}
public int vergleiche(Bruch p) {
if (this.vorzeichen && !p.vorzeichen) //vorzeichen sind nicht gleich
return 1;
else if (!this.vorzeichen && p.vorzeichen)
return -1;
else if (this.istGleich(p))
return 0;
int kgv = (this.nenner * p.nenner) / this.ggt(this.nenner, p.nenner);
int tz = this.zaehler * kgv / this.nenner;
int pz = p.zaehler * kgv / p.nenner;
if (this.vorzeichen && p.vorzeichen) // beide Br�che positiv
return (tz > pz ? 1 : -1);
else // beide negativ
return (tz > pz ? -1 : 1);
}
public void multipliziere(Bruch b)
{
this.vorzeichen = this.vorzeichen == b.vorzeichen;
this.zaehler *= b.zaehler;
this.nenner *= b.nenner;
this.kuerzen();
}
public void addiere(Bruch p) {
int kgv = (this.nenner * p.nenner) / this.ggt(this.nenner, p.nenner);
int tz = this.zaehler * kgv / this.nenner;
int pz = p.zaehler * kgv / p.nenner;
if (this.vorzeichen == p.vorzeichen)
{
this.zaehler = tz + pz;
this.nenner = kgv;
this.kuerzen();
}
else
{
int neuerZaehler = tz * (this.vorzeichen ? 1 : -1) + pz * (p.vorzeichen ? 1 : -1);
this.vorzeichen = neuerZaehler >= 0;
this.zaehler = neuerZaehler >= 0 ? neuerZaehler : -neuerZaehler;
this.nenner = kgv;
this.kuerzen();
}
}
public void subtrahiere(Bruch p) {
Bruch p2 = new Bruch(!p.vorzeichen, p.zaehler, p.nenner);
this.addiere(p2);
}
public String toString()
{
return ((!this.vorzeichen) ? "-" : "") + this.zaehler + "/" + this.nenner;
}
}
|
ant-nihil/routen-qgroundcontrol
|
libs/qmlglsink/gst-plugins-good/gst/rtpmanager/rtptimerqueue.h
|
<gh_stars>1-10
/* GStreamer RTP Manager
*
* Copyright 2007 Collabora Ltd,
* Copyright 2007 Nokia Corporation
* @author: <NAME> <<EMAIL>>.
* Copyright 2007 <NAME> <<EMAIL>>
* Copyright 2015 Kurento (http://kurento.org/)
* @author: <NAME> <<EMAIL>>
* Copyright 2016 Pexip AS
* @author: <NAME> <<EMAIL>>
* @author: <NAME> <<EMAIL>>
* Copyright (C) 2019 Net Insight AB
* Author: <NAME> <<EMAIL>>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include <gst/gst.h>
#ifndef __RTP_TIMER_QUEUE_H__
#define __RTP_TIMER_QUEUE_H__
#define RTP_TYPE_TIMER_QUEUE rtp_timer_queue_get_type()
G_DECLARE_FINAL_TYPE (RtpTimerQueue, rtp_timer_queue, RTP_TIMER, QUEUE, GObject);
/**
* RtpTimerType:
* @RTP_TIMER_EXPECTED: This is used to track when to emit retranmission
* requests. They may be converted into %RTP_TIMER_LOST
* timer if the number of retry has been exhausted.
* @RTP_TIMER_LOST: This is used to track when a packet is considered lost.
* @RTP_TIMER_DEADLINE: This is used to track when the jitterbuffer should
* start pushing buffers.
* @RTP_TIMER_EOS: This is used to track when end of stream is reached.
*/
typedef enum
{
RTP_TIMER_EXPECTED,
RTP_TIMER_LOST,
RTP_TIMER_DEADLINE,
RTP_TIMER_EOS
} RtpTimerType;
typedef struct
{
GList list;
gboolean queued;
guint16 seqnum;
guint num;
RtpTimerType type;
GstClockTime timeout;
GstClockTimeDiff offset;
GstClockTime duration;
GstClockTime rtx_base;
GstClockTime rtx_delay;
GstClockTime rtx_retry;
GstClockTime rtx_last;
guint num_rtx_retry;
guint num_rtx_received;
} RtpTimer;
void rtp_timer_free (RtpTimer * timer);
RtpTimer * rtp_timer_dup (const RtpTimer * timer);
static inline RtpTimer * rtp_timer_get_next (RtpTimer * timer)
{
GList *list = (GList *) timer;
return (RtpTimer *) list->next;
}
static inline RtpTimer * rtp_timer_get_prev (RtpTimer * timer)
{
GList *list = (GList *) timer;
return (RtpTimer *) list->prev;
}
RtpTimerQueue * rtp_timer_queue_new (void);
RtpTimer * rtp_timer_queue_find (RtpTimerQueue * queue, guint seqnum);
RtpTimer * rtp_timer_queue_peek_earliest (RtpTimerQueue * queue);
gboolean rtp_timer_queue_insert (RtpTimerQueue * queue, RtpTimer * timer);
gboolean rtp_timer_queue_reschedule (RtpTimerQueue * queue, RtpTimer * timer);
void rtp_timer_queue_unschedule (RtpTimerQueue * queue, RtpTimer * timer);
RtpTimer * rtp_timer_queue_pop_until (RtpTimerQueue * queue, GstClockTime timeout);
void rtp_timer_queue_remove_until (RtpTimerQueue * queue, GstClockTime timeout);
void rtp_timer_queue_remove_all (RtpTimerQueue * queue);
void rtp_timer_queue_set_timer (RtpTimerQueue * queue, RtpTimerType type,
guint16 seqnum, guint num, GstClockTime timeout,
GstClockTime delay, GstClockTime duration,
GstClockTimeDiff offset);
void rtp_timer_queue_set_expected (RtpTimerQueue * queue, guint16 seqnum,
GstClockTime timeout, GstClockTime delay,
GstClockTime duration);
void rtp_timer_queue_set_lost (RtpTimerQueue * queue, guint16 seqnum,
guint num, GstClockTime timeout,
GstClockTime duration, GstClockTimeDiff offset);
void rtp_timer_queue_set_eos (RtpTimerQueue * queue, GstClockTime timeout,
GstClockTimeDiff offset);
void rtp_timer_queue_set_deadline (RtpTimerQueue * queue, guint16 seqnum,
GstClockTime timeout, GstClockTimeDiff offset);
void rtp_timer_queue_update_timer (RtpTimerQueue * queue, RtpTimer * timer, guint16 seqnum,
GstClockTime timeout, GstClockTime delay,
GstClockTimeDiff offset, gboolean reset);
guint rtp_timer_queue_length (RtpTimerQueue * queue);
#endif
|
chaitany-raghav/freeCodeCamp
|
tools/contributor/lib/utils/processing-log.js
|
<filename>tools/contributor/lib/utils/processing-log.js
const config = require('../../lib/config');
const formatDate = require('date-fns/format');
const path = require('path');
const fs = require('fs');
const { saveToFile } = require('./save-to-file');
class ProcessingLog {
constructor(script) {
this._script = script;
this._startTime = null;
this._finishTime = null;
this._elapsedTime = null;
this._prs = [];
this._prCount = null;
this._logfile = path.resolve(
__dirname,
`../../work-logs/data-for_${this.getRunType()}_${this._script}.json`
);
}
getRunType() {
return config.oneoff.productionRun ? 'production' : 'test';
}
export() {
const log = {
startTime: this._startTime,
finishTime: this._finishTime,
elapsedTime: this._elapsedTime,
prCount: this._prs.length,
firstPR: this._firstPR,
lastPR: this._lastPR,
prs: this._prs
};
saveToFile(this._logfile, JSON.stringify(log, null, 2));
}
add(prNum, props) {
this._prs.push(props);
}
getPrRange() {
if (this._prs.length) {
const first = this._prs[0].number;
const last = this._prs[this._prs.length - 1].number;
return [first, last];
}
console.log('Current log file does not contain any PRs');
return [null, null];
}
start() {
this._startTime = new Date();
this.export();
}
finish(logFileName = '') {
this._finishTime = new Date();
const minutesElapsed = (this._finishTime - this._startTime) / 1000 / 60;
this._elapsedTime = minutesElapsed.toFixed(2) + ' mins';
let [first, last] = this.getPrRange();
this._firstPR = first;
this._lastPR = last;
this.export();
this.changeFilename(logFileName);
}
changeFilename(logFileName) {
const now = formatDate(new Date(), 'YYYY-MM-DDTHHmmss');
const prRange = `${this._firstPR}-${this._lastPR}`;
let finalFilename = `${this.getRunType()}_${
this._script
}_${prRange}_${now}.json`;
let newFilename = path.resolve(
__dirname,
`../../work-logs/${finalFilename}`
);
if (logFileName) {
newFilename = logFileName;
}
fs.renameSync(this._logfile, newFilename);
if (!fs.existsSync(newFilename)) {
throw 'File rename unsuccessful.';
}
this._logfile = newFilename;
}
}
module.exports = { ProcessingLog };
|
sedstrom/Witch-Android
|
witch-processor/src/main/java/se/snylt/witch/processor/SupportedAnnotations.java
|
package se.snylt.witch.processor;
import java.lang.annotation.Annotation;
import javax.lang.model.element.Element;
class SupportedAnnotations {
interface HasViewId {
Integer getViewId(Element element);
Class<? extends Annotation> getClazz();
}
// BindTargetMethod
public final static class BindData implements HasViewId {
final static String name = "se.snylt.witch.annotations.BindTargetMethod";
@Override
public Integer getViewId(Element element) {
return element.getAnnotation(se.snylt.witch.annotations.BindData.class).id();
}
@Override
public Class<? extends Annotation> getClazz() {
return se.snylt.witch.annotations.BindData.class;
}
@Override
public String toString() {
return name;
}
}
// Bind
final static class Bind implements HasViewId {
final static String name = "se.snylt.witch.annotations.Bind";
@Override
public Integer getViewId(Element element) {
return element.getAnnotation(se.snylt.witch.annotations.Bind.class).id();
}
@Override
public Class<? extends Annotation> getClazz() {
return se.snylt.witch.annotations.Bind.class;
}
}
// Setup
final static class Setup implements HasViewId {
final static String name = "se.snylt.witch.annotations.Setup";
@Override
public Integer getViewId(Element element) {
return element.getAnnotation(se.snylt.witch.annotations.Setup.class).id();
}
@Override
public Class<? extends Annotation> getClazz() {
return se.snylt.witch.annotations.Setup.class;
}
}
// Data
final static class Data {
final static String name = "se.snylt.witch.annotations.Data";
}
// BindWhen
final static class BindWhen {
final static String name = "se.snylt.witch.annotations.BindWhen";
}
// BindNull
final static class BindNull {
final static String name = "se.snylt.witch.annotations.BindNull";
}
// All annotations that bind to a view id
final static HasViewId[] HAS_VIEW_IDS = new HasViewId[] {
new Setup(),
new BindData(),
new Bind(),
};
}
|
kaysiz/kwambombo
|
db/migrate/20191002194948_create_payments.rb
|
class CreatePayments < ActiveRecord::Migration[5.2]
def change
create_table :payments do |t|
t.references :clean_requests, foreign_key: true, type: :uuid
t.string :reference_id
t.string :amount
t.string :payment_menthod
t.string :pay_request_id
t.string :status
t.timestamps
end
end
end
|
govindrgaikwad/java_repo
|
WideStringer/src/main/java/com/wide/stringer/generator/repository/GenericRepository.java
|
package com.wide.stringer.generator.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import com.wide.stringer.generator.entity.Attribute;
import com.wide.stringer.generator.entity.DataType;
import com.wide.stringer.generator.entity.Embaddable;
import com.wide.stringer.generator.entity.Method;
import com.wide.stringer.generator.entity.MethodParameter;
import com.wide.stringer.generator.entity.ObjectDefination;
import com.wide.stringer.generator.entity.Relationship;
public interface GenericRepository extends
JpaRepository<ObjectDefination, Long>, GenericCustomRepository {
// ********** Attribute Methods***********//
@Query(value = "SELECT list from Attribute list")
public List<Attribute> findAllAttribute();
@Query(value = "SELECT list from Attribute list"
+ " where list.attributeId = :id ")
public Attribute findAttributeById(@Param("id") Integer attributeId);
@Query(value = "SELECT list from Attribute list"
+ " left join fetch list.objectDefination"
+ " where list.objectDefination.objectId = :id ", countQuery = "SELECT count(list) from Attribute list"
+ " where list.objectDefination.objectId = :id ")
public List<Attribute> findAttributeByObjectId(@Param("id") Integer objectId);
@Query(value = "SELECT list from Attribute list"
+ " left join fetch list.referenceObjectDefination"
+ " where list.referenceObjectDefination.objectId = :id ", countQuery = "SELECT count(list) from Attribute list"
+ " where list.referenceObjectDefination.objectId = :id ")
public List<Attribute> findAttributeByReferenceObjectId(
@Param("id") Integer objectId);
@Query(value = "SELECT list from Attribute list"
+ " where list.name = :id ", countQuery = "SELECT count(list) from Attribute list"
+ " where list.name = :id ")
public List<Attribute> findAttributeByName(@Param("id") String name);
@Query(value = "SELECT list from Attribute list"
+ " where list.userDefinedName = :id ", countQuery = "SELECT count(list) from Attribute list"
+ " where list.userDefinedName = :id ")
public List<Attribute> findAttributeByUserDefinedName(
@Param("id") String userDefinedName);
@Query(value = "SELECT list from Attribute list"
+ " where list.camelCaseName = :id ", countQuery = "SELECT count(list) from Attribute list"
+ " where list.camelCaseName = :id ")
public List<Attribute> findAttributeByCamelCaseName(
@Param("id") String camelCaseName);
@Query(value = "SELECT list from Attribute list"
+ " where list.datatype = :id ", countQuery = "SELECT count(list) from Attribute list"
+ " where list.datatype = :id ")
public List<Attribute> findAttributeByDatatype(@Param("id") String datatype);
@Query(value = "SELECT list from Attribute list"
+ " where list.javaDataType = :id ", countQuery = "SELECT count(list) from Attribute list"
+ " where list.javaDataType = :id ")
public List<Attribute> findAttributeByJavaDataType(
@Param("id") String javaDataType);
@Query(value = "SELECT list from Attribute list"
+ " where list.primaryKey = :id ", countQuery = "SELECT count(list) from Attribute list"
+ " where list.primaryKey = :id ")
public List<Attribute> findAttributeByPrimaryKey(
@Param("id") Boolean primaryKey);
@Query(value = "SELECT list from Attribute list"
+ " where list.foreignKey = :id ", countQuery = "SELECT count(list) from Attribute list"
+ " where list.foreignKey = :id ")
public List<Attribute> findAttributeByForeignKey(
@Param("id") Boolean foreignKey);
@Query(value = "SELECT list from Attribute list"
+ " where list.embaddable = :id ", countQuery = "SELECT count(list) from Attribute list"
+ " where list.embaddable = :id ")
public List<Attribute> findAttributeByEmbaddable(
@Param("id") Boolean embaddable);
@Query(value = "SELECT list from Attribute list"
+ " left join fetch list.objectDefination"
+ " where list.name = :name and list.objectDefination.objectId = :id ")
public Attribute findAttributeByNameAndObjectId(@Param("name") String name,
@Param("id") Integer objectId);
// **********************************End***************************************//
// ******************** DataType Methods *********************************//
@Query(value = "SELECT list from DataType list")
public List<DataType> findAllDataType();
@Query(value = "SELECT list from DataType list"
+ " where list.dataTypeId = :id ")
public DataType findDataTypeById(@Param("id") Integer dataTypeId);
@Query(value = "SELECT list from DataType list"
+ " where list.constantValue = :id ", countQuery = "SELECT count(list) from DataType list"
+ " where list.constantValue = :id ")
public DataType findDataTypeByConstantValue(
@Param("id") Integer constantValue);
@Query(value = "SELECT list from DataType list"
+ " where list.sQLType = :id ", countQuery = "SELECT count(list) from DataType list"
+ " where list.sQLType = :id ")
public List<DataType> findDataTypeBySQLType(@Param("id") String sQLType);
@Query(value = "SELECT list from DataType list"
+ " where list.javaType = :id ", countQuery = "SELECT count(list) from DataType list"
+ " where list.javaType = :id ")
public List<DataType> findDataTypeByJavaType(@Param("id") String javaType);
// **********************************End***************************************//
// ******************** Embaddable Methods****************************//
@Query(value = "SELECT list from Embaddable list")
public List<Embaddable> findAllEmbaddable();
@Query(value = "SELECT list from Embaddable list"
+ " where list.embaddableId = :id ")
public Embaddable findEmbaddableById(@Param("id") Integer embaddableId);
@Query(value = "SELECT list from Embaddable list"
+ " left join fetch list.objectDefination"
+ " where list.objectDefination.objectId = :id ")
public Embaddable findEmbaddableByObjectId(@Param("id") Integer objectId);
@Query(value = "SELECT list from Embaddable list"
+ " where list.name = :id ", countQuery = "SELECT count(list) from Embaddable list"
+ " where list.name = :id ")
public List<Embaddable> findEmbaddableByName(@Param("id") String name);
@Query(value = "SELECT list from Embaddable list"
+ " where list.camelCaseName = :id ", countQuery = "SELECT count(list) from Embaddable list"
+ " where list.camelCaseName = :id ")
public List<Embaddable> findEmbaddableByCamelCaseName(
@Param("id") String camelCaseName);
// **********************************End***************************************//
// ******************** Method Methods *********************************//
@Query(value = "SELECT list from Method list")
public List<Method> findAllMethod();
@Query(value = "SELECT list from Method list"
+ " where list.methodId = :id ")
public Method findMethodById(@Param("id") Integer methodId);
@Query(value = "SELECT list from Method list"
+ " left join fetch list.objectDefination"
+ " where list.objectDefination.objectId = :id ", countQuery = "SELECT count(list) from Method list"
+ " where list.objectDefination.objectId = :id ")
public List<Method> findMethodByObjectId(@Param("id") Integer objectId);
@Query(value = "SELECT list from Method list" + " where list.name = :id ", countQuery = "SELECT count(list) from Method list"
+ " where list.name = :id ")
public List<Method> findMethodByName(@Param("id") String name);
@Query(value = "SELECT list from Method list"
+ " where list.camelCaseName = :id ", countQuery = "SELECT count(list) from Method list"
+ " where list.camelCaseName = :id ")
public List<Method> findMethodByCamelCaseName(
@Param("id") String camelCaseName);
@Query(value = "SELECT list from Method list"
+ " where list.accessSpecifier = :id ", countQuery = "SELECT count(list) from Method list"
+ " where list.accessSpecifier = :id ")
public List<Method> findMethodByAccessSpecifier(
@Param("id") String accessSpecifier);
@Query(value = "SELECT list from Method list"
+ " where list.returnType = :id ", countQuery = "SELECT count(list) from Method list"
+ " where list.returnType = :id ")
public List<Method> findMethodByReturnType(@Param("id") String returnType);
@Query(value = "SELECT list from Method list"
+ " where list.methodType = :id ", countQuery = "SELECT count(list) from Method list"
+ " where list.methodType = :id ")
public List<Method> findMethodByMethodType(@Param("id") String methodType);
@Query(value = "SELECT list from Method list"
+ " where list.soapOperationName = :id ", countQuery = "SELECT count(list) from Method list"
+ " where list.soapOperationName = :id ")
public List<Method> findMethodBySoapOperationName(
@Param("id") String soapOperationName);
@Query(value = "SELECT list from Method list"
+ " where list.soapAction = :id ", countQuery = "SELECT count(list) from Method list"
+ " where list.soapAction = :id ")
public List<Method> findMethodBySoapAction(@Param("id") String soapAction);
@Query(value = "SELECT list from Method list"
+ " where list.exceptions = :id ", countQuery = "SELECT count(list) from Method list"
+ " where list.exceptions = :id ")
public List<Method> findMethodByExceptions(@Param("id") String exceptions);
// **********************************End***************************************//
// ******************** MethodParameter Methods************************//
@Query(value = "SELECT list from MethodParameter list")
public List<MethodParameter> findAllMethodParameter();
@Query(value = "SELECT list from MethodParameter list"
+ " where list.id = :id ")
public MethodParameter findMethodParameterById(@Param("id") Integer id);
@Query(value = "SELECT list from MethodParameter list"
+ " left join fetch list.method"
+ " where list.method.methodId = :id ", countQuery = "SELECT count(list) from MethodParameter list"
+ " where list.method.methodId = :id ")
public List<MethodParameter> findMethodParameterByMethodId(
@Param("id") Integer methodId);
@Query(value = "SELECT list from MethodParameter list"
+ " left join fetch list.attribute"
+ " where list.attribute.attributeId = :id ", countQuery = "SELECT count(list) from MethodParameter list"
+ " where list.attribute.attributeId = :id ")
public List<MethodParameter> findMethodParameterByAttributeId(
@Param("id") Integer attributeId);
// **********************************End***************************************//
// ******************** ObjectDefination Methods**********************//
@Query(value = "SELECT list from ObjectDefination list")
public List<ObjectDefination> findAllObjectDefination();
@Query(value = "SELECT list from ObjectDefination list"
+ " where list.objectId = :id ")
public ObjectDefination findObjectDefinationById(
@Param("id") Integer objectId);
@Query(value = "SELECT list from ObjectDefination list"
+ " where list.name = :id ", countQuery = "SELECT count(list) from ObjectDefination list"
+ " where list.name = :id ")
public ObjectDefination findObjectDefinationByName(@Param("id") String name);
@Query(value = "SELECT list from ObjectDefination list"
+ " where list.schemaName = :id ", countQuery = "SELECT count(list) from ObjectDefination list"
+ " where list.schemaName = :id ")
public List<ObjectDefination> findObjectDefinationBySchemaName(
@Param("id") String schemaName);
@Query(value = "SELECT list from ObjectDefination list"
+ " where list.dataBaseName = :id ", countQuery = "SELECT count(list) from ObjectDefination list"
+ " where list.dataBaseName = :id ")
public List<ObjectDefination> findObjectDefinationByDataBaseName(
@Param("id") String dataBaseName);
@Query(value = "SELECT list from ObjectDefination list"
+ " where list.userDefinedName = :id ", countQuery = "SELECT count(list) from ObjectDefination list"
+ " where list.userDefinedName = :id ")
public List<ObjectDefination> findObjectDefinationByUserDefinedName(
@Param("id") String userDefinedName);
@Query(value = "SELECT list from ObjectDefination list"
+ " where list.camelCaseName = :id ", countQuery = "SELECT count(list) from ObjectDefination list"
+ " where list.camelCaseName = :id ")
public List<ObjectDefination> findObjectDefinationByCamelCaseName(
@Param("id") String camelCaseName);
@Query(value = "SELECT list from ObjectDefination list"
+ " where list.embaddable = :id ", countQuery = "SELECT count(list) from ObjectDefination list"
+ " where list.embaddable = :id ")
public List<ObjectDefination> findObjectDefinationByEmbaddable(
@Param("id") Boolean embaddable);
@Query(value = "SELECT list from ObjectDefination list"
+ " where list.updated = :id ", countQuery = "SELECT count(list) from ObjectDefination list"
+ " where list.updated = :id ")
public List<ObjectDefination> findObjectDefinationByUpdated(
@Param("id") Boolean updated);
@Query(value = "SELECT list from ObjectDefination list"
+ " where list.primaryKey = :id ", countQuery = "SELECT count(list) from ObjectDefination list"
+ " where list.primaryKey = :id ")
public List<ObjectDefination> findObjectDefinationByprimaryKey(
@Param("id") Boolean primaryKey);
// **********************************End***************************************//
// ******************** Relationship Methods***********************//
@Query(value = "SELECT list from Relationship list")
public List<Relationship> findAllRelationship();
@Query(value = "SELECT list from Relationship list"
+ " where list.relationshipId = :id ")
public Relationship findRelationshipById(@Param("id") Integer relationshipId);
@Query(value = "SELECT list from Relationship list"
+ " left join fetch list.parentObjectDefination"
+ " where list.parentObjectDefination.objectId = :id ", countQuery = "SELECT count(list) from Relationship list"
+ " where list.parentObjectDefination.objectId = :id ")
public List<Relationship> findRelationshipByParentObjectId(
@Param("id") Integer objectId);
@Query(value = "SELECT list from Relationship list"
+ " left join fetch list.relatedObjectDefination"
+ " where list.relatedObjectDefination.objectId = :id ", countQuery = "SELECT count(list) from Relationship list"
+ " where list.relatedObjectDefination.objectId = :id ")
public List<Relationship> findRelationshipByRelatedObjectId(
@Param("id") Integer objectId);
@Query(value = "SELECT list from Relationship list"
+ " left join fetch list.parentAttribute"
+ " where list.parentAttribute.attributeId = :id ", countQuery = "SELECT count(list) from Relationship list"
+ " where list.parentAttribute.attributeId = :id ")
public List<Relationship> findRelationshipByParentAttributeId(
@Param("id") Integer attributeId);
@Query(value = "SELECT list from Relationship list"
+ " left join fetch list.childAttribute"
+ " where list.childAttribute.attributeId = :id ", countQuery = "SELECT count(list) from Relationship list"
+ " where list.childAttribute.attributeId = :id ")
public List<Relationship> findRelationshipByChildAttributeId(
@Param("id") Integer attributeId);
@Query(value = "SELECT list from Relationship list"
+ " where list.relationName = :id ", countQuery = "SELECT count(list) from Relationship list"
+ " where list.relationName = :id ")
public List<Relationship> findRelationshipByRelationName(
@Param("id") String relationName);
@Query(value = "SELECT list from Relationship list"
+ " where list.camelcaseName = :id ", countQuery = "SELECT count(list) from Relationship list"
+ " where list.camelcaseName = :id ")
public List<Relationship> findRelationshipByCamelcaseName(
@Param("id") String camelcaseName);
@Query(value = "SELECT list from Relationship list"
+ " where list.cardinality = :id ", countQuery = "SELECT count(list) from Relationship list"
+ " where list.cardinality = :id ")
public List<Relationship> findRelationshipByCardinality(
@Param("id") String cardinality);
// **********************************End***************************************//
}
|
ZzzYtl/gin-vue-admin
|
server/model/xdf_sentinel_info.go
|
// 自动生成模板SentinelInfo
package model
// 如果含有time.Time 请自行import time包
type SentinelInfo struct {
SentinelID int `json:"sentinel_id" form:"sentinel_id" gorm:"primarykey; AUTO_INCREMENT; column:sentinel_id;comment:"`
RunID string `json:"run_id" form:"run_id" gorm:"column:run_id;comment:;type:char(30);size:30;"`
SentinelClusterID int `json:"sentinel_cluster_id" form:"sentinel_cluster_id" gorm:"column:sentinel_cluster_id;comment:"`
IP string `json:"ip" form:"ip" gorm:"column:ip;comment:;type:char(15);size:15;"`
Port int `json:"port" form:"port" gorm:"column:port;comment:"`
CurrentEpoch int `json:"current_epoch" form:"current_epoch" gorm:"column:current_epoch;comment:"`
ConfigEpoch int `json:"config_epoch" form:"config_epoch" gorm:"column:config_epoch;comment:"`
OnLine bool `json:"online" form:"online" gorm:"-"`
}
func (SentinelInfo) TableName() string {
return "sentinel_info"
}
// 如果使用工作流功能 需要打开下方注释 并到initialize的workflow中进行注册 且必须指定TableName
// type SentinelInfoWorkflow struct {
// // 工作流操作结构体
// WorkflowBase `json:"wf"`
// SentinelInfo `json:"business"`
// }
// func (SentinelInfo) TableName() string {
// return "sentinel_info"
// }
// 工作流注册代码
// initWorkflowModel内部注册
// model.WorkflowBusinessStruct["sentinelinfo"] = func() model.GVA_Workflow {
// return new(model.SentinelInfoWorkflow)
// }
// initWorkflowTable内部注册
// model.WorkflowBusinessTable["sentinelinfo"] = func() interface{} {
// return new(model.SentinelInfo)
// }
|
realtehcman/-UnderwaterSceneProject
|
dependencies/physx-4.1/source/geomutils/src/GuCapsule.h
|
version https://git-lfs.github.com/spec/v1
oid sha256:e1967a7aef650f65a64bd60c56f8dbd4a1aca91a3732f669e63d899e84be347b
size 2573
|
MemoryNetworks/memnets
|
fx/src/main/scala/memnets/fx/app/SideBarFX.scala
|
package memnets.fx.app
import java.text.DecimalFormat
import javafx.fxml.FXMLLoader
import memnets.fx._
import memnets.fx.fx3d.Scene3DFX
import memnets.fx.utils.ActionP
import memnets.fx.utils.TableColumnUtils.ColumnBuilder
import memnets.ml.DataSource
import memnets.model._
import memnets.ui._
import memnets.utils._
import scalafx.Includes._
import scalafx.scene.control._
import scalafx.scene.control.cell.TextFieldTableCell
import scalafx.scene.layout._
import scalafx.scene.text.Text
import scalafx.util.converter.NumberStringConverter
class SideBarFX(modelFX: ModelFX, engineFX: EngineFXAdapter) extends Logging {
import javafx.scene.{control => cfx}
val engine = engineFX.engine
val formatter: FastFormatter = TwoDigits
val loader = new FXMLLoader("sidebar.fxml".asURL)
val fx = new BorderPane(loader.load())
val showPane = new StackPane(fx.findById("showPane"))
val showBtn = new ToggleButton(fx.findById[JToggleButton]("showBtn"))
val focusText = new Text(fx.findTextById("focusText"))
val toolBar = new ToolBar(fx.findById("toolBar"))
val libBar = new ToolBar(fx.findById("libBar"))
val libSepName = "libSep"
val speed = new Label(fx.findById[JLabel]("speedLbl"))
val tabPane = new TabPane(fx.findById("tabPane"))
tabPane.setStyle("-fx-box-border: transparent;")
// retrieve by id not working
val trialTab = tabPane.tabs.get(0)
val paramTab = tabPane.tabs.get(1)
val skinTab = tabPane.tabs.get(2)
val configTab = tabPane.tabs.get(3)
val env3dTab = tabPane.tabs.get(4)
val dataTab = tabPane.tabs.get(5)
trialTab.tooltip = "trials/levels for model/game"
paramTab.tooltip = "adjustable parameters for model"
skinTab.tooltip = "visualizations for model. need to press 'Refresh skin' after editing"
configTab.tooltip = "configuration options. need to press 'Rebuild' after editing"
dataTab.tooltip = "available data sets. only used by certain models"
env3dTab.tooltip = "lighting and materials editor for 3D scenes"
speed.text.value = ""
// unlike selection/disable properties, modifying text always has to be on FX thread.
engineFX.speedText.onChange { (_, _, text) =>
runLaterP {
speed.text.value = text
}
}
val paramEditor = new ParamEditorFX(engineFX)
paramTab.setContent(paramEditor.rootPane)
val trialTable = new TableView(fx.findById[cfx.TableView[Trial]]("trialTable"))
val trialCb = new ColumnBuilder[Trial](trialTable)
trialCb.pS("Description", editable = false)
trialCb.pS("Time", editable = false, prop = "timeText")
trialCb.pI("#Ins", editable = false, prop = "inputCount")
engineFX.trialsModel.bind(trialTable)
for ((col, i) <- trialTable.columns.zipWithIndex) {
col.prefWidthProperty.unbind()
// 300 total 320-180=120/2=70
col.prefWidthProperty.value = if (i == 0) 175 else 60
}
// trialTable.setColumnResizePolicy(TableView.ConstrainedResizePolicy)
// trialTab.setContent(trialTable)
val skinEditor = new SkinEditorFX
val skinCb = new ColumnBuilder[SkinType](skinEditor.skinTable)
skinCb.pS("Name", editable = false)
skinCb.pS("ColorMap", editable = false, prop = "ColorMapName")
engineFX.skinsModel.bind(skinEditor.skinTable)
skinTab.setContent(skinEditor.fx)
val configEditor = new ConfigEditorFX
configTab.setContent(configEditor.fx)
/* can't use. listen to SkinInitializedEvent in AppBaseFX instead
engineFX.skinsModel.selectedItemProperty ==> { newSkin =>
runLaterP {
skinEditor.setSkin(newSkin)
}
}
*/
val sceneEditor = new Scene3DEditorFX
env3dTab.setContent(sceneEditor.fx)
val inputTable = new TableView(fx.findById[cfx.TableView[Signal]]("inputTable"))
inputTable.setEditable(true)
val inputCb = new ColumnBuilder[Signal](inputTable)
inputCb.pB("Use", prop = "active")
inputCb.pS("Target", editable = false)
inputCb.pI("On")
inputCb.pD("Scale")
inputCb.pD("Period")
engineFX.inputModel.bind(inputTable)
for ((col, i) <- inputTable.columns.zipWithIndex) {
col.prefWidthProperty.unbind()
col.prefWidthProperty.value = i match {
case 0 => 35
case 1 => 95
case 2 => 50
case 3 => 50
case 4 => 75
}
}
val dataTable = new TableView[DataSource]()
dataTable.setEditable(true)
dataTab.setContent(dataTable)
val dataCb = new ColumnBuilder[DataSource](dataTable)
dataCb.pS("Info", editable = false, prop = "desc")
dataCb.pI("Feat", prop = "features")
// dataCb pI("Size", prop = "size", converter = new NumberStringConverter(new DecimalFormat("0.##E0")))
val sizeCol = dataCb.pI("Size", prop = "size")
sizeCol.cellFactory = (c: TableColumn[DataSource, Number]) =>
new TextFieldTableCell[DataSource, Number](new NumberStringConverter(new DecimalFormat("0.##E0")))
dataCb.pD("Prob", prop = "probability")
import memnets.ml.DataSources.dataSourcesModel
logger.trace("datasources size = " + dataSourcesModel.getItemCount)
engineFX.dataSourcesModel.bind(dataTable)
for (col <- dataTable.columns) col.prefWidthProperty.unbind()
dataTable.columns(0).setPrefWidth(155)
dataTable.columns(1).setPrefWidth(36)
dataTable.columns(2).setPrefWidth(60)
dataTable.columns(3).setPrefWidth(40)
def bindActions(): Unit = {
ActionP.lookupActions(loader)
}
def hide(): Unit = {
showBtn.selected.value = false
}
def resize(w: Double, h: Double): Unit = {
val scale = if (h >= 720) h / 720.0 else 1.0
showPane.prefHeight.value = ModelFX.HEADER_H * scale
}
def setSkin(skin: SkinType) = {
skinEditor.setSkin(skin)
syncSceneEditor()
}
def syncSceneEditor() = {
logger.debug("syncSceneEditor")
var opt: Option[Scene3DFX] = None
for (sc3d <- modelFX.tickables.find(x => x.element.isInstanceOf[Scene3D] || x.isInstanceOf[ContainerFX])) {
logger.debug("found scene3D")
val fx: Scene3DFX = sc3d match {
case cfx: ContainerFX if cfx.tfx.isInstanceOf[Scene3DFX] =>
cfx.tfx.asInstanceOf[Scene3DFX]
case sfx: Scene3DFX =>
sfx
case default =>
null
}
opt = Option(fx)
}
env3dTab.disable = opt.isEmpty
sceneEditor.setScene(opt)
}
def tick(te: Tick): Unit = {
if (showBtn.delegate.isSelected) {
val y = modelFX.selectedY.value
if (y != null) {
if (te.t % 3 == 0)
focusText.text = y.name + ": " + formatter.format(y.act)
} else
focusText.text = "" // will not retrigger if the same
}
}
}
|
onesmash/NIM_Android_UIKit
|
src/com/netease/nim/uikit/common/adapter/HybridAdapter.java
|
<filename>src/com/netease/nim/uikit/common/adapter/HybridAdapter.java
package com.netease.nim.uikit.common.adapter;
import android.view.View;
import android.view.ViewGroup;
public class HybridAdapter extends BaseAdapter {
private final Hybrid[] hybrids;
public static abstract class Hybrid<T> {
protected static final int VIEW_TYPE_INVALID = -1;
private OnItemClickListener listener;
private boolean disabled;
public Hybrid() {
this(null);
}
public Hybrid(OnItemClickListener listener) {
this.listener = listener;
}
public abstract DataFreeViewHolder<T> onCreateViewHolder(ViewGroup parent, int viewType);
public abstract void onBindViewHolder(DataFreeViewHolder<T> holder, int position);
public abstract int getItemCount();
public abstract int getItemViewType(int position);
public abstract T getData(int position);
protected void bindViewHolder(DataFreeViewHolder<T> holder, T data) {
holder.bindViewHolder(data);
}
public boolean isEmpty() {
return getItemCount() == 0;
}
public final void setOnItemClickListener(OnItemClickListener onItemClickListener) {
this.listener = onItemClickListener;
}
public final void enable(boolean enable) {
this.disabled = !enable;
}
private void handleClick(boolean longClick, View v, int pos, Object data) {
if (listener == null) {
return;
}
if (longClick) {
listener.onLongClick(v, pos, data);
} else {
listener.onClick(v, pos, data);
}
}
}
protected static Hybrid[] make(Hybrid main, Hybrid[] before, Hybrid[] after) {
int count = 1 + (before != null ? before.length : 0) + (after != null ? after.length : 0);
Hybrid[] hybrids = new Hybrid[count];
int index = 0;
if (before != null) {
System.arraycopy(before, 0, hybrids, 0, before.length);
index += before.length;
}
hybrids[index++] = main;
if (after != null) {
System.arraycopy(after, 0, hybrids, index, after.length);
}
return hybrids;
}
public HybridAdapter(final Hybrid... hybrids) {
super(null);
super.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onClick(View v, int pos, Object data) {
handleClick(false, v, pos, data);
}
@Override
public boolean onLongClick(View v, int pos, Object data) {
handleClick(true, v, pos, data);
return false;
}
});
this.hybrids = hybrids;
setDelegate(new BaseDelegate() {
@Override
public BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
int index = viewType >> 16;
viewType = viewType & 0xffff;
if (index < 0 || index >= hybrids.length) {
return null;
}
Hybrid hybrid = hybrids[index];
return hybrid.onCreateViewHolder(parent, viewType);
}
@Override
public int getItemViewType(Object data, int pos) {
return 0;
}
});
}
@Override
public final void setOnItemClickListener(OnItemClickListener onItemClickListener) {
// disable
}
@Override
public void onBindViewHolder(BaseViewHolder holder, int position) {
for (Hybrid hybrid : hybrids) {
if (hybrid.disabled) {
continue;
}
int count = hybrid.getItemCount();
if (position < count) {
hybrid.onBindViewHolder((DataFreeViewHolder) holder, position);
listenClick(holder);
return;
}
position -= count;
}
super.onBindViewHolder(holder, position);
}
@Override
public final int getItemCount() {
int count = 0;
for (Hybrid hybrid : hybrids) {
if (hybrid.disabled) {
continue;
}
count += hybrid.getItemCount();
}
return count;
}
@Override
public final int getItemViewType(int position) {
for (int i = 0; i < hybrids.length; i++) {
Hybrid hybrid = hybrids[i];
if (hybrid.disabled) {
continue;
}
int count = hybrid.getItemCount();
if (position < count) {
return i << 16 | hybrid.getItemViewType(position) & 0xffff;
}
position -= count;
}
return Hybrid.VIEW_TYPE_INVALID;
}
@Override
protected final Object getData(int position) {
for (Hybrid hybrid : hybrids) {
if (hybrid.disabled) {
continue;
}
int count = hybrid.getItemCount();
if (position < count) {
return hybrid.getData(position);
}
position -= count;
}
return null;
}
protected final int getHybridOffset(Hybrid h) {
int count = 0;
for (Hybrid hybrid : hybrids) {
if (hybrid.disabled) {
continue;
}
if (hybrid == h) {
return count;
}
count += hybrid.getItemCount();
}
return -1;
}
private void handleClick(boolean longClick, View v, int pos, Object data) {
for (Hybrid hybrid : hybrids) {
if (hybrid.disabled) {
continue;
}
int count = hybrid.getItemCount();
if (pos < count) {
hybrid.handleClick(longClick, v, pos, data);
return;
}
pos -= count;
}
}
}
|
DeloitteDigitalAT/pluralsight
|
securing-java-web-applications/terracotta-bank/src/main/java/com/joshcummings/codeplay/terracotta/service/ServiceSupport.java
|
package com.joshcummings.codeplay.terracotta.service;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.Set;
import java.util.function.Function;
public abstract class ServiceSupport {
private static final String DATABASE_URL = "jdbc:hsqldb:mem:db";
public <T> Set<T> runQuery(String query, Function<ResultSet, T> inflater) {
return runQuery(query, ps -> ps, inflater);
}
public <T> Set<T> runQuery(String query, Preparer preparer, Function<ResultSet, T> inflater) {
Set<T> results = new HashSet<T>();
try ( Connection conn = DriverManager.getConnection(DATABASE_URL);
PreparedStatement ps = conn.prepareStatement(query);
ResultSet rs = preparer.prepare(ps).executeQuery(); ) {
while ( rs.next() ) {
results.add(inflater.apply(rs));
}
} catch ( SQLException e ) {
throw new IllegalArgumentException(e);
}
return results;
}
public void runUpdate(String query) {
try ( Connection conn = DriverManager.getConnection(DATABASE_URL);
PreparedStatement ps = conn.prepareStatement(query); ){
ps.executeUpdate();
} catch ( SQLException e ) {
throw new IllegalArgumentException(e);
}
}
@FunctionalInterface
public interface Preparer {
PreparedStatement prepare(PreparedStatement ps) throws SQLException;
}
}
|
zwollerob/PhantomJS_AMR6VL
|
src/qt/qtbase/src/widgets/util/qflickgesture.cpp
|
/****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the QtWidgets module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** As a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qgesture.h"
#include "qapplication.h"
#include "qevent.h"
#include "qwidget.h"
#include "qgraphicsitem.h"
#include "qgraphicsscene.h"
#include "qgraphicssceneevent.h"
#include "qgraphicsview.h"
#include "qscroller.h"
#include "private/qapplication_p.h"
#include "private/qevent_p.h"
#include "private/qflickgesture_p.h"
#include "qdebug.h"
#ifndef QT_NO_GESTURES
QT_BEGIN_NAMESPACE
//#define QFLICKGESTURE_DEBUG
#ifdef QFLICKGESTURE_DEBUG
# define qFGDebug qDebug
#else
# define qFGDebug while (false) qDebug
#endif
extern bool qt_sendSpontaneousEvent(QObject *receiver, QEvent *event);
static QMouseEvent *copyMouseEvent(QEvent *e)
{
switch (e->type()) {
case QEvent::MouseButtonPress:
case QEvent::MouseButtonRelease:
case QEvent::MouseMove: {
QMouseEvent *me = static_cast<QMouseEvent *>(e);
QMouseEvent *cme = new QMouseEvent(me->type(), QPoint(0, 0), me->windowPos(), me->screenPos(), me->button(), me->buttons(), me->modifiers());
QGuiApplicationPrivate::setMouseEventSource(cme, me->source());
return cme;
}
#ifndef QT_NO_GRAPHICSVIEW
case QEvent::GraphicsSceneMousePress:
case QEvent::GraphicsSceneMouseRelease:
case QEvent::GraphicsSceneMouseMove: {
QGraphicsSceneMouseEvent *me = static_cast<QGraphicsSceneMouseEvent *>(e);
#if 1
QEvent::Type met = me->type() == QEvent::GraphicsSceneMousePress ? QEvent::MouseButtonPress :
(me->type() == QEvent::GraphicsSceneMouseRelease ? QEvent::MouseButtonRelease : QEvent::MouseMove);
QMouseEvent *cme = new QMouseEvent(met, QPoint(0, 0), QPoint(0, 0), me->screenPos(), me->button(), me->buttons(), me->modifiers());
QGuiApplicationPrivate::setMouseEventSource(cme, me->source());
return cme;
#else
QGraphicsSceneMouseEvent *copy = new QGraphicsSceneMouseEvent(me->type());
copy->setPos(me->pos());
copy->setScenePos(me->scenePos());
copy->setScreenPos(me->screenPos());
for (int i = 0x1; i <= 0x10; i <<= 1) {
Qt::MouseButton button = Qt::MouseButton(i);
copy->setButtonDownPos(button, me->buttonDownPos(button));
copy->setButtonDownScenePos(button, me->buttonDownScenePos(button));
copy->setButtonDownScreenPos(button, me->buttonDownScreenPos(button));
}
copy->setLastPos(me->lastPos());
copy->setLastScenePos(me->lastScenePos());
copy->setLastScreenPos(me->lastScreenPos());
copy->setButtons(me->buttons());
copy->setButton(me->button());
copy->setModifiers(me->modifiers());
copy->setSource(me->source());
copy->setFlags(me->flags());
return copy;
#endif
}
#endif // QT_NO_GRAPHICSVIEW
default:
return 0;
}
}
class PressDelayHandler : public QObject
{
private:
PressDelayHandler(QObject *parent = 0)
: QObject(parent)
, pressDelayTimer(0)
, sendingEvent(false)
, mouseButton(Qt::NoButton)
, mouseTarget(0)
, mouseEventSource(Qt::MouseEventNotSynthesized)
{ }
static PressDelayHandler *inst;
public:
enum {
UngrabMouseBefore = 1,
RegrabMouseAfterwards = 2
};
static PressDelayHandler *instance()
{
static PressDelayHandler *inst = 0;
if (!inst)
inst = new PressDelayHandler(QCoreApplication::instance());
return inst;
}
bool shouldEventBeIgnored(QEvent *) const
{
return sendingEvent;
}
bool isDelaying() const
{
return !pressDelayEvent.isNull();
}
void pressed(QEvent *e, int delay)
{
if (!pressDelayEvent) {
pressDelayEvent.reset(copyMouseEvent(e));
pressDelayTimer = startTimer(delay);
mouseTarget = QApplication::widgetAt(pressDelayEvent->globalPos());
mouseButton = pressDelayEvent->button();
mouseEventSource = pressDelayEvent->source();
qFGDebug() << "QFG: consuming/delaying mouse press";
} else {
qFGDebug() << "QFG: NOT consuming/delaying mouse press";
}
e->setAccepted(true);
}
bool released(QEvent *e, bool scrollerWasActive, bool scrollerIsActive)
{
// consume this event if the scroller was or is active
bool result = scrollerWasActive || scrollerIsActive;
// stop the timer
if (pressDelayTimer) {
killTimer(pressDelayTimer);
pressDelayTimer = 0;
}
// we still haven't even sent the press, so do it now
if (pressDelayEvent && mouseTarget && !scrollerIsActive) {
QScopedPointer<QMouseEvent> releaseEvent(copyMouseEvent(e));
qFGDebug() << "QFG: re-sending mouse press (due to release) for " << mouseTarget;
sendMouseEvent(pressDelayEvent.data(), UngrabMouseBefore);
qFGDebug() << "QFG: faking mouse release (due to release) for " << mouseTarget;
sendMouseEvent(releaseEvent.data());
result = true; // consume this event
} else if (mouseTarget && scrollerIsActive) {
// we grabbed the mouse expicitly when the scroller became active, so undo that now
sendMouseEvent(0, UngrabMouseBefore);
}
pressDelayEvent.reset(0);
mouseTarget = 0;
return result;
}
void scrollerWasIntercepted()
{
qFGDebug() << "QFG: deleting delayed mouse press, since scroller was only intercepted";
if (pressDelayEvent) {
// we still haven't even sent the press, so just throw it away now
if (pressDelayTimer) {
killTimer(pressDelayTimer);
pressDelayTimer = 0;
}
pressDelayEvent.reset(0);
}
mouseTarget = 0;
}
void scrollerBecameActive()
{
if (pressDelayEvent) {
// we still haven't even sent the press, so just throw it away now
qFGDebug() << "QFG: deleting delayed mouse press, since scroller is active now";
if (pressDelayTimer) {
killTimer(pressDelayTimer);
pressDelayTimer = 0;
}
pressDelayEvent.reset(0);
mouseTarget = 0;
} else if (mouseTarget) {
// we did send a press, so we need to fake a release now
// release all pressed mouse buttons
/* Qt::MouseButtons mouseButtons = QApplication::mouseButtons();
for (int i = 0; i < 32; ++i) {
if (mouseButtons & (1 << i)) {
Qt::MouseButton b = static_cast<Qt::MouseButton>(1 << i);
mouseButtons &= ~b;
QPoint farFarAway(-QWIDGETSIZE_MAX, -QWIDGETSIZE_MAX);
qFGDebug() << "QFG: sending a fake mouse release at far-far-away to " << mouseTarget;
QMouseEvent re(QEvent::MouseButtonRelease, QPoint(), farFarAway,
b, mouseButtons, QApplication::keyboardModifiers());
sendMouseEvent(&re);
}
}*/
QPoint farFarAway(-QWIDGETSIZE_MAX, -QWIDGETSIZE_MAX);
qFGDebug() << "QFG: sending a fake mouse release at far-far-away to " << mouseTarget;
QMouseEvent re(QEvent::MouseButtonRelease, QPoint(), farFarAway, farFarAway,
mouseButton, QApplication::mouseButtons() & ~mouseButton,
QApplication::keyboardModifiers());
QGuiApplicationPrivate::setMouseEventSource(&re, mouseEventSource);
sendMouseEvent(&re, RegrabMouseAfterwards);
// don't clear the mouseTarget just yet, since we need to explicitly ungrab the mouse on release!
}
}
protected:
void timerEvent(QTimerEvent *e) Q_DECL_OVERRIDE
{
if (e->timerId() == pressDelayTimer) {
if (pressDelayEvent && mouseTarget) {
qFGDebug() << "QFG: timer event: re-sending mouse press to " << mouseTarget;
sendMouseEvent(pressDelayEvent.data(), UngrabMouseBefore);
}
pressDelayEvent.reset(0);
if (pressDelayTimer) {
killTimer(pressDelayTimer);
pressDelayTimer = 0;
}
}
}
void sendMouseEvent(QMouseEvent *me, int flags = 0)
{
if (mouseTarget) {
sendingEvent = true;
#ifndef QT_NO_GRAPHICSVIEW
QGraphicsItem *grabber = 0;
if (mouseTarget->parentWidget()) {
if (QGraphicsView *gv = qobject_cast<QGraphicsView *>(mouseTarget->parentWidget())) {
if (gv->scene())
grabber = gv->scene()->mouseGrabberItem();
}
}
if (grabber && (flags & UngrabMouseBefore)) {
// GraphicsView Mouse Handling Workaround #1:
// we need to ungrab the mouse before re-sending the press,
// since the scene had already set the mouse grabber to the
// original (and consumed) event's receiver
qFGDebug() << "QFG: ungrabbing" << grabber;
grabber->ungrabMouse();
}
#endif // QT_NO_GRAPHICSVIEW
if (me) {
QMouseEvent copy(me->type(), mouseTarget->mapFromGlobal(me->globalPos()),
mouseTarget->topLevelWidget()->mapFromGlobal(me->globalPos()), me->screenPos(),
me->button(), me->buttons(), me->modifiers());
QGuiApplicationPrivate::setMouseEventSource(©, me->source());
qt_sendSpontaneousEvent(mouseTarget, ©);
}
#ifndef QT_NO_GRAPHICSVIEW
if (grabber && (flags & RegrabMouseAfterwards)) {
// GraphicsView Mouse Handling Workaround #2:
// we need to re-grab the mouse after sending a faked mouse
// release, since we still need the mouse moves for the gesture
// (the scene will clear the item's mouse grabber status on
// release).
qFGDebug() << "QFG: re-grabbing" << grabber;
grabber->grabMouse();
}
#endif
sendingEvent = false;
}
}
private:
int pressDelayTimer;
QScopedPointer<QMouseEvent> pressDelayEvent;
bool sendingEvent;
Qt::MouseButton mouseButton;
QPointer<QWidget> mouseTarget;
Qt::MouseEventSource mouseEventSource;
};
/*!
\internal
\class QFlickGesture
\since 4.8
\brief The QFlickGesture class describes a flicking gesture made by the user.
\ingroup gestures
The QFlickGesture is more complex than the QPanGesture that uses QScroller and QScrollerProperties
to decide if it is triggered.
This gesture is reacting on touch event as compared to the QMouseFlickGesture.
\sa {Gestures in Widgets and Graphics View}, QScroller, QScrollerProperties, QMouseFlickGesture
*/
/*!
\internal
*/
QFlickGesture::QFlickGesture(QObject *receiver, Qt::MouseButton button, QObject *parent)
: QGesture(*new QFlickGesturePrivate, parent)
{
d_func()->q_ptr = this;
d_func()->receiver = receiver;
d_func()->receiverScroller = (receiver && QScroller::hasScroller(receiver)) ? QScroller::scroller(receiver) : 0;
d_func()->button = button;
}
QFlickGesture::~QFlickGesture()
{ }
QFlickGesturePrivate::QFlickGesturePrivate()
: receiverScroller(0), button(Qt::NoButton), macIgnoreWheel(false)
{ }
//
// QFlickGestureRecognizer
//
QFlickGestureRecognizer::QFlickGestureRecognizer(Qt::MouseButton button)
{
this->button = button;
}
/*! \reimp
*/
QGesture *QFlickGestureRecognizer::create(QObject *target)
{
#ifndef QT_NO_GRAPHICSVIEW
QGraphicsObject *go = qobject_cast<QGraphicsObject*>(target);
if (go && button == Qt::NoButton) {
go->setAcceptTouchEvents(true);
}
#endif
return new QFlickGesture(target, button);
}
/*! \internal
The recognize function detects a touch event suitable to start the attached QScroller.
The QFlickGesture will be triggered as soon as the scroller is no longer in the state
QScroller::Inactive or QScroller::Pressed. It will be finished or canceled
at the next QEvent::TouchEnd.
Note that the QScroller might continue scrolling (kinetically) at this point.
*/
QGestureRecognizer::Result QFlickGestureRecognizer::recognize(QGesture *state,
QObject *watched,
QEvent *event)
{
Q_UNUSED(watched);
static QElapsedTimer monotonicTimer;
if (!monotonicTimer.isValid())
monotonicTimer.start();
QFlickGesture *q = static_cast<QFlickGesture *>(state);
QFlickGesturePrivate *d = q->d_func();
QScroller *scroller = d->receiverScroller;
if (!scroller)
return Ignore; // nothing to do without a scroller?
QWidget *receiverWidget = qobject_cast<QWidget *>(d->receiver);
#ifndef QT_NO_GRAPHICSVIEW
QGraphicsObject *receiverGraphicsObject = qobject_cast<QGraphicsObject *>(d->receiver);
#endif
// this is only set for events that we inject into the event loop via sendEvent()
if (PressDelayHandler::instance()->shouldEventBeIgnored(event)) {
//qFGDebug() << state << "QFG: ignored event: " << event->type();
return Ignore;
}
const QMouseEvent *me = 0;
#ifndef QT_NO_GRAPHICSVIEW
const QGraphicsSceneMouseEvent *gsme = 0;
#endif
const QTouchEvent *te = 0;
QPoint globalPos;
// qFGDebug() << "FlickGesture "<<state<<"watched:"<<watched<<"receiver"<<d->receiver<<"event"<<event->type()<<"button"<<button;
switch (event->type()) {
case QEvent::MouseButtonPress:
case QEvent::MouseButtonRelease:
case QEvent::MouseMove:
if (!receiverWidget)
return Ignore;
if (button != Qt::NoButton) {
me = static_cast<const QMouseEvent *>(event);
globalPos = me->globalPos();
}
break;
#ifndef QT_NO_GRAPHICSVIEW
case QEvent::GraphicsSceneMousePress:
case QEvent::GraphicsSceneMouseRelease:
case QEvent::GraphicsSceneMouseMove:
if (!receiverGraphicsObject)
return Ignore;
if (button != Qt::NoButton) {
gsme = static_cast<const QGraphicsSceneMouseEvent *>(event);
globalPos = gsme->screenPos();
}
break;
#endif
case QEvent::TouchBegin:
case QEvent::TouchEnd:
case QEvent::TouchUpdate:
if (button == Qt::NoButton) {
te = static_cast<const QTouchEvent *>(event);
if (!te->touchPoints().isEmpty())
globalPos = te->touchPoints().at(0).screenPos().toPoint();
}
break;
#if defined(Q_DEAD_CODE_FROM_QT4_MAC)
// the only way to distinguish between real mouse wheels and wheel
// events generated by the native 2 finger swipe gesture is to listen
// for these events (according to Apple's Cocoa Event-Handling Guide)
case QEvent::NativeGesture: {
QNativeGestureEvent *nge = static_cast<QNativeGestureEvent *>(event);
if (nge->gestureType == QNativeGestureEvent::GestureBegin)
d->macIgnoreWheel = true;
else if (nge->gestureType == QNativeGestureEvent::GestureEnd)
d->macIgnoreWheel = false;
break;
}
#endif
// consume all wheel events if the scroller is active
case QEvent::Wheel:
if (d->macIgnoreWheel || (scroller->state() != QScroller::Inactive))
return Ignore | ConsumeEventHint;
break;
// consume all dbl click events if the scroller is active
case QEvent::MouseButtonDblClick:
if (scroller->state() != QScroller::Inactive)
return Ignore | ConsumeEventHint;
break;
default:
break;
}
if (!me
#ifndef QT_NO_GRAPHICSVIEW
&& !gsme
#endif
&& !te) // Neither mouse nor touch
return Ignore;
// get the current pointer position in local coordinates.
QPointF point;
QScroller::Input inputType = (QScroller::Input) 0;
switch (event->type()) {
case QEvent::MouseButtonPress:
if (me && me->button() == button && me->buttons() == button) {
point = me->globalPos();
inputType = QScroller::InputPress;
} else if (me) {
scroller->stop();
return CancelGesture;
}
break;
case QEvent::MouseButtonRelease:
if (me && me->button() == button) {
point = me->globalPos();
inputType = QScroller::InputRelease;
}
break;
case QEvent::MouseMove:
if (me && me->buttons() == button) {
point = me->globalPos();
inputType = QScroller::InputMove;
}
break;
#ifndef QT_NO_GRAPHICSVIEW
case QEvent::GraphicsSceneMousePress:
if (gsme && gsme->button() == button && gsme->buttons() == button) {
point = gsme->scenePos();
inputType = QScroller::InputPress;
} else if (gsme) {
scroller->stop();
return CancelGesture;
}
break;
case QEvent::GraphicsSceneMouseRelease:
if (gsme && gsme->button() == button) {
point = gsme->scenePos();
inputType = QScroller::InputRelease;
}
break;
case QEvent::GraphicsSceneMouseMove:
if (gsme && gsme->buttons() == button) {
point = gsme->scenePos();
inputType = QScroller::InputMove;
}
break;
#endif
case QEvent::TouchBegin:
inputType = QScroller::InputPress;
// fall through
case QEvent::TouchEnd:
if (!inputType)
inputType = QScroller::InputRelease;
// fallthrough
case QEvent::TouchUpdate:
if (!inputType)
inputType = QScroller::InputMove;
if (te->device()->type() == QTouchDevice::TouchPad) {
if (te->touchPoints().count() != 2) // 2 fingers on pad
return Ignore;
point = te->touchPoints().at(0).startScenePos() +
((te->touchPoints().at(0).scenePos() - te->touchPoints().at(0).startScenePos()) +
(te->touchPoints().at(1).scenePos() - te->touchPoints().at(1).startScenePos())) / 2;
} else { // TouchScreen
if (te->touchPoints().count() != 1) // 1 finger on screen
return Ignore;
point = te->touchPoints().at(0).scenePos();
}
break;
default:
break;
}
// Check for an active scroller at globalPos
if (inputType == QScroller::InputPress) {
foreach (QScroller *as, QScroller::activeScrollers()) {
if (as != scroller) {
QRegion scrollerRegion;
if (QWidget *w = qobject_cast<QWidget *>(as->target())) {
scrollerRegion = QRect(w->mapToGlobal(QPoint(0, 0)), w->size());
#ifndef QT_NO_GRAPHICSVIEW
} else if (QGraphicsObject *go = qobject_cast<QGraphicsObject *>(as->target())) {
if (go->scene() && !go->scene()->views().isEmpty()) {
foreach (QGraphicsView *gv, go->scene()->views())
scrollerRegion |= gv->mapFromScene(go->mapToScene(go->boundingRect()))
.translated(gv->mapToGlobal(QPoint(0, 0)));
}
#endif
}
// active scrollers always have priority
if (scrollerRegion.contains(globalPos))
return Ignore;
}
}
}
bool scrollerWasDragging = (scroller->state() == QScroller::Dragging);
bool scrollerWasScrolling = (scroller->state() == QScroller::Scrolling);
if (inputType) {
if (QWidget *w = qobject_cast<QWidget *>(d->receiver))
point = w->mapFromGlobal(point.toPoint());
#ifndef QT_NO_GRAPHICSVIEW
else if (QGraphicsObject *go = qobject_cast<QGraphicsObject *>(d->receiver))
point = go->mapFromScene(point);
#endif
// inform the scroller about the new event
scroller->handleInput(inputType, point, monotonicTimer.elapsed());
}
// depending on the scroller state return the gesture state
Result result(0);
bool scrollerIsActive = (scroller->state() == QScroller::Dragging ||
scroller->state() == QScroller::Scrolling);
// Consume all mouse events while dragging or scrolling to avoid nasty
// side effects with Qt's standard widgets.
if ((me
#ifndef QT_NO_GRAPHICSVIEW
|| gsme
#endif
) && scrollerIsActive)
result |= ConsumeEventHint;
// The only problem with this approach is that we consume the
// MouseRelease when we start the scrolling with a flick gesture, so we
// have to fake a MouseRelease "somewhere" to not mess with the internal
// states of Qt's widgets (a QPushButton would stay in 'pressed' state
// forever, if it doesn't receive a MouseRelease).
if (me
#ifndef QT_NO_GRAPHICSVIEW
|| gsme
#endif
) {
if (!scrollerWasDragging && !scrollerWasScrolling && scrollerIsActive)
PressDelayHandler::instance()->scrollerBecameActive();
else if (scrollerWasScrolling && (scroller->state() == QScroller::Dragging || scroller->state() == QScroller::Inactive))
PressDelayHandler::instance()->scrollerWasIntercepted();
}
if (!inputType) {
result |= Ignore;
} else {
switch (event->type()) {
case QEvent::MouseButtonPress:
#ifndef QT_NO_GRAPHICSVIEW
case QEvent::GraphicsSceneMousePress:
#endif
if (scroller->state() == QScroller::Pressed) {
int pressDelay = int(1000 * scroller->scrollerProperties().scrollMetric(QScrollerProperties::MousePressEventDelay).toReal());
if (pressDelay > 0) {
result |= ConsumeEventHint;
PressDelayHandler::instance()->pressed(event, pressDelay);
event->accept();
}
}
// fall through
case QEvent::TouchBegin:
q->setHotSpot(globalPos);
result |= scrollerIsActive ? TriggerGesture : MayBeGesture;
break;
case QEvent::MouseMove:
#ifndef QT_NO_GRAPHICSVIEW
case QEvent::GraphicsSceneMouseMove:
#endif
if (PressDelayHandler::instance()->isDelaying())
result |= ConsumeEventHint;
// fall through
case QEvent::TouchUpdate:
result |= scrollerIsActive ? TriggerGesture : Ignore;
break;
#ifndef QT_NO_GRAPHICSVIEW
case QEvent::GraphicsSceneMouseRelease:
#endif
case QEvent::MouseButtonRelease:
if (PressDelayHandler::instance()->released(event, scrollerWasDragging || scrollerWasScrolling, scrollerIsActive))
result |= ConsumeEventHint;
// fall through
case QEvent::TouchEnd:
result |= scrollerIsActive ? FinishGesture : CancelGesture;
break;
default:
result |= Ignore;
break;
}
}
return result;
}
/*! \reimp
*/
void QFlickGestureRecognizer::reset(QGesture *state)
{
QGestureRecognizer::reset(state);
}
QT_END_NAMESPACE
#endif // QT_NO_GESTURES
|
stvliu/tcc-transaction
|
galaxy-console/src/main/java/io/anyway/galaxy/console/dal/dao/BusinessTypeDao.java
|
<filename>galaxy-console/src/main/java/io/anyway/galaxy/console/dal/dao/BusinessTypeDao.java
package io.anyway.galaxy.console.dal.dao;
import io.anyway.galaxy.console.dal.dto.BusinessTypeDto;
import java.util.List;
/**
* Created by xiong.j on 2016/8/1.
*/
public interface BusinessTypeDao {
/**
* 增加分布式事务业务类型
* @param dto
* @return
*/
int add(BusinessTypeDto dto);
/**
* 修改分布式事务业务类型
* @param dto
* @return
*/
int update(BusinessTypeDto dto);
/**
* 获取分布式事务业务类型列表
* @param dto
* @return
*/
List<BusinessTypeDto> list(BusinessTypeDto dto);
/**
* 获取分布式事务业务类型与数据源
* @param id
* @return
*/
BusinessTypeDto get(long id);
/**
* 获取分布式事务业务类型与数据源
* @param name
* @return
*/
BusinessTypeDto getByName(String name);
/**
* 删除分布式事务业务类型
* @param id
* @return
*/
int del(long id);
}
|
kponnima/myapp-java-spring-crud
|
CoorgUSA/src/main/java/com/spring/service/VideoServiceImpl.java
|
<reponame>kponnima/myapp-java-spring-crud
package com.spring.service;
import java.util.List;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.spring.dao.VideoDao;
import com.spring.model.Video;
@Service("videoService")
@Transactional
public class VideoServiceImpl implements VideoService {
@Autowired
VideoDao dao;
public Video findById(int videoid) {
return dao.findById(videoid);
}
public List<Video> findAll() {
return dao.findAll();
}
public List<Video> findAllByUserId(int userId) {
return dao.findAllByUserId(userId);
}
public void saveVideo(Video video) {
dao.save(video);
}
public void deleteById(int videoid) {
dao.deleteById(videoid);
}
}
|
tylerslaton/api
|
pkg/apis/scorecard/v1alpha3/register.go
|
package v1alpha3
import (
"k8s.io/apimachinery/pkg/runtime/schema"
)
var (
// GroupVersion is the group and version of this package. Used for parsing purposes only.
GroupVersion = schema.GroupVersion{Group: "scorecard.operatorframework.io", Version: "v1alpha3"}
)
|
gannetson/sportschooldeopenlucht
|
sportschool/settings/secrets.py
|
"""
secrets.py
Add passwords, API keys and other secrets in this file.
"""
# Make this unique, and don't share it with anybody.
SECRET_KEY = '<KEY>'
# Database authentication
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'sportschool',
'USER': 'gannetson',
'PASSWORD': '<PASSWORD>'
}
}
|
antoshalee/mindflow
|
spec/mindflow/ast/c_node_spec.rb
|
<filename>spec/mindflow/ast/c_node_spec.rb<gh_stars>0
require 'spec_helper'
describe Mindflow::Ast::CNode do
subject { described_class.new(class_name) }
let(:class_name) { 'User' }
it 'allows to add d nodes' do
expect { subject.add_child('d', 'initialize') }.not_to raise_error
end
it 'allows to add created d node' do
d_node = Mindflow::Ast::DNode.new('publish')
expect { subject.add_child(d_node) }.not_to raise_error
end
it 'does not allow to add foo nodes' do
expect { subject.add_child('foo', 'bat') }
.to raise_error(Mindflow::Ast::UnacceptableChildError)
end
end
|
qcscine/molassembler
|
src/Molassembler/IO/SmilesEmitter.cpp
|
<filename>src/Molassembler/IO/SmilesEmitter.cpp
/*!@file
* @copyright This code is licensed under the 3-clause BSD license.
* Copyright ETH Zurich, Laboratory of Physical Chemistry, Reiher Group.
* See LICENSE.txt for details.
*/
#include "Molassembler/IO/SmilesEmitter.h"
#include "Molassembler/IO/SmilesCommon.h"
#include "Molassembler/Modeling/BondDistance.h"
#include "Molassembler/Molecule.h"
#include "Molassembler/Graph.h"
#include "Molassembler/Graph/PrivateGraph.h"
#include "Molassembler/GraphAlgorithms.h"
#include "Molassembler/StereopermutatorList.h"
#include "Molassembler/Shapes/Properties.h"
#include "Molassembler/Temple/Functional.h"
#include "Molassembler/Temple/Permutations.h"
#include "Utils/Geometry/ElementInfo.h"
#include "boost/graph/prim_minimum_spanning_tree.hpp"
#include <fstream>
#include "boost/graph/graphviz.hpp"
#include "Molassembler/Temple/Stringify.h"
#include <iostream>
#include <unordered_set>
namespace Scine {
namespace Molassembler {
namespace IO {
namespace Experimental {
struct RingClosure {
RingClosure() = default;
explicit RingClosure(AtomIndex i) : partner(i) {}
// Bond partner of ring-closing bond
AtomIndex partner;
// Marked number in depth-first traversal
boost::optional<unsigned> number;
};
struct VertexProperties {
unsigned rank = 0;
bool aromatic = false;
unsigned subsumedHydrogens = 0;
std::vector<RingClosure> closures;
};
using SpanningTree = boost::adjacency_list<
boost::vecS,
boost::vecS,
boost::bidirectionalS,
VertexProperties
>;
namespace {
struct Unity {
using key_type = typename SpanningTree::edge_descriptor;
using value_type = double;
using reference = double;
using category = boost::readable_property_map_tag;
};
inline double get(const Unity& /* u */, const Unity::key_type& /* e */) {
return 1.0;
}
struct InverseBondOrder {
using key_type = PrivateGraph::Edge;
using value_type = double;
using reference = double;
using category = boost::readable_property_map_tag;
explicit InverseBondOrder(const PrivateGraph& g) : graphRef(g) {}
std::reference_wrapper<const PrivateGraph> graphRef;
};
inline double get(const InverseBondOrder& u, const PrivateGraph::Edge& e) {
const PrivateGraph& g = u.graphRef.get();
const BondType type = g.bondType(e);
const double order = Bond::bondOrderMap.at(static_cast<unsigned>(type));
const unsigned inverseOrder = 7 - order;
/* Weight edges by the graph degree (of heavy atoms only) to incentivize ring
* closures at fulcrums of the heavy atom graph. Important for normalization
* of e.g. biphenyl.
*/
const auto heavyDegree = [&](const AtomIndex i) -> unsigned {
return Temple::accumulate(
g.adjacents(i),
0U,
[&](const unsigned carry, const AtomIndex j) -> unsigned {
if(
g.elementType(j) == Utils::ElementType::H
&& g.degree(j) == 1
) {
return carry;
}
return carry + 1;
}
);
};
return inverseOrder + heavyDegree(g.source(e)) + heavyDegree(g.target(e));
}
const std::unordered_map<unsigned, unsigned>& smilesStereodescriptorShapeMap(
const Shapes::Shape shape
) {
switch(shape) {
case Shapes::Shape::Tetrahedron: {
static std::unordered_map<unsigned, unsigned> tetrahedronMap {
{0, 1},
{1, 2},
};
return tetrahedronMap;
}
case Shapes::Shape::Square: {
static std::unordered_map<unsigned, unsigned> squareMap {
{0, 1},
{3, 2},
{22, 3}
};
return squareMap;
}
case Shapes::Shape::TrigonalBipyramid: {
static std::unordered_map<unsigned, unsigned> trigBipyramidMap {
{32, 1},
{38, 2},
{34, 3},
{44, 4},
{40, 5},
{46, 6},
{64, 7},
{70, 8},
{8, 9},
{10, 10},
{14, 11},
{20, 12},
{16, 13},
{22, 14},
{2, 15},
{4, 16},
{0, 17},
{6, 18},
{18, 19},
{12, 20},
};
return trigBipyramidMap;
}
case Shapes::Shape::Octahedron: {
static std::unordered_map<unsigned, unsigned> octahedronMap {
{152, 1},
{566, 2},
{154, 3},
{158, 4},
{164, 5},
{160, 6},
{166, 7},
{176, 8},
{178, 9},
{542, 10},
{662, 11},
{202, 12},
{668, 13},
{446, 14},
{470, 15},
{686, 16},
{590, 17},
{710, 18},
{184, 19},
{190, 20},
{208, 21},
{692, 22},
{596, 23},
{716, 24},
{304, 25},
{310, 26},
{328, 27},
{694, 28},
{598, 29},
{718, 30},
};
return octahedronMap;
}
default: throw std::out_of_range("No shape map for selected shape");
}
}
unsigned smilesStereodescriptor(
const Shapes::Shape shape,
const std::vector<Shapes::Vertex>& order
) {
const auto allRotations = Shapes::Properties::generateAllRotations(
shape,
order
);
std::unordered_set<unsigned> permutationIndices;
for(const auto& indices : allRotations) {
permutationIndices.insert(Temple::permutationIndex(indices));
}
for(const auto& pair : smilesStereodescriptorShapeMap(shape)) {
if(permutationIndices.count(pair.first) > 0) {
return pair.second;
}
}
throw std::out_of_range("No smiles stereodescriptor found!");
}
} // namespace
struct Emitter {
//! Bond stereo markers in smiles
enum class BondStereo { Forward, Backward };
static bool heteroatom(const Utils::ElementType e) {
return e != Utils::ElementType::H && e != Utils::ElementType::C;
}
Emitter(const Molecule& mol) : spanning(mol.V()), molecule(mol) {
/* Plan:
* - Find a minimum spanning tree while weighting edges according to their
* inverse bond order and sum of endpoint heavy atom degrees to find a
* suitable acyclization of the molecular graph for the smiles
* - Find the longest path within that acyclic graph
* - Find a minimum spanning tree starting at the root of the longest path
* and reduce edges from the (bidirectional acyclic) graph to fit that
* tree
*
* Details:
* - Subsumed hydrogen atoms are disconnected in the construction of the
* initial bidirectional graph mimicking the molecule
* - Record ring closures after acyclization
*/
auto subsumption = markSubsumedHydrogens();
const PrivateGraph& inner = mol.graph().inner();
/* TODO maybe should place the root vertex of this MST at the 'centroid'
* of the graph, i.e. the vertex with the lowest average distance to all
* other vertices? Unsure of the influence of this arbitrary choice here.
*/
const PrivateGraph::Vertex V = inner.V();
std::vector<PrivateGraph::Vertex> predecessors (V);
boost::prim_minimum_spanning_tree(
inner.bgl(),
boost::make_iterator_property_map(
predecessors.begin(),
boost::get(boost::vertex_index, inner.bgl())
),
boost::root_vertex(0).
weight_map(InverseBondOrder {inner})
);
// Add edges from predecessor list, but bidirectional!
for(const PrivateGraph::Vertex v : inner.vertices()) {
const PrivateGraph::Vertex predecessor = predecessors.at(v);
// Skip unreachable vertices and the root
if(predecessor == v) {
continue;
}
// Skip subsumed hydrogen atoms
if(subsumption.count(v) > 0) {
continue;
}
boost::add_edge(predecessor, v, spanning);
boost::add_edge(v, predecessor, spanning);
}
/* Figure out ring-closing bonds from predecessor list: If neither of the
* bonds vertices has the other atom as its predecessor, it is not in the
* minimum spanning tree and represents a ring closure
*/
for(const auto& bond : inner.edges()) {
const PrivateGraph::Vertex u = inner.source(bond);
const PrivateGraph::Vertex v = inner.target(bond);
if(predecessors.at(u) != v && predecessors.at(v) != u) {
spanning[u].closures.emplace_back(v);
spanning[v].closures.emplace_back(u);
}
}
longestPath = findMainBranch();
const AtomIndex root = longestPath.front();
/* Now for the second minimum spanning tree calculation to figure out the
* directionality of the tree
*/
boost::prim_minimum_spanning_tree(
spanning,
boost::make_iterator_property_map(
predecessors.begin(),
boost::get(boost::vertex_index, inner.bgl())
),
boost::root_vertex(root).
weight_map(Unity {})
);
// Impose directionality of the MST on the graph
for(PrivateGraph::Vertex v = 0; v < V; ++v) {
const PrivateGraph::Vertex predecessor = predecessors.at(v);
// Skip unreachable vertices and the root
if(predecessor == v) {
continue;
}
boost::remove_edge(v, predecessor, spanning);
}
recordVertexRank(root);
markAromaticAtoms();
markBondStereo();
}
std::unordered_map<AtomIndex, AtomIndex> markSubsumedHydrogens() {
std::unordered_map<AtomIndex, AtomIndex> result;
const PrivateGraph& inner = molecule.graph().inner();
/* Find terminal hydrogen atoms that can be rewritten into heavy atom
* labels, implicit or explicit
*/
for(const AtomIndex i : inner.vertices()) {
if(
inner.elementType(i) != Utils::ElementType::H
|| inner.degree(i) != 1
) {
continue;
}
for(const AtomIndex j : inner.adjacents(i)) {
// Cannot subsume the terminal hydrogen in another hydrogen atom
if(inner.elementType(j) == Utils::ElementType::H) {
continue;
}
result.emplace(i, j);
++spanning[j].subsumedHydrogens;
}
}
return result;
}
// Figure out the longest path in the acyclic graph
std::vector<AtomIndex> findMainBranch() const {
const unsigned V = molecule.V();
AtomIndex suggestedRoot = guessRoot();
std::vector<AtomIndex> predecessors(V, suggestedRoot);
std::vector<unsigned> distances(V, 0);
boost::breadth_first_search(
spanning,
suggestedRoot,
boost::visitor(
boost::make_bfs_visitor(
std::make_pair(
boost::record_distances(&distances[0], boost::on_tree_edge {}),
boost::record_predecessors(&predecessors[0], boost::on_tree_edge {})
)
)
)
);
AtomIndex partner = std::max_element(
std::begin(distances),
std::end(distances)
) - std::begin(distances);
auto path = PredecessorMap {predecessors}.path(partner);
// Normalization: Begin on a heteroatom, if possible
if(
heteroatom(molecule.graph().elementType(partner))
&& !heteroatom(molecule.graph().elementType(suggestedRoot))
) {
std::swap(suggestedRoot, partner);
std::reverse(std::begin(path), std::end(path));
}
return path;
}
/* Record the number of descendants of each vertex in the spanning tree
* as the internal rank property (we'll use this in descent ordering later
* for more normalized smiles).
*/
void recordVertexRank(AtomIndex i) {
// Do a non-tail-recursive DFS-like traversal
for(
auto iters = boost::out_edges(i, spanning);
iters.first != iters.second;
++iters.first
) {
const AtomIndex child = boost::target(*iters.first, spanning);
recordVertexRank(child);
spanning[i].rank += 1 + spanning[child].rank;
}
}
void markAromaticAtoms() {
const std::unordered_set<Shapes::Shape> flatShapes {
Shapes::Shape::Bent,
Shapes::Shape::EquilateralTriangle
};
for(const auto& cycleEdges : molecule.graph().cycles()) {
const bool permutatorsEverywhere = Temple::all_of(
cycleEdges,
[&](const BondIndex& bond) -> bool {
return static_cast<bool>(molecule.stereopermutators().option(bond));
}
);
if(!permutatorsEverywhere) {
continue;
}
auto cycleAtoms = makeRingIndexSequence(cycleEdges);
const bool flat = Temple::all_of(
cycleAtoms,
[&](const AtomIndex i) -> bool {
auto permutator = molecule.stereopermutators().option(i);
if(!permutator) {
return false;
}
return flatShapes.count(permutator->getShape()) > 0;
}
);
if(!flat) {
continue;
}
for(const AtomIndex i : cycleAtoms) {
spanning[i].aromatic = true;
}
for(const BondIndex& b : cycleEdges) {
aromaticBonds.insert(b);
}
}
}
void markBondStereo() {
for(
const BondStereopermutator& permutator:
molecule.stereopermutators().bondStereopermutators()
) {
const BondIndex& bond = permutator.placement();
if(
permutator.numAssignments() < 2
|| molecule.bondType(bond) != BondType::Double
|| aromaticBonds.count(bond) > 0
) {
continue;
}
const auto orderedPlacement = [&]() {
const auto forwardEdge = boost::edge(bond.first, bond.second, spanning);
if(forwardEdge.second) {
return std::make_pair(bond.first, bond.second);
}
return std::make_pair(bond.second, bond.first);
}();
const AtomIndex front = parent(orderedPlacement.first);
if(molecule.bondType(BondIndex {front, orderedPlacement.first}) != BondType::Single) {
continue;
}
auto pathIter = std::find(
std::begin(longestPath),
std::end(longestPath),
orderedPlacement.second
);
if(pathIter == std::end(longestPath)) {
pathIter = std::begin(longestPath);
}
const AtomIndex back = descendants(orderedPlacement.second, pathIter).back();
if(molecule.bondType(BondIndex {orderedPlacement.second, back}) != BondType::Single) {
continue;
}
const auto permutators = Temple::map(
orderedPlacement,
[&](const AtomIndex i) {
return molecule.stereopermutators().option(i);
}
);
const auto allowedShape = [](const Shapes::Shape shape) -> bool {
return (
shape == Shapes::Shape::Bent
|| shape == Shapes::Shape::EquilateralTriangle
);
};
if(
!permutators.first || !permutators.second
|| !allowedShape(permutators.first->getShape())
|| !allowedShape(permutators.second->getShape())
) {
continue;
}
const double dihedral = permutator.dihedral(
permutators.first.value(),
permutators.first->getRanking().getSiteIndexOf(front),
permutators.second.value(),
permutators.second->getRanking().getSiteIndexOf(back)
);
bondStereoMarkers.emplace(orderedPlacement.first, BondStereo::Forward);
if(std::fabs(dihedral) < 1e-2) {
// Front and back are Z to one another
bondStereoMarkers.emplace(back, BondStereo::Backward);
} else {
// Front and back are E to one another
bondStereoMarkers.emplace(back, BondStereo::Forward);
}
}
}
std::vector<unsigned> distance(AtomIndex a) const {
std::vector<unsigned> distances(boost::num_vertices(spanning), 0);
boost::breadth_first_search(
spanning,
a,
boost::visitor(
boost::make_bfs_visitor(
boost::record_distances(&distances[0], boost::on_tree_edge {})
)
)
);
return distances;
}
AtomIndex guessRoot() const {
using IndexDistancePair = std::pair<AtomIndex, unsigned>;
return Temple::accumulate(
molecule.graph().atoms(),
IndexDistancePair {0, 0},
[&](const IndexDistancePair& carry, const AtomIndex i) -> IndexDistancePair {
/* NOTE: We're using distances in the acyclic graph here, not distances
* in the (possibly cyclic) molecule
*/
const auto distances = distance(i);
const unsigned maxDistance = *std::max_element(
std::begin(distances),
std::end(distances)
);
if(maxDistance > carry.second) {
return std::make_pair(i, maxDistance);
}
return carry;
}
).first;
}
bool isSmilesStereogenic(const AtomIndex v) const {
auto permutator = molecule.stereopermutators().option(v);
if(!permutator) {
return false;
}
switch(permutator->getShape()) {
// These are the only shapes that smiles has descriptors for
case Shapes::Shape::Tetrahedron:
case Shapes::Shape::Square:
case Shapes::Shape::TrigonalBipyramid:
case Shapes::Shape::Octahedron:
return permutator->numAssignments() > 1;
default:
return false;
}
}
std::string atomSymbol(
const AtomIndex v,
const std::vector<AtomIndex>& descendantOrder
) const {
/* Decide whether to emit either
* - an aliphatic organic symbol
* - an aromatic organic symbol
* - a bracket atom
* - Necessary if isotopic or non-standard hydrogen count
*/
const Utils::ElementType e = molecule.elementType(v);
const bool isIsotope = Utils::ElementInfo::base(e) != e;
const unsigned hydrogenCount = spanning[v].subsumedHydrogens;
const bool isStereogenic = isSmilesStereogenic(v);
if(!isIsotope && !isStereogenic && isValenceFillElement(e)) {
const bool isAromatic = spanning[v].aromatic;
const int valence = Temple::accumulate(
molecule.graph().adjacents(v),
0U,
[&](const int count, const AtomIndex i) -> int {
if(
molecule.graph().elementType(i) == Utils::ElementType::H
&& molecule.graph().degree(i) == 1
) {
return count;
}
const BondType type = molecule.graph().bondType(BondIndex {v, i});
const int order = Bond::bondOrderMap.at(static_cast<unsigned>(type));
return count + order;
}
);
// TODO need to kekulize here too, this doesn't quite work!
const int aromaticityCompensatedValence = isAromatic ? valence + 1 : valence;
const unsigned valenceFill = valenceFillElementImplicitHydrogenCount(
aromaticityCompensatedValence,
e
);
if(valenceFill == hydrogenCount) {
std::string symbol = Utils::ElementInfo::symbol(e);
if(isAromatic) {
std::transform(
std::begin(symbol),
std::end(symbol),
std::begin(symbol),
[](unsigned char c) { return std::tolower(c); }
);
}
return symbol;
}
}
// Bracket atom
std::string elementStr = "[";
if(isIsotope) {
elementStr += std::to_string(Utils::ElementInfo::A(e));
}
elementStr += Utils::ElementInfo::symbol(e);
if(isStereogenic) {
elementStr += atomStereodescriptor(v, descendantOrder);
}
if(hydrogenCount > 1) {
elementStr += "H" + std::to_string(hydrogenCount);
} else if(hydrogenCount == 1) {
elementStr += "H";
}
elementStr += "]";
return elementStr;
}
std::string atomStereodescriptor(
const AtomIndex v,
const std::vector<AtomIndex>& descendantOrder
) const {
auto permutator = molecule.stereopermutators().option(v);
assert(permutator);
/* - Use the shape map to place the substituent order index of the smiles
* at the shape vertices (via the site indices), taking extra care of
* hydrogen counts (which are ordered first in the smiles sequence)
* - Generate all rotations of that permutation and find a smiles
* stereodescriptor for that shape that matches
*/
std::vector<SiteIndex> siteSequence;
if(spanning[v].subsumedHydrogens > 0) {
// Subsumed hydrogens are placed first in the ordering (SMILES rules)
SiteIndex i {0};
for(const auto& siteIndices : permutator->getRanking().sites) {
if(siteIndices.size() == 1) {
const AtomIndex siteAtom = siteIndices.front();
if(
molecule.graph().elementType(siteAtom) == Utils::ElementType::H
&& molecule.graph().degree(siteAtom) == 1
) {
siteSequence.push_back(i);
}
}
++i;
}
}
for(auto iters = boost::in_edges(v, spanning); iters.first != iters.second; ++iters.first) {
const AtomIndex parent = boost::source(*iters.first, spanning);
siteSequence.push_back(permutator->getRanking().getSiteIndexOf(parent));
}
for(const AtomIndex i : descendantOrder) {
siteSequence.push_back(permutator->getRanking().getSiteIndexOf(i));
}
const auto orderAtShapeVertices = Temple::map(
siteSequence,
[&](const SiteIndex i) -> Shapes::Vertex {
return permutator->getShapePositionMap().at(i);
}
);
const unsigned stereodescriptor = smilesStereodescriptor(
permutator->getShape(),
Shapes::Properties::inverseRotation(orderAtShapeVertices)
);
switch(permutator->getShape()) {
case Shapes::Shape::Tetrahedron: {
if(stereodescriptor == 1) {
return "@";
}
return "@@";
}
case Shapes::Shape::Square: {
return "@SP" + std::to_string(stereodescriptor);
}
case Shapes::Shape::TrigonalBipyramid: {
return "@TB" + std::to_string(stereodescriptor);
}
case Shapes::Shape::Octahedron: {
return "@OH" + std::to_string(stereodescriptor);
}
default: {
std::cerr << "Precondition violation for smiles emitter atom stereodescriptor! Exiting.\n";
std::exit(1); // Unreachable by precondition of isStereogenic
}
}
}
void writeEdgeType(const AtomIndex v, const AtomIndex w) {
const BondIndex bond {v, w};
switch(molecule.bondType(bond)) {
case BondType::Single: {
/* Bond between aromatic atoms that isn't aromatic itself,
* e.g. in biphenyl c1ccccc1-c2ccccc2
*/
if(
spanning[v].aromatic
&& spanning[w].aromatic
&& aromaticBonds.count(bond) == 0
) {
smiles += "-";
}
/* Double bond stereo markers */
const auto markerIter = bondStereoMarkers.find(w);
if(markerIter != std::end(bondStereoMarkers)) {
switch(markerIter->second) {
case BondStereo::Forward: {
smiles += "/";
break;
}
case BondStereo::Backward: {
smiles += "\\";
break;
}
}
}
break;
}
case BondType::Double: { smiles += "="; break; }
case BondType::Triple: { smiles += "#"; break; }
// NOTE: Eta and bond orders four through six aren't explicitly written
default: break;
}
}
/* Sort descendant vertices by increasing number of descendants, ensuring
* a continuation of the longest path is always last.
*
* TODO check if the additional conditions regarding the main branch are
* actually necessary. In principle, it could be guaranteed that the longest
* path is last by virtue of being the longest path (i.e. the path with the
* most descendants). It might not be stable against multiple longest paths,
* though.
*/
std::vector<AtomIndex> descendants(
const AtomIndex v,
const std::vector<AtomIndex>::iterator& pathIter
) const {
const auto nextOnMainBranch = [&]() -> boost::optional<AtomIndex> {
if(v != *pathIter) {
return boost::none;
}
const auto nextIter = pathIter + 1;
if(nextIter == std::end(longestPath)) {
return boost::none;
}
return *nextIter;
}();
std::vector<AtomIndex> vertices;
for(auto iters = boost::out_edges(v, spanning); iters.first != iters.second; ++iters.first) {
vertices.push_back(boost::target(*iters.first, spanning));
}
Temple::sort(
vertices,
[&](const AtomIndex i, const AtomIndex j) -> bool {
if(i == nextOnMainBranch) {
return false;
}
if(j == nextOnMainBranch) {
return true;
}
return spanning[i].rank < spanning[j].rank;
}
);
return vertices;
}
void dfs(const AtomIndex v, std::vector<AtomIndex>::iterator& pathIter) {
auto descendantOrder = descendants(v, pathIter);
smiles += atomSymbol(v, descendantOrder);
// Ring closing bonds
for(RingClosure& closure : spanning[v].closures) {
if(!closure.number) {
closure.number = closureIndex;
// Find matching closure for partner
auto& partnerClosures = spanning[closure.partner].closures;
auto partnerIter = std::find_if(
std::begin(partnerClosures),
std::end(partnerClosures),
[&](const RingClosure& hay) {
return hay.partner == v;
}
);
assert(partnerIter != std::end(partnerClosures));
assert(!partnerIter->number);
// Mark partner number
partnerIter->number = closureIndex;
++closureIndex;
}
assert(closure.number);
const unsigned number = closure.number.value();
if(number < 10) {
smiles += std::to_string(number);
} else {
smiles += "%" + std::to_string(number);
}
}
// Descend into substituents
for(const AtomIndex w : descendantOrder) {
const bool last = (w == descendantOrder.back());
if(!last) {
smiles += "(";
}
writeEdgeType(v, w);
dfs(w, pathIter);
if(!last) {
smiles += ")";
}
}
}
AtomIndex parent(const AtomIndex v) const {
auto iters = boost::in_edges(v, spanning);
assert(iters.first != iters.second);
return boost::source(*iters.first, spanning);
}
std::string dfs() {
/* Depth-first search with custom ordering that descends into the longest
* path last at each vertex
*/
auto pathIter = std::begin(longestPath);
dfs(longestPath.front(), pathIter);
return smiles;
}
unsigned closureIndex = 1;
std::string smiles;
SpanningTree spanning;
std::vector<AtomIndex> longestPath;
/* NOTE: This cannot be a spanning-tree edge property since aromatic ring
* closures are not edges in the tree
*/
std::unordered_set<BondIndex, boost::hash<BondIndex>> aromaticBonds;
std::unordered_map<AtomIndex, BondStereo> bondStereoMarkers;
const Molecule& molecule;
};
std::string emitSmiles(const Molecule& mol) {
Emitter emitter(mol);
return emitter.dfs();
}
} // namespace Experimental
} // namespace IO
} // namespace Molassembler
} // namespace Scine
|
zoujie0519/crm
|
src/main/java/com/jensen/platform/crm/api/common/queue/SystemLogConsumer.java
|
/*
* All rights Reserved, Designed By www.jensen.com
* @Title: SystemLogConsumer.java
* @Package com.jensen.platform.crm.api.common.queue
* @author: Jensen
* @date: 2020/9/28 10:41
* @version V1.0
* @Copyright: 2020 www.jensen.com Inc. All rights reserved.
* 注意:本内容仅限于深圳杰森科技有限公司内部传阅,禁止外泄以及用于其他的商业目
*/
package com.jensen.platform.crm.api.common.queue;
import com.jensen.platform.crm.api.entity.sys.SysOperateLog;
import com.jensen.platform.crm.api.service.sys.SysOperateLogService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
/**
* @ClassName: SystemLogConsumer
* @Description: 系统日志队列消费者
* @author: Jensen
* @date: 2020/9/28 10:41
*/
@Component
public class SystemLogConsumer implements Runnable {
private static Logger logger = LoggerFactory.getLogger(SystemLogConsumer.class);
public static final int DEFAULT_BATCH_SIZE = 64;
private SystemLogQueue auditLogQueue;
private SysOperateLogService sysOperateLogService;
private int batchSize = DEFAULT_BATCH_SIZE;
private boolean active = true;
private Thread thread;
/***
* @Title: init
* @Description 初始化启动线程
* @Author Jensen
* @Date 2020/9/28 10:41
* @param
* @Return
* @Exception
*/
@PostConstruct
public void init() {
thread = new Thread(this);
thread.start();
}
@PreDestroy
public void close() {
active = false;
}
@Override
public void run() {
while (active) {
execute();
}
}
/***
* @Title: execute
* @Description 执行线程
* @Author Jensen
* @Date 2020/9/28 10:41
* @param
* @Return
* @Exception
*/
public void execute() {
List<SysOperateLog> sysOperateLogs = new ArrayList<>();
try {
int size = 0;
while (size < batchSize) {
SysOperateLog sysOperateLog = auditLogQueue.poll();
if (sysOperateLog == null) {
break;
}
sysOperateLogs.add(sysOperateLog);
size++;
}
} catch (Exception ex) {
logger.info(ex.getMessage(), ex);
}
if (!sysOperateLogs.isEmpty()) {
try {
//Thread.sleep(10000);
sysOperateLogService.insertByBatch(sysOperateLogs);
}catch (Exception e){
logger.error("异常信息:{}", e.getMessage());
}
}
}
@Resource
public void setAuditLogQueue(SystemLogQueue auditLogQueue) {
this.auditLogQueue = auditLogQueue;
}
@Resource
public void setSysOperateLogService(SysOperateLogService sysOperateLogService) {
this.sysOperateLogService = sysOperateLogService;
}
public void setBatchSize(int batchSize) {
this.batchSize = batchSize;
}
}
|
Unknoob/buck
|
src/com/facebook/buck/android/ConstraintBasedAndroidNativeTargetConfigurationMatcher.java
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.buck.android;
import com.facebook.buck.android.toolchain.ndk.TargetCpuType;
import com.facebook.buck.core.exceptions.HumanReadableException;
import com.facebook.buck.core.model.BuildTarget;
import com.facebook.buck.core.model.platform.NamedPlatform;
import com.facebook.buck.core.rules.config.registry.ConfigurationRuleRegistry;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import java.util.Optional;
/**
* Matcher that uses constraints to figure out whether platform in target configuration matches the
* CPU type.
*
* <p>It keeps a mapping that provides a list of constraint values for a given CPU type. When a
* request is made, it uses the constraints for the given CPU and checks whether the platform of the
* target matches the constraints.
*/
public class ConstraintBasedAndroidNativeTargetConfigurationMatcher
implements AndroidNativeTargetConfigurationMatcher {
private final ConfigurationRuleRegistry configurationRuleRegistry;
private final ImmutableMap<TargetCpuType, NamedPlatform> targetCpuTypeToConstraints;
public ConstraintBasedAndroidNativeTargetConfigurationMatcher(
ConfigurationRuleRegistry configurationRuleRegistry,
ImmutableMap<TargetCpuType, NamedPlatform> targetCpuTypeToConstraints) {
this.configurationRuleRegistry = configurationRuleRegistry;
this.targetCpuTypeToConstraints = targetCpuTypeToConstraints;
}
@Override
public boolean nativeTargetConfigurationMatchesCpuType(
BuildTarget buildTarget, TargetCpuType targetCpuType) {
NamedPlatform cpuPlatform = targetCpuTypeToConstraints.get(targetCpuType);
if (cpuPlatform == null) {
throw new HumanReadableException(
"%s has inconsistent information about CPU type constraints: %s is not present.",
buildTarget, targetCpuType);
}
Optional<BuildTarget> buildTargetConfigurationTargets =
buildTarget.getTargetConfiguration().getConfigurationTarget();
// Platforms are always configured if we get here
Preconditions.checkState(buildTargetConfigurationTargets.isPresent());
return cpuPlatform.getBuildTarget().equals(buildTargetConfigurationTargets.get());
}
public ConfigurationRuleRegistry getConfigurationRuleRegistry() {
return configurationRuleRegistry;
}
}
|
mEDI-S/mEDI_s-Elite-Tools
|
gui/deals_from_to.py
|
<gh_stars>10-100
# -*- coding: UTF8
'''
Created on 27.08.2015
@author: mEDI
'''
from PySide import QtCore, QtGui
import PySide
import elite
from datetime import datetime, timedelta
import gui.guitools as guitools
__toolname__ = "Deals From To Finder"
__internalName__ = "DeFrToFi"
__statusTip__ = "Open A %s Window" % __toolname__
class tool(QtGui.QWidget):
main = None
mydb = elite.db
route = None
def __init__(self, main):
super(tool, self).__init__(main)
self.main = main
self.mydb = main.mydb
self.guitools = guitools.guitools(self)
self.createActions()
self.createTimer()
def getWideget(self):
gridLayout = QtGui.QGridLayout()
gridLayout.setColumnStretch(1, 1)
gridLayout.setColumnStretch(3, 2)
gridLayout.setColumnStretch(4, 1)
gridLayout.setColumnStretch(6, 2)
self.autoUpdateLocation = QtGui.QCheckBox("Auto Switch/Location")
self.autoUpdateLocation.setChecked(False)
self.autoUpdateLocation.stateChanged.connect(self.updateLocation)
gridLayout.addWidget(self.autoUpdateLocation, 1, 0)
label = QtGui.QLabel("Min Profit:")
self.minProfitSpinBox = QtGui.QSpinBox()
self.minProfitSpinBox.setRange(0, 10000)
self.minProfitSpinBox.setSuffix("cr")
self.minProfitSpinBox.setSingleStep(100)
self.minProfitSpinBox.setAlignment(QtCore.Qt.AlignRight)
minTradeProfit = self.mydb.getConfig('option_dft_minProfit')
if minTradeProfit:
self.minProfitSpinBox.setValue(minTradeProfit)
gridLayout.addWidget(label, 1, 2)
gridLayout.addWidget(self.minProfitSpinBox, 1, 3)
label = QtGui.QLabel("Max Data Age:")
self.maxAgeSpinBox = QtGui.QSpinBox()
self.maxAgeSpinBox.setRange(1, 1000)
self.maxAgeSpinBox.setSuffix("Day")
self.maxAgeSpinBox.setAlignment(QtCore.Qt.AlignRight)
configval = self.mydb.getConfig('option_dft_maxAgeDate')
if configval:
self.maxAgeSpinBox.setValue(configval)
else:
self.maxAgeSpinBox.setValue(14)
gridLayout.addWidget(label, 1, 5)
gridLayout.addWidget(self.maxAgeSpinBox, 1, 6)
label = QtGui.QLabel("Min Stock:")
self.minStockSpinBox = QtGui.QSpinBox()
self.minStockSpinBox.setRange(0, 1000000)
self.minStockSpinBox.setSingleStep(100)
self.minStockSpinBox.setAlignment(QtCore.Qt.AlignRight)
configval = self.mydb.getConfig('option_dft_minStock')
if configval:
self.minStockSpinBox.setValue(configval)
else:
self.minStockSpinBox.setValue(100)
gridLayout.addWidget(label, 2, 2)
gridLayout.addWidget(self.minStockSpinBox, 2, 3)
label = QtGui.QLabel("Max Star Dist:")
self.maxStartDistSpinBox = QtGui.QSpinBox()
self.maxStartDistSpinBox.setRange(10, 7000000)
self.maxStartDistSpinBox.setSuffix("ls")
self.maxStartDistSpinBox.setSingleStep(10)
self.maxStartDistSpinBox.setAlignment(QtCore.Qt.AlignRight)
maxStarDist = self.mydb.getConfig('option_maxStarDist')
if maxStarDist:
self.maxStartDistSpinBox.setValue(maxStarDist)
gridLayout.addWidget(label, 2, 5)
gridLayout.addWidget(self.maxStartDistSpinBox, 2, 6)
fromsystemlabel = QtGui.QLabel("From System:")
self.fromSystem = guitools.LineEdit()
configval = self.mydb.getConfig('option_dft_fromSystem')
if configval:
self.fromSystem.setText(configval)
self.fromSystem.textChanged.connect(self.triggerFromSystemChanged)
fromstationlabel = QtGui.QLabel("Station:")
self.fromStation = guitools.LineEdit()
configval = self.mydb.getConfig('option_dft_fromStation')
if configval:
self.fromStation.setText(configval)
self.fromStation.textChanged.connect(self.triggerFromStationChanged)
tosystemlabel = QtGui.QLabel("To System:")
self.toSystem = guitools.LineEdit()
configval = self.mydb.getConfig('option_dft_toSystem')
if configval:
self.toSystem.setText(configval)
self.toSystem.textChanged.connect(self.triggerToSystemChanged)
tostationlabel = QtGui.QLabel("Station:")
self.toStation = guitools.LineEdit()
configval = self.mydb.getConfig('option_dft_toStation')
if configval:
self.toStation.setText(configval)
self.toStation.textChanged.connect(self.triggerToStationChanged)
self.showOptions = QtGui.QCheckBox("Show Options")
if self.mydb.getConfig("option_dft_showOptions") != 0:
self.showOptions.setChecked(True)
self.showOptions.stateChanged.connect(self.optionsGroupBoxToggleViewAction)
self.searchbutton = QtGui.QPushButton("Search")
self.searchbutton.clicked.connect(self.searchDeals)
self.locationButton = QtGui.QToolButton()
self.locationButton.setIcon(self.guitools.getIconFromsvg("img/location.svg"))
self.locationButton.clicked.connect(self.setCurentLocation)
self.locationButton.setToolTip("Current Location")
self.switchButton = QtGui.QToolButton()
self.switchButton.setIcon(self.guitools.getIconFromsvg("img/switchTopBottom.svg"))
self.switchButton.clicked.connect(self.switchLocations)
self.switchButton.setToolTip("Switch Location")
searchgridLayout = QtGui.QGridLayout()
searchgridLayout.setContentsMargins(2, 2, 2, 2)
searchgridLayout.addWidget(self.locationButton, 0, 0)
searchgridLayout.addWidget(fromsystemlabel, 0, 1)
searchgridLayout.addWidget(self.fromSystem, 0, 2)
searchgridLayout.addWidget(fromstationlabel, 0, 4)
searchgridLayout.addWidget(self.fromStation, 0, 5)
searchgridLayout.addWidget(self.showOptions, 0, 7)
searchgridLayout.addWidget(self.switchButton, 1, 0)
searchgridLayout.addWidget(tosystemlabel, 1, 1)
searchgridLayout.addWidget(self.toSystem, 1, 2)
searchgridLayout.addWidget(tostationlabel, 1, 4)
searchgridLayout.addWidget(self.toStation, 1, 5)
searchgridLayout.addWidget(self.searchbutton, 1, 7)
self.optionsGroupBox = QtGui.QGroupBox("Options")
self.optionsGroupBox.setLayout(gridLayout)
self.searchGroupBox = QtGui.QGroupBox()
self.searchGroupBox.setFlat(True)
self.searchGroupBox.setStyleSheet("""QGroupBox {border:0;margin:0;padding:0;} QGridLayout {border:0;margin:0;padding:0;} margin:0;padding:0;""")
self.searchGroupBox.setLayout(searchgridLayout)
self.listView = QtGui.QTreeView()
self.proxyModel = QtGui.QSortFilterProxyModel()
self.proxyModel.setDynamicSortFilter(True)
self.listView.setRootIsDecorated(False)
self.listView.setAlternatingRowColors(True)
self.listView.setModel(self.proxyModel)
self.listView.setSortingEnabled(True)
self.listView.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection)
self.listView.setSelectionBehavior(QtGui.QAbstractItemView.SelectItems)
self.listView.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
self.listView.customContextMenuRequested.connect(self.dealslistContextMenuEvent)
vGroupBox = QtGui.QGroupBox()
vGroupBox.setFlat(True)
layout = QtGui.QVBoxLayout()
layout.setContentsMargins(6, 6, 6, 6)
layout.addWidget(self.optionsGroupBox)
layout.addWidget(self.searchGroupBox)
layout.addWidget(self.listView)
vGroupBox.setLayout(layout)
self.triggerFromSystemChanged()
self.triggerFromStationChanged()
self.triggerToSystemChanged()
self.triggerToStationChanged()
self.optionsGroupBoxToggleViewAction()
return vGroupBox
def triggerFromSystemChanged(self):
system = self.fromSystem.text()
self.guitools.setStationComplete(system, self.fromStation)
self.searchDeals()
def triggerFromStationChanged(self):
station = self.fromStation.text()
self.guitools.setSystemComplete(station, self.fromSystem)
self.searchDeals()
def triggerToStationChanged(self):
station = self.toStation.text()
self.guitools.setSystemComplete(station, self.toSystem)
self.searchDeals()
def triggerToSystemChanged(self):
system = self.toSystem.text()
self.guitools.setStationComplete(system, self.toStation)
self.searchDeals()
def dealslistContextMenuEvent(self, event):
menu = QtGui.QMenu(self)
menu.addAction(self.copyAct)
menu.addAction(self.markFakeItemAct)
menu.exec_(self.listView.viewport().mapToGlobal(event))
def optionsGroupBoxToggleViewAction(self):
if self.showOptions.isChecked():
self.optionsGroupBox.show()
else:
self.optionsGroupBox.hide()
def createTimer(self):
self.autoUpdateLocationTimer = QtCore.QTimer()
self.autoUpdateLocationTimer.start(1000 * 60)
self.autoUpdateLocationTimer.timeout.connect(self.updateLocation)
def setCurentLocation(self):
self.fromSystem.setText(self.main.location.getLocation())
self.fromStation.setText("")
def updateLocation(self):
if self.autoUpdateLocation.isChecked():
self.autoUpdateLocationTimer.stop()
self.triggerLocationChanged()
self.autoUpdateLocationTimer.start()
else:
print("stop update location timer")
self.autoUpdateLocationTimer.stop()
def triggerLocationChanged(self):
currentLocation = self.main.location.getLocation()
if currentLocation != self.fromSystem.text():
if currentLocation == self.toSystem.text():
self.switchLocations()
else:
self.setCurentLocation()
def createActions(self):
self.markFakeItemAct = QtGui.QAction("Set Item as Fake", self,
statusTip="Set not existing items as Fake and filter it on next search", triggered=self.markFakeItem)
self.copyAct = QtGui.QAction("Copy", self, triggered=self.guitools.copyToClipboard, shortcut=QtGui.QKeySequence.Copy)
def markFakeItem(self):
indexes = self.listView.selectionModel().selectedIndexes()
id = indexes[self.headerList.index("PriceID")].data()
if id:
msg = "Warning: fake items are ignored everywhere and no longer displayed\n"
msg += "\nSet\n From Station: %s\n Item: %s\nas Facke" % (indexes[self.headerList.index("From")].data(), indexes[self.headerList.index("Item")].data())
msgBox = QtGui.QMessageBox(QtGui.QMessageBox.Warning,
"Warning", msg,
QtGui.QMessageBox.NoButton, self)
msgBox.addButton("Save as Facke", QtGui.QMessageBox.AcceptRole)
msgBox.addButton("Cancel", QtGui.QMessageBox.RejectRole)
if msgBox.exec_() == QtGui.QMessageBox.AcceptRole:
print("set %s as fakeprice" % id)
self.main.lockDB()
self.mydb.setFakePrice(id)
self.main.unlockDB()
def switchLocations(self):
fromSystem = self.fromSystem.text()
self.fromSystem.setText(self.toSystem.text())
self.toSystem.setText(fromSystem)
fromStation = self.fromStation.text()
self.fromStation.setText(self.toStation.text())
self.toStation.setText(fromStation)
self.searchDeals()
def saveOptions(self):
self.mydb.setConfig('option_dft_fromSystem', self.fromSystem.text())
self.mydb.setConfig('option_dft_fromStation', self.fromStation.text())
self.mydb.setConfig('option_dft_toSystem', self.toSystem.text())
self.mydb.setConfig('option_dft_toStation', self.toStation.text())
self.mydb.setConfig('option_dft_maxAgeDate', self.maxAgeSpinBox.value())
self.mydb.setConfig('option_dft_minStock', self.minStockSpinBox.value())
self.mydb.setConfig('option_dft_minProfit', self.minProfitSpinBox.value())
self.mydb.setConfig('option_dft_showOptions', self.showOptions.isChecked())
if self.listView.header().count():
sectionPosList = []
for i in range(self.listView.header().count()):
sectionPosList.append(self.listView.header().logicalIndex(i))
sectionPos = ",".join(map(str, sectionPosList))
self.mydb.setConfig('option_dft.header.sectionPos', sectionPos)
def searchDeals(self):
# self.saveOptions()
firstrun = False
if not self.listView.header().count():
firstrun = True
self.headerList = ["PriceID", "Item", "From", "Buy", "Stock", "To", "Sell", "Profit", "FromAge", "ToAge", ""]
model = QtGui.QStandardItemModel(0, len(self.headerList), self)
for x, column in enumerate(self.headerList):
model.setHeaderData(x, QtCore.Qt.Horizontal, column)
fromSystem = self.fromSystem.text()
fromSystemID = self.mydb.getSystemIDbyName(fromSystem)
fromStation = self.fromStation.text()
fromStationID = self.mydb.getStationID(fromSystemID, fromStation)
toSystem = self.toSystem.text()
toSystemID = self.mydb.getSystemIDbyName(toSystem)
toStation = self.toStation.text()
toStationID = self.mydb.getStationID(toSystemID, toStation)
maxAgeDate = datetime.utcnow() - timedelta(days=self.maxAgeSpinBox.value())
minStock = self.minStockSpinBox.value()
startDist = self.maxStartDistSpinBox.value()
if not fromSystemID or not fromStationID or not toSystemID:
return
# self.main.lockDB()
if fromStationID and toStationID:
deals = self.mydb.getDealsFromTo(fromStationID, toStationID, maxAgeDate, minStock)
elif fromStationID and toSystemID:
deals = self.mydb.getDealsFromToSystem(fromStationID, toSystemID, startDist, maxAgeDate, minStock)
else:
deals = []
for deal in deals:
if self.minProfitSpinBox.value() <= deal["Profit"]:
model.insertRow(0)
model.setData(model.index(0, self.headerList.index("PriceID")), deal["priceAid"])
model.setData(model.index(0, self.headerList.index("From")), deal["fromStation"])
model.setData(model.index(0, self.headerList.index("To")), deal["toStation"])
model.setData(model.index(0, self.headerList.index("Item")), deal["itemName"])
model.setData(model.index(0, self.headerList.index("Buy")), deal["StationSell"])
model.item(0, self.headerList.index("Buy")).setTextAlignment(QtCore.Qt.AlignRight)
model.setData(model.index(0, self.headerList.index("Sell")), deal["StationBuy"])
model.item(0, self.headerList.index("Sell")).setTextAlignment(QtCore.Qt.AlignRight)
model.setData(model.index(0, self.headerList.index("Profit")), deal["Profit"])
model.item(0, self.headerList.index("Profit")).setTextAlignment(QtCore.Qt.AlignRight)
model.setData(model.index(0, self.headerList.index("Stock")), deal["Stock"])
model.item(0, self.headerList.index("Stock")).setTextAlignment(QtCore.Qt.AlignRight)
model.setData(model.index(0, self.headerList.index("FromAge")), guitools.convertDateimeToAgeStr(deal["fromAge"]))
model.item(0, self.headerList.index("FromAge")).setTextAlignment(QtCore.Qt.AlignCenter)
model.setData(model.index(0, self.headerList.index("ToAge")), guitools.convertDateimeToAgeStr(deal["toAge"]))
model.item(0, self.headerList.index("ToAge")).setTextAlignment(QtCore.Qt.AlignCenter)
self.listView.setModel(model)
if firstrun:
sectionPos = self.mydb.getConfig('option_dft.header.sectionPos')
if sectionPos:
sectionPosList = sectionPos.strip().split(',')
for i, pos in enumerate(sectionPosList):
self.listView.header().moveSection(self.listView.header().visualIndex(int(pos)), i)
self.listView.sortByColumn(self.headerList.index("Profit"), PySide.QtCore.Qt.SortOrder.DescendingOrder)
self.listView.hideColumn(self.headerList.index("PriceID"))
# self.main.unlockDB()
for i in range(0, len(self.headerList)):
self.listView.resizeColumnToContents(i)
|
amcclead7336/Enterprise_Data_Science_Final
|
venv/lib/python3.8/site-packages/azureml/_workspace/_arm_deployment_orchestrator.py
|
# ---------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# ---------------------------------------------------------
from azureml._base_sdk_common.user_agent import get_user_agent
from azureml._base_sdk_common import _ClientSessionId
from azureml._restclient.constants import RequestHeaders
from azureml._vendor.azure_resources import ResourceManagementClient
class ArmDeploymentOrchestrator(object):
def __init__(self, auth, resource_group_name, subscription_id, deployment_name):
self.auth = auth
self.subscription_id = subscription_id
self.resource_group_name = resource_group_name
self.deployment_name = deployment_name
self.deployments_client = auth._get_service_client(ResourceManagementClient, subscription_id).deployments
self.deployment_operations_client = auth._get_service_client(ResourceManagementClient,
subscription_id).deployment_operations
self.error = None
def _arm_deploy_template(self, template):
"""
Deploys ARM template to create a container registry.
"""
from azureml._vendor.azure_resources.models import DeploymentProperties
properties = DeploymentProperties(template=template, parameters={}, mode='incremental')
headers = {
RequestHeaders.USER_AGENT: get_user_agent(),
RequestHeaders.CLIENT_SESSION_ID: _ClientSessionId,
RequestHeaders.CALL_NAME: self._arm_deploy_template.__name__,
'x-ms-client-amlsdk': None
}
# set the polling frequency to 2 secs so that AzurePoller polls
# for status of our operation every two seconds rather than the default of 30 secs
operation_config = {}
operation_config['long_running_operation_timeout'] = 2
self.poller = self.deployments_client.create_or_update(self.resource_group_name, self.deployment_name,
properties, custom_headers=headers,
operation_config=operation_config)
def _check_deployment_status(self):
try:
headers = {
RequestHeaders.USER_AGENT: get_user_agent(),
RequestHeaders.CLIENT_SESSION_ID: _ClientSessionId,
RequestHeaders.CALL_NAME: self._check_deployment_status.__name__
}
deployment_operations = self.deployment_operations_client.list(self.resource_group_name,
self.deployment_name,
custom_headers=headers)
for deployment_operation in deployment_operations:
properties = deployment_operation.properties
provisioning_state = properties.provisioning_state
target_resource = properties.target_resource
if target_resource is None:
continue
resource_name = target_resource.resource_name
resource_type, previous_state = self.resources_being_deployed[resource_name]
duration = ""
try:
# azure-mgmt-resource=3.0.0 has duration inside properties and is an attribute
duration = properties.duration
except AttributeError:
try:
# azure-mgmt-resource < 3.0.0 has duration inside additional_properties
# and it is a dictionary
duration = properties.additional_properties.get('duration', "")
except Exception:
pass
# duration comes in format: "PT1M56.3454108S"
try:
duration_parts = duration.replace("PT", "").replace("S", "").split("M")
if len(duration_parts) > 1:
duration = (float(duration_parts[0]) * 60) + float(duration_parts[1])
else:
duration = float(duration_parts[0])
duration = round(duration, 2)
except Exception:
duration = ""
pass
if provisioning_state == "Failed" and previous_state != "Failed":
self.resources_being_deployed[resource_name] = (resource_type, provisioning_state)
print("Deployment of {0} with name {1} failed.".format(resource_type, resource_name))
# First time we're seeing this so let the user know it's being deployed
elif properties.provisioning_state == "Running" and previous_state is None:
print("Deploying {0} with name {1}.".format(resource_type, resource_name))
self.resources_being_deployed[resource_name] = (resource_type, provisioning_state)
# If the provisioning has already succeeded but we hadn't seen it Running before
# (really quick deployment - so probably never happening) let user know resource
# is being deployed and then let user know it has been deployed
elif properties.provisioning_state == "Succeeded" and previous_state is None:
print("Deploying {0} with name {1}.".format(resource_type, resource_name))
print("Deployed {0} with name {1}. Took {2} seconds.".format(resource_type, resource_name,
duration))
self.resources_being_deployed[resource_name] = (resource_type, provisioning_state)
# Finally, deployment has succeeded and was previously running, so mark it as finished
elif properties.provisioning_state == "Succeeded" and previous_state != "Succeeded":
print("Deployed {0} with name {1}. Took {2} seconds.".format(resource_type, resource_name,
duration))
self.resources_being_deployed[resource_name] = (resource_type, provisioning_state)
except Exception: # if the call fails for whatever reason, the user doesn't get feedback
pass
|
my5t3ry/loopchat-client
|
src/components/core/lib/actions/addCompositionByURL.js
|
<filename>src/components/core/lib/actions/addCompositionByURL.js
"use strict";
import DAWCoreBuilder from "../DAWCoreBuilder";
DAWCoreBuilder.prototype.addCompositionByURL = function(url, opt ) {
return fetch( url )
.then( res => {
if ( !res.ok ) {
throw "The file is not accessible: " + url;
}
return res.json();
} )
.then(
cmp => this.addComposition( cmp, opt ),
e => { throw e; }
);
};
|
TonyBrewer/OpenHT
|
tests/reserve_bug/src_pers/PersIn2_src.cpp
|
<reponame>TonyBrewer/OpenHT<filename>tests/reserve_bug/src_pers/PersIn2_src.cpp<gh_stars>10-100
#include "Ht.h"
#include "PersIn2.h"
#define BUSY_RETRY(b) {if (b) {HtRetry(); break;}}
#ifndef min
#define min(a,b) (((a)<(b)) ? (a) : (b))
#endif
void
CPersIn2::PersIn2()
{
if (PR_htValid) {
switch (PR_htInst) {
case IN2_ENTER:
S_xIdx = 0;
S_xDimLen = PR_xDimLen;
S_sum = 0;
S_addrB += (uint32_t)(PR_yDimOff * PR_xDimLen * TYPE_SIZE);
HtContinue(IN2_OPEN);
break;
case IN2_OPEN:
// Open read stream B, once
if (!ReadStreamBusy_B())
ReadStreamOpen_B(SR_addrB, PR_xDimLen);
S_inBbusy = true;
HtContinue(IN2_RETURN);
break;
case IN2_RETURN: {
BUSY_RETRY(SR_inBbusy);
BUSY_RETRY(SendReturnBusy_in2());
SendReturn_in2();
}
break;
default:
assert(0);
}
}
if (ReadStreamReady_B())
{
GW_bBuf.write_addr(SR_xIdx);
GW_bBuf = ReadStream_B();
S_xIdx += 1;
S_inBbusy = !ReadStreamLast_B();
}
}
|
cctvzd7/aliyun-openapi-java-sdk
|
aliyun-java-sdk-ecsinc/src/main/java/com/aliyuncs/ecsinc/model/v20160314/InnerQueryConstraintsResponse.java
|
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.aliyuncs.ecsinc.model.v20160314;
import java.util.List;
import com.aliyuncs.AcsResponse;
import com.aliyuncs.ecsinc.transform.v20160314.InnerQueryConstraintsResponseUnmarshaller;
import com.aliyuncs.transform.UnmarshallerContext;
/**
* @author auto create
* @version
*/
public class InnerQueryConstraintsResponse extends AcsResponse {
private String requestId;
private Boolean success;
private String code;
private String message;
private String entityType;
private String entityKey;
private ImageConstraintsModel imageConstraintsModel;
public String getRequestId() {
return this.requestId;
}
public void setRequestId(String requestId) {
this.requestId = requestId;
}
public Boolean getSuccess() {
return this.success;
}
public void setSuccess(Boolean success) {
this.success = success;
}
public String getCode() {
return this.code;
}
public void setCode(String code) {
this.code = code;
}
public String getMessage() {
return this.message;
}
public void setMessage(String message) {
this.message = message;
}
public String getEntityType() {
return this.entityType;
}
public void setEntityType(String entityType) {
this.entityType = entityType;
}
public String getEntityKey() {
return this.entityKey;
}
public void setEntityKey(String entityKey) {
this.entityKey = entityKey;
}
public ImageConstraintsModel getImageConstraintsModel() {
return this.imageConstraintsModel;
}
public void setImageConstraintsModel(ImageConstraintsModel imageConstraintsModel) {
this.imageConstraintsModel = imageConstraintsModel;
}
public static class ImageConstraintsModel {
private String imageId;
private Boolean supportIoOptimized;
private String networkType;
private Cpu cpu;
private Mem mem;
private SysDisk sysDisk;
private DataDisk dataDisk;
private InstanceTypeFamily instanceTypeFamily;
private GpuAmount gpuAmount;
private EniQuantity eniQuantity;
private TcpPortRange tcpPortRange;
private UdpPortRange udpPortRange;
public String getImageId() {
return this.imageId;
}
public void setImageId(String imageId) {
this.imageId = imageId;
}
public Boolean getSupportIoOptimized() {
return this.supportIoOptimized;
}
public void setSupportIoOptimized(Boolean supportIoOptimized) {
this.supportIoOptimized = supportIoOptimized;
}
public String getNetworkType() {
return this.networkType;
}
public void setNetworkType(String networkType) {
this.networkType = networkType;
}
public Cpu getCpu() {
return this.cpu;
}
public void setCpu(Cpu cpu) {
this.cpu = cpu;
}
public Mem getMem() {
return this.mem;
}
public void setMem(Mem mem) {
this.mem = mem;
}
public SysDisk getSysDisk() {
return this.sysDisk;
}
public void setSysDisk(SysDisk sysDisk) {
this.sysDisk = sysDisk;
}
public DataDisk getDataDisk() {
return this.dataDisk;
}
public void setDataDisk(DataDisk dataDisk) {
this.dataDisk = dataDisk;
}
public InstanceTypeFamily getInstanceTypeFamily() {
return this.instanceTypeFamily;
}
public void setInstanceTypeFamily(InstanceTypeFamily instanceTypeFamily) {
this.instanceTypeFamily = instanceTypeFamily;
}
public GpuAmount getGpuAmount() {
return this.gpuAmount;
}
public void setGpuAmount(GpuAmount gpuAmount) {
this.gpuAmount = gpuAmount;
}
public EniQuantity getEniQuantity() {
return this.eniQuantity;
}
public void setEniQuantity(EniQuantity eniQuantity) {
this.eniQuantity = eniQuantity;
}
public TcpPortRange getTcpPortRange() {
return this.tcpPortRange;
}
public void setTcpPortRange(TcpPortRange tcpPortRange) {
this.tcpPortRange = tcpPortRange;
}
public UdpPortRange getUdpPortRange() {
return this.udpPortRange;
}
public void setUdpPortRange(UdpPortRange udpPortRange) {
this.udpPortRange = udpPortRange;
}
public static class Cpu {
private Long minValue;
private Long maxValue;
public Long getMinValue() {
return this.minValue;
}
public void setMinValue(Long minValue) {
this.minValue = minValue;
}
public Long getMaxValue() {
return this.maxValue;
}
public void setMaxValue(Long maxValue) {
this.maxValue = maxValue;
}
}
public static class Mem {
private Long minValue;
private Long maxValue;
public Long getMinValue() {
return this.minValue;
}
public void setMinValue(Long minValue) {
this.minValue = minValue;
}
public Long getMaxValue() {
return this.maxValue;
}
public void setMaxValue(Long maxValue) {
this.maxValue = maxValue;
}
}
public static class SysDisk {
private Long minValue;
private Long maxValue;
public Long getMinValue() {
return this.minValue;
}
public void setMinValue(Long minValue) {
this.minValue = minValue;
}
public Long getMaxValue() {
return this.maxValue;
}
public void setMaxValue(Long maxValue) {
this.maxValue = maxValue;
}
}
public static class DataDisk {
private Long minValue;
private Long maxValue;
public Long getMinValue() {
return this.minValue;
}
public void setMinValue(Long minValue) {
this.minValue = minValue;
}
public Long getMaxValue() {
return this.maxValue;
}
public void setMaxValue(Long maxValue) {
this.maxValue = maxValue;
}
}
public static class InstanceTypeFamily {
private List<String> includeList;
private List<String> excludeList;
public List<String> getIncludeList() {
return this.includeList;
}
public void setIncludeList(List<String> includeList) {
this.includeList = includeList;
}
public List<String> getExcludeList() {
return this.excludeList;
}
public void setExcludeList(List<String> excludeList) {
this.excludeList = excludeList;
}
}
public static class GpuAmount {
private Long minValue;
private Long maxValue;
public Long getMinValue() {
return this.minValue;
}
public void setMinValue(Long minValue) {
this.minValue = minValue;
}
public Long getMaxValue() {
return this.maxValue;
}
public void setMaxValue(Long maxValue) {
this.maxValue = maxValue;
}
}
public static class EniQuantity {
private Long minValue;
private Long maxValue;
public Long getMinValue() {
return this.minValue;
}
public void setMinValue(Long minValue) {
this.minValue = minValue;
}
public Long getMaxValue() {
return this.maxValue;
}
public void setMaxValue(Long maxValue) {
this.maxValue = maxValue;
}
}
public static class TcpPortRange {
private List<String> includeList1;
private List<String> excludeList2;
public List<String> getIncludeList1() {
return this.includeList1;
}
public void setIncludeList1(List<String> includeList1) {
this.includeList1 = includeList1;
}
public List<String> getExcludeList2() {
return this.excludeList2;
}
public void setExcludeList2(List<String> excludeList2) {
this.excludeList2 = excludeList2;
}
}
public static class UdpPortRange {
private List<String> includeList3;
private List<String> excludeList4;
public List<String> getIncludeList3() {
return this.includeList3;
}
public void setIncludeList3(List<String> includeList3) {
this.includeList3 = includeList3;
}
public List<String> getExcludeList4() {
return this.excludeList4;
}
public void setExcludeList4(List<String> excludeList4) {
this.excludeList4 = excludeList4;
}
}
}
@Override
public InnerQueryConstraintsResponse getInstance(UnmarshallerContext context) {
return InnerQueryConstraintsResponseUnmarshaller.unmarshall(this, context);
}
}
|
lucaslehnert/rlutils
|
test/policy/test_UniformRandomPolicy.py
|
#
# Copyright (c) 2020 The rlutils authors
#
# This source code is licensed under an MIT license found in the LICENSE file in the root directory of this project.
#
from unittest import TestCase
class TestUniformRandomPolicy(TestCase):
def test(self):
import rlutils as rl
import numpy as np
from scipy.stats import chisquare
for seed in [1, 12, 123, 1234, 12345]:
rl.set_seeds(seed)
num_samples = 500
num_actions = 4
policy = rl.policy.uniform_random(num_actions)
act_sample = np.array([policy(None) for _ in range(num_samples)])
act_sample_cnts = np.array([np.sum(act_sample == i) for i in range(num_actions)])
act_comp_cnts = (np.ones(num_actions) / num_actions) * num_samples
p_val = chisquare(act_sample_cnts, act_comp_cnts).pvalue
self.assertLessEqual(.1, p_val)
|
tugrulkarakaya/NeVarNeYok
|
app/src/main/java/uk/co/nevarneyok/ux/dialogs/LoginDialogFragment.java
|
<gh_stars>1-10
package uk.co.nevarneyok.ux.dialogs;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.design.widget.TextInputLayout;
import android.support.v4.app.DialogFragment;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.digits.sdk.android.AuthCallback;
import com.digits.sdk.android.DigitsAuthButton;
import com.digits.sdk.android.DigitsException;
import com.digits.sdk.android.DigitsSession;
import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Arrays;
import uk.co.nevarneyok.BuildConfig;
import uk.co.nevarneyok.CONST;
import uk.co.nevarneyok.MyApplication;
import uk.co.nevarneyok.R;
import uk.co.nevarneyok.SettingsMy;
import uk.co.nevarneyok.api.EndPoints;
import uk.co.nevarneyok.api.GsonRequest;
import uk.co.nevarneyok.controllers.UserController;
import uk.co.nevarneyok.entities.User;
import uk.co.nevarneyok.interfaces.LoginDialogInterface;
import uk.co.nevarneyok.listeners.OnSingleClickListener;
import uk.co.nevarneyok.listeners.OnTouchPasswordListener;
import uk.co.nevarneyok.utils.JsonUtils;
import uk.co.nevarneyok.utils.MsgUtils;
import uk.co.nevarneyok.utils.Utils;
import uk.co.nevarneyok.ux.MainActivity;
import timber.log.Timber;
import com.facebook.FacebookSdk;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.FacebookAuthProvider;
import com.twitter.sdk.android.core.TwitterCore;
import static com.facebook.FacebookSdk.getApplicationContext;
/**
* Dialog handles user login, registration and forgotten password function.
*/
public class LoginDialogFragment extends DialogFragment implements FacebookCallback<LoginResult> {
public static final String MSG_RESPONSE = "response: %s";
private CallbackManager callbackManager;
private LoginDialogInterface loginDialogInterface;
private ProgressDialog progressDialog;
private FormState actualFormState = FormState.BASE;
private LinearLayout loginBaseForm;
private LinearLayout loginRegistrationForm;
private LinearLayout loginEmailForm;
private LinearLayout loginEmailForgottenForm;
private TextInputLayout loginRegistrationEmailWrapper;
private TextInputLayout loginRegistrationPasswordWrapper;
private RadioButton loginRegistrationGenderWoman;
private TextInputLayout loginEmailEmailWrapper;
private TextInputLayout loginEmailPasswordWrapper;
private TextInputLayout loginEmailForgottenEmailWrapper;
private FirebaseAuth mAuth;
/**
* Creates dialog which handles user login, registration and forgotten password function.
*
* @param loginDialogInterface listener receiving login/registration results.
* @return new instance of dialog.
*/
public static LoginDialogFragment newInstance(LoginDialogInterface loginDialogInterface) {
LoginDialogFragment frag = new LoginDialogFragment();
frag.loginDialogInterface = loginDialogInterface;
return frag;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setStyle(DialogFragment.STYLE_NO_TITLE, R.style.dialogFullscreen);
progressDialog = Utils.generateProgressDialog(getActivity(), false);
mAuth = FirebaseAuth.getInstance();
}
@Override
public void onStart() {
super.onStart();
Dialog d = getDialog();
if (d != null) {
int width = ViewGroup.LayoutParams.MATCH_PARENT;
int height = ViewGroup.LayoutParams.MATCH_PARENT;
Window window = d.getWindow();
window.setLayout(width, height);
window.setWindowAnimations(R.style.dialogFragmentAnimation);
d.setOnKeyListener(new DialogInterface.OnKeyListener() {
@Override
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
if (BuildConfig.DEBUG)
Timber.d("onKey: %d (Back=%d). Event:%d (Down:%d, Up:%d)", keyCode, KeyEvent.KEYCODE_BACK, event.getAction(),
KeyEvent.ACTION_DOWN, KeyEvent.ACTION_UP);
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
switch (actualFormState) {
case REGISTRATION:
if (event.getAction() == KeyEvent.ACTION_UP) {
setVisibilityOfRegistrationForm(false);
}
return true;
case FORGOTTEN_PASSWORD:
if (event.getAction() == KeyEvent.ACTION_UP) {
setVisibilityOfEmailForgottenForm(false);
}
return true;
case EMAIL:
if (event.getAction() == KeyEvent.ACTION_UP) {
setVisibilityOfEmailForm(false);
}
return true;
default:
return false;
}
}
return false;
}
});
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Timber.d("%s - OnCreateView", this.getClass().getSimpleName());
View view = inflater.inflate(R.layout.dialog_login, container, false);
callbackManager = CallbackManager.Factory.create();
loginBaseForm = (LinearLayout) view.findViewById(R.id.login_base_form);
loginRegistrationForm = (LinearLayout) view.findViewById(R.id.login_registration_form);
loginEmailForm = (LinearLayout) view.findViewById(R.id.login_email_form);
loginEmailForgottenForm = (LinearLayout) view.findViewById(R.id.login_email_forgotten_form);
prepareLoginFormNavigation(view);
prepareInputBoxes(view);
prepareActionButtons(view);
return view;
}
private void prepareInputBoxes(View view) {
// Registration form
loginRegistrationEmailWrapper = (TextInputLayout) view.findViewById(R.id.login_registration_email_wrapper);
loginRegistrationPasswordWrapper = (TextInputLayout) view.findViewById(R.id.login_registration_password_wrapper);
loginRegistrationGenderWoman = (RadioButton) view.findViewById(R.id.login_registration_sex_woman);
EditText registrationPassword = loginRegistrationPasswordWrapper.getEditText();
if (registrationPassword != null) {
registrationPassword.setOnTouchListener(new OnTouchPasswordListener(registrationPassword));
}
// Login email form
loginEmailEmailWrapper = (TextInputLayout) view.findViewById(R.id.login_email_email_wrapper);
EditText loginEmail = loginEmailEmailWrapper.getEditText();
if (loginEmail != null) loginEmail.setText(SettingsMy.getUserEmailHint());
loginEmailPasswordWrapper = (TextInputLayout) view.findViewById(R.id.login_email_password_wrapper);
EditText emailPassword = loginEmailPasswordWrapper.getEditText();
if (emailPassword != null) {
emailPassword.setOnTouchListener(new OnTouchPasswordListener(emailPassword));
emailPassword.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEND || actionId == 124) {
invokeLoginWithEmail();
return true;
}
return false;
}
});
}
loginEmailForgottenEmailWrapper = (TextInputLayout) view.findViewById(R.id.login_email_forgotten_email_wrapper);
EditText emailForgottenPassword = loginEmailForgottenEmailWrapper.getEditText();
if (emailForgottenPassword != null)
emailForgottenPassword.setText(SettingsMy.getUserEmailHint());
// Simple accounts whisperer.
Account[] accounts = AccountManager.get(getActivity()).getAccountsByType("com.google");
String[] addresses = new String[accounts.length];
for (int i = 0; i < accounts.length; i++) {
addresses[i] = accounts[i].name;
Timber.e("Sets autocompleteEmails: %s", accounts[i].name);
}
ArrayAdapter<String> emails = new ArrayAdapter<>(getActivity(), android.R.layout.simple_dropdown_item_1line, addresses);
AutoCompleteTextView textView = (AutoCompleteTextView) view.findViewById(R.id.login_registration_email_text_auto);
textView.setAdapter(emails);
}
private void prepareLoginFormNavigation(View view) {
// Login email
Button loginFormEmailButton = (Button) view.findViewById(R.id.login_form_email_btn);
loginFormEmailButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setVisibilityOfEmailForm(true);
}
});
ImageButton closeEmailBtn = (ImageButton) view.findViewById(R.id.login_email_close_button);
closeEmailBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Slow to display ripple effect
(new Handler()).postDelayed(new Runnable() {
@Override
public void run() {
setVisibilityOfEmailForm(false);
}
}, 200);
}
});
// Registration
TextView loginFormRegistrationButton = (TextView) view.findViewById(R.id.login_form_registration_btn);
loginFormRegistrationButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setVisibilityOfRegistrationForm(true);
}
});
ImageButton closeRegistrationBtn = (ImageButton) view.findViewById(R.id.login_registration_close_button);
closeRegistrationBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Slow to display ripple effect
(new Handler()).postDelayed(new Runnable() {
@Override
public void run() {
setVisibilityOfRegistrationForm(false);
}
}, 200);
}
});
// Email forgotten password
TextView loginEmailFormForgottenButton = (TextView) view.findViewById(R.id.login_email_forgotten_password);
loginEmailFormForgottenButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setVisibilityOfEmailForgottenForm(true);
}
});
ImageButton closeEmailForgottenFormBtn = (ImageButton) view.findViewById(R.id.login_email_forgotten_back_button);
closeEmailForgottenFormBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Slow to display ripple effect
(new Handler()).postDelayed(new Runnable() {
@Override
public void run() {
setVisibilityOfEmailForgottenForm(false);
}
}, 200);
}
});
}
private void prepareActionButtons(View view) {
TextView loginBaseSkip = (TextView) view.findViewById(R.id.login_form_skip);
loginBaseSkip.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// if (loginDialogInterface != null) loginDialogInterface.skipLogin();
dismiss();
}
});
// FB login
Button fbLogin = (Button) view.findViewById(R.id.login_form_facebook);
fbLogin.setOnClickListener(new OnSingleClickListener() {
@Override
public void onSingleClick(View v) {
invokeFacebookLogin();
}
});
Button emailLogin = (Button) view.findViewById(R.id.login_email_confirm);
emailLogin.setOnClickListener(new OnSingleClickListener() {
@Override
public void onSingleClick(View v) {
invokeLoginWithEmail();
}
});
Button registerBtn = (Button) view.findViewById(R.id.login_registration_confirm);
registerBtn.setOnClickListener(new OnSingleClickListener() {
@Override
public void onSingleClick(View v) {
invokeRegisterNewUser();
}
});
Button resetPassword = (Button) view.findViewById(R.id.login_email_forgotten_confirm);
resetPassword.setOnClickListener(new OnSingleClickListener() {
@Override
public void onSingleClick(View v) {
invokeResetPassword();
}
});
}
private void invokeFacebookLogin() {
LoginManager.getInstance().registerCallback(callbackManager, this);
LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("public_profile", "email"));
}
private void handleFacebookAccessToken(final AccessToken token) {
try {
//facebook service to get user info
GraphRequest request = GraphRequest.newMeRequest(token, new GraphRequest.GraphJSONObjectCallback() {
@Override
public void onCompleted(JSONObject fbUser, GraphResponse graphResponse) {
firebaseAccessCheck(token, fbUser);
}
});
Bundle bundle = new Bundle();
bundle.putString("fields", "id,email,name");
request.setParameters(bundle);
request.executeAsync();
} catch (Exception ex) {
handleNonFatalError(getString(R.string.Receiving_facebook_profile_failed), true);
}
}
private void firebaseAccessCheck(AccessToken token, final JSONObject fbUser){
AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
mAuth.signInWithCredential(credential)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
Timber.i("signInWithCredential:onComplete:" + task.isSuccessful());
if (!task.isSuccessful()) {
Timber.e("Error on receiving user profile information.");
Timber.e(task.getException(), "Error: %s", task.getException()==null?"":task.getException().toString());
handleNonFatalError(getString(R.string.Receiving_facebook_profile_failed), true);
}else {
User user = new User(FirebaseAuth.getInstance().getCurrentUser().getUid());
user.setEmail(fbUser.optString("email"));
user.setName(fbUser.optString("name"));
user.setFbId(fbUser.optString("id"));
user.setProviderId(fbUser.optString("id"));
user.setProvider(getString(R.string.providers_facebook));
user.setProfileImageUrl("https://graph.facebook.com/"+user.getProviderId()+"/picture?type=large");
final UserController userController = new UserController(user);
userController.saveAndRetrieveData(new UserController.completion() {
@Override
public void setResult(boolean result, User user) {
if(result){
Timber.d(MSG_RESPONSE, user.toString());
handleUserLogin(user);
} else{
try{
userController.signOut();
} catch(Exception e){
MsgUtils.showToast(getActivity(),MsgUtils.TOAST_TYPE_INTERNAL_ERROR, getString(R.string.Sign_out_error),MsgUtils.ToastLength.SHORT);
}
if (progressDialog != null) progressDialog.cancel();
MsgUtils.showToast(getActivity(), MsgUtils.TOAST_TYPE_MESSAGE, null, MsgUtils.ToastLength.LONG);
}
}
});
}
}
});
}
private void invokeRegisterNewUser() {
hideSoftKeyboard();
if (isRequiredFields(loginRegistrationEmailWrapper, loginRegistrationPasswordWrapper)) {
// SettingsMy.setUserEmailHint(etRegistrationEmail.getText().toString());
try{
registerNewUser(loginRegistrationEmailWrapper.getEditText(), loginRegistrationPasswordWrapper.getEditText());
}catch(Exception ex){
MsgUtils.showToast(getActivity(), MsgUtils.TOAST_TYPE_INTERNAL_ERROR, null, MsgUtils.ToastLength.SHORT);
}
}
}
private void registerNewUser(EditText editTextEmail, EditText editTextPassword) {
SettingsMy.setUserEmailHint(editTextEmail.getText().toString());
progressDialog.show();
try {
mAuth.createUserWithEmailAndPassword(editTextEmail.getText().toString().trim(), editTextPassword.getText().toString().trim())
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful()) {
Timber.d(MSG_RESPONSE, "Parse new user registration failed");
MsgUtils.showToast(task.getException().getLocalizedMessage(), MsgUtils.TOAST_TYPE_MESSAGE, MsgUtils.ToastLength.LONG);
if (progressDialog != null) progressDialog.cancel();
return;
}
final User user = new User(task.getResult().getUser().getUid());
user.setGender(loginRegistrationGenderWoman.isChecked() ? "female" : "male");
user.setProvider(getString(R.string.providers_email));
UserController userController = new UserController(user);
userController.getAuthInfo();
userController.save(new UserController.FirebaseCallResult() {
@Override
public void onComplete(boolean result) {
Timber.d(MSG_RESPONSE, user.toString());
handleUserLogin(user);
}
});
}
});
} catch (Exception ex) {
if (progressDialog != null) progressDialog.cancel();
MsgUtils.showToast(ex.getLocalizedMessage(), MsgUtils.TOAST_TYPE_MESSAGE, MsgUtils.ToastLength.LONG);
}
}
private void invokeLoginWithEmail() {
hideSoftKeyboard();
if (isRequiredFields(loginEmailEmailWrapper, loginEmailPasswordWrapper)) {
try{
logInWithEmail(loginEmailEmailWrapper.getEditText(), loginEmailPasswordWrapper.getEditText());
}catch(Exception ex){
MsgUtils.showToast("", MsgUtils.TOAST_TYPE_INTERNAL_ERROR, MsgUtils.ToastLength.LONG);
}
}
}
private void logInWithEmail(EditText editTextEmail, final EditText editTextPassword) {
SettingsMy.setUserEmailHint(editTextEmail.getText().toString());
String url = String.format(EndPoints.USER_LOGIN_EMAIL, SettingsMy.getActualNonNullShop(getActivity()).getId());
progressDialog.show();
if (BuildConfig.DEBUG) Timber.d("Login user: %s", editTextEmail.getText().toString().trim());
mAuth.signInWithEmailAndPassword(editTextEmail.getText().toString().trim(), editTextPassword.getText().toString().trim())
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
editTextPassword.setText("");
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful()) {
if (progressDialog != null) progressDialog.cancel();
MsgUtils.showToast(task.getException().getLocalizedMessage(), MsgUtils.TOAST_TYPE_MESSAGE, MsgUtils.ToastLength.LONG);
}
else{
//get user details here
User user = new User(FirebaseAuth.getInstance().getCurrentUser().getUid());
final UserController userController = new UserController(user);
userController.retrieveData(new UserController.completion() {
@Override
public void setResult(boolean result, User user) {
if(result){
Timber.d(MSG_RESPONSE, user.toString());
handleUserLogin(user);
} else{
try{
try{
UserController.signOut();
} catch(Exception e){
MsgUtils.showToast(getActivity(),MsgUtils.TOAST_TYPE_INTERNAL_ERROR, getString(R.string.Sign_out_error),MsgUtils.ToastLength.SHORT);
}
if (progressDialog != null) progressDialog.cancel();
MsgUtils.showToast(getActivity(), MsgUtils.TOAST_TYPE_MESSAGE, null, MsgUtils.ToastLength.LONG);
} catch(Exception e){
MsgUtils.showToast(getActivity(),MsgUtils.TOAST_TYPE_INTERNAL_ERROR, getString(R.string.Sign_out_error),MsgUtils.ToastLength.SHORT);
}
}
}
});
}
}
});
}
private void handleUserLogin(User user) {
SettingsMy.setActiveUser(user);
if (progressDialog != null) progressDialog.cancel();
// Invalidate GCM token for new registration with authorized user.
SettingsMy.setTokenSentToServer(false);
if (getActivity() instanceof MainActivity)
((MainActivity) getActivity()).registerGcmOnServer();
MainActivity.invalidateDrawerMenuHeader();
if (loginDialogInterface != null) {
loginDialogInterface.successfulLoginOrRegistration(user);
} else {
Timber.e("Interface is null");
MsgUtils.showToast(getActivity(), MsgUtils.TOAST_TYPE_INTERNAL_ERROR, null, MsgUtils.ToastLength.SHORT);
}
dismiss();
}
private void invokeResetPassword() {
EditText emailForgottenPasswordEmail = loginEmailForgottenEmailWrapper.getEditText();
if (emailForgottenPasswordEmail == null || emailForgottenPasswordEmail.getText().toString().equalsIgnoreCase("")) {
loginEmailForgottenEmailWrapper.setErrorEnabled(true);
loginEmailForgottenEmailWrapper.setError(getString(R.string.Required_field));
} else {
loginEmailForgottenEmailWrapper.setErrorEnabled(false);
try{
resetPassword(emailForgottenPasswordEmail);
}catch(Exception ex){
MsgUtils.showToast("", MsgUtils.TOAST_TYPE_INTERNAL_ERROR, MsgUtils.ToastLength.LONG);
}
}
}
private void resetPassword(EditText emailOfForgottenPassword) {
FirebaseAuth auth = FirebaseAuth.getInstance();
String emailAddress = emailOfForgottenPassword.getText().toString().trim();
progressDialog.show();
auth.sendPasswordResetEmail(emailAddress)
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
Timber.d("Reset password on url success. Response: %s", task.toString());
progressDialog.cancel();
MsgUtils.showToast(getActivity(), MsgUtils.TOAST_TYPE_MESSAGE, getString(R.string.Check_your_email_we_sent_you_an_confirmation_email), MsgUtils.ToastLength.LONG);
setVisibilityOfEmailForgottenForm(false);
}else{
if (progressDialog != null) progressDialog.cancel();
JSONObject json = new JSONObject();
try {
json = new JSONObject(getString(R.string.Send_password_reset_error));
} catch (JSONException e) {
e.printStackTrace();
}
MsgUtils.showMessage(getActivity(), json);
}
}
});
}
private void hideSoftKeyboard() {
if (getActivity() != null && getView() != null) {
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getView().getWindowToken(), 0);
}
}
private void setVisibilityOfRegistrationForm(boolean setVisible) {
if (setVisible) {
actualFormState = FormState.REGISTRATION;
loginBaseForm.setVisibility(View.INVISIBLE);
loginRegistrationForm.setVisibility(View.VISIBLE);
} else {
actualFormState = FormState.BASE;
loginBaseForm.setVisibility(View.VISIBLE);
loginRegistrationForm.setVisibility(View.INVISIBLE);
hideSoftKeyboard();
}
}
private void setVisibilityOfEmailForm(boolean setVisible) {
if (setVisible) {
actualFormState = FormState.EMAIL;
loginBaseForm.setVisibility(View.INVISIBLE);
loginEmailForm.setVisibility(View.VISIBLE);
} else {
actualFormState = FormState.BASE;
loginBaseForm.setVisibility(View.VISIBLE);
loginEmailForm.setVisibility(View.INVISIBLE);
hideSoftKeyboard();
}
}
private void setVisibilityOfEmailForgottenForm(boolean setVisible) {
if (setVisible) {
actualFormState = FormState.FORGOTTEN_PASSWORD;
loginEmailForm.setVisibility(View.INVISIBLE);
loginEmailForgottenForm.setVisibility(View.VISIBLE);
} else {
actualFormState = FormState.EMAIL;
loginEmailForm.setVisibility(View.VISIBLE);
loginEmailForgottenForm.setVisibility(View.INVISIBLE);
}
hideSoftKeyboard();
}
/**
* Check if editTexts are valid view and if user set all required fields.
*
* @return true if ok.
*/
private boolean isRequiredFields(TextInputLayout emailWrapper, TextInputLayout passwordWrapper) {
if (emailWrapper == null || passwordWrapper == null) {
Timber.e(new RuntimeException(), "Called isRequiredFields with null parameters.");
MsgUtils.showToast(getActivity(), MsgUtils.TOAST_TYPE_INTERNAL_ERROR, null, MsgUtils.ToastLength.LONG);
return false;
} else {
EditText email = emailWrapper.getEditText();
EditText password = passwordWrapper.getEditText();
if (email == null || password == null) {
Timber.e(new RuntimeException(), "Called isRequiredFields with null editTexts in wrappers.");
MsgUtils.showToast(getActivity(), MsgUtils.TOAST_TYPE_INTERNAL_ERROR, null, MsgUtils.ToastLength.LONG);
return false;
} else {
boolean isEmail = false;
boolean isPassword = false;
if (email.getText().toString().equalsIgnoreCase("")) {
emailWrapper.setErrorEnabled(true);
emailWrapper.setError(getString(R.string.Required_field));
} else {
emailWrapper.setErrorEnabled(false);
isEmail = true;
}
if (password.getText().toString().equalsIgnoreCase("")) {
passwordWrapper.setErrorEnabled(true);
passwordWrapper.setError(getString(R.string.Required_field));
} else {
passwordWrapper.setErrorEnabled(false);
isPassword = true;
}
if (isEmail && isPassword) {
return true;
} else {
Timber.e("Some fields are required.");
return false;
}
}
}
}
@Override
public void onStop() {
super.onStop();
MyApplication.getInstance().getRequestQueue().cancelAll(CONST.LOGIN_DIALOG_REQUESTS_TAG);
}
@Override
public void onDetach() {
loginDialogInterface = null;
super.onDetach();
}
@Override
public void onSuccess(final LoginResult loginResult) {
Timber.d("FB login success");
if (loginResult == null) {
Timber.e("Fb login succeed with null loginResult.");
handleNonFatalError(getString(R.string.Facebook_login_failed), true);
} else {
Timber.d("Result: %s", loginResult.toString());
handleFacebookAccessToken(loginResult.getAccessToken());
}
}
@Override
public void onCancel() {
Timber.d("Fb login canceled");
}
@Override
public void onError(FacebookException e) {
Timber.e(e, "Fb login error");
handleNonFatalError(getString(R.string.Facebook_login_failed), false);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (callbackManager != null)
callbackManager.onActivityResult(requestCode, resultCode, data);
else {
Timber.d("OnActivityResult, null callbackManager object.");
}
}
/**
* Volley request that sends FB_ID and FB_ACCESS_TOKEN to API
*/
private void verifyUserOnApi(JSONObject userProfileObject, AccessToken fbAccessToken) {
String url = String.format(EndPoints.USER_LOGIN_FACEBOOK, SettingsMy.getActualNonNullShop(getActivity()).getId());
JSONObject jo = new JSONObject();
try {
jo.put(JsonUtils.TAG_FB_ID, userProfileObject.getString("id"));
jo.put(JsonUtils.TAG_FB_ACCESS_TOKEN, fbAccessToken.getToken());
} catch (JSONException e) {
Timber.e(e, "Exception while parsing fb user.");
MsgUtils.showToast(getActivity(), MsgUtils.TOAST_TYPE_INTERNAL_ERROR, null, MsgUtils.ToastLength.LONG);
return;
}
progressDialog.show();
GsonRequest<User> verifyFbUser = new GsonRequest<>(Request.Method.POST, url, jo.toString(), User.class,
new Response.Listener<User>() {
@Override
public void onResponse(@NonNull User response) {
Timber.d(MSG_RESPONSE, response.toString());
handleUserLogin(response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
if (progressDialog != null) progressDialog.cancel();
MsgUtils.logAndShowErrorMessage(getActivity(), error);
try{
UserController.signOut();
} catch(Exception e){
MsgUtils.showToast(getActivity(),MsgUtils.TOAST_TYPE_INTERNAL_ERROR, getString(R.string.Sign_out_error),MsgUtils.ToastLength.SHORT);
}
}
}, getFragmentManager(), null);
verifyFbUser.setRetryPolicy(MyApplication.getDefaultRetryPolice());
verifyFbUser.setShouldCache(false);
MyApplication.getInstance().addToRequestQueue(verifyFbUser, CONST.LOGIN_DIALOG_REQUESTS_TAG);
}
/**
* Handle errors, when user have identity at least.
* Show error message to user.
*/
private void handleNonFatalError(String message, boolean logoutFromFb) {
if (logoutFromFb) {
try{
UserController.signOut();
} catch(Exception e){
MsgUtils.showToast(getActivity(),MsgUtils.TOAST_TYPE_INTERNAL_ERROR, getString(R.string.Sign_out_error),MsgUtils.ToastLength.SHORT);
}
}
if (getActivity() != null)
MsgUtils.showToast(getActivity(), MsgUtils.TOAST_TYPE_MESSAGE, message, MsgUtils.ToastLength.LONG);
}
private enum FormState {
BASE, REGISTRATION, EMAIL, FORGOTTEN_PASSWORD
}
}
|
jiangjianli/qianyueweb
|
vue-element-admin/node_modules/echarts/src/component/tooltip/TooltipModel.js
|
<reponame>jiangjianli/qianyueweb
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import * as echarts from '../../echarts';
export default echarts.extendComponentModel({
type: 'tooltip',
dependencies: ['axisPointer'],
defaultOption: {
zlevel: 0,
z: 8,
show: true,
// tooltip主体内容
showContent: true,
// 'trigger' only works on coordinate system.
// 'item' | 'axis' | 'none'
trigger: 'item',
// 'click' | 'mousemove' | 'none'
triggerOn: 'mousemove|click',
alwaysShowContent: false,
displayMode: 'single', // 'single' | 'multipleByCoordSys'
// 位置 {Array} | {Function}
// position: null
// Consider triggered from axisPointer handle, verticalAlign should be 'middle'
// align: null,
// verticalAlign: null,
// 是否约束 content 在 viewRect 中。默认 false 是为了兼容以前版本。
confine: false,
// 内容格式器:{string}(Template) ¦ {Function}
// formatter: null
showDelay: 0,
// 隐藏延迟,单位ms
hideDelay: 100,
// 动画变换时间,单位s
transitionDuration: 0.4,
enterable: false,
// 提示背景颜色,默认为透明度为0.7的黑色
backgroundColor: 'rgba(50,50,50,0.7)',
// 提示边框颜色
borderColor: '#333',
// 提示边框圆角,单位px,默认为4
borderRadius: 4,
// 提示边框线宽,单位px,默认为0(无边框)
borderWidth: 0,
// 提示内边距,单位px,默认各方向内边距为5,
// 接受数组分别设定上右下左边距,同css
padding: 5,
// Extra css text
extraCssText: '',
// 坐标轴指示器,坐标轴触发有效
axisPointer: {
// 默认为直线
// 可选为:'line' | 'shadow' | 'cross'
type: 'line',
// type 为 line 的时候有效,指定 tooltip line 所在的轴,可选
// 可选 'x' | 'y' | 'angle' | 'radius' | 'auto'
// 默认 'auto',会选择类型为 category 的轴,对于双数值轴,笛卡尔坐标系会默认选择 x 轴
// 极坐标系会默认选择 angle 轴
axis: 'auto',
animation: 'auto',
animationDurationUpdate: 200,
animationEasingUpdate: 'exponentialOut',
crossStyle: {
color: '#999',
width: 1,
type: 'dashed',
// TODO formatter
textStyle: {}
}
// lineStyle and shadowStyle should not be specified here,
// otherwise it will always override those styles on option.axisPointer.
},
textStyle: {
color: '#fff',
fontSize: 14
}
}
});
|
stromnet/norbert
|
network/src/main/scala/com/linkedin/norbert/network/server/NetworkServer.scala
|
<reponame>stromnet/norbert
/*
* Copyright 2009-2010 LinkedIn, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.linkedin.norbert
package network
package server
import java.util.concurrent.atomic.AtomicBoolean
import java.net.InetAddress
import netty.{NettyNetworkServer, NetworkServerConfig}
import cluster._
import logging.Logging
object NetworkServer {
def apply(config: NetworkServerConfig): NetworkServer = new NettyNetworkServer(config)
}
trait NetworkServer extends Logging {
this: ClusterClientComponent with ClusterIoServerComponent with MessageExecutorComponent with MessageHandlerRegistryComponent =>
@volatile private var markAvailableWhenConnected = true
private var listenerKey: ClusterListenerKey = _
private var nodeOption: Option[Node] = None
private val shutdownSwitch = new AtomicBoolean
/**
* Registers a message handler with the <code>NetworkServer</code>. The <code>NetworkServer</code> will call the
* provided handler when an incoming request of type <code>requestMessage</code> is received. If a response is
* expected then a response message should also be provided.
*
* @param requestMessage an instance of an incoming request message
* @param responseMessage an instance of an outgoing response message
* @param handler the function to call when an incoming message of type <code>requestMessage</code> is recieved
*/
def registerHandler[RequestMsg, ResponseMsg](handler: RequestMsg => ResponseMsg)
(implicit is: InputSerializer[RequestMsg, ResponseMsg], os: OutputSerializer[RequestMsg, ResponseMsg]) {
messageHandlerRegistry.registerHandler(handler)
}
def addFilters(filters: List[Filter]) : Unit = messageExecutor.addFilters(filters)
/**
* Binds the network server instance to the wildcard address and the port of the <code>Node</code> identified
* by the unique URL (machine and port) of the machine. It will look through all nodes in zookeeper to identify it's
* own nodeId. There may be issues with this for machines with multiple interfaces, etc as it uses InetAddress.getLocalHost.
*
* @throws InvalidNodeException thrown if no <code>Node</code> with the specified machine's URL is configured in zookeeper
* @throws NetworkingException thrown if unable to bind
*/
def bindByPort(port: Int): Unit = bindByUrl(InetAddress.getLocalHost.getCanonicalHostName, port)
/**
* Binds the network server instance to the wildcard address and the port of the <code>Node</code> identified
* by the unique URL (machine and port) of the machine. It will look through all nodes in zookeeper to identify it's
* own nodeId.
*
* @throws InvalidNodeException thrown if no <code>Node</code> with the specified machine's URL is configured in zookeeper
* @throws NetworkingException thrown if unable to bind
*/
def bindByUrl(hostname: String, port: Int, markAvailable: Boolean = true): Unit = {
log.debug("Ensuring ClusterClient is started")
clusterClient.start
clusterClient.awaitConnectionUninterruptibly
val node = clusterClient.nodeByUrl(hostname, port).getOrElse(throw new InvalidNodeException("No node for URL: %s:%d exists".format(hostname, port)))
//Bind with that node
bindNode(node, markAvailable)
}
def bindOrCreateByUrl(hostname: String, port: Int, partitionBuilder:Option[Int => Set[Int]] = None): Unit = {
try {
bindByUrl(hostname, port)
} catch {
case ex:InvalidNodeException =>
/* This node doesn't exist so we need to create it */
clusterClient.addNodeByUrl(hostname, port, partitionBuilder)
bindByUrl(hostname, port)
}
}
/**
* Binds the network server instance to the wildcard address and the port of the <code>Node</code> identified
* by the provided nodeId and automatically marks the <code>Node</code> available in the cluster. A
* <code>Node</code>'s url must be specified in the format hostname:port.
*
* @param nodeId the id of the <code>Node</code> this server is associated with.
*
* @throws InvalidNodeException thrown if no <code>Node</code> with the specified <code>nodeId</code> exists
* @throws NetworkingException thrown if unable to bind
*/
def bind(nodeId: Int): Unit = bind(nodeId, true)
/**
* Binds the network server instance to the wildcard address and the port of the <code>Node</code> identified
* by the provided nodeId and marks the <code>Node</code> available in the cluster if <code>markAvailable</code> is true. A
* <code>Node</code>'s url must be specified in the format hostname:port.
*
* @param nodeId the id of the <code>Node</code> this server is associated with.
* @param markAvailable if true marks the <code>Node</code> identified by <code>nodeId</code> as available after binding to
* the port
*
* @throws InvalidNodeException thrown if no <code>Node</code> with the specified <code>nodeId</code> exists or if the
* format of the <code>Node</code>'s url isn't hostname:port
* @throws NetworkingException thrown if unable to bind
*/
def bind(nodeId: Int, markAvailable: Boolean, initialCapability: Long = 0L): Unit = doIfNotShutdown {
if (nodeOption.isDefined) throw new NetworkingException("Attempt to bind an already bound NetworkServer")
log.info("Starting NetworkServer...")
log.debug("Ensuring ClusterClient is started")
clusterClient.start
clusterClient.awaitConnectionUninterruptibly
val node = clusterClient.nodeWithId(nodeId).getOrElse(throw new InvalidNodeException("No node with id %d exists".format(nodeId)))
bindNode(node, markAvailable, initialCapability)
}
/**
* Binds the network server instance to the wildcard address and the port of the <code>Node</code> identified
* by the node passed in. The node will need to be found through other means first. Note: there is no validation to
* check the validity of the node, that should be done before calling this method.
*
* @throws NetworkingException thrown if unable to bind
*/
private def bindNode(node: Node, markAvailable: Boolean, initialCapability: Long = 0L): Unit = doIfNotShutdown {
clusterIoServer.bind(node, true)
nodeOption = Some(node)
markAvailableWhenConnected = markAvailable
log.debug("Registering with ClusterClient")
listenerKey = clusterClient.addListener(new ClusterListener {
def handleClusterEvent(event: ClusterEvent) = event match {
case ClusterEvents.Connected(_) =>
if (markAvailableWhenConnected) {
log.debug("Marking node with id %d available".format(node.id))
try {
clusterClient.markNodeUnavailable(node.id)
clusterClient.markNodeAvailable(node.id, initialCapability)
} catch {
case ex: ClusterException => log.error(ex, "Unable to mark node available")
}
}
case ClusterEvents.Shutdown => doShutdown(true)
case _ => // do nothing
}
})
log.info("NetworkServer started")
}
/**
* Returns the <code>Node</code> associated with this server.
*
* @return the <code>Node</code> associated with this server
*/
def myNode: Node = doIfNotShutdown { nodeOption.getOrElse(throw new NetworkServerNotBoundException) }
/**
* Marks the node available in the cluster if the server is bound with initial capability string as 0L
*/
def markAvailable : Unit =markAvailable(0L)
/**
* Marks the node available in the cluster if the server is bound with the initial capability string associated
*/
def markAvailable(initialCapability: Long = 0L): Unit = {
clusterClient.markNodeAvailable(myNode.id, initialCapability)
markAvailableWhenConnected = true
}
/**
* Marks the node unavailable in the cluster if bound.
*/
def markUnavailable: Unit = {
clusterClient.markNodeUnavailable(myNode.id)
markAvailableWhenConnected = false
}
def setNodeCapabiity(capability: Long): Unit = {
clusterClient.setNodeCapability(myNode.id, capability)
}
/**
* Shuts down the network server. This results in unbinding from the port, closing the child sockets, and marking the node unavailable.
*/
def shutdown: Unit = doShutdown(false)
private def doShutdown(fromCluster: Boolean) {
if (shutdownSwitch.compareAndSet(false, true)) {
log.info("Shutting down NetworkServer for %s...".format(nodeOption.map(_.toString).getOrElse("[unbound]")))
if (!fromCluster) {
nodeOption.foreach { node =>
try {
log.debug("Unregistering from ClusterClient")
clusterClient.removeListener(listenerKey)
log.debug("Marking %s unavailable".format(node))
clusterClient.markNodeUnavailable(node.id)
} catch {
case ex: ClusterShutdownException => // cluster already shut down, ignore
}
}
}
log.debug("Closing opened sockets")
clusterIoServer.shutdown
log.info("NetworkServer shut down")
}
}
private def doIfNotShutdown[T](block: => T): T = if (shutdownSwitch.get) throw new NetworkShutdownException else block
}
|
cse-library/koha
|
intranet/htdocs/intranet-tmpl/prog/js/datatables.js
|
// These default options are for translation but can be used
// for any other datatables settings
// MSG_DT_* variables comes from datatables.inc
// To use it, write:
// $("#table_id").dataTable($.extend(true, {}, dataTableDefaults, {
// // other settings
// } ) );
var dataTablesDefaults = {
"oLanguage": {
"oPaginate": {
"sFirst" : window.MSG_DT_FIRST || "First",
"sLast" : window.MSG_DT_LAST || "Last",
"sNext" : window.MSG_DT_NEXT || "Next",
"sPrevious" : window.MSG_DT_PREVIOUS || "Previous"
},
"sEmptyTable" : window.MSG_DT_EMPTY_TABLE || "No data available in table",
"sInfo" : window.MSG_DT_INFO || "Showing _START_ to _END_ of _TOTAL_ entries",
"sInfoEmpty" : window.MSG_DT_INFO_EMPTY || "No entries to show",
"sInfoFiltered" : window.MSG_DT_INFO_FILTERED || "(filtered from _MAX_ total entries)",
"sLengthMenu" : window.MSG_DT_LENGTH_MENU || "Show _MENU_ entries",
"sLoadingRecords" : window.MSG_DT_LOADING_RECORDS || "Loading...",
"sProcessing" : window.MSG_DT_PROCESSING || "Processing...",
"sSearch" : window.MSG_DT_SEARCH || "Search:",
"sZeroRecords" : window.MSG_DT_ZERO_RECORDS || "No matching records found",
buttons: {
"copyTitle" : window.MSG_DT_COPY_TITLE || "Copy to clipboard",
"copyKeys" : window.MSG_DT_COPY_KEYS || "Press <i>ctrl</i> or <i>⌘</i> + <i>C</i> to copy the table data<br>to your system clipboard.<br><br>To cancel, click this message or press escape.",
"copySuccess": {
_: window.MSG_DT_COPY_SUCCESS_X || "Copied %d rows to clipboard",
1: window.MSG_DT_COPY_SUCCESS_ONE || "Copied one row to clipboard"
}
}
},
"dom": '<"top pager"ilpfB>tr<"bottom pager"ip>',
"buttons": [],
"aLengthMenu": [[10, 20, 50, 100, -1], [10, 20, 50, 100, window.MSG_DT_ALL || "All"]],
"iDisplayLength": 20
};
// Return an array of string containing the values of a particular column
$.fn.dataTableExt.oApi.fnGetColumnData = function ( oSettings, iColumn, bUnique, bFiltered, bIgnoreEmpty ) {
// check that we have a column id
if ( typeof iColumn == "undefined" ) return new Array();
// by default we only wany unique data
if ( typeof bUnique == "undefined" ) bUnique = true;
// by default we do want to only look at filtered data
if ( typeof bFiltered == "undefined" ) bFiltered = true;
// by default we do not wany to include empty values
if ( typeof bIgnoreEmpty == "undefined" ) bIgnoreEmpty = true;
// list of rows which we're going to loop through
var aiRows;
// use only filtered rows
if (bFiltered == true) aiRows = oSettings.aiDisplay;
// use all rows
else aiRows = oSettings.aiDisplayMaster; // all row numbers
// set up data array
var asResultData = new Array();
for (var i=0,c=aiRows.length; i<c; i++) {
iRow = aiRows[i];
var aData = this.fnGetData(iRow);
var sValue = aData[iColumn];
// ignore empty values?
if (bIgnoreEmpty == true && sValue.length == 0) continue;
// ignore unique values?
else if (bUnique == true && jQuery.inArray(sValue, asResultData) > -1) continue;
// else push the value onto the result data array
else asResultData.push(sValue);
}
return asResultData;
}
// List of unbind keys (Ctrl, Alt, Direction keys, etc.)
// These keys must not launch filtering
var blacklist_keys = new Array(0, 16, 17, 18, 37, 38, 39, 40);
// Set a filtering delay for global search field
jQuery.fn.dataTableExt.oApi.fnSetFilteringDelay = function ( oSettings, iDelay ) {
/*
* Inputs: object:oSettings - dataTables settings object - automatically given
* integer:iDelay - delay in milliseconds
* Usage: $('#example').dataTable().fnSetFilteringDelay(250);
* Author: <NAME> (www.zygimantas.com) and <NAME>
* License: GPL v2 or BSD 3 point style
* Contact: zygimantas.berziunas /AT\ hotmail.com
*/
var
_that = this,
iDelay = (typeof iDelay == 'undefined') ? 250 : iDelay;
this.each( function ( i ) {
$.fn.dataTableExt.iApiIndex = i;
var
$this = this,
oTimerId = null,
sPreviousSearch = null,
anControl = $( 'input', _that.fnSettings().aanFeatures.f );
anControl.unbind( 'keyup.DT' ).bind( 'keyup.DT', function(event) {
var $$this = $this;
if (blacklist_keys.indexOf(event.keyCode) != -1) {
return this;
}else if ( event.keyCode == '13' ) {
$.fn.dataTableExt.iApiIndex = i;
_that.fnFilter( $(this).val() );
} else {
if (sPreviousSearch === null || sPreviousSearch != anControl.val()) {
window.clearTimeout(oTimerId);
sPreviousSearch = anControl.val();
oTimerId = window.setTimeout(function() {
$.fn.dataTableExt.iApiIndex = i;
_that.fnFilter( anControl.val() );
}, iDelay);
}
}
});
return this;
} );
return this;
}
// Add a filtering delay on general search and on all input (with a class 'filter')
jQuery.fn.dataTableExt.oApi.fnAddFilters = function ( oSettings, sClass, iDelay ) {
var table = this;
this.fnSetFilteringDelay(iDelay);
var filterTimerId = null;
$(table).find("input."+sClass).keyup(function(event) {
if (blacklist_keys.indexOf(event.keyCode) != -1) {
return this;
}else if ( event.keyCode == '13' ) {
table.fnFilter( $(this).val(), $(this).attr('data-column_num') );
} else {
window.clearTimeout(filterTimerId);
var input = this;
filterTimerId = window.setTimeout(function() {
table.fnFilter($(input).val(), $(input).attr('data-column_num'));
}, iDelay);
}
});
$(table).find("select."+sClass).on('change', function() {
table.fnFilter($(this).val(), $(this).attr('data-column_num'));
});
}
// Sorting on html contains
// <a href="foo.pl">bar</a> sort on 'bar'
function dt_overwrite_html_sorting_localeCompare() {
jQuery.fn.dataTableExt.oSort['html-asc'] = function(a,b) {
a = a.replace(/<.*?>/g, "").replace(/\s+/g, " ");
b = b.replace(/<.*?>/g, "").replace(/\s+/g, " ");
if (typeof(a.localeCompare == "function")) {
return a.localeCompare(b);
} else {
return (a > b) ? 1 : ((a < b) ? -1 : 0);
}
};
jQuery.fn.dataTableExt.oSort['html-desc'] = function(a,b) {
a = a.replace(/<.*?>/g, "").replace(/\s+/g, " ");
b = b.replace(/<.*?>/g, "").replace(/\s+/g, " ");
if(typeof(b.localeCompare == "function")) {
return b.localeCompare(a);
} else {
return (b > a) ? 1 : ((b < a) ? -1 : 0);
}
};
jQuery.fn.dataTableExt.oSort['num-html-asc'] = function(a,b) {
var x = a.replace( /<.*?>/g, "" );
var y = b.replace( /<.*?>/g, "" );
x = parseFloat( x );
y = parseFloat( y );
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
};
jQuery.fn.dataTableExt.oSort['num-html-desc'] = function(a,b) {
var x = a.replace( /<.*?>/g, "" );
var y = b.replace( /<.*?>/g, "" );
x = parseFloat( x );
y = parseFloat( y );
return ((x < y) ? 1 : ((x > y) ? -1 : 0));
};
}
$.fn.dataTableExt.oPagination.four_button = {
/*
* Function: oPagination.four_button.fnInit
* Purpose: Initalise dom elements required for pagination with a list of the pages
* Returns: -
* Inputs: object:oSettings - dataTables settings object
* node:nPaging - the DIV which contains this pagination control
* function:fnCallbackDraw - draw function which must be called on update
*/
"fnInit": function ( oSettings, nPaging, fnCallbackDraw )
{
nFirst = document.createElement( 'span' );
nPrevious = document.createElement( 'span' );
nNext = document.createElement( 'span' );
nLast = document.createElement( 'span' );
nFirst.appendChild( document.createTextNode( oSettings.oLanguage.oPaginate.sFirst ) );
nPrevious.appendChild( document.createTextNode( oSettings.oLanguage.oPaginate.sPrevious ) );
nNext.appendChild( document.createTextNode( oSettings.oLanguage.oPaginate.sNext ) );
nLast.appendChild( document.createTextNode( oSettings.oLanguage.oPaginate.sLast ) );
nFirst.className = "paginate_button first";
nPrevious.className = "paginate_button previous";
nNext.className="paginate_button next";
nLast.className = "paginate_button last";
nPaging.appendChild( nFirst );
nPaging.appendChild( nPrevious );
nPaging.appendChild( nNext );
nPaging.appendChild( nLast );
$(nFirst).click( function () {
oSettings.oApi._fnPageChange( oSettings, "first" );
fnCallbackDraw( oSettings );
} );
$(nPrevious).click( function() {
oSettings.oApi._fnPageChange( oSettings, "previous" );
fnCallbackDraw( oSettings );
} );
$(nNext).click( function() {
oSettings.oApi._fnPageChange( oSettings, "next" );
fnCallbackDraw( oSettings );
} );
$(nLast).click( function() {
oSettings.oApi._fnPageChange( oSettings, "last" );
fnCallbackDraw( oSettings );
} );
/* Disallow text selection */
$(nFirst).bind( 'selectstart', function () { return false; } );
$(nPrevious).bind( 'selectstart', function () { return false; } );
$(nNext).bind( 'selectstart', function () { return false; } );
$(nLast).bind( 'selectstart', function () { return false; } );
},
/*
* Function: oPagination.four_button.fnUpdate
* Purpose: Update the list of page buttons shows
* Returns: -
* Inputs: object:oSettings - dataTables settings object
* function:fnCallbackDraw - draw function which must be called on update
*/
"fnUpdate": function ( oSettings, fnCallbackDraw )
{
if ( !oSettings.aanFeatures.p )
{
return;
}
/* Loop over each instance of the pager */
var an = oSettings.aanFeatures.p;
for ( var i=0, iLen=an.length ; i<iLen ; i++ )
{
var buttons = an[i].getElementsByTagName('span');
if ( oSettings._iDisplayStart === 0 )
{
buttons[0].className = "paginate_disabled_previous";
buttons[1].className = "paginate_disabled_previous";
}
else
{
buttons[0].className = "paginate_enabled_previous";
buttons[1].className = "paginate_enabled_previous";
}
if ( oSettings.fnDisplayEnd() == oSettings.fnRecordsDisplay() )
{
buttons[2].className = "paginate_disabled_next";
buttons[3].className = "paginate_disabled_next";
}
else
{
buttons[2].className = "paginate_enabled_next";
buttons[3].className = "paginate_enabled_next";
}
}
}
};
$.fn.dataTableExt.oSort['num-html-asc'] = function(a,b) {
var x = a.replace( /<.*?>/g, "" );
var y = b.replace( /<.*?>/g, "" );
x = parseFloat( x );
y = parseFloat( y );
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
};
$.fn.dataTableExt.oSort['num-html-desc'] = function(a,b) {
var x = a.replace( /<.*?>/g, "" );
var y = b.replace( /<.*?>/g, "" );
x = parseFloat( x );
y = parseFloat( y );
return ((x < y) ? 1 : ((x > y) ? -1 : 0));
};
(function() {
/*
* Natural Sort algorithm for Javascript - Version 0.7 - Released under MIT license
* Author: <NAME> (based on chunking idea from <NAME>)
* Contributors: <NAME> (mgrier.com), <NAME>, <NAME>, guillermo
* See: http://js-naturalsort.googlecode.com/svn/trunk/naturalSort.js
*/
function naturalSort (a, b) {
var re = /(^-?[0-9]+(\.?[0-9]*)[df]?e?[0-9]?$|^0x[0-9a-f]+$|[0-9]+)/gi,
sre = /(^[ ]*|[ ]*$)/g,
dre = /(^([\w ]+,?[\w ]+)?[\w ]+,?[\w ]+\d+:\d+(:\d+)?[\w ]?|^\d{1,4}[\/\-]\d{1,4}[\/\-]\d{1,4}|^\w+, \w+ \d+, \d{4})/,
hre = /^0x[0-9a-f]+$/i,
ore = /^0/,
// convert all to strings and trim()
x = a.toString().replace(sre, '') || '',
y = b.toString().replace(sre, '') || '',
// chunk/tokenize
xN = x.replace(re, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0'),
yN = y.replace(re, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0'),
// numeric, hex or date detection
xD = parseInt(x.match(hre), 10) || (xN.length != 1 && x.match(dre) && Date.parse(x)),
yD = parseInt(y.match(hre), 10) || xD && y.match(dre) && Date.parse(y) || null;
// first try and sort Hex codes or Dates
if (yD)
if ( xD < yD ) return -1;
else if ( xD > yD ) return 1;
// natural sorting through split numeric strings and default strings
for(var cLoc=0, numS=Math.max(xN.length, yN.length); cLoc < numS; cLoc++) {
// find floats not starting with '0', string or 0 if not defined (Clint Priest)
var oFxNcL = !(xN[cLoc] || '').match(ore) && parseFloat(xN[cLoc]) || xN[cLoc] || 0;
var oFyNcL = !(yN[cLoc] || '').match(ore) && parseFloat(yN[cLoc]) || yN[cLoc] || 0;
// handle numeric vs string comparison - number < string - (<NAME>)
if (isNaN(oFxNcL) !== isNaN(oFyNcL)) return (isNaN(oFxNcL)) ? 1 : -1;
// rely on string comparison if different types - i.e. '02' < 2 != '02' < '2'
else if (typeof oFxNcL !== typeof oFyNcL) {
oFxNcL += '';
oFyNcL += '';
}
if (oFxNcL < oFyNcL) return -1;
if (oFxNcL > oFyNcL) return 1;
}
return 0;
}
jQuery.extend( jQuery.fn.dataTableExt.oSort, {
"natural-asc": function ( a, b ) {
return naturalSort(a,b);
},
"natural-desc": function ( a, b ) {
return naturalSort(a,b) * -1;
}
} );
}());
/* Plugin to allow sorting on data stored in a span's title attribute
*
* Ex: <td><span title="[% ISO_date %]">[% formatted_date %]</span></td>
*
* In DataTables config:
* "aoColumns": [
* { "sType": "title-string" },
* ]
* http://datatables.net/plug-ins/sorting#hidden_title_string
*/
jQuery.extend( jQuery.fn.dataTableExt.oSort, {
"title-string-pre": function ( a ) {
return a.match(/title="(.*?)"/)[1].toLowerCase();
},
"title-string-asc": function ( a, b ) {
return ((a < b) ? -1 : ((a > b) ? 1 : 0));
},
"title-string-desc": function ( a, b ) {
return ((a < b) ? 1 : ((a > b) ? -1 : 0));
}
} );
/* Plugin to allow sorting on numeric data stored in a span's title attribute
*
* Ex: <td><span title="[% decimal_number_that_JS_parseFloat_accepts %]">
* [% formatted currency %]
* </span></td>
*
* In DataTables config:
* "aoColumns": [
* { "sType": "title-numeric" },
* ]
* http://datatables.net/plug-ins/sorting#hidden_title
*/
jQuery.extend( jQuery.fn.dataTableExt.oSort, {
"title-numeric-pre": function ( a ) {
var x = a.match(/title="*(-?[0-9\.]+)/)[1];
return parseFloat( x );
},
"title-numeric-asc": function ( a, b ) {
return ((a < b) ? -1 : ((a > b) ? 1 : 0));
},
"title-numeric-desc": function ( a, b ) {
return ((a < b) ? 1 : ((a > b) ? -1 : 0));
}
} );
(function() {
/* Plugin to allow text sorting to ignore articles
*
* In DataTables config:
* "aoColumns": [
* { "sType": "anti-the" },
* ]
* Based on the plugin found here:
* http://datatables.net/plug-ins/sorting#anti_the
* Modified to exclude HTML tags from sorting
* Extended to accept a string of space-separated articles
* from a configuration file (in English, "a," "an," and "the")
*/
if(CONFIG_EXCLUDE_ARTICLES_FROM_SORT){
var articles = CONFIG_EXCLUDE_ARTICLES_FROM_SORT.split(" ");
var rpattern = "";
for(i=0;i<articles.length;i++){
rpattern += "^" + articles[i] + " ";
if(i < articles.length - 1){ rpattern += "|"; }
}
var re = new RegExp(rpattern, "i");
}
jQuery.extend( jQuery.fn.dataTableExt.oSort, {
"anti-the-pre": function ( a ) {
var x = String(a).replace( /<[\s\S]*?>/g, "" );
var y = x.trim();
var z = y.replace(re, "").toLowerCase();
return z;
},
"anti-the-asc": function ( a, b ) {
return ((a < b) ? -1 : ((a > b) ? 1 : 0));
},
"anti-the-desc": function ( a, b ) {
return ((a < b) ? 1 : ((a > b) ? -1 : 0));
}
});
}());
// Remove string between NSB NSB characters
$.fn.dataTableExt.oSort['nsb-nse-asc'] = function(a,b) {
var pattern = new RegExp("\x88.*\x89");
a = a.replace(pattern, "");
b = b.replace(pattern, "");
return (a > b) ? 1 : ((a < b) ? -1 : 0);
}
$.fn.dataTableExt.oSort['nsb-nse-desc'] = function(a,b) {
var pattern = new RegExp("\x88.*\x89");
a = a.replace(pattern, "");
b = b.replace(pattern, "");
return (b > a) ? 1 : ((b < a) ? -1 : 0);
}
/* Define two custom functions (asc and desc) for basket callnumber sorting */
jQuery.fn.dataTableExt.oSort['callnumbers-asc'] = function(x,y) {
var x_array = x.split("<div>");
var y_array = y.split("<div>");
/* Pop the first elements, they are empty strings */
x_array.shift();
y_array.shift();
x_array = jQuery.map( x_array, function( a ) {
return parse_callnumber( a );
});
y_array = jQuery.map( y_array, function( a ) {
return parse_callnumber( a );
});
x_array.sort();
y_array.sort();
x = x_array.shift();
y = y_array.shift();
if ( !x ) { x = ""; }
if ( !y ) { y = ""; }
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
};
jQuery.fn.dataTableExt.oSort['callnumbers-desc'] = function(x,y) {
var x_array = x.split("<div>");
var y_array = y.split("<div>");
/* Pop the first elements, they are empty strings */
x_array.shift();
y_array.shift();
x_array = jQuery.map( x_array, function( a ) {
return parse_callnumber( a );
});
y_array = jQuery.map( y_array, function( a ) {
return parse_callnumber( a );
});
x_array.sort();
y_array.sort();
x = x_array.pop();
y = y_array.pop();
if ( !x ) { x = ""; }
if ( !y ) { y = ""; }
return ((x < y) ? 1 : ((x > y) ? -1 : 0));
};
function parse_callnumber ( html ) {
var array = html.split('<span class="callnumber">');
if ( array[1] ) {
array = array[1].split('</span>');
return array[0];
} else {
return "";
}
}
// see http://www.datatables.net/examples/advanced_init/footer_callback.html
function footer_column_sum( api, column_numbers ) {
// Remove the formatting to get integer data for summation
var intVal = function ( i ) {
if ( typeof i === 'number' ) {
if ( isNaN(i) ) return 0;
return i;
} else if ( typeof i === 'string' ) {
var value = i.replace(/[a-zA-Z ,.]/g, '')*1;
if ( isNaN(value) ) return 0;
return value;
}
return 0;
};
for ( var indice = 0 ; indice < column_numbers.length ; indice++ ) {
var column_number = column_numbers[indice];
var total = 0;
var cells = api.column( column_number, { page: 'current' } ).nodes().to$().find("span.total_amount");
$(cells).each(function(){
total += intVal( $(this).html() );
});
total /= 100; // Hard-coded decimal precision
// Update footer
$( api.column( column_number ).footer() ).html(total.format_price());
};
}
|
Mindhome/field_service
|
mindhome_alpha/erpnext/telephony/doctype/call_log/call_log.js
|
// Copyright (c) 2020, Frappe Technologies Pvt. Ltd. and contributors
// For license information, please see license.txt
frappe.ui.form.on('Call Log', {
refresh: function(frm) {
frm.events.setup_recording_audio_control(frm);
const incoming_call = frm.doc.type == 'Incoming';
frm.add_custom_button(incoming_call ? __('Callback'): __('Call Again'), () => {
const number = incoming_call ? frm.doc.from : frm.doc.to;
frappe.phone_call.handler(number, frm);
});
},
setup_recording_audio_control(frm) {
const recording_wrapper = frm.get_field('recording_html').$wrapper;
if (!frm.doc.recording_url || frm.doc.recording_url == 'null') {
recording_wrapper.empty();
} else {
recording_wrapper.addClass('input-max-width');
recording_wrapper.html(`
<audio
controls
src="${frm.doc.recording_url}">
</audio>
`);
}
}
});
|
ingrammicro/cio
|
cmd/cookbook_versions_cmd.go
|
// Copyright (c) 2017-2021 Ingram Micro Inc.
package cmd
import (
"fmt"
"github.com/ingrammicro/cio/api/blueprint"
"github.com/ingrammicro/cio/api/types"
"github.com/ingrammicro/cio/utils"
"github.com/ingrammicro/cio/utils/format"
"github.com/urfave/cli"
)
// WireUpCookbookVersion prepares common resources to send request to Concerto API
func WireUpCookbookVersion(c *cli.Context) (sv *blueprint.CookbookVersionService, f format.Formatter) {
f = format.GetFormatter()
config, err := utils.GetConcertoConfig()
if err != nil {
f.PrintFatal("Couldn't wire up config", err)
}
hcs, err := utils.NewHTTPConcertoService(config)
if err != nil {
f.PrintFatal("Couldn't wire up concerto service", err)
}
sv, err = blueprint.NewCookbookVersionService(hcs)
if err != nil {
f.PrintFatal("Couldn't wire up CookbookVersion service", err)
}
return sv, f
}
// CookbookVersionList subcommand function
func CookbookVersionList(c *cli.Context) error {
debugCmdFuncInfo(c)
svc, formatter := WireUpCookbookVersion(c)
cookbookVersions, err := svc.ListCookbookVersions()
if err != nil {
formatter.PrintFatal("Couldn't receive cookbook versions data", err)
}
labelables := make([]types.Labelable, len(cookbookVersions))
for i := 0; i < len(cookbookVersions); i++ {
labelables[i] = types.Labelable(cookbookVersions[i])
}
labelIDsByName, labelNamesByID := LabelLoadsMapping(c)
filteredLabelables := LabelFiltering(c, labelables, labelIDsByName)
LabelAssignNamesForIDs(c, filteredLabelables, labelNamesByID)
cookbookVersions = make([]*types.CookbookVersion, len(filteredLabelables))
for i, labelable := range filteredLabelables {
cb, ok := labelable.(*types.CookbookVersion)
if !ok {
formatter.PrintFatal(LabelFilteringUnexpected,
fmt.Errorf("expected labelable to be a *types.CookbookVersion, got a %T", labelable))
}
cookbookVersions[i] = cb
}
if err = formatter.PrintList(cookbookVersions); err != nil {
formatter.PrintFatal(PrintFormatError, err)
}
return nil
}
// CookbookVersionShow subcommand function
func CookbookVersionShow(c *cli.Context) error {
debugCmdFuncInfo(c)
svc, formatter := WireUpCookbookVersion(c)
checkRequiredFlags(c, []string{"id"}, formatter)
cookbookVersion, err := svc.GetCookbookVersion(c.String("id"))
if err != nil {
formatter.PrintFatal("Couldn't receive cookbook version data", err)
}
_, labelNamesByID := LabelLoadsMapping(c)
cookbookVersion.FillInLabelNames(labelNamesByID)
if err = formatter.PrintItem(*cookbookVersion); err != nil {
formatter.PrintFatal(PrintFormatError, err)
}
return nil
}
// CookbookVersionUpload subcommand function
// create/upload/process
func CookbookVersionUpload(c *cli.Context) error {
debugCmdFuncInfo(c)
svc, formatter := WireUpCookbookVersion(c)
checkRequiredFlags(c, []string{"filepath"}, formatter)
sourceFilePath := c.String("filepath")
if !utils.FileExists(sourceFilePath) {
formatter.PrintFatal("Invalid file path", fmt.Errorf("no such file or directory: %s", sourceFilePath))
}
cbIn := map[string]interface{}{}
labelIDsByName, labelNamesByID := LabelLoadsMapping(c)
if c.IsSet("labels") {
cbIn["label_ids"] = LabelResolution(c, c.String("labels"), &labelNamesByID, &labelIDsByName)
}
// creates new cookbook_version
cookbookVersion, err := svc.CreateCookbookVersion(&cbIn)
if err != nil {
formatter.PrintFatal("Couldn't create cookbook version data", err)
}
// uploads new cookbook_version file
err = svc.UploadCookbookVersion(sourceFilePath, cookbookVersion.UploadURL)
if err != nil {
cleanCookbookVersion(c, cookbookVersion.ID)
formatter.PrintFatal("Couldn't upload cookbook version data", err)
}
// processes the new cookbook_version
cookbookVersionID := cookbookVersion.ID
cookbookVersion, err = svc.ProcessCookbookVersion(cookbookVersion.ID, utils.FlagConvertParams(c))
if err != nil {
cleanCookbookVersion(c, cookbookVersionID)
formatter.PrintFatal("Couldn't process cookbook version", err)
}
cookbookVersion.FillInLabelNames(labelNamesByID)
if err = formatter.PrintItem(*cookbookVersion); err != nil {
formatter.PrintFatal(PrintFormatError, err)
}
return nil
}
// cleanCookbookVersion deletes CookbookVersion. Ideally for cleaning at uploading error cases
func cleanCookbookVersion(c *cli.Context, cookbookVersionID string) {
svc, formatter := WireUpCookbookVersion(c)
if err := svc.DeleteCookbookVersion(cookbookVersionID); err != nil {
formatter.PrintError("Couldn't clean failed cookbook version", err)
}
}
// CookbookVersionDelete subcommand function
func CookbookVersionDelete(c *cli.Context) error {
debugCmdFuncInfo(c)
svc, formatter := WireUpCookbookVersion(c)
checkRequiredFlags(c, []string{"id"}, formatter)
err := svc.DeleteCookbookVersion(c.String("id"))
if err != nil {
formatter.PrintFatal("Couldn't delete cookbook version", err)
}
return nil
}
|
ardyno/nuxt.js
|
test/utils/setup.js
|
process.env.FORCE_COLOR = 0
const chalk = require('chalk')
chalk.level = 0
chalk.supportsColor = false
process.env.FORCE_COLOR = 0
|
hull-ships/hull-slack
|
server/lib/build-attachments.js
|
<reponame>hull-ships/hull-slack
//@noflow
import _ from "lodash";
import moment from "moment";
import humanize from "./humanize";
// import flags from "./flags";
import entityUtils from "../util/entity-utils";
import format from "./format-value";
const MOMENT_FORMAT = "MMMM Do YYYY, h:mm:ss a";
function formatObjToText(ob) {
return _.join(
_.map(format(_.omit(ob, "id")), p => `*${p.title}*: ${p.value}`),
"\n"
);
}
function colorFactory() {
const COLORS = ["#83D586", "#49A2E1", "#FF625A", "#E57831", "#4BC2B8"];
let i = -1;
const l = COLORS.length;
return function cycle() {
i += 1;
return COLORS[i % l];
};
}
const FORMATTER = [
{
key: "email",
value: email => `:love_letter: ${email}`,
short: true,
},
// {
// key: "phone",
// value: phone => `:telephone_receiver: ${phone}`,
// short: true
// },
// {
// key: "address_country",
// value: (address = {}, user) => `${flags(user.address_country)} ${_.join(_.compact([user.address_country, user.address_state, user.address_city]), ", ")}`,
// short: false
// },
// {
// key: "first_seen_at",
// value: first_seen_at => `:stopwatch: *First Seen*: ${moment(first_seen_at).format(MOMENT_FORMAT)}`,
// short: false
// },
// {
// key: "created_at",
// value: created_at => `:stopwatch: *Signup*: ${moment(created_at).format(MOMENT_FORMAT)}`,
// short: false
// }
];
function getEntityAttachment({
traits = {},
entity = {},
color,
pretext,
targetEntity,
}) {
const name =
targetEntity === "user"
? entityUtils.getUserName(entity)
: entityUtils.getDomainName(entity);
const fields = _.reduce(
FORMATTER,
(ff, formatter) => {
const value = _.get(entity, formatter.key);
if (value === null || value === undefined) return ff;
ff.push({
value: formatter.value(value, entity),
short: formatter.short,
});
return ff;
},
[]
);
let footer = `:eyeglasses: ${moment(entity.last_seen_at).format(
MOMENT_FORMAT
)}`;
if (entity.sessions_count)
footer = `${footer} :desktop_computer: ${entity.sessions_count}`;
return {
mrkdwn_in: ["text", "fields", "pretext"],
pretext,
fallback: name,
color: color(),
fields,
footer,
thumb_url: entity.picture,
};
}
function getChangesAttachment(changes, color) {
return !_.size(changes)
? {}
: {
author_name: ":chart_with_upwards_trend: Changes",
mrkdwn_in: ["text", "fields", "pretext"],
color: color(),
fallback: `Changes: ${_.keys(changes || {}).join(", ")}`,
text: formatObjToText(_.mapValues(changes, v => `${v[0]} → ${v[1]}`)),
};
}
function getTraitsAttachments(traits, color) {
return _.reduce(
_.pickBy(traits, _.isPlainObject),
(atts, value, key) => {
if (_.isObject(value)) {
atts.push({
mrkdwn_in: ["text", "fields", "pretext"],
author_name: `:globe_with_meridians: ${humanize(key)}`,
text: formatObjToText(value),
color: color(),
fallback: key,
});
}
return atts;
},
[]
);
}
function cleanAttributeName(attribute) {
if (attribute.match(/^account\./)) {
attribute = attribute.replace("account.", "");
}
return attribute;
}
function group(entity) {
return _.reduce(
entity,
(grouped, value, key) => {
let dest = key;
if (key.match(/^traits_/)) {
if (key.match(/\//)) {
dest = key.replace(/^traits_/, "");
} else {
dest = key.replace(/^traits_/, "traits/");
}
}
return _.setWith(grouped, dest.split("/"), value, Object);
},
{}
);
}
function getWhitelistedEntity({ entity = {}, entity_whitelist = [] }) {
// if account variable exists on entity, do not remove the account prefix
const removeAccountPrefix = entity.account ? false : true;
entity_whitelist = _.reduce(
entity_whitelist,
(cleanList, value, key) => {
let cleanValue = value;
if (removeAccountPrefix) {
cleanValue = cleanAttributeName(value);
}
cleanList.push(cleanValue);
return cleanList;
},
[]
);
let whitelistedEntity = _.pick(entity, entity_whitelist);
return group(whitelistedEntity);
}
function getSegmentAttachments(
entity_segment_changes = {},
entity_segments,
color
) {
const segmentString = (_.map(entity_segments, "name") || []).join(", ");
return {
author_name: ":busts_in_silhouette: Segments",
text: segmentString,
fallback: `Segments: ${segmentString}`,
color: color(),
fields: _.map(entity_segment_changes, (segs, action) => {
const names = _.map(segs, "name");
const emoji = `:${action === "left" ? "outbox" : "inbox"}_tray:`;
return {
title: `${emoji} ${humanize(action)} segment${
names.length > 1 ? "s" : ""
}`,
value: names.join(", "),
};
}),
};
}
function getEventsAttachments(events = [], color) {
if (!events.length) return {};
return _.map(events, e => {
try {
const { days_since_signup: ds } = e.context || {};
const actions = [];
if (e.props && e.props.length) {
actions.push({
name: "expand",
value: "event",
text: "Show Properties",
type: "button",
});
}
return {
title: `:star: ${e.event}`,
ts: moment(e.created_at).format("X"),
footer: `:clock2: ${ds} day${Math.abs(ds) === 1 ? "" : "s"} ${
ds >= 0 ? "after" : "before"
} signup`,
fallback: e.event,
color: color(),
actions,
callback_id: e._id,
attachment_type: "default",
mrkdwn_in: ["text", "fields", "pretext"],
};
} catch (err) {
console.log(err);
}
return true;
});
}
module.exports = function buildAttachments({
entity = {},
entity_segments = [],
entity_changes = {},
entity_segment_changes = {},
entity_events = [],
pretext = "",
entity_whitelist = [],
targetEntity,
options = {},
}) {
let attachments = {};
const color = colorFactory();
let entityAttachment;
let entity_segments_attachments;
let entity_changes_attachments;
let entity_traits_attachments;
let entity_events_attachments;
const traits = _.size(entity_whitelist)
? getWhitelistedEntity({ entity, entity_whitelist })
: entity;
entityAttachment = getEntityAttachment({
traits,
entity,
color,
pretext,
targetEntity,
});
entity_segments_attachments = getSegmentAttachments(
entity_segment_changes,
entity_segments,
color
);
entity_changes_attachments = getChangesAttachment(
entity_changes[targetEntity],
color
);
entity_traits_attachments = getTraitsAttachments(traits, color);
entity_events_attachments = getEventsAttachments(entity_events, color);
attachments[targetEntity] = entityAttachment;
if (options.sendSegments !== false) {
attachments["segments"] = entity_segments_attachments;
}
attachments["events"] = entity_events_attachments;
if (options.sendChanges !== false) {
attachments["changes"] = entity_changes_attachments;
}
attachments["traits"] = entity_traits_attachments;
return attachments;
};
|
Berrysoft/XamlCpp
|
ui/include/xaml/ui/drawing_conv.hpp
|
<filename>ui/include/xaml/ui/drawing_conv.hpp
#ifndef XAML_UI_NATIVE_DRAWING_HPP
#define XAML_UI_NATIVE_DRAWING_HPP
#include <xaml/ui/drawing.h>
#ifdef XAML_UI_WINDOWS
#include <Windows.h>
#elif defined(XAML_UI_COCOA)
#include <xaml/ui/cocoa/objc.h>
#elif defined(XAML_UI_GTK3)
#include <gtk/gtk.h>
#elif defined(XAML_UI_QT)
#include <QPoint>
#include <QRect>
#include <QSize>
#endif // XAML_UI_WINDOWS
template <typename To, typename From>
inline To xaml_to_native(From const&) noexcept = delete;
#ifdef XAML_UI_WINDOWS
constexpr xaml_size xaml_from_native(SIZE const& s) noexcept
{
return { (double)s.cx, (double)s.cy };
}
template <>
constexpr SIZE xaml_to_native<SIZE, xaml_size>(xaml_size const& s) noexcept
{
return { (LONG)s.width, (LONG)s.height };
}
constexpr xaml_point xaml_from_native(POINT const& p) noexcept
{
return { (double)p.x, (double)p.y };
}
template <>
constexpr POINT xaml_to_native<POINT, xaml_point>(xaml_point const& p) noexcept
{
return { (LONG)p.x, (LONG)p.y };
}
constexpr xaml_rectangle xaml_from_native(RECT const& r) noexcept
{
return { (double)r.left, (double)r.top, (double)r.right - r.left, (double)r.bottom - r.top };
}
template <>
constexpr RECT xaml_to_native<RECT, xaml_rectangle>(xaml_rectangle const& r) noexcept
{
return { (LONG)r.x, (LONG)r.y, (LONG)(r.x + r.width), (LONG)(r.y + r.height) };
}
#elif defined(XAML_UI_GTK3)
constexpr xaml_size xaml_from_native(gint width, gint height) noexcept
{
return { (double)width, (double)height };
}
template <>
inline std::tuple<gint, gint> xaml_to_native<std::tuple<gint, gint>, xaml_size>(xaml_size const& s) noexcept
{
return std::make_tuple((std::max)(0, (int)s.width), (std::max)(1, (int)s.height));
}
constexpr xaml_point xaml_from_native(GdkPoint const& p) noexcept
{
return { (double)p.x, (double)p.y };
}
template <>
constexpr GdkPoint xaml_to_native<GdkPoint, xaml_point>(xaml_point const& p) noexcept
{
return { (int)p.x, (int)p.y };
}
constexpr xaml_rectangle xaml_from_native(GdkRectangle const& r) noexcept
{
return { (double)r.x, (double)r.y, (double)r.width, (double)r.height };
}
template <>
constexpr GdkRectangle xaml_to_native<GdkRectangle, xaml_rectangle>(xaml_rectangle const& r) noexcept
{
return { (int)r.x, (int)r.y, (int)r.width, (int)r.height };
}
#elif defined(XAML_UI_COCOA) && defined(__OBJC__)
constexpr xaml_size xaml_from_native(NSSize const& s) noexcept
{
return { s.width, s.height };
}
template <>
constexpr NSSize xaml_to_native<NSSize, xaml_size>(xaml_size const& s) noexcept
{
return { s.width, s.height };
}
constexpr xaml_point xaml_from_native(NSPoint const& p) noexcept
{
return { p.x, p.y };
}
template <>
constexpr NSPoint xaml_to_native<NSPoint, xaml_point>(xaml_point const& p) noexcept
{
return { p.x, p.y };
}
constexpr xaml_rectangle xaml_from_native(NSRect const& r) noexcept
{
return { r.origin.x, r.origin.y, r.size.width, r.size.height };
}
template <>
constexpr NSRect xaml_to_native<NSRect, xaml_rectangle>(xaml_rectangle const& r) noexcept
{
return { { r.x, r.y }, { r.width, r.height } };
}
template <>
inline NSColor* xaml_to_native<NSColor*, xaml_color>(xaml_color const& c) noexcept
{
return [NSColor colorWithCalibratedRed:(c.r / 255.0) green:(c.g / 255.0) blue:(c.b / 255.0) alpha:(c.a / 255.0)];
}
#elif defined(XAML_UI_QT)
constexpr xaml_size xaml_from_native(QSize const& s) noexcept
{
return { (double)s.width(), (double)s.height() };
}
template <>
constexpr QSize xaml_to_native<QSize, xaml_size>(xaml_size const& s) noexcept
{
return { (int)s.width, (int)s.height };
}
constexpr xaml_size xaml_from_native(QSizeF const& s) noexcept
{
return { s.width(), s.height() };
}
template <>
constexpr QSizeF xaml_to_native<QSizeF, xaml_size>(xaml_size const& s) noexcept
{
return { s.width, s.height };
}
constexpr xaml_point xaml_from_native(QPoint const& p) noexcept
{
return { (double)p.x(), (double)p.y() };
}
template <>
constexpr QPoint xaml_to_native<QPoint, xaml_point>(xaml_point const& p) noexcept
{
return { (int)p.x, (int)p.y };
}
constexpr xaml_point xaml_from_native(QPointF const& p) noexcept
{
return { p.x(), p.y() };
}
template <>
constexpr QPointF xaml_to_native<QPointF, xaml_point>(xaml_point const& p) noexcept
{
return { p.x, p.y };
}
constexpr xaml_rectangle xaml_from_native(QRect const& r) noexcept
{
return { (double)r.left(), (double)r.top(), (double)r.width(), (double)r.height() };
}
template <>
constexpr QRect xaml_to_native<QRect, xaml_rectangle>(xaml_rectangle const& r) noexcept
{
return { (int)r.x, (int)r.y, (int)(r.width), (int)(r.height) };
}
constexpr xaml_rectangle xaml_from_native(QRectF const& r) noexcept
{
return { r.left(), r.top(), r.width(), r.height() };
}
template <>
constexpr QRectF xaml_to_native<QRectF, xaml_rectangle>(xaml_rectangle const& r) noexcept
{
return { r.x, r.y, r.width, r.height };
}
#endif // XAML_UI_WINDOWS
#endif // !XAML_UI_NATIVE_DRAWING_HPP
|
NYCMOTI/open-bid
|
spec/view_models/account_subnav_view_model_spec.rb
|
<reponame>NYCMOTI/open-bid<filename>spec/view_models/account_subnav_view_model_spec.rb
require 'rails_helper'
describe AccountSubnavViewModel do
describe '#profile_tab_class' do
it 'should be active when the active_tab is profile' do
view_model = AccountSubnavViewModel.new(active_tab: :profile, current_user: nil)
expect(view_model.profile_tab_class).to eq('nav-auction active')
end
it 'should not be active otherwise' do
view_model = AccountSubnavViewModel.new(active_tab: :bids_placed, current_user: nil)
expect(view_model.profile_tab_class).to eq('nav-auction')
end
end
describe '#bids_tab_class' do
it 'should be active when the active_tab is bids_placed' do
view_model = AccountSubnavViewModel.new(active_tab: :bids_placed, current_user: nil)
expect(view_model.bids_tab_class).to eq('nav-auction active')
end
it 'should not be active otherwise' do
view_model = AccountSubnavViewModel.new(active_tab: :profile, current_user: nil)
expect(view_model.bids_tab_class).to eq('nav-auction')
end
end
def bids_tab_partial
it 'should be null if the current_user is an admin' do
user = create(:admin)
view_model = AccountSubnavViewModel.new(active_tab: :bids_placed, current_user: user)
expect(view_model.bids_tab_partial).to eq('components/null')
end
end
end
|
powwowinc/devtools-frontend
|
smartux-build/inspector/accessibility/ARIAMetadata.js
|
import{config}from'./ARIAProperties.js';export class ARIAMetadata{constructor(config){this._attributes=new Map();if(config){this._initialize(config);}}
_initialize(config){const attributes=config['attributes'];const booleanEnum=['true','false'];for(const attributeConfig of attributes){if(attributeConfig.type==='boolean'){attributeConfig.enum=booleanEnum;}
this._attributes.set(attributeConfig.name,new Attribute(attributeConfig));}
this._roleNames=config['roles'].map(roleConfig=>roleConfig.name);}
valuesForProperty(property){if(this._attributes.has(property)){return this._attributes.get(property).getEnum();}
if(property==='role'){return this._roleNames;}
return[];}}
export function ariaMetadata(){if(!ARIAMetadata._instance){ARIAMetadata._instance=new ARIAMetadata(config||null);}
return ARIAMetadata._instance;}
export class Attribute{constructor(config){this._enum=[];if('enum'in config){this._enum=config.enum;}}
getEnum(){return this._enum;}}
|
LoopFiftyFour/Java-Connector
|
core/src/main/java/com/loop54/exceptions/ClientInfoException.java
|
<reponame>LoopFiftyFour/Java-Connector<gh_stars>1-10
package com.loop54.exceptions;
/** Thrown when we cannot read the client info properly. */
public class ClientInfoException extends Loop54Exception {
public ClientInfoException(String message) {
super(message);
}
}
|
wipup/discord-bot
|
src/main/java/wp/discord/bot/listener/text/CommandMessageListener.java
|
<filename>src/main/java/wp/discord/bot/listener/text/CommandMessageListener.java
package wp.discord.bot.listener.text;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import lombok.extern.slf4j.Slf4j;
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.entities.Activity;
import net.dv8tion.jda.api.events.GenericEvent;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import wp.discord.bot.config.properties.DiscordProperties;
import wp.discord.bot.config.properties.DiscordStatus;
import wp.discord.bot.core.TracingHandler;
import wp.discord.bot.core.action.ActionHandleManager;
import wp.discord.bot.core.bot.AbstractDiscordEventListener;
import wp.discord.bot.core.cmd.CommandLineProcessor;
import wp.discord.bot.exception.ActionFailException;
import wp.discord.bot.exception.BotException;
import wp.discord.bot.model.BotAction;
import wp.discord.bot.util.Reply;
import wp.discord.bot.util.SafeUtil;
@Component
@Slf4j
public class CommandMessageListener extends AbstractDiscordEventListener<MessageReceivedEvent> {
@Autowired
private JDA jda;
@Autowired
private DiscordProperties discordProperties;
@Autowired
private CommandLineProcessor cmdProcessor;
@Autowired
private ActionHandleManager actionManager;
@Autowired
private TracingHandler tracingHandler;
@Override
public void handleEvent(MessageReceivedEvent event) throws Exception {
try {
String cmd = event.getMessage().getContentRaw();
executeCommand(event, cmd);
} catch (RuntimeException e) {
log.error("Unexpected Runtime Error: {}", e.getMessage(), e);
handleRuntimeException(event, e);
throw e;
} catch (ActionFailException e) {
log.error("Action Error: {}", e.getMessage(), e);
sendReply(event, e);
} catch (BotException e) {
log.error("Bot Error: {}", e.getMessage(), e);
sendReply(event, e);
throw e;
}
}
private void handleRuntimeException(MessageReceivedEvent event, RuntimeException e) throws Exception {
Reply reply = Reply.of().literal("Sorry ").mention(event.getAuthor()).literal(", I couldn't understand your request.");
sendReply(event, new BotException(reply));
}
private void sendReply(MessageReceivedEvent event, BotException e) throws Exception {
String reply = SafeUtil.get(() -> e.getReplyMessage().toString());
if (reply != null) {
event.getChannel().sendMessage(reply).queue(tracingHandler.onSendMessageSuccess(), tracingHandler.onSendMessageFail());
} else {
throw e;
}
}
public void executeCommand(GenericEvent relatedEvent, String cmd) throws Exception {
if (StringUtils.isBlank(cmd)) {
return;
}
log.info("[CMD] {}", cmd);
List<BotAction> actions = cmdProcessor.parseMultiLineCommand(relatedEvent, cmd);
actionManager.executeActions(actions);
}
@Override
public void setReady() {
super.setReady();
DiscordStatus status = discordProperties.getStatus();
log.info("Application is ready, setting status: {}", status);
jda.getPresence().setActivity(Activity.of(status.getType(), status.getName()));
jda.getPresence().setStatus(status.getStatus());
}
@Override
public boolean acceptCondition(MessageReceivedEvent event) {
return !event.getAuthor().isBot();
}
@Override
public Class<MessageReceivedEvent> eventClass() {
return MessageReceivedEvent.class;
}
}
|
tornaia/hr2
|
hr2-java-parent/hr2-backend-impl/src/test/java/test/builder/SzabadsagnyilvantartasBuilder.java
|
<filename>hr2-java-parent/hr2-backend-impl/src/test/java/test/builder/SzabadsagnyilvantartasBuilder.java<gh_stars>1-10
package test.builder;
import hu.interconnect.hr.domain.Szabadsagnyilvantartas;
public class SzabadsagnyilvantartasBuilder extends Builder<Szabadsagnyilvantartas> {
private int megvaltottSzabadsag;
public SzabadsagnyilvantartasBuilder megvaltottSzabadsag(int megvaltottSzabadsag) {
this.megvaltottSzabadsag = megvaltottSzabadsag;
return this;
}
@Override
public Szabadsagnyilvantartas letrehoz() {
return new Szabadsagnyilvantartas(megvaltottSzabadsag);
}
}
|
mossnana/rumors-api
|
src/graphql/queries/ListArticles.js
|
import { GraphQLInt, GraphQLString, GraphQLInputObjectType, GraphQLList } from 'graphql';
import client from 'util/client';
import {
createFilterType,
createSortType,
getSortArgs,
pagingArgs,
getArithmeticExpressionType,
getOperatorAndOperand,
} from 'graphql/util';
import scrapUrls from 'util/scrapUrls';
import { ArticleConnection } from 'graphql/models/Article';
export default {
args: {
filter: {
type: createFilterType('ListArticleFilter', {
replyCount: {
type: getArithmeticExpressionType(
'ListArticleReplyCountExpr',
GraphQLInt
),
description:
'List only the articles whose number of replies matches the criteria.',
},
moreLikeThis: {
type: new GraphQLInputObjectType({
name: 'ListArticleMoreLikeThisInput',
fields: {
like: {
type: GraphQLString,
description: 'The text string to query.',
},
minimumShouldMatch: { type: GraphQLString },
},
}),
description: 'List all articles related to a given string.',
},
replyRequestCount: {
type: getArithmeticExpressionType(
'ListArticleReplyRequestCountExpr',
GraphQLInt
),
description:
'List only the articles whose number of replies matches the criteria.',
},
appId: {
type: GraphQLString,
description:
'Use with userId to show only articles from a specific user.',
},
userId: {
type: GraphQLString,
description:
'Use with appId to show only articles from a specific user.',
},
fromUserOfArticleId: {
type: GraphQLString,
description: `
Specify an articleId here to show only articles from the sender of that specified article.
When specified, it overrides the settings of appId and userId.
`,
},
categories: {
type: GraphQLString,
description: 'List with articles contain categories use , for separated categories'
}
}),
},
orderBy: {
type: createSortType('ListArticleOrderBy', [
'_score',
'updatedAt',
'createdAt',
'replyRequestCount',
'replyCount',
'lastRequestedAt',
]),
},
...pagingArgs,
},
async resolve(
rootValue,
{ filter = {}, orderBy = [], ...otherParams },
{ loaders }
) {
const body = {
sort: getSortArgs(orderBy, {
replyCount: o => ({ normalArticleReplyCount: { order: o } }),
}),
track_scores: true, // for _score sorting
};
// Collecting queries that will be used in bool queries later
const shouldQueries = []; // Affects scores
const filterQueries = []; // Not affects scores
if (filter.fromUserOfArticleId) {
let specifiedArticle;
try {
specifiedArticle = (await client.get({
index: 'articles',
type: 'doc',
id: filter.fromUserOfArticleId,
_source: ['userId', 'appId'],
}))._source;
} catch (e) {
if (e.statusCode && e.statusCode === 404) {
throw new Error(
'fromUserOfArticleId does not match any existing articles'
);
}
// Re-throw unknown error
throw e;
}
// Overriding filter's userId and appId, as indicated in the description
//
// eslint-disable-next-line require-atomic-updates
filter.userId = specifiedArticle.userId;
// eslint-disable-next-line require-atomic-updates
filter.appId = specifiedArticle.appId;
}
// if (filter.appId && filter.userId) {
// filterQueries.push(
// { term: { appId: filter.appId } },
// { term: { userId: filter.userId } }
// );
// } else if (filter.appId || filter.userId) {
// throw new Error('Both appId and userId must be specified at once');
// }
if (filter.appId) {
filterQueries.push(
{ term: { appId: filter.appId } },
);
}
if (filter.userId) {
filterQueries.push(
{ term: { userId: filter.userId } }
);
}
filterQueries.push({
"bool" : {
"must_not" : {
"exists" : {
"field" : "status"
}
}
}
})
if (filter.moreLikeThis) {
const scrapResults = (await scrapUrls(filter.moreLikeThis.like, {
client,
cacheLoader: loaders.urlLoader,
})).filter(r => r);
const likeQuery = [
filter.moreLikeThis.like,
...scrapResults.map(({ title, summary }) => `${title} ${summary}`),
];
shouldQueries.push(
{
more_like_this: {
fields: ['title', 'text'],
like: likeQuery,
min_term_freq: 1,
min_doc_freq: 1,
minimum_should_match: filter.moreLikeThis.minimumShouldMatch || '3<70%',
},
},
{
nested: {
path: 'hyperlinks',
score_mode: 'sum',
query: {
more_like_this: {
fields: ['hyperlinks.title', 'hyperlinks.summary'],
like: likeQuery,
min_term_freq: 1,
min_doc_freq: 1,
minimum_should_match:
filter.moreLikeThis.minimumShouldMatch || '10<70%',
},
},
},
}
);
// Additionally, match the scrapped URLs with other article's scrapped urls
//
const urls = scrapResults.reduce((urls, result) => {
if (!result) return urls;
if (result.url) urls.push(result.url);
if (result.canonical) urls.push(result.canonical);
return urls;
}, []);
if (urls.length > 0) {
shouldQueries.push({
nested: {
path: 'hyperlinks',
score_mode: 'sum',
query: {
terms: {
'hyperlinks.url': urls,
},
},
},
});
}
}
if (filter.replyCount) {
const { operator, operand } = getOperatorAndOperand(filter.replyCount);
filterQueries.push({
script: {
script: {
source: `doc['normalArticleReplyCount'].value ${operator} params.operand`,
params: {
operand,
},
},
},
});
}
if (filter.replyRequestCount) {
const { operator, operand } = getOperatorAndOperand(
filter.replyRequestCount
);
filterQueries.push({
script: {
script: {
source: `doc['replyRequestCount'].value ${operator} params.operand`,
params: {
operand,
},
},
},
});
}
if (filter.categories && filter.categories.length > 0) {
const categories = filter.categories.split(',')
filterQueries.push({
bool : {
should : categories.map(c => ({ "term" : { "categories" : c } })),
minimum_should_match: categories.length
}
});
}
body.query = {
bool: {
should:
shouldQueries.length === 0 ? [{ match_all: {} }] : shouldQueries,
filter: filterQueries,
minimum_should_match: 1, // At least 1 "should" query should present
},
};
// should return search context for resolveEdges & resolvePageInfo
return {
index: 'articles',
type: 'doc',
body,
...otherParams,
};
},
type: ArticleConnection,
};
|
ollystephens/benthos
|
lib/condition/constructor_test.go
|
<filename>lib/condition/constructor_test.go
package condition
import (
"encoding/json"
"testing"
"github.com/Jeffail/benthos/v3/lib/log"
"github.com/Jeffail/benthos/v3/lib/metrics"
yaml "gopkg.in/yaml.v3"
)
func TestConstructorDescription(t *testing.T) {
if len(Descriptions()) == 0 {
t.Error("package descriptions were empty")
}
}
func TestConstructorBadType(t *testing.T) {
conf := NewConfig()
conf.Type = "not_exist"
if _, err := New(conf, nil, log.Noop(), metrics.Noop()); err == nil {
t.Error("Expected error, received nil for invalid type")
}
}
func TestConstructorConfigYAMLInference(t *testing.T) {
conf := []Config{}
if err := yaml.Unmarshal([]byte(`[
{
"text": {
"value": "foo"
},
"jmespath": {
"query": "foo"
}
}
]`), &conf); err == nil {
t.Error("Expected error from multi candidates")
}
if err := yaml.Unmarshal([]byte(`[
{
"text": {
"arg": "foo"
}
}
]`), &conf); err != nil {
t.Error(err)
}
if exp, act := 1, len(conf); exp != act {
t.Errorf("Wrong number of config parts: %v != %v", act, exp)
return
}
if exp, act := TypeText, conf[0].Type; exp != act {
t.Errorf("Wrong inferred type: %v != %v", act, exp)
}
if exp, act := "equals_cs", conf[0].Text.Operator; exp != act {
t.Errorf("Wrong default operator: %v != %v", act, exp)
}
if exp, act := "foo", conf[0].Text.Arg; exp != act {
t.Errorf("Wrong arg: %v != %v", act, exp)
}
}
func TestConstructorConfigDefaultsYAML(t *testing.T) {
conf := []Config{}
if err := yaml.Unmarshal([]byte(`[
{
"type": "text",
"text": {
"part": 1
}
}
]`), &conf); err != nil {
t.Error(err)
}
if exp, act := 1, len(conf); exp != act {
t.Errorf("Wrong number of config parts: %v != %v", act, exp)
return
}
if exp, act := "equals_cs", conf[0].Text.Operator; exp != act {
t.Errorf("Wrong default operator: %v != %v", act, exp)
}
if exp, act := 1, conf[0].Text.Part; exp != act {
t.Errorf("Wrong default part: %v != %v", act, exp)
}
}
func TestSanitise(t *testing.T) {
var actObj interface{}
var act []byte
var err error
exp := `{` +
`"type":"text",` +
`"text":{` +
`"arg":"foo",` +
`"operator":"equals_cs",` +
`"part":1` +
`}` +
`}`
conf := NewConfig()
conf.Type = "text"
conf.Text.Part = 1
conf.Text.Arg = "foo"
if actObj, err = SanitiseConfig(conf); err != nil {
t.Fatal(err)
}
if act, err = json.Marshal(actObj); err != nil {
t.Fatal(err)
}
if string(act) != exp {
t.Errorf("Wrong sanitised output: %s != %v", act, exp)
}
}
|
juyss/workspace
|
IcePoint_Project/icepoint-framework/icepoint-core/src/main/java/com/icepoint/framework/core/flow/dsl/GenericFilter.java
|
package com.icepoint.framework.core.flow.dsl;
import com.icepoint.framework.core.flow.FlowMetadata;
/**
* @author <NAME>
*/
@FunctionalInterface
public interface GenericFilter<P> extends Component {
boolean filter(P payload, FlowMetadata metadata);
}
|
fossabot/keto
|
warden/helper_test.go
|
<filename>warden/helper_test.go
/*
* Copyright © 2015-2018 <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @author <NAME> <<EMAIL>>
* @copyright 2015-2018 <NAME> <<EMAIL>>
* @license Apache-2.0
*/
package warden_test
import (
"os"
"testing"
"github.com/ory/keto/role"
"github.com/ory/keto/warden"
"github.com/ory/ladon"
"github.com/ory/ladon/manager/memory"
"github.com/sirupsen/logrus"
)
var (
accessRequestTestCases = []struct {
req *warden.AccessRequest
expectErr bool
}{
{
req: &warden.AccessRequest{
Subject: "alice",
Resource: "other-thing",
Action: "create",
Context: ladon.Context{},
},
expectErr: true,
},
{
req: &warden.AccessRequest{
Subject: "alice",
Resource: "matrix",
Action: "delete",
Context: ladon.Context{},
},
expectErr: true,
},
{
req: &warden.AccessRequest{
Subject: "alice",
Resource: "matrix",
Action: "create",
Context: ladon.Context{},
},
expectErr: false,
},
{
req: &warden.AccessRequest{
Subject: "ken",
Resource: "forbidden_matrix",
Action: "create",
Context: ladon.Context{},
},
expectErr: true,
},
{
req: &warden.AccessRequest{
Subject: "ken",
Resource: "allowed_matrix",
Action: "create",
Context: ladon.Context{},
},
expectErr: false,
},
}
wardens = map[string]warden.Firewall{}
ladonWarden = &ladon.Ladon{
Manager: &memory.MemoryManager{
Policies: map[string]ladon.Policy{
"1": &ladon.DefaultPolicy{
ID: "1",
Subjects: []string{"alice", "group1", "client"},
Resources: []string{"matrix", "forbidden_matrix", "rn:hydra:token<.*>"},
Actions: []string{"create", "decide"},
Effect: ladon.AllowAccess,
},
"2": &ladon.DefaultPolicy{
ID: "2",
Subjects: []string{"siri"},
Resources: []string{"<.*>"},
Actions: []string{"decide"},
Effect: ladon.AllowAccess,
},
"3": &ladon.DefaultPolicy{
ID: "3",
Subjects: []string{"group1"},
Resources: []string{"forbidden_matrix", "rn:hydra:token<.*>"},
Actions: []string{"create", "decide"},
Effect: ladon.DenyAccess,
},
"4": &ladon.DefaultPolicy{
ID: "4",
Subjects: []string{"group1"},
Resources: []string{"allowed_matrix", "rn:hydra:token<.*>"},
Actions: []string{"create", "decide"},
Effect: ladon.AllowAccess,
},
},
},
}
)
func TestMain(m *testing.M) {
wardens["local"] = &warden.Warden{
L: logrus.New(),
Warden: ladonWarden,
Roles: &role.MemoryManager{
Roles: map[string]role.Role{
"group1": {
ID: "group1",
Members: []string{"ken"},
},
},
},
}
os.Exit(m.Run())
}
|
junxworks/junx-ep
|
junx-ep-auth/src/main/java/io/github/junxworks/ep/auth/model/UserModel.java
|
<filename>junx-ep-auth/src/main/java/io/github/junxworks/ep/auth/model/UserModel.java
/*
***************************************************************************************
* EP for web developers.Supported By Junxworks
* @Title: UserModel.java
* @Package io.github.junxworks.ep.auth.model
* @Description: (用一句话描述该文件做什么)
* @author: Administrator
* @date: 2020-7-19 12:18:41
* @version V1.0
* @Copyright: 2020 Junxworks. All rights reserved.
* 注意:
* ----------------------------------------------------------------------------------
* 文件修改记录
* 文件版本: 修改人: 修改原因:
***************************************************************************************
*/
package io.github.junxworks.ep.auth.model;
import java.io.Serializable;
import java.util.List;
/**
* {类的详细说明}.
*
* @ClassName: UserModel
* @author: Michael
* @date: 2020-7-19 12:18:41
* @since: v1.0
*/
public class UserModel implements Serializable {
/** 常量 SUPER_ADMIN. */
public static final long SUPER_ADMIN = -1;
/** 常量 serialVersionUID. */
private static final long serialVersionUID = 7941789731039560137L;
/** id. */
private Long id;
/** nick. */
private String nick;
/** name. */
private String name;
/** username. */
private String username;
/** id card. */
private String idCard;
/** email. */
private String email;
/** mobile. */
private String mobile;
/** user type. */
private int userType;
/** org no. */
private String orgNo;
/** org name. */
private String orgName;
/** org type. */
private String orgType;
/** status. */
private int status;
/** authorizations. */
private List<String> authorizations;
/** roles. */
private List<String> roles;
public String getOrgName() {
return orgName;
}
public void setOrgName(String orgName) {
this.orgName = orgName;
}
public String getOrgType() {
return orgType;
}
public void setOrgType(String orgType) {
this.orgType = orgType;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getNick() {
return nick;
}
public void setNick(String nick) {
this.nick = nick;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getIdCard() {
return idCard;
}
public void setIdCard(String idCard) {
this.idCard = idCard;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public int getUserType() {
return userType;
}
public void setUserType(int userType) {
this.userType = userType;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getOrgNo() {
return orgNo;
}
public void setOrgNo(String orgNo) {
this.orgNo = orgNo;
}
public boolean isAdmin() {
return SUPER_ADMIN == id;
}
/**
* To string.
*
* @return the string
*/
/* shiro删除认证cache的时候会用到
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return username;
}
public List<String> getAuthorizations() {
return authorizations;
}
public void setAuthorizations(List<String> authorizations) {
this.authorizations = authorizations;
}
/**
* Auth.
*
* @param authorize the authorize
* @return true, if successful
*/
public boolean auth(String authorize) {
return authorizations != null && authorizations.contains(authorize);
}
public List<String> getRoles() {
return roles;
}
public void setRoles(List<String> roles) {
this.roles = roles;
}
/**
* Checks for role.
*
* @param roleTag the role tag
* @return true, if successful
*/
public boolean hasRole(String roleTag) {
return roles != null && roles.contains(roleTag);
}
}
|
nahuel-coliva/a-MLLibrary
|
run.py
|
<filename>run.py
#!/usr/bin/env python3
"""
Copyright 2019 <NAME>
Copyright 2019 <NAME>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import argparse
import os
import sequence_data_processing
def main():
"""
Main script to use the library standalone
The main argument of this script is the configuration file which describes the experimental campaing to be performed i.e., which is the input file, which are the pre-processing steps to be performed, which technique with which hyper-parameters have to be used.
Example of configuration files can be found in example_confiigurations directory
Other arguments are:
-d, --debug: enables the debug printing.
-s, --seed: specifies the seed to be used; it is mainly exploited in the split of the data into training, hyper-parameter selection, and validtion set. If it is not specified, seed=0 will be used making the whole process deterministic.input
-o, --output: specifies the output directory where logs and results will be put. If the directory already exists, the script fails. This behaviour has been designed to avoid unintentinal overwriting.
-j: specifies the maximum number of processes which can be used.
-g, --generate-plots: enables generation of plots of type actual vs. predicted.
-t, --self-check: enables the test of the generated regressor on the whole input set.
-l, --details: increase the verbosity of the library. In particular, results in terms of MAPE on different sets are printed for all the built regressors and not only for the best one.
"""
parser = argparse.ArgumentParser(description="Perform exploration of regression techniques")
parser.add_argument('-c', "--configuration-file", help="configuration file for the infrastructure", required=True)
parser.add_argument('-d', "--debug", help="enable debug messages", default=False, action="store_true")
parser.add_argument('-s', "--seed", help="RNG seed", default=0)
parser.add_argument('-o', "--output", help="output folder where all the models will be stored", default="output")
parser.add_argument('-j', help="number of processes to be used", default=1)
parser.add_argument('-g', "--generate-plots", help="generate plots", default=False, action="store_true")
parser.add_argument('-t', "--self-check", help="predict the input data with the generate regressor", default=False, action="store_true")
parser.add_argument('-l', "--details", help="print results of the single experiments", default=False, action="store_true")
args = parser.parse_args()
os.environ["CUDA_VISIBLE_DEVICES"] = ""
sequence_data_processor = sequence_data_processing.SequenceDataProcessing(args.configuration_file, debug=args.debug, seed=args.seed, output=args.output, j=args.j, generate_plots=args.generate_plots, self_check=args.self_check, details=args.details)
sequence_data_processor.process()
if __name__ == '__main__':
main()
|
deepfield/a10sdk-python
|
a10sdk/core/route/route_map_set.py
|
<reponame>deepfield/a10sdk-python<filename>a10sdk/core/route/route_map_set.py
from a10sdk.common.A10BaseClass import A10BaseClass
class Rt(A10BaseClass):
"""This class does not support CRUD Operations please use parent.
:param value: {"type": "string", "description": "VPN extended community", "format": "string-rlx"}
:param DeviceProxy: The device proxy for REST operations and session handling. Refer to `common/device_proxy.py`
"""
def __init__(self, **kwargs):
self.ERROR_MSG = ""
self.b_key = "rt"
self.DeviceProxy = ""
self.value = ""
for keys, value in kwargs.items():
setattr(self,keys, value)
class Soo(A10BaseClass):
"""This class does not support CRUD Operations please use parent.
:param value: {"type": "string", "description": "VPN extended community", "format": "string-rlx"}
:param DeviceProxy: The device proxy for REST operations and session handling. Refer to `common/device_proxy.py`
"""
def __init__(self, **kwargs):
self.ERROR_MSG = ""
self.b_key = "soo"
self.DeviceProxy = ""
self.value = ""
for keys, value in kwargs.items():
setattr(self,keys, value)
class Extcommunity(A10BaseClass):
"""This class does not support CRUD Operations please use parent.
:param DeviceProxy: The device proxy for REST operations and session handling. Refer to `common/device_proxy.py`
"""
def __init__(self, **kwargs):
self.ERROR_MSG = ""
self.b_key = "extcommunity"
self.DeviceProxy = ""
self.rt = {}
self.soo = {}
for keys, value in kwargs.items():
setattr(self,keys, value)
class Origin(A10BaseClass):
"""This class does not support CRUD Operations please use parent.
:param egp: {"default": 0, "not-list": ["igp", "incomplete"], "type": "number", "description": "remote EGP", "format": "flag"}
:param incomplete: {"default": 0, "not-list": ["egp", "igp"], "type": "number", "description": "unknown heritage", "format": "flag"}
:param igp: {"default": 0, "not-list": ["egp", "incomplete"], "type": "number", "description": "local IGP", "format": "flag"}
:param DeviceProxy: The device proxy for REST operations and session handling. Refer to `common/device_proxy.py`
"""
def __init__(self, **kwargs):
self.ERROR_MSG = ""
self.b_key = "origin"
self.DeviceProxy = ""
self.egp = ""
self.incomplete = ""
self.igp = ""
for keys, value in kwargs.items():
setattr(self,keys, value)
class AggregatorAs(A10BaseClass):
"""This class does not support CRUD Operations please use parent.
:param ip: {"type": "string", "description": "IP address of aggregator", "format": "ipv4-address"}
:param asn: {"description": "AS number", "minimum": 1, "type": "number", "maximum": 4294967295, "format": "number"}
:param DeviceProxy: The device proxy for REST operations and session handling. Refer to `common/device_proxy.py`
"""
def __init__(self, **kwargs):
self.ERROR_MSG = ""
self.b_key = "aggregator-as"
self.DeviceProxy = ""
self.ip = ""
self.asn = ""
for keys, value in kwargs.items():
setattr(self,keys, value)
class Aggregator(A10BaseClass):
"""This class does not support CRUD Operations please use parent.
:param DeviceProxy: The device proxy for REST operations and session handling. Refer to `common/device_proxy.py`
"""
def __init__(self, **kwargs):
self.ERROR_MSG = ""
self.b_key = "aggregator"
self.DeviceProxy = ""
self.aggregator_as = {}
for keys, value in kwargs.items():
setattr(self,keys, value)
class Weight(A10BaseClass):
"""This class does not support CRUD Operations please use parent.
:param weight_val: {"description": "Weight value", "minimum": 0, "type": "number", "maximum": 4294967295, "format": "number"}
:param DeviceProxy: The device proxy for REST operations and session handling. Refer to `common/device_proxy.py`
"""
def __init__(self, **kwargs):
self.ERROR_MSG = ""
self.b_key = "weight"
self.DeviceProxy = ""
self.weight_val = ""
for keys, value in kwargs.items():
setattr(self,keys, value)
class Level(A10BaseClass):
"""This class does not support CRUD Operations please use parent.
:param value: {"enum": ["level-1", "level-1-2", "level-2"], "type": "string", "description": "'level-1': Export into a level-1 area; 'level-1-2': Export into level-1 and level-2; 'level-2': Export into level-2 sub-domain; ", "format": "enum"}
:param DeviceProxy: The device proxy for REST operations and session handling. Refer to `common/device_proxy.py`
"""
def __init__(self, **kwargs):
self.ERROR_MSG = ""
self.b_key = "level"
self.DeviceProxy = ""
self.value = ""
for keys, value in kwargs.items():
setattr(self,keys, value)
class NextHop(A10BaseClass):
"""This class does not support CRUD Operations please use parent.
:param address: {"type": "string", "description": "IP address of next hop", "format": "ipv4-address"}
:param DeviceProxy: The device proxy for REST operations and session handling. Refer to `common/device_proxy.py`
"""
def __init__(self, **kwargs):
self.ERROR_MSG = ""
self.b_key = "next-hop"
self.DeviceProxy = ""
self.address = ""
for keys, value in kwargs.items():
setattr(self,keys, value)
class Ip(A10BaseClass):
"""This class does not support CRUD Operations please use parent.
:param DeviceProxy: The device proxy for REST operations and session handling. Refer to `common/device_proxy.py`
"""
def __init__(self, **kwargs):
self.ERROR_MSG = ""
self.b_key = "ip"
self.DeviceProxy = ""
self.next_hop = {}
for keys, value in kwargs.items():
setattr(self,keys, value)
class Metric(A10BaseClass):
"""This class does not support CRUD Operations please use parent.
:param value: {"minLength": 1, "maxLength": 128, "type": "string", "description": "Metric value", "format": "string"}
:param DeviceProxy: The device proxy for REST operations and session handling. Refer to `common/device_proxy.py`
"""
def __init__(self, **kwargs):
self.ERROR_MSG = ""
self.b_key = "metric"
self.DeviceProxy = ""
self.value = ""
for keys, value in kwargs.items():
setattr(self,keys, value)
class AsPath(A10BaseClass):
"""This class does not support CRUD Operations please use parent.
:param num: {"description": "AS number", "minimum": 1, "type": "number", "maximum": 4294967295, "format": "number"}
:param num2: {"description": "AS number", "minimum": 1, "type": "number", "maximum": 4294967295, "format": "number"}
:param prepend: {"type": "string", "description": "Prepend to the as-path (AS number)", "format": "string-rlx"}
:param DeviceProxy: The device proxy for REST operations and session handling. Refer to `common/device_proxy.py`
"""
def __init__(self, **kwargs):
self.ERROR_MSG = ""
self.b_key = "as-path"
self.DeviceProxy = ""
self.num = ""
self.num2 = ""
self.prepend = ""
for keys, value in kwargs.items():
setattr(self,keys, value)
class CommList(A10BaseClass):
"""This class does not support CRUD Operations please use parent.
:param name: {"description": "Community-list name", "format": "string", "minLength": 1, "not-list": ["v-std", "v-exp"], "maxLength": 128, "type": "string"}
:param v_std: {"description": "Community-list number (standard)", "format": "number", "not-list": ["v-exp", "name"], "maximum": 99, "minimum": 1, "type": "number"}
:param v_exp_delete: {"default": 0, "type": "number", "description": "Delete matching communities", "format": "flag"}
:param v_exp: {"description": "Community-list number (expanded)", "format": "number", "not-list": ["v-std", "name"], "maximum": 199, "minimum": 100, "type": "number"}
:param name_delete: {"default": 0, "type": "number", "description": "Delete matching communities", "format": "flag"}
:param delete: {"default": 0, "type": "number", "description": "Delete matching communities", "format": "flag"}
:param DeviceProxy: The device proxy for REST operations and session handling. Refer to `common/device_proxy.py`
"""
def __init__(self, **kwargs):
self.ERROR_MSG = ""
self.b_key = "comm-list"
self.DeviceProxy = ""
self.name = ""
self.v_std = ""
self.v_exp_delete = ""
self.v_exp = ""
self.name_delete = ""
self.delete = ""
for keys, value in kwargs.items():
setattr(self,keys, value)
class LocalPreference(A10BaseClass):
"""This class does not support CRUD Operations please use parent.
:param val: {"description": "Preference value", "minimum": 0, "type": "number", "maximum": 4294967295, "format": "number"}
:param DeviceProxy: The device proxy for REST operations and session handling. Refer to `common/device_proxy.py`
"""
def __init__(self, **kwargs):
self.ERROR_MSG = ""
self.b_key = "local-preference"
self.DeviceProxy = ""
self.val = ""
for keys, value in kwargs.items():
setattr(self,keys, value)
class Tag(A10BaseClass):
"""This class does not support CRUD Operations please use parent.
:param value: {"description": "Tag value", "minimum": 0, "type": "number", "maximum": 4294967295, "format": "number"}
:param DeviceProxy: The device proxy for REST operations and session handling. Refer to `common/device_proxy.py`
"""
def __init__(self, **kwargs):
self.ERROR_MSG = ""
self.b_key = "tag"
self.DeviceProxy = ""
self.value = ""
for keys, value in kwargs.items():
setattr(self,keys, value)
class Local(A10BaseClass):
"""This class does not support CRUD Operations please use parent.
:param address: {"type": "string", "description": "IPv6 address of next hop", "format": "ipv6-address"}
:param DeviceProxy: The device proxy for REST operations and session handling. Refer to `common/device_proxy.py`
"""
def __init__(self, **kwargs):
self.ERROR_MSG = ""
self.b_key = "local"
self.DeviceProxy = ""
self.address = ""
for keys, value in kwargs.items():
setattr(self,keys, value)
class NextHop1(A10BaseClass):
"""This class does not support CRUD Operations please use parent.
:param address: {"type": "string", "description": "global address of next hop", "format": "ipv6-address"}
:param DeviceProxy: The device proxy for REST operations and session handling. Refer to `common/device_proxy.py`
"""
def __init__(self, **kwargs):
self.ERROR_MSG = ""
self.b_key = "next-hop-1"
self.DeviceProxy = ""
self.local = {}
self.address = ""
for keys, value in kwargs.items():
setattr(self,keys, value)
class Ipv6(A10BaseClass):
"""This class does not support CRUD Operations please use parent.
:param DeviceProxy: The device proxy for REST operations and session handling. Refer to `common/device_proxy.py`
"""
def __init__(self, **kwargs):
self.ERROR_MSG = ""
self.b_key = "ipv6"
self.DeviceProxy = ""
self.next_hop_1 = {}
for keys, value in kwargs.items():
setattr(self,keys, value)
class DampeningCfg(A10BaseClass):
"""This class does not support CRUD Operations please use parent.
:param dampening_max_supress: {"description": "Maximum duration to suppress a stable route(minutes)", "minimum": 1, "type": "number", "maximum": 255, "format": "number"}
:param dampening: {"default": 0, "type": "number", "description": "Enable route-flap dampening", "format": "flag"}
:param dampening_penalty: {"description": "Un-reachability Half-life time for the penalty(minutes)", "minimum": 1, "type": "number", "maximum": 45, "format": "number"}
:param dampening_half_time: {"description": "Reachability Half-life time for the penalty(minutes)", "minimum": 1, "type": "number", "maximum": 45, "format": "number"}
:param dampening_supress: {"description": "Value to start suppressing a route", "minimum": 1, "type": "number", "maximum": 20000, "format": "number"}
:param dampening_reuse: {"description": "Value to start reusing a route", "minimum": 1, "type": "number", "maximum": 20000, "format": "number"}
:param DeviceProxy: The device proxy for REST operations and session handling. Refer to `common/device_proxy.py`
"""
def __init__(self, **kwargs):
self.ERROR_MSG = ""
self.b_key = "dampening-cfg"
self.DeviceProxy = ""
self.dampening_max_supress = ""
self.dampening = ""
self.dampening_penalty = ""
self.dampening_half_time = ""
self.dampening_supress = ""
self.dampening_reuse = ""
for keys, value in kwargs.items():
setattr(self,keys, value)
class OriginatorId(A10BaseClass):
"""This class does not support CRUD Operations please use parent.
:param originator_ip: {"type": "string", "description": "IP address of originator", "format": "ipv4-address"}
:param DeviceProxy: The device proxy for REST operations and session handling. Refer to `common/device_proxy.py`
"""
def __init__(self, **kwargs):
self.ERROR_MSG = ""
self.b_key = "originator-id"
self.DeviceProxy = ""
self.originator_ip = ""
for keys, value in kwargs.items():
setattr(self,keys, value)
class MetricType(A10BaseClass):
"""This class does not support CRUD Operations please use parent.
:param value: {"enum": ["external", "internal", "type-1", "type-2"], "type": "string", "description": "'external': IS-IS external metric type; 'internal': IS-IS internal metric type; 'type-1': OSPF external type 1 metric; 'type-2': OSPF external type 2 metric; ", "format": "enum"}
:param DeviceProxy: The device proxy for REST operations and session handling. Refer to `common/device_proxy.py`
"""
def __init__(self, **kwargs):
self.ERROR_MSG = ""
self.b_key = "metric-type"
self.DeviceProxy = ""
self.value = ""
for keys, value in kwargs.items():
setattr(self,keys, value)
class Set(A10BaseClass):
"""Class Description::
Set values in destination routing protocol.
Class set supports CRUD Operations and inherits from `common/A10BaseClass`.
This class is the `"PARENT"` class for this module.`
:param atomic_aggregate: {"default": 0, "optional": true, "type": "number", "description": "BGP atomic aggregate attribute", "format": "flag"}
:param community: {"optional": true, "type": "string", "description": "BGP community attribute", "format": "string-rlx"}
:param uuid: {"description": "uuid of the object", "format": "string", "minLength": 1, "modify-not-allowed": 1, "optional": true, "maxLength": 64, "type": "string"}
:param DeviceProxy: The device proxy for REST operations and session handling. Refer to `common/device_proxy.py`
URL for this object::
`https://<Hostname|Ip address>//axapi/v3/route-map/{tag}+{action}+{sequence}/set`.
"""
def __init__(self, **kwargs):
self.ERROR_MSG = ""
self.required=[]
self.b_key = "set"
self.a10_url="/axapi/v3/route-map/{tag}+{action}+{sequence}/set"
self.DeviceProxy = ""
self.extcommunity = {}
self.origin = {}
self.aggregator = {}
self.weight = {}
self.level = {}
self.ip = {}
self.metric = {}
self.as_path = {}
self.comm_list = {}
self.atomic_aggregate = ""
self.community = ""
self.local_preference = {}
self.tag = {}
self.ipv6 = {}
self.dampening_cfg = {}
self.originator_id = {}
self.metric_type = {}
self.uuid = ""
for keys, value in kwargs.items():
setattr(self,keys, value)
|
guilhermejccavalcanti/ontop
|
mapping/core/src/main/java/it/unibz/inf/ontop/spec/mapping/transformer/impl/TMappingProcessor.java
|
<filename>mapping/core/src/main/java/it/unibz/inf/ontop/spec/mapping/transformer/impl/TMappingProcessor.java<gh_stars>0
package it.unibz.inf.ontop.spec.mapping.transformer.impl;
/*
* #%L
* ontop-reformulation-core
* %%
* Copyright (C) 2009 - 2014 Free University of Bozen-Bolzano
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import it.unibz.inf.ontop.datalog.CQIE;
import it.unibz.inf.ontop.datalog.impl.CQContainmentCheckUnderLIDs;
import it.unibz.inf.ontop.model.term.functionsymbol.BuiltinPredicate;
import it.unibz.inf.ontop.model.term.functionsymbol.Predicate;
import it.unibz.inf.ontop.model.term.Function;
import it.unibz.inf.ontop.model.term.Term;
import it.unibz.inf.ontop.spec.mapping.TMappingExclusionConfig;
import it.unibz.inf.ontop.spec.ontology.ClassExpression;
import it.unibz.inf.ontop.spec.ontology.DataPropertyExpression;
import it.unibz.inf.ontop.spec.ontology.DataSomeValuesFrom;
import it.unibz.inf.ontop.spec.ontology.OClass;
import it.unibz.inf.ontop.spec.ontology.ObjectPropertyExpression;
import it.unibz.inf.ontop.spec.ontology.ObjectSomeValuesFrom;
import it.unibz.inf.ontop.spec.ontology.Equivalences;
import it.unibz.inf.ontop.spec.ontology.EquivalencesDAG;
import it.unibz.inf.ontop.spec.ontology.ClassifiedTBox;
import it.unibz.inf.ontop.substitution.Substitution;
import it.unibz.inf.ontop.substitution.impl.SubstitutionUtilities;
import it.unibz.inf.ontop.utils.ImmutableCollectors;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import static it.unibz.inf.ontop.model.OntopModelSingletons.TERM_FACTORY;
public class TMappingProcessor {
private static final boolean noCQC = false;
// TODO: the implementation of EXCLUDE ignores equivalent classes / properties
private static class TMappingIndexEntry implements Iterable<TMappingRule> {
private final List<TMappingRule> rules = new LinkedList<>();
public TMappingIndexEntry copyOf(Predicate newPredicate) {
TMappingIndexEntry copy = new TMappingIndexEntry();
for (TMappingRule rule : rules) {
Function newHead = TERM_FACTORY.getFunction(newPredicate, rule.getHeadTerms());
TMappingRule newRule = new TMappingRule(newHead, rule);
copy.rules.add(newRule);
}
return copy;
}
@Override
public Iterator<TMappingRule> iterator() {
return rules.iterator();
}
/***
*
* This is an optimization mechanism that allows T-mappings to produce a
* smaller number of mappings, and hence, the unfolding will be able to
* produce fewer queries.
*
* Given a set of mappings for a class/property A in currentMappings
* , this method tries to add a the data coming from a new mapping for A in
* an optimal way, that is, this method will attempt to include the content
* of coming from newmapping by modifying an existing mapping
* instead of adding a new mapping.
*
* <p/>
*
* To do this, this method will strip newmapping from any
* (in)equality conditions that hold over the variables of the query,
* leaving only the raw body. Then it will look for another "stripped"
* mapping <bold>m</bold> in currentMappings such that m is
* equivalent to stripped(newmapping). If such a m is found, this method
* will add the extra semantics of newmapping to "m" by appending
* newmapping's conditions into an OR atom, together with the existing
* conditions of m.
*
* </p>
* If no such m is found, then this method simply adds newmapping to
* currentMappings.
*
*
* <p/>
* For example. If new mapping is equal to
* <p/>
*
* S(x,z) :- R(x,y,z), y = 2
*
* <p/>
* and there exists a mapping m
* <p/>
* S(x,z) :- R(x,y,z), y > 7
*
* This method would modify 'm' as follows:
*
* <p/>
* S(x,z) :- R(x,y,z), OR(y > 7, y = 2)
*
* <p/>
*
*/
public void mergeMappingsWithCQC(TMappingRule newRule) {
// Facts are just added
if (newRule.isFact()) {
rules.add(newRule);
return;
}
if (noCQC) {
for (TMappingRule r : rules)
if (r.equals(newRule))
return;
rules.add(newRule);
return;
}
Iterator<TMappingRule> mappingIterator = rules.iterator();
while (mappingIterator.hasNext()) {
TMappingRule currentRule = mappingIterator.next();
// ROMAN (14 Oct 2015): quick fix, but one has to be more careful with variables in filters
if (currentRule.equals(newRule))
return;
boolean couldIgnore = false;
Substitution toNewRule = newRule.computeHomomorphsim(currentRule);
if ((toNewRule != null) && checkConditions(newRule, currentRule, toNewRule)) {
if (newRule.databaseAtomsSize() < currentRule.databaseAtomsSize()) {
couldIgnore = true;
}
else {
// if the new mapping is redundant and there are no conditions then do not add anything
return;
}
}
Substitution fromNewRule = currentRule.computeHomomorphsim(newRule);
if ((fromNewRule != null) && checkConditions(currentRule, newRule, fromNewRule)) {
// The existing query is more specific than the new query, so we
// need to add the new query and remove the old
mappingIterator.remove();
continue;
}
if (couldIgnore) {
// if the new mapping is redundant and there are no conditions then do not add anything
return;
}
if ((toNewRule != null) && (fromNewRule != null)) {
// We found an equivalence, we will try to merge the conditions of
// newRule into the currentRule
//System.err.println("\n" + newRule + "\n v \n" + currentRule + "\n");
// Here we can merge conditions of the new query with the one we have
// just found
// new map always has just one set of filters !!
List<Function> newconditions = TMappingRule.cloneList(newRule.getConditions().get(0));
for (Function f : newconditions)
SubstitutionUtilities.applySubstitution(f, fromNewRule);
List<List<Function>> existingconditions = currentRule.getConditions();
List<List<Function>> filterAtoms = new ArrayList<>(existingconditions.size() + 1);
for (List<Function> econd : existingconditions) {
boolean found2 = true;
for (Function ec : econd)
if (!newconditions.contains(ec)) {
found2 = false;
break;
}
// if each of the existing conditions is found then the new condition is redundant
if (found2)
return;
boolean found = true;
for (Function nc : newconditions)
if (!econd.contains(nc)) {
found = false;
break;
}
// if each of the new conditions is found among econd then the old condition is redundant
if (found) {
//System.err.println(econd + " contains " + newconditions);
}
else
filterAtoms.add(TMappingRule.cloneList(econd));
}
filterAtoms.add(newconditions);
mappingIterator.remove();
newRule = new TMappingRule(currentRule, filterAtoms);
break;
}
}
rules.add(newRule);
}
private boolean checkConditions(TMappingRule rule1, TMappingRule rule2, Substitution toRule1) {
if (rule2.getConditions().size() == 0)
return true;
if (rule2.getConditions().size() > 1 || rule1.getConditions().size() != 1)
return false;
List<Function> conjucntion1 = rule1.getConditions().get(0);
List<Function> conjunction2 = TMappingRule.cloneList(rule2.getConditions().get(0));
for (Function f : conjunction2) {
SubstitutionUtilities.applySubstitution(f, toRule1);
if (!conjucntion1.contains(f))
return false;
}
return true;
}
}
// end of the inner class
/**
* constructs the TMappings for object properties using DAG
* @param mappingIndex
* @param originalMappings
* @param dag
*/
private static void getObjectTMappings(Map<Predicate, TMappingIndexEntry> mappingIndex,
Map<Predicate, List<TMappingRule>> originalMappings,
EquivalencesDAG<ObjectPropertyExpression> dag,
TMappingExclusionConfig excludeFromTMappings) {
for (Equivalences<ObjectPropertyExpression> propertySet : dag) {
ObjectPropertyExpression representative = propertySet.getRepresentative();
if (representative.isInverse())
continue;
if (excludeFromTMappings.contains(representative)) {
continue;
}
/* Getting the current node mappings */
Predicate currentPredicate = representative.getPredicate();
TMappingIndexEntry currentNodeMappings = getMappings(mappingIndex, currentPredicate);
for (Equivalences<ObjectPropertyExpression> descendants : dag.getSub(propertySet)) {
for(ObjectPropertyExpression childproperty : descendants) {
/*
* adding the mappings of the children as own mappings, the new
* mappings use the current predicate instead of the child's
* predicate and, if the child is inverse and the current is
* positive, it will also invert the terms in the head
*/
List<TMappingRule> childmappings = originalMappings.get(childproperty.getPredicate());
if (childmappings == null)
continue;
for (TMappingRule childmapping : childmappings) {
List<Term> terms = childmapping.getHeadTerms();
Function newMappingHead = !childproperty.isInverse()
? TERM_FACTORY.getFunction(currentPredicate, terms)
: TERM_FACTORY.getFunction(currentPredicate, terms.get(1), terms.get(0));
TMappingRule newmapping = new TMappingRule(newMappingHead, childmapping);
currentNodeMappings.mergeMappingsWithCQC(newmapping);
}
}
}
/* Setting up mappings for the equivalent classes */
for (ObjectPropertyExpression equivProperty : propertySet) {
if (!equivProperty.isInverse())
setMappings(mappingIndex, equivProperty.getPredicate(), currentNodeMappings);
}
} // Properties loop ended
}
/**
* constructs the TMappings for data properties using DAG
* @param mappingIndex
* @param originalMappings
* @param dag
*/
private static void getDataTMappings(Map<Predicate, TMappingIndexEntry> mappingIndex,
Map<Predicate, List<TMappingRule>> originalMappings,
EquivalencesDAG<DataPropertyExpression> dag,
TMappingExclusionConfig excludeFromTMappings) {
for (Equivalences<DataPropertyExpression> propertySet : dag) {
DataPropertyExpression representative = propertySet.getRepresentative();
if (excludeFromTMappings.contains(representative)) {
continue;
}
/* Getting the current node mappings */
Predicate currentPredicate = representative.getPredicate();
TMappingIndexEntry currentNodeMappings = getMappings(mappingIndex, currentPredicate);
for (Equivalences<DataPropertyExpression> descendants : dag.getSub(propertySet)) {
for(DataPropertyExpression childproperty : descendants) {
/*
* adding the mappings of the children as own mappings, the new
* mappings use the current predicate instead of the child's
* predicate and, if the child is inverse and the current is
* positive, it will also invert the terms in the head
*/
List<TMappingRule> childmappings = originalMappings.get(childproperty.getPredicate());
if (childmappings == null)
continue;
for (TMappingRule childmapping : childmappings) {
List<Term> terms = childmapping.getHeadTerms();
Function newMappingHead = TERM_FACTORY.getFunction(currentPredicate, terms);
TMappingRule newmapping = new TMappingRule(newMappingHead, childmapping);
currentNodeMappings.mergeMappingsWithCQC(newmapping);
}
}
}
/* Setting up mappings for the equivalent classes */
for (DataPropertyExpression equivProperty : propertySet) {
setMappings(mappingIndex, equivProperty.getPredicate(), currentNodeMappings);
}
} // Properties loop ended
}
/**
* constructs the TMappings using DAG
* @param originalMappings
* @param reasoner
* @return
*/
public static List<CQIE> getTMappings(List<CQIE> originalMappings, ClassifiedTBox reasoner, CQContainmentCheckUnderLIDs cqc, TMappingExclusionConfig excludeFromTMappings) {
final boolean printouts = false;
if (printouts)
System.out.println("ORIGINAL MAPPING SIZE: " + originalMappings.size());
if (excludeFromTMappings == null)
throw new NullPointerException("excludeFromTMappings");
Map<Predicate, TMappingIndexEntry> mappingIndex = new HashMap<>();
Map<Predicate, List<TMappingRule>> originalMappingIndex = new HashMap<>();
/***
* Creates an index of all mappings based on the predicate of the head of
* the mapping. The returned map can be used for fast access to the mapping
* list.
*/
//CQContainmentCheckUnderLIDs cqc0 = new CQContainmentCheckUnderLIDs(null);
if (printouts)
System.out.println("===CHECKING REDUNDANCY: " + cqc);
for (CQIE mapping : originalMappings) {
if (!noCQC)
mapping = cqc.removeRedundantAtoms(mapping);
else {
int c = 0;
for (Function a : mapping.getBody())
if (!(a.getFunctionSymbol() instanceof BuiltinPredicate))
c++;
if (c == 1)
CQContainmentCheckUnderLIDs.oneAtomQs++;
else if (c == 2)
CQContainmentCheckUnderLIDs.twoAtomQs++;
}
TMappingRule rule = new TMappingRule(mapping.getHead(), mapping.getBody(), cqc);
Predicate ruleIndex = mapping.getHead().getFunctionSymbol();
List<TMappingRule> ms = originalMappingIndex.get(ruleIndex);
if (ms == null) {
ms = new LinkedList<>();
originalMappingIndex.put(ruleIndex, ms);
}
ms.add(rule);
TMappingIndexEntry set = getMappings(mappingIndex, ruleIndex);
set.mergeMappingsWithCQC(rule);
}
if (printouts)
System.out.println("===END OF CHECKING REDUNDANCY: " + CQContainmentCheckUnderLIDs.oneAtomQs + "/" + CQContainmentCheckUnderLIDs.twoAtomQs);
/*
* We start with the property mappings, since class t-mappings require
* that these are already processed.
* Processing mappings for all Properties
*
* We process the mappings for the descendants of the current node,
* adding them to the list of mappings of the current node as defined in
* the TMappings specification.
*/
getObjectTMappings(mappingIndex, originalMappingIndex, reasoner.objectPropertiesDAG(), excludeFromTMappings);
getDataTMappings(mappingIndex, originalMappingIndex, reasoner.dataPropertiesDAG(), excludeFromTMappings);
/*
* Property t-mappings are done, we now continue with class t-mappings.
*/
for (Equivalences<ClassExpression> classSet : reasoner.classesDAG()) {
if (!(classSet.getRepresentative() instanceof OClass))
continue;
OClass representative = (OClass)classSet.getRepresentative();
if (excludeFromTMappings.contains(representative)) {
continue;
}
/* Getting the current node mappings */
Predicate currentPredicate = representative.getPredicate();
TMappingIndexEntry currentNodeMappings = getMappings(mappingIndex, currentPredicate);
for (Equivalences<ClassExpression> descendants : reasoner.classesDAG().getSub(classSet)) {
for (ClassExpression childDescription : descendants) {
/* adding the mappings of the children as own mappings, the new
* mappings. There are three cases, when the child is a named
* class, or when it is an \exists P or \exists \inv P.
*/
final int arg;
final Predicate childPredicate;
if (childDescription instanceof OClass) {
childPredicate = ((OClass) childDescription).getPredicate();
arg = 0;
}
else if (childDescription instanceof ObjectSomeValuesFrom) {
ObjectPropertyExpression some = ((ObjectSomeValuesFrom) childDescription).getProperty();
childPredicate = some.getPredicate();
arg = some.isInverse() ? 1 : 0;
}
else {
assert (childDescription instanceof DataSomeValuesFrom);
DataPropertyExpression some = ((DataSomeValuesFrom) childDescription).getProperty();
childPredicate = some.getPredicate();
arg = 0; // can never be an inverse
}
List<TMappingRule> childmappings = originalMappingIndex.get(childPredicate);
if (childmappings == null)
continue;
for (TMappingRule childmapping : childmappings) {
List<Term> terms = childmapping.getHeadTerms();
Function newMappingHead = TERM_FACTORY.getFunction(currentPredicate, terms.get(arg));
TMappingRule newmapping = new TMappingRule(newMappingHead, childmapping);
currentNodeMappings.mergeMappingsWithCQC(newmapping);
}
}
}
/* Setting up mappings for the equivalent classes */
for (ClassExpression equiv : classSet) {
if (equiv instanceof OClass)
setMappings(mappingIndex, ((OClass) equiv).getPredicate(), currentNodeMappings);
}
}
List<CQIE> tmappingsProgram = new LinkedList<>();
for (Entry<Predicate, TMappingIndexEntry> entry : mappingIndex.entrySet()) {
for (TMappingRule mapping : entry.getValue()) {
CQIE cq = mapping.asCQIE();
tmappingsProgram.add(cq);
}
}
List<CQIE> nonOntologyRules = originalMappingIndex.entrySet().stream()
.filter(e -> !mappingIndex.containsKey(e.getKey()))
.flatMap(e -> e.getValue().stream())
.map(m -> m.asCQIE())
.collect(ImmutableCollectors.toList());
tmappingsProgram.addAll(nonOntologyRules);
if (printouts) {
Map<Integer, Set<Predicate>> frequences = new HashMap<>();
for (Entry<Predicate, TMappingIndexEntry> entry : mappingIndex.entrySet()) {
if (!entry.getValue().rules.isEmpty()) {
Set<Predicate> freq = frequences.get(entry.getValue().rules.size());
if (freq == null) {
freq = new HashSet<>();
frequences.put(entry.getValue().rules.size(), freq);
}
freq.add(entry.getKey());
}
}
System.out.println("T-MAPPING SIZE: " + tmappingsProgram.size());
List<Integer> sorted = new ArrayList<>(frequences.keySet());
Collections.sort(sorted);
for (Integer idx : sorted) {
for (Predicate p : frequences.get(idx)) {
TMappingIndexEntry e = mappingIndex.get(p);
System.out.println(p + " " + e.rules.size());
for (TMappingRule r : e.rules)
System.out.println(" " + r.asCQIE());
}
}
int total = 0;
for (Integer idx: sorted) {
System.out.println(" " + idx + ": " + frequences.get(idx).size() + " " + frequences.get(idx));
total += frequences.get(idx).size();
}
System.out.println("NUMBER OF PREDICATES: " + total);
System.out.println("TMAP " + tmappingsProgram);
}
return tmappingsProgram;
}
private static TMappingIndexEntry getMappings(Map<Predicate, TMappingIndexEntry> mappingIndex, Predicate current) {
TMappingIndexEntry currentMappings = mappingIndex.get(current);
if (currentMappings == null) {
currentMappings = new TMappingIndexEntry();
mappingIndex.put(current, currentMappings);
}
return currentMappings;
}
private static void setMappings(Map<Predicate, TMappingIndexEntry> mappingIndex, Predicate predicate, TMappingIndexEntry mapping) {
mappingIndex.put(predicate, mapping.copyOf(predicate));
}
}
|
amznero/graph-learn
|
graphlearn/python/graph.py
|
# Copyright 2020 Alibaba Group Holding Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# =============================================================================
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import atexit
import json
import warnings
import numpy as np
from graphlearn import pywrap_graphlearn as pywrap
from graphlearn.python.server import Server
import graphlearn.python.data as data
import graphlearn.python.errors as errors
import graphlearn.python.gsl as gsl
import graphlearn.python.operator as ops
import graphlearn.python.sampler as samplers
import graphlearn.python.utils as utils
class Graph(object):
""" Entry of graph data operations, such as cluster initialization, data
loading and sampling. Both homogeneous and heterogeneous graphs are supported.
To use GL, we should define a Graph object first.
```
import graphlearn as gl
g = gl.Graph()
```
Based on a Graph object, we can do things through the APIs below.
node(): Add a kind of VERTEX with vertex type and data schema.
edge(): Add a kind of EDGE with (src_type, edge_type, dst_type) tuple and data schema.
init(): Load and initialize graph data. Cluster info is needed in distributed mode.
get_topology(): Get topology info for heterogeneous graph.
node_sampler(): Create a VERTEX sampler to iterate vertices of given type in this graph.
edge_sampler(): Create an EDGE sampler to iterate edges of given type in this graph.
neighbor_sampler(): Create a NEIGHBOR sampler to sample neighbors for given
vertices according to a metapath.
negative_sampler(): Create a NEGATIVE sampler to sample un-neighbored vertices
for given inputs according to a metapath.
subgraph_sampler(): Create SUBGRAPH sampler to sample a sub-graph.
V(): Entry of GSL, starting with VERTEX sampling.
E(): Entry of GSL, starting with EDGE sampling.
"""
def __init__(self):
# list of NodeSource added by .node()
self._node_sources = []
# list of EdgeSource added by .edge()
self._edge_sources = []
# list of NodeSource added by .node()
# maintain the graph's static topology for fast query.
self._topology = data.Topology()
# maintain a map of node_type with it's decoder
self._node_decoders = {}
# maintain a map of edge_type with it's decoder
self._edge_decoders = {}
self._undirected_edges = []
self._server = None
self._client = None
self.node_state = data.NodeState()
self.edge_state = data.EdgeState()
self._datasets = []
def stop_sampling():
if self._server:
self._server.stop_sampling()
atexit.register(stop_sampling)
def node(self,
source,
node_type,
decoder,
option=None,
mask=utils.Mask.NONE):
""" Add graph vertices that will be loaded from a given path.
Args:
source (string): Data source path where to load the nodes.
node_type (string): Indicates the type of the added nodes.
decoder (Decoder): A Decoder object to describe the data schema.
mask (TRAIN | TEST | VAL): Mark the source as TRAIN data, TEST data
or VAL data for the given node_type in the graph.
"""
if not isinstance(source, str):
raise ValueError('source for node() must be string.')
if not isinstance(node_type, str):
raise ValueError('node_type for node() must be string.')
if not isinstance(decoder, data.Decoder):
raise ValueError('decoder must be an instance of `Decoder`, got {}'
.format(type(decoder)))
node_type = utils.get_mask_type(node_type, mask)
self._node_decoders[node_type] = decoder
node_source = self._construct_node_source(source, node_type, decoder, option)
self._node_sources.append(node_source)
return self
def edge(self,
source,
edge_type,
decoder=None,
directed=True,
option=None,
mask=utils.Mask.NONE):
""" Add graph edges that will be loaded from a given path.
Args:
source (string): Data source path where to load the edges.
edge_type (tuple): A tuple of (src_type, dst_type, edge_type) that
indicates types of the edges.
decoder (Decoder): A Decoder object to describe the data schema.
directed (boolean): Whether edges are directed.
mask (TRAIN | TEST | VAL): Mark the source as TRAIN data, TEST data
or VAL data for the given edge_type in the graph.
"""
if not isinstance(source, str):
raise ValueError('source for edge() must be a string.')
if not isinstance(edge_type, tuple) or len(edge_type) != 3:
raise ValueError("edge_type for edge() must be a tuple of "
"(src_type, dst_tye, edge_type).")
if not decoder:
decoder = data.Decoder()
if not isinstance(decoder, data.Decoder):
raise ValueError('decoder must be an instance of Decoder, got {}'
.format(type(decoder)))
masked_edge_type = utils.get_mask_type(edge_type[2], mask)
self._edge_decoders[masked_edge_type] = decoder
self._topology.add(masked_edge_type, edge_type[0], edge_type[1])
edge_source = self._construct_edge_source(
source, (edge_type[0], edge_type[1], masked_edge_type),
decoder,
direction=pywrap.Direction.ORIGIN,
option=option)
self._edge_sources.append(edge_source)
if not directed:
self.add_reverse_edges(edge_type, source, decoder, option)
return self
@property
def undirected_edges(self):
return self._undirected_edges
def add_reverse_edges(self, edge_type, source, decoder, option):
self._undirected_edges.append(edge_type[2])
if (edge_type[0] != edge_type[1]): # pylint: disable=superfluous-parens
reversed_edge_type = edge_type[2] + '_reverse'
edge_source_reverse = self._construct_edge_source(
source,
(edge_type[1], edge_type[0], reversed_edge_type),
decoder,
direction=pywrap.Direction.REVERSED,
option=option)
self._edge_sources.append(edge_source_reverse)
self._edge_decoders[reversed_edge_type] = decoder
self._topology.add(reversed_edge_type, edge_type[1], edge_type[0])
else:
edge_source_reverse = self._construct_edge_source(
source,
edge_type,
decoder,
direction=pywrap.Direction.REVERSED,
option=option)
self._edge_sources.append(edge_source_reverse)
def init(self, task_index=0, task_count=1,
cluster="", job_name="", **kwargs):
""" Initialize the graph object in local mode or distributed mode.
If deployed in local mode, just call `g.init()` without any parameters.
If in distributed, you should care about WORKER mode and SERVER mode.
Args:
task_index (int): Current task index.
If in WORKER mode, it means the current worker index.
If in SERVER mode, it means the current server index.
task_count (int): Total task count. Only needed in WORKER mode.
It means in the total worker count.
cluster (dict | json string): Only needed in SERVER mode.
3 kinds of schemas are supported:
cluster = {
"server_count": 2,
"client_count": 4,
"tracker": "root://graphlearn"
}
cluster = {
"server": "127.0.0.2:6666,127.0.0.3:7777",
"client": "127.0.0.4:8888,127.0.0.5:9999"
}
cluster = {
"server": "127.0.0.2:6666,127.0.0.3:7777",
"client_count", 2
}
server_count (int): count of servers.
client_count (int): count of clients.
server (string): hosts of servers, split by ','.
job_name (str): `client` or `server`. Only needed in SERVER mode.
kwargs:
tracker (string): Optional tracker path for WORKER mode.
hosts (string): Optional worker hosts for WORKER mode.
"""
if not cluster and task_count == 1:
# Local mode
pywrap.set_deploy_mode(pywrap.DeployMode.LOCAL)
self.deploy_in_local_mode()
elif not cluster:
if task_count > 1 or kwargs.get("hosts") is not None:
# WORKER mode
pywrap.set_deploy_mode(pywrap.DeployMode.WORKER)
tracker = kwargs.get("tracker", "root://graphlearn")
hosts = kwargs.get("hosts")
self.deploy_in_worker_mode(tracker, hosts, task_index, task_count)
else:
# SERVER mode
pywrap.set_deploy_mode(pywrap.DeployMode.SERVER)
self.deploy_in_server_mode(task_index, cluster, job_name)
return self
def deploy_in_local_mode(self):
self._client = pywrap.in_memory_client()
self._server = Server(0, 1, "", "")
self._server.start()
self._server.init(self._edge_sources, self._node_sources)
def deploy_in_worker_mode(self, tracker, hosts, task_index, task_count):
if hosts:
pywrap.set_server_hosts(hosts)
hosts = hosts.split(',')
host = hosts[task_index]
task_count = len(hosts)
else:
host = "0.0.0.0:0"
assert task_index < task_count
pywrap.set_client_id(task_index)
pywrap.set_client_count(task_count)
pywrap.set_server_count(task_count)
pywrap.set_tracker(tracker)
self._client = pywrap.in_memory_client()
self._server = Server(task_index, task_count, host, tracker)
self._server.start()
self._server.init(self._edge_sources, self._node_sources)
def deploy_in_server_mode(self, task_index, cluster, job_name):
if isinstance(cluster, dict):
cluster_spec = cluster
elif isinstance(cluster, str):
cluster_spec = json.loads(cluster)
else:
raise ValueError("cluster must be dict or json string.")
tracker = cluster_spec.get("tracker", "root://graphlearn")
# parse servers
server_count = cluster_spec.get("server_count")
servers = cluster_spec.get("server")
if servers:
pywrap.set_server_hosts(servers)
servers = servers.split(',')
server_count = len(servers)
# parse clients
client_count = cluster_spec.get("client_count")
clients = cluster_spec.get("client")
if clients:
client_count = len(clients.split(','))
if not server_count or not client_count:
raise ValueError("Invalid cluster schema")
pywrap.set_server_count(server_count)
pywrap.set_client_count(client_count)
if job_name == "client":
pywrap.set_tracker(tracker)
pywrap.set_client_id(task_index)
self._client = pywrap.rpc_client()
self._server = None
elif job_name == "server":
self._client = None
server_host = "0.0.0.0:0" if not servers else servers[task_index]
self._server = Server(task_index, server_count, server_host, tracker)
self._server.start()
self._server.init(self._edge_sources, self._node_sources)
else:
raise ValueError("Only support client and server job name in SERVER mode.")
def add_dataset(self, ds):
self._datasets.append(ds)
def close(self):
self.wait_for_close()
def wait_for_close(self):
for ds in self._datasets:
ds.close()
if self._client:
self._client.stop()
self._client = None
if self._server:
self._server.stop()
self._server = None
def V(self,
t,
feed=None,
node_from=pywrap.NodeFrom.NODE,
mask=utils.Mask.NONE):
""" Entry of GSL, starting from VERTEX.
Args:
t (string): The type of node which is the entry of query or the type
of edge when node is from edge source or dst.
feed (None| numpy.ndarray | types.GeneratorType | `Nodes`): When `feed`
is not `None`, the `type` should be a node type, which means query the
attributes of the specified node ids.
None: Default. Sample nodes with the following .shuffle and .batch API.
numpy.ndarray: Any shape of ids. Get nodes of the given ids and
node_type.
types.Generator: A generator of numpy.ndarray. Get nodes of generated
ids and given node_type.
`Nodes`: A `Nodes` object.
node_from (NodeFrom): Default is `NodeFrom.NODE`, which means sample or
or iterate node from node. `NodeFrom.EDGE_SRC` means sample or
iterate node from source node of edge, and `NodeFrom.EDGE_DST` means
sample or iterate node from destination node of edge. If node is from
edge, the `type` must be an edge type.
mask (NONE | TRAIN | TEST | VAL): The given node set is indexed by both the
raw node type and mask value. The default mask value is NONE, which plays
nothing on the index.
"""
if feed is not None:
raise NotImplementedError("`feed` is not supported for now.")
dag = gsl.Dag(self)
params = {pywrap.kNodeType: utils.get_mask_type(t, mask),
pywrap.kNodeFrom: int(node_from)}
source_node = gsl.TraverseVertexDagNode(
dag, op_name="GetNodes", params=params)
source_node.set_output_field(pywrap.kNodeIds)
source_node.set_path(t, node_from)
# Add sink node to dag
gsl.SinkNode(dag)
return source_node
def E(self,
edge_type,
feed=None,
reverse=False):
""" Entry of GSL, starting from EDGE.
Args:
edge_type (string): The type of edge which is the entry of query.
feed (None| (np.ndarray, np.ndarray) | types.GeneratorType | `Edges`):
None: Default. Sample edges with the following .shuffle and .batch API.
(np.ndarray, np.ndarray): src_ids, dst_ids. Get edges of the given
(src_ids, dst_ids) and given edge_type. src_ids and dst_ids must be
the same shape, dtype is int.
types.Generator: A generator of (numpy.ndarray, numpy.ndarray). Get
edges of generated (src_ids, dst_ids) and given edge_type.
`Edges`: An `Edges` object.
"""
if feed is not None:
raise NotImplementedError("`feed` is not supported for now.")
dag = gsl.Dag(self)
if reverse:
edge_type = edge_type + "_reverse"
dag = gsl.Dag(self)
params = {pywrap.kEdgeType: edge_type}
source_node = gsl.TraverseSourceEdgeDagNode(
dag, op_name="GetEdges", params=params)
source_node.set_output_field(pywrap.kEdgeIds)
source_node.set_path(edge_type, pywrap.NodeFrom.NODE)
# Add sink node to dag
gsl.SinkNode(dag)
return source_node
def get_topology(self):
""" Get the topology of the graph.
Return:
`Topology` object.
"""
return self._topology
def get_node_decoder(self, node_type):
""" Get decoder of the specific node_type.
"""
decoder = self._node_decoders.get(node_type)
if not decoder:
warnings.warn("Node_type {} not exist in graph. Use default decoder."
.format(node_type))
decoder = data.Decoder()
return decoder
def get_edge_decoder(self, edge_type):
""" Get decoder of the specific edge_type.
"""
decoder = self._edge_decoders.get(edge_type)
if not decoder:
warnings.warn("Edge_type {} not exist in graph. Use default decoder."
.format(edge_type))
decoder = data.Decoder()
return decoder
def get_node_decoders(self):
""" Get all of the node_decoders.
"""
return self._node_decoders
def get_edge_decoders(self):
""" Get all of the edge_decoders.
"""
return self._edge_decoders
def get_nodes(self, node_type, ids, offsets=None, shape=None):
'''Get nodes from the graph.
Args:
node_type (string): Type of nodes, which should has been added by
`Graph.node()`.
ids (numpy.ndarray): ids of nodes. In sparse case, it must be 1D.
offsets: (list): To get `SparseNodes`, whose dense shape is 2D,
`offsets` indicates the number of nodes for each line.
Default None means it is a dense `Nodes`.
shape (tuple, Optional): Indicates the shape of nodes ids, attrs, etc.
For dense case, default None means ids.shape. For sparse case, it
must has a value which indicates the 2D dense shape.
Return:
A `Nodes` object or a `SparseNodes` object.
'''
if offsets is None:
nodes = data.Nodes(ids, node_type, shape=shape, graph=self)
else:
nodes = data.SparseNodes(ids, offsets, shape, node_type, graph=self)
return nodes
def get_edges(self, edge_type, src_ids, dst_ids, edge_ids=None, offsets=None,
shape=None, reverse=False):
""" Get edges from the graph.
Args:
edge_type (string): Edge type of edges.
src_ids (numpy.ndarray): Source ids of edges.
dst_ids (numpy.ndarray): Destination ids of edges.
offsets: (list): To get `SparseEdges`, whose dense shape is 2D,
`offsets` indicates the number of edges for each line.
Default None means it is a dense `Edges`.
shape (tuple): Indicates the shape of edge src_ids, dst_ids,
weights, etc. For dense case, default None means src_ids.shape.
For sparse case, it must have a value which indicates the
2D dense shape.
reverse (boolean): Indicates that if the edges are return as reversed.
Default `False` means return the original edges. `True` can be assigned
only if the edges are added to the graph as undirected.
Return:
An `Edges` object or a `SparseEdges` object.
"""
if reverse:
edge_type = edge_type + "_reverse"
src_type = self._topology.get_src_type(edge_type)
dst_type = self._topology.get_dst_type(edge_type)
if offsets is None:
edges = data.Edges(src_ids, src_type,
dst_ids, dst_type,
edge_type,
edge_ids,
shape=shape,
graph=self)
else:
edges = data.SparseEdges(src_ids, src_type,
dst_ids, dst_type,
edge_type,
offsets, shape,
edge_ids,
graph=self)
return edges
def is_directed(self, edge_type):
""" The specific edge_type of edges is directed or not.
"""
decoder = self._edge_decoders.get(edge_type)
if not decoder:
raise ValueError("edge type {} not exist in graph.".format(edge_type))
if edge_type in self._undirected_edges:
return False
return True
def node_sampler(self,
t,
batch_size=64,
strategy="by_order",
node_from=pywrap.NodeFrom.NODE,
mask=utils.Mask.NONE):
""" Sampler for sample one type of nodes.
Args:
t (string): Sample nodes of the given type `t`. `t` can be node type
which indicates that sampling node dat, otherwise, `t` can be
edge type which indicate that sampling source node or dst node of
edge data.
batch_size (int, Optional): How many nodes will be returned for get().
strategy (string, Optional): Indicates how to sample edges,
"by_order", "random" and "shuffle" are supported.
"by_order": Get node by order. Raise `graphlearn.OutOfRangeError` when
all the nodes are visited. Each node will be visited and only be
visited once.
"random": Randomly get nodes. No visting state will be hold, so out of
range will not happened.
"shuffle": Get nodes with shuffle. Raise `graphlearn.OutOfRangeError`
when all the nodes are visited. Each node will be visited and only
be visited once.
node_from (graphlearn.NODE | graphlearn.EDGE_SRC | graphlearn.EDGE_DST):
`graphlearn.NODE`: get node from node data, and `t` must be a node
type.
`graphlearn.EDGE_SRC`: get node from source node of edge data, and `t`
must be an edge type.
`graphlearn.EDGE_DST`: get node from destination node of edge data, and
`t` must be an edge type.
Return:
A `NodeSampler` object.
"""
sampler = utils.strategy2op(strategy, "NodeSampler")
return getattr(samplers, sampler)(self,
t,
batch_size=batch_size,
strategy=strategy,
node_from=node_from,
mask=mask)
def edge_sampler(self,
edge_type,
batch_size=64,
strategy="by_order",
mask=utils.Mask.NONE):
"""Sampler for sample one type of edges.
Args:
edge_type (string): Sample edges of the edge_type.
batch_size (int, Optional): How many edges will be returned for get().
strategy (string, Optional):Indicates how to sample edges,
"by_order", "random" and "shuffle" are supported.
"by_order": Get edge by order. Raise `graphlearn.OutOfRangeError` when
all the edges are visited. Each edge will be visited and only be
visited once.
"random": Randomly get edges. No visting state will be hold, so out of
range will not happened.
"shuffle": Get edges with shuffle. Raise `graphlearn.OutOfRangeError`
when all the edges are visited. Each edge will be visited and only
be visited once.
Return:
An `EdgeSampler` object.
"""
sampler = utils.strategy2op(strategy, "EdgeSampler")
return getattr(samplers, sampler)(self,
edge_type,
batch_size=batch_size,
strategy=strategy,
mask=mask)
def neighbor_sampler(self,
meta_path,
expand_factor,
strategy="random"):
""" Sampler for sample neighbors and edges along a meta path.
The neighbors of the seed nodes and edges between seed nodes and
neighbors are called layer.
Args:
meta_path (list): A list of edge_type.
expand_factor (int | list): Number of neighbors sampled from all
the dst nodes of the node along the corresponding meta_path.
int: indicates the number of neighbors sampled for each node.
list of int: indicates the number of neighbors sampled for each node of
each hop, and length of expand_factor is same with length of meta_path.
strategy (string): Indicates how to sample meta paths,
"edge_weight", "random", "in_degree" are supported.
"edge_weight": sample neighbor nodes by the edge weight between seed
node and dst node.
"random": randomly sample neighbor nodes.
"in_degree": sample neighbor nodes by the in degree of the neighbors.
Return:
A 'NeighborSampler' object.
"""
sampler = utils.strategy2op(strategy, "NeighborSampler")
return getattr(samplers, sampler)(self,
meta_path,
expand_factor,
strategy=strategy)
def negative_sampler(self,
object_type,
expand_factor,
strategy="random",
conditional=False,
**kwargs):
"""Sampler for sampling negative dst nodes of the given src nodes
with edge_type.
Args:
edge_type (string): Sample negative nodes of the source node with
specified edge_type.
strategy (string or list): Indicates how to sample negative edges,
"random" and "in_degree" are supported.
"random": randomly sample negative nodes.
"in_degree": sample negative nodes by the in degree of the target nodes.
expand_factor (int): Indicates how many negatives to sample for one node.
conditional(bool): Indicates whether sample under condition.
Return:
A 'NegativeSampler' object.
"""
if not conditional:
sampler = utils.strategy2op(strategy, "NegativeSampler")
return getattr(samplers, sampler)(self,
object_type,
expand_factor,
strategy=strategy)
else:
return getattr(samplers, "ConditionalNegativeSampler")(self,
object_type,
expand_factor,
strategy=strategy,
**kwargs)
def _construct_node_source(self, path, node_type, decoder=None, option=None):
source = pywrap.NodeSource()
source.id_type = node_type
self._common_construct_source(source, path, decoder, option)
return source
def _construct_edge_source(self,
path,
edge_type,
decoder,
direction=pywrap.Direction.ORIGIN,
option=None):
source = pywrap.EdgeSource()
if isinstance(edge_type, tuple) and len(edge_type) == 3:
source.src_id_type, source.dst_id_type, source.edge_type = edge_type
else:
raise ValueError("edge_type param for .edge must be a tuple with "
"(src_type, dst_type, edge_type)")
source.direction = direction
self._common_construct_source(source, path, decoder, option)
return source
def _common_construct_source(self, source, path, decoder, option=None):
"""Construct pywrap.Source
"""
source.path = path
source.format = decoder.data_format
if option:
source.option = option
else:
source.option = pywrap.IndexOption()
source.option.name = "sort"
if decoder.attributed:
source.attr_info.delimiter = decoder.attr_delimiter
for t in decoder.attr_types:
type_str, bucket_size, is_multival = decoder.parse(t)
if is_multival:
source.attr_info.append_hash_bucket(0)
elif bucket_size is not None:
source.attr_info.append_hash_bucket(bucket_size)
else:
source.attr_info.append_hash_bucket(0)
if type_str == "int":
source.attr_info.append_type(pywrap.DataType.INT64)
elif type_str == "float":
source.attr_info.append_type(pywrap.DataType.FLOAT)
else:
source.attr_info.append_type(pywrap.DataType.STRING)
def lookup_nodes(self, node_type, ids):
""" Get the attributes of given nodes.
"""
ids = np.array(ids)
req = pywrap.new_lookup_nodes_request(node_type)
pywrap.set_lookup_nodes_request(req, ids)
res = pywrap.new_lookup_nodes_response()
status = self._client.lookup_nodes(req, res)
if status.ok():
decoder = self.get_node_decoder(node_type)
weights = pywrap.get_node_weights(res) if decoder.weighted else None
labels = pywrap.get_node_labels(res) if decoder.labeled else None
int_attrs = pywrap.get_node_int_attributes(
res) if decoder.attributed else None
float_attrs = pywrap.get_node_float_attributes(
res) if decoder.attributed else None
string_attrs = pywrap.get_node_string_attributes(
res) if decoder.attributed else None
int_attrs, float_attrs, string_attrs = decoder.format_attrs(
int_attrs, float_attrs, string_attrs)
pywrap.del_op_response(res)
pywrap.del_op_request(req)
errors.raise_exception_on_not_ok_status(status)
return data.Values(
int_attrs=int_attrs,
float_attrs=float_attrs,
string_attrs=string_attrs,
weights=weights,
labels=labels,
graph=self)
def lookup_edges(self, edge_type, src_ids, edge_ids):
""" Get the attributes of given edges.
"""
src_ids = np.array(src_ids)
edge_ids = np.array(edge_ids)
batch_size = src_ids.flatten().size
if batch_size != edge_ids.flatten().size:
raise ValueError("src_ids and edge_ids for lookup edges must "
"be same, got {} and {}"
.format(batch_size, edge_ids.flatten().size))
req = pywrap.new_lookup_edges_request(edge_type)
pywrap.set_lookup_edges_request(req, src_ids, edge_ids)
res = pywrap.new_lookup_edges_response()
status = self._client.lookup_edges(req, res)
if status.ok():
decoder = self.get_edge_decoder(edge_type)
weights = pywrap.get_edge_weights(res) if decoder.weighted else None
labels = pywrap.get_edge_labels(res) if decoder.labeled else None
int_attrs = pywrap.get_edge_int_attributes(
res) if decoder.attributed else None
float_attrs = pywrap.get_edge_float_attributes(
res) if decoder.attributed else None
string_attrs = pywrap.get_edge_string_attributes(
res) if decoder.attributed else None
int_attrs, float_attrs, string_attrs = decoder.format_attrs(
int_attrs, float_attrs, string_attrs)
pywrap.del_op_response(res)
pywrap.del_op_request(req)
errors.raise_exception_on_not_ok_status(status)
return data.Values(
int_attrs=int_attrs,
float_attrs=float_attrs,
string_attrs=string_attrs,
weights=weights,
labels=labels,
graph=self)
def search(self, node_type, inputs, option):
knn = ops.KnnOperator(self._client)
inputs = np.array(inputs)
return knn.search(node_type, inputs, option.k)
def subgraph_sampler(self,
seed_type,
nbr_type,
batch_size=64,
strategy="random_node"):
"""Sampler for sample SubGraph.
Args:
graph (`Graph` object): The graph which sample from.
seed_type (string): Sample seed type, either node type or edge type.
nbr_type (string): Neighbor type of seeds nodes/edges.
batch_size (int): How many nodes will be returned for `get()`.
strategy (string, Optional): Sampling strategy. "random_node".
Return:
An `SubGraphSampler` object.
"""
sampler = utils.strategy2op(strategy, "SubGraphSampler")
return getattr(samplers, sampler)(self,
seed_type,
nbr_type,
batch_size=batch_size,
strategy=strategy)
def get_node_count(self, type):
if type not in self.get_node_decoders().keys():
raise ValueError('Graph has no node type of {}'.format(type))
return self.get_entity_count(type, True)
def get_edge_count(self, type):
if type not in self.get_edge_decoders().keys():
raise ValueError('Graph has no edge type of {}'.format(type))
return self.get_entity_count(type, False)
def get_entity_count(self, type, is_node):
req = pywrap.new_get_count_request(type, is_node=is_node)
res = pywrap.new_get_count_response()
status = self._client.get_count(req, res)
if status.ok():
count = pywrap.get_count(res)
pywrap.del_op_response(res)
pywrap.del_op_request(req)
errors.raise_exception_on_not_ok_status(status)
return count
def _get_degree(self, edge_type, node_from, ids):
req = pywrap.new_get_degree_request(edge_type, node_from)
pywrap.set_degree_request(req, ids)
res = pywrap.new_get_degree_response()
status = self._client.get_degree(req, res)
if status.ok():
degrees = pywrap.get_degree(res)
pywrap.del_op_response(res)
pywrap.del_op_request(req)
errors.raise_exception_on_not_ok_status(status)
return degrees
def in_degrees(self, ids, edge_type):
ids = np.array(ids)
return self._get_degree(edge_type, pywrap.NodeFrom.EDGE_DST, ids)
def out_degrees(self, ids, edge_type):
ids = np.array(ids)
return self._get_degree(edge_type, pywrap.NodeFrom.EDGE_SRC, ids)
def get_client(self):
return self._client
|
joansmith2/picketlink
|
modules/config/src/main/java/org/picketlink/config/federation/IDPType.java
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2008, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.picketlink.config.federation;
import static org.picketlink.common.util.StringUtil.isNotNull;
import static org.picketlink.common.util.StringUtil.isNullOrEmpty;
/**
* IDP Type defines the configuration for an Identity Provider.
* <p/>
* <p/>
* <p/>
* Java class for IDPType complex type.
* <p/>
* <p/>
* The following schema fragment specifies the expected content contained within this class.
* <p/>
* <pre>
* <complexType name="IDPType">
* <complexContent>
* <extension base="{urn:picketlink:identity-federation:config:1.0}ProviderType">
* <sequence>
* <element name="Encryption" type="{urn:picketlink:identity-federation:config:1.0}EncryptionType"
* minOccurs="0"/>
* </sequence>
* <attribute name="AssertionValidity" type="{http://www.w3.org/2001/XMLSchema}long" default="300000" />
* <attribute name="RoleGenerator" type="{http://www.w3.org/2001/XMLSchema}string"
* default="org.picketlink.identity.federation.bindings.tomcat.TomcatRoleGenerator" />
* <attribute name="AttributeManager" type="{http://www.w3.org/2001/XMLSchema}string"
* default="org.picketlink.identity.federation.bindings.tomcat.TomcatAttributeManager" />
* <attribute name="Encrypt" type="{http://www.w3.org/2001/XMLSchema}boolean" default="false" />
* </extension>
* </complexContent>
* </complexType>
* </pre>
*/
public class IDPType extends ProviderType {
protected EncryptionType encryption;
protected String roleGenerator;
protected String attributeManager;
protected Boolean encrypt = Boolean.FALSE;
protected String hostedURI;
/**
* SAML Web Browser SSO Profile has a requirement that the IDP does not respond back in Redirect Binding. Set this
* to false if you want to force the IDP to respond to SPs using the Redirect Binding.
*/
private boolean strictPostBinding = true;
/**
* Tells the IDP if SSL clients should be authenticated.
*/
private boolean sslClientAuthentication = false;
/**
* If the user wants to set a particular {@link IdentityParticipantStack}
*/
private String identityParticipantStack = null;
/**
* Gets the value of the encryption property.
*
* @return possible object is {@link EncryptionType }
*/
public EncryptionType getEncryption() {
return encryption;
}
/**
* Sets the value of the encryption property.
*
* @param value allowed object is {@link EncryptionType }
*/
public void setEncryption(EncryptionType value) {
this.encryption = value;
}
/**
* Gets the value of the roleGenerator property.
*
* @return possible object is {@link String }
*/
public String getRoleGenerator() {
if (roleGenerator == null) {
return "org.picketlink.identity.federation.bindings.tomcat.TomcatRoleGenerator";
} else {
return roleGenerator;
}
}
/**
* Sets the value of the roleGenerator property.
*
* @param value allowed object is {@link String }
*/
public void setRoleGenerator(String value) {
this.roleGenerator = value;
}
/**
* Gets the value of the attributeManager property.
*
* @return possible object is {@link String }
*/
public String getAttributeManager() {
if (attributeManager == null) {
return "org.picketlink.identity.federation.bindings.tomcat.TomcatAttributeManager";
} else {
return attributeManager;
}
}
/**
* Sets the value of the attributeManager property.
*
* @param value allowed object is {@link String }
*/
public void setAttributeManager(String value) {
this.attributeManager = value;
}
/**
* Gets the value of the encrypt property.
*
* @return possible object is {@link Boolean }
*/
public boolean isEncrypt() {
if (encrypt == null) {
return false;
} else {
return encrypt;
}
}
/**
* Sets the value of the encrypt property.
*
* @param value allowed object is {@link Boolean }
*/
public void setEncrypt(Boolean value) {
this.encrypt = value;
}
/**
* Gets the value of the encrypt property.
*
* @return possible object is {@link String}
*/
public String getHostedURI() {
return hostedURI;
}
/**
* Sets the value of the hostedURI property.
*
* @param value allowed object is {@link String}
*/
public void setHostedURI(String hostedURI) {
this.hostedURI = hostedURI;
}
/**
* Import values from another {@link IDPType}
*
* @param other
*/
public void importFrom(IDPType other) {
super.importFrom(other);
String attributeManager = other.getAttributeManager();
if (isNotNull(attributeManager)) {
setAttributeManager(attributeManager);
}
encrypt = other.isEncrypt();
if (isNotNull(other.getRoleGenerator())) {
this.roleGenerator = other.getRoleGenerator();
}
String hostedURI = other.getHostedURI();
if (!isNullOrEmpty(hostedURI)) {
setHostedURI(hostedURI);
}
}
/**
* Sets the value of the strictPostBinding property.
*
* @param value allowed object is {@link Boolean }
*/
public void setStrictPostBinding(boolean strictPostBinding) {
this.strictPostBinding = strictPostBinding;
}
/**
* Gets the value of the strictPostBinding property.
*
* @return possible object is {@link Boolean }
*/
public boolean isStrictPostBinding() {
return this.strictPostBinding;
}
/**
* Gets the value of the supportsSSL property.
*
* @return
*/
public boolean isSSLClientAuthentication() {
return this.sslClientAuthentication;
}
/**
* Sets the value of the supportsSSL property.
*
* @param sslClientAuthentication
*/
public void setSSLClientAuthentication(boolean sslClientAuthentication) {
this.sslClientAuthentication = sslClientAuthentication;
}
/**
* Sets the value of the identityParticipantStack property. The value must be the name of a {@link
* IdentityParticipantStack} subclass.
*
* @param value allowed object is {@link String }
*/
public void setIdentityParticipantStack(String identityParticipantStack) {
this.identityParticipantStack = identityParticipantStack;
}
/**
* Gets the value of the identityParticipantStack property.
*
* @return possible object is {@link String }
*/
public String getIdentityParticipantStack() {
return this.identityParticipantStack;
}
}
|
pauldoo/scratch
|
spraffbot/project/plugins.sbt
|
addSbtPlugin("com.typesafe.sbteclipse" % "sbteclipse-plugin" % "2.4.0")
resolvers += "sonatype-releases" at "https://oss.sonatype.org/content/repositories/releases/"
|
blue42u/hpctoolkit-prof2
|
src/lib/profile/util/atomic_unordered.hpp
|
<filename>src/lib/profile/util/atomic_unordered.hpp
// -*-Mode: C++;-*-
// * BeginRiceCopyright *****************************************************
//
// $HeadURL$
// $Id$
//
// --------------------------------------------------------------------------
// Part of HPCToolkit (hpctoolkit.org)
//
// Information about sources of support for research and development of
// HPCToolkit is at 'hpctoolkit.org' and in 'README.Acknowledgments'.
// --------------------------------------------------------------------------
//
// Copyright ((c)) 2019-2020, Rice University
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of Rice University (RICE) nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// This software is provided by RICE and contributors "as is" and any
// express or implied warranties, including, but not limited to, the
// implied warranties of merchantability and fitness for a particular
// purpose are disclaimed. In no event shall RICE or contributors be
// liable for any direct, indirect, incidental, special, exemplary, or
// consequential damages (including, but not limited to, procurement of
// substitute goods or services; loss of use, data, or profits; or
// business interruption) however caused and on any theory of liability,
// whether in contract, strict liability, or tort (including negligence
// or otherwise) arising in any way out of the use of this software, even
// if advised of the possibility of such damage.
//
// ******************************************************* EndRiceCopyright *
#ifndef HPCTOOLKIT_PROFILE_UTIL_ATOMIC_UNORDERED_H
#define HPCTOOLKIT_PROFILE_UTIL_ATOMIC_UNORDERED_H
#include <atomic>
#include <cmath>
#include <memory>
#include "../stdshim/shared_mutex.hpp"
namespace hpctoolkit::util {
template<class K, class H = std::hash<K>, class Eq = std::equal_to<K>,
class A = std::allocator<K>>
class atomic_unordered_set {
public:
using key_type = K;
using value_type = K;
using size_type = std::size_t;
using difference_type = std::ptrdiff_t;
using hasher = H;
using key_equal = Eq;
using allocator_type = A;
using reference = K&;
using const_reference = const K&;
using pointer = typename std::allocator_traits<A>::pointer;
using const_pointer = typename std::allocator_traits<A>::const_pointer;
/// Constructors for empty sets, with the given initial size.
atomic_unordered_set() : atomic_unordered_set(0) {};
atomic_unordered_set(size_type sz, const A& a)
: atomic_unordered_set(sz, H(), Eq(), a) {};
atomic_unordered_set(size_type sz, const H& h, const A& a)
: atomic_unordered_set(sz, h, Eq(), a) {};
explicit atomic_unordered_set(const A& a)
: atomic_unordered_set(0, H(), Eq(), a) {};
explicit atomic_unordered_set(size_type sz, const H& h = H(),
const Eq& eq = Eq(), const A& a = A());
/// Constructors for sets copied from a given iterator.
template<class It>
atomic_unordered_set(It beg, It end, size_type sz, const A& a)
: atomic_unordered_set(beg, end, sz, H(), Eq(), a) {};
template<class It>
atomic_unordered_set(It beg, It end, size_type sz, const H& h, const A& a)
: atomic_unordered_set(beg, end, sz, h, Eq(), a) {};
template<class It>
atomic_unordered_set(It beg, It end, size_type sz = 0, const H& h = H(),
const Eq& eq = Eq(), const A& a = A());
/// Constructors for sets copied from another set.
// MT: Externally Synchronized (o)
atomic_unordered_set(const atomic_unordered_set& o)
: atomic_unordered_set(o, std::allocator_traits<allocator_type>
::select_on_container_copy_construction(o.get_allocator())) {};
atomic_unordered_set(const atomic_unordered_set& o, const A& a);
/// Constructors for sets moved from another set.
// MT: Externally Synchronized (o)
atomic_unordered_set(atomic_unordered_set&& o)
: atomic_unordered_set(std::move(o), o.m_alloc) {};
atomic_unordered_set(atomic_unordered_set&& o, const A& a);
/// Constructors for sets initialized with an initializer list.
atomic_unordered_set(std::initializer_list<value_type> it, size_type sz,
const A& a)
: atomic_unordered_set(it, sz, H(), Eq(), a) {};
atomic_unordered_set(std::initializer_list<value_type> it, size_type sz,
const H& h, const A& a)
: atomic_unordered_set(it, sz, h, Eq(), a) {};
atomic_unordered_set(std::initializer_list<value_type> it, size_type sz = 0,
const H& h = H(), const Eq& eq = Eq(), const A& a = A())
: atomic_unordered_set(it.begin(), it.end(), sz, h, eq, a) {};
/// Destructor.
~atomic_unordered_set();
/// Copy assignment
// MT: Externally Synchronized (this, o)
atomic_unordered_set& operator=(const atomic_unordered_set& o);
/// Move assignment
// MT: Externally Synchronized (this, o)
atomic_unordered_set& operator=(atomic_unordered_set&& o);
/// Replacement assignment
// MT: Externally Synchronized
atomic_unordered_set& operator=(std::initializer_list<value_type> it);
/// Get the allocator in use by this container.
// MT: Externally Synchronized
A get_allocator() const { return m_alloc; }
// TODO: iterator, const_iterator, begin(), cbegin(), end(), cend()
using iterator = value_type*;
using const_iterator = const value_type*;
iterator begin();
const_iterator begin() const;
const_iterator cbegin() const;
iterator end();
const_iterator end() const;
const_iterator cend() const;
/// Check if the container is empty.
// MT: Internally Synchronized, Unstable
bool empty() const noexcept { return size() == 0; }
/// Get the number of elements currently in the container.
// MT: Internally Synchronized, Unstable
size_type size() const noexcept;
/// Get the (theoretical) upper bound on the size of the container.
// MT: Safe (static/const)
size_type max_size() const noexcept {
return std::numeric_limits<difference_type>::max();
}
/// Clear the container, resulting in an empty set.
// MT: Externally Synchronized
void clear() noexcept;
/// Insert a new element into the container, by copy or by move.
// MT: Internally Synchronized
std::pair<iterator, bool> insert(const value_type& k);
std::pair<iterator, bool> insert(value_type&& k);
/// Insert a new element into the container, with an (unused) hint.
// MT: Internally Synchronized
iterator insert(const_iterator, const value_type& k) { return insert(k).first; }
iterator insert(const_iterator, value_type&& k) { return insert(std::move(k)).first; }
/// Insert a sequence of elements into the container.
// MT: Internally Synchronized
template<class It>
void insert(It beg, It end) { for(It it = beg; it != end; ++it) insert(*it); }
void insert(std::initializer_list<value_type> il) { insert(il.begin(), il.end()); }
/// Insert a new element into the container, by construction.
// MT: Internally Synchronized
template<class... Args>
std::pair<iterator, bool> emplace(Args&&... args);
/// Insert a new element into the container, by construction with a hint.
// MT: Internally Synchronized
template<class... Args>
std::pair<iterator, bool> emplace_hint(const_iterator, Args&&... args) {
return emplace(std::forward<Args>(args)...);
}
/// Remove an element from the container, given its position.
// MT: Externally Synchronized
iterator erase(const_iterator pos);
/// Remove a number of elements from the container.
// MT: Externally Synchronized
iterator erase(const_iterator beg, const_iterator end);
/// Remove the element matching the given one, if it exists.
// MT: Externally Synchronized
size_type erase(const K& k);
/// Swap the contents of two containers.
// MT: Externally Synchronized (this, o)
void swap(atomic_unordered_set& o);
/// Get the number of elements that are equivalent to k.
// MT: Internally Synchronized, Unstable
size_type count(const K& k) const;
/// Find the element if any exist equivalent to k.
// MT: Internally Synchronized, Unstable
iterator find(const K& k);
const_iterator find(const K& k) const;
/// Get the range of elements equivalent to k.
// MT: Internally Synchronized, Unstable
std::pair<iterator,iterator> equal_range(const K& k) {
auto x = find(k);
return {x, x};
}
std::pair<const_iterator,const_iterator> equal_range(const K& k) const {
auto x = find(k);
return {x, x};
}
/// Get the current maximum size of the container.
// MT: Internally Synchronized, Unstable
size_type slot_count() const;
/// Get the current usage factor.
// MT: Internally Synchronized, Unstable
float usage_factor() const;
/// Get the current maximum usage factor.
// MT: Externally Synchronized
float max_usage_factor() const { return max_usage; }
/// Set the current maximum usage factor. May issue a rehash.
// MT: Externally Synchronized
void max_usage_factor(float m);
/// Sets the total number of slots to the larger of sz and size(),
/// and rehashes the contents.
// MT: Externally Synchronized
void rehash(size_type sz);
/// Reserve enough space for the given number of elements.
// MT: Externally Synchronized
void reserve(size_type cnt) {
if(slot_count()*max_usage_factor() > cnt) return;
rehash(std::ceil(cnt / max_usage_factor()));
}
/// Get the function used to hash the elements.
// MT: Externally Synchronized
H hash_function() const { return m_hash; }
/// Get the function used to compare elements.
// MT: Externally Synchronized
Eq key_eq() const { return m_equal; }
private:
// Tuning parameters.
float max_usage;
// Important storage bits, for proper standards compat
H m_hash;
Eq m_equal;
A m_alloc;
};
template<class K, class V, class H = std::hash<K>, class Eq = std::equal_to<K>,
class A = std::allocator<std::pair<const K, V>>>
class atomic_unordered_map {
public:
using key_type = K;
using mapped_type = V;
using value_type = std::pair<const K, V>;
using size_type = std::size_t;
using difference_type = std::ptrdiff_t;
using hasher = H;
using key_equal = Eq;
using allocator_type = A;
using reference = value_type&;
using const_reference = const value_type&;
using pointer = typename std::allocator_traits<A>::pointer;
using const_pointer = typename std::allocator_traits<A>::const_pointer;
/// Constructors for empty sets, with the given initial size.
atomic_unordered_map() : atomic_unordered_map(0) {};
atomic_unordered_map(size_type sz, const A& a)
: atomic_unordered_map(sz, H(), Eq(), a) {};
atomic_unordered_map(size_type sz, const H& h, const A& a)
: atomic_unordered_map(sz, h, Eq(), a) {};
explicit atomic_unordered_map(const A& a)
: atomic_unordered_map(0, H(), Eq(), a) {};
explicit atomic_unordered_map(size_type sz, const H& h = H(),
const Eq& eq = Eq(), const A& a = A())
: lock(), data_cnt(sz), data(nullptr), used(0),
max_usage(0.8), m_hash(h), m_equal(eq), m_alloc(a) {
if(sz != 0) {
data = new std::atomic<value_type*>[sz];
for(size_type i = 0; i < sz; i++)
data[i].store(nullptr, std::memory_order_relaxed);
}
}
/// Constructors for sets copied from a given iterator.
template<class It>
atomic_unordered_map(It beg, It end, size_type sz, const A& a)
: atomic_unordered_map(beg, end, sz, H(), Eq(), a) {};
template<class It>
atomic_unordered_map(It beg, It end, size_type sz, const H& h, const A& a)
: atomic_unordered_map(beg, end, sz, h, Eq(), a) {};
template<class It>
atomic_unordered_map(It beg, It end, size_type sz = 0, const H& h = H(),
const Eq& eq = Eq(), const A& a = A());
/// Constructors for sets copied from another set.
// MT: Externally Synchronized (o)
atomic_unordered_map(const atomic_unordered_map& o)
: atomic_unordered_map(o, std::allocator_traits<allocator_type>
::select_on_container_copy_construction(o.get_allocator())) {};
atomic_unordered_map(const atomic_unordered_map& o, const A& a);
/// Constructors for sets moved from another set.
// MT: Externally Synchronized (o)
atomic_unordered_map(atomic_unordered_map&& o)
: atomic_unordered_map(std::move(o), o.m_alloc) {};
atomic_unordered_map(atomic_unordered_map&& o, const A& a);
/// Constructors for sets initialized with an initializer list.
atomic_unordered_map(std::initializer_list<value_type> it, size_type sz,
const A& a)
: atomic_unordered_map(it, sz, H(), Eq(), a) {};
atomic_unordered_map(std::initializer_list<value_type> it, size_type sz,
const H& h, const A& a)
: atomic_unordered_map(it, sz, h, Eq(), a) {};
atomic_unordered_map(std::initializer_list<value_type> it, size_type sz = 0,
const H& h = H(), const Eq& eq = Eq(), const A& a = A())
: atomic_unordered_map(it.begin(), it.end(), sz, h, eq, a) {};
/// Destructor.
// MT: Externally Synchronized
~atomic_unordered_map() {
for(size_type i = 0; i < data_cnt; i++)
if(data[i]) delete data[i];
if(data != nullptr) delete[] data;
}
/// Copy assignment
// MT: Externally Synchronized (this, o)
atomic_unordered_map& operator=(const atomic_unordered_map& o);
/// Move assignment
// MT: Externally Synchronized (this, o)
atomic_unordered_map& operator=(atomic_unordered_map&& o);
/// Replacement assignment
// MT: Externally Synchronized
atomic_unordered_map& operator=(std::initializer_list<value_type> it);
/// Get the allocator in use by this container.
// MT: Externally Synchronized
A get_allocator() const { return m_alloc; }
class const_iterator {
public:
const_iterator() : max(0), idx(0), data(nullptr) {};
~const_iterator() = default;
const_iterator& operator++(int) { const_iterator tmp=*this; operator++(); return tmp; }
bool operator!=(const const_iterator& o) { return !operator==(o); }
bool operator==(const const_iterator& o) {
if(data == nullptr && o.data == nullptr) return true;
return data == o.data && idx == o.idx;
}
value_type& operator*() { return *operator->(); }
value_type* operator->() { return data[idx].load(std::memory_order_relaxed); }
const_iterator& operator++() { idx++; return _update(); }
private:
friend class atomic_unordered_map;
const_iterator(std::atomic<value_type*>* d, size_type c, size_type i)
: max(c), idx(i), data(d) {};
const_iterator& _update() {
while(idx < max && data[idx].load(std::memory_order_relaxed) == nullptr)
idx++;
return *this;
}
size_type max;
size_type idx;
std::atomic<value_type*>* data;
};
// TODO: iterator, const_iterator, begin(), cbegin(), end(), cend()
using iterator = value_type*;
iterator begin();
const_iterator begin() const { return const_iterator(data, data_cnt, 0)._update(); }
const_iterator cbegin() const { return begin(); }
iterator end();
const_iterator end() const { return const_iterator(data, data_cnt, data_cnt); }
const_iterator cend() const { return end(); }
/// Check if the container is empty.
// MT: Internally Synchronized, Unstable
bool empty() const noexcept { return size() == 0; }
/// Get the number of elements currently in the container.
// MT: Internally Synchronized, Unstable
size_type size() const noexcept {
return used.load(std::memory_order_relaxed);
}
/// Get the (theoretical) upper bound on the size of the container.
// MT: Safe (static/const)
size_type max_size() const noexcept {
return std::numeric_limits<difference_type>::max();
}
/// Clear the container, resulting in an empty set.
// MT: Externally Synchronized
void clear() noexcept;
/// Insert a new element into the container, by copy or by move.
// MT: Internally Synchronized
std::pair<iterator, bool> insert(const value_type& k);
std::pair<iterator, bool> insert(value_type&& k);
/// Insert a new element into the container, with an (unused) hint.
// MT: Internally Synchronized
iterator insert(const_iterator, const value_type& k) { return insert(k).first; }
iterator insert(const_iterator, value_type&& k) { return insert(std::move(k)).first; }
/// Insert a sequence of elements into the container.
// MT: Internally Synchronized
template<class It>
void insert(It beg, It end) { for(It it = beg; it != end; ++it) insert(*it); }
void insert(std::initializer_list<value_type> il) { insert(il.begin(), il.end()); }
/// Insert a new element into the container, by construction.
// MT: Internally Synchronized
template<class... Args>
std::pair<iterator, bool> emplace(Args&&... args) {
std::shared_lock<stdshim::shared_mutex> lk(lock);
return _emplace(lk, std::forward<Args>(args)...);
// Speculate that we will insert. Prep things to do so.
value_type* newvp = new value_type(std::forward<Args>(args)...);
auto mused = used.fetch_add(1, std::memory_order_relaxed);
reserve(mused+1, lk);
// Now do the insertion.
std::size_t hi = m_hash(newvp->first);
for(unsigned int i = 0; true; i++) {
value_type* vp = _probe(hi, newvp, lk);
if(vp == nullptr) return {newvp, true};
if(m_equal(vp->first, newvp->first)) {
delete newvp;
return {vp, false};
}
hi = _nexthash(hi, i+1);
}
}
/// Insert a new element into the container, by construction with a hint.
// MT: Internally Synchronized
template<class... Args>
std::pair<iterator, bool> emplace_hint(const_iterator, Args&&... args) {
return emplace(std::forward<Args>(args)...);
}
/// Insert a new element into the container, by construction, unless there is
/// already an element with the specified key.
// MT: Internally Synchronized
template<class... Args>
std::pair<iterator,bool> try_emplace(const K& k, Args&&... args) {
std::shared_lock<stdshim::shared_mutex> lk(lock);
auto x = _find(k, lk);
if(x != nullptr) return {x, false};
return _emplace(lk, std::piecewise_construct,
std::forward_as_tuple(k),
std::forward_as_tuple(std::forward<Args>(args)...));
}
template<class... Args>
std::pair<iterator,bool> try_emplace(K&& k, Args&&... args) {
std::shared_lock<stdshim::shared_mutex> lk(lock);
auto x = _find(std::move(k), lk);
if(x != nullptr) return {x, false};
return _emplace(lk, std::piecewise_construct,
std::forward_as_tuple(std::move(k)),
std::forward_as_tuple(std::forward<Args>(args)...));
}
template<class... Args>
iterator try_emplace(const_iterator h, const K& k, Args&&... args);
template<class... Args>
iterator try_emplace(const_iterator h, K&& k, Args&&... args);
/// Remove an element from the container, given its position.
// MT: Externally Synchronized
iterator erase(const_iterator pos);
/// Remove a number of elements from the container.
// MT: Externally Synchronized
iterator erase(const_iterator beg, const_iterator end);
/// Remove the element matching the given one, if it exists.
// MT: Externally Synchronized
size_type erase(const K& k);
/// Swap the contents of two containers.
// MT: Externally Synchronized (this, o)
void swap(atomic_unordered_map& o);
/// Looks up a value in the container, throwing std::out_of_range if not found.
// MT: Internally Synchronized, Unstable
V& at(const K& k) {
auto it = find(k);
if(it == end()) throw std::out_of_range();
return it->second;
}
const V& at(const K& k) const {
auto it = find(k);
if(it == end()) throw std::out_of_range();
return it->second;
}
/// Access the element mapped from the given key, inserting it if not present.
// MT: Internally Synchronized
V& operator[](const K& k) {
return try_emplace(k).first->second;
}
V& operator[](K&& k) {
return try_emplace(std::move(k)).first->second;
}
/// Get the number of elements that are equivalent to k.
// MT: Internally Synchronized, Unstable
size_type count(const K& k) const;
/// Find the element if any exist equivalent to k.
// MT: Internally Synchronized, Unstable
iterator find(const K& k) {
std::shared_lock<stdshim::shared_mutex> lk(lock);
return _find(std::move(k), lk);
}
iterator find_pointer(const K& k) const {
std::shared_lock<stdshim::shared_mutex> lk(lock);
return _find(std::move(k), lk);
}
const_iterator find(const K& k) const;
/// Get the range of elements equivalent to k.
// MT: Internally Synchronized, Unstable
std::pair<iterator,iterator> equal_range(const K& k) {
auto x = find(k);
return {x, x};
}
std::pair<const_iterator,const_iterator> equal_range(const K& k) const {
auto x = find(k);
return {x, x};
}
/// Get the current maximum size of the container.
// MT: Internally Synchronized, Unstable
size_type slot_count() const;
/// Get the current usage factor.
// MT: Internally Synchronized, Unstable
float usage_factor() const;
/// Get the current maximum usage factor.
// MT: Externally Synchronized
float max_usage_factor() const { return max_usage; }
/// Set the current maximum usage factor. May issue a rehash.
// MT: Externally Synchronized
void max_usage_factor(float m);
/// Sets the total number of slots to the larger of sz and size(),
/// and rehashes the contents.
// MT: Externally Synchronized
void rehash(size_type sz) {
sz = std::max(sz, size());
auto olddata = data;
auto olddata_cnt = data_cnt;
data = new std::atomic<value_type*>[sz];
data_cnt = sz;
for(size_type idx = 0; idx < data_cnt; idx++)
data[idx].store(nullptr, std::memory_order_relaxed);
for(size_type idx = 0; idx < olddata_cnt; idx++) {
auto vp = olddata[idx].load(std::memory_order_relaxed);
if(vp != nullptr) {
auto hi = m_hash(vp->first);
for(unsigned int i = 0; true; i++) {
if(_probe_unsafe(hi, vp) == nullptr) break;
hi = _nexthash(hi, i+1);
}
}
}
if(olddata != nullptr) delete[] olddata;
}
/// Reserve enough space for the given number of elements.
// MT: Externally Synchronized
void reserve(size_type cnt) {
if(slot_count()*max_usage_factor() > cnt) return;
rehash(std::ceil(cnt / max_usage_factor()));
}
/// Get the function used to hash the elements.
// MT: Externally Synchronized
H hash_function() const { return m_hash; }
/// Get the function used to compare elements.
// MT: Externally Synchronized
Eq key_eq() const { return m_equal; }
private:
// Probe the given hash in the data strip, returning its current value, and
// replacing its value with the given one if not present.
// Returns nullptr if the given node was inserted.
value_type* _probe(std::size_t hash, value_type* v, std::shared_lock<stdshim::shared_mutex>&) {
if(data_cnt == 0) return nullptr;
auto& a = data[hash % data_cnt];
if(v == nullptr) return a.load(std::memory_order_acquire);
value_type* vp = nullptr;
a.compare_exchange_strong(vp, v, std::memory_order_release,
std::memory_order_acquire);
return vp;
}
value_type* _probe_unsafe(std::size_t hash, value_type* v) {
if(data_cnt == 0) return nullptr;
auto& a = data[hash % data_cnt];
auto oldvp = a.load(std::memory_order_relaxed);
if(oldvp == nullptr) a.store(v, std::memory_order_relaxed);
return oldvp;
}
// Probe the given hash in the data strip, returning its current value.
value_type* _probe_const(std::size_t hash, std::shared_lock<stdshim::shared_mutex>&) const {
if(data_cnt == 0) return nullptr;
auto& a = data[hash % data_cnt];
return a.load(std::memory_order_acquire);
}
// Sequence of hash values to try next.
static std::size_t _nexthash(std::size_t last, unsigned int idx) {
return last + 1;
}
// Reserve enough space for the given number of elements, but threadsafe.
void reserve(size_type cnt, std::shared_lock<stdshim::shared_mutex>& lk) {
if(cnt <= data_cnt*max_usage) return;
// Time for a rehash.
lk.unlock();
{
std::unique_lock<stdshim::shared_mutex> ulk(lock);
rehash(std::ceil((cnt * 1.25) / max_usage));
}
lk.lock();
}
// Emplace, but with the lock outside.
template<class... Args>
std::pair<iterator, bool> _emplace(std::shared_lock<stdshim::shared_mutex>& lk, Args&&... args) {
// Speculate that we will insert. Prep things to do so.
value_type* newvp = new value_type(std::forward<Args>(args)...);
auto mused = used.fetch_add(1, std::memory_order_relaxed);
reserve(mused+1, lk);
// Now do the insertion.
std::size_t hi = m_hash(newvp->first);
for(unsigned int i = 0; true; i++) {
value_type* vp = _probe(hi, newvp, lk);
if(vp == nullptr) return {newvp, true};
if(m_equal(vp->first, newvp->first)) {
delete newvp;
return {vp, false};
}
hi = _nexthash(hi, i+1);
}
}
// Find, but with the lock outside, and without an iterator.
value_type* _find(const K& k, std::shared_lock<stdshim::shared_mutex>& lk) const {
std::size_t hi = m_hash(k);
for(unsigned int i = 0; true; i++) {
value_type* vp = _probe_const(hi, lk);
if(vp == nullptr) return nullptr;
if(m_equal(k, vp->first)) return vp;
hi = _nexthash(hi, i+1);
}
}
// Data strip / slot array, and maintaining lock.
mutable stdshim::shared_mutex lock;
size_type data_cnt;
std::atomic<value_type*>* data;
// (Prospective) size of the container, used for usage factor calculations.
std::atomic<size_type> used;
// Tuning parameters.
float max_usage;
// Important storage bits, for proper standards compat
H m_hash;
Eq m_equal;
A m_alloc;
};
}
#endif // HPCTOOLKIT_PROFILE_UTIL_ATOMIC_UNORDERED_H
|
zondahuman/algorithm-svr
|
algorithm-leetcode/src/main/java/com/abin/lee/algorithm/nowcoder/BinaryTreePrintByRow.java
|
<filename>algorithm-leetcode/src/main/java/com/abin/lee/algorithm/nowcoder/BinaryTreePrintByRow.java
package com.abin.lee.algorithm.nowcoder;
import com.abin.lee.algorithm.common.json.jackson.JsonUtil;
import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
/**
* Created by abin on 2018/7/26.
* 把二叉树打印成多行
* 题目描述
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
*/
public class BinaryTreePrintByRow {
ArrayList<ArrayList<Integer>> Print(TreeNode pRoot) {
ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> nodeList = new ArrayList<Integer>();
if (null == pRoot)
return list;
Deque<TreeNode> queue = new LinkedList<TreeNode>();
queue.add(pRoot);
TreeNode last = pRoot;
TreeNode currentLast = pRoot;
while (!queue.isEmpty()) {
TreeNode temp = queue.remove();
nodeList.add(temp.val);
if (temp.left != null) {
queue.add(temp.left);
currentLast = temp.left;
}
if (temp.right != null) {
queue.add(temp.right);
currentLast = temp.right;
}
if (temp == last) {
list.add(new ArrayList<Integer>(nodeList));
nodeList.clear();
last = currentLast;
}
}
return list;
}
ArrayList<ArrayList<Integer>> Print1(TreeNode pRoot) {
ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();
if (null == pRoot)
return list;
Deque<TreeNode> queue = new LinkedList<TreeNode>();
queue.push(pRoot);
while (!queue.isEmpty()) {
int size = queue.size();
ArrayList<Integer> nodeList = new ArrayList<Integer>();
for (int i = 0; i <size ; i++) {
TreeNode temp = queue.remove();
nodeList.add(temp.val);
if (temp.left != null) {
queue.add(temp.left);
}
if (temp.right != null) {
queue.add(temp.right);
}
}
list.add(nodeList);
}
return list;
}
ArrayList<ArrayList<Integer> > Print2(TreeNode pRoot) {
ArrayList<ArrayList<Integer>> ret = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> tmp = new ArrayList<Integer>();
LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
if(pRoot == null)
return ret;
queue.add(pRoot);
int now=1, next=0;
while(!queue.isEmpty()) {
TreeNode node = queue.remove();
now--;
tmp.add(node.val);
if(node.left != null){
queue.add(node.left);
next++;
}
if(node.right!=null){
queue.add(node.right);
next++;
}
if(now==0){
ret.add(new ArrayList<>(tmp));
tmp.clear();
now = next;
next = 0;
}
}
return ret;
}
public static void main(String[] args) {
TreeNode t1 = new TreeNode(1);
TreeNode t2 = new TreeNode(2);
TreeNode t3 = new TreeNode(3);
TreeNode t4 = new TreeNode(4);
TreeNode t5 = new TreeNode(5);
TreeNode t6 = new TreeNode(6);
TreeNode t7 = new TreeNode(7);
TreeNode t8 = new TreeNode(8);
t1.left = t2;
t1.right = t3;
t2.left = t4;
t3.left = t5;
t3.right = t6;
t5.left = t7;
t5.right = t8;
ArrayList<ArrayList<Integer>> list = new BinaryTreePrintByRow().Print(t1);
// ArrayList<ArrayList<Integer>> list = new BinaryTreePrintByRow().Print1(t1);
// ArrayList<ArrayList<Integer>> list = new BinaryTreePrintByRow().Print2(t1);
System.out.println("list=" + JsonUtil.toJson(list));
}
public static class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
}
|
YairFernando67/mattermost-webapp
|
tests/helpers/markdown_hotkey_helpers.js
|
<filename>tests/helpers/markdown_hotkey_helpers.js<gh_stars>1-10
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
/**
* @module makrdownHotkeyHelpers
* consolidate testing of similar behavior across components
*/
import {shallow} from 'enzyme';
import Constants from 'utils/constants';
import {shallowWithIntl} from 'tests/helpers/intl-test-helper';
/**
* @param {string} [input] text input
* @param {int} [start] selection's start index
* @param {int} [end] selection's end index
* @param {object} [keycode] Keycode constant associated with key press
* @return {object} keydown event object
*/
export function makeSelectionEvent(input, start, end) {
return {
preventDefault: jest.fn(),
target: {
selectionStart: start,
selectionEnd: end,
value: input,
},
};
}
function makeMarkdownHotkeyEvent(input, start, end, keycode, altKey = false) {
return {
preventDefault: jest.fn(),
stopPropagation: jest.fn(),
ctrlKey: true,
altKey,
key: keycode[0],
keyCode: keycode[1],
target: {
selectionStart: start,
selectionEnd: end,
value: input,
},
};
}
/**
* @param {string} [input] text input
* @param {int} [start] selection's start index
* @param {int} [end] selection's end index
* @return {object} keydown event object
*/
export function makeBoldHotkeyEvent(input, start, end) {
return makeMarkdownHotkeyEvent(input, start, end, Constants.KeyCodes.B);
}
/**
* @param {string} [input] text input
* @param {int} [start] selection's start index
* @param {int} [end] selection's end index
* @return {object} keydown event object
*/
export function makeItalicHotkeyEvent(input, start, end) {
return makeMarkdownHotkeyEvent(input, start, end, Constants.KeyCodes.I);
}
function makeLinkHotKeyEvent(input, start, end) {
return makeMarkdownHotkeyEvent(input, start, end, Constants.KeyCodes.K, true);
}
/**
* helper to test markdown hotkeys on key down behavior common to many textarea inputs
* @param {function} generateInstance - single paramater "value" of the initial value
* @param {function} initRefs - React Component instance and setSelectionRange function
* @param {function} getValue - single parameter for the React Component instance
* NOTE: runs Jest tests
*/
export function testComponentForMarkdownHotkeys(generateInstance, initRefs, find, getValue, intlInjected = true) {
const shallowRender = intlInjected ? shallowWithIntl : shallow;
test('component adds bold markdown', () => {
// "Fafda" is selected with ctrl + B hotkey
const input = '<NAME> & Sambharo';
const e = makeBoldHotkeyEvent(input, 7, 12);
const instance = shallowRender(generateInstance(input));
console.log('##### instance', instance.debug());
const setSelectionRange = jest.fn();
initRefs(instance, setSelectionRange);
find(instance).props().onKeyDown?.(e);
find(instance).props().handleKeyDown?.(e);
expect(getValue(instance)).toBe('Jalebi **Fafda** & Sambharo');
expect(setSelectionRange).toHaveBeenCalled();
});
test('component adds italic markdown', () => {
// "Fafda" is selected with ctrl + I hotkey
const input = '<NAME> & Sambharo';
const e = makeItalicHotkeyEvent(input, 7, 12);
const instance = shallowRender(generateInstance(input));
const setSelectionRange = jest.fn();
initRefs(instance, setSelectionRange);
find(instance).props().onKeyDown?.(e);
find(instance).props().handleKeyDown?.(e);
expect(getValue(instance)).toBe('Jalebi *Fafda* & Sambharo');
expect(setSelectionRange).toHaveBeenCalled();
});
test('component starts bold markdown', () => {
// Nothing is selected, caret is just before "Fafde" with ctrl + B
const input = '<NAME> & Sambharo';
const e = makeBoldHotkeyEvent(input, 7, 7);
const instance = shallowRender(generateInstance(input));
const setSelectionRange = jest.fn();
initRefs(instance, setSelectionRange);
find(instance).props().onKeyDown?.(e);
find(instance).props().handleKeyDown?.(e);
expect(getValue(instance)).toBe('Jalebi ****Fafda & Sambharo');
expect(setSelectionRange).toHaveBeenCalled();
});
test('component starts italic markdown', () => {
// Nothing is selected, caret is just before "Fafde" with ctrl + B
const input = '<NAME> & Sambharo';
const e = makeItalicHotkeyEvent(input, 7, 7);
const instance = shallowRender(generateInstance(input));
const setSelectionRange = jest.fn();
initRefs(instance, setSelectionRange);
find(instance).props().onKeyDown?.(e);
find(instance).props().handleKeyDown?.(e);
expect(getValue(instance)).toBe('Jalebi **Fafda & Sambharo');
expect(setSelectionRange).toHaveBeenCalled();
});
test('component adds link markdown when something is selected', () => {
// "Fafda" is selected with ctrl + alt + K hotkey
const input = '<NAME>';
const e = makeLinkHotKeyEvent(input, 7, 12);
const instance = shallowRender(generateInstance(input));
let selectionStart = -1;
let selectionEnd = -1;
const setSelectionRange = jest.fn((start, end) => {
selectionStart = start;
selectionEnd = end;
});
initRefs(instance, setSelectionRange);
find(instance).props().onKeyDown?.(e);
find(instance).props().handleKeyDown?.(e);
expect(getValue(instance)).toBe('Jalebi [Fafda](url) & Sambharo');
expect(setSelectionRange).toHaveBeenCalled();
expect(selectionStart).toBe(15);
expect(selectionEnd).toBe(18);
});
test('component adds link markdown when cursor is before a word', () => {
// Cursor is before "Fafda" with ctrl + alt + K hotkey
const input = '<NAME> & Sambharo';
const e = makeLinkHotKeyEvent(input, 7, 7);
const instance = shallowRender(generateInstance(input));
let selectionStart = -1;
let selectionEnd = -1;
const setSelectionRange = jest.fn((start, end) => {
selectionStart = start;
selectionEnd = end;
});
initRefs(instance, setSelectionRange);
find(instance).props().onKeyDown?.(e);
find(instance).props().handleKeyDown?.(e);
expect(getValue(instance)).toBe('Jalebi [Fafda](url) & Sambharo');
expect(setSelectionRange).toHaveBeenCalled();
expect(selectionStart).toBe(15);
expect(selectionEnd).toBe(18);
});
test('component adds link markdown when cursor is in a word', () => {
// Cursor is after "Fafda" with ctrl + alt + K hotkey
const input = '<NAME>';
const e = makeLinkHotKeyEvent(input, 10, 10);
const instance = shallowRender(generateInstance(input));
let selectionStart = -1;
let selectionEnd = -1;
const setSelectionRange = jest.fn((start, end) => {
selectionStart = start;
selectionEnd = end;
});
initRefs(instance, setSelectionRange);
find(instance).props().onKeyDown?.(e);
find(instance).props().handleKeyDown?.(e);
expect(getValue(instance)).toBe('Jalebi [Fafda](url) & Sambharo');
expect(setSelectionRange).toHaveBeenCalled();
expect(selectionStart).toBe(15);
expect(selectionEnd).toBe(18);
});
test('component adds link markdown when cursor is after a word', () => {
// Cursor is after "Fafda" with ctrl + alt + K hotkey
const input = '<NAME>';
const e = makeLinkHotKeyEvent(input, 12, 12);
const instance = shallowRender(generateInstance(input));
let selectionStart = -1;
let selectionEnd = -1;
const setSelectionRange = jest.fn((start, end) => {
selectionStart = start;
selectionEnd = end;
});
initRefs(instance, setSelectionRange);
find(instance).props().onKeyDown?.(e);
find(instance).props().handleKeyDown?.(e);
expect(getValue(instance)).toBe('Jalebi [Fafda](url) & Sambharo');
expect(setSelectionRange).toHaveBeenCalled();
expect(selectionStart).toBe(15);
expect(selectionEnd).toBe(18);
});
test('component adds link markdown when cursor is at the end of line', () => {
// Cursor is after "Sambharo" with ctrl + alt + K hotkey
const input = '<NAME> & Sambharo';
const e = makeLinkHotKeyEvent(input, 23, 23);
const instance = shallowRender(generateInstance(input));
let selectionStart = -1;
let selectionEnd = -1;
const setSelectionRange = jest.fn((start, end) => {
selectionStart = start;
selectionEnd = end;
});
initRefs(instance, setSelectionRange);
find(instance).props().onKeyDown?.(e);
find(instance).props().handleKeyDown?.(e);
expect(getValue(instance)).toBe('Jalebi Fafda & Sambharo [](url)');
expect(setSelectionRange).toHaveBeenCalled();
expect(selectionStart).toBe(25);
expect(selectionEnd).toBe(25);
});
test('component removes link markdown', () => {
// "Fafda" is selected with ctrl + alt + K hotkey
const input = 'Jalebi [Fafda](url) & Sambharo';
const e = makeLinkHotKeyEvent(input, 8, 13);
const instance = shallowRender(generateInstance(input));
let selectionStart = -1;
let selectionEnd = -1;
const setSelectionRange = jest.fn((start, end) => {
selectionStart = start;
selectionEnd = end;
});
initRefs(instance, setSelectionRange);
find(instance).props().onKeyDown?.(e);
find(instance).props().handleKeyDown?.(e);
expect(getValue(instance)).toBe('<NAME> & Sambharo');
expect(setSelectionRange).toHaveBeenCalled();
expect(selectionStart).toBe(7);
expect(selectionEnd).toBe(12);
});
}
|
JDSherbert/Sherbert-Engine
|
SherbertEngine Project/SherbertEngine/Texture.h
|
#pragma once
#include "Bindable.h"
class Surface;
namespace Bind
{
class Texture : public Bindable
{
public:
Texture( Graphics& gfx,const std::string& path,UINT slot = 0 );
void Bind( Graphics& gfx ) noxnd override;
static std::shared_ptr<Texture> Resolve( Graphics& gfx,const std::string& path,UINT slot = 0 );
static std::string GenerateUID( const std::string& path,UINT slot = 0 );
std::string GetUID() const noexcept override;
bool HasAlpha() const noexcept;
private:
static UINT CalculateNumberOfMipLevels( UINT width,UINT height ) noexcept;
private:
unsigned int slot;
protected:
bool hasAlpha = false;
std::string path;
Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> pTextureView;
};
}
|
bula3-1992/openprojectsd
|
db/migrate/20191106020937_change_control_level_to_control_level_id.rb
|
<filename>db/migrate/20191106020937_change_control_level_to_control_level_id.rb
class ChangeControlLevelToControlLevelId < ActiveRecord::Migration[5.2]
def change
change_table :work_packages do |t|
t.rename :control_level, :control_level_id
end
change_table :work_package_journals do |t|
t.rename :control_level, :control_level_id
end
end
end
|
Cmccrave/CMProtoBot
|
Source/McRave/Walls.cpp
|
#include "McRave.h"
using namespace BWAPI;
using namespace std;
using namespace BWEM;
using namespace UnitTypes;
namespace McRave::Walls {
namespace {
BWEB::Wall* mainWall = nullptr;
BWEB::Wall* naturalWall = nullptr;
vector<UnitType> buildings;
vector<UnitType> defenses;
bool tight;
bool openWall;
UnitType tightType = None;
void initializeWallParameters()
{
// Figure out what we need to be tight against
if (Players::TvP())
tightType = Protoss_Zealot;
else if (Players::TvZ())
tightType = Zerg_Zergling;
else
tightType = None;
// Protoss wall parameters
if (Broodwar->self()->getRace() == Races::Protoss) {
if (Players::vZ()) {
tight = false;
buildings ={ Protoss_Gateway, Protoss_Forge, Protoss_Pylon };
defenses.insert(defenses.end(), 10, Protoss_Photon_Cannon);
}
else {
tight = false;
buildings ={ Protoss_Forge, Protoss_Pylon, Protoss_Pylon, Protoss_Pylon };
defenses.insert(defenses.end(), 10, Protoss_Photon_Cannon);
}
}
// Terran wall parameters
if (Broodwar->self()->getRace() == Races::Terran) {
tight = true;
buildings ={ Terran_Barracks, Terran_Supply_Depot, Terran_Supply_Depot };
}
// Zerg wall parameters
if (Broodwar->self()->getRace() == Races::Zerg) {
tight = false;
defenses.insert(defenses.end(), 20, Zerg_Creep_Colony);
//buildings ={ Zerg_Hatchery, Zerg_Evolution_Chamber };
}
}
}
void findNaturalWall()
{
naturalWall = BWEB::Walls::getWall(BWEB::Map::getNaturalChoke());
}
void findMainWall()
{
mainWall = BWEB::Walls::getWall(BWEB::Map::getMainChoke());
}
void findHardWalls()
{
if (!Terrain::isShitMap())
return;
// The unfortunate reality of playing Zerg on literally the shittiest map in a tournament.
multimap<UnitType, TilePosition> wall1 ={
{ Zerg_Sunken_Colony, TilePosition(37,108) },
{ Zerg_Sunken_Colony, TilePosition(35,108) },
{ Zerg_Sunken_Colony, TilePosition(35,110) },
{ Zerg_Sunken_Colony, TilePosition(33,110) },
{ Zerg_Sunken_Colony, TilePosition(33,112) },
{ Zerg_Sunken_Colony, TilePosition(33,114) },
{ Zerg_Sunken_Colony, TilePosition(31,114) },
{ Zerg_Sunken_Colony, TilePosition(31,116) },
{ Zerg_Sunken_Colony, TilePosition(29,116) },
{ Zerg_Sunken_Colony, TilePosition(29,118) },
{ Zerg_Sunken_Colony, TilePosition(27,117) },
{ Zerg_Sunken_Colony, TilePosition(25,118) },
{ Zerg_Hatchery, TilePosition(35,112) }
};
auto choke1 = Util::getClosestChokepoint(Position(TilePosition(35, 112)));
auto area1 = mapBWEM.GetArea(TilePosition(35, 112));
BWEB::Walls::createHardWall(wall1, area1, choke1);
multimap<UnitType, TilePosition> wall2 ={
{ Zerg_Sunken_Colony, TilePosition(58,97) },
{ Zerg_Sunken_Colony, TilePosition(58,99) },
{ Zerg_Sunken_Colony, TilePosition(56,97) },
{ Zerg_Sunken_Colony, TilePosition(56,99) },
{ Zerg_Sunken_Colony, TilePosition(56,101) },
{ Zerg_Sunken_Colony, TilePosition(54,99) },
{ Zerg_Sunken_Colony, TilePosition(54,101) },
{ Zerg_Sunken_Colony, TilePosition(54,103) },
{ Zerg_Sunken_Colony, TilePosition(52,101) },
{ Zerg_Sunken_Colony, TilePosition(52,103) },
{ Zerg_Sunken_Colony, TilePosition(52,105) },
{ Zerg_Sunken_Colony, TilePosition(50,103) },
{ Zerg_Hatchery, TilePosition(50,98) }
};
auto choke2 = Util::getClosestChokepoint(Position(TilePosition(50, 98)));
auto area2 = mapBWEM.GetArea(TilePosition(50, 98));
BWEB::Walls::createHardWall(wall2, area2, choke2);
multimap<UnitType, TilePosition> wall3 ={
{ Zerg_Sunken_Colony, TilePosition(114,64) },
{ Zerg_Sunken_Colony, TilePosition(114,66) },
{ Zerg_Sunken_Colony, TilePosition(116,64) },
{ Zerg_Sunken_Colony, TilePosition(116,66) },
{ Zerg_Sunken_Colony, TilePosition(118,64) },
{ Zerg_Sunken_Colony, TilePosition(118,66) },
{ Zerg_Sunken_Colony, TilePosition(120,64) },
{ Zerg_Sunken_Colony, TilePosition(120,66) },
{ Zerg_Sunken_Colony, TilePosition(120,68) },
{ Zerg_Sunken_Colony, TilePosition(122,68) },
{ Zerg_Sunken_Colony, TilePosition(122,70) },
{ Zerg_Sunken_Colony, TilePosition(124,69) },
{ Zerg_Hatchery, TilePosition(122,65) }
};
auto choke3 = Util::getClosestChokepoint(Position(TilePosition(122, 65)));
auto area3 = mapBWEM.GetArea(TilePosition(122, 65));
BWEB::Walls::createHardWall(wall3, area3, choke3);
multimap<UnitType, TilePosition> wall4 ={
{ Zerg_Sunken_Colony, TilePosition(118,24) },
{ Zerg_Sunken_Colony, TilePosition(118,26) },
{ Zerg_Sunken_Colony, TilePosition(118,28) },
{ Zerg_Sunken_Colony, TilePosition(118,30) },
{ Zerg_Sunken_Colony, TilePosition(118,32) },
{ Zerg_Sunken_Colony, TilePosition(118,34) },
{ Zerg_Sunken_Colony, TilePosition(120,24) },
{ Zerg_Sunken_Colony, TilePosition(120,26) },
{ Zerg_Sunken_Colony, TilePosition(120,28) },
{ Zerg_Sunken_Colony, TilePosition(120,30) },
{ Zerg_Sunken_Colony, TilePosition(120,32) },
{ Zerg_Sunken_Colony, TilePosition(120,34) },
{ Zerg_Hatchery, TilePosition(122,27) }
};
auto choke4 = Util::getClosestChokepoint(Position(TilePosition(112, 27)));
auto area4 = mapBWEM.GetArea(TilePosition(122, 27));
BWEB::Walls::createHardWall(wall4, area4, choke4);
multimap<UnitType, TilePosition> wall5 ={
{ Zerg_Sunken_Colony, TilePosition(38,0) },
{ Zerg_Sunken_Colony, TilePosition(36,0) },
{ Zerg_Sunken_Colony, TilePosition(36,2) },
{ Zerg_Sunken_Colony, TilePosition(34,0) },
{ Zerg_Sunken_Colony, TilePosition(34,2) },
{ Zerg_Sunken_Colony, TilePosition(34,4) },
{ Zerg_Sunken_Colony, TilePosition(32,2) },
{ Zerg_Sunken_Colony, TilePosition(32,4) },
{ Zerg_Sunken_Colony, TilePosition(32,6) },
{ Zerg_Sunken_Colony, TilePosition(30,4) },
{ Zerg_Sunken_Colony, TilePosition(30,6) },
{ Zerg_Sunken_Colony, TilePosition(30,8) },
{ Zerg_Hatchery, TilePosition(28,1) }
};
auto choke5 = Util::getClosestChokepoint(Position(TilePosition(28, 1)));
auto area5 = mapBWEM.GetArea(TilePosition(28, 1));
BWEB::Walls::createHardWall(wall5, area5, choke5);
multimap<UnitType, TilePosition> wall6 ={
{ Zerg_Sunken_Colony, TilePosition(22,26) },
{ Zerg_Sunken_Colony, TilePosition(24,25) },
{ Zerg_Sunken_Colony, TilePosition(24,27) },
{ Zerg_Sunken_Colony, TilePosition(26,26) },
{ Zerg_Sunken_Colony, TilePosition(26,28) },
{ Zerg_Sunken_Colony, TilePosition(28,26) },
{ Zerg_Sunken_Colony, TilePosition(28,28) },
{ Zerg_Sunken_Colony, TilePosition(28,30) },
{ Zerg_Sunken_Colony, TilePosition(30,30) },
{ Zerg_Sunken_Colony, TilePosition(31,32) },
{ Zerg_Sunken_Colony, TilePosition(32,30) },
{ Zerg_Sunken_Colony, TilePosition(33,32) },
{ Zerg_Hatchery, TilePosition(30,27) }
};
auto choke6 = Util::getClosestChokepoint(Position(TilePosition(30, 27)));
auto area6 = mapBWEM.GetArea(TilePosition(30, 27));
BWEB::Walls::createHardWall(wall6, area6, choke6);
}
void findWalls()
{
if (Terrain::isShitMap())
return;
// Create a Zerg/Protoss wall at every natural
if (Broodwar->self()->getRace() != Races::Terran) {
openWall = true;
for (auto &station : BWEB::Stations::getStations()) {
initializeWallParameters();
if (!station.isNatural())
continue;
// Create a wall and reduce the building count on each iteration
while (!BWEB::Walls::getWall(station.getChokepoint())) {
BWEB::Walls::createWall(buildings, station.getBase()->GetArea(), station.getChokepoint(), tightType, defenses, openWall, tight);
if (Players::PvZ() || buildings.empty())
break;
UnitType lastBuilding = *buildings.rbegin();
buildings.pop_back();
if (lastBuilding == Zerg_Hatchery)
buildings.push_back(Zerg_Evolution_Chamber);
}
}
}
// Create a Terran wall at every main
else {
for (auto &station : BWEB::Stations::getStations()) {
if (!station.isMain())
continue;
BWEB::Walls::createWall(buildings, station.getBase()->GetArea(), station.getChokepoint(), tightType, defenses, openWall, tight);
}
}
}
void onStart()
{
initializeWallParameters();
findWalls();
findHardWalls();
findMainWall();
findNaturalWall();
}
void onFrame()
{
if (Terrain::isShitMap() && Terrain::getEnemyStartingPosition().isValid()) {
if (BWEB::Map::getMainTile() == TilePosition(8, 7)) {
if (Terrain::getEnemyStartingTilePosition() == TilePosition(43, 118))
naturalWall = BWEB::Walls::getClosestWall(TilePosition(30, 27));
else
naturalWall = BWEB::Walls::getClosestWall(TilePosition(28, 1));
}
if (BWEB::Map::getMainTile() == TilePosition(43, 118)) {
if (Terrain::getEnemyStartingTilePosition() == TilePosition(8, 7))
naturalWall = BWEB::Walls::getClosestWall(TilePosition(35, 112));
else
naturalWall = BWEB::Walls::getClosestWall(TilePosition(50, 98));
}
if (BWEB::Map::getMainTile() == TilePosition(117, 51)) {
if (Terrain::getEnemyStartingTilePosition() == TilePosition(8, 7))
naturalWall = BWEB::Walls::getClosestWall(TilePosition(122, 27));
else
naturalWall = BWEB::Walls::getClosestWall(TilePosition(122, 65));
}
}
}
int calcSaturationRatio(BWEB::Wall& wall, int defensesDesired)
{
auto closestNatural = BWEB::Stations::getClosestNaturalStation(TilePosition(wall.getCentroid()));
auto closestMain = BWEB::Stations::getClosestMainStation(TilePosition(wall.getCentroid()));
auto saturationRatio = clamp((Stations::getSaturationRatio(closestNatural) + Stations::getSaturationRatio(closestMain)), 0.1, 1.0);
if (Strategy::enemyRush() || Strategy::enemyPressure() || Util::getTime() < Time(6, 00))
return defensesDesired;
return int(ceil(saturationRatio * double(defensesDesired)));
}
int calcGroundDefZvP(BWEB::Wall& wall) {
// Try to see what we expect based on first Zealot push out
if (Strategy::getEnemyBuild() == "Unknown" && Scouts::enemyDeniedScout() && Players::getVisibleCount(PlayerState::Enemy, Protoss_Zealot) >= 1 && wall.getGroundDefenseCount() == 0) {
auto closestZealot = Util::getClosestUnit(BWEB::Map::getMainPosition(), PlayerState::Self, [&](auto &u) {
return u.getType() == Protoss_Zealot;
});
if (closestZealot && closestZealot->timeArrivesWhen() < Time(3, 50) && BWEB::Map::getGroundDistance(closestZealot->getPosition(), BWEB::Map::getNaturalPosition()) < 640.0)
return (Util::getTime() > Time(2, 50));
}
// See if they expanded or got some tech at a reasonable point for 1 base play
auto noExpandOrTech = Util::getTime() > Time(5, 00) && !Strategy::enemyFastExpand()
&& Players::getTotalCount(PlayerState::Enemy, Protoss_Corsair) == 0
&& Players::getTotalCount(PlayerState::Enemy, Protoss_Dark_Templar) == 0
&& Players::getTotalCount(PlayerState::Enemy, Protoss_High_Templar) == 0
&& Players::getTotalCount(PlayerState::Enemy, Protoss_Reaver) == 0
&& Players::getTotalCount(PlayerState::Enemy, Protoss_Archon) == 0;
// 4Gate - Upwards of 12 sunkens allowed... Still sane Exile?
if (Strategy::getEnemyTransition() == "4Gate" && Util::getTime() < Time(12, 00)) {
if (Strategy::enemyFastExpand()) {
return 1
+ (Util::getTime() > Time(4, 00))
+ (Util::getTime() > Time(4, 30))
+ (Util::getTime() > Time(5, 00))
+ (Util::getTime() > Time(5, 20))
+ (Util::getTime() > Time(5, 40))
+ (Util::getTime() > Time(6, 00))
+ (Util::getTime() > Time(6, 20))
+ (Util::getTime() > Time(6, 40))
+ (Util::getTime() > Time(7, 20))
+ (Util::getTime() > Time(8, 20))
+ (Util::getTime() > Time(9, 20));
}
else {
return 1
+ (Util::getTime() > Time(4, 00))
+ (Util::getTime() > Time(4, 30))
+ (Util::getTime() > Time(5, 00))
+ (Util::getTime() > Time(5, 20))
+ (Util::getTime() > Time(5, 40))
+ (Util::getTime() > Time(6, 00))
+ (Util::getTime() > Time(6, 20))
+ (Util::getTime() > Time(6, 40))
+ (Util::getTime() > Time(7, 00))
+ (Util::getTime() > Time(8, 00))
+ (Util::getTime() > Time(9, 00));
}
}
// 1GateCore
if (Strategy::getEnemyBuild() == "1GateCore" || (Strategy::getEnemyBuild() == "Unknown" && Players::getVisibleCount(PlayerState::Enemy, Protoss_Zealot) >= 1)) {
if (Strategy::getEnemyTransition() == "Corsair" && Util::getTime() < Time(8, 30))
return (Util::getTime() > Time(3, 40)) + (Util::getTime() > Time(7, 30));
else if (Strategy::getEnemyTransition() == "DT" && Util::getTime() < Time(8, 30))
return (Util::getTime() > Time(3, 40)) + (Util::getTime() > Time(4, 20)) + (Util::getTime() > Time(5, 00)) + (Util::getTime() > Time(5, 20)) + (Util::getTime() > Time(5, 40));
else if (Util::getTime() < Time(6, 15) && Players::getVisibleCount(PlayerState::Enemy, Protoss_Dragoon) >= 1)
return (Util::getTime() > Time(3, 40)) + (Util::getTime() > Time(4, 00)) + (Util::getTime() > Time(4, 20)) + noExpandOrTech;
else if (Util::getTime() < Time(6, 15))
return (Util::getTime() > Time(3, 40)) + noExpandOrTech;
}
// 2Gate
if (Strategy::getEnemyBuild() == "2Gate") {
if ((Players::getVisibleCount(PlayerState::Enemy, Protoss_Dragoon) > 0 || Players::getVisibleCount(PlayerState::Enemy, Protoss_Cybernetics_Core) > 0) && Util::getTime() < Time(5, 15))
return (Util::getTime() > Time(3, 00)) + (Util::getTime() > Time(4, 00)) + (Util::getTime() > Time(4, 20)) + noExpandOrTech;
else if (Util::getTime() < Time(5, 15) && Strategy::getEnemyOpener() == "10/17")
return (Util::getTime() > Time(3, 30)) + (Util::getTime() > Time(4, 00)) + (Util::getTime() > Time(4, 20)) + noExpandOrTech;
else if (Util::getTime() < Time(5, 15) && (Strategy::getEnemyOpener() == "10/12" || Strategy::getEnemyOpener() == "Unknown"))
return (Util::getTime() > Time(3, 10)) + (Util::getTime() > Time(3, 30)) + (Util::getTime() > Time(4, 00)) + noExpandOrTech;
else if (Util::getTime() < Time(5, 15) && (Strategy::getEnemyOpener() == "9/9" || Strategy::getEnemyTransition() == "ZealotRush"))
return (Util::getTime() > Time(2, 50)) + (Util::getTime() > Time(4, 00)) + noExpandOrTech;
}
// FFE
if (Strategy::getEnemyBuild() == "FFE") {
if (Strategy::getEnemyTransition() == "Carriers")
return 0;
if (Strategy::getEnemyTransition() == "5GateGoon" && Util::getTime() < Time(10, 00))
return ((Util::getTime() > Time(5, 40)) + (Util::getTime() > Time(6, 00)) + (Util::getTime() > Time(6, 20)) + (Util::getTime() > Time(6, 40))) + (Util::getTime() > Time(7, 00)) + (Util::getTime() > Time(8, 00)) + (Util::getTime() > Time(9, 00));
if (Strategy::getEnemyTransition() == "NeoBisu" && Util::getTime() < Time(6, 30))
return ((2 * (Util::getTime() > Time(6, 00))));
if (Strategy::getEnemyTransition() == "Speedlot" && Util::getTime() < Time(7, 00))
return ((2 * (Util::getTime() > Time(5, 00))) + (2 * (Util::getTime() > Time(5, 30))) + (2 * (Util::getTime() > Time(6, 00))));
if (Strategy::getEnemyTransition() == "Unknown" && Util::getTime() < Time(5, 15))
return ((2 * (Util::getTime() > Time(6, 00))) + (Util::getTime() > Time(6, 30)) + (2 * (Util::getTime() > Time(8, 00))));
if (Util::getTime() < Time(8, 00))
return ((Util::getTime() > Time(5, 45)) + (Util::getTime() > Time(6, 15)) + (Util::getTime() > Time(6, 45)));
}
// Outside of openers, base it off how large the ground army of enemy is
if (Util::getTime() > Time(8, 00)) {
const auto divisor = 2.0 + max(0.0, (double(Util::getTime().minutes - 6) / 4.0));
const auto count = int(double(Players::getVisibleCount(PlayerState::Enemy, Protoss_Zealot) + Players::getVisibleCount(PlayerState::Enemy, Protoss_Dragoon)) / divisor);
return (count);
}
return 0;
}
int calcGroundDefZvT(BWEB::Wall& wall) {
// 2Rax
if (Strategy::getEnemyBuild() == "2Rax") {
if (Strategy::enemyProxy())
return 0;
if (!Strategy::enemyFastExpand() && !Strategy::enemyRush() && Util::getTime() < Time(5, 00))
return (2 * (Util::getTime() > Time(3, 15))) + (2 * (Util::getTime() > Time(4, 30)));
if (Strategy::enemyRush())
return (2 + (Util::getTime() > Time(4, 30)) + (Util::getTime() > Time(5, 30)));
}
// RaxCC
if (Strategy::getEnemyBuild() == "RaxCC") {
if (Strategy::enemyProxy())
return 0;
return (Util::getTime() > Time(4, 30)) + (Util::getTime() > Time(4, 45));
}
// RaxFact
if (Strategy::getEnemyBuild() == "RaxFact") {
if (Strategy::getEnemyTransition() == "5FacGoliath")
return 5 * (Util::getTime() > Time(11, 00));
if (Strategy::getEnemyTransition() == "2Fact" || Players::getTotalCount(PlayerState::Enemy, Terran_Vulture) > 0 || Strategy::enemyWalled())
return (Util::getTime() > Time(3, 30));
}
if (!Strategy::enemyFastExpand() && Strategy::getEnemyBuild() != "RaxCC")
return ((Util::getTime() > Time(3, 30)) + (Util::getTime() > Time(4, 30)) + (Util::getTime() > Time(5, 00)));
if (Util::getTime() > Time(10, 00))
return max(1, (Util::getTime().minutes / 4));
return (Util::getTime() > Time(3, 30));
}
int calcGroundDefZvZ(BWEB::Wall& wall) {
if ((BuildOrder::getCurrentTransition().find("Muta") != string::npos || Util::getTime() > Time(6, 00)) && (BuildOrder::takeNatural() || int(Stations::getMyStations().size()) >= 2)) {
if (Players::ZvZ() && BuildOrder::isOpener() && BuildOrder::buildCount(Zerg_Spire) > 0 && vis(Zerg_Spire) == 0)
return 0;
else if (Strategy::getEnemyTransition() == "2HatchSpeedling")
return (Util::getTime() > Time(3, 45)) + (Util::getTime() > Time(4, 00)) + (Util::getTime() > Time(5, 30));
else if (Util::getTime() < Time(6, 00) && Players::getTotalCount(PlayerState::Enemy, Zerg_Zergling) >= 40)
return 6;
else if (Util::getTime() < Time(6, 00) && (Players::getVisibleCount(PlayerState::Enemy, Zerg_Hatchery) >= 3 || Players::getTotalCount(PlayerState::Enemy, Zerg_Zergling) >= 26))
return 4;
else if (Strategy::enemyPressure())
return (Util::getTime() > Time(4, 10)) + (vis(Zerg_Sunken_Colony) > 0) + (vis(Zerg_Drone) >= 8 && com(Zerg_Sunken_Colony) >= 2);
else if (Strategy::enemyRush() && total(Zerg_Zergling) >= 6)
return 1 + (vis(Zerg_Sunken_Colony) > 0) + (vis(Zerg_Drone) >= 8 && com(Zerg_Sunken_Colony) >= 2);
}
return 0;
}
int needGroundDefenses(BWEB::Wall& wall)
{
auto groundCount = wall.getGroundDefenseCount() /*+ (BuildOrder::getCurrentTransition().find("2Hatch") == string::npos) * ((Util::getTime() > Time(6, 00)) + (Util::getTime() > Time(7, 00)))*/;
if (!Terrain::isInAllyTerritory(wall.getArea()))
return 0;
// Protoss
if (Broodwar->self()->getRace() == Races::Protoss) {
auto prepareExpansionDefenses = Util::getTime() < Time(10, 0) && vis(Protoss_Nexus) >= 2 && com(Protoss_Forge) > 0;
if (Players::vP() && prepareExpansionDefenses && BuildOrder::isWallNat()) {
auto cannonCount = 2 + int(1 + Players::getVisibleCount(PlayerState::Enemy, Protoss_Zealot) + Players::getVisibleCount(PlayerState::Enemy, Protoss_Dragoon) - com(Protoss_Zealot) - com(Protoss_Dragoon) - com(Protoss_High_Templar) - com(Protoss_Dark_Templar)) / 2;
return cannonCount - groundCount;
}
if (Players::vZ() && BuildOrder::isWallNat()) {
auto cannonCount = int(com(Protoss_Forge) > 0)
+ (Players::getVisibleCount(PlayerState::Enemy, Zerg_Zergling) >= 6)
+ (Players::getVisibleCount(PlayerState::Enemy, Zerg_Zergling) >= 12)
+ (Players::getVisibleCount(PlayerState::Enemy, Zerg_Zergling) >= 24)
+ (Players::getVisibleCount(PlayerState::Enemy, Zerg_Hydralisk) / 2);
// TODO: If scout died, go to 2 cannons, if next scout dies, go 3 cannons
if (Strategy::getEnemyTransition() == "2HatchHydra")
return 5 - groundCount;
else if (Strategy::getEnemyTransition() == "3HatchHydra")
return 4 - groundCount;
else if (Strategy::getEnemyTransition() == "2HatchMuta" && Util::getTime() > Time(4, 0))
return 3 - groundCount;
else if (Strategy::getEnemyTransition() == "3HatchMuta" && Util::getTime() > Time(5, 0))
return 3 - groundCount;
else if (Strategy::getEnemyOpener() == "4Pool")
return 2 + (Players::getSupply(PlayerState::Self, Races::Protoss) >= 24) - groundCount;
return cannonCount - groundCount;
}
}
// Terran
// Zerg
if (Broodwar->self()->getRace() == Races::Zerg) {
if (Players::vP())
return calcSaturationRatio(wall, calcGroundDefZvP(wall)) - groundCount;
if (Players::vT())
return calcSaturationRatio(wall, calcGroundDefZvT(wall)) - groundCount;
if (Players::vZ())
return calcSaturationRatio(wall, calcGroundDefZvZ(wall)) - groundCount;
}
return 0;
}
int needAirDefenses(BWEB::Wall& wall)
{
auto airCount = wall.getAirDefenseCount();
const auto enemyAir = Players::getTotalCount(PlayerState::Enemy, Protoss_Corsair) > 0
|| Players::getTotalCount(PlayerState::Enemy, Protoss_Scout) > 0
|| Players::getTotalCount(PlayerState::Enemy, Protoss_Stargate) > 0
|| Players::getTotalCount(PlayerState::Enemy, Terran_Wraith) > 0
|| Players::getTotalCount(PlayerState::Enemy, Terran_Valkyrie) > 0
|| Players::getTotalCount(PlayerState::Enemy, Zerg_Mutalisk) > 0
|| (Players::getTotalCount(PlayerState::Enemy, Zerg_Spire) > 0 && Util::getTime() > Time(4, 45));
if (!Terrain::isInAllyTerritory(wall.getArea()))
return 0;
// Protoss
if (Broodwar->self()->getRace() == Races::Protoss) {
return 0;
}
// Terran
// Zerg
if (Broodwar->self()->getRace() == Races::Zerg) {
if (Players::ZvZ() && Util::getTime() > Time(4, 30) && total(Zerg_Zergling) > Players::getTotalCount(PlayerState::Enemy, Zerg_Zergling) && com(Zerg_Spire) == 0 && Strategy::getEnemyTransition() == "Unknown" && BuildOrder::getCurrentTransition() == "2HatchMuta")
return 1 - airCount;
if (Players::ZvZ() && Util::getTime() > Time(4, 15) && Strategy::getEnemyTransition() == "1HatchMuta" && BuildOrder::getCurrentTransition() == "2HatchMuta")
return 1 - airCount;
if (Players::ZvP() && Util::getTime() > Time(4, 00) && Strategy::getEnemyBuild() == "1GateCore" && Strategy::getEnemyTransition() == "Corsair")
return 1 - airCount;
if (Players::ZvP() && Util::getTime() > Time(4, 30) && Strategy::getEnemyBuild() == "2Gate" && Strategy::getEnemyTransition() == "Corsair")
return 1 - airCount;
}
return 0;
}
BWEB::Wall* getMainWall() { return mainWall; }
BWEB::Wall* getNaturalWall() { return naturalWall; }
}
|
ssyyzs/JavaMesh
|
javamesh-samples/javamesh-flowcontrol/flowcontrol-server/src/main/java/com/huawei/flowcontrol/console/entity/MachineInfoVo.java
|
<gh_stars>0
package com.huawei.flowcontrol.console.entity;
import lombok.Getter;
import lombok.Setter;
import java.util.ArrayList;
import java.util.List;
/**
* 此处部分引用alibaba/Sentinel开源社区代码,诚挚感谢alibaba/Sentinel开源团队的慷慨贡献
*/
@Getter
@Setter
public class MachineInfoVo extends MachineInfo {
private boolean healthy;
public static List<MachineInfoVo> fromMachineInfoList(List<MachineInfo> machines) {
List<MachineInfoVo> list = new ArrayList<>();
for (MachineInfo machine : machines) {
list.add(fromMachineInfo(machine));
}
return list;
}
public static MachineInfoVo fromMachineInfo(MachineInfo machine) {
MachineInfoVo vo = new MachineInfoVo();
vo.setApp(machine.getApp());
vo.setHostname(machine.getHostname());
vo.setIp(machine.getIp());
vo.setPort(machine.getPort());
vo.setLastHeartbeat(machine.getLastHeartbeat());
vo.setHeartbeatVersion(machine.getHeartbeatVersion());
vo.setVersion(machine.getVersion());
vo.setHealthy(machine.isHealthy());
return vo;
}
@Override
public boolean equals(Object o) {
return super.equals(o);
}
@Override
public int hashCode() {
return super.hashCode();
}
}
|
AnWooJin/Portfolio
|
GameEngineContents/Thorn_InOutState.cpp
|
#include "Thorn_InOut.h"
#include "Player.h"
#include <GameEngine/GameEngineRenderer.h>
#include <GameEngine/GameEngineCollision.h>
void Thorn_InOut::InStart()
{
MyRenderer_->ChangeAnimation("Thorn_In");
MyCollision_->Off();
}
void Thorn_InOut::OutStart()
{
MyRenderer_->ChangeAnimation("Thorn_Out");
MyCollision_->On();
}
void Thorn_InOut::InUpdate()
{
if (true == MyPlayer_->IsPlayerMove())
{
ChangeState(Thorn_InOutState::Out);
}
}
void Thorn_InOut::OutUpdate()
{
if (true == MyPlayer_->IsPlayerMove())
{
ChangeState(Thorn_InOutState::In);
}
}
|
banadiga/sandbox
|
caching/src/main/java/com/banadiga/caching/controller/ItemsController.java
|
<reponame>banadiga/sandbox
package com.banadiga.caching.controller;
import com.banadiga.caching.dto.Item;
import com.banadiga.caching.service.ItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import java.util.Collection;
@RestController
@RequestMapping(value = "/items")
public class ItemsController {
@Autowired
private ItemService itemService;
@RequestMapping(method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)
@ResponseBody
public Item create(Item item) {
return itemService.create(item);
}
@GetMapping(path = "{id}")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public Item read(@PathVariable("id") String id) {
return itemService.read(id);
}
@RequestMapping(method = RequestMethod.PUT, path = "{id}")
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public Item update(@PathVariable("id") String id, Item item) {
return itemService.update(id, item);
}
@DeleteMapping(path = "{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void delete(@PathVariable("id") String id) {
itemService.delete(id);
}
@GetMapping
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public Collection<Item> list() {
return itemService.list();
}
}
|
Waginator/mycv
|
src/test/java/com/wagner/mycv/model/repository/LanguageRepositoryIntegrationTest.java
|
package com.wagner.mycv.model.repository;
import com.wagner.mycv.model.entity.Language;
import com.wagner.mycv.testutil.LanguageTestUtil;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import javax.persistence.EntityManager;
import javax.sql.DataSource;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
@ExtendWith(SpringExtension.class)
@DataJpaTest
@TestPropertySource(locations = "classpath:application-integrationtest.properties")
class LanguageRepositoryIntegrationTest {
private final Language language = LanguageTestUtil.createTestEntity();
@Autowired private DataSource dataSource;
@Autowired private JdbcTemplate jdbcTemplate;
@Autowired private EntityManager entityManager;
@Autowired private LanguageRepository languageRepository;
@Test
void injectedComponentsAreNotNull(){
assertThat(dataSource).isNotNull();
assertThat(jdbcTemplate).isNotNull();
assertThat(entityManager).isNotNull();
assertThat(languageRepository).isNotNull();
}
@Test
void test_find_language() {
entityManager.persist(language);
Optional<Language> result = languageRepository.findById(1L);
assertThat(result.isPresent()).isTrue();
//noinspection OptionalGetWithoutIsPresent
Language languageResponse = result.get();
assertThat(languageResponse).isNotNull();
assertThat(languageResponse.getId()).isEqualTo(1L);
assertThat(languageResponse.getLevel()).isEqualTo(language.getLevel());
assertThat(languageResponse.getName()).isEqualTo(language.getName());
assertThat(languageResponse.getUserId()).isEqualTo(language.getUserId());
}
}
|
otaviooasc/CRUD-Angular
|
frontend/node_modules/tslint/lib/rules/noInferrableTypesRule.js
|
"use strict";
/**
* @license
* Copyright 2015 Palantir Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.Rule = void 0;
var tslib_1 = require("tslib");
var tsutils_1 = require("tsutils");
var ts = require("typescript");
var Lint = require("../index");
var OPTION_IGNORE_PARMS = "ignore-params";
var OPTION_IGNORE_PROPERTIES = "ignore-properties";
var Rule = /** @class */ (function (_super) {
tslib_1.__extends(Rule, _super);
function Rule() {
return _super !== null && _super.apply(this, arguments) || this;
}
/* tslint:enable:object-literal-sort-keys */
Rule.FAILURE_STRING_FACTORY = function (type) {
return "Type " + type + " trivially inferred from a " + type + " literal, remove type annotation";
};
Rule.prototype.apply = function (sourceFile) {
return this.applyWithWalker(new NoInferrableTypesWalker(sourceFile, this.ruleName, {
ignoreParameters: this.ruleArguments.indexOf(OPTION_IGNORE_PARMS) !== -1,
ignoreProperties: this.ruleArguments.indexOf(OPTION_IGNORE_PROPERTIES) !== -1,
}));
};
/* tslint:disable:object-literal-sort-keys */
Rule.metadata = {
ruleName: "no-inferrable-types",
description: "Disallows explicit type declarations for variables or parameters initialized to a number, string, or boolean.",
rationale: "Explicit types where they can be easily inferred by the compiler make code more verbose.",
optionsDescription: Lint.Utils.dedent(templateObject_1 || (templateObject_1 = tslib_1.__makeTemplateObject(["\n Two arguments may be optionally provided:\n\n * `", "` allows specifying an inferrable type annotation for function params.\n This can be useful when combining with the `typedef` rule.\n * `", "` allows specifying an inferrable type annotation for class properties."], ["\n Two arguments may be optionally provided:\n\n * \\`", "\\` allows specifying an inferrable type annotation for function params.\n This can be useful when combining with the \\`typedef\\` rule.\n * \\`", "\\` allows specifying an inferrable type annotation for class properties."])), OPTION_IGNORE_PARMS, OPTION_IGNORE_PROPERTIES),
options: {
type: "array",
items: {
type: "string",
enum: [OPTION_IGNORE_PARMS, OPTION_IGNORE_PROPERTIES],
},
minLength: 0,
maxLength: 2,
},
hasFix: true,
optionExamples: [
true,
[true, OPTION_IGNORE_PARMS],
[true, OPTION_IGNORE_PARMS, OPTION_IGNORE_PROPERTIES],
],
type: "typescript",
typescriptOnly: true,
};
return Rule;
}(Lint.Rules.AbstractRule));
exports.Rule = Rule;
var NoInferrableTypesWalker = /** @class */ (function (_super) {
tslib_1.__extends(NoInferrableTypesWalker, _super);
function NoInferrableTypesWalker() {
return _super !== null && _super.apply(this, arguments) || this;
}
NoInferrableTypesWalker.prototype.walk = function (sourceFile) {
var _this = this;
var cb = function (node) {
if (shouldCheck(node, _this.options)) {
var name = node.name, type = node.type, initializer = node.initializer;
if (type !== undefined &&
initializer !== undefined &&
typeIsInferrable(type.kind, initializer)) {
var fix = Lint.Replacement.deleteFromTo(name.end, type.end);
_this.addFailureAtNode(type, Rule.FAILURE_STRING_FACTORY(ts.tokenToString(type.kind)), fix);
}
}
return ts.forEachChild(node, cb);
};
return ts.forEachChild(sourceFile, cb);
};
return NoInferrableTypesWalker;
}(Lint.AbstractWalker));
function shouldCheck(node, _a) {
var ignoreParameters = _a.ignoreParameters, ignoreProperties = _a.ignoreProperties;
switch (node.kind) {
case ts.SyntaxKind.Parameter:
return (!ignoreParameters &&
!tsutils_1.hasModifier(node.modifiers, ts.SyntaxKind.ReadonlyKeyword) &&
// "ignore-properties" also works for parameter properties
!(ignoreProperties && node.modifiers !== undefined));
case ts.SyntaxKind.PropertyDeclaration:
return !ignoreProperties && !tsutils_1.hasModifier(node.modifiers, ts.SyntaxKind.ReadonlyKeyword);
case ts.SyntaxKind.VariableDeclaration:
return true;
default:
return false;
}
}
function typeIsInferrable(type, initializer) {
switch (type) {
case ts.SyntaxKind.BooleanKeyword:
return (initializer.kind === ts.SyntaxKind.TrueKeyword ||
initializer.kind === ts.SyntaxKind.FalseKeyword);
case ts.SyntaxKind.NumberKeyword:
return Lint.isNumeric(initializer);
case ts.SyntaxKind.StringKeyword:
switch (initializer.kind) {
case ts.SyntaxKind.StringLiteral:
case ts.SyntaxKind.NoSubstitutionTemplateLiteral:
case ts.SyntaxKind.TemplateExpression:
return true;
default:
return false;
}
default:
return false;
}
}
var templateObject_1;
|
rboixaderg/guillotina
|
guillotina/contrib/workflows/subscriber.py
|
<filename>guillotina/contrib/workflows/subscriber.py
from guillotina import configure
from guillotina.component import query_adapter
from guillotina.contrib.workflows.interfaces import IWorkflow
from guillotina.contrib.workflows.interfaces import IWorkflowBehavior
from guillotina.interfaces import IObjectAddedEvent
from guillotina.interfaces import IResource
from guillotina.security.utils import apply_sharing
from guillotina.utils import get_authenticated_user_id
import datetime
@configure.subscriber(for_=(IResource, IObjectAddedEvent), priority=1001) # after indexing
async def workflow_object_added(obj, event):
workflow = query_adapter(obj, IWorkflowBehavior)
wkf = query_adapter(obj, IWorkflow)
if workflow is not None and wkf is not None:
user_id = get_authenticated_user_id()
await workflow.load(create=True)
state = workflow.review_state
if "set_permission" in wkf.states[state]:
await apply_sharing(obj, wkf.states[state]["set_permission"])
setattr(workflow, "history", [])
workflow.history.append(
{
"actor": user_id,
"comments": "",
"time": datetime.datetime.now(),
"title": "Created",
"type": "workflow",
"data": {"action": None, "review_state": state},
}
)
workflow.register()
|
dbrambilla/event-stream-processing-microservices
|
warehouse/warehouse-worker/src/main/java/demo/warehouse/WarehouseStateFactory.java
|
package demo.warehouse;
import demo.warehouse.domain.Warehouse;
import demo.warehouse.domain.WarehouseStatus;
import demo.warehouse.event.WarehouseEvent;
import demo.warehouse.event.WarehouseEventType;
import demo.warehouse.event.WarehouseEvents;
import org.apache.log4j.Logger;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.MediaTypes;
import org.springframework.hateoas.client.Traverson;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.statemachine.StateMachine;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
@Service
public class WarehouseStateFactory {
final private Logger log = Logger.getLogger(WarehouseStateFactory.class);
final private WarehouseStateService stateService;
public WarehouseStateFactory(WarehouseStateService stateService) {
this.stateService = stateService;
}
public Warehouse apply(WarehouseEvent warehouseEvent) {
Assert.notNull(warehouseEvent, "Cannot apply a null event");
Assert.notNull(warehouseEvent.getId(), "The event payload's identity link was not found");
StateMachine<WarehouseStatus, WarehouseEventType> stateMachine = getStateMachine(warehouseEvent);
stateMachine.stop();
return stateMachine.getExtendedState().get("warehouse", Warehouse.class);
}
private StateMachine<WarehouseStatus, WarehouseEventType> getStateMachine(WarehouseEvent warehouseEvent) {
Link eventId = warehouseEvent.getId();
log.info(String.format("Warehouse event received: %s", eventId));
StateMachine<WarehouseStatus, WarehouseEventType> stateMachine;
Map<String, Object> contextMap;
WarehouseEvents eventLog;
eventLog = getEventLog(warehouseEvent);
contextMap = getEventHeaders(warehouseEvent);
stateMachine = stateService.newStateMachine();
// Replicate the aggregate state
eventLog.getContent().stream()
.sorted((a, b) -> a.getCreatedAt().compareTo(b.getCreatedAt()))
.forEach(e -> stateMachine.sendEvent(MessageBuilder.createMessage(e.getType(), e.getId()
.equals(eventId) ? new MessageHeaders(contextMap) : new MessageHeaders(null))));
return stateMachine;
}
private Map<String, Object> getEventHeaders(WarehouseEvent warehouseEvent) {
Map<String, Object> headerMap = new HashMap<>();
headerMap.put("event", warehouseEvent);
return headerMap;
}
private WarehouseEvents getEventLog(WarehouseEvent event) {
// Follow the hypermedia link to fetch the attached warehouse
Traverson traverson = new Traverson(
URI.create(event.getLink("warehouse")
.getHref()),
MediaTypes.HAL_JSON
);
// Get the event log for the attached warehouse resource
return traverson.follow("events")
.toEntity(WarehouseEvents.class)
.getBody();
}
}
|
boom-roasted/ImageWAO
|
src/main/python/ui/imageviewer/menus/colormenu.py
|
<reponame>boom-roasted/ImageWAO<filename>src/main/python/ui/imageviewer/menus/colormenu.py
from PySide2 import QtCore, QtGui, QtWidgets
class ColorMenu(QtWidgets.QMenu):
# When the color is changed, the new color will be emitted
# from this signal
colorChanged = QtCore.Signal(QtGui.QColor)
def __init__(self, colors):
"""
Create and assign menu actions with icons corresponding
to the input list of colors
"""
super().__init__()
self.actions = []
self._activeIndex = 0
for color in colors:
qcolor = QtGui.QColor(color)
icon = self.circularColorIcon(qcolor)
action = QtWidgets.QAction(icon, qcolor.name(QtGui.QColor.HexRgb))
action.qcolor = qcolor
action.setCheckable(True)
action.triggered.connect(self.handleColorChanged)
self.actions.append(action)
self.addAction(action)
# Initialize the first item as the one selected
self._activeIndex = 0
self.actions[0].setChecked(True)
@property
def activeColor(self):
return self.actions[self._activeIndex].qcolor
def emitActiveColor(self):
"""
Trigger an emit for the active index.
This method is used internally, but can also be called externally
to manually emit the colorChanged signal on the active index.
This can be helpful when initializing the class after setting up
the proper slots.
"""
self.colorChanged.emit(self.activeColor)
@staticmethod
def circularColorIcon(qcolor, w=100, h=100):
"""
Creates a circular icon with transparent background
and solid color of a given width w and height h
"""
img = QtGui.QImage(w, h, QtGui.QImage.Format_ARGB32)
img.fill(QtGui.qRgba(0, 0, 0, 0))
painter = QtGui.QPainter(img)
painter.setBrush(qcolor)
painter.drawEllipse(5, 5, w - 10, h - 10)
painter.end()
icon = QtGui.QIcon(QtGui.QPixmap.fromImage(img))
return icon
@staticmethod
def maskedIcon(qcolor, maskImg: QtGui.QPixmap):
"""
Creates an icon of a given color from the given mask
"""
img = QtGui.QPixmap(maskImg.size())
mask = maskImg.createMaskFromColor(
QtGui.QColor("black"), QtCore.Qt.MaskOutColor
)
img.fill(qcolor)
img.setMask(mask)
return img
def handleColorChanged(self, checked):
# If we tried to uncheck an item, don't allow it
if checked is False:
self.actions[self._activeIndex].setChecked(True)
return
# Uncheck the previously active index
self.actions[self._activeIndex].setChecked(False)
# Find the new active action, change the active index,
# and emit the color
for i, a in enumerate(self.actions):
if a.isChecked():
self._activeIndex = i
self.emitActiveColor()
return
class ColorableAction(QtWidgets.QAction):
"""
An action whose icon can be re-colored with a mask.
Instance also contains information about what kind of drawing
it might perform
"""
def __init__(self, mask: QtGui.QPixmap, *args, **kwargs):
super().__init__(*args, **kwargs)
self.mask = mask
self.setIcon(mask)
def recolor(self, color: QtGui.QColor):
self.setIcon(ColorMenu.maskedIcon(color, self.mask))
|
pekd/vmx86
|
projects/org.graalvm.vm.trcview/src/org/graalvm/vm/trcview/analysis/type/ArchitectureTypeInfo.java
|
package org.graalvm.vm.trcview.analysis.type;
public class ArchitectureTypeInfo {
public static final ArchitectureTypeInfo LP32 = new ArchitectureTypeInfo(4, 2, 2, 4);
public static final ArchitectureTypeInfo ILP32 = new ArchitectureTypeInfo(4, 2, 4, 4);
public static final ArchitectureTypeInfo LLP64 = new ArchitectureTypeInfo(8, 2, 4, 4);
public static final ArchitectureTypeInfo LP64 = new ArchitectureTypeInfo(8, 2, 4, 8);
public static final ArchitectureTypeInfo ILP64 = new ArchitectureTypeInfo(8, 2, 8, 8);
public static final ArchitectureTypeInfo SILP64 = new ArchitectureTypeInfo(8, 8, 8, 8);
private final int pointerSize;
private final int shortSize;
private final int intSize;
private final int longSize;
public ArchitectureTypeInfo(int pointerSize, int shortSize, int intSize, int longSize) {
if (shortSize > intSize) {
throw new IllegalArgumentException("sizeof(short) must be less than or equal to sizeof(int)");
}
if (intSize > longSize) {
throw new IllegalArgumentException("sizeof(int) must be less than or equal to sizeof(long)");
}
this.pointerSize = pointerSize;
this.shortSize = shortSize;
this.intSize = intSize;
this.longSize = longSize;
}
public int getPointerSize() {
return pointerSize;
}
public int getShortSize() {
return shortSize;
}
public int getIntSize() {
return intSize;
}
public int getLongSize() {
return longSize;
}
private static DataType getType(int size, boolean isUnsigned) {
if (isUnsigned) {
switch (size) {
case 1:
return DataType.U8;
case 2:
return DataType.U16;
case 4:
return DataType.U32;
case 8:
return DataType.U64;
default:
throw new IllegalArgumentException("invalid size " + size);
}
} else {
switch (size) {
case 1:
return DataType.S8;
case 2:
return DataType.S16;
case 4:
return DataType.S32;
case 8:
return DataType.S64;
default:
throw new IllegalArgumentException("invalid size " + size);
}
}
}
public DataType getShortType(boolean isUnsigned) {
return getType(shortSize, isUnsigned);
}
public DataType getIntType(boolean isUnsigned) {
return getType(intSize, isUnsigned);
}
public DataType getLongType(boolean isUnsigned) {
return getType(longSize, isUnsigned);
}
}
|
zyb2013/gameserver
|
server/src/gensrc/java/com/xinqihd/sns/gameserver/proto/XinqiUserExData.java
|
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: UserExData.proto
package com.xinqihd.sns.gameserver.proto;
public final class XinqiUserExData {
private XinqiUserExData() {}
public static void registerAllExtensions(
com.google.protobuf.ExtensionRegistry registry) {
}
public interface UserExDataOrBuilder
extends com.google.protobuf.MessageOrBuilder {
// required int32 roleExp = 1;
boolean hasRoleExp();
int getRoleExp();
// required int32 roleGold = 2;
boolean hasRoleGold();
int getRoleGold();
// required int32 roleCoin = 3;
boolean hasRoleCoin();
int getRoleCoin();
// required int32 roleArrange = 4;
boolean hasRoleArrange();
int getRoleArrange();
// required int32 roleWinOdds = 5;
boolean hasRoleWinOdds();
int getRoleWinOdds();
// required int32 roleWins = 6;
boolean hasRoleWins();
int getRoleWins();
// required int32 sign = 7;
boolean hasSign();
int getSign();
// optional int32 point = 9;
boolean hasPoint();
int getPoint();
// optional int32 roleBindCoin = 10;
boolean hasRoleBindCoin();
int getRoleBindCoin();
// optional bool isMoneyAdd = 11 [default = false];
boolean hasIsMoneyAdd();
boolean getIsMoneyAdd();
// optional int32 shootMode = 12;
boolean hasShootMode();
int getShootMode();
}
public static final class UserExData extends
com.google.protobuf.GeneratedMessage
implements UserExDataOrBuilder {
// Use UserExData.newBuilder() to construct.
private UserExData(Builder builder) {
super(builder);
}
private UserExData(boolean noInit) {}
private static final UserExData defaultInstance;
public static UserExData getDefaultInstance() {
return defaultInstance;
}
public UserExData getDefaultInstanceForType() {
return defaultInstance;
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.xinqihd.sns.gameserver.proto.XinqiUserExData.internal_static_com_xinqihd_sns_gameserver_proto_UserExData_descriptor;
}
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.xinqihd.sns.gameserver.proto.XinqiUserExData.internal_static_com_xinqihd_sns_gameserver_proto_UserExData_fieldAccessorTable;
}
private int bitField0_;
// required int32 roleExp = 1;
public static final int ROLEEXP_FIELD_NUMBER = 1;
private int roleExp_;
public boolean hasRoleExp() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
public int getRoleExp() {
return roleExp_;
}
// required int32 roleGold = 2;
public static final int ROLEGOLD_FIELD_NUMBER = 2;
private int roleGold_;
public boolean hasRoleGold() {
return ((bitField0_ & 0x00000002) == 0x00000002);
}
public int getRoleGold() {
return roleGold_;
}
// required int32 roleCoin = 3;
public static final int ROLECOIN_FIELD_NUMBER = 3;
private int roleCoin_;
public boolean hasRoleCoin() {
return ((bitField0_ & 0x00000004) == 0x00000004);
}
public int getRoleCoin() {
return roleCoin_;
}
// required int32 roleArrange = 4;
public static final int ROLEARRANGE_FIELD_NUMBER = 4;
private int roleArrange_;
public boolean hasRoleArrange() {
return ((bitField0_ & 0x00000008) == 0x00000008);
}
public int getRoleArrange() {
return roleArrange_;
}
// required int32 roleWinOdds = 5;
public static final int ROLEWINODDS_FIELD_NUMBER = 5;
private int roleWinOdds_;
public boolean hasRoleWinOdds() {
return ((bitField0_ & 0x00000010) == 0x00000010);
}
public int getRoleWinOdds() {
return roleWinOdds_;
}
// required int32 roleWins = 6;
public static final int ROLEWINS_FIELD_NUMBER = 6;
private int roleWins_;
public boolean hasRoleWins() {
return ((bitField0_ & 0x00000020) == 0x00000020);
}
public int getRoleWins() {
return roleWins_;
}
// required int32 sign = 7;
public static final int SIGN_FIELD_NUMBER = 7;
private int sign_;
public boolean hasSign() {
return ((bitField0_ & 0x00000040) == 0x00000040);
}
public int getSign() {
return sign_;
}
// optional int32 point = 9;
public static final int POINT_FIELD_NUMBER = 9;
private int point_;
public boolean hasPoint() {
return ((bitField0_ & 0x00000080) == 0x00000080);
}
public int getPoint() {
return point_;
}
// optional int32 roleBindCoin = 10;
public static final int ROLEBINDCOIN_FIELD_NUMBER = 10;
private int roleBindCoin_;
public boolean hasRoleBindCoin() {
return ((bitField0_ & 0x00000100) == 0x00000100);
}
public int getRoleBindCoin() {
return roleBindCoin_;
}
// optional bool isMoneyAdd = 11 [default = false];
public static final int ISMONEYADD_FIELD_NUMBER = 11;
private boolean isMoneyAdd_;
public boolean hasIsMoneyAdd() {
return ((bitField0_ & 0x00000200) == 0x00000200);
}
public boolean getIsMoneyAdd() {
return isMoneyAdd_;
}
// optional int32 shootMode = 12;
public static final int SHOOTMODE_FIELD_NUMBER = 12;
private int shootMode_;
public boolean hasShootMode() {
return ((bitField0_ & 0x00000400) == 0x00000400);
}
public int getShootMode() {
return shootMode_;
}
private void initFields() {
roleExp_ = 0;
roleGold_ = 0;
roleCoin_ = 0;
roleArrange_ = 0;
roleWinOdds_ = 0;
roleWins_ = 0;
sign_ = 0;
point_ = 0;
roleBindCoin_ = 0;
isMoneyAdd_ = false;
shootMode_ = 0;
}
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized != -1) return isInitialized == 1;
if (!hasRoleExp()) {
memoizedIsInitialized = 0;
return false;
}
if (!hasRoleGold()) {
memoizedIsInitialized = 0;
return false;
}
if (!hasRoleCoin()) {
memoizedIsInitialized = 0;
return false;
}
if (!hasRoleArrange()) {
memoizedIsInitialized = 0;
return false;
}
if (!hasRoleWinOdds()) {
memoizedIsInitialized = 0;
return false;
}
if (!hasRoleWins()) {
memoizedIsInitialized = 0;
return false;
}
if (!hasSign()) {
memoizedIsInitialized = 0;
return false;
}
memoizedIsInitialized = 1;
return true;
}
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
getSerializedSize();
if (((bitField0_ & 0x00000001) == 0x00000001)) {
output.writeInt32(1, roleExp_);
}
if (((bitField0_ & 0x00000002) == 0x00000002)) {
output.writeInt32(2, roleGold_);
}
if (((bitField0_ & 0x00000004) == 0x00000004)) {
output.writeInt32(3, roleCoin_);
}
if (((bitField0_ & 0x00000008) == 0x00000008)) {
output.writeInt32(4, roleArrange_);
}
if (((bitField0_ & 0x00000010) == 0x00000010)) {
output.writeInt32(5, roleWinOdds_);
}
if (((bitField0_ & 0x00000020) == 0x00000020)) {
output.writeInt32(6, roleWins_);
}
if (((bitField0_ & 0x00000040) == 0x00000040)) {
output.writeInt32(7, sign_);
}
if (((bitField0_ & 0x00000080) == 0x00000080)) {
output.writeInt32(9, point_);
}
if (((bitField0_ & 0x00000100) == 0x00000100)) {
output.writeInt32(10, roleBindCoin_);
}
if (((bitField0_ & 0x00000200) == 0x00000200)) {
output.writeBool(11, isMoneyAdd_);
}
if (((bitField0_ & 0x00000400) == 0x00000400)) {
output.writeInt32(12, shootMode_);
}
getUnknownFields().writeTo(output);
}
private int memoizedSerializedSize = -1;
public int getSerializedSize() {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
if (((bitField0_ & 0x00000001) == 0x00000001)) {
size += com.google.protobuf.CodedOutputStream
.computeInt32Size(1, roleExp_);
}
if (((bitField0_ & 0x00000002) == 0x00000002)) {
size += com.google.protobuf.CodedOutputStream
.computeInt32Size(2, roleGold_);
}
if (((bitField0_ & 0x00000004) == 0x00000004)) {
size += com.google.protobuf.CodedOutputStream
.computeInt32Size(3, roleCoin_);
}
if (((bitField0_ & 0x00000008) == 0x00000008)) {
size += com.google.protobuf.CodedOutputStream
.computeInt32Size(4, roleArrange_);
}
if (((bitField0_ & 0x00000010) == 0x00000010)) {
size += com.google.protobuf.CodedOutputStream
.computeInt32Size(5, roleWinOdds_);
}
if (((bitField0_ & 0x00000020) == 0x00000020)) {
size += com.google.protobuf.CodedOutputStream
.computeInt32Size(6, roleWins_);
}
if (((bitField0_ & 0x00000040) == 0x00000040)) {
size += com.google.protobuf.CodedOutputStream
.computeInt32Size(7, sign_);
}
if (((bitField0_ & 0x00000080) == 0x00000080)) {
size += com.google.protobuf.CodedOutputStream
.computeInt32Size(9, point_);
}
if (((bitField0_ & 0x00000100) == 0x00000100)) {
size += com.google.protobuf.CodedOutputStream
.computeInt32Size(10, roleBindCoin_);
}
if (((bitField0_ & 0x00000200) == 0x00000200)) {
size += com.google.protobuf.CodedOutputStream
.computeBoolSize(11, isMoneyAdd_);
}
if (((bitField0_ & 0x00000400) == 0x00000400)) {
size += com.google.protobuf.CodedOutputStream
.computeInt32Size(12, shootMode_);
}
size += getUnknownFields().getSerializedSize();
memoizedSerializedSize = size;
return size;
}
private static final long serialVersionUID = 0L;
@java.lang.Override
protected java.lang.Object writeReplace()
throws java.io.ObjectStreamException {
return super.writeReplace();
}
public static com.xinqihd.sns.gameserver.proto.XinqiUserExData.UserExData parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return newBuilder().mergeFrom(data).buildParsed();
}
public static com.xinqihd.sns.gameserver.proto.XinqiUserExData.UserExData parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return newBuilder().mergeFrom(data, extensionRegistry)
.buildParsed();
}
public static com.xinqihd.sns.gameserver.proto.XinqiUserExData.UserExData parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return newBuilder().mergeFrom(data).buildParsed();
}
public static com.xinqihd.sns.gameserver.proto.XinqiUserExData.UserExData parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return newBuilder().mergeFrom(data, extensionRegistry)
.buildParsed();
}
public static com.xinqihd.sns.gameserver.proto.XinqiUserExData.UserExData parseFrom(java.io.InputStream input)
throws java.io.IOException {
return newBuilder().mergeFrom(input).buildParsed();
}
public static com.xinqihd.sns.gameserver.proto.XinqiUserExData.UserExData parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return newBuilder().mergeFrom(input, extensionRegistry)
.buildParsed();
}
public static com.xinqihd.sns.gameserver.proto.XinqiUserExData.UserExData parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
Builder builder = newBuilder();
if (builder.mergeDelimitedFrom(input)) {
return builder.buildParsed();
} else {
return null;
}
}
public static com.xinqihd.sns.gameserver.proto.XinqiUserExData.UserExData parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
Builder builder = newBuilder();
if (builder.mergeDelimitedFrom(input, extensionRegistry)) {
return builder.buildParsed();
} else {
return null;
}
}
public static com.xinqihd.sns.gameserver.proto.XinqiUserExData.UserExData parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return newBuilder().mergeFrom(input).buildParsed();
}
public static com.xinqihd.sns.gameserver.proto.XinqiUserExData.UserExData parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return newBuilder().mergeFrom(input, extensionRegistry)
.buildParsed();
}
public static Builder newBuilder() { return Builder.create(); }
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder(com.xinqihd.sns.gameserver.proto.XinqiUserExData.UserExData prototype) {
return newBuilder().mergeFrom(prototype);
}
public Builder toBuilder() { return newBuilder(this); }
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessage.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
public static final class Builder extends
com.google.protobuf.GeneratedMessage.Builder<Builder>
implements com.xinqihd.sns.gameserver.proto.XinqiUserExData.UserExDataOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.xinqihd.sns.gameserver.proto.XinqiUserExData.internal_static_com_xinqihd_sns_gameserver_proto_UserExData_descriptor;
}
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.xinqihd.sns.gameserver.proto.XinqiUserExData.internal_static_com_xinqihd_sns_gameserver_proto_UserExData_fieldAccessorTable;
}
// Construct using com.xinqihd.sns.gameserver.proto.XinqiUserExData.UserExData.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
}
}
private static Builder create() {
return new Builder();
}
public Builder clear() {
super.clear();
roleExp_ = 0;
bitField0_ = (bitField0_ & ~0x00000001);
roleGold_ = 0;
bitField0_ = (bitField0_ & ~0x00000002);
roleCoin_ = 0;
bitField0_ = (bitField0_ & ~0x00000004);
roleArrange_ = 0;
bitField0_ = (bitField0_ & ~0x00000008);
roleWinOdds_ = 0;
bitField0_ = (bitField0_ & ~0x00000010);
roleWins_ = 0;
bitField0_ = (bitField0_ & ~0x00000020);
sign_ = 0;
bitField0_ = (bitField0_ & ~0x00000040);
point_ = 0;
bitField0_ = (bitField0_ & ~0x00000080);
roleBindCoin_ = 0;
bitField0_ = (bitField0_ & ~0x00000100);
isMoneyAdd_ = false;
bitField0_ = (bitField0_ & ~0x00000200);
shootMode_ = 0;
bitField0_ = (bitField0_ & ~0x00000400);
return this;
}
public Builder clone() {
return create().mergeFrom(buildPartial());
}
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.xinqihd.sns.gameserver.proto.XinqiUserExData.UserExData.getDescriptor();
}
public com.xinqihd.sns.gameserver.proto.XinqiUserExData.UserExData getDefaultInstanceForType() {
return com.xinqihd.sns.gameserver.proto.XinqiUserExData.UserExData.getDefaultInstance();
}
public com.xinqihd.sns.gameserver.proto.XinqiUserExData.UserExData build() {
com.xinqihd.sns.gameserver.proto.XinqiUserExData.UserExData result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
private com.xinqihd.sns.gameserver.proto.XinqiUserExData.UserExData buildParsed()
throws com.google.protobuf.InvalidProtocolBufferException {
com.xinqihd.sns.gameserver.proto.XinqiUserExData.UserExData result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(
result).asInvalidProtocolBufferException();
}
return result;
}
public com.xinqihd.sns.gameserver.proto.XinqiUserExData.UserExData buildPartial() {
com.xinqihd.sns.gameserver.proto.XinqiUserExData.UserExData result = new com.xinqihd.sns.gameserver.proto.XinqiUserExData.UserExData(this);
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
to_bitField0_ |= 0x00000001;
}
result.roleExp_ = roleExp_;
if (((from_bitField0_ & 0x00000002) == 0x00000002)) {
to_bitField0_ |= 0x00000002;
}
result.roleGold_ = roleGold_;
if (((from_bitField0_ & 0x00000004) == 0x00000004)) {
to_bitField0_ |= 0x00000004;
}
result.roleCoin_ = roleCoin_;
if (((from_bitField0_ & 0x00000008) == 0x00000008)) {
to_bitField0_ |= 0x00000008;
}
result.roleArrange_ = roleArrange_;
if (((from_bitField0_ & 0x00000010) == 0x00000010)) {
to_bitField0_ |= 0x00000010;
}
result.roleWinOdds_ = roleWinOdds_;
if (((from_bitField0_ & 0x00000020) == 0x00000020)) {
to_bitField0_ |= 0x00000020;
}
result.roleWins_ = roleWins_;
if (((from_bitField0_ & 0x00000040) == 0x00000040)) {
to_bitField0_ |= 0x00000040;
}
result.sign_ = sign_;
if (((from_bitField0_ & 0x00000080) == 0x00000080)) {
to_bitField0_ |= 0x00000080;
}
result.point_ = point_;
if (((from_bitField0_ & 0x00000100) == 0x00000100)) {
to_bitField0_ |= 0x00000100;
}
result.roleBindCoin_ = roleBindCoin_;
if (((from_bitField0_ & 0x00000200) == 0x00000200)) {
to_bitField0_ |= 0x00000200;
}
result.isMoneyAdd_ = isMoneyAdd_;
if (((from_bitField0_ & 0x00000400) == 0x00000400)) {
to_bitField0_ |= 0x00000400;
}
result.shootMode_ = shootMode_;
result.bitField0_ = to_bitField0_;
onBuilt();
return result;
}
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.xinqihd.sns.gameserver.proto.XinqiUserExData.UserExData) {
return mergeFrom((com.xinqihd.sns.gameserver.proto.XinqiUserExData.UserExData)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.xinqihd.sns.gameserver.proto.XinqiUserExData.UserExData other) {
if (other == com.xinqihd.sns.gameserver.proto.XinqiUserExData.UserExData.getDefaultInstance()) return this;
if (other.hasRoleExp()) {
setRoleExp(other.getRoleExp());
}
if (other.hasRoleGold()) {
setRoleGold(other.getRoleGold());
}
if (other.hasRoleCoin()) {
setRoleCoin(other.getRoleCoin());
}
if (other.hasRoleArrange()) {
setRoleArrange(other.getRoleArrange());
}
if (other.hasRoleWinOdds()) {
setRoleWinOdds(other.getRoleWinOdds());
}
if (other.hasRoleWins()) {
setRoleWins(other.getRoleWins());
}
if (other.hasSign()) {
setSign(other.getSign());
}
if (other.hasPoint()) {
setPoint(other.getPoint());
}
if (other.hasRoleBindCoin()) {
setRoleBindCoin(other.getRoleBindCoin());
}
if (other.hasIsMoneyAdd()) {
setIsMoneyAdd(other.getIsMoneyAdd());
}
if (other.hasShootMode()) {
setShootMode(other.getShootMode());
}
this.mergeUnknownFields(other.getUnknownFields());
return this;
}
public final boolean isInitialized() {
if (!hasRoleExp()) {
return false;
}
if (!hasRoleGold()) {
return false;
}
if (!hasRoleCoin()) {
return false;
}
if (!hasRoleArrange()) {
return false;
}
if (!hasRoleWinOdds()) {
return false;
}
if (!hasRoleWins()) {
return false;
}
if (!hasSign()) {
return false;
}
return true;
}
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder(
this.getUnknownFields());
while (true) {
int tag = input.readTag();
switch (tag) {
case 0:
this.setUnknownFields(unknownFields.build());
onChanged();
return this;
default: {
if (!parseUnknownField(input, unknownFields,
extensionRegistry, tag)) {
this.setUnknownFields(unknownFields.build());
onChanged();
return this;
}
break;
}
case 8: {
bitField0_ |= 0x00000001;
roleExp_ = input.readInt32();
break;
}
case 16: {
bitField0_ |= 0x00000002;
roleGold_ = input.readInt32();
break;
}
case 24: {
bitField0_ |= 0x00000004;
roleCoin_ = input.readInt32();
break;
}
case 32: {
bitField0_ |= 0x00000008;
roleArrange_ = input.readInt32();
break;
}
case 40: {
bitField0_ |= 0x00000010;
roleWinOdds_ = input.readInt32();
break;
}
case 48: {
bitField0_ |= 0x00000020;
roleWins_ = input.readInt32();
break;
}
case 56: {
bitField0_ |= 0x00000040;
sign_ = input.readInt32();
break;
}
case 72: {
bitField0_ |= 0x00000080;
point_ = input.readInt32();
break;
}
case 80: {
bitField0_ |= 0x00000100;
roleBindCoin_ = input.readInt32();
break;
}
case 88: {
bitField0_ |= 0x00000200;
isMoneyAdd_ = input.readBool();
break;
}
case 96: {
bitField0_ |= 0x00000400;
shootMode_ = input.readInt32();
break;
}
}
}
}
private int bitField0_;
// required int32 roleExp = 1;
private int roleExp_ ;
public boolean hasRoleExp() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
public int getRoleExp() {
return roleExp_;
}
public Builder setRoleExp(int value) {
bitField0_ |= 0x00000001;
roleExp_ = value;
onChanged();
return this;
}
public Builder clearRoleExp() {
bitField0_ = (bitField0_ & ~0x00000001);
roleExp_ = 0;
onChanged();
return this;
}
// required int32 roleGold = 2;
private int roleGold_ ;
public boolean hasRoleGold() {
return ((bitField0_ & 0x00000002) == 0x00000002);
}
public int getRoleGold() {
return roleGold_;
}
public Builder setRoleGold(int value) {
bitField0_ |= 0x00000002;
roleGold_ = value;
onChanged();
return this;
}
public Builder clearRoleGold() {
bitField0_ = (bitField0_ & ~0x00000002);
roleGold_ = 0;
onChanged();
return this;
}
// required int32 roleCoin = 3;
private int roleCoin_ ;
public boolean hasRoleCoin() {
return ((bitField0_ & 0x00000004) == 0x00000004);
}
public int getRoleCoin() {
return roleCoin_;
}
public Builder setRoleCoin(int value) {
bitField0_ |= 0x00000004;
roleCoin_ = value;
onChanged();
return this;
}
public Builder clearRoleCoin() {
bitField0_ = (bitField0_ & ~0x00000004);
roleCoin_ = 0;
onChanged();
return this;
}
// required int32 roleArrange = 4;
private int roleArrange_ ;
public boolean hasRoleArrange() {
return ((bitField0_ & 0x00000008) == 0x00000008);
}
public int getRoleArrange() {
return roleArrange_;
}
public Builder setRoleArrange(int value) {
bitField0_ |= 0x00000008;
roleArrange_ = value;
onChanged();
return this;
}
public Builder clearRoleArrange() {
bitField0_ = (bitField0_ & ~0x00000008);
roleArrange_ = 0;
onChanged();
return this;
}
// required int32 roleWinOdds = 5;
private int roleWinOdds_ ;
public boolean hasRoleWinOdds() {
return ((bitField0_ & 0x00000010) == 0x00000010);
}
public int getRoleWinOdds() {
return roleWinOdds_;
}
public Builder setRoleWinOdds(int value) {
bitField0_ |= 0x00000010;
roleWinOdds_ = value;
onChanged();
return this;
}
public Builder clearRoleWinOdds() {
bitField0_ = (bitField0_ & ~0x00000010);
roleWinOdds_ = 0;
onChanged();
return this;
}
// required int32 roleWins = 6;
private int roleWins_ ;
public boolean hasRoleWins() {
return ((bitField0_ & 0x00000020) == 0x00000020);
}
public int getRoleWins() {
return roleWins_;
}
public Builder setRoleWins(int value) {
bitField0_ |= 0x00000020;
roleWins_ = value;
onChanged();
return this;
}
public Builder clearRoleWins() {
bitField0_ = (bitField0_ & ~0x00000020);
roleWins_ = 0;
onChanged();
return this;
}
// required int32 sign = 7;
private int sign_ ;
public boolean hasSign() {
return ((bitField0_ & 0x00000040) == 0x00000040);
}
public int getSign() {
return sign_;
}
public Builder setSign(int value) {
bitField0_ |= 0x00000040;
sign_ = value;
onChanged();
return this;
}
public Builder clearSign() {
bitField0_ = (bitField0_ & ~0x00000040);
sign_ = 0;
onChanged();
return this;
}
// optional int32 point = 9;
private int point_ ;
public boolean hasPoint() {
return ((bitField0_ & 0x00000080) == 0x00000080);
}
public int getPoint() {
return point_;
}
public Builder setPoint(int value) {
bitField0_ |= 0x00000080;
point_ = value;
onChanged();
return this;
}
public Builder clearPoint() {
bitField0_ = (bitField0_ & ~0x00000080);
point_ = 0;
onChanged();
return this;
}
// optional int32 roleBindCoin = 10;
private int roleBindCoin_ ;
public boolean hasRoleBindCoin() {
return ((bitField0_ & 0x00000100) == 0x00000100);
}
public int getRoleBindCoin() {
return roleBindCoin_;
}
public Builder setRoleBindCoin(int value) {
bitField0_ |= 0x00000100;
roleBindCoin_ = value;
onChanged();
return this;
}
public Builder clearRoleBindCoin() {
bitField0_ = (bitField0_ & ~0x00000100);
roleBindCoin_ = 0;
onChanged();
return this;
}
// optional bool isMoneyAdd = 11 [default = false];
private boolean isMoneyAdd_ ;
public boolean hasIsMoneyAdd() {
return ((bitField0_ & 0x00000200) == 0x00000200);
}
public boolean getIsMoneyAdd() {
return isMoneyAdd_;
}
public Builder setIsMoneyAdd(boolean value) {
bitField0_ |= 0x00000200;
isMoneyAdd_ = value;
onChanged();
return this;
}
public Builder clearIsMoneyAdd() {
bitField0_ = (bitField0_ & ~0x00000200);
isMoneyAdd_ = false;
onChanged();
return this;
}
// optional int32 shootMode = 12;
private int shootMode_ ;
public boolean hasShootMode() {
return ((bitField0_ & 0x00000400) == 0x00000400);
}
public int getShootMode() {
return shootMode_;
}
public Builder setShootMode(int value) {
bitField0_ |= 0x00000400;
shootMode_ = value;
onChanged();
return this;
}
public Builder clearShootMode() {
bitField0_ = (bitField0_ & ~0x00000400);
shootMode_ = 0;
onChanged();
return this;
}
// @@protoc_insertion_point(builder_scope:com.xinqihd.sns.gameserver.proto.UserExData)
}
static {
defaultInstance = new UserExData(true);
defaultInstance.initFields();
}
// @@protoc_insertion_point(class_scope:com.xinqihd.sns.gameserver.proto.UserExData)
}
private static com.google.protobuf.Descriptors.Descriptor
internal_static_com_xinqihd_sns_gameserver_proto_UserExData_descriptor;
private static
com.google.protobuf.GeneratedMessage.FieldAccessorTable
internal_static_com_xinqihd_sns_gameserver_proto_UserExData_fieldAccessorTable;
public static com.google.protobuf.Descriptors.FileDescriptor
getDescriptor() {
return descriptor;
}
private static com.google.protobuf.Descriptors.FileDescriptor
descriptor;
static {
java.lang.String[] descriptorData = {
"\n\020UserExData.proto\022 com.xinqihd.sns.game" +
"server.proto\"\336\001\n\nUserExData\022\017\n\007roleExp\030\001" +
" \002(\005\022\020\n\010roleGold\030\002 \002(\005\022\020\n\010roleCoin\030\003 \002(\005" +
"\022\023\n\013roleArrange\030\004 \002(\005\022\023\n\013roleWinOdds\030\005 \002" +
"(\005\022\020\n\010roleWins\030\006 \002(\005\022\014\n\004sign\030\007 \002(\005\022\r\n\005po" +
"int\030\t \001(\005\022\024\n\014roleBindCoin\030\n \001(\005\022\031\n\nisMon" +
"eyAdd\030\013 \001(\010:\005false\022\021\n\tshootMode\030\014 \001(\005B\021B" +
"\017XinqiUserExData"
};
com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner =
new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() {
public com.google.protobuf.ExtensionRegistry assignDescriptors(
com.google.protobuf.Descriptors.FileDescriptor root) {
descriptor = root;
internal_static_com_xinqihd_sns_gameserver_proto_UserExData_descriptor =
getDescriptor().getMessageTypes().get(0);
internal_static_com_xinqihd_sns_gameserver_proto_UserExData_fieldAccessorTable = new
com.google.protobuf.GeneratedMessage.FieldAccessorTable(
internal_static_com_xinqihd_sns_gameserver_proto_UserExData_descriptor,
new java.lang.String[] { "RoleExp", "RoleGold", "RoleCoin", "RoleArrange", "RoleWinOdds", "RoleWins", "Sign", "Point", "RoleBindCoin", "IsMoneyAdd", "ShootMode", },
com.xinqihd.sns.gameserver.proto.XinqiUserExData.UserExData.class,
com.xinqihd.sns.gameserver.proto.XinqiUserExData.UserExData.Builder.class);
return null;
}
};
com.google.protobuf.Descriptors.FileDescriptor
.internalBuildGeneratedFileFrom(descriptorData,
new com.google.protobuf.Descriptors.FileDescriptor[] {
}, assigner);
}
// @@protoc_insertion_point(outer_class_scope)
}
|
insightfullogic/java-multi-inherit
|
src/test/java/com/insightfullogic/multiinherit/traits/Ordering.java
|
<reponame>insightfullogic/java-multi-inherit
package com.insightfullogic.multiinherit.traits;
import com.insightfullogic.multiinherit.api.TraitWith;
@TraitWith(OrderingImpl.class)
public interface Ordering {
public int compare(Object r);
public boolean lessThan(Object r);
public boolean greaterThan(Object r);
public boolean equalsOrd(final Object other);
}
|
lukasz-pekala/AFE-Firmware
|
lib/AFE-Data-Structure/AFE-PASSWORD-Structure.h
|
<reponame>lukasz-pekala/AFE-Firmware
/* AFE Firmware for smart home devices, Website: https://afe.smartnydom.pl/ */
#ifndef _AFE_PASSWORD_Structure_h
#define _AFE_PASSWORD_Structure_h
#if defined(ARDUINO) && ARDUINO >= 100
#include "arduino.h"
#else
#include "WProgram.h"
#endif
struct PASSWORD {
boolean protect;
char password[10];
};
#endif
|
CodelityLtd/codelity-event-sourcing
|
codelity-event-sourcing-spring-config/src/test/java/uk/co/codelity/event/sourcing/spring/AutoConfigurationTest.java
|
<reponame>CodelityLtd/codelity-event-sourcing
package uk.co.codelity.event.sourcing.spring;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import uk.co.codelity.event.sourcing.core.bootstrap.Bootstrapper;
import uk.co.codelity.event.sourcing.core.context.EventSourcingContext;
import java.util.HashMap;
import java.util.Map;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
class AutoConfigurationTest {
@Mock
ApplicationContext applicationContext;
@Mock
Bootstrapper bootstrapper;
@Captor
ArgumentCaptor<String> appClassCaptor;
@Test
void shouldRunBootstrapperInitContext() throws Exception {
Map<String, Object> beans = new HashMap<>();
beans.put("app", new App());
when(applicationContext.getBeansWithAnnotation(SpringBootApplication.class)).thenReturn(beans);
AutoConfiguration autoConfiguration = new AutoConfiguration();
EventSourcingContext eventSourcingContext = autoConfiguration.eventSourcingContext(applicationContext, bootstrapper);
verify(bootstrapper, times(1)).initContext(appClassCaptor.capture());
assertThat(appClassCaptor.getValue(), is(App.class.getPackageName()));
}
@SpringBootApplication
static class App { }
}
|
javinc/ratatxt
|
ui/src/reducers/version.js
|
<gh_stars>0
import { VERSION } from '../actions/types'
import { formatError } from './util'
const initialObjectState = {
production: false,
tag: '',
git_commit: '',
built: '',
}
export default function version(
state = {
data: initialObjectState,
fetching: false,
error: null,
},
action
) {
switch (action.type) {
case VERSION.REQUEST:
return {
...state,
fetching: true,
error: null,
}
case VERSION.SUCCESS:
return {
...state,
fetching: false,
error: null,
data: action.data,
}
case VERSION.FAILURE:
return {
...state,
fetching: false,
error: formatError(action.error),
}
default:
return state
}
}
|
hehanlin/pat_match
|
heHanLin/yi/1011.cpp
|
<filename>heHanLin/yi/1011.cpp
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
using namespace std;
/*
1011. A+B和C (15)
https://www.patest.cn/contests/pat-b-practise/1011
给定区间[-231, 231]内的3个整数A、B和C,请判断A+B是否大于C。
输入格式:
输入第1行给出正整数T(<=10),是测试用例的个数。随后给出T组测试用例,每组占一行,顺序给出A、B和C。整数间以空格分隔。
输出格式:
对每组测试用例,在一行中输出“Case #X: true”如果A+B>C,否则输出“Case #X: false”,其中X是测试用例的编号(从1开始)。
输入样例:
4
1 2 3
2 3 4
2147483647 0 2147483646
0 -2147483648 -2147483647
输出样例:
Case #1: false
Case #2: true
Case #3: true
Case #4: false
*/
int main() {
int num, i;
i = 1;
cin>>num;
vector<string> arr;
int64_t x, y, z;
char c;
while(cin>>x>>y>>z) {
stringstream ss;
if(x+y>z) {
ss<<"Case #"<<i++<<": true";
cout<<ss.str()<<endl;
}else {
ss<<"Case #"<<i++<<": false";
cout<<ss.str()<<endl;
}
}
}
|
SvenTUM/mrmap
|
mrmap/api/urls.py
|
<reponame>SvenTUM/mrmap<filename>mrmap/api/urls.py
"""
Author: <NAME>
Organization: Spatial data infrastructure Rhineland-Palatinate, Germany
Contact: <EMAIL>
Created on: 15.08.19
"""
from django.urls import path, include
# Routers provide an easy way of automatically determining the URL conf.
from rest_framework import routers
from api.views import *
router = routers.DefaultRouter()
# catalogue api
router.register('catalogue', CatalogueViewSet, basename="catalogue")
router.register('suggestion', SuggestionViewSet, basename="suggestion")
router.register('category', CategoryViewSet, basename="category")
# modular parts of api
router.register('organization', OrganizationViewSet, basename="organization")
router.register('metadata', MetadataViewSet, basename="metadata")
router.register('service', ServiceViewSet, basename="service")
router.register('layer', LayerViewSet, basename="layer")
router.register('group', GroupViewSet, basename="group")
router.register('monitoring', MonitoringViewSet, basename="monitoring")
router.register('pending-tasks', PendingTasksViewSet, basename="pending-tasks")
app_name = "api"
urlpatterns = [
path("", include(router.urls)),
path("menu", menu_view, name="menu"),
path("generate-token", generate_token, name="generate-token"),
]
|
LesleyLai/biggroum
|
python/fixrgraph/solr/import_patterns.py
|
import sys
import os
import optparse
import logging
import string
import collections
import re
import pysolr
from fixrgraph.annotator.protobuf import proto_acdfg_pb2
from fixrgraph.solr.common import MissingProtobufField
from fixrgraph.solr.common import upload_pool
from fixrgraph.solr.import_graphs import get_id as get_groum_key
from fixrgraph.solr.import_graphs import check_field, get_repo_sni
from fixrgraph.solr.patterns_utils import PatternInfo, parse_cluster_info
def _get_pattern_key(cluster_id, pattern_id, pattern_type):
key = "%s/%s/%s" % (cluster_id, pattern_type, pattern_id)
return key
def _get_cluster_key(cluster_id):
key = "%s" % (cluster_id)
return key
def _get_groum_key_from_bin(acdfg_path):
logging.debug("Importing groum %s" % acdfg_path)
with open(acdfg_path, "rb") as acdfg_file:
acdfg = proto_acdfg_pb2.Acdfg()
acdfg.ParseFromString(acdfg_file.read())
check_field(acdfg.repo_tag, "repo_name")
check_field(acdfg.repo_tag, "user_name")
check_field(acdfg.repo_tag, "commit_hash")
repo_name = acdfg.repo_tag.repo_name
user_name = acdfg.repo_tag.user_name
class_name = acdfg.source_info.class_name
method_name = acdfg.source_info.method_name
hash_sni = acdfg.repo_tag.commit_hash
repo_sni = get_repo_sni(user_name, repo_name)
groum_key = get_groum_key(repo_sni, hash_sni, class_name, method_name)
acdfg_file.close()
return groum_key
def _create_pattern_docs(current_path, cluster_info_path):
pattern_doc_list = []
cluster_id_re= re.match(r".*cluster_(\d+)$",current_path)
if cluster_id_re is not None:
cluster_id = cluster_id_re.group(1)
else:
logging.warn("Cannot find cluster id from %s" % current_path)
cluster_id = -1
# Read the pattern info
with open(cluster_info_path, 'r') as f:
pattern_info_list = parse_cluster_info(f)
f.close()
for pattern_info in pattern_info_list:
pattern_doc = {}
pattern_doc["doc_type_sni"] = "pattern"
pattern_doc["id"] = _get_pattern_key(cluster_id,
pattern_info.id,
pattern_info.type)
pattern_doc["cluster_key_sni"] = _get_cluster_key(cluster_id)
pattern_doc["type_sni"] = pattern_info.type
pattern_doc["frequency_sni"] = pattern_info.frequency
groum_keys_list = []
for groum in pattern_info.groum_files_list:
if (groum.startswith("isol_") or
groum.startswith("pop_") or
groum.startswith("anom_")):
logging.debug("Skipping pattern groum %s..." % groum)
continue
acdfg_path = os.path.join(current_path, groum)
groum_key = _get_groum_key_from_bin(acdfg_path)
groum_keys_list.append(groum_key)
pattern_doc["groum_keys_t"] = groum_keys_list
assert pattern_info.dot_name is not None
dot_path = os.path.join(current_path, pattern_info.dot_name)
with open(dot_path, 'r') as dot_file:
pattern_doc["groum_dot_sni"] = dot_file.read()
pattern_doc_list.append(pattern_doc)
return pattern_doc_list
def main():
logging.basicConfig(level=logging.DEBUG)
p = optparse.OptionParser()
p.add_option('-c', '--cluster_dir', help="Base path containing the clusters")
p.add_option('-s', '--solr_url', help="URL to solr")
def usage(msg=""):
if msg:
print "----%s----\n" % msg
p.print_help()
print "Example of usage %s" % ("python import_graphs.py "
"-c /tmp/testextraction/clusters "
"-s 'http://localhost:8983/solr/groums'")
sys.exit(1)
opts, args = p.parse_args()
if (not opts.solr_url): usage("Solr URL not provided!")
paths = [(opts.cluster_dir, "Cluster dir")]
for (path,msg) in paths:
if (not path): usage("%s not provided!" % msg)
if (not os.path.isdir(path)): usage("%s %s does "
"not exist!" % (msg,path))
solr = pysolr.Solr(opts.solr_url)
doc_pool = []
threshold = 10000
name_pattern = re.compile("cluster_(\d+)_info.txt")
for root, dirs, files in os.walk(opts.cluster_dir):
for name in files:
res_match = name_pattern.match(name)
if res_match is not None:
pattern_id = res_match.group(1)
cluster_info_path = os.path.join(root, name)
try:
current_path = os.path.dirname(cluster_info_path)
pattern_docs = _create_pattern_docs(current_path,
cluster_info_path)
doc_pool.extend(pattern_docs)
except MissingProtobufField as e:
logging.warn("Missing field for %s (%s)" % (name, relpath))
except IOError as e:
logging.warn("Error reading file %s" % (e.filename))
doc_pool = upload_pool(solr, threshold, doc_pool)
doc_pool = upload_pool(solr, -1, doc_pool)
if __name__ == '__main__':
main()
|
hpehl/hal.next
|
app/src/main/java/org/jboss/hal/client/configuration/subsystem/jca/AddressTemplates.java
|
<reponame>hpehl/hal.next
/*
* Copyright 2022 Red Hat
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.hal.client.configuration.subsystem.jca;
import org.jboss.hal.meta.AddressTemplate;
interface AddressTemplates {
String JCA_ADDRESS = "/{selected.profile}/subsystem=jca";
String ARCHIVE_VALIDATION_ADDRESS = JCA_ADDRESS + "/archive-validation=archive-validation";
String BEAN_VALIDATION_ADDRESS = JCA_ADDRESS + "/bean-validation=bean-validation";
String BOOTSTRAP_CONTEXT_ADDRESS = JCA_ADDRESS + "/bootstrap-context=*";
String CCM_ADDRESS = JCA_ADDRESS + "/cached-connection-manager=cached-connection-manager";
String DISTRIBUTED_WORKMANAGER_ADDRESS = JCA_ADDRESS + "/distributed-workmanager=*";
String DISTRIBUTED_WORKMANAGER_LRT_ADDRESS = DISTRIBUTED_WORKMANAGER_ADDRESS + "/long-running-threads=*";
String DISTRIBUTED_WORKMANAGER_SRT_ADDRESS = DISTRIBUTED_WORKMANAGER_ADDRESS + "/short-running-threads=*";
String TRACER_ADDRESS = JCA_ADDRESS + "/tracer=tracer";
String WORKMANAGER_ADDRESS = JCA_ADDRESS + "/workmanager=*";
String WORKMANAGER_LRT_ADDRESS = WORKMANAGER_ADDRESS + "/long-running-threads=*";
String WORKMANAGER_SRT_ADDRESS = WORKMANAGER_ADDRESS + "/short-running-threads=*";
AddressTemplate JCA_TEMPLATE = AddressTemplate.of(JCA_ADDRESS);
AddressTemplate ARCHIVE_VALIDATION_TEMPLATE = AddressTemplate.of(ARCHIVE_VALIDATION_ADDRESS);
AddressTemplate BEAN_VALIDATION_TEMPLATE = AddressTemplate.of(BEAN_VALIDATION_ADDRESS);
AddressTemplate BOOTSTRAP_CONTEXT_TEMPLATE = AddressTemplate.of(BOOTSTRAP_CONTEXT_ADDRESS);
AddressTemplate CCM_TEMPLATE = AddressTemplate.of(CCM_ADDRESS);
AddressTemplate DISTRIBUTED_WORKMANAGER_TEMPLATE = AddressTemplate.of(DISTRIBUTED_WORKMANAGER_ADDRESS);
AddressTemplate DISTRIBUTED_WORKMANAGER_LRT_TEMPLATE = AddressTemplate.of(DISTRIBUTED_WORKMANAGER_LRT_ADDRESS);
AddressTemplate DISTRIBUTED_WORKMANAGER_SRT_TEMPLATE = AddressTemplate.of(DISTRIBUTED_WORKMANAGER_SRT_ADDRESS);
AddressTemplate TRACER_TEMPLATE = AddressTemplate.of(TRACER_ADDRESS);
AddressTemplate WORKMANAGER_TEMPLATE = AddressTemplate.of(WORKMANAGER_ADDRESS);
AddressTemplate WORKMANAGER_LRT_TEMPLATE = AddressTemplate.of(WORKMANAGER_LRT_ADDRESS);
AddressTemplate WORKMANAGER_SRT_TEMPLATE = AddressTemplate.of(WORKMANAGER_SRT_ADDRESS);
}
|
ChefWu551/spring-framework
|
05spring-tx/src/main/java/com/mountain/MainJdbcTemplate.java
|
<reponame>ChefWu551/spring-framework
package com.mountain;
import com.mountain.model.BookNum;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.List;
public class MainJdbcTemplate {
public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("config.xml");
JdbcTemplate template = applicationContext.getBean(JdbcTemplate.class);
System.out.println(template);
/* String sqlUpdate = "update bookNum set num=? where id=?";
int resultUpdate = template.update(sqlUpdate, 100, 1);
System.out.println("更新了: " + resultUpdate);*/
/* String sqlInsert = "insert into bookNum (id, num) values(?, ?)";
List<Object[]> batchArgs = new ArrayList<Object[]>() {{
add(new Object[]{7, 10}); add(new Object[]{8, 10});
}};
int[] resultInsert = template.batchUpdate(sqlInsert, batchArgs);
template.execute("DELETE from bookNum where id in (7, 8)");
System.out.println(resultInsert.toString());*/
/*BookNum book = template.queryForObject("select id, num from bookNum where id = ?", new BeanPropertyRowMapper<>(BookNum.class), 5);
System.out.println(book.toString());
List<BookNum> bookNums = template.query("select id, num from bookNum where num = ?", new BeanPropertyRowMapper<>(BookNum.class), 10);
bookNums.forEach(item -> System.out.println(item.toString()));*/
}
}
|
zbelateche/ee272_cgra
|
simple_cb/simple_cb_magma.py
|
<filename>simple_cb/simple_cb_magma.py<gh_stars>1-10
import magma
from common.mux_wrapper import MuxWrapper
from common.zext_wrapper import ZextWrapper
from generator.configurable import Configurable, ConfigurationType
class CB(Configurable):
def __init__(self, num_tracks, width):
super().__init__()
if num_tracks <= 1:
raise ValueError("num_tracks must be > 1")
self.num_tracks = num_tracks
self.width = width
sel_bits = magma.bitutils.clog2(self.num_tracks)
self.mux = MuxWrapper(self.num_tracks, self.width)
T = magma.Bits(self.width)
self.add_ports(
I=magma.In(magma.Array(self.num_tracks, T)),
O=magma.Out(T),
clk=magma.In(magma.Clock),
reset=magma.In(magma.AsyncReset),
config=magma.In(ConfigurationType(8, 32)),
read_config_data=magma.Out(magma.Bits(32)),
)
self.add_configs(S=sel_bits)
# read_config_data output
num_config_reg = len(self.registers)
if(num_config_reg > 1):
self.read_config_data_mux = MuxWrapper(num_config_reg, 32)
self.wire(self.ports.config.config_addr,
self.read_config_data_mux.ports.S)
self.wire(self.read_config_data_mux.ports.O,
self.ports.read_config_data)
for idx, reg in enumerate(self.registers.values()):
self.wire(reg.ports.O, self.read_config_data_mux.ports.I[idx])
# Wire up config register resets
self.wire(reg.ports.reset, self.ports.reset)
# If we only have 1 config register, we don't need a mux
# Wire sole config register directly to read_config_data_output
else:
reg = list(self.registers.values())[0]
zext = ZextWrapper(reg.width, 32)
self.wire(reg.ports.O, zext.ports.I)
zext_out = zext.ports.O
self.wire(zext_out, self.ports.read_config_data)
self.wire(self.ports.I, self.mux.ports.I)
self.wire(self.registers.S.ports.O, self.mux.ports.S)
self.wire(self.mux.ports.O, self.ports.O)
for idx, reg in enumerate(self.registers.values()):
reg.set_addr(idx)
reg.set_addr_width(8)
reg.set_data_width(32)
self.wire(self.ports.config.config_addr, reg.ports.config_addr)
self.wire(self.ports.config.config_data, reg.ports.config_data)
# Connect config_en for each config reg
self.wire(reg.ports.config_en, self.ports.config.write[0])
def name(self):
return f"CB_{self.num_tracks}_{self.width}"
|
Joao-Maria-Janeiro/SaoPerolasDjango
|
cart/views.py
|
<filename>cart/views.py
from django.shortcuts import render, redirect
from .models import Cart, Cart_userless, CartProduct, ShippingDetails, Order, OrderUserless
from .forms import CreateShipphingDetails
from django.contrib.auth.decorators import login_required
from products.models import Product
from django.http import HttpResponse
import datetime
import stripe
from django.conf import settings
import uuid
from django.contrib.auth.models import User
from django.contrib.auth import login
import smtplib
import cart.config_email as config
stripe.api_key = settings.STRIPE_SECRET_KEY
def send_mail(products, shipping_details, receiver_email, total_price):
print(receiver_email)
try:
server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo()
server.starttls()
server.login(config.EMAIL, config.PASSWORD)
msg = "Produtos: \n"
for productz in products:
msg += "Nome: " + productz.product.name + " | Quantidade: " + str(productz.quantity) + "\n"
msg += "Preço total: " + str(total_price) + "\n"
msg += "Detalhes de shipping: \n"
msg += "Nome Completo: " + shipping_details.full_name + "\nMorada: " + shipping_details.adress + "\nCidade: " + shipping_details.city + "\nLocalidade: " + shipping_details.localidade + "\nZip: " + shipping_details.zip + "\nPaís: "+ shipping_details.country + "\nNúmero de Telemóvel: " + shipping_details.phone_number
message = "Subject: {}\n\n{}".format("Nova Compra", msg).encode('utf-8').strip()
server.sendmail(config.EMAIL, config.RECIEVER_EMAIL, message)
server.quit()
print("Sucess: Email Sent!")
except Exception as e:
print("E-mail not sent!")
print(e)
def stripeInfos(request, shipping_details, cart):
token = request.POST['stripeToken']
charge = stripe.Charge.create(
amount=100*cart.total_price,
currency='eur',
description='Products',
source=token,
receipt_email=shipping_details.email,
)
def clear_cart(cart):
cart.products.clear()
cart.total_price = 0
cart.save()
def checkNew(cart, id):
found = 0
for productz in cart.products.all():
if productz.product.name == Product.objects.get(id=id).name:
product = productz
found = 1
cart.products.remove(product)
product.quantity += 1
product.save()
cart.products.add(product)
return found
def calc_price(cart):
if(len(cart.products.all()) == 0):
cart.total_price = 0
return
for productz in cart.products.all():
price = int(productz.product.price) * (productz.quantity)
cart.total_price += price
cart.total_price += 3
# Create your views here.
def add_to_cart(request, id):
if request.user.is_authenticated:
found = 0
user = request.user
cart = user.cart
found = checkNew(cart, id)
if found == 0:
product = CartProduct(product=Product.objects.get(id=id))
product.save()
cart.products.add(product)
cart.total_price = 0
calc_price(cart)
cart.save()
else:
name = str(uuid.uuid4())
email = name + "@gmail.com"
user = User.objects.create_user(name, email, 'johnpassword')
user.save()
user.userprofile.anonymous_user = True
user.userprofile.save()
# user.save()
login(request, user)
found = 0
cart = user.cart
found = checkNew(cart, id)
if found == 0:
product = CartProduct(product=Product.objects.get(id=id))
product.save()
cart.products.add(product)
cart.total_price = 0
calc_price(cart)
cart.save()
return redirect('display_cart')
def remove_from_cart(request, id):
if request.user.is_authenticated:
user = request.user
cart = user.cart
product = CartProduct.objects.get(id=id)
cart.products.remove(product)
cart.total_price = 0
calc_price(cart)
cart.save()
else:
return HttpResponse('Cart is empty')
return redirect('display_cart')
@login_required
def shipping_details(request):
if request.method == 'POST':
if request.POST['full_name'] == '':
request.user.userprofile.use_saved_details = True
request.user.userprofile.save()
return redirect('order_details')
else:
form = CreateShipphingDetails(request.POST)
if form.is_valid():
form.email = request.POST['email']
details = form.save()
request.user.userprofile.use_saved_details = False
request.user.userprofile.shipping_details_id = details.id
request.user.userprofile.save()
return redirect('order_details')
else:
form = CreateShipphingDetails()
return render(request, 'cart/shippingDetails.html', {'form': form})
@login_required
def order_details(request):
if request.method == 'POST':
if request.user.is_authenticated:
if request.user.cart.total_price != 0 :
cart = request.user.cart
total_price = cart.total_price
if request.user.userprofile.use_saved_details == True:
shipping_details = ShippingDetails(full_name = request.user.username + ' ' + request.user.userprofile.last_name, adress = request.user.userprofile.address, city = request.user.userprofile.city, localidade = request.user.userprofile.localidade, zip = request.user.userprofile.zip_code, country = request.user.userprofile.country, phone_number = request.user.userprofile.cell_number, email = request.user.userprofile.email)
shipping_details.save()
else:
shipping_details = ShippingDetails.objects.get(id=request.user.userprofile.shipping_details_id)
date_ordered = datetime.datetime.now()
order = Order(cart=cart, total_price=total_price, shipping_details=shipping_details, date_ordered=date_ordered)
order.save()
publishKey = settings.STRIPE_PUBLISHABLE_KEY
if request.method == 'POST':
try:
stripeInfos(request, shipping_details, cart)
send_mail(cart.products.all(), shipping_details, shipping_details.email, cart.total_price)
clear_cart(cart)
return render(request, 'cart/SuccessFulOrder.html')
except stripe.error.CardError as e:
return render(request, 'cart/cardError.html')
context = {
'order': order,
'STRIPE_PUBLISHABLE_KEY': publishKey
}
else:
return HttpResponse('Empty cart or shipping information missing')
else:
return HttpResponse('Empty cart or shipping information missing')
return render(request, 'cart/OrderDetails.html', {'order':order, 'context':context})
else:
if request.user.is_authenticated:
if request.user.cart.total_price != 0:
cart = request.user.cart
return render(request, 'cart/OrderDetails.html', {'cart': cart})
else:
return HttpResponse('Empty cart or shipping information missing')
@login_required
def increase_quantity(request, id):
if request.method == 'POST':
quantity = int(request.POST['quantity'])
if request.user.is_authenticated:
user = request.user
cart = user.cart
else:
return HttpResponse('Cart is empty')
product = CartProduct.objects.get(id=id)
if product.quantity + quantity >= 0:
if(product.quantity + quantity == 0):
cart.products.remove(product);
else:
product.quantity += quantity
product.save()
cart.total_price = 0
calc_price(cart)
cart.save()
return redirect('display_cart')
def display_cart(request):
if request.user.is_authenticated:
user = request.user
cart = user.cart
else:
return HttpResponse('Cart is empty')
return render(request, 'cart/display_cart.html', {'cart': cart})
|
HATTER-LONG/TDD_Learning
|
test/Catch2/GeoServerTest/GeoServerTest.cpp
|
#include "GeoServer/GeoServer.h"
#include "GeoServer/Location.h"
#include "GeoServer/User.h"
#include "GeoServer/VectorUtil.h"
#include "TestTimer.h"
#include <catch2/catch.hpp>
using namespace std;
using namespace Catch;
class Fixture
{
public:
GeoServer m_server;
const string m_aUser { "auser" };
const double m_locationToLerance { 0.005 };
};
TEST_CASE_METHOD(Fixture, "Tracks m_aUser", "[AGeoServer]")
{
m_server.track(m_aUser);
REQUIRE(m_server.isTracking(m_aUser));
}
TEST_CASE_METHOD(Fixture, "Is not tracking m_aUser not tracked", "[AGeoServer]")
{
REQUIRE_FALSE(m_server.isTracking(m_aUser));
}
TEST_CASE_METHOD(Fixture, "Tracks multiple users", "[AGeoServer]")
{
m_server.track(m_aUser);
m_server.track("anotheruser");
REQUIRE_FALSE(m_server.isTracking("thirduser"));
REQUIRE(m_server.isTracking(m_aUser));
REQUIRE(m_server.isTracking("anotheruser"));
}
TEST_CASE_METHOD(Fixture, "Is tracking answers false when user no longer tracked", "[AGeoServer]")
{
m_server.track(m_aUser);
m_server.stopTracking(m_aUser);
REQUIRE_FALSE(m_server.isTracking(m_aUser));
}
TEST_CASE_METHOD(Fixture, "Updates location of user", "[AGeoServer]")
{
m_server.track(m_aUser);
m_server.updateLocation(m_aUser, Location { 38, -104 });
auto location = m_server.locationOf(m_aUser);
REQUIRE(location.latitude() == 38);
REQUIRE(location.longitude() == -104);
}
TEST_CASE_METHOD(Fixture, "Answers unknown location for user not tracked", "[AGeoServer]")
{
REQUIRE(m_server.locationOf("anAbUser").isUnknown());
}
TEST_CASE_METHOD(Fixture, "Answers unknown location for tracked user with no location update", "[AGeoServer]")
{
m_server.track(m_aUser);
REQUIRE(m_server.locationOf(m_aUser).isUnknown());
}
TEST_CASE_METHOD(Fixture, "Answers unknown location for user no longer tracked", "[AGeoServer]")
{
m_server.track(m_aUser);
m_server.updateLocation(m_aUser, Location(40, 100));
m_server.stopTracking(m_aUser);
REQUIRE(m_server.locationOf(m_aUser).isUnknown());
}
class FixtureUserInBox
{
public:
GeoServer server;
const double TenMeters { 10 };
const double Width { 2000 + TenMeters };
const double Height { 4000 + TenMeters };
const string aUser { "auser" };
const string bUser { "buser" };
const string cUser { "cuser" };
Location aUserLocation { 38, -103 };
FixtureUserInBox()
{
server.track(aUser);
server.track(bUser);
server.track(cUser);
server.updateLocation(aUser, aUserLocation);
}
vector<string> UserNames(const vector<User>& users)
{
return Collect<User, string>(users, [](User each) { return each.name(); });
};
};
TEST_CASE_METHOD(FixtureUserInBox, "Answers users in specified range", "[AGeoServer_UsersInBox]")
{
server.updateLocation(bUser, Location { aUserLocation.go(Width / 2 - TenMeters, East) });
auto users = server.usersInBox(aUser, Width, Height);
REQUIRE_THAT(vector<string> { bUser }, Equals(UserNames(users)));
}
TEST_CASE_METHOD(FixtureUserInBox, "Answers only users within specified range", "[AGeoServer_UsersInBox]")
{
server.updateLocation(bUser, Location { aUserLocation.go(Width / 2 + TenMeters, East) });
server.updateLocation(cUser, Location { aUserLocation.go(Width / 2 - TenMeters, East) });
auto users = server.usersInBox(aUser, Width, Height);
REQUIRE_THAT(vector<string> { cUser }, Equals(UserNames(users)));
}
TEST_CASE_METHOD(FixtureUserInBox, "Handles large numbers of users",
"[.][Slow][AGeoServer_UsersInBox_Slow][AGeoServer_UsersInBox]")
{
Location anotherLocation { aUserLocation.go(10, West) };
const unsigned int lots { 500000 };
for (unsigned int i { 0 }; i < lots; i++)
{
string user { "user" + to_string(i) };
server.track(user);
server.updateLocation(user, anotherLocation);
}
ToolBox::TestTimer testtimer;
auto users = server.usersInBox(aUser, Width, Height);
REQUIRE(lots == users.size());
}
|
Arronlong/nutz-book-project
|
nutzcn-core/src/main/java/net/wendal/nutzbook/core/bean/datatable/DataTableOrder.java
|
package net.wendal.nutzbook.core.bean.datatable;
/**
* Created by wendal on 2015/12/20.
*/
public class DataTableOrder {
protected int column;
protected String dir;
public int getColumn() {
return column;
}
public void setColumn(int column) {
this.column = column;
}
public String getDir() {
return dir;
}
public void setDir(String dir) {
this.dir = dir;
}
}
|
synapticarbors/wagyu
|
tests/binding_tests/intersect_node_tests/test_repr.py
|
import sys
from _wagyu import IntersectNode
from hypothesis import given
from . import strategies
@given(strategies.intersect_nodes)
def test_basic(intersect_node: IntersectNode) -> None:
result = repr(intersect_node)
assert result.startswith(IntersectNode.__module__)
assert IntersectNode.__qualname__ in result
@given(strategies.intersect_nodes)
def test_round_trip(intersect_node: IntersectNode) -> None:
result = repr(intersect_node)
assert eval(result, sys.modules) == intersect_node
|
JayElango/hyscale
|
deployer/deployer-services/src/main/java/io/hyscale/deployer/services/processor/PodParentProvider.java
|
/**
* Copyright 2019 <NAME>, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.hyscale.deployer.services.processor;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Component;
import io.hyscale.commons.exception.HyscaleException;
import io.hyscale.commons.utils.ResourceSelectorUtil;
import io.hyscale.deployer.services.factory.PodParentFactory;
import io.hyscale.deployer.services.handler.PodParentHandler;
import io.hyscale.deployer.services.model.PodParent;
import io.kubernetes.client.openapi.ApiClient;
@Component
public class PodParentProvider {
/**
*
* @param apiClient
* @param appName
* @param serviceName
* @param namespace
* @return {@link PodParent} for the app and service in the given namespace
* @throws HyscaleException
*/
public PodParent getPodParent(ApiClient apiClient, String appName, String serviceName, String namespace)
throws HyscaleException {
List<PodParentHandler> podParentHandlerList = PodParentFactory.getAllHandlers();
String selector = ResourceSelectorUtil.getServiceSelector(appName, serviceName);
for (PodParentHandler podParentHandler : podParentHandlerList) {
List podParentResource = podParentHandler.getBySelector(apiClient, selector, true, namespace);
if (podParentResource != null && !podParentResource.isEmpty()) {
return new PodParent(podParentHandler.getKind(), podParentResource.get(0));
}
}
return null;
}
/**
* Provides a list of {@link PodParent} for the app in given namespace
*
* @param apiClient
* @param appName
* @param namespace
* @return list of {@link PodParent}
* @throws HyscaleException
*/
public List<PodParent> getPodParents(ApiClient apiClient, String appName, String namespace)
throws HyscaleException {
List<PodParent> podParentList = new ArrayList<PodParent>();
List<PodParentHandler> podParentHandlerList = PodParentFactory.getAllHandlers();
String selector = ResourceSelectorUtil.getSelector(appName);
for (PodParentHandler podParentHandler : podParentHandlerList) {
List podParentResource = podParentHandler.getBySelector(apiClient, selector, true, namespace);
if (podParentResource != null) {
podParentResource.stream().forEach(each -> {
PodParent podParent = new PodParent(podParentHandler.getKind(), each);
podParentList.add(podParent);
});
}
}
return podParentList;
}
/**
*
* @param apiClient
* @param appName
* @param serviceName
* @param namespace
* @return true if {@link PodParent} exists for the app and service
* @throws HyscaleException
*/
public boolean hasPodParent(ApiClient apiClient, String appName, String serviceName, String namespace)
throws HyscaleException {
return getPodParent(apiClient, appName, serviceName, namespace) != null ? true : false;
}
/**
* Provides list of all {@link PodParent} available in the cluster
*
* @param apiClient
* @return list of {@link PodParent}
* @throws HyscaleException
*/
public List<PodParent> getAllPodParents(ApiClient apiClient) throws HyscaleException {
List<PodParent> podParentList = new ArrayList<PodParent>();
List<PodParentHandler> podParentHandlerList = PodParentFactory.getAllHandlers();
for (PodParentHandler podParentHandler : podParentHandlerList) {
List podParentResource = podParentHandler.listForAllNamespaces(apiClient, null, true);
if (podParentResource != null) {
podParentResource.stream().forEach(each -> {
PodParent podParent = new PodParent(podParentHandler.getKind(), each);
podParentList.add(podParent);
});
}
}
return podParentList;
}
}
|
ooici/coi-services
|
ion/services/sa/test/test_instrument_alerts.py
|
#!/usr/bin/env python
"""
@package ion.services.sa.test
@file ion/services/sa/test/test_alerts.py
@author <NAME>
@brief Test alerts
"""
from ion.services.sa.test.helpers import AgentProcessStateGate
from pyon.public import log, IonObject
from pyon.util.int_test import IonIntegrationTestCase
from pyon.public import CFG, RT, PRED
from pyon.agent.agent import ResourceAgentEvent
from pyon.agent.agent import ResourceAgentClient
from pyon.util.context import LocalContextMixin
from pyon.event.event import EventSubscriber
import time
from interface.objects import StreamAlertType, AggregateStatusType
from interface.services.sa.iinstrument_management_service import InstrumentManagementServiceClient
from interface.services.sa.idata_acquisition_management_service import DataAcquisitionManagementServiceClient
from interface.services.coi.iresource_registry_service import ResourceRegistryServiceClient
from interface.services.sa.idata_product_management_service import DataProductManagementServiceClient
from interface.services.dm.idataset_management_service import DatasetManagementServiceClient
from interface.services.dm.ipubsub_management_service import PubsubManagementServiceClient
from interface.services.cei.iprocess_dispatcher_service import ProcessDispatcherServiceClient
from interface.objects import ProcessStateEnum, StreamConfiguration, AgentCommand, ProcessDefinition, ComputedStringValue, DataProduct
from ion.services.cei.process_dispatcher_service import ProcessStateGate
from ion.agents.port.port_agent_process import PortAgentProcessType, PortAgentType
from ion.services.dm.utility.granule_utils import time_series_domain
# This import will dynamically load the driver egg. It is needed for the MI includes below
from ion.agents.instrument.test.load_test_driver_egg import load_egg
DRV_URI_GOOD = load_egg()['dvr_egg']
from mi.instrument.seabird.sbe37smb.ooicore.driver import SBE37ProtocolEvent
#from mi.instrument.seabird.sbe37smb.ooicore.driver import SBE37Parameter
from mock import patch
import gevent
from gevent import queue
from nose.plugins.attrib import attr
"""
# Used to validate param config retrieved from driver.
PARAMS = {
SBE37Parameter.OUTPUTSAL : bool,
SBE37Parameter.OUTPUTSV : bool,
SBE37Parameter.NAVG : int,
SBE37Parameter.SAMPLENUM : int,
SBE37Parameter.INTERVAL : int,
SBE37Parameter.STORETIME : bool,
SBE37Parameter.TXREALTIME : bool,
SBE37Parameter.SYNCMODE : bool,
SBE37Parameter.SYNCWAIT : int,
SBE37Parameter.TCALDATE : tuple,
SBE37Parameter.TA0 : float,
SBE37Parameter.TA1 : float,
SBE37Parameter.TA2 : float,
SBE37Parameter.TA3 : float,
SBE37Parameter.CCALDATE : tuple,
SBE37Parameter.CG : float,
SBE37Parameter.CH : float,
SBE37Parameter.CI : float,
SBE37Parameter.CJ : float,
SBE37Parameter.WBOTC : float,
SBE37Parameter.CTCOR : float,
SBE37Parameter.CPCOR : float,
SBE37Parameter.PCALDATE : tuple,
SBE37Parameter.PA0 : float,
SBE37Parameter.PA1 : float,
SBE37Parameter.PA2 : float,
SBE37Parameter.PTCA0 : float,
SBE37Parameter.PTCA1 : float,
SBE37Parameter.PTCA2 : float,
SBE37Parameter.PTCB0 : float,
SBE37Parameter.PTCB1 : float,
SBE37Parameter.PTCB2 : float,
SBE37Parameter.POFFSET : float,
SBE37Parameter.RCALDATE : tuple,
SBE37Parameter.RTCA0 : float,
SBE37Parameter.RTCA1 : float,
SBE37Parameter.RTCA2 : float
}
"""
class FakeProcess(LocalContextMixin):
"""
A fake process used because the test case is not an ion process.
"""
name = ''
id=''
process_type = ''
@attr('HARDWARE', group='sa')
@patch.dict(CFG, {'endpoint':{'receive':{'timeout': 180}}})
class TestInstrumentAlerts(IonIntegrationTestCase):
pdict_id = None
def setUp(self):
self._start_container()
self.container.start_rel_from_url('res/deploy/r2deploy.yml')
# Now create client to DataProductManagementService
self.imsclient = InstrumentManagementServiceClient(node=self.container.node)
self.damsclient = DataAcquisitionManagementServiceClient(node=self.container.node)
self.rrclient = ResourceRegistryServiceClient(node=self.container.node)
self.dataproductclient = DataProductManagementServiceClient(node=self.container.node)
self.dataset_management = DatasetManagementServiceClient(node=self.container.node)
self.pubsubclient = PubsubManagementServiceClient(node=self.container.node)
self.processdispatchclient = ProcessDispatcherServiceClient(node=self.container.node)
self.catch_alert= gevent.queue.Queue()
def _create_instrument_model(self):
instModel_obj = IonObject( RT.InstrumentModel,
name='SBE37IMModel',
description="SBE37IMModel" )
instModel_id = self.imsclient.create_instrument_model(instModel_obj)
self.addCleanup(self.imsclient.delete_instrument_model, instModel_id)
return instModel_id
def _create_instrument_agent(self, instModel_id):
raw_config = StreamConfiguration(stream_name='raw', parameter_dictionary_name='ctd_raw_param_dict')
parsed_config = StreamConfiguration(stream_name='parsed', parameter_dictionary_name='ctd_parsed_param_dict')
instAgent_obj = IonObject(RT.InstrumentAgent,
name='agent007',
description="SBE37IMAgent",
driver_uri=DRV_URI_GOOD,
stream_configurations = [raw_config, parsed_config] )
instAgent_id = self.imsclient.create_instrument_agent(instAgent_obj)
self.addCleanup(self.imsclient.delete_instrument_agent, instAgent_id)
self.imsclient.assign_instrument_model_to_instrument_agent(instModel_id, instAgent_id)
return instAgent_id
def _create_instrument_device(self, instModel_id):
instDevice_obj = IonObject(RT.InstrumentDevice, name='SBE37IMDevice', description="SBE37IMDevice", serial_number="12345" )
instDevice_id = self.imsclient.create_instrument_device(instrument_device=instDevice_obj)
self.imsclient.assign_instrument_model_to_instrument_device(instModel_id, instDevice_id)
self.addCleanup(self.imsclient.delete_instrument_device, instDevice_id)
log.debug("test_activateInstrumentSample: new InstrumentDevice id = %s (SA Req: L4-CI-SA-RQ-241) ", instDevice_id)
return instDevice_id
def _create_instrument_stream_alarms(self, instDevice_id):
#Create stream alarms
"""
test_two_sided_interval
Test interval alarm and alarm event publishing for a closed
inteval.
"""
temp_alert_def1 = {
'name' : 'temperature_warning_interval temp below 25',
'stream_name' : 'parsed',
'description' : 'temperature_warning_interval temp below 25',
'alert_type' : StreamAlertType.WARNING,
'aggregate_type' : AggregateStatusType.AGGREGATE_DATA,
'value_id' : 'temp',
'resource_id' : instDevice_id,
'origin_type' : 'device',
#'lower_bound' : 0,
#'lower_rel_op' : '<',
# temp
'upper_rel_op' : '<=',
'upper_bound' : 25,
'alert_class' : 'IntervalAlert'
}
temp_alert_def2 = {
'name' : 'temperature_warning_interval temp below 50',
'stream_name' : 'parsed',
'description' : 'temperature_warning_interval temp below 50',
'alert_type' : StreamAlertType.WARNING,
'aggregate_type' : AggregateStatusType.AGGREGATE_DATA,
'value_id' : 'temp',
'resource_id' : instDevice_id,
'origin_type' : 'device',
#'lower_bound' : 25,
#'lower_rel_op' : '<',
# temp
'upper_rel_op' : '<=',
'upper_bound' : 50,
'alert_class' : 'IntervalAlert'
}
temp_alert_def3 = {
'name' : 'temperature_warning_interval temp below 75',
'stream_name' : 'parsed',
'description' : 'temperature_warning_interval temp below 75',
'alert_type' : StreamAlertType.WARNING,
'aggregate_type' : AggregateStatusType.AGGREGATE_DATA,
'value_id' : 'temp',
'resource_id' : instDevice_id,
'origin_type' : 'device',
#'lower_bound' : 50,
#'lower_rel_op' : '<',
# temp
'upper_rel_op' : '<=',
'upper_bound' : 75,
'alert_class' : 'IntervalAlert'
}
late_data_alert_def = {
'name' : 'late_data_warning',
'stream_name' : 'parsed',
'description' : 'Expected data has not arrived.',
'alert_type' : StreamAlertType.WARNING,
'aggregate_type' : AggregateStatusType.AGGREGATE_COMMS,
'value_id' : None,
'resource_id' : instDevice_id,
'origin_type' : 'device',
'time_delta' : 2,
'alert_class' : 'LateDataAlert'
}
return [temp_alert_def1, temp_alert_def2, temp_alert_def3, late_data_alert_def]
def _create_instrument_agent_instance(self, instAgent_id, instDevice_id):
port_agent_config = {
'device_addr': CFG.device.sbe37.host,
'device_port': CFG.device.sbe37.port,
'process_type': PortAgentProcessType.UNIX,
'binary_path': "port_agent",
'port_agent_addr': 'localhost',
'command_port': CFG.device.sbe37.port_agent_cmd_port,
'data_port': CFG.device.sbe37.port_agent_data_port,
'log_level': 5,
'type': PortAgentType.ETHERNET
}
self.all_alerts = self._create_instrument_stream_alarms(instDevice_id)
instAgentInstance_obj = IonObject(RT.InstrumentAgentInstance, name='SBE37IMAgentInstance',
description="SBE37IMAgentInstance",
port_agent_config = port_agent_config,
alerts= self.all_alerts
)
instAgentInstance_id = self.imsclient.create_instrument_agent_instance(instAgentInstance_obj,
instAgent_id,
instDevice_id)
self.addCleanup(self.imsclient.delete_instrument_agent_instance, instAgentInstance_id)
return instAgentInstance_id
def test_alerts(self):
#
# test that with the 4009 sim we can get a late data alert
# as well as alerts for out of range for > 25, > 50, and > 75
# as well as the ALL_CLEAR alerts for each of them.
#
#-------------------------------------------------------------------------------------
# Create InstrumentModel
#-------------------------------------------------------------------------------------
instModel_id = self._create_instrument_model()
#-------------------------------------------------------------------------------------
# Create InstrumentAgent
#-------------------------------------------------------------------------------------
instAgent_id = self._create_instrument_agent(instModel_id)
#-------------------------------------------------------------------------------------
# Create InstrumentDevice
#-------------------------------------------------------------------------------------
instDevice_id = self._create_instrument_device(instModel_id)
# It is necessary for the instrument device to be associated with atleast one output data product
parsed_pdict_id = self.dataset_management.read_parameter_dictionary_by_name('ctd_parsed_param_dict', id_only=True)
parsed_stream_def_id = self.pubsubclient.create_stream_definition(name='parsed', parameter_dictionary_id=parsed_pdict_id)
raw_pdict_id = self.dataset_management.read_parameter_dictionary_by_name('raw', id_only=True)
raw_stream_def_id = self.pubsubclient.create_stream_definition(name='raw', parameter_dictionary_id=raw_pdict_id)
# We are creating two data products here, one for parsed and another raw
dp_obj_parsed = IonObject(RT.DataProduct,
name='parsed_data_product',
description='Parsed output data product for instrument')
dp_obj_raw = IonObject(RT.DataProduct,
name='raw_data_prod',
description='Raw output data product for instrument')
parsed_out_data_prod_id = self.dataproductclient.create_data_product(data_product=dp_obj_parsed, stream_definition_id=parsed_stream_def_id)
raw_out_data_prod_id = self.dataproductclient.create_data_product(data_product=dp_obj_raw, stream_definition_id=raw_stream_def_id)
self.addCleanup(self.dataproductclient.delete_data_product, parsed_out_data_prod_id)
self.addCleanup(self.dataproductclient.delete_data_product, raw_out_data_prod_id)
self.dataproductclient.activate_data_product_persistence(data_product_id=parsed_out_data_prod_id)
self.dataproductclient.activate_data_product_persistence(data_product_id=raw_out_data_prod_id)
# todo: note that the generated config on the instruments will be done for both raw and parsed stream defs since these two data products constructed with each are associated as output data products with the instrument
# todo: if the config is not generated for a stream def, then the instrument agent will complain if the simulator generates data corresponding to a stream def that is not there in the stream config as a mentioned stream def
self.damsclient.assign_data_product(input_resource_id=instDevice_id, data_product_id=parsed_out_data_prod_id)
self.damsclient.assign_data_product(input_resource_id=instDevice_id, data_product_id=raw_out_data_prod_id)
log.debug("assigned instdevice id: %s to data product: %s", instDevice_id, raw_out_data_prod_id)
#-------------------------------------------------------------------------------------
# Create Instrument Agent Instance
#-------------------------------------------------------------------------------------
instAgentInstance_id = self._create_instrument_agent_instance(instAgent_id,instDevice_id )
#-------------------------------------------------------------------------------------
# Launch InstrumentAgentInstance, connect to the resource agent client
#-------------------------------------------------------------------------------------
self.imsclient.start_instrument_agent_instance(instrument_agent_instance_id=instAgentInstance_id)
self.addCleanup(self.imsclient.stop_instrument_agent_instance,
instrument_agent_instance_id=instAgentInstance_id)
inst_agent_instance_obj= self.imsclient.read_instrument_agent_instance(instAgentInstance_id)
# Wait for instrument agent to spawn
gate = AgentProcessStateGate(self.processdispatchclient.read_process,
instDevice_id,
ProcessStateEnum.RUNNING)
self.assertTrue(gate.await(15), "The instrument agent instance did not spawn in 15 seconds")
# Start a resource agent client to talk with the instrument agent.
self._ia_client = ResourceAgentClient(instDevice_id,
to_name=gate.process_id,
process=FakeProcess())
#-------------------------------------------------------------------------------------
# Set up the subscriber to catch the alert event
#-------------------------------------------------------------------------------------
def callback_for_alert(event, *args, **kwargs):
log.debug("caught an alert: %s", event)
self.catch_alert.put(event)
self.event_subscriber = EventSubscriber(event_type='DeviceStatusAlertEvent',
origin=instDevice_id,
callback=callback_for_alert)
self.event_subscriber.start()
self.addCleanup(self.event_subscriber.stop)
#-------------------------------------------------------------------------------------
# Running the instrument....
#-------------------------------------------------------------------------------------
cmd = AgentCommand(command=ResourceAgentEvent.INITIALIZE)
# Prevent this test from hanging indefinitely until
# OOIION-1313 is resolved
timeout_val = 90
with gevent.Timeout(timeout_val, Exception('Agent failed to initialize after %fs' % timeout_val)):
reply = self._ia_client.execute_agent(cmd)
self.assertTrue(reply.status == 0)
cmd = AgentCommand(command=ResourceAgentEvent.GO_ACTIVE)
with gevent.Timeout(timeout_val, Exception('Agent failed to go active after %fs' % timeout_val)):
reply = self._ia_client.execute_agent(cmd)
self.assertTrue(reply.status == 0)
cmd = AgentCommand(command=ResourceAgentEvent.GET_RESOURCE_STATE)
with gevent.Timeout(timeout_val, Exception('Agent failed to get resource after %fs' % timeout_val)):
retval = self._ia_client.execute_agent(cmd)
state = retval.result
log.debug("(L4-CI-SA-RQ-334): current state after sending go_active command %s", str(state))
self.assertTrue(state, 'DRIVER_STATE_COMMAND')
cmd = AgentCommand(command=ResourceAgentEvent.RUN)
with gevent.Timeout(timeout_val, Exception('Agent failed to run after %fs' % timeout_val)):
reply = self._ia_client.execute_agent(cmd)
self.assertTrue(reply.status == 0)
cmd = AgentCommand(command=SBE37ProtocolEvent.START_AUTOSAMPLE)
with gevent.Timeout(timeout_val, Exception('Agent failed to start autosample after %fs' % timeout_val)):
retval = self._ia_client.execute_resource(cmd)
got_bad_temp = [False, False, False, False]
got_late_data = False
got_temp_all_clear = [False, False, False, False]
runtime = 0
starttime = time.time()
caught_events = []
while (got_bad_temp[0] == False or
got_bad_temp[1] == False or
got_bad_temp[2] == False or
got_temp_all_clear[0] == False or
got_temp_all_clear[1] == False or
got_temp_all_clear[2] == False or
got_late_data == False) and runtime < 120:
a = self.catch_alert.get(timeout=180)
caught_events.append(a)
if a.name == 'temperature_warning_interval temp below 25':
if a.sub_type == 'WARNING' and \
a.values[0] > 25:
got_bad_temp[0] = True
log.error(str(a.values[0]) + " should be above 25")
elif a.sub_type == 'ALL_CLEAR':
got_temp_all_clear[0] = True
log.debug("25 ALL_CLEAR")
if a.name == 'temperature_warning_interval temp below 50':
if a.sub_type == 'WARNING' and \
a.values[0] > 50:
got_bad_temp[1] = True
log.error(str(a.values[0]) + " should be above 50")
elif a.sub_type == 'ALL_CLEAR':
got_temp_all_clear[1] = True
log.debug("50 ALL_CLEAR" )
if a.name == 'temperature_warning_interval temp below 75':
if a.sub_type == 'WARNING' and \
a.values[0] > 75:
got_bad_temp[2] = True
log.error(str(a.values[0]) + " should be above 75")
elif a.sub_type == 'ALL_CLEAR':
got_temp_all_clear[2] = True
log.debug("75 ALL_CLEAR")
if a.name == 'late_data_warning' and \
a.description == 'Expected data has not arrived.':
got_late_data = True
log.debug("late value")
runtime = time.time() - starttime
log.debug("caught_events: %s", [c.name for c in caught_events])
for c in caught_events:
self.assertIn(c.name, ['temperature_warning_interval temp below 25',
'temperature_warning_interval temp below 50',
'temperature_warning_interval temp below 75',
'late_data_warning'])
self.assertEqual(c.origin, instDevice_id)
self.assertEqual(c.type_, 'DeviceStatusAlertEvent')
self.assertEqual(c.origin_type, 'InstrumentDevice')
self.assertTrue(got_bad_temp)
#simply log the state of the late data flag and the simulator does not seem to be consistent.
log.debug("test_alerts late data alert flag: %s", got_late_data)
|
wgnet/wds_qt
|
qtdeclarative/tests/auto/qml/qqmlecmascript/data/jsimport/importWithNoImports.js
|
// This js file has no imports, and so should inherit
// scope from the QML file which includes it.
function componentError() {
var i = 5;
var errorIsOne = Component.error == 1;
if (errorIsOne == true) {
i = i + 7;
}
return i;
}
|
alanverresen/bvl-api
|
bvlapi/guid/guid.py
|
<filename>bvlapi/guid/guid.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Contains functionality to check if a string is a GUID.
import re
def is_bvlapi_guid(guid):
""" Checks that a given string is potentially a GUID used by the API.
:param str guid: a string that might be a GUID
:rtype: bool
:return: is the given string a GUID?
"""
return re.match(r"^BVBL", guid)
|
mistlog/rollup
|
test/function/samples/deprecations/this-getAssetFileName/_config.js
|
<gh_stars>1000+
module.exports = {
description: 'marks this.getAssetFileName as deprecated',
options: {
plugins: {
renderChunk() {
this.getAssetFileName(this.emitFile({ type: 'asset', name: 'asset', source: 'asset' }));
}
}
},
generateError: {
code: 'PLUGIN_ERROR',
hook: 'renderChunk',
message:
'The "this.getAssetFileName" plugin context function used by plugin at position 1 is deprecated. The "this.getFileName" plugin context function should be used instead.',
plugin: 'at position 1',
pluginCode: 'DEPRECATED_FEATURE'
}
};
|
genjosanzo/mule-devkit
|
tools/nexus/src/main/java/org/mule/devkit/nexus/ModuleContentGenerator.java
|
/**
* Mule Development Kit
* Copyright 2010-2011 (c) MuleSoft, Inc. All rights reserved. http://www.mulesoft.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mule.devkit.nexus;
import org.apache.maven.index.ArtifactInfo;
import org.apache.maven.index.ArtifactInfoFilter;
import org.apache.maven.index.NexusIndexer;
import org.apache.maven.index.context.IndexingContext;
import org.sonatype.nexus.index.DefaultIndexerManager;
import org.sonatype.nexus.index.IndexArtifactFilter;
import org.sonatype.nexus.index.IndexerManager;
import org.sonatype.nexus.proxy.IllegalOperationException;
import org.sonatype.nexus.proxy.ItemNotFoundException;
import org.sonatype.nexus.proxy.LocalStorageException;
import org.sonatype.nexus.proxy.item.ContentGenerator;
import org.sonatype.nexus.proxy.item.ContentLocator;
import org.sonatype.nexus.proxy.item.StorageFileItem;
import org.sonatype.nexus.proxy.repository.Repository;
import javax.inject.Inject;
import javax.inject.Named;
@Named(ModuleContentGenerator.ID)
public class ModuleContentGenerator
implements ContentGenerator {
public static final String ID = "ModuleContentGenerator";
@Inject
private IndexerManager indexerManager;
@Inject
private IndexArtifactFilter indexArtifactFilter;
@Inject
private NexusIndexer nexusIndexer;
@Override
public String getGeneratorId() {
return ID;
}
@Override
public ContentLocator generateContent(Repository repository, String path, StorageFileItem item)
throws IllegalOperationException, ItemNotFoundException, LocalStorageException {
// make length unknown (since it will be known only in the moment of actual content pull)
item.setLength(-1);
return new ModuleContentLocator(repository.getId(),
((DefaultIndexerManager) indexerManager).getRepositoryIndexContext(repository), nexusIndexer,
new ArtifactInfoFilter() {
public boolean accepts(IndexingContext ctx, ArtifactInfo ai) {
return indexArtifactFilter.filterArtifactInfo(ai);
}
});
}
}
|
vishnudevk/MiBandDecompiled
|
Original Files/source/src/com/tencent/connect/auth/d.java
|
// Decompiled by Jad v1.5.8e. Copyright 2001 <NAME>.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: braces fieldsfirst space lnc
package com.tencent.connect.auth;
import android.app.Dialog;
import android.view.View;
import com.tencent.tauth.IUiListener;
// Referenced classes of package com.tencent.connect.auth:
// g, c
class d extends g
{
final IUiListener a;
final Object b;
final c c;
d(c c1, Dialog dialog, IUiListener iuilistener, Object obj)
{
c = c1;
a = iuilistener;
b = obj;
super(c1, dialog);
}
public void onClick(View view)
{
c.a();
if (d != null && d.isShowing())
{
d.dismiss();
}
if (a != null)
{
a.onComplete(b);
}
}
}
|
Siddharth2016/PYTHON3_prog
|
Hackerearth Set/TheRiseOfWeirdThings.py
|
# THE RISE OF THE WEIRD THINGS
def insertionsort(Arr,n):
for start in range(n):
pos = start
while pos>0 and Arr[pos]<Arr[pos-1]:
(Arr[pos],Arr[pos-1]) = (Arr[pos-1],Arr[pos])
pos -= 1
n = int(input())
Arr = list(map(int, input().split()))
insertionsort(Arr,n)
rese = ""
reso = ""
sme = smo = 0
for i in Arr:
if i%2==0:
rese += str(i) + " "
sme += i
else:
reso += str(i) + " "
smo += i
rese += str(sme) + " " + reso + str(smo)
print(rese)
|
shao1chuan/pythonbook
|
Python 基础教程/1.7.2 D集合推导式.py
|
<filename>Python 基础教程/1.7.2 D集合推导式.py
import random
li = [random.randint(1,10) for i in range(10)]
print(li)
norepeat = []
for i in li:
if i not in norepeat:
norepeat.append(i)
print(norepeat)
print(set(norepeat))
print(set(li))
|
Scicrop/JSatTrak
|
wwjbackport/src/main/java/gov/nasa/worldwind/view/orbit/OrbitViewModel.java
|
/*
Copyright (C) 2001, 2007 United States Government as represented by
the Administrator of the National Aeronautics and Space Administration.
All Rights Reserved.
*/
package gov.nasa.worldwind.view.orbit;
import gov.nasa.worldwind.geom.Angle;
import gov.nasa.worldwind.geom.Matrix;
import gov.nasa.worldwind.geom.Position;
import gov.nasa.worldwind.geom.Vec4;
import gov.nasa.worldwind.globes.Globe;
/**
* @author dcollins
* @version $Id: OrbitViewModel.java 4100 2008-01-08 02:49:54Z dcollins $
*/
public interface OrbitViewModel
{
public interface ModelCoordinates
{
Position getCenterPosition();
Angle getHeading();
Angle getPitch();
double getZoom();
}
Matrix computeTransformMatrix(Globe globe, Position center, Angle heading, Angle pitch, double zoom);
ModelCoordinates computeModelCoordinates(Globe globe, Vec4 eyePoint, Vec4 centerPoint, Vec4 up);
ModelCoordinates computeModelCoordinates(Globe globe, Matrix modelview, Vec4 centerPoint);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.