repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
YousefED/DefinitelyTyped
types/node-schedule/node-schedule-tests.ts
5532
import nodeSchedule = require("node-schedule"); /** * Test for {@link Job} class. */ function testJob() { let name: string = ''; let jc: nodeSchedule.JobCallback = null; let callback: () => void = null; let jobSpec: nodeSchedule.Job = new nodeSchedule.Job(jc); let job: nodeSchedule.Job = new nodeSchedule.Job(jc, callback); let job2: nodeSchedule.Job = new nodeSchedule.Job(name, jc, callback); let jobName: string = job.name; } function testTrackInvocation() { let job: nodeSchedule.Job = new nodeSchedule.Job(() => {}); let success: boolean = job.trackInvocation( new nodeSchedule.Invocation(job, new Date(), new nodeSchedule.RecurrenceRule(0, 0, 0, 0, 0, 0, 0)) ); } function testStopTrackingInvocation() { let job: nodeSchedule.Job = new nodeSchedule.Job(() => {}); let success = job.stopTrackingInvocation( new nodeSchedule.Invocation(job, new Date(), new nodeSchedule.RecurrenceRule(0, 0, 0, 0, 0, 0, 0)) ); } function testTriggeredJobs() { let job: nodeSchedule.Job = new nodeSchedule.Job(() => {}); let triggeredJobs: number = job.triggeredJobs(); } function testSetTriggeredJobs() { let job: nodeSchedule.Job = new nodeSchedule.Job(() => {}); job.setTriggeredJobs(19); } function testCancel() { let job: nodeSchedule.Job = new nodeSchedule.Job(() => {}); let success: boolean = job.cancel(); let success2: boolean = job.cancel(true); } function testCancelNext() { let job: nodeSchedule.Job = new nodeSchedule.Job(() => {}); let success: boolean = job.cancelNext(); let success2: boolean = job.cancelNext(true); } function testReschedule() { let job: nodeSchedule.Job = new nodeSchedule.Job(() => {}); let success: boolean = job.reschedule(''); let success2: boolean = job.reschedule(1234); let success3: boolean = job.reschedule(new nodeSchedule.RecurrenceRule(0, 0, 0, 0, 0, 0, 0)); } function testNextInvocation() { let job: nodeSchedule.Job = new nodeSchedule.Job(() => {}); let nextInvocation: Date = job.nextInvocation(); } function testPendingInvocations() { let job: nodeSchedule.Job = new nodeSchedule.Job(() => {}); let pendingInvocations: nodeSchedule.Invocation[] = job.pendingInvocations(); } function testInvoke() { let job: nodeSchedule.Job = new nodeSchedule.Job(() => {}); job.invoke(); } function testRunOnDate() { let job: nodeSchedule.Job = new nodeSchedule.Job(() => {}); job.runOnDate(new Date()); } function testSchedule() { let job: nodeSchedule.Job = new nodeSchedule.Job(() => {}); let success: boolean = job.schedule(new Date()); success = job.schedule(''); success = job.schedule(1234); } /** * Test for {@link Range} class. */ function testRange() { let range = new nodeSchedule.Range(0); let twoParametersRange: nodeSchedule.Range = new nodeSchedule.Range(0, 0); let threeParametersRange: nodeSchedule.Range = new nodeSchedule.Range(0, 0, 0); let contained: boolean = range.contains(0); } /** * Test for {@link RecurrenceRule} class. */ function testRecurrenceRule() { let range = new nodeSchedule.Range(0, 0, 0); let rule: nodeSchedule.RecurrenceRule = new nodeSchedule.RecurrenceRule(0, 0, 0, [0, range], 0, 0, 0); let rule2: nodeSchedule.RecurrenceRule = new nodeSchedule.RecurrenceRule(0, 0, 0, 0, 0, 0, 0); let nextInvocation: Date = rule.nextInvocationDate(new Date()); let rule3: nodeSchedule.RecurrenceRule = new nodeSchedule.RecurrenceRule(); rule2.month = "7"; rule2.date = [1, new nodeSchedule.Range(5, 15, 5), "23"]; rule2.hour = 5; rule2.minute = new nodeSchedule.Range(4, 6); rule2.second = new nodeSchedule.Range(8, 12, 2); } /** * Test for {@link Invocation} class. */ function testInvocation() { let job = new nodeSchedule.Job(() => {}); let fireDate = new Date(); let rule: nodeSchedule.RecurrenceRule = new nodeSchedule.RecurrenceRule(0, 0, 0, 0, 0, 0, 0); let invocation = new nodeSchedule.Invocation(job, fireDate, rule); invocation.timerID = 0; } /** * Test for {@link scheduleJob} class. */ function testScheduleJob() { let callback: nodeSchedule.JobCallback = null; let job: nodeSchedule.Job = nodeSchedule.scheduleJob('', callback); let rule: nodeSchedule.RecurrenceRule = new nodeSchedule.RecurrenceRule(0, 0, 0, 0, 0, 0, 0); let job2: nodeSchedule.Job = nodeSchedule.scheduleJob(rule, callback); let date: Date = new Date(); let job3: nodeSchedule.Job = nodeSchedule.scheduleJob(date, callback); let jobObjLit: nodeSchedule.Job = nodeSchedule.scheduleJob({hour: 14, minute: 30, dayOfWeek: 0}, callback); let startDate: Date = new Date(); let endDate: Date = new Date(startDate.getDate() + 10000); let jobDateRange: nodeSchedule.Job = nodeSchedule.scheduleJob({start: startDate, end: endDate, rule: "* * * * * *"}, callback); } function testRescheduleJob() { let job: nodeSchedule.Job = nodeSchedule.rescheduleJob(new nodeSchedule.Job(() => {}), new Date()); job = nodeSchedule.rescheduleJob(new nodeSchedule.Job(() => {}), new nodeSchedule.RecurrenceRule(0, 0, 0, 0, 0, 0, 0)); job = nodeSchedule.rescheduleJob(new nodeSchedule.Job(() => {}), ''); job = nodeSchedule.rescheduleJob('', ''); } /** * Test for {@link cancelJob} function. */ function testCancelJob() { let job = new nodeSchedule.Job(() => {}); let success: boolean = nodeSchedule.cancelJob(job); success = nodeSchedule.cancelJob('jobName'); }
mit
markogresak/DefinitelyTyped
types/echarts/options/series/custom.d.ts
346658
declare namespace echarts { namespace EChartOption { /** * **custom series** * * `custom series` supports customizing graphic elements, and then generate * more types of charts. * * echarts manages the creation, deletion, animation and interaction * with other components (like * [dataZoom](https://echarts.apache.org/en/option.html#dataZoom) * 、 * [visualMap](https://echarts.apache.org/en/option.html#visualMap) * ), which frees developers from handle those issue themselves. * * **For example, a "x-range" chart is made by custom sereis:** * * [see doc](https://echarts.apache.org/en/option.html#series-custom) * * ** * [More samples of custom series](https://echarts.apache.org/examples/en/index.html#chart-type-custom) * ** * * ** * [A tutotial of custom series](https://echarts.apache.org/en/tutorial.html#Custom%20Series) * ** * * **Customize the render logic (in renderItem method)** * * `custom series` requires developers to write a render logic by themselves. * This render logic is called * [renderItem](https://echarts.apache.org/en/option.html#series-custom.renderItem) * . * * For example: * * [see doc](https://echarts.apache.org/en/option.html#series-custom) * * [renderItem](https://echarts.apache.org/en/option.html#series-custom.renderItem) * will be called on each data item. * * [renderItem](https://echarts.apache.org/en/option.html#series-custom.renderItem) * provides two parameters: * * + [params](https://echarts.apache.org/en/option.html#series-custom.renderItem.arguments.params) * : provides info about the current series and data and coordinate * system. * + [api](https://echarts.apache.org/en/option.html#series-custom.renderItem.arguments.api) * : includes some methods. * * [renderItem](https://echarts.apache.org/en/option.html#series-custom.renderItem) * method should returns graphic elements definitions.See * [renderItem.return](https://echarts.apache.org/en/option.html#series-custom.renderItem.return) * . * * Generally, the main process of * [renderItem](https://echarts.apache.org/en/option.html#series-custom.renderItem) * is that retrieve value from data and convert them to graphic elements * on the current coordinate system. Two methods in * [renderItem.arguments.api](https://echarts.apache.org/en/option.html#series-custom.renderItem.arguments.api) * are always used in this procedure: * * + [api.value(...)](https://echarts.apache.org/en/option.html#series-custom.renderItem.arguments.api.value) * is used to retrieve value from data. * For example, `api.value(0)` * retrieve the value of the first dimension in the current data item. * + [api.coord(...)](https://echarts.apache.org/en/option.html#series-custom.renderItem.arguments.api.coord) * is used to convert data to coordinate. * For example, `var point = api.coord([api.value(0), * api.value(1)])` * converet the data to the point on the current coordinate system. * * Sometimes * [api.size(...)](https://echarts.apache.org/en/option.html#series-custom.renderItem.arguments.api.size) * method is needed, which calculates the size on the coordinate system * by a given data range. * * Moreover, * [api.style(...)](https://echarts.apache.org/en/option.html#series-custom.renderItem.arguments.api.style) * method can be used to set style. * It provides not only the style settings specified in * [series.itemStyle](https://echarts.apache.org/en/option.html#series-custom.itemStyle) * , but also the result of visual mapping. * This method can also be called like `api.style({fill: * 'green', stroke: 'yellow'})` to override those style settings. * * **Dimension mapping (by encode and dimension option)** * * In most cases, * [series.encode](https://echarts.apache.org/en/option.html#series-custom.encode) * is needed to be specified when using `custom series` serise, which * indicate the mapping of dimensions, and then echarts can render appropriate * axis by the extent of those data. * * `encode.tooltip` * and `encode.label` * can also be specified to define the content of default `tooltip` * and `label`. * [series.dimensions](https://echarts.apache.org/en/option.html#series-custom.dimensions) * can also be specified to defined names of each dimensions, which * will be displayed in tooltip. * * For example: * * [see doc](https://echarts.apache.org/en/option.html#series-custom) * * **Controlled by dataZoom** * * When use `custom series` with * [dataZoom](https://echarts.apache.org/en/option.html#dataZoom) * , * [dataZoom.filterMode](https://echarts.apache.org/en/option.html#dataZoom.filterMode) * usually be set as `'weakFilter'`, which prevent `dataItem` from being * filtered when only part of its dimensions are out of the current * data window. * * **Difference between `dataIndex` and `dataIndexInside`** * * + `dataIndex` is the index of a `dataItem` in the original data. * + `dataIndexInside` is the index of a `dataItem` in the current data * window (see * [dataZoom](https://echarts.apache.org/en/option.html#dataZoom) * . * * [renderItem.arguments.api](https://echarts.apache.org/en/option.html#series-custom.renderItem.arguments.api) * uses `dataIndexInside` as the input parameter but not `dataIndex`, * because conversion from `dataIndex` to `dataIndexInside` is time-consuming. * * **Event listener** * * [see doc](https://echarts.apache.org/en/option.html#series-custom) * * * @see https://echarts.apache.org/en/option.html#series-custom */ interface SeriesCustom { /** * @default * "custom" * @see https://echarts.apache.org/en/option.html#series-custom.type */ type?: string | undefined; /** * Component ID, not specified by default. * If specified, it can be used to refer the component in option * or API. * * * @see https://echarts.apache.org/en/option.html#series-custom.id */ id?: string | undefined; /** * Series name used for displaying in * [tooltip](https://echarts.apache.org/en/option.html#tooltip) * and filtering with * [legend](https://echarts.apache.org/en/option.html#legend) * , or updaing data and configuration with `setOption`. * * * @see https://echarts.apache.org/en/option.html#series-custom.name */ name?: string | undefined; /** * Whether to enable highlighting chart when * [legend](https://echarts.apache.org/en/option.html#legend) * is being hovered. * * * @default * "true" * @see https://echarts.apache.org/en/option.html#series-custom.legendHoverLink */ legendHoverLink?: boolean | undefined; /** * The coordinate used in the series, whose options are: * * + `null` or `'none'` * * No coordinate. * * + `'cartesian2d'` * * Use a two-dimensional rectangular coordinate (also known as Cartesian * coordinate), with * [xAxisIndex](https://echarts.apache.org/en/option.html#series-custom.xAxisIndex) * and * [yAxisIndex](https://echarts.apache.org/en/option.html#series-custom.yAxisIndex) * to assign the corresponding axis component. * * + `'polar'` * * Use polar coordinates, with * [polarIndex](https://echarts.apache.org/en/option.html#series-custom.polarIndex) * to assign the corresponding polar coordinate component. * * + `'geo'` * * Use geographic coordinate, with * [geoIndex](https://echarts.apache.org/en/option.html#series-custom.geoIndex) * to assign the corresponding geographic coordinate components. * * + `'none'` * * Do not use coordinate system. * * * @default * "cartesian2d" * @see https://echarts.apache.org/en/option.html#series-custom.coordinateSystem */ coordinateSystem?: string | undefined; /** * Index of * [x axis](https://echarts.apache.org/en/option.html#xAxis) * to combine with, which is useful for multiple x axes in one chart. * * * @see https://echarts.apache.org/en/option.html#series-custom.xAxisIndex */ xAxisIndex?: number | undefined; /** * Index of * [y axis](https://echarts.apache.org/en/option.html#yAxis) * to combine with, which is useful for multiple y axes in one chart. * * * @see https://echarts.apache.org/en/option.html#series-custom.yAxisIndex */ yAxisIndex?: number | undefined; /** * Index of * [polar coordinate](https://echarts.apache.org/en/option.html#polar) * to combine with, which is useful for multiple polar axes in one * chart. * * * @see https://echarts.apache.org/en/option.html#series-custom.polarIndex */ polarIndex?: number | undefined; /** * Index of * [geographic coordinate](https://echarts.apache.org/en/option.html#geo) * to combine with, which is useful for multiple geographic axes * in one chart. * * * @see https://echarts.apache.org/en/option.html#series-custom.geoIndex */ geoIndex?: number | undefined; /** * Index of * [calendar coordinates](https://echarts.apache.org/en/option.html#calendar) * to combine with, which is useful for multiple calendar coordinates * in one chart. * * * @see https://echarts.apache.org/en/option.html#series-custom.calendarIndex */ calendarIndex?: number | undefined; /** * `custom series` requires developers to write a render logic by * themselves. This render logic is called * [renderItem](https://echarts.apache.org/en/option.html#series-custom.renderItem) * . * * For example: * * [see doc](https://echarts.apache.org/en/option.html#series-custom.custom) * * [renderItem](https://echarts.apache.org/en/option.html#series-custom.renderItem) * will be called on each data item. * * [renderItem](https://echarts.apache.org/en/option.html#series-custom.renderItem) * provides two parameters: * * + [params](https://echarts.apache.org/en/option.html#series-custom.renderItem.arguments.params) * : provides info about the current series and data and coordinate * system. * + [api](https://echarts.apache.org/en/option.html#series-custom.renderItem.arguments.api) * : includes some methods. * * [renderItem](https://echarts.apache.org/en/option.html#series-custom.renderItem) * method should returns graphic elements definitions.See * [renderItem.return](https://echarts.apache.org/en/option.html#series-custom.renderItem.return) * . * * Generally, the main process of * [renderItem](https://echarts.apache.org/en/option.html#series-custom.renderItem) * is that retrieve value from data and convert them to graphic * elements on the current coordinate system. Two methods in * [renderItem.arguments.api](https://echarts.apache.org/en/option.html#series-custom.renderItem.arguments.api) * are always used in this procedure: * * + [api.value(...)](https://echarts.apache.org/en/option.html#series-custom.renderItem.arguments.api.value) * is used to retrieve value from data. * For example, `api.value(0)` * retrieve the value of the first dimension in the current data * item. * + [api.coord(...)](https://echarts.apache.org/en/option.html#series-custom.renderItem.arguments.api.coord) * is used to convert data to coordinate. * For example, `var point = api.coord([api.value(0), * api.value(1)])` * converet the data to the point on the current coordinate system. * * Sometimes * [api.size(...)](https://echarts.apache.org/en/option.html#series-custom.renderItem.arguments.api.size) * method is needed, which calculates the size on the coordinate * system by a given data range. * * Moreover, * [api.style(...)](https://echarts.apache.org/en/option.html#series-custom.renderItem.arguments.api.style) * method can be used to set style. * It provides not only the style settings specified in * [series.itemStyle](https://echarts.apache.org/en/option.html#series-custom.itemStyle) * , but also the result of visual mapping. * This method can also be called like `api.style({fill: * 'green', stroke: 'yellow'})` to override those style settings. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem * * @returns * `renderItem` should returns graphic element definitions. * Each graphic element is an object. See * [graphic](https://echarts.apache.org/en/option.html#graphic.elements) * for detailed info. * (But width\\height\\top\\bottom is not supported here) * * If nothing should be rendered in this data item, just returns * nothing. * * For example: * * [see doc](https://echarts.apache.org/en/option.html#series-custom.custom.renderItem) * [see doc](https://echarts.apache.org/en/option.html#series-custom.custom.renderItem) * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return */ renderItem?: SeriesCustom.RenderItem | undefined; /** * Graphic style of , `emphasis` is the style when it is highlighted, * like being hovered by mouse, or highlighted via legend connect. * * * @see https://echarts.apache.org/en/option.html#series-custom.itemStyle */ itemStyle?: { /** * color. Color is taken from * [option.color Palette](https://echarts.apache.org/en/option.html#color) * by default. * * > Color can be represented in RGB, for example `'rgb(128, * 128, 128)'`. * RGBA can be used when you need alpha channel, for example * `'rgba(128, 128, 128, 0.5)'`. * You may also use hexadecimal format, for example `'#ccc'`. * Gradient color and texture are also supported besides single * colors. * > * > [see doc](https://echarts.apache.org/en/option.html#series-custom.custom.itemStyle) * * * @see https://echarts.apache.org/en/option.html#series-custom.itemStyle.color */ color?: EChartOption.Color | undefined; /** * border color, whose format is similar to that of `color`. * * * @default * "#000" * @see https://echarts.apache.org/en/option.html#series-custom.itemStyle.borderColor */ borderColor?: EChartOption.Color | undefined; /** * border width. No border when it is set to be 0. * * * @see https://echarts.apache.org/en/option.html#series-custom.itemStyle.borderWidth */ borderWidth?: number | undefined; /** * Border type, which can be `'solid'`, `'dashed'`, or `'dotted'`. * `'solid'` by default. * * * @default * "solid" * @see https://echarts.apache.org/en/option.html#series-custom.itemStyle.borderType */ borderType?: string | undefined; /** * Size of shadow blur. * This attribute should be used along with `shadowColor`,`shadowOffsetX`, * `shadowOffsetY` to set shadow to component. * * For example: * * [see doc](https://echarts.apache.org/en/option.html#series-custom.custom.itemStyle) * * * @see https://echarts.apache.org/en/option.html#series-custom.itemStyle.shadowBlur */ shadowBlur?: number | undefined; /** * Shadow color. Support same format as `color`. * * * @see https://echarts.apache.org/en/option.html#series-custom.itemStyle.shadowColor */ shadowColor?: EChartOption.Color | undefined; /** * Offset distance on the horizontal direction of shadow. * * * @see https://echarts.apache.org/en/option.html#series-custom.itemStyle.shadowOffsetX */ shadowOffsetX?: number | undefined; /** * Offset distance on the vertical direction of shadow. * * * @see https://echarts.apache.org/en/option.html#series-custom.itemStyle.shadowOffsetY */ shadowOffsetY?: number | undefined; /** * Opacity of the component. * Supports value from 0 to 1, and the component will not be * drawn when set to 0. * * * @see https://echarts.apache.org/en/option.html#series-custom.itemStyle.opacity */ opacity?: number | undefined; } | undefined; /** * @see https://echarts.apache.org/en/option.html#series-custom.emphasis */ emphasis?: { /** * @see https://echarts.apache.org/en/option.html#series-custom.emphasis.itemStyle */ itemStyle?: { /** * color. * * > Color can be represented in RGB, for example `'rgb(128, * 128, 128)'`. * RGBA can be used when you need alpha channel, for example * `'rgba(128, 128, 128, 0.5)'`. * You may also use hexadecimal format, for example `'#ccc'`. * Gradient color and texture are also supported besides * single colors. * > * > [see doc](https://echarts.apache.org/en/option.html#series-custom.custom.emphasis.itemStyle) * * * @see https://echarts.apache.org/en/option.html#series-custom.emphasis.itemStyle.color */ color?: EChartOption.Color | undefined; /** * border color, whose format is similar to that of `color`. * * * @default * "#000" * @see https://echarts.apache.org/en/option.html#series-custom.emphasis.itemStyle.borderColor */ borderColor?: EChartOption.Color | undefined; /** * border width. No border when it is set to be 0. * * * @see https://echarts.apache.org/en/option.html#series-custom.emphasis.itemStyle.borderWidth */ borderWidth?: number | undefined; /** * Border type, which can be `'solid'`, `'dashed'`, or `'dotted'`. * `'solid'` by default. * * * @default * "solid" * @see https://echarts.apache.org/en/option.html#series-custom.emphasis.itemStyle.borderType */ borderType?: string | undefined; /** * Size of shadow blur. * This attribute should be used along with `shadowColor`,`shadowOffsetX`, * `shadowOffsetY` to set shadow to component. * * For example: * * [see doc](https://echarts.apache.org/en/option.html#series-custom.custom.emphasis.itemStyle) * * * @see https://echarts.apache.org/en/option.html#series-custom.emphasis.itemStyle.shadowBlur */ shadowBlur?: number | undefined; /** * Shadow color. Support same format as `color`. * * * @see https://echarts.apache.org/en/option.html#series-custom.emphasis.itemStyle.shadowColor */ shadowColor?: EChartOption.Color | undefined; /** * Offset distance on the horizontal direction of shadow. * * * @see https://echarts.apache.org/en/option.html#series-custom.emphasis.itemStyle.shadowOffsetX */ shadowOffsetX?: number | undefined; /** * Offset distance on the vertical direction of shadow. * * * @see https://echarts.apache.org/en/option.html#series-custom.emphasis.itemStyle.shadowOffsetY */ shadowOffsetY?: number | undefined; /** * Opacity of the component. * Supports value from 0 to 1, and the component will not * be drawn when set to 0. * * * @see https://echarts.apache.org/en/option.html#series-custom.emphasis.itemStyle.opacity */ opacity?: number | undefined; } | undefined; } | undefined; /** * `dimensions` can be used to define dimension info for `series.data` * or `dataset.source`. * * Notice: if * [dataset](https://echarts.apache.org/en/option.html#dataset) * is used, we can provide dimension names in the first column/row * of * [dataset.source](https://echarts.apache.org/en/option.html#dataset.source) * , and not need to specify `dimensions` here. * But if `dimensions` is specified here, echarts will not retrieve * dimension names from the first row/column of `dataset.source` * any more. * * For example: * * [see doc](https://echarts.apache.org/en/option.html#series-custom.custom) * [see doc](https://echarts.apache.org/en/option.html#series-custom.custom) * * Each data item of `dimensions` can be: * * + `string`, for example, `'someName'`, which equals to `{name: * 'someName'}`. * + `Object`, where the attributes can be: * + name: `string`. * + type: `string`, supports: * + `number` * + `float`, that is, * [Float64Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float64Array) * * + `int`, that is, * [Int32Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int32Array) * * + `ordinal`, discrete value, which represents string generally. * + `time`, time value, see * [data](https://echarts.apache.org/en/option.html#series.data) * to check the format of time value. * + displayName: `string`, generally used in tooltip for dimension * display. If not specified, use `name` by default. * * When `dimensions` is specified, the default `tooltip` will be * displayed vertically, which is better to show diemsion names. * Otherwise, `tooltip` will displayed only value horizontally. * * * @see https://echarts.apache.org/en/option.html#series-custom.dimensions */ dimensions?: any[] | undefined; /** * Define what is encoded to for each dimension of `data`. * For example: * * [see doc](https://echarts.apache.org/en/option.html#series-custom.custom) * * Attributes of encode are different according to the type of coordinate * systtems. For * [cartesian2d](https://echarts.apache.org/en/option.html#grid) * , `x` and `y` can be defined. For * [polar](https://echarts.apache.org/en/option.html#polar) * , `radius` and `angle` can be defined. For * [geo](https://echarts.apache.org/en/option.html#geo) * , `lng` and `lat` can be defined. * Attribute `tooltip` and `itemName` (data item name in tooltip) * are always able to be defined. * * When * [dimensions](https://echarts.apache.org/en/option.html#series.dimensions) * is used to defined name for a certain dimension, `encode` can * refer the name directly. For example: * * [see doc](https://echarts.apache.org/en/option.html#series-custom.custom) * * Specially, in \[custom series(~series-custom), some property * in `encode`, corresponding to axis, can be set as null to make * the series not controlled by the axis, that is, the series data * will not be count in the extent of the axis, and the * [dataZoom](https://echarts.apache.org/en/option.html#dataZoom) * on the axis will not filter the series. * * [see doc](https://echarts.apache.org/en/option.html#series-custom.custom) * * * @see https://echarts.apache.org/en/option.html#series-custom.encode */ encode?: object | undefined; /** * When * [dataset](https://echarts.apache.org/en/option.html#dataset) * is used, `seriesLayoutBy` specifies whether the column or the * row of `dataset` is mapped to the series, namely, the series * is "layout" on columns or rows. Optional values: * * + 'column': by default, the columns of `dataset` are mapped the * series. In this case, each column represents a dimension. * + 'row':the rows of `dataset` are mapped to the series. * In this case, each row represents a dimension. * * Check this * [example](https://echarts.apache.org/examples/en/editor.html?c=dataset-series-layout-by) * . * * * @default * "column" * @see https://echarts.apache.org/en/option.html#series-custom.seriesLayoutBy */ seriesLayoutBy?: string | undefined; /** * If * [series.data](https://echarts.apache.org/en/option.html#series.data) * is not specified, and * [dataset](https://echarts.apache.org/en/option.html#dataset) * exists, the series will use `dataset`. * `datasetIndex` specifies which dataset will be used. * * * @see https://echarts.apache.org/en/option.html#series-custom.datasetIndex */ datasetIndex?: number | undefined; /** * Data array of series, which can be in the following forms: * * Notice, if no `data` specified in series, and there is * [dataset](https://echarts.apache.org/en/option.html#dataset) * in option, series will use the first * [dataset](https://echarts.apache.org/en/option.html#dataset) * as its datasource. If `data` has been specified, * [dataset](https://echarts.apache.org/en/option.html#dataset) * will not used. * * `series.datasetIndex` can be used to specify other * [dataset](https://echarts.apache.org/en/option.html#dataset) * . * * Basically, data is represented by a two-dimension array, like * the example below, where each colum is named as a "dimension". * * [see doc](https://echarts.apache.org/en/option.html#series-custom.custom) * * + In * [cartesian (grid)](https://echarts.apache.org/en/option.html#grid) * , "dimX" and "dimY" correspond to * [xAxis](https://echarts.apache.org/en/option.html#xAxis) * and * [yAxis](https://echarts.apache.org/en/option.html#yAxis) * repectively. * + In * [polar](https://echarts.apache.org/en/option.html#polar) * "dimX" and "dimY" correspond to * [radiusAxis](https://echarts.apache.org/en/option.html#radiusAxis) * 和 * [angleAxis](https://echarts.apache.org/en/option.html#anbleAxis) * repectively. * + Other dimensions are optional, which can be used in other place. * For example: * + [visualMap](https://echarts.apache.org/en/option.html#visualMap) * can map one or more dimensions to viusal (color, symbol size * ...). * + [series.symbolSize](https://echarts.apache.org/en/option.html#series.symbolSize) * can be set as a callback function, where symbol size can be calculated * by values of a certain dimension. * + Values in other dimensions can be shown by * [tooltip.formatter](https://echarts.apache.org/en/option.html#tooltip.formatter) * or * [series.label.formatter](https://echarts.apache.org/en/option.html#series.label.formatter) * . * * Especially, when there is one and only one category axis (axis.type * is `'category'`), data can be simply be represented by a one-dimension * array, like: * * [see doc](https://echarts.apache.org/en/option.html#series-custom.custom) * * **Relationship between "value" and * [axis.type](https://echarts.apache.org/en/option.html#xAxis.type) * ** * * + When a dimension corresponds to a value axis (axis.type * is `'value'` or `'log'`): * * The value can be a `number` (like `12`) (can also be a number * in a `string` format, like `'12'`). * * + When a dimension corresponds to a category axis (axis.type * is `'category'`): * * The value should be the ordinal of the axis.data * (based on `0`), the string value of the axis.data. * For example: * * [see doc](https://echarts.apache.org/en/option.html#series-custom.custom) * * There is an example of double category axes: * [Github Punchcard](https://echarts.apache.org/examples/en/editor.html?c=scatter-punchCard) * . * * + When a dimension corresponds to a time axis (type is `'time'`), * the value can be: * * + a timestamp, like `1484141700832`, which represents a UTC time. * + a date string, in one of the formats below: * + a subset of * [ISO 8601](http://www.ecma-international.org/ecma-262/5.1/#se * c-15.9.1.15) * , only including (all of these are treated as local time unless * timezone is specified, which is consistent with * [moment](https://momentjs.com/) * ): * + only part of year/month/date/time are specified: `'2012-03'`, * `'2012-03-01'`, `'2012-03-01 05'`, `'2012-03-01 05:06'`. * + separated by `"T"` or a space: `'2012-03-01T12:22:33.123'`, * `'2012-03-01 12:22:33.123'`. * + timezone specified: `'2012-03-01T12:22:33Z'`, `'2012-03-01T12:22:33+8000'`, * `'2012-03-01T12:22:33-05:00'`. * + other date string format (all of these are treated as local * time): `'2012'`, `'2012-3-1'`, `'2012/3/1'`, `'2012/03/01'`, * `'2009/6/12 2:00'`, `'2009/6/12 2:05:08'`, `'2009/6/12 2:05:08.123'`. * + a JavaScript Date instance created by user: * + Caution, when using a data string to create a Date instance, * [browser differences and inconsistencies](http://dygraphs.com/date-formats.html) * should be considered. * + For example: In chrome, `new Date('2012-01-01')` is treated * as a Jan 1st 2012 in UTC, while `new Date('2012-1-1')` and `new * Date('2012/01/01')` are treated as Jan 1st 2012 in local timezone. * In safari `new Date('2012-1-1')` is not supported. * + So if you intent to perform `new Date(dateString)`, it is strongly * recommended to use a time parse library (e.g., * [moment](https://momentjs.com/) * ), or use `echarts.number.parseDate`, or check * [this](http://dygraphs.com/date-formats.html) * . * * **Customize a data item:** * * When needing to customize a data item, it can be set as an object, * where property `value` reprensent real value. For example: * * [see doc](https://echarts.apache.org/en/option.html#series-custom.custom) * * **Empty value:** * * `'-'` or `null` or `undefined` or `NaN` can be used to describe * that a data item is not exists (ps:_not exist_ does not means * its value is `0`). * * For example, line chart can break when encounter an empty value, * and scatter chart do not display graphic elements for empty values. * * * @see https://echarts.apache.org/en/option.html#series-custom.data */ data?: | (void | string | number | SeriesCustom.DataObject)[] | (void | string | number | SeriesCustom.DataObject)[][] | undefined; /** * `zlevel` value of all graghical elements in custom series. * * `zlevel` is used to make layers with Canvas. * Graphical elements with different `zlevel` values will be placed * in different Canvases, which is a common optimization technique. * We can put those frequently changed elements (like those with * animations) to a seperate `zlevel`. * Notice that too many Canvases will increase memory cost, and * should be used carefully on mobile phones to avoid crash. * * Canvases with bigger `zlevel` will be placed on Canvases with * smaller `zlevel`. * * * @see https://echarts.apache.org/en/option.html#series-custom.zlevel */ zlevel?: number | undefined; /** * `z` value of all graghical elements in custom series, which controls * order of drawing graphical components. * Components with smaller `z` values may be overwritten by those * with larger `z` values. * * `z` has a lower priority to `zlevel`, and will not create new * Canvas. * * * @default * 2 * @see https://echarts.apache.org/en/option.html#series-custom.z */ z?: number | undefined; /** * Whether to ignore mouse events. * Default value is false, for triggering and responding to mouse * events. * * * @see https://echarts.apache.org/en/option.html#series-custom.silent */ silent?: boolean | undefined; /** * Whether to enable animation. * * * @default * "true" * @see https://echarts.apache.org/en/option.html#series-custom.animation */ animation?: boolean | undefined; /** * Whether to set graphic number threshold to animation. * Animation will be disabled when graphic number is larger than * threshold. * * * @default * 2000 * @see https://echarts.apache.org/en/option.html#series-custom.animationThreshold */ animationThreshold?: number | undefined; /** * Duration of the first animation, which supports callback function * for different data to have different animation effect: * * [see doc](https://echarts.apache.org/en/option.html#series-custom.custom) * * * @default * 1000 * @see https://echarts.apache.org/en/option.html#series-custom.animationDuration */ animationDuration?: Function | number | undefined; /** * Easing method used for the first animation. * Varied easing effects can be found at * [easing effect example](https://echarts.apache.org/examples/en/editor.html?c=line-easing) * . * * * @default * "cubicOut" * @see https://echarts.apache.org/en/option.html#series-custom.animationEasing */ animationEasing?: string | undefined; /** * Delay before updating the first animation, which supports callback * function for different data to have different animation effect. * * For example: * * [see doc](https://echarts.apache.org/en/option.html#series-custom.custom) * * See * [this example](https://echarts.apache.org/examples/en/editor.html?c=bar-animation-delay) * for more information. * * * @see https://echarts.apache.org/en/option.html#series-custom.animationDelay */ animationDelay?: Function | number | undefined; /** * Time for animation to complete, which supports callback function * for different data to have different animation effect: * * [see doc](https://echarts.apache.org/en/option.html#series-custom.custom) * * * @default * 300 * @see https://echarts.apache.org/en/option.html#series-custom.animationDurationUpdate */ animationDurationUpdate?: Function | number | undefined; /** * Easing method used for animation. * * * @default * "cubicOut" * @see https://echarts.apache.org/en/option.html#series-custom.animationEasingUpdate */ animationEasingUpdate?: string | undefined; /** * Delay before updating animation, which supports callback function * for different data to have different animation effect. * * For example: * * [see doc](https://echarts.apache.org/en/option.html#series-custom.custom) * * See * [this example](https://echarts.apache.org/examples/en/editor.html?c=bar-animation-delay) * for more information. * * * @see https://echarts.apache.org/en/option.html#series-custom.animationDelayUpdate */ animationDelayUpdate?: Function | number | undefined; /** * tooltip settings in this series. * * * @see https://echarts.apache.org/en/option.html#series-custom.tooltip */ tooltip?: BaseTooltip | undefined; } namespace SeriesCustom { interface DataObject { /** * Name of data item. * * * @see https://echarts.apache.org/en/option.html#series-custom.data.name */ name?: string | undefined; /** * Value of data item. * * * @see https://echarts.apache.org/en/option.html#series-custom.data.value */ value?: number | number[] | undefined; /** * @see https://echarts.apache.org/en/option.html#series-custom.data.itemStyle */ itemStyle?: { /** * color. * * > Color can be represented in RGB, for example `'rgb(128, * 128, 128)'`. * RGBA can be used when you need alpha channel, for example * `'rgba(128, 128, 128, 0.5)'`. * You may also use hexadecimal format, for example `'#ccc'`. * Gradient color and texture are also supported besides * single colors. * > * > [see doc](https://echarts.apache.org/en/option.html#series-custom.custom.data.itemStyle) * * * @see https://echarts.apache.org/en/option.html#series-custom.data.itemStyle.color */ color?: EChartOption.Color | undefined; /** * border color, whose format is similar to that of `color`. * * * @default * "#000" * @see https://echarts.apache.org/en/option.html#series-custom.data.itemStyle.borderColor */ borderColor?: EChartOption.Color | undefined; /** * border width. No border when it is set to be 0. * * * @see https://echarts.apache.org/en/option.html#series-custom.data.itemStyle.borderWidth */ borderWidth?: number | undefined; /** * Border type, which can be `'solid'`, `'dashed'`, or `'dotted'`. * `'solid'` by default. * * * @default * "solid" * @see https://echarts.apache.org/en/option.html#series-custom.data.itemStyle.borderType */ borderType?: string | undefined; /** * Size of shadow blur. * This attribute should be used along with `shadowColor`,`shadowOffsetX`, * `shadowOffsetY` to set shadow to component. * * For example: * * [see doc](https://echarts.apache.org/en/option.html#series-custom.custom.data.itemStyle) * * * @see https://echarts.apache.org/en/option.html#series-custom.data.itemStyle.shadowBlur */ shadowBlur?: number | undefined; /** * Shadow color. Support same format as `color`. * * * @see https://echarts.apache.org/en/option.html#series-custom.data.itemStyle.shadowColor */ shadowColor?: EChartOption.Color | undefined; /** * Offset distance on the horizontal direction of shadow. * * * @see https://echarts.apache.org/en/option.html#series-custom.data.itemStyle.shadowOffsetX */ shadowOffsetX?: number | undefined; /** * Offset distance on the vertical direction of shadow. * * * @see https://echarts.apache.org/en/option.html#series-custom.data.itemStyle.shadowOffsetY */ shadowOffsetY?: number | undefined; /** * Opacity of the component. * Supports value from 0 to 1, and the component will not * be drawn when set to 0. * * * @see https://echarts.apache.org/en/option.html#series-custom.data.itemStyle.opacity */ opacity?: number | undefined; } | undefined; /** * @see https://echarts.apache.org/en/option.html#series-custom.data.emphasis */ emphasis?: { /** * @see https://echarts.apache.org/en/option.html#series-custom.data.emphasis.itemStyle */ itemStyle?: { /** * color. * * > Color can be represented in RGB, for example `'rgb(128, * 128, 128)'`. * RGBA can be used when you need alpha channel, for * example `'rgba(128, 128, 128, 0.5)'`. * You may also use hexadecimal format, for example * `'#ccc'`. * Gradient color and texture are also supported besides * single colors. * > * > [see doc](https://echarts.apache.org/en/option.html#series-custom.custom.data.emphasis.itemStyle) * * * @see https://echarts.apache.org/en/option.html#series-custom.data.emphasis.itemStyle.color */ color?: EChartOption.Color | undefined; /** * border color, whose format is similar to that of * `color`. * * * @default * "#000" * @see https://echarts.apache.org/en/option.html#series-custom.data.emphasis.itemStyle.borderColor */ borderColor?: EChartOption.Color | undefined; /** * border width. No border when it is set to be 0. * * * @see https://echarts.apache.org/en/option.html#series-custom.data.emphasis.itemStyle.borderWidth */ borderWidth?: number | undefined; /** * Border type, which can be `'solid'`, `'dashed'`, * or `'dotted'`. `'solid'` by default. * * * @default * "solid" * @see https://echarts.apache.org/en/option.html#series-custom.data.emphasis.itemStyle.borderType */ borderType?: string | undefined; /** * Size of shadow blur. * This attribute should be used along with `shadowColor`,`shadowOffsetX`, * `shadowOffsetY` to set shadow to component. * * For example: * * [see doc](https://echarts.apache.org/en/option.html#series-custom.custom.data.emphasis.itemStyle) * * * @see https://echarts.apache.org/en/option.html#series-custom.data.emphasis.itemStyle.shadowBlur */ shadowBlur?: number | undefined; /** * Shadow color. Support same format as `color`. * * * @see https://echarts.apache.org/en/option.html#series-custom.data.emphasis.itemStyle.shadowColor */ shadowColor?: EChartOption.Color | undefined; /** * Offset distance on the horizontal direction of shadow. * * * @see https://echarts.apache.org/en/option.html#series-custom.data.emphasis.itemStyle.shadowOffsetX */ shadowOffsetX?: number | undefined; /** * Offset distance on the vertical direction of shadow. * * * @see https://echarts.apache.org/en/option.html#series-custom.data.emphasis.itemStyle.shadowOffsetY */ shadowOffsetY?: number | undefined; /** * Opacity of the component. * Supports value from 0 to 1, and the component will * not be drawn when set to 0. * * * @see https://echarts.apache.org/en/option.html#series-custom.data.emphasis.itemStyle.opacity */ opacity?: number | undefined; } | undefined; } | undefined; /** * tooltip settings in this series data. * * * @see https://echarts.apache.org/en/option.html#series-custom.data.tooltip */ tooltip?: BaseTooltip | undefined; } /** * `custom series` requires developers to write a render logic by * themselves. This render logic is called * [renderItem](https://echarts.apache.org/en/option.html#series-custom.renderItem) * . * * For example: * * [see doc](https://echarts.apache.org/en/option.html#series-custom.custom) * * [renderItem](https://echarts.apache.org/en/option.html#series-custom.renderItem) * will be called on each data item. * * [renderItem](https://echarts.apache.org/en/option.html#series-custom.renderItem) * provides two parameters: * * + [params](https://echarts.apache.org/en/option.html#series-custom.renderItem.arguments.params) * : provides info about the current series and data and coordinate * system. * + [api](https://echarts.apache.org/en/option.html#series-custom.renderItem.arguments.api) * : includes some methods. * * [renderItem](https://echarts.apache.org/en/option.html#series-custom.renderItem) * method should returns graphic elements definitions.See * [renderItem.return](https://echarts.apache.org/en/option.html#series-custom.renderItem.return) * . * * Generally, the main process of * [renderItem](https://echarts.apache.org/en/option.html#series-custom.renderItem) * is that retrieve value from data and convert them to graphic * elements on the current coordinate system. Two methods in * [renderItem.arguments.api](https://echarts.apache.org/en/option.html#series-custom.renderItem.arguments.api) * are always used in this procedure: * * + [api.value(...)](https://echarts.apache.org/en/option.html#series-custom.renderItem.arguments.api.value) * is used to retrieve value from data. * For example, `api.value(0)` * retrieve the value of the first dimension in the current data * item. * + [api.coord(...)](https://echarts.apache.org/en/option.html#series-custom.renderItem.arguments.api.coord) * is used to convert data to coordinate. * For example, `var point = api.coord([api.value(0), * api.value(1)])` * converet the data to the point on the current coordinate system. * * Sometimes * [api.size(...)](https://echarts.apache.org/en/option.html#series-custom.renderItem.arguments.api.size) * method is needed, which calculates the size on the coordinate * system by a given data range. * * Moreover, * [api.style(...)](https://echarts.apache.org/en/option.html#series-custom.renderItem.arguments.api.style) * method can be used to set style. * It provides not only the style settings specified in * [series.itemStyle](https://echarts.apache.org/en/option.html#series-custom.itemStyle) * , but also the result of visual mapping. * This method can also be called like `api.style({fill: * 'green', stroke: 'yellow'})` to override those style settings. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem */ interface RenderItem { (params: RenderItemParams, api: RenderItemApi): RenderItemReturnGroup | RenderItemReturnPath | RenderItemReturnImage | RenderItemReturnText | RenderItemReturnRect | RenderItemReturnCircle | RenderItemReturnRing | RenderItemReturnSector | RenderItemReturnArc | RenderItemReturnPolygon | RenderItemReturnPolyline | RenderItemReturnLine | RenderItemReturnBezierCurve; } /** * The first parameter of `renderItem`, including: * * [see doc](https://echarts.apache.org/en/option.html#series-custom.custom.renderItem.arguments) * * Difference between `dataIndex` and `dataIndexInside`: * * + `dataIndex` is the index of a `dataItem` in the original * data. * + `dataIndexInside` is the index of a `dataItem` in the * current data window (see * [dataZoom](https://echarts.apache.org/en/option.html#dataZoom) * . * * [renderItem.arguments.api](https://echarts.apache.org/en/option.html#series-custom.renderItem.arguments.api) * uses `dataIndexInside` as the input parameter but not * `dataIndex`, because conversion from `dataIndex` to `dataIndexInside` * is time-consuming. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.arguments.params */ interface RenderItemParams { /** * An object that developers can store something temporarily here. Life cycle: current round of rendering. */ context?: Record<string, any> | undefined; /** * The id of this series. */ seriesId?: string | undefined; /** * The name of this series. */ seriesName?: string | undefined; /** * The index of this series. */ seriesIndex?: number | undefined; /** * The index of this data item. */ dataIndex?: number | undefined; /** * The index of this data item in the current data window (see dataZoom). */ dataIndexInside?: number | undefined; /** * The count of data in the current data window (see dataZoom). */ dataInsideLength?: number | undefined; /** * The type of action that trigger this render. */ actionType?: string | undefined; /** * coordSys is variable by different types of coordinate systems. */ coordSys?: CoordSys | undefined; } /** * The second parameter of `renderItem`. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.arguments.api */ interface RenderItemApi { /** * Get value on the given dimension. * * [see doc](https://echarts.apache.org/en/option.html#series-custom.custom.renderItem.arguments.api) * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.arguments.api.value */ value?: Function | undefined; /** * Convert data to coordinate. * * [see doc](https://echarts.apache.org/en/option.html#series-custom.custom.renderItem.arguments.api) * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.arguments.api.coord */ coord?: Function | undefined; /** * Get the size by the given data range. * * For example, in `cartesian2d`, suppose calling `api.size([2, * 4])` returns `[12.4, * 55]`. * It represents that on x axis, data range `2` corresponds * to size `12.4`, * and on y axis data range `4` corresponds to size * `55`. * * In some coordinate systems (for example, polar) or * when log axis is used, the size is different in different * point. * So the second parameter is necessary to calculate * size on the given point. * * [see doc](https://echarts.apache.org/en/option.html#series-custom.custom.renderItem.arguments.api) * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.arguments.api.size */ size?: Function | undefined; /** * The method obtains style info defined in * [series.itemStyle](https://echarts.apache.org/en/option.html#series-custom.itemStyle) * , and visual info obtained by visual mapping, and * return them. * Those returned info can be assigned to `style` attribute * of graphic element definition directly. * Developers can also override style info by calling * this method like this: `api.style({fill: * 'green', stroke: 'yellow'})`. * * [see doc](https://echarts.apache.org/en/option.html#series-custom.custom.renderItem.arguments.api) * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.arguments.api.style */ style?: Function | undefined; /** * The method obtains style info defined in * [series.itemStyle.emphasis](https://echarts.apache.org/en/option.html#series-custom.itemStyle.emphasis) * , and visual info obtained by visual mapping, and * return them. * Those returned info can be assigned to `style` attribute * of graphic element definition directly. * Developers can also override style info by calling * this method like this: `api.style({fill: * 'green', stroke: 'yellow'})`. * * [see doc](https://echarts.apache.org/en/option.html#series-custom.custom.renderItem.arguments.api) * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.arguments.api.styleEmphasis */ styleEmphasis?: Function | undefined; /** * Get the visual info. It is rarely be used. * * [see doc](https://echarts.apache.org/en/option.html#series-custom.custom.renderItem.arguments.api) * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.arguments.api.visual */ visual?: Function | undefined; /** * When `barLayout` is needed, (for example, when attaching * some extra graphic elements to bar chart), this method * can be used to obtain bar layout info. * * See a * [sample](https://echarts.apache.org/examples/en/editor.html?c=custom-bar-trend) * . * * [see doc](https://echarts.apache.org/en/option.html#series-custom.custom.renderItem.arguments.api) * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.arguments.api.barLayout */ barLayout?: Function | undefined; /** * Obtain the current series index. * Notice that the `currentSeriesIndex` is different * from `seriesIndex` when legend is used to filter * some series. * * ``` * @return {number} * * ``` * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.arguments.api.currentSeriesIndices */ currentSeriesIndices?: Function | undefined; /** * Obtain font string, which can be used on style setting * directly. * * [see doc](https://echarts.apache.org/en/option.html#series-custom.custom.renderItem.arguments.api) * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.arguments.api.font */ font?: Function | undefined; /** * ``` * @return {number} Width of echarts containter. * * ``` * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.arguments.api.getWidth */ getWidth?: Function | undefined; /** * ``` * @return {number} Height of echarts container. * * ``` * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.arguments.api.getHeight */ getHeight?: Function | undefined; /** * ``` * @return {module:zrender} zrender instance. * * ``` * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.arguments.api.getZr */ getZr?: Function | undefined; /** * ``` * @return {number} The current devicePixelRatio。 * * ``` * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.arguments.api.getDevicePixelRatio */ getDevicePixelRatio?: Function | undefined; } /** * coordSys is variable by different types of coordinate systems. */ interface CoordSys { type?: 'cartesian2d' | 'calendar' | 'geo' | 'polar' | 'singleAxis' | undefined; /** * x of grid rect, calendar rect, geo rect or singleAxis rect * * It is not valid when type is 'polar' */ x?: number | undefined; /** * y of grid rect, calendar rect, geo rect or singleAxis rect * * It is not valid when type is 'polar' */ y?: number | undefined; /** * width of grid rect, calendar rect, geo rect or singleAxis rect * * It is not valid when type is 'polar' */ width?: number | undefined; /** * height of grid rect, calendar rect, geo rect or singleAxis rect * * It is not valid when type is 'polar' */ height?: number | undefined; // calendar cellWidth /** * calendar cellWidth * * It is valid when type is 'calendar' */ cellWidth?: number | undefined; /** * calendar cellHeight * * It is valid when type is 'calendar' */ cellHeight?: number | undefined; /** * calendar rangeInfo * * It is valid when type is 'calendar' */ rangeInfo?: RangeInfo | undefined; /** * zoom ratio, 1 if no zoom, 0.5 means shrink to 50%. * * It is valid when type is 'geo' */ zoom?: number | undefined; /** * x of polar center. * * It is valid when type is 'polar' */ cx?: number | undefined; /** * y of polar center. * * It is valid when type is 'polar' */ cy?: number | undefined; /** * outer radius of polar. * * It is valid when type is 'polar' */ r?: number | undefined; /** * inner radius of polar. * * It is valid when type is 'polar' */ r0?: number | undefined; } /** * calendar rangeInfo */ interface RangeInfo { /** * date start of calendar. */ start?: any; /** * date end of calendar. */ end?: any; /** * number of weeks in calendar. */ weeks?: number | undefined; /** * day count in calendar. */ dayCount?: number | undefined; } /** * `group` is the only type that can contain children, so that * a group of elements can be positioned and transformed together. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group */ interface RenderItemReturnGroup { /** * Must be specified when define a graphic element at the * first time. * * Optional value * * [image](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_image) * , * [text](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_text) * , * [circle](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_circle) * , * [sector](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_sector) * , * [ring](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_ring) * , * [polygon](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon) * , * [polyline](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polyline) * , * [rect](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_rect) * , * [line](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_line) * , * [bezierCurve](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_bezierCurve) * , * [arc](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_arc) * , * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * , * * * @default * "group" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group.type */ type?: string | undefined; /** * id is used to specifying element when willing to update * it. id can be ignored if you do not need it. * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group.id */ id?: string | undefined; /** * `2D transform` can be applied to graphic elements, including: * * + [position](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.position) * : `[horizontal translate offset, vertical translate offset]`, * `[0, 0]` by default. * Positive value means translate towards right or bottom. * + [rotation](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.rotation) * : Rotation in radian, `0` by default. * Positive when anticlockwise. * + [scale](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.scale) * : `[horizontal scale factor, vertical scale factor]`, * `[1, 1]` by default. * * [origin](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.origin) * specifies the origin point of rotation and scaling, `[0, * 0]` by default. * * Notice: * * + The coordinates specified in the transform attribute * above are relative to the `[0, 0]` of the parent element * (that is, * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * or the root canvas). Thus we are able to * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * multiple elements, and * [groups](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * can be nested. * + The order that the transform attributes are applied * to a single graphic element is: Firstly, `rotation`, * then, `scale`, finally, `position`. * * * @default * [0, 0] * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group.position */ position?: any[] | undefined; /** * `2D transform` can be applied to graphic elements, including: * * + [position](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.position) * : `[horizontal translate offset, vertical translate offset]`, * `[0, 0]` by default. * Positive value means translate towards right or bottom. * + [rotation](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.rotation) * : Rotation in radian, `0` by default. * Positive when anticlockwise. * + [scale](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.scale) * : `[horizontal scale factor, vertical scale factor]`, * `[1, 1]` by default. * * [origin](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.origin) * specifies the origin point of rotation and scaling, `[0, * 0]` by default. * * Notice: * * + The coordinates specified in the transform attribute * above are relative to the `[0, 0]` of the parent element * (that is, * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * or the root canvas). Thus we are able to * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * multiple elements, and * [groups](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * can be nested. * + The order that the transform attributes are applied * to a single graphic element is: Firstly, `rotation`, * then, `scale`, finally, `position`. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group.rotation */ rotation?: number | undefined; /** * `2D transform` can be applied to graphic elements, including: * * + [position](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.position) * : `[horizontal translate offset, vertical translate offset]`, * `[0, 0]` by default. * Positive value means translate towards right or bottom. * + [rotation](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.rotation) * : Rotation in radian, `0` by default. * Positive when anticlockwise. * + [scale](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.scale) * : `[horizontal scale factor, vertical scale factor]`, * `[1, 1]` by default. * * [origin](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.origin) * specifies the origin point of rotation and scaling, `[0, * 0]` by default. * * Notice: * * + The coordinates specified in the transform attribute * above are relative to the `[0, 0]` of the parent element * (that is, * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * or the root canvas). Thus we are able to * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * multiple elements, and * [groups](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * can be nested. * + The order that the transform attributes are applied * to a single graphic element is: Firstly, `rotation`, * then, `scale`, finally, `position`. * * * @default * [1, 1] * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group.scale */ scale?: any[] | undefined; /** * `2D transform` can be applied to graphic elements, including: * * + [position](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.position) * : `[horizontal translate offset, vertical translate offset]`, * `[0, 0]` by default. * Positive value means translate towards right or bottom. * + [rotation](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.rotation) * : Rotation in radian, `0` by default. * Positive when anticlockwise. * + [scale](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.scale) * : `[horizontal scale factor, vertical scale factor]`, * `[1, 1]` by default. * * [origin](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.origin) * specifies the origin point of rotation and scaling, `[0, * 0]` by default. * * Notice: * * + The coordinates specified in the transform attribute * above are relative to the `[0, 0]` of the parent element * (that is, * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * or the root canvas). Thus we are able to * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * multiple elements, and * [groups](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * can be nested. * + The order that the transform attributes are applied * to a single graphic element is: Firstly, `rotation`, * then, `scale`, finally, `position`. * * * @default * [0, 0] * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group.origin */ origin?: number | undefined; /** * Define the overlap relationship between graphic elements. * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group.z2 */ z2?: number | undefined; /** * See * [diffChildrenByName](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.diffChildrenByName) * 。 * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group.name */ name?: string | undefined; /** * User defined data, can be visited in event listeners. * * [see doc](https://echarts.apache.org/en/option.html#series-custom.custom.renderItem.return_group) * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group.info */ info?: any; /** * Whether response to mouse events / touch events. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group.silent */ silent?: boolean | undefined; /** * Whether the element is visible. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group.invisible */ invisible?: boolean | undefined; /** * Whether the element is totally ignored (neither render * nor listen events). * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group.ignore */ ignore?: boolean | undefined; /** * Specify width of this `group`. * * This width is only used for the positioning of its children. * * When width is `0`, children can also be positioned according * to its parent using `left: 'center'`. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group.width */ width?: number | undefined; /** * Specify height of this `group`. * * This height is only used for the positioning of its children. * * When height is `0`, children can also be positioned according * to its parent using `top: 'middle'`. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group.height */ height?: number | undefined; /** * In * [custom series](https://echarts.apache.org/en/option.html#series-custom) * , when `diffChildrenByName` is set as `true`, for each * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * returned from * [renderItem](https://echarts.apache.org/en/option.html#series-custom.renderItem) * , "diff" will be performed to its * [children](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group.children) * according to the * [name](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.name) * attribute of each graphic elements. * Here "diff" means that map the coming graphic elements * to the existing graphic elements when repainting according * to `name`, which enables the transition animation if * data is modified. * * But notice that the operation is performance consuming, * do not use it for large data amount. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group.diffChildrenByName */ diffChildrenByName?: boolean | undefined; /** * A list of children, each item is a declaration of an * element. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group.children */ children?: any[] | undefined; /** * Empahsis style of the graphic element, whose structure * is the same as * [style](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.style) * . * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group.styleEmphasis */ styleEmphasis?: object | undefined; } /** * Use * [SVG PathData](http://www.w3.org/TR/SVG/paths.html#PathData) * to describe a path. * Can be used to draw icons or any other shapes fitting the * specified size by auto transforming. * * See examples: * [icons](https://echarts.apache.org/examples/en/editor.html?c=custom-calendar-icon) * and * [shapes](https://echarts.apache.org/examples/en/editor.html?c=custom-gantt-flight) * . * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_path */ interface RenderItemReturnPath { /** * Must be specified when define a graphic element at the * first time. * * Optional values: * * [image](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_image) * , * [text](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_text) * , * [circle](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_circle) * , * [sector](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_sector) * , * [ring](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_ring) * , * [polygon](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon) * , * [polyline](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polyline) * , * [rect](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_rect) * , * [line](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_line) * , * [bezierCurve](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_bezierCurve) * , * [arc](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_arc) * , * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * , * * * @default * "path" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_path.type */ type?: string | undefined; /** * id is used to specifying element when willing to update * it. id can be ignored if you do not need it. * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_path.id */ id?: string | undefined; /** * `2D transform` can be applied to graphic elements, including: * * + [position](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.position) * : `[horizontal translate offset, vertical translate offset]`, * `[0, 0]` by default. * Positive value means translate towards right or bottom. * + [rotation](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.rotation) * : Rotation in radian, `0` by default. * Positive when anticlockwise. * + [scale](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.scale) * : `[horizontal scale factor, vertical scale factor]`, * `[1, 1]` by default. * * [origin](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.origin) * specifies the origin point of rotation and scaling, `[0, * 0]` by default. * * Notice: * * + The coordinates specified in the transform attribute * above are relative to the `[0, 0]` of the parent element * (that is, * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * or the root canvas). Thus we are able to * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * multiple elements, and * [groups](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * can be nested. * + The order that the transform attributes are applied * to a single graphic element is: Firstly, `rotation`, * then, `scale`, finally, `position`. * * * @default * [0, 0] * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_path.position */ position?: any[] | undefined; /** * `2D transform` can be applied to graphic elements, including: * * + [position](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.position) * : `[horizontal translate offset, vertical translate offset]`, * `[0, 0]` by default. * Positive value means translate towards right or bottom. * + [rotation](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.rotation) * : Rotation in radian, `0` by default. * Positive when anticlockwise. * + [scale](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.scale) * : `[horizontal scale factor, vertical scale factor]`, * `[1, 1]` by default. * * [origin](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.origin) * specifies the origin point of rotation and scaling, `[0, * 0]` by default. * * Notice: * * + The coordinates specified in the transform attribute * above are relative to the `[0, 0]` of the parent element * (that is, * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * or the root canvas). Thus we are able to * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * multiple elements, and * [groups](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * can be nested. * + The order that the transform attributes are applied * to a single graphic element is: Firstly, `rotation`, * then, `scale`, finally, `position`. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_path.rotation */ rotation?: number | undefined; /** * `2D transform` can be applied to graphic elements, including: * * + [position](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.position) * : `[horizontal translate offset, vertical translate offset]`, * `[0, 0]` by default. * Positive value means translate towards right or bottom. * + [rotation](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.rotation) * : Rotation in radian, `0` by default. * Positive when anticlockwise. * + [scale](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.scale) * : `[horizontal scale factor, vertical scale factor]`, * `[1, 1]` by default. * * [origin](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.origin) * specifies the origin point of rotation and scaling, `[0, * 0]` by default. * * Notice: * * + The coordinates specified in the transform attribute * above are relative to the `[0, 0]` of the parent element * (that is, * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * or the root canvas). Thus we are able to * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * multiple elements, and * [groups](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * can be nested. * + The order that the transform attributes are applied * to a single graphic element is: Firstly, `rotation`, * then, `scale`, finally, `position`. * * * @default * [1, 1] * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_path.scale */ scale?: any[] | undefined; /** * `2D transform` can be applied to graphic elements, including: * * + [position](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.position) * : `[horizontal translate offset, vertical translate offset]`, * `[0, 0]` by default. * Positive value means translate towards right or bottom. * + [rotation](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.rotation) * : Rotation in radian, `0` by default. * Positive when anticlockwise. * + [scale](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.scale) * : `[horizontal scale factor, vertical scale factor]`, * `[1, 1]` by default. * * [origin](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.origin) * specifies the origin point of rotation and scaling, `[0, * 0]` by default. * * Notice: * * + The coordinates specified in the transform attribute * above are relative to the `[0, 0]` of the parent element * (that is, * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * or the root canvas). Thus we are able to * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * multiple elements, and * [groups](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * can be nested. * + The order that the transform attributes are applied * to a single graphic element is: Firstly, `rotation`, * then, `scale`, finally, `position`. * * * @default * [0, 0] * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_path.origin */ origin?: number | undefined; /** * Define the overlap relationship between graphic elements. * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_path.z2 */ z2?: number | undefined; /** * See * [diffChildrenByName](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.diffChildrenByName) * 。 * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_path.name */ name?: string | undefined; /** * User defined data, can be visited in event listeners. * * [see doc](https://echarts.apache.org/en/option.html#series-custom.custom.renderItem.return_path) * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_path.info */ info?: any; /** * Whether response to mouse events / touch events. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_path.silent */ silent?: boolean | undefined; /** * Whether the element is visible. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_path.invisible */ invisible?: boolean | undefined; /** * Whether the element is totally ignored (neither render * nor listen events). * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_path.ignore */ ignore?: boolean | undefined; /** * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_path.shape */ shape?: { /** * [SVG PathData](http://www.w3.org/TR/SVG/paths.html#PathData) * . * * For example, `'M0,0 L0,-20 L30,-20 C42,-20 38,-1 * 50,-1 L70,-1 L70,0 Z'`。 * * If * [width](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_path.shape.width) * , * [height](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_path.shape.height) * , * [x](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_path.shape.x) * and * [y](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_path.shape.y) * specified, `pathData` will be transformed to fit * the defined rect. * If they are not specified, do not do that. * * [layout](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_path.shape.layout) * can be used to specify the transform strategy. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_path.shape.pathData */ pathData?: string | undefined; /** * Alias of * [pathData](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_path.shape.pathData) * . * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_path.shape.d */ d?: string | undefined; /** * If * [width](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_path.shape.width) * , * [height](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_path.shape.height) * , * [x](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_path.shape.x) * and * [y](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_path.shape.y) * specified, `pathData` will be transformed to fit * the defined rect. * * `layout` can be used to specify the transform strategy. * * Optional value: * * + `'center'`: Keep aspect ratio, put the path in * the center of the rect, expand as far as possible * but never overflow. * + `'cover'`: Transform the path according to the * aspect ratio of the rect, fill the rect and do not * overflow. * * * @default * "center" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_path.shape.layout */ layout?: string | undefined; /** * The x value of the left-top corner of the element * in the coordinate system of its parent. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_path.shape.x */ x?: number | undefined; /** * The y value of the left-top corner of the element * in the coordinate system of its parent. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_path.shape.y */ y?: number | undefined; /** * The width of the shape of the element. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_path.shape.width */ width?: number | undefined; /** * The height of the shape of the element. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_path.shape.height */ height?: number | undefined; } | undefined; /** * More attributes in `style` (for example, * [rich text](https://echarts.apache.org/en/tutorial.html#Rich%20Text) * ), see the `style` related attributes in * [zrender/graphic/Displayable](https://ecomfe.github.io/zrender-doc/public/api.html#zrenderdisplayable) * . * * Notice, the attribute names of the `style` of graphic * elements is derived from `zrender`, which may be different * from the attribute names in `echarts label`, `echarts * itemStyle`, etc., * although they have the same meaning. For example: * * + [itemStyle.color](https://echarts.apache.org/en/option.html#series-scatter.label.color) * => `style.fill` * + [itemStyle.borderColor](https://echarts.apache.org/en/option.html#series-scatter.label.color) * => `style.stroke` * + [label.color](https://echarts.apache.org/en/option.html#series-scatter.label.color) * => `style.textFill` * + [label.textBorderColor](https://echarts.apache.org/en/option.html#series-scatter.label.textBorderColor) * => `style.textStroke` * + ... * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_path.style */ style?: { /** * Color filled in this element. * * * @default * '#000' * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_path.style.fill */ fill?: string | undefined; /** * Color of stroke. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_path.style.stroke */ stroke?: string | undefined; /** * Width of stroke. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_path.style.lineWidth */ lineWidth?: number | undefined; /** * Width of shadow. * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_path.style.shadowBlur */ shadowBlur?: number | undefined; /** * X offset of shadow. * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_path.style.shadowOffsetX */ shadowOffsetX?: number | undefined; /** * Y offset of shadow. * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_path.style.shadowOffsetY */ shadowOffsetY?: number | undefined; /** * color of shadow. * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_path.style.shadowColor */ shadowColor?: number | undefined; } | undefined; /** * Empahsis style of the graphic element, whose structure * is the same as * [style](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.style) * . * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_path.styleEmphasis */ styleEmphasis?: object | undefined; } /** * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_image */ interface RenderItemReturnImage { /** * Must be specified when define a graphic element at the * first time. * * Optional values: * * [image](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_image) * , * [text](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_text) * , * [circle](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_circle) * , * [sector](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_sector) * , * [ring](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_ring) * , * [polygon](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon) * , * [polyline](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polyline) * , * [rect](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_rect) * , * [line](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_line) * , * [bezierCurve](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_bezierCurve) * , * [arc](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_arc) * , * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * , * * * @default * "image" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_image.type */ type?: string | undefined; /** * id is used to specifying element when willing to update * it. id can be ignored if you do not need it. * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_image.id */ id?: string | undefined; /** * `2D transform` can be applied to graphic elements, including: * * + [position](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.position) * : `[horizontal translate offset, vertical translate offset]`, * `[0, 0]` by default. * Positive value means translate towards right or bottom. * + [rotation](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.rotation) * : Rotation in radian, `0` by default. * Positive when anticlockwise. * + [scale](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.scale) * : `[horizontal scale factor, vertical scale factor]`, * `[1, 1]` by default. * * [origin](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.origin) * specifies the origin point of rotation and scaling, `[0, * 0]` by default. * * Notice: * * + The coordinates specified in the transform attribute * above are relative to the `[0, 0]` of the parent element * (that is, * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * or the root canvas). Thus we are able to * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * multiple elements, and * [groups](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * can be nested. * + The order that the transform attributes are applied * to a single graphic element is: Firstly, `rotation`, * then, `scale`, finally, `position`. * * * @default * [0, 0] * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_image.position */ position?: any[] | undefined; /** * `2D transform` can be applied to graphic elements, including: * * + [position](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.position) * : `[horizontal translate offset, vertical translate offset]`, * `[0, 0]` by default. * Positive value means translate towards right or bottom. * + [rotation](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.rotation) * : Rotation in radian, `0` by default. * Positive when anticlockwise. * + [scale](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.scale) * : `[horizontal scale factor, vertical scale factor]`, * `[1, 1]` by default. * * [origin](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.origin) * specifies the origin point of rotation and scaling, `[0, * 0]` by default. * * Notice: * * + The coordinates specified in the transform attribute * above are relative to the `[0, 0]` of the parent element * (that is, * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * or the root canvas). Thus we are able to * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * multiple elements, and * [groups](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * can be nested. * + The order that the transform attributes are applied * to a single graphic element is: Firstly, `rotation`, * then, `scale`, finally, `position`. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_image.rotation */ rotation?: number | undefined; /** * `2D transform` can be applied to graphic elements, including: * * + [position](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.position) * : `[horizontal translate offset, vertical translate offset]`, * `[0, 0]` by default. * Positive value means translate towards right or bottom. * + [rotation](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.rotation) * : Rotation in radian, `0` by default. * Positive when anticlockwise. * + [scale](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.scale) * : `[horizontal scale factor, vertical scale factor]`, * `[1, 1]` by default. * * [origin](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.origin) * specifies the origin point of rotation and scaling, `[0, * 0]` by default. * * Notice: * * + The coordinates specified in the transform attribute * above are relative to the `[0, 0]` of the parent element * (that is, * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * or the root canvas). Thus we are able to * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * multiple elements, and * [groups](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * can be nested. * + The order that the transform attributes are applied * to a single graphic element is: Firstly, `rotation`, * then, `scale`, finally, `position`. * * * @default * [1, 1] * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_image.scale */ scale?: any[] | undefined; /** * `2D transform` can be applied to graphic elements, including: * * + [position](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.position) * : `[horizontal translate offset, vertical translate offset]`, * `[0, 0]` by default. * Positive value means translate towards right or bottom. * + [rotation](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.rotation) * : Rotation in radian, `0` by default. * Positive when anticlockwise. * + [scale](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.scale) * : `[horizontal scale factor, vertical scale factor]`, * `[1, 1]` by default. * * [origin](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.origin) * specifies the origin point of rotation and scaling, `[0, * 0]` by default. * * Notice: * * + The coordinates specified in the transform attribute * above are relative to the `[0, 0]` of the parent element * (that is, * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * or the root canvas). Thus we are able to * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * multiple elements, and * [groups](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * can be nested. * + The order that the transform attributes are applied * to a single graphic element is: Firstly, `rotation`, * then, `scale`, finally, `position`. * * * @default * [0, 0] * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_image.origin */ origin?: number | undefined; /** * Define the overlap relationship between graphic elements. * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_image.z2 */ z2?: number | undefined; /** * See * [diffChildrenByName](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.diffChildrenByName) * 。 * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_image.name */ name?: string | undefined; /** * User defined data, can be visited in event listeners. * * [see doc](https://echarts.apache.org/en/option.html#series-custom.custom.renderItem.return_image) * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_image.info */ info?: any; /** * Whether response to mouse events / touch events. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_image.silent */ silent?: boolean | undefined; /** * Whether the element is visible. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_image.invisible */ invisible?: boolean | undefined; /** * Whether the element is totally ignored (neither render * nor listen events). * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_image.ignore */ ignore?: boolean | undefined; /** * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_image.style */ style?: { /** * Specify contant of the image, can be a URL, or * [dataURI](https://tools.ietf.org/html/rfc2397) * . * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_image.style.image */ image?: string | undefined; /** * The x value of the left-top corner of the element * in the coordinate system of its parent. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_image.style.x */ x?: number | undefined; /** * The y value of the left-top corner of the element * in the coordinate system of its parent. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_image.style.y */ y?: number | undefined; /** * The width of the shape of the element. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_image.style.width */ width?: number | undefined; /** * The height of the shape of the element. * * More attributes in `style` (for example, * [rich text](https://echarts.apache.org/en/tutorial.html#Rich%20Text) * ), see the `style` related attributes in * [zrender/graphic/Displayable](https://ecomfe.github.io/zrender-doc/public/api.html#zrenderdisplayable) * . * * Notice, the attribute names of the `style` of graphic * elements is derived from `zrender`, which may be * different from the attribute names in `echarts label`, * `echarts itemStyle`, etc., * although they have the same meaning. For example: * * + [itemStyle.color](https://echarts.apache.org/en/option.html#series-scatter.label.color) * => `style.fill` * + [itemStyle.borderColor](https://echarts.apache.org/en/option.html#series-scatter.label.color) * => `style.stroke` * + [label.color](https://echarts.apache.org/en/option.html#series-scatter.label.color) * => `style.textFill` * + [label.textBorderColor](https://echarts.apache.org/en/option.html#series-scatter.label.textBorderColor) * => `style.textStroke` * + ... * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_image.style.height */ height?: number | undefined; /** * Color filled in this element. * * * @default * '#000' * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_image.style.fill */ fill?: string | undefined; /** * Color of stroke. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_image.style.stroke */ stroke?: string | undefined; /** * Width of stroke. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_image.style.lineWidth */ lineWidth?: number | undefined; /** * Width of shadow. * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_image.style.shadowBlur */ shadowBlur?: number | undefined; /** * X offset of shadow. * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_image.style.shadowOffsetX */ shadowOffsetX?: number | undefined; /** * Y offset of shadow. * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_image.style.shadowOffsetY */ shadowOffsetY?: number | undefined; /** * color of shadow. * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_image.style.shadowColor */ shadowColor?: number | undefined; } | undefined; /** * Empahsis style of the graphic element, whose structure * is the same as * [style](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.style) * . * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_image.styleEmphasis */ styleEmphasis?: object | undefined; } /** * Text block. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_text */ interface RenderItemReturnText { /** * Must be specified when define a graphic element at the * first time. * * Optional values: * * [image](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_image) * , * [text](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_text) * , * [circle](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_circle) * , * [sector](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_sector) * , * [ring](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_ring) * , * [polygon](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon) * , * [polyline](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polyline) * , * [rect](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_rect) * , * [line](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_line) * , * [bezierCurve](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_bezierCurve) * , * [arc](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_arc) * , * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * , * * * @default * "text" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_text.type */ type?: string | undefined; /** * id is used to specifying element when willing to update * it. id can be ignored if you do not need it. * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_text.id */ id?: string | undefined; /** * `2D transform` can be applied to graphic elements, including: * * + [position](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.position) * : `[horizontal translate offset, vertical translate offset]`, * `[0, 0]` by default. * Positive value means translate towards right or bottom. * + [rotation](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.rotation) * : Rotation in radian, `0` by default. * Positive when anticlockwise. * + [scale](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.scale) * : `[horizontal scale factor, vertical scale factor]`, * `[1, 1]` by default. * * [origin](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.origin) * specifies the origin point of rotation and scaling, `[0, * 0]` by default. * * Notice: * * + The coordinates specified in the transform attribute * above are relative to the `[0, 0]` of the parent element * (that is, * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * or the root canvas). Thus we are able to * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * multiple elements, and * [groups](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * can be nested. * + The order that the transform attributes are applied * to a single graphic element is: Firstly, `rotation`, * then, `scale`, finally, `position`. * * * @default * [0, 0] * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_text.position */ position?: any[] | undefined; /** * `2D transform` can be applied to graphic elements, including: * * + [position](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.position) * : `[horizontal translate offset, vertical translate offset]`, * `[0, 0]` by default. * Positive value means translate towards right or bottom. * + [rotation](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.rotation) * : Rotation in radian, `0` by default. * Positive when anticlockwise. * + [scale](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.scale) * : `[horizontal scale factor, vertical scale factor]`, * `[1, 1]` by default. * * [origin](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.origin) * specifies the origin point of rotation and scaling, `[0, * 0]` by default. * * Notice: * * + The coordinates specified in the transform attribute * above are relative to the `[0, 0]` of the parent element * (that is, * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * or the root canvas). Thus we are able to * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * multiple elements, and * [groups](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * can be nested. * + The order that the transform attributes are applied * to a single graphic element is: Firstly, `rotation`, * then, `scale`, finally, `position`. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_text.rotation */ rotation?: number | undefined; /** * `2D transform` can be applied to graphic elements, including: * * + [position](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.position) * : `[horizontal translate offset, vertical translate offset]`, * `[0, 0]` by default. * Positive value means translate towards right or bottom. * + [rotation](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.rotation) * : Rotation in radian, `0` by default. * Positive when anticlockwise. * + [scale](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.scale) * : `[horizontal scale factor, vertical scale factor]`, * `[1, 1]` by default. * * [origin](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.origin) * specifies the origin point of rotation and scaling, `[0, * 0]` by default. * * Notice: * * + The coordinates specified in the transform attribute * above are relative to the `[0, 0]` of the parent element * (that is, * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * or the root canvas). Thus we are able to * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * multiple elements, and * [groups](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * can be nested. * + The order that the transform attributes are applied * to a single graphic element is: Firstly, `rotation`, * then, `scale`, finally, `position`. * * * @default * [1, 1] * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_text.scale */ scale?: any[] | undefined; /** * `2D transform` can be applied to graphic elements, including: * * + [position](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.position) * : `[horizontal translate offset, vertical translate offset]`, * `[0, 0]` by default. * Positive value means translate towards right or bottom. * + [rotation](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.rotation) * : Rotation in radian, `0` by default. * Positive when anticlockwise. * + [scale](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.scale) * : `[horizontal scale factor, vertical scale factor]`, * `[1, 1]` by default. * * [origin](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.origin) * specifies the origin point of rotation and scaling, `[0, * 0]` by default. * * Notice: * * + The coordinates specified in the transform attribute * above are relative to the `[0, 0]` of the parent element * (that is, * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * or the root canvas). Thus we are able to * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * multiple elements, and * [groups](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * can be nested. * + The order that the transform attributes are applied * to a single graphic element is: Firstly, `rotation`, * then, `scale`, finally, `position`. * * * @default * [0, 0] * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_text.origin */ origin?: number | undefined; /** * Define the overlap relationship between graphic elements. * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_text.z2 */ z2?: number | undefined; /** * See * [diffChildrenByName](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.diffChildrenByName) * 。 * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_text.name */ name?: string | undefined; /** * User defined data, can be visited in event listeners. * * [see doc](https://echarts.apache.org/en/option.html#series-custom.custom.renderItem.return_text) * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_text.info */ info?: any; /** * Whether response to mouse events / touch events. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_text.silent */ silent?: boolean | undefined; /** * Whether the element is visible. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_text.invisible */ invisible?: boolean | undefined; /** * Whether the element is totally ignored (neither render * nor listen events). * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_text.ignore */ ignore?: boolean | undefined; /** * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_text.style */ style?: { /** * Text content. `\n` can be used as a line break. * * * @default * '' * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_text.style.text */ text?: string | undefined; /** * The x value of the left-top corner of the element * in the coordinate system of its parent. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_text.style.x */ x?: number | undefined; /** * The y value of the left-top corner of the element * in the coordinate system of its parent. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_text.style.y */ y?: number | undefined; /** * Font size, font type, font weight, font color, follow * the form of * [css font](https://developer.mozilla.org/en-US/docs/Web/CSS/font) * . * * For example: * * [see doc](https://echarts.apache.org/en/option.html#series-custom.custom.renderItem.return_text.style) * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_text.style.font */ font?: string | undefined; /** * Text horizontal alignment. * Optional values: `'left'`, `'center'`, `'right'`. * * `'left'` means the left side of the text block is * specified by the * [style.x](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_text.style.x) * , while `'right'` means the right side of the text * block is specified by * [style.y](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_text.style.y) * . * * * @default * "left" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_text.style.textAlign */ textAlign?: string | undefined; /** * Text vertical alignment. * Optional values: `'top'`, `'middle'`, `'bottom'`. * * More attributes in `style` (for example, * [rich text](https://echarts.apache.org/en/tutorial.html#Rich%20Text) * ), see the `style` related attributes in * [zrender/graphic/Displayable](https://ecomfe.github.io/zrender-doc/public/api.html#zrenderdisplayable) * . * * Notice, the attribute names of the `style` of graphic * elements is derived from `zrender`, which may be * different from the attribute names in `echarts label`, * `echarts itemStyle`, etc., * although they have the same meaning. For example: * * + [itemStyle.color](https://echarts.apache.org/en/option.html#series-scatter.label.color) * => `style.fill` * + [itemStyle.borderColor](https://echarts.apache.org/en/option.html#series-scatter.label.color) * => `style.stroke` * + [label.color](https://echarts.apache.org/en/option.html#series-scatter.label.color) * => `style.textFill` * + [label.textBorderColor](https://echarts.apache.org/en/option.html#series-scatter.label.textBorderColor) * => `style.textStroke` * + ... * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_text.style.textVerticalAlign */ textVerticalAlign?: string | undefined; /** * Color filled in this element. * * * @default * '#000' * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_text.style.fill */ fill?: string | undefined; /** * Color of stroke. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_text.style.stroke */ stroke?: string | undefined; /** * Width of stroke. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_text.style.lineWidth */ lineWidth?: number | undefined; /** * Width of shadow. * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_text.style.shadowBlur */ shadowBlur?: number | undefined; /** * X offset of shadow. * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_text.style.shadowOffsetX */ shadowOffsetX?: number | undefined; /** * Y offset of shadow. * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_text.style.shadowOffsetY */ shadowOffsetY?: number | undefined; /** * color of shadow. * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_text.style.shadowColor */ shadowColor?: number | undefined; } | undefined; /** * Empahsis style of the graphic element, whose structure * is the same as * [style](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.style) * . * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_text.styleEmphasis */ styleEmphasis?: object | undefined; } /** * Rectangle element. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_rect */ interface RenderItemReturnRect { /** * Must be specified when define a graphic element at the * first time. * * Optional values: * * [image](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_image) * , * [text](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_text) * , * [circle](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_circle) * , * [sector](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_sector) * , * [ring](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_ring) * , * [polygon](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon) * , * [polyline](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polyline) * , * [rect](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_rect) * , * [line](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_line) * , * [bezierCurve](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_bezierCurve) * , * [arc](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_arc) * , * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * , * * * @default * "rect" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_rect.type */ type?: string | undefined; /** * id is used to specifying element when willing to update * it. id can be ignored if you do not need it. * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_rect.id */ id?: string | undefined; /** * `2D transform` can be applied to graphic elements, including: * * + [position](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.position) * : `[horizontal translate offset, vertical translate offset]`, * `[0, 0]` by default. * Positive value means translate towards right or bottom. * + [rotation](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.rotation) * : Rotation in radian, `0` by default. * Positive when anticlockwise. * + [scale](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.scale) * : `[horizontal scale factor, vertical scale factor]`, * `[1, 1]` by default. * * [origin](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.origin) * specifies the origin point of rotation and scaling, `[0, * 0]` by default. * * Notice: * * + The coordinates specified in the transform attribute * above are relative to the `[0, 0]` of the parent element * (that is, * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * or the root canvas). Thus we are able to * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * multiple elements, and * [groups](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * can be nested. * + The order that the transform attributes are applied * to a single graphic element is: Firstly, `rotation`, * then, `scale`, finally, `position`. * * * @default * [0, 0] * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_rect.position */ position?: any[] | undefined; /** * `2D transform` can be applied to graphic elements, including: * * + [position](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.position) * : `[horizontal translate offset, vertical translate offset]`, * `[0, 0]` by default. * Positive value means translate towards right or bottom. * + [rotation](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.rotation) * : Rotation in radian, `0` by default. * Positive when anticlockwise. * + [scale](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.scale) * : `[horizontal scale factor, vertical scale factor]`, * `[1, 1]` by default. * * [origin](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.origin) * specifies the origin point of rotation and scaling, `[0, * 0]` by default. * * Notice: * * + The coordinates specified in the transform attribute * above are relative to the `[0, 0]` of the parent element * (that is, * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * or the root canvas). Thus we are able to * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * multiple elements, and * [groups](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * can be nested. * + The order that the transform attributes are applied * to a single graphic element is: Firstly, `rotation`, * then, `scale`, finally, `position`. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_rect.rotation */ rotation?: number | undefined; /** * `2D transform` can be applied to graphic elements, including: * * + [position](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.position) * : `[horizontal translate offset, vertical translate offset]`, * `[0, 0]` by default. * Positive value means translate towards right or bottom. * + [rotation](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.rotation) * : Rotation in radian, `0` by default. * Positive when anticlockwise. * + [scale](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.scale) * : `[horizontal scale factor, vertical scale factor]`, * `[1, 1]` by default. * * [origin](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.origin) * specifies the origin point of rotation and scaling, `[0, * 0]` by default. * * Notice: * * + The coordinates specified in the transform attribute * above are relative to the `[0, 0]` of the parent element * (that is, * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * or the root canvas). Thus we are able to * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * multiple elements, and * [groups](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * can be nested. * + The order that the transform attributes are applied * to a single graphic element is: Firstly, `rotation`, * then, `scale`, finally, `position`. * * * @default * [1, 1] * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_rect.scale */ scale?: any[] | undefined; /** * `2D transform` can be applied to graphic elements, including: * * + [position](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.position) * : `[horizontal translate offset, vertical translate offset]`, * `[0, 0]` by default. * Positive value means translate towards right or bottom. * + [rotation](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.rotation) * : Rotation in radian, `0` by default. * Positive when anticlockwise. * + [scale](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.scale) * : `[horizontal scale factor, vertical scale factor]`, * `[1, 1]` by default. * * [origin](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.origin) * specifies the origin point of rotation and scaling, `[0, * 0]` by default. * * Notice: * * + The coordinates specified in the transform attribute * above are relative to the `[0, 0]` of the parent element * (that is, * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * or the root canvas). Thus we are able to * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * multiple elements, and * [groups](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * can be nested. * + The order that the transform attributes are applied * to a single graphic element is: Firstly, `rotation`, * then, `scale`, finally, `position`. * * * @default * [0, 0] * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_rect.origin */ origin?: number | undefined; /** * Define the overlap relationship between graphic elements. * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_rect.z2 */ z2?: number | undefined; /** * See * [diffChildrenByName](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.diffChildrenByName) * 。 * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_rect.name */ name?: string | undefined; /** * User defined data, can be visited in event listeners. * * [see doc](https://echarts.apache.org/en/option.html#series-custom.custom.renderItem.return_rect) * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_rect.info */ info?: any; /** * Whether response to mouse events / touch events. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_rect.silent */ silent?: boolean | undefined; /** * Whether the element is visible. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_rect.invisible */ invisible?: boolean | undefined; /** * Whether the element is totally ignored (neither render * nor listen events). * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_rect.ignore */ ignore?: boolean | undefined; /** * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_rect.shape */ shape?: { /** * The x value of the left-top corner of the element * in the coordinate system of its parent. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_rect.shape.x */ x?: number | undefined; /** * The y value of the left-top corner of the element * in the coordinate system of its parent. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_rect.shape.y */ y?: number | undefined; /** * The width of the shape of the element. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_rect.shape.width */ width?: number | undefined; /** * The height of the shape of the element. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_rect.shape.height */ height?: number | undefined; /** * Specify border radius of the rectangular here. * Generally, `r` should be `[topLeftRadius, topRightRadius, * BottomRightRadius, bottomLeftRadius]`, where each * item is a number. * * Abbreviation is enabled, for example: * * + `r`: `1` means `[1, 1, 1, 1]` * + `r`: `[1]` means `[1, 1, 1, 1]` * + `r`: `[1, 2]` means `[1, 2, 1, 2]` * + `r`: `[1, 2, 3]` means `[1, 2, 3, 2]` * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_rect.shape.r */ r?: any[] | undefined; } | undefined; /** * More attributes in `style` (for example, * [rich text](https://echarts.apache.org/en/tutorial.html#Rich%20Text) * ), see the `style` related attributes in * [zrender/graphic/Displayable](https://ecomfe.github.io/zrender-doc/public/api.html#zrenderdisplayable) * . * * Notice, the attribute names of the `style` of graphic * elements is derived from `zrender`, which may be different * from the attribute names in `echarts label`, `echarts * itemStyle`, etc., * although they have the same meaning. For example: * * + [itemStyle.color](https://echarts.apache.org/en/option.html#series-scatter.label.color) * => `style.fill` * + [itemStyle.borderColor](https://echarts.apache.org/en/option.html#series-scatter.label.color) * => `style.stroke` * + [label.color](https://echarts.apache.org/en/option.html#series-scatter.label.color) * => `style.textFill` * + [label.textBorderColor](https://echarts.apache.org/en/option.html#series-scatter.label.textBorderColor) * => `style.textStroke` * + ... * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_rect.style */ style?: { /** * Color filled in this element. * * * @default * '#000' * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_rect.style.fill */ fill?: string | undefined; /** * Color of stroke. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_rect.style.stroke */ stroke?: string | undefined; /** * Width of stroke. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_rect.style.lineWidth */ lineWidth?: number | undefined; /** * Width of shadow. * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_rect.style.shadowBlur */ shadowBlur?: number | undefined; /** * X offset of shadow. * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_rect.style.shadowOffsetX */ shadowOffsetX?: number | undefined; /** * Y offset of shadow. * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_rect.style.shadowOffsetY */ shadowOffsetY?: number | undefined; /** * color of shadow. * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_rect.style.shadowColor */ shadowColor?: number | undefined; } | undefined; /** * Empahsis style of the graphic element, whose structure * is the same as * [style](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.style) * . * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_rect.styleEmphasis */ styleEmphasis?: object | undefined; } /** * Circle element. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_circle */ interface RenderItemReturnCircle { /** * Must be specified when define a graphic element at the * first time. * * Optional values: * * [image](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_image) * , * [text](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_text) * , * [circle](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_circle) * , * [sector](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_sector) * , * [ring](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_ring) * , * [polygon](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon) * , * [polyline](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polyline) * , * [rect](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_rect) * , * [line](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_line) * , * [bezierCurve](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_bezierCurve) * , * [arc](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_arc) * , * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * , * * * @default * "circle" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_circle.type */ type?: string | undefined; /** * id is used to specifying element when willing to update * it. id can be ignored if you do not need it. * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_circle.id */ id?: string | undefined; /** * `2D transform` can be applied to graphic elements, including: * * + [position](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.position) * : `[horizontal translate offset, vertical translate offset]`, * `[0, 0]` by default. * Positive value means translate towards right or bottom. * + [rotation](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.rotation) * : Rotation in radian, `0` by default. * Positive when anticlockwise. * + [scale](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.scale) * : `[horizontal scale factor, vertical scale factor]`, * `[1, 1]` by default. * * [origin](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.origin) * specifies the origin point of rotation and scaling, `[0, * 0]` by default. * * Notice: * * + The coordinates specified in the transform attribute * above are relative to the `[0, 0]` of the parent element * (that is, * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * or the root canvas). Thus we are able to * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * multiple elements, and * [groups](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * can be nested. * + The order that the transform attributes are applied * to a single graphic element is: Firstly, `rotation`, * then, `scale`, finally, `position`. * * * @default * [0, 0] * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_circle.position */ position?: any[] | undefined; /** * `2D transform` can be applied to graphic elements, including: * * + [position](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.position) * : `[horizontal translate offset, vertical translate offset]`, * `[0, 0]` by default. * Positive value means translate towards right or bottom. * + [rotation](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.rotation) * : Rotation in radian, `0` by default. * Positive when anticlockwise. * + [scale](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.scale) * : `[horizontal scale factor, vertical scale factor]`, * `[1, 1]` by default. * * [origin](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.origin) * specifies the origin point of rotation and scaling, `[0, * 0]` by default. * * Notice: * * + The coordinates specified in the transform attribute * above are relative to the `[0, 0]` of the parent element * (that is, * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * or the root canvas). Thus we are able to * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * multiple elements, and * [groups](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * can be nested. * + The order that the transform attributes are applied * to a single graphic element is: Firstly, `rotation`, * then, `scale`, finally, `position`. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_circle.rotation */ rotation?: number | undefined; /** * `2D transform` can be applied to graphic elements, including: * * + [position](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.position) * : `[horizontal translate offset, vertical translate offset]`, * `[0, 0]` by default. * Positive value means translate towards right or bottom. * + [rotation](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.rotation) * : Rotation in radian, `0` by default. * Positive when anticlockwise. * + [scale](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.scale) * : `[horizontal scale factor, vertical scale factor]`, * `[1, 1]` by default. * * [origin](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.origin) * specifies the origin point of rotation and scaling, `[0, * 0]` by default. * * Notice: * * + The coordinates specified in the transform attribute * above are relative to the `[0, 0]` of the parent element * (that is, * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * or the root canvas). Thus we are able to * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * multiple elements, and * [groups](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * can be nested. * + The order that the transform attributes are applied * to a single graphic element is: Firstly, `rotation`, * then, `scale`, finally, `position`. * * * @default * [1, 1] * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_circle.scale */ scale?: any[] | undefined; /** * `2D transform` can be applied to graphic elements, including: * * + [position](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.position) * : `[horizontal translate offset, vertical translate offset]`, * `[0, 0]` by default. * Positive value means translate towards right or bottom. * + [rotation](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.rotation) * : Rotation in radian, `0` by default. * Positive when anticlockwise. * + [scale](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.scale) * : `[horizontal scale factor, vertical scale factor]`, * `[1, 1]` by default. * * [origin](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.origin) * specifies the origin point of rotation and scaling, `[0, * 0]` by default. * * Notice: * * + The coordinates specified in the transform attribute * above are relative to the `[0, 0]` of the parent element * (that is, * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * or the root canvas). Thus we are able to * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * multiple elements, and * [groups](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * can be nested. * + The order that the transform attributes are applied * to a single graphic element is: Firstly, `rotation`, * then, `scale`, finally, `position`. * * * @default * [0, 0] * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_circle.origin */ origin?: number | undefined; /** * Define the overlap relationship between graphic elements. * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_circle.z2 */ z2?: number | undefined; /** * See * [diffChildrenByName](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.diffChildrenByName) * 。 * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_circle.name */ name?: string | undefined; /** * User defined data, can be visited in event listeners. * * [see doc](https://echarts.apache.org/en/option.html#series-custom.custom.renderItem.return_circle) * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_circle.info */ info?: any; /** * Whether response to mouse events / touch events. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_circle.silent */ silent?: boolean | undefined; /** * Whether the element is visible. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_circle.invisible */ invisible?: boolean | undefined; /** * Whether the element is totally ignored (neither render * nor listen events). * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_circle.ignore */ ignore?: boolean | undefined; /** * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_circle.shape */ shape?: { /** * The x value of the center of the element in the coordinate * system of its parent. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_circle.shape.cx */ cx?: number | undefined; /** * The y value of the center of the element in the coordinate * system of its parent. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_circle.shape.cy */ cy?: number | undefined; /** * Outside radius. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_circle.shape.r */ r?: number | undefined; } | undefined; /** * More attributes in `style` (for example, * [rich text](https://echarts.apache.org/en/tutorial.html#Rich%20Text) * ), see the `style` related attributes in * [zrender/graphic/Displayable](https://ecomfe.github.io/zrender-doc/public/api.html#zrenderdisplayable) * . * * Notice, the attribute names of the `style` of graphic * elements is derived from `zrender`, which may be different * from the attribute names in `echarts label`, `echarts * itemStyle`, etc., * although they have the same meaning. For example: * * + [itemStyle.color](https://echarts.apache.org/en/option.html#series-scatter.label.color) * => `style.fill` * + [itemStyle.borderColor](https://echarts.apache.org/en/option.html#series-scatter.label.color) * => `style.stroke` * + [label.color](https://echarts.apache.org/en/option.html#series-scatter.label.color) * => `style.textFill` * + [label.textBorderColor](https://echarts.apache.org/en/option.html#series-scatter.label.textBorderColor) * => `style.textStroke` * + ... * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_circle.style */ style?: { /** * Color filled in this element. * * * @default * '#000' * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_circle.style.fill */ fill?: string | undefined; /** * Color of stroke. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_circle.style.stroke */ stroke?: string | undefined; /** * Width of stroke. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_circle.style.lineWidth */ lineWidth?: number | undefined; /** * Width of shadow. * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_circle.style.shadowBlur */ shadowBlur?: number | undefined; /** * X offset of shadow. * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_circle.style.shadowOffsetX */ shadowOffsetX?: number | undefined; /** * Y offset of shadow. * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_circle.style.shadowOffsetY */ shadowOffsetY?: number | undefined; /** * color of shadow. * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_circle.style.shadowColor */ shadowColor?: number | undefined; } | undefined; /** * Empahsis style of the graphic element, whose structure * is the same as * [style](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.style) * . * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_circle.styleEmphasis */ styleEmphasis?: object | undefined; } /** * Ring element. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_ring */ interface RenderItemReturnRing { /** * Must be specified when define a graphic element at the * first time. * * Optional values: * * [image](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_image) * , * [text](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_text) * , * [circle](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_circle) * , * [sector](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_sector) * , * [ring](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_ring) * , * [polygon](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon) * , * [polyline](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polyline) * , * [rect](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_rect) * , * [line](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_line) * , * [bezierCurve](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_bezierCurve) * , * [arc](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_arc) * , * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * , * * * @default * "ring" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_ring.type */ type?: string | undefined; /** * id is used to specifying element when willing to update * it. id can be ignored if you do not need it. * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_ring.id */ id?: string | undefined; /** * `2D transform` can be applied to graphic elements, including: * * + [position](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.position) * : `[horizontal translate offset, vertical translate offset]`, * `[0, 0]` by default. * Positive value means translate towards right or bottom. * + [rotation](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.rotation) * : Rotation in radian, `0` by default. * Positive when anticlockwise. * + [scale](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.scale) * : `[horizontal scale factor, vertical scale factor]`, * `[1, 1]` by default. * * [origin](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.origin) * specifies the origin point of rotation and scaling, `[0, * 0]` by default. * * Notice: * * + The coordinates specified in the transform attribute * above are relative to the `[0, 0]` of the parent element * (that is, * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * or the root canvas). Thus we are able to * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * multiple elements, and * [groups](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * can be nested. * + The order that the transform attributes are applied * to a single graphic element is: Firstly, `rotation`, * then, `scale`, finally, `position`. * * * @default * [0, 0] * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_ring.position */ position?: any[] | undefined; /** * `2D transform` can be applied to graphic elements, including: * * + [position](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.position) * : `[horizontal translate offset, vertical translate offset]`, * `[0, 0]` by default. * Positive value means translate towards right or bottom. * + [rotation](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.rotation) * : Rotation in radian, `0` by default. * Positive when anticlockwise. * + [scale](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.scale) * : `[horizontal scale factor, vertical scale factor]`, * `[1, 1]` by default. * * [origin](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.origin) * specifies the origin point of rotation and scaling, `[0, * 0]` by default. * * Notice: * * + The coordinates specified in the transform attribute * above are relative to the `[0, 0]` of the parent element * (that is, * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * or the root canvas). Thus we are able to * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * multiple elements, and * [groups](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * can be nested. * + The order that the transform attributes are applied * to a single graphic element is: Firstly, `rotation`, * then, `scale`, finally, `position`. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_ring.rotation */ rotation?: number | undefined; /** * `2D transform` can be applied to graphic elements, including: * * + [position](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.position) * : `[horizontal translate offset, vertical translate offset]`, * `[0, 0]` by default. * Positive value means translate towards right or bottom. * + [rotation](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.rotation) * : Rotation in radian, `0` by default. * Positive when anticlockwise. * + [scale](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.scale) * : `[horizontal scale factor, vertical scale factor]`, * `[1, 1]` by default. * * [origin](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.origin) * specifies the origin point of rotation and scaling, `[0, * 0]` by default. * * Notice: * * + The coordinates specified in the transform attribute * above are relative to the `[0, 0]` of the parent element * (that is, * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * or the root canvas). Thus we are able to * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * multiple elements, and * [groups](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * can be nested. * + The order that the transform attributes are applied * to a single graphic element is: Firstly, `rotation`, * then, `scale`, finally, `position`. * * * @default * [1, 1] * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_ring.scale */ scale?: any[] | undefined; /** * `2D transform` can be applied to graphic elements, including: * * + [position](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.position) * : `[horizontal translate offset, vertical translate offset]`, * `[0, 0]` by default. * Positive value means translate towards right or bottom. * + [rotation](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.rotation) * : Rotation in radian, `0` by default. * Positive when anticlockwise. * + [scale](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.scale) * : `[horizontal scale factor, vertical scale factor]`, * `[1, 1]` by default. * * [origin](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.origin) * specifies the origin point of rotation and scaling, `[0, * 0]` by default. * * Notice: * * + The coordinates specified in the transform attribute * above are relative to the `[0, 0]` of the parent element * (that is, * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * or the root canvas). Thus we are able to * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * multiple elements, and * [groups](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * can be nested. * + The order that the transform attributes are applied * to a single graphic element is: Firstly, `rotation`, * then, `scale`, finally, `position`. * * * @default * [0, 0] * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_ring.origin */ origin?: number | undefined; /** * Define the overlap relationship between graphic elements. * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_ring.z2 */ z2?: number | undefined; /** * See * [diffChildrenByName](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.diffChildrenByName) * 。 * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_ring.name */ name?: string | undefined; /** * User defined data, can be visited in event listeners. * * [see doc](https://echarts.apache.org/en/option.html#series-custom.custom.renderItem.return_ring) * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_ring.info */ info?: any; /** * Whether response to mouse events / touch events. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_ring.silent */ silent?: boolean | undefined; /** * Whether the element is visible. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_ring.invisible */ invisible?: boolean | undefined; /** * Whether the element is totally ignored (neither render * nor listen events). * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_ring.ignore */ ignore?: boolean | undefined; /** * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_ring.shape */ shape?: { /** * The x value of the center of the element in the coordinate * system of its parent. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_ring.shape.cx */ cx?: number | undefined; /** * The y value of the center of the element in the coordinate * system of its parent. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_ring.shape.cy */ cy?: number | undefined; /** * Outside radius. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_ring.shape.r */ r?: number | undefined; /** * Inside radius. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_ring.shape.r0 */ r0?: number | undefined; } | undefined; /** * More attributes in `style` (for example, * [rich text](https://echarts.apache.org/en/tutorial.html#Rich%20Text) * ), see the `style` related attributes in * [zrender/graphic/Displayable](https://ecomfe.github.io/zrender-doc/public/api.html#zrenderdisplayable) * . * * Notice, the attribute names of the `style` of graphic * elements is derived from `zrender`, which may be different * from the attribute names in `echarts label`, `echarts * itemStyle`, etc., * although they have the same meaning. For example: * * + [itemStyle.color](https://echarts.apache.org/en/option.html#series-scatter.label.color) * => `style.fill` * + [itemStyle.borderColor](https://echarts.apache.org/en/option.html#series-scatter.label.color) * => `style.stroke` * + [label.color](https://echarts.apache.org/en/option.html#series-scatter.label.color) * => `style.textFill` * + [label.textBorderColor](https://echarts.apache.org/en/option.html#series-scatter.label.textBorderColor) * => `style.textStroke` * + ... * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_ring.style */ style?: { /** * Color filled in this element. * * * @default * '#000' * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_ring.style.fill */ fill?: string | undefined; /** * Color of stroke. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_ring.style.stroke */ stroke?: string | undefined; /** * Width of stroke. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_ring.style.lineWidth */ lineWidth?: number | undefined; /** * Width of shadow. * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_ring.style.shadowBlur */ shadowBlur?: number | undefined; /** * X offset of shadow. * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_ring.style.shadowOffsetX */ shadowOffsetX?: number | undefined; /** * Y offset of shadow. * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_ring.style.shadowOffsetY */ shadowOffsetY?: number | undefined; /** * color of shadow. * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_ring.style.shadowColor */ shadowColor?: number | undefined; } | undefined; /** * Empahsis style of the graphic element, whose structure * is the same as * [style](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.style) * . * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_ring.styleEmphasis */ styleEmphasis?: object | undefined; } /** * Sector element. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_sector */ interface RenderItemReturnSector { /** * Must be specified when define a graphic element at the * first time. * * Optional values: * * [image](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_image) * , * [text](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_text) * , * [circle](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_circle) * , * [sector](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_sector) * , * [ring](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_ring) * , * [polygon](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon) * , * [polyline](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polyline) * , * [rect](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_rect) * , * [line](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_line) * , * [bezierCurve](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_bezierCurve) * , * [arc](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_arc) * , * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * , * * * @default * "sector" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_sector.type */ type?: string | undefined; /** * id is used to specifying element when willing to update * it. id can be ignored if you do not need it. * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_sector.id */ id?: string | undefined; /** * `2D transform` can be applied to graphic elements, including: * * + [position](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.position) * : `[horizontal translate offset, vertical translate offset]`, * `[0, 0]` by default. * Positive value means translate towards right or bottom. * + [rotation](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.rotation) * : Rotation in radian, `0` by default. * Positive when anticlockwise. * + [scale](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.scale) * : `[horizontal scale factor, vertical scale factor]`, * `[1, 1]` by default. * * [origin](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.origin) * specifies the origin point of rotation and scaling, `[0, * 0]` by default. * * Notice: * * + The coordinates specified in the transform attribute * above are relative to the `[0, 0]` of the parent element * (that is, * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * or the root canvas). Thus we are able to * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * multiple elements, and * [groups](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * can be nested. * + The order that the transform attributes are applied * to a single graphic element is: Firstly, `rotation`, * then, `scale`, finally, `position`. * * * @default * [0, 0] * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_sector.position */ position?: any[] | undefined; /** * `2D transform` can be applied to graphic elements, including: * * + [position](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.position) * : `[horizontal translate offset, vertical translate offset]`, * `[0, 0]` by default. * Positive value means translate towards right or bottom. * + [rotation](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.rotation) * : Rotation in radian, `0` by default. * Positive when anticlockwise. * + [scale](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.scale) * : `[horizontal scale factor, vertical scale factor]`, * `[1, 1]` by default. * * [origin](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.origin) * specifies the origin point of rotation and scaling, `[0, * 0]` by default. * * Notice: * * + The coordinates specified in the transform attribute * above are relative to the `[0, 0]` of the parent element * (that is, * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * or the root canvas). Thus we are able to * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * multiple elements, and * [groups](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * can be nested. * + The order that the transform attributes are applied * to a single graphic element is: Firstly, `rotation`, * then, `scale`, finally, `position`. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_sector.rotation */ rotation?: number | undefined; /** * `2D transform` can be applied to graphic elements, including: * * + [position](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.position) * : `[horizontal translate offset, vertical translate offset]`, * `[0, 0]` by default. * Positive value means translate towards right or bottom. * + [rotation](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.rotation) * : Rotation in radian, `0` by default. * Positive when anticlockwise. * + [scale](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.scale) * : `[horizontal scale factor, vertical scale factor]`, * `[1, 1]` by default. * * [origin](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.origin) * specifies the origin point of rotation and scaling, `[0, * 0]` by default. * * Notice: * * + The coordinates specified in the transform attribute * above are relative to the `[0, 0]` of the parent element * (that is, * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * or the root canvas). Thus we are able to * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * multiple elements, and * [groups](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * can be nested. * + The order that the transform attributes are applied * to a single graphic element is: Firstly, `rotation`, * then, `scale`, finally, `position`. * * * @default * [1, 1] * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_sector.scale */ scale?: any[] | undefined; /** * `2D transform` can be applied to graphic elements, including: * * + [position](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.position) * : `[horizontal translate offset, vertical translate offset]`, * `[0, 0]` by default. * Positive value means translate towards right or bottom. * + [rotation](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.rotation) * : Rotation in radian, `0` by default. * Positive when anticlockwise. * + [scale](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.scale) * : `[horizontal scale factor, vertical scale factor]`, * `[1, 1]` by default. * * [origin](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.origin) * specifies the origin point of rotation and scaling, `[0, * 0]` by default. * * Notice: * * + The coordinates specified in the transform attribute * above are relative to the `[0, 0]` of the parent element * (that is, * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * or the root canvas). Thus we are able to * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * multiple elements, and * [groups](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * can be nested. * + The order that the transform attributes are applied * to a single graphic element is: Firstly, `rotation`, * then, `scale`, finally, `position`. * * * @default * [0, 0] * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_sector.origin */ origin?: number | undefined; /** * Define the overlap relationship between graphic elements. * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_sector.z2 */ z2?: number | undefined; /** * See * [diffChildrenByName](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.diffChildrenByName) * 。 * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_sector.name */ name?: string | undefined; /** * User defined data, can be visited in event listeners. * * [see doc](https://echarts.apache.org/en/option.html#series-custom.custom.renderItem.return_sector) * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_sector.info */ info?: any; /** * Whether response to mouse events / touch events. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_sector.silent */ silent?: boolean | undefined; /** * Whether the element is visible. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_sector.invisible */ invisible?: boolean | undefined; /** * Whether the element is totally ignored (neither render * nor listen events). * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_sector.ignore */ ignore?: boolean | undefined; /** * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_sector.shape */ shape?: { /** * The x value of the center of the element in the coordinate * system of its parent. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_sector.shape.cx */ cx?: number | undefined; /** * The y value of the center of the element in the coordinate * system of its parent. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_sector.shape.cy */ cy?: number | undefined; /** * Outside radius. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_sector.shape.r */ r?: number | undefined; /** * Inside radius. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_sector.shape.r0 */ r0?: number | undefined; /** * start angle, in radian. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_sector.shape.startAngle */ startAngle?: number | undefined; /** * end anble, in radian. * * * @default * "Math.PI * 2" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_sector.shape.endAngle */ endAngle?: number | undefined; /** * Whether draw clockwise. * * * @default * "true" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_sector.shape.clockwise */ clockwise?: boolean | undefined; } | undefined; /** * More attributes in `style` (for example, * [rich text](https://echarts.apache.org/en/tutorial.html#Rich%20Text) * ), see the `style` related attributes in * [zrender/graphic/Displayable](https://ecomfe.github.io/zrender-doc/public/api.html#zrenderdisplayable) * . * * Notice, the attribute names of the `style` of graphic * elements is derived from `zrender`, which may be different * from the attribute names in `echarts label`, `echarts * itemStyle`, etc., * although they have the same meaning. For example: * * + [itemStyle.color](https://echarts.apache.org/en/option.html#series-scatter.label.color) * => `style.fill` * + [itemStyle.borderColor](https://echarts.apache.org/en/option.html#series-scatter.label.color) * => `style.stroke` * + [label.color](https://echarts.apache.org/en/option.html#series-scatter.label.color) * => `style.textFill` * + [label.textBorderColor](https://echarts.apache.org/en/option.html#series-scatter.label.textBorderColor) * => `style.textStroke` * + ... * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_sector.style */ style?: { /** * Color filled in this element. * * * @default * '#000' * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_sector.style.fill */ fill?: string | undefined; /** * Color of stroke. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_sector.style.stroke */ stroke?: string | undefined; /** * Width of stroke. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_sector.style.lineWidth */ lineWidth?: number | undefined; /** * Width of shadow. * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_sector.style.shadowBlur */ shadowBlur?: number | undefined; /** * X offset of shadow. * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_sector.style.shadowOffsetX */ shadowOffsetX?: number | undefined; /** * Y offset of shadow. * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_sector.style.shadowOffsetY */ shadowOffsetY?: number | undefined; /** * color of shadow. * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_sector.style.shadowColor */ shadowColor?: number | undefined; } | undefined; /** * Empahsis style of the graphic element, whose structure * is the same as * [style](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.style) * . * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_sector.styleEmphasis */ styleEmphasis?: object | undefined; } /** * Arc element. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_arc */ interface RenderItemReturnArc { /** * Must be specified when define a graphic element at the * first time. * * Optional values: * * [image](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_image) * , * [text](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_text) * , * [circle](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_circle) * , * [sector](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_sector) * , * [ring](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_ring) * , * [polygon](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon) * , * [polyline](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polyline) * , * [rect](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_rect) * , * [line](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_line) * , * [bezierCurve](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_bezierCurve) * , * [arc](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_arc) * , * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * , * * * @default * "arc" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_arc.type */ type?: string | undefined; /** * id is used to specifying element when willing to update * it. id can be ignored if you do not need it. * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_arc.id */ id?: string | undefined; /** * `2D transform` can be applied to graphic elements, including: * * + [position](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.position) * : `[horizontal translate offset, vertical translate offset]`, * `[0, 0]` by default. * Positive value means translate towards right or bottom. * + [rotation](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.rotation) * : Rotation in radian, `0` by default. * Positive when anticlockwise. * + [scale](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.scale) * : `[horizontal scale factor, vertical scale factor]`, * `[1, 1]` by default. * * [origin](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.origin) * specifies the origin point of rotation and scaling, `[0, * 0]` by default. * * Notice: * * + The coordinates specified in the transform attribute * above are relative to the `[0, 0]` of the parent element * (that is, * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * or the root canvas). Thus we are able to * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * multiple elements, and * [groups](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * can be nested. * + The order that the transform attributes are applied * to a single graphic element is: Firstly, `rotation`, * then, `scale`, finally, `position`. * * * @default * [0, 0] * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_arc.position */ position?: any[] | undefined; /** * `2D transform` can be applied to graphic elements, including: * * + [position](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.position) * : `[horizontal translate offset, vertical translate offset]`, * `[0, 0]` by default. * Positive value means translate towards right or bottom. * + [rotation](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.rotation) * : Rotation in radian, `0` by default. * Positive when anticlockwise. * + [scale](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.scale) * : `[horizontal scale factor, vertical scale factor]`, * `[1, 1]` by default. * * [origin](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.origin) * specifies the origin point of rotation and scaling, `[0, * 0]` by default. * * Notice: * * + The coordinates specified in the transform attribute * above are relative to the `[0, 0]` of the parent element * (that is, * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * or the root canvas). Thus we are able to * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * multiple elements, and * [groups](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * can be nested. * + The order that the transform attributes are applied * to a single graphic element is: Firstly, `rotation`, * then, `scale`, finally, `position`. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_arc.rotation */ rotation?: number | undefined; /** * `2D transform` can be applied to graphic elements, including: * * + [position](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.position) * : `[horizontal translate offset, vertical translate offset]`, * `[0, 0]` by default. * Positive value means translate towards right or bottom. * + [rotation](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.rotation) * : Rotation in radian, `0` by default. * Positive when anticlockwise. * + [scale](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.scale) * : `[horizontal scale factor, vertical scale factor]`, * `[1, 1]` by default. * * [origin](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.origin) * specifies the origin point of rotation and scaling, `[0, * 0]` by default. * * Notice: * * + The coordinates specified in the transform attribute * above are relative to the `[0, 0]` of the parent element * (that is, * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * or the root canvas). Thus we are able to * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * multiple elements, and * [groups](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * can be nested. * + The order that the transform attributes are applied * to a single graphic element is: Firstly, `rotation`, * then, `scale`, finally, `position`. * * * @default * [1, 1] * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_arc.scale */ scale?: any[] | undefined; /** * `2D transform` can be applied to graphic elements, including: * * + [position](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.position) * : `[horizontal translate offset, vertical translate offset]`, * `[0, 0]` by default. * Positive value means translate towards right or bottom. * + [rotation](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.rotation) * : Rotation in radian, `0` by default. * Positive when anticlockwise. * + [scale](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.scale) * : `[horizontal scale factor, vertical scale factor]`, * `[1, 1]` by default. * * [origin](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.origin) * specifies the origin point of rotation and scaling, `[0, * 0]` by default. * * Notice: * * + The coordinates specified in the transform attribute * above are relative to the `[0, 0]` of the parent element * (that is, * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * or the root canvas). Thus we are able to * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * multiple elements, and * [groups](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * can be nested. * + The order that the transform attributes are applied * to a single graphic element is: Firstly, `rotation`, * then, `scale`, finally, `position`. * * * @default * [0, 0] * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_arc.origin */ origin?: number | undefined; /** * Define the overlap relationship between graphic elements. * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_arc.z2 */ z2?: number | undefined; /** * See * [diffChildrenByName](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.diffChildrenByName) * 。 * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_arc.name */ name?: string | undefined; /** * User defined data, can be visited in event listeners. * * [see doc](https://echarts.apache.org/en/option.html#series-custom.custom.renderItem.return_arc) * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_arc.info */ info?: any; /** * Whether response to mouse events / touch events. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_arc.silent */ silent?: boolean | undefined; /** * Whether the element is visible. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_arc.invisible */ invisible?: boolean | undefined; /** * Whether the element is totally ignored (neither render * nor listen events). * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_arc.ignore */ ignore?: boolean | undefined; /** * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_arc.shape */ shape?: { /** * The x value of the center of the element in the coordinate * system of its parent. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_arc.shape.cx */ cx?: number | undefined; /** * The y value of the center of the element in the coordinate * system of its parent. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_arc.shape.cy */ cy?: number | undefined; /** * Outside radius. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_arc.shape.r */ r?: number | undefined; /** * Inside radius. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_arc.shape.r0 */ r0?: number | undefined; /** * start angle, in radian. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_arc.shape.startAngle */ startAngle?: number | undefined; /** * end anble, in radian. * * * @default * "Math.PI * 2" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_arc.shape.endAngle */ endAngle?: number | undefined; /** * Whether draw clockwise. * * * @default * "true" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_arc.shape.clockwise */ clockwise?: boolean | undefined; } | undefined; /** * More attributes in `style` (for example, * [rich text](https://echarts.apache.org/en/tutorial.html#Rich%20Text) * ), see the `style` related attributes in * [zrender/graphic/Displayable](https://ecomfe.github.io/zrender-doc/public/api.html#zrenderdisplayable) * . * * Notice, the attribute names of the `style` of graphic * elements is derived from `zrender`, which may be different * from the attribute names in `echarts label`, `echarts * itemStyle`, etc., * although they have the same meaning. For example: * * + [itemStyle.color](https://echarts.apache.org/en/option.html#series-scatter.label.color) * => `style.fill` * + [itemStyle.borderColor](https://echarts.apache.org/en/option.html#series-scatter.label.color) * => `style.stroke` * + [label.color](https://echarts.apache.org/en/option.html#series-scatter.label.color) * => `style.textFill` * + [label.textBorderColor](https://echarts.apache.org/en/option.html#series-scatter.label.textBorderColor) * => `style.textStroke` * + ... * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_arc.style */ style?: { /** * Color filled in this element. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_arc.style.fill */ fill?: string | undefined; /** * Color of stroke. * * * @default * "#000" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_arc.style.stroke */ stroke?: string | undefined; /** * Width of stroke. * * * @default * 1 * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_arc.style.lineWidth */ lineWidth?: number | undefined; /** * Width of shadow. * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_arc.style.shadowBlur */ shadowBlur?: number | undefined; /** * X offset of shadow. * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_arc.style.shadowOffsetX */ shadowOffsetX?: number | undefined; /** * Y offset of shadow. * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_arc.style.shadowOffsetY */ shadowOffsetY?: number | undefined; /** * color of shadow. * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_arc.style.shadowColor */ shadowColor?: number | undefined; } | undefined; /** * Empahsis style of the graphic element, whose structure * is the same as * [style](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.style) * . * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_arc.styleEmphasis */ styleEmphasis?: object | undefined; } /** * Polygon element. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon */ interface RenderItemReturnPolygon { /** * Must be specified when define a graphic element at the * first time. * * Optional values: * * [image](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_image) * , * [text](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_text) * , * [circle](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_circle) * , * [sector](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_sector) * , * [ring](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_ring) * , * [polygon](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon) * , * [polyline](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polyline) * , * [rect](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_rect) * , * [line](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_line) * , * [bezierCurve](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_bezierCurve) * , * [arc](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_arc) * , * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * , * * * @default * "polygon" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.type */ type?: string | undefined; /** * id is used to specifying element when willing to update * it. id can be ignored if you do not need it. * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.id */ id?: string | undefined; /** * `2D transform` can be applied to graphic elements, including: * * + [position](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.position) * : `[horizontal translate offset, vertical translate offset]`, * `[0, 0]` by default. * Positive value means translate towards right or bottom. * + [rotation](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.rotation) * : Rotation in radian, `0` by default. * Positive when anticlockwise. * + [scale](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.scale) * : `[horizontal scale factor, vertical scale factor]`, * `[1, 1]` by default. * * [origin](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.origin) * specifies the origin point of rotation and scaling, `[0, * 0]` by default. * * Notice: * * + The coordinates specified in the transform attribute * above are relative to the `[0, 0]` of the parent element * (that is, * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * or the root canvas). Thus we are able to * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * multiple elements, and * [groups](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * can be nested. * + The order that the transform attributes are applied * to a single graphic element is: Firstly, `rotation`, * then, `scale`, finally, `position`. * * * @default * [0, 0] * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.position */ position?: any[] | undefined; /** * `2D transform` can be applied to graphic elements, including: * * + [position](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.position) * : `[horizontal translate offset, vertical translate offset]`, * `[0, 0]` by default. * Positive value means translate towards right or bottom. * + [rotation](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.rotation) * : Rotation in radian, `0` by default. * Positive when anticlockwise. * + [scale](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.scale) * : `[horizontal scale factor, vertical scale factor]`, * `[1, 1]` by default. * * [origin](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.origin) * specifies the origin point of rotation and scaling, `[0, * 0]` by default. * * Notice: * * + The coordinates specified in the transform attribute * above are relative to the `[0, 0]` of the parent element * (that is, * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * or the root canvas). Thus we are able to * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * multiple elements, and * [groups](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * can be nested. * + The order that the transform attributes are applied * to a single graphic element is: Firstly, `rotation`, * then, `scale`, finally, `position`. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.rotation */ rotation?: number | undefined; /** * `2D transform` can be applied to graphic elements, including: * * + [position](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.position) * : `[horizontal translate offset, vertical translate offset]`, * `[0, 0]` by default. * Positive value means translate towards right or bottom. * + [rotation](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.rotation) * : Rotation in radian, `0` by default. * Positive when anticlockwise. * + [scale](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.scale) * : `[horizontal scale factor, vertical scale factor]`, * `[1, 1]` by default. * * [origin](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.origin) * specifies the origin point of rotation and scaling, `[0, * 0]` by default. * * Notice: * * + The coordinates specified in the transform attribute * above are relative to the `[0, 0]` of the parent element * (that is, * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * or the root canvas). Thus we are able to * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * multiple elements, and * [groups](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * can be nested. * + The order that the transform attributes are applied * to a single graphic element is: Firstly, `rotation`, * then, `scale`, finally, `position`. * * * @default * [1, 1] * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.scale */ scale?: any[] | undefined; /** * `2D transform` can be applied to graphic elements, including: * * + [position](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.position) * : `[horizontal translate offset, vertical translate offset]`, * `[0, 0]` by default. * Positive value means translate towards right or bottom. * + [rotation](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.rotation) * : Rotation in radian, `0` by default. * Positive when anticlockwise. * + [scale](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.scale) * : `[horizontal scale factor, vertical scale factor]`, * `[1, 1]` by default. * * [origin](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.origin) * specifies the origin point of rotation and scaling, `[0, * 0]` by default. * * Notice: * * + The coordinates specified in the transform attribute * above are relative to the `[0, 0]` of the parent element * (that is, * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * or the root canvas). Thus we are able to * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * multiple elements, and * [groups](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * can be nested. * + The order that the transform attributes are applied * to a single graphic element is: Firstly, `rotation`, * then, `scale`, finally, `position`. * * * @default * [0, 0] * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.origin */ origin?: number | undefined; /** * Define the overlap relationship between graphic elements. * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.z2 */ z2?: number | undefined; /** * See * [diffChildrenByName](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.diffChildrenByName) * 。 * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.name */ name?: string | undefined; /** * User defined data, can be visited in event listeners. * * [see doc](https://echarts.apache.org/en/option.html#series-custom.custom.renderItem.return_polygon) * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.info */ info?: any; /** * Whether response to mouse events / touch events. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.silent */ silent?: boolean | undefined; /** * Whether the element is visible. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.invisible */ invisible?: boolean | undefined; /** * Whether the element is totally ignored (neither render * nor listen events). * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.ignore */ ignore?: boolean | undefined; /** * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.shape */ shape?: { /** * A list of points, which defines the shape, like `[[22, * 44], [44, 55], [11, 44], ...]`. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.shape.points */ points?: any[] | undefined; /** * Whether smooth the line. * * + If the value is number, bezier interpolation is * used, and the value specified the level of smooth, * which is in the range of `[0, 1]`. * + If the value is `'spline'`, Catmull-Rom spline * interpolation is used. * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.shape.smooth */ smooth?: number | string | undefined; /** * Whether prevent the smooth process cause the line * out of the bounding box. * * Only works when `smooth` is `number` (bezier smooth). * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.shape.smoothConstraint */ smoothConstraint?: boolean | undefined; } | undefined; /** * More attributes in `style` (for example, * [rich text](https://echarts.apache.org/en/tutorial.html#Rich%20Text) * ), see the `style` related attributes in * [zrender/graphic/Displayable](https://ecomfe.github.io/zrender-doc/public/api.html#zrenderdisplayable) * . * * Notice, the attribute names of the `style` of graphic * elements is derived from `zrender`, which may be different * from the attribute names in `echarts label`, `echarts * itemStyle`, etc., * although they have the same meaning. For example: * * + [itemStyle.color](https://echarts.apache.org/en/option.html#series-scatter.label.color) * => `style.fill` * + [itemStyle.borderColor](https://echarts.apache.org/en/option.html#series-scatter.label.color) * => `style.stroke` * + [label.color](https://echarts.apache.org/en/option.html#series-scatter.label.color) * => `style.textFill` * + [label.textBorderColor](https://echarts.apache.org/en/option.html#series-scatter.label.textBorderColor) * => `style.textStroke` * + ... * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.style */ style?: { /** * Color filled in this element. * * * @default * '#000' * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.style.fill */ fill?: string | undefined; /** * Color of stroke. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.style.stroke */ stroke?: string | undefined; /** * Width of stroke. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.style.lineWidth */ lineWidth?: number | undefined; /** * Width of shadow. * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.style.shadowBlur */ shadowBlur?: number | undefined; /** * X offset of shadow. * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.style.shadowOffsetX */ shadowOffsetX?: number | undefined; /** * Y offset of shadow. * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.style.shadowOffsetY */ shadowOffsetY?: number | undefined; /** * color of shadow. * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.style.shadowColor */ shadowColor?: number | undefined; } | undefined; /** * Empahsis style of the graphic element, whose structure * is the same as * [style](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.style) * . * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.styleEmphasis */ styleEmphasis?: object | undefined; } /** * Polyline element. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polyline */ interface RenderItemReturnPolyline { /** * Must be specified when define a graphic element at the * first time. * * Optional values: * * [image](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_image) * , * [text](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_text) * , * [circle](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_circle) * , * [sector](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_sector) * , * [ring](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_ring) * , * [polygon](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon) * , * [polyline](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polyline) * , * [rect](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_rect) * , * [line](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_line) * , * [bezierCurve](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_bezierCurve) * , * [arc](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_arc) * , * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * , * * * @default * "polyline" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polyline.type */ type?: string | undefined; /** * id is used to specifying element when willing to update * it. id can be ignored if you do not need it. * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polyline.id */ id?: string | undefined; /** * `2D transform` can be applied to graphic elements, including: * * + [position](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.position) * : `[horizontal translate offset, vertical translate offset]`, * `[0, 0]` by default. * Positive value means translate towards right or bottom. * + [rotation](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.rotation) * : Rotation in radian, `0` by default. * Positive when anticlockwise. * + [scale](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.scale) * : `[horizontal scale factor, vertical scale factor]`, * `[1, 1]` by default. * * [origin](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.origin) * specifies the origin point of rotation and scaling, `[0, * 0]` by default. * * Notice: * * + The coordinates specified in the transform attribute * above are relative to the `[0, 0]` of the parent element * (that is, * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * or the root canvas). Thus we are able to * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * multiple elements, and * [groups](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * can be nested. * + The order that the transform attributes are applied * to a single graphic element is: Firstly, `rotation`, * then, `scale`, finally, `position`. * * * @default * [0, 0] * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polyline.position */ position?: any[] | undefined; /** * `2D transform` can be applied to graphic elements, including: * * + [position](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.position) * : `[horizontal translate offset, vertical translate offset]`, * `[0, 0]` by default. * Positive value means translate towards right or bottom. * + [rotation](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.rotation) * : Rotation in radian, `0` by default. * Positive when anticlockwise. * + [scale](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.scale) * : `[horizontal scale factor, vertical scale factor]`, * `[1, 1]` by default. * * [origin](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.origin) * specifies the origin point of rotation and scaling, `[0, * 0]` by default. * * Notice: * * + The coordinates specified in the transform attribute * above are relative to the `[0, 0]` of the parent element * (that is, * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * or the root canvas). Thus we are able to * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * multiple elements, and * [groups](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * can be nested. * + The order that the transform attributes are applied * to a single graphic element is: Firstly, `rotation`, * then, `scale`, finally, `position`. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polyline.rotation */ rotation?: number | undefined; /** * `2D transform` can be applied to graphic elements, including: * * + [position](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.position) * : `[horizontal translate offset, vertical translate offset]`, * `[0, 0]` by default. * Positive value means translate towards right or bottom. * + [rotation](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.rotation) * : Rotation in radian, `0` by default. * Positive when anticlockwise. * + [scale](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.scale) * : `[horizontal scale factor, vertical scale factor]`, * `[1, 1]` by default. * * [origin](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.origin) * specifies the origin point of rotation and scaling, `[0, * 0]` by default. * * Notice: * * + The coordinates specified in the transform attribute * above are relative to the `[0, 0]` of the parent element * (that is, * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * or the root canvas). Thus we are able to * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * multiple elements, and * [groups](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * can be nested. * + The order that the transform attributes are applied * to a single graphic element is: Firstly, `rotation`, * then, `scale`, finally, `position`. * * * @default * [1, 1] * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polyline.scale */ scale?: any[] | undefined; /** * `2D transform` can be applied to graphic elements, including: * * + [position](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.position) * : `[horizontal translate offset, vertical translate offset]`, * `[0, 0]` by default. * Positive value means translate towards right or bottom. * + [rotation](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.rotation) * : Rotation in radian, `0` by default. * Positive when anticlockwise. * + [scale](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.scale) * : `[horizontal scale factor, vertical scale factor]`, * `[1, 1]` by default. * * [origin](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.origin) * specifies the origin point of rotation and scaling, `[0, * 0]` by default. * * Notice: * * + The coordinates specified in the transform attribute * above are relative to the `[0, 0]` of the parent element * (that is, * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * or the root canvas). Thus we are able to * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * multiple elements, and * [groups](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * can be nested. * + The order that the transform attributes are applied * to a single graphic element is: Firstly, `rotation`, * then, `scale`, finally, `position`. * * * @default * [0, 0] * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polyline.origin */ origin?: number | undefined; /** * Define the overlap relationship between graphic elements. * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polyline.z2 */ z2?: number | undefined; /** * See * [diffChildrenByName](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.diffChildrenByName) * 。 * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polyline.name */ name?: string | undefined; /** * User defined data, can be visited in event listeners. * * [see doc](https://echarts.apache.org/en/option.html#series-custom.custom.renderItem.return_polyline) * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polyline.info */ info?: any; /** * Whether response to mouse events / touch events. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polyline.silent */ silent?: boolean | undefined; /** * Whether the element is visible. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polyline.invisible */ invisible?: boolean | undefined; /** * Whether the element is totally ignored (neither render * nor listen events). * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polyline.ignore */ ignore?: boolean | undefined; /** * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polyline.shape */ shape?: { /** * A list of points, which defines the shape, like `[[22, * 44], [44, 55], [11, 44], ...]`. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polyline.shape.points */ points?: any[] | undefined; /** * Whether smooth the line. * * + If the value is number, bezier interpolation is * used, and the value specified the level of smooth, * which is in the range of `[0, 1]`. * + If the value is `'spline'`, Catmull-Rom spline * interpolation is used. * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polyline.shape.smooth */ smooth?: number | string | undefined; /** * Whether prevent the smooth process cause the line * out of the bounding box. * * Only works when `smooth` is `number` (bezier smooth). * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polyline.shape.smoothConstraint */ smoothConstraint?: boolean | undefined; } | undefined; /** * More attributes in `style` (for example, * [rich text](https://echarts.apache.org/en/tutorial.html#Rich%20Text) * ), see the `style` related attributes in * [zrender/graphic/Displayable](https://ecomfe.github.io/zrender-doc/public/api.html#zrenderdisplayable) * . * * Notice, the attribute names of the `style` of graphic * elements is derived from `zrender`, which may be different * from the attribute names in `echarts label`, `echarts * itemStyle`, etc., * although they have the same meaning. For example: * * + [itemStyle.color](https://echarts.apache.org/en/option.html#series-scatter.label.color) * => `style.fill` * + [itemStyle.borderColor](https://echarts.apache.org/en/option.html#series-scatter.label.color) * => `style.stroke` * + [label.color](https://echarts.apache.org/en/option.html#series-scatter.label.color) * => `style.textFill` * + [label.textBorderColor](https://echarts.apache.org/en/option.html#series-scatter.label.textBorderColor) * => `style.textStroke` * + ... * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polyline.style */ style?: { /** * Color filled in this element. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polyline.style.fill */ fill?: string | undefined; /** * Color of stroke. * * * @default * "#000" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polyline.style.stroke */ stroke?: string | undefined; /** * Width of stroke. * * * @default * 5 * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polyline.style.lineWidth */ lineWidth?: number | undefined; /** * Width of shadow. * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polyline.style.shadowBlur */ shadowBlur?: number | undefined; /** * X offset of shadow. * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polyline.style.shadowOffsetX */ shadowOffsetX?: number | undefined; /** * Y offset of shadow. * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polyline.style.shadowOffsetY */ shadowOffsetY?: number | undefined; /** * color of shadow. * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polyline.style.shadowColor */ shadowColor?: number | undefined; } | undefined; /** * Empahsis style of the graphic element, whose structure * is the same as * [style](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.style) * . * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polyline.styleEmphasis */ styleEmphasis?: object | undefined; } /** * Line element. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_line */ interface RenderItemReturnLine { /** * Must be specified when define a graphic element at the * first time. * * Optional values: * * [image](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_image) * , * [text](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_text) * , * [circle](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_circle) * , * [sector](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_sector) * , * [ring](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_ring) * , * [polygon](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon) * , * [polyline](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polyline) * , * [rect](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_rect) * , * [line](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_line) * , * [bezierCurve](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_bezierCurve) * , * [arc](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_arc) * , * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * , * * * @default * "line" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_line.type */ type?: string | undefined; /** * id is used to specifying element when willing to update * it. id can be ignored if you do not need it. * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_line.id */ id?: string | undefined; /** * `2D transform` can be applied to graphic elements, including: * * + [position](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.position) * : `[horizontal translate offset, vertical translate offset]`, * `[0, 0]` by default. * Positive value means translate towards right or bottom. * + [rotation](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.rotation) * : Rotation in radian, `0` by default. * Positive when anticlockwise. * + [scale](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.scale) * : `[horizontal scale factor, vertical scale factor]`, * `[1, 1]` by default. * * [origin](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.origin) * specifies the origin point of rotation and scaling, `[0, * 0]` by default. * * Notice: * * + The coordinates specified in the transform attribute * above are relative to the `[0, 0]` of the parent element * (that is, * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * or the root canvas). Thus we are able to * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * multiple elements, and * [groups](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * can be nested. * + The order that the transform attributes are applied * to a single graphic element is: Firstly, `rotation`, * then, `scale`, finally, `position`. * * * @default * [0, 0] * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_line.position */ position?: any[] | undefined; /** * `2D transform` can be applied to graphic elements, including: * * + [position](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.position) * : `[horizontal translate offset, vertical translate offset]`, * `[0, 0]` by default. * Positive value means translate towards right or bottom. * + [rotation](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.rotation) * : Rotation in radian, `0` by default. * Positive when anticlockwise. * + [scale](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.scale) * : `[horizontal scale factor, vertical scale factor]`, * `[1, 1]` by default. * * [origin](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.origin) * specifies the origin point of rotation and scaling, `[0, * 0]` by default. * * Notice: * * + The coordinates specified in the transform attribute * above are relative to the `[0, 0]` of the parent element * (that is, * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * or the root canvas). Thus we are able to * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * multiple elements, and * [groups](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * can be nested. * + The order that the transform attributes are applied * to a single graphic element is: Firstly, `rotation`, * then, `scale`, finally, `position`. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_line.rotation */ rotation?: number | undefined; /** * `2D transform` can be applied to graphic elements, including: * * + [position](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.position) * : `[horizontal translate offset, vertical translate offset]`, * `[0, 0]` by default. * Positive value means translate towards right or bottom. * + [rotation](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.rotation) * : Rotation in radian, `0` by default. * Positive when anticlockwise. * + [scale](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.scale) * : `[horizontal scale factor, vertical scale factor]`, * `[1, 1]` by default. * * [origin](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.origin) * specifies the origin point of rotation and scaling, `[0, * 0]` by default. * * Notice: * * + The coordinates specified in the transform attribute * above are relative to the `[0, 0]` of the parent element * (that is, * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * or the root canvas). Thus we are able to * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * multiple elements, and * [groups](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * can be nested. * + The order that the transform attributes are applied * to a single graphic element is: Firstly, `rotation`, * then, `scale`, finally, `position`. * * * @default * [1, 1] * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_line.scale */ scale?: any[] | undefined; /** * `2D transform` can be applied to graphic elements, including: * * + [position](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.position) * : `[horizontal translate offset, vertical translate offset]`, * `[0, 0]` by default. * Positive value means translate towards right or bottom. * + [rotation](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.rotation) * : Rotation in radian, `0` by default. * Positive when anticlockwise. * + [scale](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.scale) * : `[horizontal scale factor, vertical scale factor]`, * `[1, 1]` by default. * * [origin](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.origin) * specifies the origin point of rotation and scaling, `[0, * 0]` by default. * * Notice: * * + The coordinates specified in the transform attribute * above are relative to the `[0, 0]` of the parent element * (that is, * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * or the root canvas). Thus we are able to * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * multiple elements, and * [groups](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * can be nested. * + The order that the transform attributes are applied * to a single graphic element is: Firstly, `rotation`, * then, `scale`, finally, `position`. * * * @default * [0, 0] * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_line.origin */ origin?: number | undefined; /** * Define the overlap relationship between graphic elements. * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_line.z2 */ z2?: number | undefined; /** * See * [diffChildrenByName](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.diffChildrenByName) * 。 * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_line.name */ name?: string | undefined; /** * User defined data, can be visited in event listeners. * * [see doc](https://echarts.apache.org/en/option.html#series-custom.custom.renderItem.return_line) * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_line.info */ info?: any; /** * Whether response to mouse events / touch events. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_line.silent */ silent?: boolean | undefined; /** * Whether the element is visible. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_line.invisible */ invisible?: boolean | undefined; /** * Whether the element is totally ignored (neither render * nor listen events). * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_line.ignore */ ignore?: boolean | undefined; /** * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_line.shape */ shape?: { /** * x value of the start point. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_line.shape.x1 */ x1?: number | undefined; /** * y value of the start point. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_line.shape.y1 */ y1?: number | undefined; /** * x value of the end point. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_line.shape.x2 */ x2?: number | undefined; /** * y value of the end point. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_line.shape.y2 */ y2?: number | undefined; /** * Specify the percentage of drawing, useful in animation. * * Value range: \[0, 1\]. * * * @default * 1 * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_line.shape.percent */ percent?: number | undefined; } | undefined; /** * More attributes in `style` (for example, * [rich text](https://echarts.apache.org/en/tutorial.html#Rich%20Text) * ), see the `style` related attributes in * [zrender/graphic/Displayable](https://ecomfe.github.io/zrender-doc/public/api.html#zrenderdisplayable) * . * * Notice, the attribute names of the `style` of graphic * elements is derived from `zrender`, which may be different * from the attribute names in `echarts label`, `echarts * itemStyle`, etc., * although they have the same meaning. For example: * * + [itemStyle.color](https://echarts.apache.org/en/option.html#series-scatter.label.color) * => `style.fill` * + [itemStyle.borderColor](https://echarts.apache.org/en/option.html#series-scatter.label.color) * => `style.stroke` * + [label.color](https://echarts.apache.org/en/option.html#series-scatter.label.color) * => `style.textFill` * + [label.textBorderColor](https://echarts.apache.org/en/option.html#series-scatter.label.textBorderColor) * => `style.textStroke` * + ... * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_line.style */ style?: { /** * Color filled in this element. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_line.style.fill */ fill?: string | undefined; /** * Color of stroke. * * * @default * "#000" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_line.style.stroke */ stroke?: string | undefined; /** * Width of stroke. * * * @default * 5 * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_line.style.lineWidth */ lineWidth?: number | undefined; /** * Width of shadow. * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_line.style.shadowBlur */ shadowBlur?: number | undefined; /** * X offset of shadow. * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_line.style.shadowOffsetX */ shadowOffsetX?: number | undefined; /** * Y offset of shadow. * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_line.style.shadowOffsetY */ shadowOffsetY?: number | undefined; /** * color of shadow. * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_line.style.shadowColor */ shadowColor?: number | undefined; } | undefined; /** * Empahsis style of the graphic element, whose structure * is the same as * [style](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.style) * . * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_line.styleEmphasis */ styleEmphasis?: object | undefined; } /** * Quadratic bezier curve or cubic bezier curve. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_bezierCurve */ interface RenderItemReturnBezierCurve { /** * Must be specified when define a graphic element at the * first time. * * Optional values: * * [image](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_image) * , * [text](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_text) * , * [circle](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_circle) * , * [sector](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_sector) * , * [ring](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_ring) * , * [polygon](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon) * , * [polyline](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polyline) * , * [rect](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_rect) * , * [line](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_line) * , * [bezierCurve](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_bezierCurve) * , * [arc](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_arc) * , * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * , * * * @default * "bezierCurve" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_bezierCurve.type */ type?: string | undefined; /** * id is used to specifying element when willing to update * it. id can be ignored if you do not need it. * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_bezierCurve.id */ id?: string | undefined; /** * `2D transform` can be applied to graphic elements, including: * * + [position](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.position) * : `[horizontal translate offset, vertical translate offset]`, * `[0, 0]` by default. * Positive value means translate towards right or bottom. * + [rotation](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.rotation) * : Rotation in radian, `0` by default. * Positive when anticlockwise. * + [scale](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.scale) * : `[horizontal scale factor, vertical scale factor]`, * `[1, 1]` by default. * * [origin](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.origin) * specifies the origin point of rotation and scaling, `[0, * 0]` by default. * * Notice: * * + The coordinates specified in the transform attribute * above are relative to the `[0, 0]` of the parent element * (that is, * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * or the root canvas). Thus we are able to * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * multiple elements, and * [groups](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * can be nested. * + The order that the transform attributes are applied * to a single graphic element is: Firstly, `rotation`, * then, `scale`, finally, `position`. * * * @default * [0, 0] * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_bezierCurve.position */ position?: any[] | undefined; /** * `2D transform` can be applied to graphic elements, including: * * + [position](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.position) * : `[horizontal translate offset, vertical translate offset]`, * `[0, 0]` by default. * Positive value means translate towards right or bottom. * + [rotation](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.rotation) * : Rotation in radian, `0` by default. * Positive when anticlockwise. * + [scale](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.scale) * : `[horizontal scale factor, vertical scale factor]`, * `[1, 1]` by default. * * [origin](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.origin) * specifies the origin point of rotation and scaling, `[0, * 0]` by default. * * Notice: * * + The coordinates specified in the transform attribute * above are relative to the `[0, 0]` of the parent element * (that is, * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * or the root canvas). Thus we are able to * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * multiple elements, and * [groups](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * can be nested. * + The order that the transform attributes are applied * to a single graphic element is: Firstly, `rotation`, * then, `scale`, finally, `position`. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_bezierCurve.rotation */ rotation?: number | undefined; /** * `2D transform` can be applied to graphic elements, including: * * + [position](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.position) * : `[horizontal translate offset, vertical translate offset]`, * `[0, 0]` by default. * Positive value means translate towards right or bottom. * + [rotation](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.rotation) * : Rotation in radian, `0` by default. * Positive when anticlockwise. * + [scale](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.scale) * : `[horizontal scale factor, vertical scale factor]`, * `[1, 1]` by default. * * [origin](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.origin) * specifies the origin point of rotation and scaling, `[0, * 0]` by default. * * Notice: * * + The coordinates specified in the transform attribute * above are relative to the `[0, 0]` of the parent element * (that is, * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * or the root canvas). Thus we are able to * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * multiple elements, and * [groups](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * can be nested. * + The order that the transform attributes are applied * to a single graphic element is: Firstly, `rotation`, * then, `scale`, finally, `position`. * * * @default * [1, 1] * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_bezierCurve.scale */ scale?: any[] | undefined; /** * `2D transform` can be applied to graphic elements, including: * * + [position](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.position) * : `[horizontal translate offset, vertical translate offset]`, * `[0, 0]` by default. * Positive value means translate towards right or bottom. * + [rotation](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.rotation) * : Rotation in radian, `0` by default. * Positive when anticlockwise. * + [scale](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.scale) * : `[horizontal scale factor, vertical scale factor]`, * `[1, 1]` by default. * * [origin](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.origin) * specifies the origin point of rotation and scaling, `[0, * 0]` by default. * * Notice: * * + The coordinates specified in the transform attribute * above are relative to the `[0, 0]` of the parent element * (that is, * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * or the root canvas). Thus we are able to * [group](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * multiple elements, and * [groups](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_group) * can be nested. * + The order that the transform attributes are applied * to a single graphic element is: Firstly, `rotation`, * then, `scale`, finally, `position`. * * * @default * [0, 0] * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_bezierCurve.origin */ origin?: number | undefined; /** * Define the overlap relationship between graphic elements. * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_bezierCurve.z2 */ z2?: number | undefined; /** * See * [diffChildrenByName](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.diffChildrenByName) * 。 * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_bezierCurve.name */ name?: string | undefined; /** * User defined data, can be visited in event listeners. * * [see doc](https://echarts.apache.org/en/option.html#series-custom.custom.renderItem.return_bezierCurve) * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_bezierCurve.info */ info?: any; /** * Whether response to mouse events / touch events. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_bezierCurve.silent */ silent?: boolean | undefined; /** * Whether the element is visible. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_bezierCurve.invisible */ invisible?: boolean | undefined; /** * Whether the element is totally ignored (neither render * nor listen events). * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_bezierCurve.ignore */ ignore?: boolean | undefined; /** * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_bezierCurve.shape */ shape?: { /** * x value of the start point. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_bezierCurve.shape.x1 */ x1?: number | undefined; /** * y value of the start point. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_bezierCurve.shape.y1 */ y1?: number | undefined; /** * x value of the end point. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_bezierCurve.shape.x2 */ x2?: number | undefined; /** * y value of the end point. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_bezierCurve.shape.y2 */ y2?: number | undefined; /** * x of control point. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_bezierCurve.shape.cpx1 */ cpx1?: number | undefined; /** * y of control point. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_bezierCurve.shape.cpy1 */ cpy1?: number | undefined; /** * x of the second control point. * If specified, cubic bezier is used. * * If both `cpx2` and `cpy2` are not set, quatratic * bezier is used. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_bezierCurve.shape.cpx2 */ cpx2?: number | undefined; /** * y of the second control point. * If specified, cubic bezier is used. * * If both `cpx2` and `cpy2` are not set, quatratic * bezier is used. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_bezierCurve.shape.cpy2 */ cpy2?: number | undefined; /** * Specify the percentage of drawing, useful in animation. * * Value range: \[0, 1\]. * * * @default * 1 * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_bezierCurve.shape.percent */ percent?: number | undefined; } | undefined; /** * More attributes in `style` (for example, * [rich text](https://echarts.apache.org/en/tutorial.html#Rich%20Text) * ), see the `style` related attributes in * [zrender/graphic/Displayable](https://ecomfe.github.io/zrender-doc/public/api.html#zrenderdisplayable) * . * * Notice, the attribute names of the `style` of graphic * elements is derived from `zrender`, which may be different * from the attribute names in `echarts label`, `echarts * itemStyle`, etc., * although they have the same meaning. For example: * * + [itemStyle.color](https://echarts.apache.org/en/option.html#series-scatter.label.color) * => `style.fill` * + [itemStyle.borderColor](https://echarts.apache.org/en/option.html#series-scatter.label.color) * => `style.stroke` * + [label.color](https://echarts.apache.org/en/option.html#series-scatter.label.color) * => `style.textFill` * + [label.textBorderColor](https://echarts.apache.org/en/option.html#series-scatter.label.textBorderColor) * => `style.textStroke` * + ... * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_bezierCurve.style */ style?: { /** * Color filled in this element. * * * @default * '#000' * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_bezierCurve.style.fill */ fill?: string | undefined; /** * Color of stroke. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_bezierCurve.style.stroke */ stroke?: string | undefined; /** * Width of stroke. * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_bezierCurve.style.lineWidth */ lineWidth?: number | undefined; /** * Width of shadow. * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_bezierCurve.style.shadowBlur */ shadowBlur?: number | undefined; /** * X offset of shadow. * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_bezierCurve.style.shadowOffsetX */ shadowOffsetX?: number | undefined; /** * Y offset of shadow. * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_bezierCurve.style.shadowOffsetY */ shadowOffsetY?: number | undefined; /** * color of shadow. * * * @default * "undefined" * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_bezierCurve.style.shadowColor */ shadowColor?: number | undefined; } | undefined; /** * Empahsis style of the graphic element, whose structure * is the same as * [style](https://echarts.apache.org/en/option.html#series-custom.renderItem.return_polygon.style) * . * * * @see https://echarts.apache.org/en/option.html#series-custom.renderItem.return_bezierCurve.styleEmphasis */ styleEmphasis?: object | undefined; } } } }
mit
B3n30/citra-1
src/common/logging/filter.cpp
3038
// Copyright 2014 Citra Emulator Project // Licensed under GPLv2 or any later version // Refer to the license.txt file included. #include <algorithm> #include "common/logging/backend.h" #include "common/logging/filter.h" #include "common/string_util.h" namespace Log { namespace { template <typename It> Level GetLevelByName(const It begin, const It end) { for (u8 i = 0; i < static_cast<u8>(Level::Count); ++i) { const char* level_name = GetLevelName(static_cast<Level>(i)); if (Common::ComparePartialString(begin, end, level_name)) { return static_cast<Level>(i); } } return Level::Count; } template <typename It> Class GetClassByName(const It begin, const It end) { for (ClassType i = 0; i < static_cast<ClassType>(Class::Count); ++i) { const char* level_name = GetLogClassName(static_cast<Class>(i)); if (Common::ComparePartialString(begin, end, level_name)) { return static_cast<Class>(i); } } return Class::Count; } template <typename Iterator> bool ParseFilterRule(Filter& instance, Iterator begin, Iterator end) { auto level_separator = std::find(begin, end, ':'); if (level_separator == end) { LOG_ERROR(Log, "Invalid log filter. Must specify a log level after `:`: {}", std::string(begin, end)); return false; } const Level level = GetLevelByName(level_separator + 1, end); if (level == Level::Count) { LOG_ERROR(Log, "Unknown log level in filter: {}", std::string(begin, end)); return false; } if (Common::ComparePartialString(begin, level_separator, "*")) { instance.ResetAll(level); return true; } const Class log_class = GetClassByName(begin, level_separator); if (log_class == Class::Count) { LOG_ERROR(Log, "Unknown log class in filter: {}", std::string(begin, end)); return false; } instance.SetClassLevel(log_class, level); return true; } } // Anonymous namespace Filter::Filter(Level default_level) { ResetAll(default_level); } void Filter::ResetAll(Level level) { class_levels.fill(level); } void Filter::SetClassLevel(Class log_class, Level level) { class_levels[static_cast<std::size_t>(log_class)] = level; } void Filter::ParseFilterString(std::string_view filter_view) { auto clause_begin = filter_view.cbegin(); while (clause_begin != filter_view.cend()) { auto clause_end = std::find(clause_begin, filter_view.cend(), ' '); // If clause isn't empty if (clause_end != clause_begin) { ParseFilterRule(*this, clause_begin, clause_end); } if (clause_end != filter_view.cend()) { // Skip over the whitespace ++clause_end; } clause_begin = clause_end; } } bool Filter::CheckMessage(Class log_class, Level level) const { return static_cast<u8>(level) >= static_cast<u8>(class_levels[static_cast<std::size_t>(log_class)]); } } // namespace Log
gpl-2.0
georchestra/georchestra
mapfishapp/src/main/webapp/lib/proj4js/lib/defs/EPSG2664.js
118
Proj4js.defs["EPSG:2664"] = "+proj=tmerc +lat_0=0 +lon_0=90 +k=1 +x_0=30500000 +y_0=0 +ellps=krass +units=m +no_defs";
gpl-3.0
GH1995/tools
archives/cpp-primer-5th/GCC_pre_C11/18/Sales_data.cc
3831
/* * This file contains code from "C++ Primer, Fifth Edition", by Stanley B. * Lippman, Josee Lajoie, and Barbara E. Moo, and is covered under the * copyright and warranty notices given in that book: * * "Copyright (c) 2013 by Objectwrite, Inc., Josee Lajoie, and Barbara E. Moo." * * * "The authors and publisher have taken care in the preparation of this book, * but make no expressed or implied warranty of any kind and assume no * responsibility for errors or omissions. No liability is assumed for * incidental or consequential damages in connection with or arising out of the * use of the information or programs contained herein." * * Permission is granted for this code to be used for educational purposes in * association with the book, given proper citation if and when posted or * reproduced.Any commercial use of this code requires the explicit written * permission of the publisher, Addison-Wesley Professional, a division of * Pearson Education, Inc. Send your request for permission, stating clearly * what code you would like to use, and in what specific way, to the following * address: * * Pearson Education, Inc. * Rights and Permissions Department * One Lake Street * Upper Saddle River, NJ 07458 * Fax: (201) 236-3290 */ #include <string> using std::istream; using std::ostream; #include "Sales_data.h" #include "bookexcept.h" // this version of the compound assignment operator // throws an exception if the objects refer to different books Sales_data& Sales_data::operator+=(const Sales_data &rhs) { if (isbn() != rhs.isbn()) throw isbn_mismatch("wrong isbns", isbn(), rhs.isbn()); units_sold += rhs.units_sold; revenue += rhs.revenue; return *this; } // operator+ code is unchanged, but because it uses += // this version of the function also throws when called // for books whose isbns differ Sales_data operator+(const Sales_data &lhs, const Sales_data &rhs) { Sales_data sum = lhs; // copy data members from lhs into sum sum += rhs; // add rhs into sum return sum; } // remaning functions unchanged from chapter 16 // define the hash interface for Sales_data namespace std { size_t hash<Sales_data>::operator()(const Sales_data& s) const { return hash<string>()(s.bookNo) ^ hash<unsigned>()(s.units_sold) ^ hash<double>()(s.revenue); } } // close the std namespace; note: no semicolon after the close curly // remaining members unchanged from chapter 14 Sales_data::Sales_data(istream &is) { is >> *this; // read a transaction from is into this object } double Sales_data::avg_price() const { if (units_sold) return revenue/units_sold; else return 0; } istream &operator>>(istream &is, Sales_data &item) { double price; // no need to initialize; we'll read into price before we use it is >> item.bookNo >> item.units_sold >> price; if (is) // check that the inputs succeeded item.revenue = item.units_sold * price; else item = Sales_data(); // input failed: give the object the default state return is; } ostream &operator<<(ostream &os, const Sales_data &item) { os << item.isbn() << " " << item.units_sold << " " << item.revenue << " " << item.avg_price(); return os; } // operators replace these original named functions istream &read(istream &is, Sales_data &item) { double price = 0; is >> item.bookNo >> item.units_sold >> price; item.revenue = price * item.units_sold; return is; } ostream &print(ostream &os, const Sales_data &item) { os << item.isbn() << " " << item.units_sold << " " << item.revenue << " " << item.avg_price(); return os; } Sales_data add(const Sales_data &lhs, const Sales_data &rhs) { Sales_data sum = lhs; // copy data members from lhs into sum sum += rhs; // add rhs into sum return sum; }
gpl-3.0
GFI-Informatique/georchestra
mapfishapp/src/main/webapp/lib/proj4js/lib/defs/EPSG32157.js
146
Proj4js.defs["EPSG:32157"] = "+proj=tmerc +lat_0=40.5 +lon_0=-108.75 +k=0.9999375 +x_0=600000 +y_0=0 +ellps=GRS80 +datum=NAD83 +units=m +no_defs";
gpl-3.0
dev-pnt/gers-pruebas
modules/Meetings/field_arrays.php
3290
<?php if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point'); /********************************************************************************* * SugarCRM Community Edition is a customer relationship management program developed by * SugarCRM, Inc. Copyright (C) 2004-2012 SugarCRM Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by the * Free Software Foundation with the addition of the following permission added * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * This program 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 Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along with * this program; if not, see http://www.gnu.org/licenses or write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. * * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road, * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License version 3, * these Appropriate Legal Notices must retain the display of the "Powered by * SugarCRM" logo. If the display of the logo is not reasonably feasible for * technical reasons, the Appropriate Legal Notices must display the words * "Powered by SugarCRM". ********************************************************************************/ /********************************************************************************* * Description: Contains field arrays that are used for caching * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. * All Rights Reserved. * Contributor(s): ______________________________________.. ********************************************************************************/ $fields_array['Meeting'] = array ('column_fields' => Array("id" , "date_entered" , "date_modified" , "assigned_user_id" , "modified_user_id" , "created_by" , "description" , "name" , "status" , "location" , "date_start" , "time_start" , "date_end" , "duration_hours" , "duration_minutes" , "parent_type" , "parent_id" , 'reminder_time' ,'outlook_id' ), 'list_fields' => Array('id', 'location', 'duration_hours', 'name ', 'status', 'parent_type', 'parent_name', 'parent_id', 'date_start', 'time_start', 'assigned_user_name', 'assigned_user_id', 'contact_name', 'contact_id','first_name','last_name','required','accept_status','outlook_id','duration_minutes' ), 'required_fields' => array("name"=>1, "date_start"=>2, "time_start"=>3, "duration_hours"=>4), ); ?>
agpl-3.0
IrishLAs/SugarCRM-Public
modules/Notes/metadata/subpanels/ForHistory.php
4588
<?php if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point'); /********************************************************************************* * SugarCRM Community Edition is a customer relationship management program developed by * SugarCRM, Inc. Copyright (C) 2004-2012 SugarCRM Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by the * Free Software Foundation with the addition of the following permission added * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * This program 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 Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along with * this program; if not, see http://www.gnu.org/licenses or write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. * * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road, * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License version 3, * these Appropriate Legal Notices must retain the display of the "Powered by * SugarCRM" logo. If the display of the logo is not reasonably feasible for * technical reasons, the Appropriate Legal Notices must display the words * "Powered by SugarCRM". ********************************************************************************/ $subpanel_layout = array( //Removed button because this layout def is a component of //the activities sub-panel. 'where' => '', 'list_fields' => array( 'object_image'=>array( 'vname' => 'LBL_OBJECT_IMAGE', 'widget_class' => 'SubPanelIcon', 'width' => '2%', 'image2'=>'attachment', 'image2_url_field'=> array( 'id_field' => 'id', 'filename_field' => 'filename', ), ), 'name'=>array( 'vname' => 'LBL_LIST_SUBJECT', 'widget_class' => 'SubPanelDetailViewLink', 'width' => '30%', ), 'status'=>array( 'widget_class' => 'SubPanelActivitiesStatusField', 'vname' => 'LBL_LIST_STATUS', 'width' => '15%', 'force_exists'=>true //this will create a fake field in the case a field is not defined ), 'reply_to_status' => array( 'usage' => 'query_only', 'force_exists' => true, 'force_default' => 0, ), 'contact_name'=>array( 'widget_class' => 'SubPanelDetailViewLink', 'target_record_key' => 'contact_id', 'target_module' => 'Contacts', 'module' => 'Contacts', 'vname' => 'LBL_LIST_CONTACT', 'width' => '11%', 'sortable'=>false, ), 'parent_id'=>array( 'usage'=>'query_only', 'force_exists'=>true ), 'parent_type'=>array( 'usage'=>'query_only', 'force_exists'=>true ), 'date_modified'=>array( 'vname' => 'LBL_LIST_DATE_MODIFIED', 'width' => '10%', ), 'date_entered'=>array( 'vname' => 'LBL_LIST_DATE_ENTERED', 'width' => '10%', ), 'assigned_user_name' => array ( 'name' => 'assigned_user_name', 'vname' => 'LBL_LIST_ASSIGNED_TO_NAME', 'widget_class' => 'SubPanelDetailViewLink', 'target_record_key' => 'assigned_user_id', 'target_module' => 'Employees', 'width' => '10%', ), 'assigned_user_owner' => array ( 'force_exists'=>true, //this will create a fake field since this field is not defined 'usage'=>'query_only' ), 'assigned_user_mod' => array ( 'force_exists'=>true, //this will create a fake field since this field is not defined 'usage'=>'query_only' ), 'edit_button'=>array( 'vname' => 'LBL_EDIT_BUTTON', 'widget_class' => 'SubPanelEditButton', 'width' => '2%', ), 'remove_button'=>array( 'vname' => 'LBL_REMOVE', 'widget_class' => 'SubPanelRemoveButton', 'width' => '2%', ), 'file_url'=>array( 'usage'=>'query_only' ), 'filename'=>array( 'usage'=>'query_only' ), ), ); ?>
agpl-3.0
sanguinariojoe/FreeCAD
src/Mod/Path/App/FeatureArea.cpp
8671
/**************************************************************************** * Copyright (c) 2017 Zheng Lei (realthunder) <realthunder.dev@gmail.com> * * * * This file is part of the FreeCAD CAx development system. * * * * 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; see the file COPYING.LIB. If not, * * write to the Free Software Foundation, Inc., 59 Temple Place, * * Suite 330, Boston, MA 02111-1307, USA * * * ****************************************************************************/ #include "PreCompiled.h" #ifndef _PreComp_ # include <BRep_Builder.hxx> # include <TopoDS_Compound.hxx> #endif #include "FeatureArea.h" #include "FeatureAreaPy.h" #include <App/DocumentObjectPy.h> #include <Base/Placement.h> #include <Mod/Part/App/PartFeature.h> FC_LOG_LEVEL_INIT("Path.Area",true,true) using namespace Path; PROPERTY_SOURCE(Path::FeatureArea, Part::Feature) PARAM_ENUM_STRING_DECLARE(static const char *Enums,AREA_PARAMS_ALL) FeatureArea::FeatureArea() :myInited(false) { ADD_PROPERTY(Sources,(0)); ADD_PROPERTY(WorkPlane,(TopoDS_Shape())); PARAM_PROP_ADD("Area",AREA_PARAMS_OPCODE); PARAM_PROP_ADD("Area",AREA_PARAMS_BASE); PARAM_PROP_ADD("Offset",AREA_PARAMS_OFFSET); PARAM_PROP_ADD("Offset", AREA_PARAMS_OFFSET_CONF); PARAM_PROP_ADD("Pocket",AREA_PARAMS_POCKET); PARAM_PROP_ADD("Pocket",AREA_PARAMS_POCKET_CONF); PARAM_PROP_ADD("Section",AREA_PARAMS_SECTION); PARAM_PROP_ADD("libarea",AREA_PARAMS_CAREA); PARAM_PROP_SET_ENUM(Enums,AREA_PARAMS_ALL); PocketMode.setValue((long)0); } FeatureArea::~FeatureArea() { } Area &FeatureArea::getArea() { if(!myInited) execute(); return myArea; } App::DocumentObjectExecReturn *FeatureArea::execute(void) { myInited = true; std::vector<App::DocumentObject*> links = Sources.getValues(); if (links.empty()) return new App::DocumentObjectExecReturn("No shapes linked"); for (std::vector<App::DocumentObject*>::iterator it = links.begin(); it != links.end(); ++it) { if (!(*it && (*it)->isDerivedFrom(Part::Feature::getClassTypeId()))) return new App::DocumentObjectExecReturn("Linked object is not a Part object (has no Shape)."); TopoDS_Shape shape = static_cast<Part::Feature*>(*it)->Shape.getShape().getShape(); if (shape.IsNull()) return new App::DocumentObjectExecReturn("Linked shape object is empty"); } FC_TIME_INIT(t); AreaParams params; #define AREA_PROP_GET(_param) \ params.PARAM_FNAME(_param) = PARAM_FNAME(_param).getValue(); PARAM_FOREACH(AREA_PROP_GET,AREA_PARAMS_CONF) myArea.clean(true); myArea.setParams(params); TopoDS_Shape workPlane = WorkPlane.getShape().getShape(); myArea.setPlane(workPlane); for (std::vector<App::DocumentObject*>::iterator it = links.begin(); it != links.end(); ++it) { myArea.add(static_cast<Part::Feature*>(*it)->Shape.getShape().getShape(), PARAM_PROP_ARGS(AREA_PARAMS_OPCODE)); } myShapes.clear(); if(myArea.getSectionCount()==0) myShapes.push_back(myArea.getShape(-1)); else { myShapes.reserve(myArea.getSectionCount()); for(int i=0;i<(int)myArea.getSectionCount();++i) myShapes.push_back(myArea.getShape(i)); } bool hasShape = false; if(myShapes.empty()) Shape.setValue(TopoDS_Shape()); else{ // compound is built even if there is only one shape to save the // trouble of messing around with placement BRep_Builder builder; TopoDS_Compound compound; builder.MakeCompound(compound); for(auto &shape : myShapes) { if(shape.IsNull()) continue; hasShape = true; builder.Add(compound,shape); } Shape.setValue(compound); } FC_TIME_LOG(t,"feature execute"); if(!hasShape) return new App::DocumentObjectExecReturn("no output shape"); return DocumentObject::StdReturn; } const std::vector<TopoDS_Shape> &FeatureArea::getShapes() { getArea(); return myShapes; } short FeatureArea::mustExecute(void) const { if(myInited && !myArea.isBuilt()) return 1; return Part::Feature::mustExecute(); } PyObject *FeatureArea::getPyObject() { if (PythonObject.is(Py::_None())){ // ref counter is set to 1 PythonObject = Py::Object(new FeatureAreaPy(this),true); } return Py::new_reference_to(PythonObject); } // FeatureAreaView ------------------------------------------------------------- // PROPERTY_SOURCE(Path::FeatureAreaView, Part::Feature) FeatureAreaView::FeatureAreaView() { ADD_PROPERTY(Source,(0)); ADD_PROPERTY_TYPE(SectionIndex,(0),"Section",App::Prop_None,"The start index of the section to show, negative value for reverse index from bottom"); ADD_PROPERTY_TYPE(SectionCount,(1),"Section",App::Prop_None,"Number of sections to show, 0 to show all section starting from SectionIndex"); } std::list<TopoDS_Shape> FeatureAreaView::getShapes() { std::list<TopoDS_Shape> shapes; App::DocumentObject* pObj = Source.getValue(); if (!pObj) return shapes; if(!pObj->isDerivedFrom(FeatureArea::getClassTypeId())) return shapes; auto all_shapes = static_cast<FeatureArea*>(pObj)->getShapes(); if(all_shapes.empty()) return shapes; int index=SectionIndex.getValue(),count=SectionCount.getValue(); if(index<0) { index += ((int)all_shapes.size()); if(index<0) return shapes; if(count<=0 || index+1-count<0) { count = index+1; index = 0; }else index -= count-1; }else if(index >= (int)all_shapes.size()) return shapes; if(count<=0) count = all_shapes.size(); count += index; if(count>(int)all_shapes.size()) count = all_shapes.size(); for(int i=index;i<count;++i) shapes.push_back(all_shapes[i]); return shapes; } App::DocumentObjectExecReturn *FeatureAreaView::execute(void) { App::DocumentObject* pObj = Source.getValue(); if (!pObj) return new App::DocumentObjectExecReturn("No shape linked"); if(!pObj->isDerivedFrom(FeatureArea::getClassTypeId())) return new App::DocumentObjectExecReturn("Linked object is not a FeatureArea"); bool hasShape = false; std::list<TopoDS_Shape> shapes = getShapes(); if(shapes.empty()) Shape.setValue(TopoDS_Shape()); else{ BRep_Builder builder; TopoDS_Compound compound; builder.MakeCompound(compound); for(auto &shape : shapes) { if(shape.IsNull()) continue; hasShape = true; builder.Add(compound,shape); } Shape.setValue(compound); } if(!hasShape) return new App::DocumentObjectExecReturn("no output shape"); return DocumentObject::StdReturn; } // Python feature --------------------------------------------------------- namespace App { /// @cond DOXERR PROPERTY_SOURCE_TEMPLATE(Path::FeatureAreaPython, Path::FeatureArea) PROPERTY_SOURCE_TEMPLATE(Path::FeatureAreaViewPython, Path::FeatureAreaView) template<> const char* Path::FeatureAreaPython::getViewProviderName(void) const { return "PathGui::ViewProviderAreaPython"; } template<> const char* Path::FeatureAreaViewPython::getViewProviderName(void) const { return "PathGui::ViewProviderAreaViewPython"; } /// @endcond // explicit template instantiation template class PathExport FeaturePythonT<Path::FeatureArea>; }
lgpl-2.1
mbborgez/fenix
src/main/java/org/fenixedu/academic/domain/accessControl/PersistentTeachersWithGradesToSubmitGroup.java
1828
/** * Copyright © 2002 Instituto Superior Técnico * * This file is part of FenixEdu Academic. * * FenixEdu Academic 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 3 of the License, or * (at your option) any later version. * * FenixEdu Academic 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 FenixEdu Academic. If not, see <http://www.gnu.org/licenses/>. */ package org.fenixedu.academic.domain.accessControl; import org.fenixedu.academic.domain.DegreeCurricularPlan; import org.fenixedu.academic.domain.ExecutionSemester; import org.fenixedu.bennu.core.groups.Group; public class PersistentTeachersWithGradesToSubmitGroup extends PersistentTeachersWithGradesToSubmitGroup_Base { protected PersistentTeachersWithGradesToSubmitGroup(ExecutionSemester period, DegreeCurricularPlan degreeCurricularPlan) { super(); init(period, degreeCurricularPlan); } @Override public Group toGroup() { return TeachersWithGradesToSubmitGroup.get(getPeriod(), getDegreeCurricularPlan()); } public static PersistentTeachersWithGradesToSubmitGroup getInstance(final ExecutionSemester period, final DegreeCurricularPlan degreeCurricularPlan) { return singleton(PersistentTeachersWithGradesToSubmitGroup.class, period, degreeCurricularPlan, () -> new PersistentTeachersWithGradesToSubmitGroup(period, degreeCurricularPlan)); } }
lgpl-3.0
NSAmelchev/ignite
modules/core/src/test/java/org/apache/ignite/internal/processors/cache/local/GridCacheLocalTxMultiThreadedSelfTest.java
3183
/* * 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 org.apache.ignite.internal.processors.cache.local; import org.apache.ignite.configuration.CacheConfiguration; import org.apache.ignite.configuration.IgniteConfiguration; import org.apache.ignite.internal.processors.cache.GridCacheProcessor; import org.apache.ignite.internal.processors.cache.IgniteTxMultiThreadedAbstractTest; import org.apache.ignite.testframework.MvccFeatureChecker; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.junit.Before; import static org.apache.ignite.cache.CacheMode.LOCAL; /** * Tests for local transactions. */ public class GridCacheLocalTxMultiThreadedSelfTest extends IgniteTxMultiThreadedAbstractTest { /** Cache debug flag. */ private static final boolean CACHE_DEBUG = false; /** */ @Before public void beforeGridCacheLocalEvictionEventSelfTest() { MvccFeatureChecker.skipIfNotSupported(MvccFeatureChecker.Feature.LOCAL_CACHE); } /** {@inheritDoc} */ @Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception { MvccFeatureChecker.skipIfNotSupported(MvccFeatureChecker.Feature.LOCAL_CACHE); IgniteConfiguration c = super.getConfiguration(igniteInstanceName); c.getTransactionConfiguration().setTxSerializableEnabled(true); CacheConfiguration cc = defaultCacheConfiguration(); cc.setCacheMode(LOCAL); cc.setEvictionPolicy(null); c.setCacheConfiguration(cc); // Disable log4j debug by default. Logger log4j = Logger.getLogger(GridCacheProcessor.class.getPackage().getName()); log4j.setLevel(CACHE_DEBUG ? Level.DEBUG : Level.INFO); return c; } /** {@inheritDoc} */ @Override protected int gridCount() { return 1; } /** {@inheritDoc} */ @Override protected int keyCount() { return 3; } /** {@inheritDoc} */ @Override protected int maxKeyValue() { return 3; } /** {@inheritDoc} */ @Override protected int threadCount() { return 2; } /** {@inheritDoc} */ @Override protected int iterations() { return 1000; } /** {@inheritDoc} */ @Override protected boolean isTestDebug() { return false; } /** {@inheritDoc} */ @Override protected boolean printMemoryStats() { return true; } }
apache-2.0
LegNeato/buck
src/com/facebook/buck/util/UnixUserIdFetcher.java
1148
/* * Copyright 2015-present Facebook, 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.facebook.buck.util; import java.lang.reflect.Method; /** Fetches the user ID of the running process. */ public class UnixUserIdFetcher implements UserIdFetcher { @Override public long getUserId() { try { Class<?> cls = Class.forName("com.sun.security.auth.module.UnixSystem", true, null); Object unixSystem = cls.newInstance(); Method getUid = cls.getDeclaredMethod("getUid"); return (long) getUid.invoke(unixSystem); } catch (Exception e) { throw new RuntimeException(e); } } }
apache-2.0
MikeThomsen/nifi
nifi-nar-bundles/nifi-standard-services/nifi-lookup-services-bundle/nifi-lookup-services/src/main/java/org/apache/nifi/lookup/db/DatabaseRecordLookupService.java
9202
/* * 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 org.apache.nifi.lookup.db; import com.github.benmanes.caffeine.cache.Cache; import com.github.benmanes.caffeine.cache.Caffeine; import com.github.benmanes.caffeine.cache.Expiry; import org.apache.commons.lang3.StringUtils; import org.apache.nifi.annotation.documentation.CapabilityDescription; import org.apache.nifi.annotation.documentation.Tags; import org.apache.nifi.annotation.lifecycle.OnEnabled; import org.apache.nifi.components.PropertyDescriptor; import org.apache.nifi.controller.ConfigurationContext; import org.apache.nifi.controller.ControllerServiceInitializationContext; import org.apache.nifi.dbcp.DBCPService; import org.apache.nifi.expression.ExpressionLanguageScope; import org.apache.nifi.lookup.LookupFailureException; import org.apache.nifi.lookup.RecordLookupService; import org.apache.nifi.processor.util.StandardValidators; import org.apache.nifi.serialization.record.Record; import org.apache.nifi.serialization.record.ResultSetRecordSet; import org.apache.nifi.util.Tuple; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.stream.Stream; @Tags({"lookup", "cache", "enrich", "join", "rdbms", "database", "reloadable", "key", "value", "record"}) @CapabilityDescription("A relational-database-based lookup service. When the lookup key is found in the database, " + "the specified columns (or all if Lookup Value Columns are not specified) are returned as a Record. Only one row " + "will be returned for each lookup, duplicate database entries are ignored.") public class DatabaseRecordLookupService extends AbstractDatabaseLookupService implements RecordLookupService { private volatile Cache<Tuple<String, Object>, Record> cache; static final PropertyDescriptor LOOKUP_VALUE_COLUMNS = new PropertyDescriptor.Builder() .name("dbrecord-lookup-value-columns") .displayName("Lookup Value Columns") .description("A comma-delimited list of columns in the table that will be returned when the lookup key matches. Note that this may be case-sensitive depending on the database.") .required(false) .addValidator(StandardValidators.NON_EMPTY_VALIDATOR) .expressionLanguageSupported(ExpressionLanguageScope.FLOWFILE_ATTRIBUTES) .build(); @Override protected void init(final ControllerServiceInitializationContext context) { final List<PropertyDescriptor> properties = new ArrayList<>(); properties.add(DBCP_SERVICE); properties.add(TABLE_NAME); properties.add(LOOKUP_KEY_COLUMN); properties.add(LOOKUP_VALUE_COLUMNS); properties.add(CACHE_SIZE); properties.add(CLEAR_CACHE_ON_ENABLED); properties.add(CACHE_EXPIRATION); this.properties = Collections.unmodifiableList(properties); } @OnEnabled public void onEnabled(final ConfigurationContext context) { this.dbcpService = context.getProperty(DBCP_SERVICE).asControllerService(DBCPService.class); this.lookupKeyColumn = context.getProperty(LOOKUP_KEY_COLUMN).evaluateAttributeExpressions().getValue(); final int cacheSize = context.getProperty(CACHE_SIZE).evaluateAttributeExpressions().asInteger(); final boolean clearCache = context.getProperty(CLEAR_CACHE_ON_ENABLED).asBoolean(); final long durationNanos = context.getProperty(CACHE_EXPIRATION).isSet() ? context.getProperty(CACHE_EXPIRATION).evaluateAttributeExpressions().asTimePeriod(TimeUnit.NANOSECONDS) : 0L; if (this.cache == null || (cacheSize > 0 && clearCache)) { if (durationNanos > 0) { this.cache = Caffeine.newBuilder() .maximumSize(cacheSize) .expireAfter(new Expiry<Tuple<String, Object>, Record>() { @Override public long expireAfterCreate(Tuple<String, Object> stringObjectTuple, Record record, long currentTime) { return durationNanos; } @Override public long expireAfterUpdate(Tuple<String, Object> stringObjectTuple, Record record, long currentTime, long currentDuration) { return currentDuration; } @Override public long expireAfterRead(Tuple<String, Object> stringObjectTuple, Record record, long currentTime, long currentDuration) { return currentDuration; } }) .build(); } else { this.cache = Caffeine.newBuilder() .maximumSize(cacheSize) .build(); } } } @Override public Optional<Record> lookup(Map<String, Object> coordinates) throws LookupFailureException { return lookup(coordinates, null); } @Override public Optional<Record> lookup(final Map<String, Object> coordinates, Map<String, String> context) throws LookupFailureException { if (coordinates == null) { return Optional.empty(); } final Object key = coordinates.get(KEY); if (StringUtils.isBlank(key.toString())) { return Optional.empty(); } final String tableName = getProperty(TABLE_NAME).evaluateAttributeExpressions(context).getValue(); final String lookupValueColumnsList = getProperty(LOOKUP_VALUE_COLUMNS).evaluateAttributeExpressions(context).getValue(); Set<String> lookupValueColumnsSet = new LinkedHashSet<>(); if (lookupValueColumnsList != null) { Stream.of(lookupValueColumnsList) .flatMap(path -> Arrays.stream(path.split(","))) .filter(DatabaseRecordLookupService::isNotBlank) .map(String::trim) .forEach(lookupValueColumnsSet::add); } final String lookupValueColumns = lookupValueColumnsSet.isEmpty() ? "*" : String.join(",", lookupValueColumnsSet); Tuple<String, Object> cacheLookupKey = new Tuple<>(tableName, key); // Not using the function param of cache.get so we can catch and handle the checked exceptions Record foundRecord = cache.get(cacheLookupKey, k -> null); if (foundRecord == null) { final String selectQuery = "SELECT " + lookupValueColumns + " FROM " + tableName + " WHERE " + lookupKeyColumn + " = ?"; try (final Connection con = dbcpService.getConnection(context); final PreparedStatement st = con.prepareStatement(selectQuery)) { st.setObject(1, key); ResultSet resultSet = st.executeQuery(); ResultSetRecordSet resultSetRecordSet = new ResultSetRecordSet(resultSet, null); foundRecord = resultSetRecordSet.next(); // Populate the cache if the record is present if (foundRecord != null) { cache.put(cacheLookupKey, foundRecord); } } catch (SQLException se) { throw new LookupFailureException("Error executing SQL statement: " + selectQuery + "for value " + key.toString() + " : " + (se.getCause() == null ? se.getMessage() : se.getCause().getMessage()), se); } catch (IOException ioe) { throw new LookupFailureException("Error retrieving result set for SQL statement: " + selectQuery + "for value " + key.toString() + " : " + (ioe.getCause() == null ? ioe.getMessage() : ioe.getCause().getMessage()), ioe); } } return Optional.ofNullable(foundRecord); } private static boolean isNotBlank(final String value) { return value != null && !value.trim().isEmpty(); } @Override public Set<String> getRequiredKeys() { return REQUIRED_KEYS; } }
apache-2.0
NSAmelchev/ignite
modules/core/src/main/java/org/apache/ignite/internal/processors/odbc/odbc/OdbcStreamingBatchRequest.java
3000
package org.apache.ignite.internal.processors.odbc.odbc; /* * 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 java.util.List; import org.apache.ignite.internal.util.tostring.GridToStringExclude; import org.apache.ignite.internal.util.tostring.GridToStringInclude; import org.apache.ignite.internal.util.typedef.internal.S; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * ODBC query execute request with the batch of parameters. */ public class OdbcStreamingBatchRequest extends OdbcRequest implements java.lang.Comparable<OdbcStreamingBatchRequest> { /** Schema name. */ @GridToStringInclude(sensitive = true) private String schemaName; /** Sql query. */ @GridToStringExclude() private List<OdbcQuery> queries; /** * Last stream batch flag - whether open streamers on current connection * must be flushed and closed after this batch. */ @GridToStringInclude(sensitive = true) private boolean last; /** Order. */ @GridToStringInclude(sensitive = true) private long order; /** * @param schema Schema. * @param queries SQL queries list. * @param last Last page flag. * @param order Order. */ public OdbcStreamingBatchRequest(@Nullable String schema, List<OdbcQuery> queries, boolean last, long order) { super(STREAMING_BATCH); this.schemaName = schema; this.queries = queries; this.last = last; this.order = order; } /** * @return Schema name. */ @Nullable public String schemaName() { return schemaName; } /** * @return Queries. */ public List<OdbcQuery> queries() { return queries; } /** * @return Last stream batch flag. */ public boolean last() { return last; } /** * @return Request order. */ public long order() { return order; } /** {@inheritDoc} */ @Override public String toString() { return S.toString(OdbcStreamingBatchRequest.class, this); } /** {@inheritDoc} */ @Override public int compareTo(@NotNull OdbcStreamingBatchRequest o) { return Long.compare(order, o.order); } }
apache-2.0
alex-ionochkin/koding
go/src/vendor/github.com/kr/binarydist/diff_test.go
1293
package binarydist import ( "bytes" "io/ioutil" "os" "os/exec" "testing" ) var diffT = []struct { old *os.File new *os.File }{ { old: mustWriteRandFile("test.old", 1e3, 1), new: mustWriteRandFile("test.new", 1e3, 2), }, { old: mustOpen("testdata/sample.old"), new: mustOpen("testdata/sample.new"), }, } func TestDiff(t *testing.T) { for _, s := range diffT { got, err := ioutil.TempFile("/tmp", "bspatch.") if err != nil { panic(err) } os.Remove(got.Name()) exp, err := ioutil.TempFile("/tmp", "bspatch.") if err != nil { panic(err) } cmd := exec.Command("bsdiff", s.old.Name(), s.new.Name(), exp.Name()) cmd.Stdout = os.Stdout err = cmd.Run() os.Remove(exp.Name()) if err != nil { panic(err) } err = Diff(s.old, s.new, got) if err != nil { t.Fatal("err", err) } _, err = got.Seek(0, 0) if err != nil { panic(err) } gotBuf := mustReadAll(got) expBuf := mustReadAll(exp) if !bytes.Equal(gotBuf, expBuf) { t.Fail() t.Logf("diff %s %s", s.old.Name(), s.new.Name()) t.Logf("%s: len(got) = %d", got.Name(), len(gotBuf)) t.Logf("%s: len(exp) = %d", exp.Name(), len(expBuf)) i := matchlen(gotBuf, expBuf) t.Logf("produced different output at pos %d; %d != %d", i, gotBuf[i], expBuf[i]) } } }
apache-2.0
coldstartdk/hassio-addons
prometheus/storage/local/test_helpers.go
2539
// Copyright 2014 The Prometheus Authors // 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. // NOTE ON FILENAME: Do not rename this file helpers_test.go (which might appear // an obvious choice). We need NewTestStorage in tests outside of the local // package, too. On the other hand, moving NewTestStorage in its own package // would cause circular dependencies in the tests in packages local. package local import ( "time" "github.com/prometheus/common/model" "github.com/prometheus/prometheus/storage/local/chunk" "github.com/prometheus/prometheus/util/testutil" ) type testStorageCloser struct { storage Storage directory testutil.Closer } func (t *testStorageCloser) Close() { if err := t.storage.Stop(); err != nil { panic(err) } t.directory.Close() } // NewTestStorage creates a storage instance backed by files in a temporary // directory. The returned storage is already in serving state. Upon closing the // returned test.Closer, the temporary directory is cleaned up. func NewTestStorage(t testutil.T, encoding chunk.Encoding) (*MemorySeriesStorage, testutil.Closer) { chunk.DefaultEncoding = encoding directory := testutil.NewTemporaryDirectory("test_storage", t) o := &MemorySeriesStorageOptions{ TargetHeapSize: 1000000000, PersistenceRetentionPeriod: 24 * time.Hour * 365 * 100, // Enough to never trigger purging. PersistenceStoragePath: directory.Path(), HeadChunkTimeout: 5 * time.Minute, CheckpointInterval: time.Hour, SyncStrategy: Adaptive, } storage := NewMemorySeriesStorage(o) storage.archiveHighWatermark = model.Latest if err := storage.Start(); err != nil { directory.Close() t.Fatalf("Error creating storage: %s", err) } closer := &testStorageCloser{ storage: storage, directory: directory, } return storage, closer } func makeFingerprintSeriesPair(s *MemorySeriesStorage, fp model.Fingerprint) fingerprintSeriesPair { return fingerprintSeriesPair{fp, s.seriesForRange(fp, model.Earliest, model.Latest)} }
apache-2.0
deasmi/terraform-provider-libvirt
vendor/github.com/mitchellh/packer/builder/amazon/chroot/step_snapshot.go
2589
package chroot import ( "errors" "fmt" "time" "github.com/aws/aws-sdk-go/service/ec2" awscommon "github.com/hashicorp/packer/builder/amazon/common" "github.com/hashicorp/packer/packer" "github.com/mitchellh/multistep" ) // StepSnapshot creates a snapshot of the created volume. // // Produces: // snapshot_id string - ID of the created snapshot type StepSnapshot struct { snapshotId string } func (s *StepSnapshot) Run(state multistep.StateBag) multistep.StepAction { ec2conn := state.Get("ec2").(*ec2.EC2) ui := state.Get("ui").(packer.Ui) volumeId := state.Get("volume_id").(string) ui.Say("Creating snapshot...") description := fmt.Sprintf("Packer: %s", time.Now().String()) createSnapResp, err := ec2conn.CreateSnapshot(&ec2.CreateSnapshotInput{ VolumeId: &volumeId, Description: &description, }) if err != nil { err := fmt.Errorf("Error creating snapshot: %s", err) state.Put("error", err) ui.Error(err.Error()) return multistep.ActionHalt } // Set the snapshot ID so we can delete it later s.snapshotId = *createSnapResp.SnapshotId ui.Message(fmt.Sprintf("Snapshot ID: %s", s.snapshotId)) // Wait for the snapshot to be ready stateChange := awscommon.StateChangeConf{ Pending: []string{"pending"}, StepState: state, Target: "completed", Refresh: func() (interface{}, string, error) { resp, err := ec2conn.DescribeSnapshots(&ec2.DescribeSnapshotsInput{SnapshotIds: []*string{&s.snapshotId}}) if err != nil { return nil, "", err } if len(resp.Snapshots) == 0 { return nil, "", errors.New("No snapshots found.") } s := resp.Snapshots[0] return s, *s.State, nil }, } _, err = awscommon.WaitForState(&stateChange) if err != nil { err := fmt.Errorf("Error waiting for snapshot: %s", err) state.Put("error", err) ui.Error(err.Error()) return multistep.ActionHalt } state.Put("snapshot_id", s.snapshotId) snapshots := map[string][]string{ *ec2conn.Config.Region: {s.snapshotId}, } state.Put("snapshots", snapshots) return multistep.ActionContinue } func (s *StepSnapshot) Cleanup(state multistep.StateBag) { if s.snapshotId == "" { return } _, cancelled := state.GetOk(multistep.StateCancelled) _, halted := state.GetOk(multistep.StateHalted) if cancelled || halted { ec2conn := state.Get("ec2").(*ec2.EC2) ui := state.Get("ui").(packer.Ui) ui.Say("Removing snapshot since we cancelled or halted...") _, err := ec2conn.DeleteSnapshot(&ec2.DeleteSnapshotInput{SnapshotId: &s.snapshotId}) if err != nil { ui.Error(fmt.Sprintf("Error: %s", err)) } } }
apache-2.0
mogoweb/webkit_for_android5.1
webkit/Source/WebCore/platform/graphics/chromium/cc/CCCanvasLayerImpl.cpp
3195
/* * Copyright (C) 2011 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS 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 APPLE OR ITS 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. */ #include "config.h" #if USE(ACCELERATED_COMPOSITING) #include "cc/CCCanvasLayerImpl.h" #include "CanvasLayerChromium.h" #include "GraphicsContext3D.h" #include "LayerRendererChromium.h" #include <wtf/text/WTFString.h> namespace WebCore { CCCanvasLayerImpl::CCCanvasLayerImpl(LayerChromium* owner) : CCLayerImpl(owner) , m_textureId(0) , m_premultipliedAlpha(true) { } CCCanvasLayerImpl::~CCCanvasLayerImpl() { } void CCCanvasLayerImpl::draw(const IntRect&) { ASSERT(layerRenderer()); const CCCanvasLayerImpl::Program* program = layerRenderer()->canvasLayerProgram(); ASSERT(program && program->initialized()); GraphicsContext3D* context = layerRenderer()->context(); GLC(context, context->activeTexture(GraphicsContext3D::TEXTURE0)); GLC(context, context->bindTexture(GraphicsContext3D::TEXTURE_2D, m_textureId)); GC3Denum sfactor = m_premultipliedAlpha ? GraphicsContext3D::ONE : GraphicsContext3D::SRC_ALPHA; GLC(context, context->blendFunc(sfactor, GraphicsContext3D::ONE_MINUS_SRC_ALPHA)); layerRenderer()->useShader(program->program()); GLC(context, context->uniform1i(program->fragmentShader().samplerLocation(), 0)); LayerChromium::drawTexturedQuad(context, layerRenderer()->projectionMatrix(), drawTransform(), bounds().width(), bounds().height(), drawOpacity(), program->vertexShader().matrixLocation(), program->fragmentShader().alphaLocation()); } void CCCanvasLayerImpl::dumpLayerProperties(TextStream& ts, int indent) const { writeIndent(ts, indent); ts << "canvas layer texture id: " << m_textureId << " premultiplied: " << m_premultipliedAlpha << "\n"; CCLayerImpl::dumpLayerProperties(ts, indent); } } #endif // USE(ACCELERATED_COMPOSITING)
apache-2.0
DeepakRajendranMsft/azure-powershell
src/ResourceManager/Network/Commands.Network/Models/PSExpressRouteCircuitRoutesTable.cs
919
// // Copyright (c) Microsoft. 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. // namespace Microsoft.Azure.Commands.Network.Models { public class PSExpressRouteCircuitRoutesTable { public string AddressPrefix { get; set; } public string NextHopType { get; set; } public string NextHopIP { get; set; } public string AsPath { get; set; } } }
apache-2.0
charithag/carbon-device-mgt
components/apimgt-extensions/org.wso2.carbon.apimgt.webapp.publisher/src/test/java/org/wso2/carbon/apimgt/webapp/publisher/utils/MockServletContext.java
6038
/* * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. 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 org.wso2.carbon.apimgt.webapp.publisher.utils; import javax.servlet.*; import javax.servlet.descriptor.JspConfigDescriptor; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.util.Enumeration; import java.util.EventListener; import java.util.Map; import java.util.Set; public class MockServletContext implements ServletContext { @Override public ServletContext getContext(String s) { return null; } @Override public String getContextPath() { return null; } @Override public int getMajorVersion() { return 0; } @Override public int getMinorVersion() { return 0; } @Override public int getEffectiveMajorVersion() { return 0; } @Override public int getEffectiveMinorVersion() { return 0; } @Override public String getMimeType(String s) { return null; } @Override public Set<String> getResourcePaths(String s) { return null; } @Override public URL getResource(String s) throws MalformedURLException { return null; } @Override public InputStream getResourceAsStream(String s) { return null; } @Override public RequestDispatcher getRequestDispatcher(String s) { return null; } @Override public RequestDispatcher getNamedDispatcher(String s) { return null; } @Override public Servlet getServlet(String s) throws ServletException { return null; } @Override public Enumeration<Servlet> getServlets() { return null; } @Override public Enumeration<String> getServletNames() { return null; } @Override public void log(String s) { } @Override public void log(Exception e, String s) { } @Override public void log(String s, Throwable throwable) { } @Override public String getRealPath(String s) { return null; } @Override public String getServerInfo() { return null; } @Override public String getInitParameter(String s) { return "/*"; } @Override public Enumeration<String> getInitParameterNames() { return null; } @Override public boolean setInitParameter(String s, String s1) { return false; } @Override public Object getAttribute(String s) { return null; } @Override public Enumeration<String> getAttributeNames() { return null; } @Override public void setAttribute(String s, Object o) { } @Override public void removeAttribute(String s) { } @Override public String getServletContextName() { return null; } @Override public ServletRegistration.Dynamic addServlet(String s, String s1) { return null; } @Override public ServletRegistration.Dynamic addServlet(String s, Servlet servlet) { return null; } @Override public ServletRegistration.Dynamic addServlet(String s, Class<? extends Servlet> aClass) { return null; } @Override public <T extends Servlet> T createServlet(Class<T> aClass) throws ServletException { return null; } @Override public ServletRegistration getServletRegistration(String s) { return null; } @Override public Map<String, ? extends ServletRegistration> getServletRegistrations() { return null; } @Override public FilterRegistration.Dynamic addFilter(String s, String s1) { return null; } @Override public FilterRegistration.Dynamic addFilter(String s, Filter filter) { return null; } @Override public FilterRegistration.Dynamic addFilter(String s, Class<? extends Filter> aClass) { return null; } @Override public <T extends Filter> T createFilter(Class<T> aClass) throws ServletException { return null; } @Override public FilterRegistration getFilterRegistration(String s) { return null; } @Override public Map<String, ? extends FilterRegistration> getFilterRegistrations() { return null; } @Override public SessionCookieConfig getSessionCookieConfig() { return null; } @Override public void setSessionTrackingModes(Set<SessionTrackingMode> set) throws IllegalStateException, IllegalArgumentException { } @Override public Set<SessionTrackingMode> getDefaultSessionTrackingModes() { return null; } @Override public Set<SessionTrackingMode> getEffectiveSessionTrackingModes() { return null; } @Override public void addListener(String s) { } @Override public <T extends EventListener> void addListener(T t) { } @Override public void addListener(Class<? extends EventListener> aClass) { } @Override public <T extends EventListener> T createListener(Class<T> aClass) throws ServletException { return null; } @Override public void declareRoles(String... strings) { } @Override public ClassLoader getClassLoader() { return null; } @Override public JspConfigDescriptor getJspConfigDescriptor() { return null; } }
apache-2.0
fasterthanlime/homebrew
Library/Homebrew/caveats.rb
4459
class Caveats attr_reader :f def initialize(f) @f = f end def caveats caveats = [] caveats << f.caveats if f.caveats.to_s.length > 0 caveats << f.keg_only_text if f.keg_only? && f.respond_to?(:keg_only_text) caveats << bash_completion_caveats caveats << zsh_completion_caveats caveats << plist_caveats caveats << python_caveats caveats << app_caveats caveats.compact.join("\n") end def empty? caveats.empty? end private def keg @keg ||= [f.prefix, f.opt_prefix, f.linked_keg].map do |d| Keg.new(d.resolved_path) rescue nil end.compact.first end def bash_completion_caveats if keg and keg.completion_installed? :bash then <<-EOS.undent Bash completion has been installed to: #{HOMEBREW_PREFIX}/etc/bash_completion.d EOS end end def zsh_completion_caveats if keg and keg.completion_installed? :zsh then <<-EOS.undent zsh completion has been installed to: #{HOMEBREW_PREFIX}/share/zsh/site-functions EOS end end def python_caveats return unless keg return unless keg.python_site_packages_installed? return if Formula["python"].installed? site_packages = if f.keg_only? "#{f.opt_prefix}/lib/python2.7/site-packages" else "#{HOMEBREW_PREFIX}/lib/python2.7/site-packages" end dir = "~/Library/Python/2.7/lib/python/site-packages" dir_path = Pathname.new(dir).expand_path file = "#{dir}/homebrew.pth" file_path = Pathname.new(file).expand_path if !file_path.readable? || !file_path.read.include?(site_packages) s = "If you need Python to find the installed site-packages:\n" s += " mkdir -p #{dir}\n" unless dir_path.exist? s += " echo '#{site_packages}' > #{file}" end end def app_caveats if keg and keg.app_installed? <<-EOS.undent .app bundles were installed. Run `brew linkapps` to symlink these to /Applications. EOS end end def plist_caveats s = [] if f.plist or (keg and keg.plist_installed?) destination = f.plist_startup ? '/Library/LaunchDaemons' \ : '~/Library/LaunchAgents' plist_filename = f.plist_path.basename plist_link = "#{destination}/#{plist_filename}" plist_domain = f.plist_path.basename('.plist') destination_path = Pathname.new File.expand_path destination plist_path = destination_path/plist_filename # we readlink because this path probably doesn't exist since caveats # occurs before the link step of installation if (not plist_path.file?) and (not plist_path.symlink?) if f.plist_startup s << "To have launchd start #{f.name} at startup:" s << " sudo mkdir -p #{destination}" unless destination_path.directory? s << " sudo cp -fv #{f.opt_prefix}/*.plist #{destination}" else s << "To have launchd start #{f.name} at login:" s << " mkdir -p #{destination}" unless destination_path.directory? s << " ln -sfv #{f.opt_prefix}/*.plist #{destination}" end s << "Then to load #{f.name} now:" if f.plist_startup s << " sudo launchctl load #{plist_link}" else s << " launchctl load #{plist_link}" end if f.plist_manual s << "Or, if you don't want/need launchctl, you can just run:" s << " #{f.plist_manual}" end elsif Kernel.system "/bin/launchctl list #{plist_domain} &>/dev/null" s << "To reload #{f.name} after an upgrade:" if f.plist_startup s << " sudo launchctl unload #{plist_link}" s << " sudo cp -fv #{f.opt_prefix}/*.plist #{destination}" s << " sudo launchctl load #{plist_link}" else s << " launchctl unload #{plist_link}" s << " launchctl load #{plist_link}" end else s << "To load #{f.name}:" if f.plist_startup s << " sudo launchctl load #{plist_link}" else s << " launchctl load #{plist_link}" end if f.plist_manual s << "Or, if you don't want/need launchctl, you can just run:" s << " #{f.plist_manual}" end end s << '' << "WARNING: launchctl will fail when run under tmux." if ENV['TMUX'] end s.join("\n") unless s.empty? end end
bsd-2-clause
carlmod/homebrew-cask
Casks/streakerbar.rb
395
cask :v1 => 'streakerbar' do version '1.0' sha256 '70c4e5863d1eaaf4c8ed96e1e110ca9f48de811bdffb92beb024827e08947e72' url "http://github.com/chaserx/streakerbar/releases/download/v#{version}/streakerbar.zip" appcast 'http://github.com/chaserx/streakerbar/releases.atom' name 'streakerbar' homepage 'https://github.com/chaserx/streakerbar' license :mit app 'streakerbar.app' end
bsd-2-clause
quantumsteve/homebrew
Library/Formula/elasticsearch.rb
4053
class Elasticsearch < Formula desc "Distributed search & analytics engine" homepage "https://www.elastic.co/products/elasticsearch" url "https://download.elasticsearch.org/elasticsearch/release/org/elasticsearch/distribution/tar/elasticsearch/2.2.1/elasticsearch-2.2.1.tar.gz" sha256 "7d43d18a8ee8d715d827ed26b4ff3d939628f5a5b654c6e8de9d99bf3a9b2e03" head do url "https://github.com/elasticsearch/elasticsearch.git" depends_on :java => "1.8" depends_on "gradle" => :build end bottle :unneeded depends_on :java => "1.7+" def cluster_name "elasticsearch_#{ENV["USER"]}" end def install if build.head? # Build the package from source system "gradle", "clean", "assemble" # Extract the package to the current directory targz = Dir["distribution/tar/build/distributions/elasticsearch-*.tar.gz"].first system "tar", "--strip-components=1", "-xf", targz end # Remove Windows files rm_f Dir["bin/*.bat"] rm_f Dir["bin/*.exe"] # Install everything else into package directory libexec.install "bin", "config", "lib", "modules" # Set up Elasticsearch for local development: inreplace "#{libexec}/config/elasticsearch.yml" do |s| # 1. Give the cluster a unique name s.gsub!(/#\s*cluster\.name\: .*/, "cluster.name: #{cluster_name}") # 2. Configure paths s.sub!(%r{#\s*path\.data: /path/to.+$}, "path.data: #{var}/elasticsearch/") s.sub!(%r{#\s*path\.logs: /path/to.+$}, "path.logs: #{var}/log/elasticsearch/") end inreplace "#{libexec}/bin/elasticsearch.in.sh" do |s| # Configure ES_HOME s.sub!(%r{#\!/bin/sh\n}, "#!/bin/sh\n\nES_HOME=#{libexec}") end inreplace "#{libexec}/bin/plugin" do |s| # Add the proper ES_CLASSPATH configuration s.sub!(/SCRIPT="\$0"/, %(SCRIPT="$0"\nES_CLASSPATH=#{libexec}/lib)) # Replace paths to use libexec instead of lib s.gsub!(%r{\$ES_HOME/lib/}, "$ES_CLASSPATH/") end # Move config files into etc (etc/"elasticsearch").install Dir[libexec/"config/*"] (etc/"elasticsearch/scripts").mkdir unless File.exist?(etc/"elasticsearch/scripts") (libexec/"config").rmtree bin.write_exec_script Dir[libexec/"bin/elasticsearch"] end def post_install # Make sure runtime directories exist (var/"elasticsearch/#{cluster_name}").mkpath (var/"log/elasticsearch").mkpath ln_s etc/"elasticsearch", libexec/"config" (libexec/"plugins").mkdir end def caveats; <<-EOS.undent Data: #{var}/elasticsearch/#{cluster_name}/ Logs: #{var}/log/elasticsearch/#{cluster_name}.log Plugins: #{libexec}/plugins/ Config: #{etc}/elasticsearch/ plugin script: #{libexec}/bin/plugin EOS end plist_options :manual => "elasticsearch" def plist; <<-EOS.undent <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>KeepAlive</key> <false/> <key>Label</key> <string>#{plist_name}</string> <key>ProgramArguments</key> <array> <string>#{HOMEBREW_PREFIX}/bin/elasticsearch</string> </array> <key>EnvironmentVariables</key> <dict> </dict> <key>RunAtLoad</key> <true/> <key>WorkingDirectory</key> <string>#{var}</string> <key>StandardErrorPath</key> <string>#{var}/log/elasticsearch.log</string> <key>StandardOutPath</key> <string>#{var}/log/elasticsearch.log</string> </dict> </plist> EOS end test do system "#{libexec}/bin/plugin", "list" pid = "#{testpath}/pid" begin mkdir testpath/"config" system "#{bin}/elasticsearch", "-d", "-p", pid, "--path.home", testpath sleep 10 system "curl", "-XGET", "localhost:9200/" ensure Process.kill(9, File.read(pid).to_i) end end end
bsd-2-clause
victorv/arrayfire
src/backend/opencl/select.hpp
645
/******************************************************* * Copyright (c) 2015, ArrayFire * All rights reserved. * * This file is distributed under 3-clause BSD license. * The complete license agreement can be obtained at: * http://arrayfire.com/licenses/BSD-3-Clause ********************************************************/ #pragma once #include <Array.hpp> namespace opencl { template<typename T> void select(Array<T> &out, const Array<char> &cond, const Array<T> &a, const Array<T> &b); template<typename T, bool flip> void select_scalar(Array<T> &out, const Array<char> &cond, const Array<T> &a, const double &b); }
bsd-3-clause
joone/chromium-crosswalk
content/test/gpu/page_sets/gpu_rasterization_tests.py
3786
# Copyright 2014 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. from telemetry.story import story_set as story_set_module from gpu_tests import gpu_test_base class GpuRasterizationBlueBoxPage(gpu_test_base.PageBase): def __init__(self, story_set, expectations): super(GpuRasterizationBlueBoxPage, self).__init__( url='file://../../data/gpu/pixel_background.html', page_set=story_set, name='GpuRasterization.BlueBox', expectations=expectations) self.expectations = [ {'comment': 'body-t', 'color': [255, 255, 255], 'tolerance': 0, 'location': [5, 5], 'size': [1, 1]}, {'comment': 'body-r', 'color': [255, 255, 255], 'tolerance': 0, 'location': [215, 5], 'size': [1, 1]}, {'comment': 'body-b', 'color': [255, 255, 255], 'tolerance': 0, 'location': [215, 215], 'size': [1, 1]}, {'comment': 'body-l', 'color': [255, 255, 255], 'tolerance': 0, 'location': [5, 215], 'size': [1, 1]}, {'comment': 'background-t', 'color': [0, 0, 0], 'tolerance': 0, 'location': [30, 30], 'size': [1, 1]}, {'comment': 'background-r', 'color': [0, 0, 0], 'tolerance': 0, 'location': [170, 30], 'size': [1, 1]}, {'comment': 'background-b', 'color': [0, 0, 0], 'tolerance': 0, 'location': [170, 170], 'size': [1, 1]}, {'comment': 'background-l', 'color': [0, 0, 0], 'tolerance': 0, 'location': [30, 170], 'size': [1, 1]}, {'comment': 'box-t', 'color': [0, 0, 255], 'tolerance': 0, 'location': [70, 70], 'size': [1, 1]}, {'comment': 'box-r', 'color': [0, 0, 255], 'tolerance': 0, 'location': [140, 70], 'size': [1, 1]}, {'comment': 'box-b', 'color': [0, 0, 255], 'tolerance': 0, 'location': [140, 140], 'size': [1, 1]}, {'comment': 'box-l', 'color': [0, 0, 255], 'tolerance': 0, 'location': [70, 140], 'size': [1, 1]} ] self.test_rect = [0, 0, 220, 220] def RunNavigateSteps(self, action_runner): super(GpuRasterizationBlueBoxPage, self).RunNavigateSteps(action_runner) action_runner.WaitForJavaScriptCondition( 'domAutomationController._finished', timeout_in_seconds=30) class GpuRasterizationConcavePathsPage(gpu_test_base.PageBase): def __init__(self, story_set, expectations): super(GpuRasterizationConcavePathsPage, self).__init__( url='file://../../data/gpu/concave_paths.html', page_set=story_set, name='GpuRasterization.ConcavePaths', expectations=expectations) self.expectations = [ {'comment': 'outside', 'color': [255, 255, 255], 'tolerance': 0, 'location': [5, 5], 'size': [1, 1]}, {'comment': 'inside', 'color': [255, 215, 0], 'tolerance': 0, 'location': [20, 50], 'size': [1, 1]} ] self.test_rect = [0, 0, 100, 100] def RunNavigateSteps(self, action_runner): super(GpuRasterizationConcavePathsPage, self).RunNavigateSteps( action_runner) action_runner.WaitForJavaScriptCondition( 'domAutomationController._finished', timeout_in_seconds=30) class GpuRasterizationTestsStorySet(story_set_module.StorySet): """ Basic test cases for GPU rasterization. """ def __init__(self, expectations): super(GpuRasterizationTestsStorySet, self).__init__() self.AddStory(GpuRasterizationBlueBoxPage(self, expectations)) self.AddStory(GpuRasterizationConcavePathsPage(self, expectations))
bsd-3-clause
antiface/mne-python
tutorials/plot_cluster_stats_spatio_temporal.py
7497
""" .. _tut_stats_cluster_source_1samp: ================================================================= Permutation t-test on source data with spatio-temporal clustering ================================================================= Tests if the evoked response is significantly different between conditions across subjects (simulated here using one subject's data). The multiple comparisons problem is addressed with a cluster-level permutation test across space and time. """ # Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr> # Eric Larson <larson.eric.d@gmail.com> # License: BSD (3-clause) import os.path as op import numpy as np from numpy.random import randn from scipy import stats as stats import mne from mne import (io, spatial_tris_connectivity, compute_morph_matrix, grade_to_tris) from mne.epochs import equalize_epoch_counts from mne.stats import (spatio_temporal_cluster_1samp_test, summarize_clusters_stc) from mne.minimum_norm import apply_inverse, read_inverse_operator from mne.datasets import sample print(__doc__) ############################################################################### # Set parameters data_path = sample.data_path() raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif' event_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw-eve.fif' subjects_dir = data_path + '/subjects' tmin = -0.2 tmax = 0.3 # Use a lower tmax to reduce multiple comparisons # Setup for reading the raw data raw = io.Raw(raw_fname) events = mne.read_events(event_fname) ############################################################################### # Read epochs for all channels, removing a bad one raw.info['bads'] += ['MEG 2443'] picks = mne.pick_types(raw.info, meg=True, eog=True, exclude='bads') event_id = 1 # L auditory reject = dict(grad=1000e-13, mag=4000e-15, eog=150e-6) epochs1 = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks, baseline=(None, 0), reject=reject, preload=True) event_id = 3 # L visual epochs2 = mne.Epochs(raw, events, event_id, tmin, tmax, picks=picks, baseline=(None, 0), reject=reject, preload=True) # Equalize trial counts to eliminate bias (which would otherwise be # introduced by the abs() performed below) equalize_epoch_counts([epochs1, epochs2]) ############################################################################### # Transform to source space fname_inv = data_path + '/MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif' snr = 3.0 lambda2 = 1.0 / snr ** 2 method = "dSPM" # use dSPM method (could also be MNE or sLORETA) inverse_operator = read_inverse_operator(fname_inv) sample_vertices = [s['vertno'] for s in inverse_operator['src']] # Let's average and compute inverse, resampling to speed things up evoked1 = epochs1.average() evoked1.resample(50) condition1 = apply_inverse(evoked1, inverse_operator, lambda2, method) evoked2 = epochs2.average() evoked2.resample(50) condition2 = apply_inverse(evoked2, inverse_operator, lambda2, method) # Let's only deal with t > 0, cropping to reduce multiple comparisons condition1.crop(0, None) condition2.crop(0, None) tmin = condition1.tmin tstep = condition1.tstep ############################################################################### # Transform to common cortical space # Normally you would read in estimates across several subjects and morph # them to the same cortical space (e.g. fsaverage). For example purposes, # we will simulate this by just having each "subject" have the same # response (just noisy in source space) here. Note that for 7 subjects # with a two-sided statistical test, the minimum significance under a # permutation test is only p = 1/(2 ** 6) = 0.015, which is large. n_vertices_sample, n_times = condition1.data.shape n_subjects = 7 print('Simulating data for %d subjects.' % n_subjects) # Let's make sure our results replicate, so set the seed. np.random.seed(0) X = randn(n_vertices_sample, n_times, n_subjects, 2) * 10 X[:, :, :, 0] += condition1.data[:, :, np.newaxis] X[:, :, :, 1] += condition2.data[:, :, np.newaxis] # It's a good idea to spatially smooth the data, and for visualization # purposes, let's morph these to fsaverage, which is a grade 5 source space # with vertices 0:10242 for each hemisphere. Usually you'd have to morph # each subject's data separately (and you might want to use morph_data # instead), but here since all estimates are on 'sample' we can use one # morph matrix for all the heavy lifting. fsave_vertices = [np.arange(10242), np.arange(10242)] morph_mat = compute_morph_matrix('sample', 'fsaverage', sample_vertices, fsave_vertices, 20, subjects_dir) n_vertices_fsave = morph_mat.shape[0] # We have to change the shape for the dot() to work properly X = X.reshape(n_vertices_sample, n_times * n_subjects * 2) print('Morphing data.') X = morph_mat.dot(X) # morph_mat is a sparse matrix X = X.reshape(n_vertices_fsave, n_times, n_subjects, 2) # Finally, we want to compare the overall activity levels in each condition, # the diff is taken along the last axis (condition). The negative sign makes # it so condition1 > condition2 shows up as "red blobs" (instead of blue). X = np.abs(X) # only magnitude X = X[:, :, :, 0] - X[:, :, :, 1] # make paired contrast ############################################################################### # Compute statistic # To use an algorithm optimized for spatio-temporal clustering, we # just pass the spatial connectivity matrix (instead of spatio-temporal) print('Computing connectivity.') connectivity = spatial_tris_connectivity(grade_to_tris(5)) # Note that X needs to be a multi-dimensional array of shape # samples (subjects) x time x space, so we permute dimensions X = np.transpose(X, [2, 1, 0]) # Now let's actually do the clustering. This can take a long time... # Here we set the threshold quite high to reduce computation. p_threshold = 0.001 t_threshold = -stats.distributions.t.ppf(p_threshold / 2., n_subjects - 1) print('Clustering.') T_obs, clusters, cluster_p_values, H0 = clu = \ spatio_temporal_cluster_1samp_test(X, connectivity=connectivity, n_jobs=2, threshold=t_threshold) # Now select the clusters that are sig. at p < 0.05 (note that this value # is multiple-comparisons corrected). good_cluster_inds = np.where(cluster_p_values < 0.05)[0] ############################################################################### # Visualize the clusters print('Visualizing clusters.') # Now let's build a convenient representation of each cluster, where each # cluster becomes a "time point" in the SourceEstimate stc_all_cluster_vis = summarize_clusters_stc(clu, tstep=tstep, vertices=fsave_vertices, subject='fsaverage') # Let's actually plot the first "time point" in the SourceEstimate, which # shows all the clusters, weighted by duration subjects_dir = op.join(data_path, 'subjects') # blue blobs are for condition A < condition B, red for A > B brain = stc_all_cluster_vis.plot(hemi='both', subjects_dir=subjects_dir, time_label='Duration significant (ms)') brain.set_data_time_index(0) brain.show_view('lateral') brain.save_image('clusters.png')
bsd-3-clause
josharian/go.ssa
src/image/draw/bench_test.go
5788
// Copyright 2011 The Go 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 draw import ( "image" "image/color" "testing" ) const ( dstw, dsth = 640, 480 srcw, srch = 400, 300 ) // bench benchmarks drawing src and mask images onto a dst image with the // given op and the color models to create those images from. // The created images' pixels are initialized to non-zero values. func bench(b *testing.B, dcm, scm, mcm color.Model, op Op) { b.StopTimer() var dst Image switch dcm { case color.RGBAModel: dst1 := image.NewRGBA(image.Rect(0, 0, dstw, dsth)) for y := 0; y < dsth; y++ { for x := 0; x < dstw; x++ { dst1.SetRGBA(x, y, color.RGBA{ uint8(5 * x % 0x100), uint8(7 * y % 0x100), uint8((7*x + 5*y) % 0x100), 0xff, }) } } dst = dst1 case color.RGBA64Model: dst1 := image.NewRGBA64(image.Rect(0, 0, dstw, dsth)) for y := 0; y < dsth; y++ { for x := 0; x < dstw; x++ { dst1.SetRGBA64(x, y, color.RGBA64{ uint16(53 * x % 0x10000), uint16(59 * y % 0x10000), uint16((59*x + 53*y) % 0x10000), 0xffff, }) } } dst = dst1 default: b.Fatal("unknown destination color model", dcm) } var src image.Image switch scm { case nil: src = &image.Uniform{C: color.RGBA{0x11, 0x22, 0x33, 0xff}} case color.CMYKModel: src1 := image.NewCMYK(image.Rect(0, 0, srcw, srch)) for y := 0; y < srch; y++ { for x := 0; x < srcw; x++ { src1.SetCMYK(x, y, color.CMYK{ uint8(13 * x % 0x100), uint8(11 * y % 0x100), uint8((11*x + 13*y) % 0x100), uint8((31*x + 37*y) % 0x100), }) } } src = src1 case color.GrayModel: src1 := image.NewGray(image.Rect(0, 0, srcw, srch)) for y := 0; y < srch; y++ { for x := 0; x < srcw; x++ { src1.SetGray(x, y, color.Gray{ uint8((11*x + 13*y) % 0x100), }) } } src = src1 case color.RGBAModel: src1 := image.NewRGBA(image.Rect(0, 0, srcw, srch)) for y := 0; y < srch; y++ { for x := 0; x < srcw; x++ { src1.SetRGBA(x, y, color.RGBA{ uint8(13 * x % 0x80), uint8(11 * y % 0x80), uint8((11*x + 13*y) % 0x80), 0x7f, }) } } src = src1 case color.RGBA64Model: src1 := image.NewRGBA64(image.Rect(0, 0, srcw, srch)) for y := 0; y < srch; y++ { for x := 0; x < srcw; x++ { src1.SetRGBA64(x, y, color.RGBA64{ uint16(103 * x % 0x8000), uint16(101 * y % 0x8000), uint16((101*x + 103*y) % 0x8000), 0x7fff, }) } } src = src1 case color.NRGBAModel: src1 := image.NewNRGBA(image.Rect(0, 0, srcw, srch)) for y := 0; y < srch; y++ { for x := 0; x < srcw; x++ { src1.SetNRGBA(x, y, color.NRGBA{ uint8(13 * x % 0x100), uint8(11 * y % 0x100), uint8((11*x + 13*y) % 0x100), 0x7f, }) } } src = src1 case color.YCbCrModel: yy := make([]uint8, srcw*srch) cb := make([]uint8, srcw*srch) cr := make([]uint8, srcw*srch) for i := range yy { yy[i] = uint8(3 * i % 0x100) cb[i] = uint8(5 * i % 0x100) cr[i] = uint8(7 * i % 0x100) } src = &image.YCbCr{ Y: yy, Cb: cb, Cr: cr, YStride: srcw, CStride: srcw, SubsampleRatio: image.YCbCrSubsampleRatio444, Rect: image.Rect(0, 0, srcw, srch), } default: b.Fatal("unknown source color model", scm) } var mask image.Image switch mcm { case nil: // No-op. case color.AlphaModel: mask1 := image.NewAlpha(image.Rect(0, 0, srcw, srch)) for y := 0; y < srch; y++ { for x := 0; x < srcw; x++ { a := uint8((23*x + 29*y) % 0x100) // Glyph masks are typically mostly zero, // so we only set a quarter of mask1's pixels. if a >= 0xc0 { mask1.SetAlpha(x, y, color.Alpha{a}) } } } mask = mask1 default: b.Fatal("unknown mask color model", mcm) } b.StartTimer() for i := 0; i < b.N; i++ { // Scatter the destination rectangle to draw into. x := 3 * i % (dstw - srcw) y := 7 * i % (dsth - srch) DrawMask(dst, dst.Bounds().Add(image.Pt(x, y)), src, image.ZP, mask, image.ZP, op) } } // The BenchmarkFoo functions exercise a drawFoo fast-path function in draw.go. func BenchmarkFillOver(b *testing.B) { bench(b, color.RGBAModel, nil, nil, Over) } func BenchmarkFillSrc(b *testing.B) { bench(b, color.RGBAModel, nil, nil, Src) } func BenchmarkCopyOver(b *testing.B) { bench(b, color.RGBAModel, color.RGBAModel, nil, Over) } func BenchmarkCopySrc(b *testing.B) { bench(b, color.RGBAModel, color.RGBAModel, nil, Src) } func BenchmarkNRGBAOver(b *testing.B) { bench(b, color.RGBAModel, color.NRGBAModel, nil, Over) } func BenchmarkNRGBASrc(b *testing.B) { bench(b, color.RGBAModel, color.NRGBAModel, nil, Src) } func BenchmarkYCbCr(b *testing.B) { bench(b, color.RGBAModel, color.YCbCrModel, nil, Over) } func BenchmarkGray(b *testing.B) { bench(b, color.RGBAModel, color.GrayModel, nil, Over) } func BenchmarkCMYK(b *testing.B) { bench(b, color.RGBAModel, color.CMYKModel, nil, Over) } func BenchmarkGlyphOver(b *testing.B) { bench(b, color.RGBAModel, nil, color.AlphaModel, Over) } func BenchmarkRGBA(b *testing.B) { bench(b, color.RGBAModel, color.RGBA64Model, nil, Src) } // The BenchmarkGenericFoo functions exercise the generic, slow-path code. func BenchmarkGenericOver(b *testing.B) { bench(b, color.RGBA64Model, color.RGBA64Model, nil, Over) } func BenchmarkGenericMaskOver(b *testing.B) { bench(b, color.RGBA64Model, color.RGBA64Model, color.AlphaModel, Over) } func BenchmarkGenericSrc(b *testing.B) { bench(b, color.RGBA64Model, color.RGBA64Model, nil, Src) } func BenchmarkGenericMaskSrc(b *testing.B) { bench(b, color.RGBA64Model, color.RGBA64Model, color.AlphaModel, Src) }
bsd-3-clause
wjdeclan/stansbury-computer-graphics
ClientGame/stdafx.cpp
108
#include "stdafx.h" // TODO: reference any additional headers you need in STDAFX.H // and not in this file
bsd-3-clause
thiz11/platform_external_owasp_sanitizer
src/tests/org/owasp/html/UrlTextExampleTest.java
2472
// Copyright (c) 2013, Mike Samuel // 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 the OWASP 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 THE COPYRIGHT HOLDERS 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 THE // COPYRIGHT HOLDER 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. package org.owasp.html; import java.io.IOException; import junit.framework.TestCase; import org.junit.Test; import org.owasp.html.examples.UrlTextExample; public class UrlTextExampleTest extends TestCase { @Test public void testExample() throws IOException { StringBuilder out = new StringBuilder(); UrlTextExample.run( out, "<a href='//www.example.com/'>Examples<br> like this</a> are fun!\n", "<img src='https://www.example.com/example.png'> are fun!\n", "<a href='www.google.com'>This</a> is not a link to google!" ); assertEquals( "" + "<a href=\"//www.example.com/\">Examples<br /> like this</a>" + " - www.example.com are fun!\n" + "<img src=\"https://www.example.com/example.png\" />" + " - www.example.com are fun!\n" + "<a href=\"www.google.com\">This</a> is not a link to google!", out.toString()); } }
bsd-3-clause
tsibelman/orleans
test/TestGrains/ObserverGrain.cs
907
using System.Threading.Tasks; using Orleans; using UnitTests.GrainInterfaces; namespace UnitTests.Grains { public class ObserverGrain : Grain, IObserverGrain, ISimpleGrainObserver { protected ISimpleGrainObserver Observer { get; set; } // supports only a single observer protected ISimpleObserverableGrain Target { get; set; } #region IObserverGrain Members public Task SetTarget(ISimpleObserverableGrain target) { Target = target; return target.Subscribe(this); } public Task Subscribe(ISimpleGrainObserver observer) { this.Observer = observer; return TaskDone.Done; } #endregion #region ISimpleGrainObserver Members public void StateChanged(int a, int b) { Observer.StateChanged(a, b); } #endregion } }
mit
r0k3/lila
modules/site/src/main/Socket.scala
762
package lila.site import scala.concurrent.duration.Duration import akka.actor._ import play.api.libs.iteratee._ import play.api.libs.json._ import actorApi._ import lila.socket._ import lila.socket.actorApi.SendToFlag private[site] final class Socket(timeout: Duration) extends SocketActor[Member](timeout) { override val startsOnApplicationBoot = true def receiveSpecific = { case Join(uid, username, tags) => { val (enumerator, channel) = Concurrent.broadcast[JsValue] val member = Member(channel, username, tags) addMember(uid, member) sender ! Connected(enumerator, member) } case SendToFlag(flag, message) => members.values filter (_ hasFlag flag) foreach { _.channel push message } } }
mit
Saldum/Paymill-Codeigniter
application/libraries/Paymill/tests/Services/Paymill/ClientsTest.php
4452
<?php /** * @see Services_Paymill_Exception */ require_once '../lib/Services/Paymill/Exception.php'; /** * @see Services_Paymill_Customer */ require_once '../lib/Services/Paymill/Clients.php'; /** * @see Services_Paymill_BaseTest */ require_once 'TestBase.php'; /** * Services_Paymill_Customer test case. */ class Services_Paymill_ClientsTest extends Services_Paymill_TestBase { /** * @var Services_Paymill_Clients */ private $_clients; /** * Prepares the environment before running a test. */ protected function setUp() { parent::setUp (); $this->_clients = new Services_Paymill_Clients($this->_apiTestKey, $this->_apiUrl); } /** * Cleans up the environment after running a test. */ protected function tearDown() { $this->_clients = null; parent::tearDown (); } /** * Tests Services_Paymill_Clients->create() */ public function testCreate() { $email = 'john.bigboote@example.org'; $client = $this->_clients->create(array('email' => $email)); $this->assertArrayHasKey('email', $client, $this->getMessages($email)); $this->assertEquals($email, $client['email']); return $client['id']; } /** * Tests Services_Paymill_Clients->get() * @depends testCreate */ public function testGet() { $filters = array('count'=>10,'offset'=>0,); $clients = $this->_clients->get($filters); $this->assertInternalType('array', $clients); $this->assertGreaterThanOrEqual(1, count($clients), $this->getMessages($clients)); $this->assertArrayHasKey('id', $clients[0]); } /** * Tests Services_Paymill_Clients->getOne() * @depends testCreate */ public function testGetOne($clientId) { $client = $this->_clients->getOne($clientId); $this->assertNotNull($client); $this->assertArrayHasKey('id', $client); $this->assertEquals($clientId, $client['id']); return $client['id']; } /** * Tests Services_Paymill_Clients->getOne() */ public function testGetOneNull() { $client = $this->_clients->getOne(null); $this->assertNull($client); } /** * Tests Services_Paymill_Clients->getOne() */ public function testGetOneUnknownId() { try { $client = $this->_clients->getOne("client_9285c809b6744paymill"); } catch (Exception $e) { $this->assertInstanceOf('Services_Paymill_Exception', $e); $this->assertEquals(404, $e->getCode() ); } } /** * Tests Services_Paymill_Clients->update() * @depends testGetOne */ public function testUpdate($clientId) { $email = 'john.emdall@example.org'; $client = $this->_clients->update(array('id' => $clientId, 'email' => $email) ); $this->assertInternalType('array', $client); $this->assertArrayHasKey('email', $client); $this->assertEquals($email, $client['email']); return $client['id']; } /** * Tests Services_Paymill_Clients->update() */ public function testUpdateUnknownId() { $clientId = 'UNKNOWNID'; $email = 'john.emdall@example.org'; try { $client = $this->_clients->update(array('id' => $clientId, 'email' => $email) ); } catch (Exception $e) { $this->assertInstanceOf('Services_Paymill_Exception', $e); $this->assertEquals(404, $e->getCode() ); } } /** * Tests Services_Paymill_Clients->delete() * @depends testUpdate */ public function testDeleteNull() { try { $response = $this->_clients->delete(null); } catch (Exception $e) { $this->assertInstanceOf('Services_Paymill_Exception', $e); $this->assertEquals(412, $e->getCode() ); } } /** * Tests Services_Paymill_Clients->delete() * @depends testUpdate */ public function testDelete($clientId) { $client = $this->_clients->delete($clientId); $this->assertInternalType('array', $client); $this->assertEquals($clientId, $client["id"]); $client = $this->_clients->getOne($clientId); $this->assertEquals("Client not found", $client["error"]); } }
mit
cyberid41/sculpin
src/Sculpin/Core/Permalink/PermalinkInterface.php
585
<?php /* * This file is a part of Sculpin. * * (c) Dragonfly Development Inc. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sculpin\Core\Permalink; /** * Permalink Interface. * * @author Beau Simensen <beau@dflydev.com> */ interface PermalinkInterface { /** * Relative file path * * @return string */ public function relativeFilePath(); /** * Relative URL path * * @return string */ public function relativeUrlPath(); }
mit
jrrall/simple_node
server.js
233
var Composer = require('./index'); Composer(function (err, server) { if (err) { throw err; } server.start(function () { console.log('Started the plot device on port ' + server.info.port); }); });
mit
pyKy/kivy-doc-ja
kivy/input/postproc/calibration.py
3305
''' Calibration =========== .. versionadded:: 1.9.0 Recalibrate input device to a specific range / offset. Let's say you have 3 1080p displays, the 2 firsts are multitouch. By default, both will have mixed touch, the range will conflict with each others: the 0-1 range will goes to 0-5760 px (remember, 3 * 1920 = 5760.) To fix it, you need to manually reference them. For example:: [input] left = mtdev,/dev/input/event17 middle = mtdev,/dev/input/event15 # the right screen is just a display. Then, you can use the calibration postproc module:: [postproc:calibration] left = xratio=0.3333 middle = xratio=0.3333,xoffset=0.3333 Now, the touches from the left screen will be within 0-0.3333 range, and the touches from the middle screen will be within 0.3333-0.6666 range. ''' __all__ = ('InputPostprocCalibration', ) from kivy.config import Config from kivy.logger import Logger class InputPostprocCalibration(object): '''Recalibrate the inputs. The configuration must go within a section named `postproc:calibration`. Within the section, you must have line like:: devicename = param=value,param=value :Parameters: `xratio`: float Value to multiply X `yratio`: float Value to multiply Y `xoffset`: float Value to add to X `yoffset`: float Value to add to Y ''' def __init__(self): super(InputPostprocCalibration, self).__init__() self.devices = {} self.frame = 0 if not Config.has_section('postproc:calibration'): return default_params = {'xoffset': 0, 'yoffset': 0, 'xratio': 1, 'yratio': 1} for device_key, params_str in Config.items('postproc:calibration'): params = default_params.copy() for param in params_str.split(','): param = param.strip() if not param: continue key, value = param.split('=', 1) if key not in ('xoffset', 'yoffset', 'xratio', 'yratio'): Logger.error( 'Calibration: invalid key provided: {}'.format(key)) params[key] = float(value) self.devices[device_key] = params def process(self, events): # avoid doing any processing if there is no device to calibrate at all. if not self.devices: return events self.frame += 1 frame = self.frame for etype, event in events: # frame-based logic below doesn't account for # end events having been already processed if etype == 'end': continue if event.device not in self.devices: continue # some providers use the same event to update and end if 'calibration:frame' not in event.ud: event.ud['calibration:frame'] = frame elif event.ud['calibration:frame'] == frame: continue params = self.devices[event.device] event.sx = event.sx * params['xratio'] + params['xoffset'] event.sy = event.sy * params['yratio'] + params['yoffset'] event.ud['calibration:frame'] = frame return events
mit
burzum/Robo
tests/unit/CommandStackTest.php
815
<?php use Codeception\Util\Stub; class CommandStackTest extends \Codeception\TestCase\Test { public function testExecStackExecutableIsTrimmedFromCommand() { $commandStack = Stub::make('Robo\Task\CommandStack', array( 'executable' => 'some-executable' )); verify($commandStack ->exec('some-executable status') ->getCommand() )->equals('some-executable status'); } public function testExecStackCommandIsNotTrimmedIfHavingSameCharsAsExecutable() { $commandStack = Stub::make('Robo\Task\CommandStack', array( 'executable' => 'some-executable' )); verify($commandStack ->exec('status') ->getCommand() )->equals('some-executable status'); } }
mit
msanchex/testmasm
libs/charisma/bower_components/datatables/media/unit_testing/tests_onhold/1_dom/bJQueryUI.js
760
// DATA_TEMPLATE: dom_data oTest.fnStart( "bJQueryUI" ); $(document).ready( function () { $('#example').dataTable( { "bJQueryUI": true } ); oTest.fnTest( "Header elements are fully wrapped by DIVs", null, function () { var test = true; $('#example thead th').each( function () { if ( this.childNodes > 1 ) { test = false; } } ); return test; } ); oTest.fnTest( "One div for each header element", null, function () { return $('#example thead th div').length == 5; } ); oTest.fnTest( "One span for each header element, nested as child of div", null, function () { return $('#example thead th div>span').length == 5; } ); oTest.fnComplete(); } );
mit
b923242/scharfrichter
NAudio/CoreAudioApi/Interfaces/IAudioRenderClient.cs
488
using System; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; namespace NAudio.CoreAudioApi.Interfaces { [Guid("F294ACFC-3146-4483-A7BF-ADDCA7C260E2"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] interface IAudioRenderClient { int GetBuffer(int numFramesRequested, out IntPtr dataBufferPointer); int ReleaseBuffer(int numFramesWritten, AudioClientBufferFlags bufferFlags); } }
mit
progre/DefinitelyTyped
react-icons/md/looks-two.d.ts
188
// TypeScript Version: 2.1 import * as React from 'react'; import { IconBaseProps } from 'react-icon-base'; export default class MdLooksTwo extends React.Component<IconBaseProps, any> { }
mit
sensukho/mgcommunity
vendor/sonata-project/media-bundle/Listener/ORM/MediaEventSubscriber.php
1298
<?php /* * This file is part of the Sonata project. * * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sonata\MediaBundle\Listener\ORM; use Doctrine\Common\EventArgs; use Doctrine\ORM\Events; use Sonata\MediaBundle\Listener\BaseMediaEventSubscriber; class MediaEventSubscriber extends BaseMediaEventSubscriber { /** * @return array */ public function getSubscribedEvents() { return array( Events::prePersist, Events::preUpdate, Events::preRemove, Events::postUpdate, Events::postRemove, Events::postPersist, ); } /** * @param \Doctrine\Common\EventArgs $args * @return void */ protected function recomputeSingleEntityChangeSet(EventArgs $args) { $em = $args->getEntityManager(); $em->getUnitOfWork()->recomputeSingleEntityChangeSet( $em->getClassMetadata(get_class($args->getEntity())), $args->getEntity() ); } /** * @inheritdoc */ protected function getMedia(EventArgs $args) { return $args->getEntity(); } }
mit
mocsy/coreclr
tests/src/CoreMangLib/cti/system/enum/enumiconvertibletouint16.cs
5891
using System; /// <summary> /// System.Enum.IConvertibleToUint16(System.Type,IFormatProvider ) /// </summary> public class EnumIConvertibleToUint16 { #region Public Methods public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; retVal = NegTest2() && retVal; return retVal; } #region Positive Test Cases public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: Convert an enum of zero to Uint16"); try { color c1 = color.blue; IConvertible i1 = c1 as IConvertible; UInt16 u1 = i1.ToUInt16(null); if (u1 != 0) { TestLibrary.TestFramework.LogError("001", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: Test a system defined enum type"); try { Enum e2 = System.StringComparison.CurrentCultureIgnoreCase; UInt16 l2 = (e2 as IConvertible).ToUInt16(null); if (l2 != 1) { TestLibrary.TestFramework.LogError("003", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest3: Convert an enum of Uint16.maxvalue to uint16"); try { color c1 = color.white; IConvertible i1 = c1 as IConvertible; UInt16 u1 = i1.ToUInt16(null); if (u1 != UInt16.MaxValue) { TestLibrary.TestFramework.LogError("005", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest4: Convert an enum of negative zero to Uint16 "); try { color c1 = color.red; IConvertible i1 = c1 as IConvertible; UInt16 u1 = i1.ToUInt16(null); if (u1 != 0) { TestLibrary.TestFramework.LogError("007", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e); retVal = false; } return retVal; } #endregion #region Nagetive Test Cases public bool NegTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest1: Convert an enum of negative value to Uint16"); try { e_test e1 = e_test.itemA; IConvertible i1 = e1 as IConvertible; UInt16 u1 = i1.ToUInt16(null); TestLibrary.TestFramework.LogError("101", "The OverflowException was not thrown as expected"); retVal = false; } catch (OverflowException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("102", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest2: Convert an enum of the value which is bigger than uint16.maxvalue to Uint16"); try { e_test e1 = e_test.itemB; IConvertible i1 = e1 as IConvertible; UInt16 u1 = i1.ToUInt16(null); TestLibrary.TestFramework.LogError("103", "The OverflowException was not thrown as expected"); retVal = false; } catch (OverflowException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("104", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } #endregion #endregion public static int Main() { EnumIConvertibleToUint16 test = new EnumIConvertibleToUint16(); TestLibrary.TestFramework.BeginTestCase("EnumIConvertibleToUint16"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } enum color { blue = 0, white = UInt16.MaxValue, red = -0, } enum e_test : long { itemA = -123, itemB = Int32.MaxValue, itemC = Int64.MaxValue, itemD = -0, } }
mit
ravifreek63/jvm
jdk/src/share/demo/jfc/Metalworks/ContrastMetalTheme.java
5019
/* * Copyright (c) 1998, 2011, Oracle and/or its affiliates. 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 Oracle 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 THE COPYRIGHT HOLDERS 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 THE COPYRIGHT OWNER 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. */ import javax.swing.UIDefaults; import javax.swing.border.Border; import javax.swing.border.CompoundBorder; import javax.swing.border.LineBorder; import javax.swing.plaf.BorderUIResource; import javax.swing.plaf.ColorUIResource; import javax.swing.plaf.basic.BasicBorders; import javax.swing.plaf.metal.DefaultMetalTheme; /** * This class describes a higher-contrast Metal Theme. * * @author Michael C. Albers * @author Alexander Kouznetsov */ public class ContrastMetalTheme extends DefaultMetalTheme { @Override public String getName() { return "Contrast"; } private final ColorUIResource primary1 = new ColorUIResource(0, 0, 0); private final ColorUIResource primary2 = new ColorUIResource(204, 204, 204); private final ColorUIResource primary3 = new ColorUIResource(255, 255, 255); private final ColorUIResource primaryHighlight = new ColorUIResource(102, 102, 102); private final ColorUIResource secondary2 = new ColorUIResource(204, 204, 204); private final ColorUIResource secondary3 = new ColorUIResource(255, 255, 255); @Override protected ColorUIResource getPrimary1() { return primary1; } @Override protected ColorUIResource getPrimary2() { return primary2; } @Override protected ColorUIResource getPrimary3() { return primary3; } @Override public ColorUIResource getPrimaryControlHighlight() { return primaryHighlight; } @Override protected ColorUIResource getSecondary2() { return secondary2; } @Override protected ColorUIResource getSecondary3() { return secondary3; } @Override public ColorUIResource getControlHighlight() { return super.getSecondary3(); } @Override public ColorUIResource getFocusColor() { return getBlack(); } @Override public ColorUIResource getTextHighlightColor() { return getBlack(); } @Override public ColorUIResource getHighlightedTextColor() { return getWhite(); } @Override public ColorUIResource getMenuSelectedBackground() { return getBlack(); } @Override public ColorUIResource getMenuSelectedForeground() { return getWhite(); } @Override public ColorUIResource getAcceleratorForeground() { return getBlack(); } @Override public ColorUIResource getAcceleratorSelectedForeground() { return getWhite(); } @Override public void addCustomEntriesToTable(UIDefaults table) { Border blackLineBorder = new BorderUIResource(new LineBorder(getBlack())); Border whiteLineBorder = new BorderUIResource(new LineBorder(getWhite())); Object textBorder = new BorderUIResource(new CompoundBorder( blackLineBorder, new BasicBorders.MarginBorder())); table.put("ToolTip.border", blackLineBorder); table.put("TitledBorder.border", blackLineBorder); table.put("Table.focusCellHighlightBorder", whiteLineBorder); table.put("Table.focusCellForeground", getWhite()); table.put("TextField.border", textBorder); table.put("PasswordField.border", textBorder); table.put("TextArea.border", textBorder); table.put("TextPane.font", textBorder); } }
gpl-2.0
mlundblad/gnome-shell
tests/interactive/border-radius.js
2121
// -*- mode: js; js-indent-level: 4; indent-tabs-mode: nil -*- const Clutter = imports.gi.Clutter; const St = imports.gi.St; const UI = imports.testcommon.ui; function test() { let stage = new Clutter.Stage({ width: 640, height: 480 }); UI.init(stage); let vbox = new St.BoxLayout({ width: stage.width, height: stage.height, style: 'background: #ffee88;' }); stage.add_actor(vbox); let scroll = new St.ScrollView(); vbox.add(scroll, { expand: true }); let box = new St.BoxLayout({ vertical: true, style: 'padding: 10px;' + 'spacing: 20px;' }); scroll.add_actor(box); function addTestCase(radii, useGradient) { let background; if (useGradient) background = 'background-gradient-direction: vertical;' + 'background-gradient-start: white;' + 'background-gradient-end: gray;'; else background = 'background: white;'; box.add(new St.Label({ text: "border-radius: " + radii + ";", style: 'border: 1px solid black; ' + 'border-radius: ' + radii + ';' + 'padding: 5px;' + background }), { x_fill: false }); } // uniform backgrounds addTestCase(" 0px 5px 10px 15px", false); addTestCase(" 5px 10px 15px 0px", false); addTestCase("10px 15px 0px 5px", false); addTestCase("15px 0px 5px 10px", false); // gradient backgrounds addTestCase(" 0px 5px 10px 15px", true); addTestCase(" 5px 10px 15px 0px", true); addTestCase("10px 15px 0px 5px", true); addTestCase("15px 0px 5px 10px", true); // border-radius reduction // these should all take the cairo fallback, // so don't bother testing w/ or w/out gradients. addTestCase("200px 200px 200px 200px", false); addTestCase("200px 200px 0px 200px", false); addTestCase("999px 0px 999px 0px", false); UI.main(stage); } test();
gpl-2.0
PrasadG193/gcc_gimple_fe
libstdc++-v3/testsuite/27_io/basic_ostream/inserters_other/char/exceptions_badbit_throw.cc
1711
// Copyright (C) 2003-2016 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, 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 General Public License for more details. // You should have received a copy of the GNU General Public License along // with this library; see the file COPYING3. If not see // <http://www.gnu.org/licenses/>. #include <ostream> #include <streambuf> #include <sstream> #include <testsuite_hooks.h> #include <testsuite_io.h> using namespace std; void test13() { bool test __attribute__((unused)) = true; __gnu_test::fail_streambuf bob; ostream stream(&bob); stream.exceptions(ios_base::badbit); stringbuf sbuf("Foo, bar, qux", ios_base::in); try { stream << &sbuf; } catch (...) { VERIFY(false); } VERIFY( stream.rdstate() & ios_base::failbit ); VERIFY( (stream.rdstate() & ios_base::badbit) == 0 ); } void test15() { bool test __attribute__((unused)) = true; ostringstream stream; stream.exceptions(ios_base::badbit); __gnu_test::fail_streambuf bib; try { stream << &bib; } catch (...) { VERIFY(false); } VERIFY( stream.rdstate() & ios_base::failbit ); VERIFY( (stream.rdstate() & ios_base::badbit) == 0 ); } // libstdc++/9371 int main() { test13(); test15(); return 0; }
gpl-2.0
YuZhang/ndnSIM
examples/ndn-triangle-calculate-routes.cc
3754
/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2013 University of California, Los Angeles * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Alexander Afanasyev <alexander.afanasyev@ucla.edu> */ // ndn-triangle-calculate-routes.cc #include "ns3/core-module.h" #include "ns3/network-module.h" #include "ns3/ndnSIM-module.h" using namespace ns3; using namespace std; int main (int argc, char *argv[]) { // setting default parameters for PointToPoint links and channels Config::SetDefault ("ns3::PointToPointNetDevice::DataRate", StringValue ("1Mbps")); Config::SetDefault ("ns3::PointToPointChannel::Delay", StringValue ("10ms")); Config::SetDefault ("ns3::DropTailQueue::MaxPackets", StringValue ("20")); // Read optional command-line parameters (e.g., enable visualizer with ./waf --run=<> --visualize CommandLine cmd; cmd.Parse (argc, argv); ofstream file1 ("/tmp/topo1.txt"); file1 << "router\n\n" << "#node city y x mpi-partition\n" << "A1 NA 1 1 1\n" << "B1 NA 80 -40 1\n" << "C1 NA 80 40 1\n" << "A2 NA 1 1 1\n" << "B2 NA 80 -40 1\n" << "C2 NA 80 40 1\n\n" << "link\n\n" << "# from to capacity metric delay queue\n" << "A1 B1 10Mbps 100 1ms 100\n" << "A1 C1 10Mbps 50 1ms 100\n" << "B1 C1 10Mbps 1 1ms 100\n" << "A2 B2 10Mbps 50 1ms 100\n" << "A2 C2 10Mbps 100 1ms 100\n" << "B2 C2 10Mbps 1 1ms 100\n"; file1.close (); AnnotatedTopologyReader topologyReader (""); topologyReader.SetFileName ("/tmp/topo1.txt"); topologyReader.Read (); // Install NDN stack on all nodes ndn::StackHelper ndnHelper; ndnHelper.InstallAll (); topologyReader.ApplyOspfMetric (); ndn::GlobalRoutingHelper ndnGlobalRoutingHelper; ndnGlobalRoutingHelper.InstallAll (); ndnGlobalRoutingHelper.AddOrigins ("/test/prefix", Names::Find<Node> ("C1")); ndnGlobalRoutingHelper.AddOrigins ("/test/prefix", Names::Find<Node> ("C2")); ndn::GlobalRoutingHelper::CalculateRoutes (); cout << "FIB content on node A1" << endl; Ptr<ndn::Fib> fib = Names::Find<Node> ("A1")->GetObject<ndn::Fib> (); for (Ptr<ndn::fib::Entry> entry = fib->Begin (); entry != fib->End (); entry = fib->Next (entry)) { cout << *entry << " (this is towards: "; cout << Names::FindName (DynamicCast<const ndn::NetDeviceFace> (entry->FindBestCandidate (0).GetFace ())->GetNetDevice ()->GetChannel ()->GetDevice (1)->GetNode ()); cout << ")" << endl; } cout << "FIB content on node A2" << endl; fib = Names::Find<Node> ("A2")->GetObject<ndn::Fib> (); for (Ptr<ndn::fib::Entry> entry = fib->Begin (); entry != fib->End (); entry = fib->Next (entry)) { cout << *entry << " (this is towards: "; cout << Names::FindName (DynamicCast<const ndn::NetDeviceFace> (entry->FindBestCandidate (0).GetFace ())->GetNetDevice ()->GetChannel ()->GetDevice (1)->GetNode ()); cout << ")" << endl; } Simulator::Stop (Seconds (20.0)); Simulator::Run (); Simulator::Destroy (); return 0; }
gpl-3.0
maanboyz/android-rage-maker
src/com/tmarki/comicmaker/ImageSelect.java
7099
// Rage Comic Maker for Android (c) Tamas Marki 2011-2013 // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program 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 General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. package com.tmarki.comicmaker; import java.io.IOException; import java.io.InputStream; import java.lang.ref.SoftReference; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Vector; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnKeyListener; import android.content.SharedPreferences.Editor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.os.Handler; import android.text.Editable; import android.text.TextWatcher; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ImageView; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; public class ImageSelect extends Dialog { private ListAdapter packImageSelectAdapter = null; private Context context = null; private CharSequence folderSelected = ""; private PackHandler packhandler = null; Map<CharSequence, Vector<String>> externalImages = null; private BackPressedListener backListener = null; public String[] myStuff; public AdapterView.OnItemClickListener clickListener; public interface BackPressedListener { public void backPressed (); } final LayoutInflater mInflater;/* = (LayoutInflater) getContext() .getSystemService( Context.LAYOUT_INFLATER_SERVICE);*/ public ImageSelect(Context c, CharSequence folder, Map<CharSequence, Vector<String>> externals, BackPressedListener bpl, PackHandler ph) { super (c); context = c; folderSelected = folder; externalImages = externals; backListener = bpl; packhandler = ph; mInflater = (LayoutInflater)c.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } static class QueueItem { public String filename; public ImageLoadedListener listener; } public interface ImageLoadedListener { public void imageLoaded(String filename, SoftReference<BitmapDrawable> imageBitmap ); } Map<CharSequence, Map<CharSequence, Vector<CharSequence>>> mExternalImages = null; private void makeImageSelectAdapter (final String[] imageNames) { myStuff = imageNames; packImageSelectAdapter = new ArrayAdapter<String>( context, R.layout.image_select_row, imageNames) { public View getView(int position, View convertView, ViewGroup parent) { View row; if (null == convertView) { row = mInflater.inflate(R.layout.image_select_row, null); } else { row = convertView; } ImageView tv = (ImageView) row.findViewById(R.id.icon); if (tv != null) { String filename = imageNames[position]; Bitmap bmp = packhandler.getDefaultPackDrawable(folderSelected.toString(), filename, 0, context.getAssets()); if (bmp != null) tv.setImageBitmap(bmp); TextView title = (TextView) row.findViewById(R.id.title); if (title != null) title.setText(filename.replace('-', ' ').replace('_', ' ').replace (".png", "").replace(".jpg", "")); } return row; } }; } private String[] filterMemes (String filt) { if (!folderSelected.equals(PackHandler.ALL_THE_FACES)) { List<String> sv = (List<String>)externalImages.get(folderSelected).clone(); if (filt.length() > 0) { boolean done = false; while (!done) { done = true; for (String ss : sv) { if (!ss.toLowerCase().contains(filt)) { sv.remove(ss); done = false; break; } } } } if (sv.size () > 0) { String[] s = new String[sv.size()]; sv.toArray(s); return s; } } else { int ALL_LIMIT = 10000; int cnt = 0; outerloop: for (CharSequence fold : externalImages.keySet()) { for (String s : externalImages.get(fold)) { if (filt.length() == 0 || s.toLowerCase().contains(filt)) cnt += 1; if (cnt >= ALL_LIMIT) break outerloop; } } if (cnt > 0) { String[] ret = new String[cnt]; cnt = 0; outerloop: for (CharSequence fold : externalImages.keySet()) { for (String s : externalImages.get(fold)) { if (filt.length() == 0 || s.toLowerCase().contains(filt)) { ret[cnt] = s; cnt += 1; } if (cnt >= ALL_LIMIT) break outerloop; } } return ret; } /* sv = new Vector<String>(); for (CharSequence cs : externalImages.keySet()) { if (cs.equals(folderSelected)) continue; sv.addAll(externalImages.get(cs)); } if (folderSelected.equals("--ALL--") && sv.size() > 50) sv = sv.subList(0, 50);*/ } return null; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.imageselect); setTitle(R.string.image_select_title); String[] s = filterMemes (""); final ListView lv = (ListView)findViewById(R.id.imageList); if (s != null/* && !folderSelected.equals("--ALL--")*/) { makeImageSelectAdapter(s); if (lv != null) { lv.setAdapter(packImageSelectAdapter); if (clickListener != null) lv.setOnItemClickListener(clickListener); /* String[] filt = filteredMemes (sharedPref.getString("filter", "")); if (filt != null) setupMemes (lv, filt);*/ } } EditText et = (EditText)findViewById(R.id.searchText); et.addTextChangedListener(new TextWatcher() { public void afterTextChanged(Editable s) { } public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void onTextChanged(CharSequence s, int start, int before, int count) { String str = s.toString().toLowerCase(); String[] filtered = filterMemes(str); if (filtered != null) { makeImageSelectAdapter(filtered); lv.setAdapter(packImageSelectAdapter); } else if (packImageSelectAdapter != null) { lv.setAdapter(null); } } }); } }
gpl-3.0
selmentdev/selment-toolchain
source/gcc-latest/libstdc++-v3/testsuite/27_io/basic_ostream/inserters_arithmetic/char/exceptions_failbit_throw.cc
1734
// Copyright (C) 2003-2016 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, 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 General Public License for more details. // You should have received a copy of the GNU General Public License along // with this library; see the file COPYING3. If not see // <http://www.gnu.org/licenses/>. #include <sstream> #include <testsuite_hooks.h> #include <testsuite_io.h> // libstdc++/10093 template<typename T> void test_failbit() { using namespace std; bool test __attribute__((unused)) = true; locale loc(locale::classic(), new __gnu_test::fail_num_put_char); ostringstream stream("jaylib - champion sound"); stream.imbue(loc); stream.exceptions(ios_base::failbit); try { T i = T(); stream << i; } catch (const ios_base::failure&) { VERIFY( false ); } catch(...) { VERIFY( false ); } // stream should set badbit. VERIFY( stream.bad() ); VERIFY( (stream.rdstate() & ios_base::failbit) == 0 ); VERIFY( !stream.eof() ); } int main() { test_failbit<bool>(); test_failbit<short>(); test_failbit<unsigned short>(); test_failbit<int>(); test_failbit<unsigned int>(); test_failbit<long>(); test_failbit<unsigned long>(); test_failbit<float>(); test_failbit<double>(); return 0; }
gpl-3.0
applifireAlgo/OnlineShopEx
onlineshopping/src/main/webapp/ext/packages/sencha-core/src/data/NodeInterface.js
81227
/** * This class is used as a set of methods that are applied to the prototype of a * Model to decorate it with a Node API. This means that models used in conjunction with a tree * will have all of the tree related methods available on the model. In general this class will * not be used directly by the developer. This class also creates extra fields on the model if * they do not exist, to help maintain the tree state and UI. These fields are documented as * config options. */ Ext.define('Ext.data.NodeInterface', { requires: [ 'Ext.data.field.Boolean', 'Ext.data.field.Integer', 'Ext.data.field.String', 'Ext.data.writer.Json', 'Ext.mixin.Observable' ], /** * @cfg {String} parentId * ID of parent node. */ /** * @cfg {Number} index * The position of the node inside its parent. When parent has 4 children and the node is third amongst them, * index will be 2. */ /** * @cfg {Number} depth * The number of parents this node has. A root node has depth 0, a child of it depth 1, and so on... */ /** * @cfg {Boolean} [expanded=false] * True if the node is expanded. */ /** * @cfg {Boolean} [expandable=false] * Set to true to allow for expanding/collapsing of this node. */ /** * @cfg {Boolean} [checked=null] * Set to true or false to show a checkbox alongside this node. */ /** * @cfg {Boolean} [leaf=false] * Set to true to indicate that this child can have no children. The expand icon/arrow will then not be * rendered for this node. */ /** * @cfg {String} cls * CSS class to apply for this node. */ /** * @cfg {String} iconCls * CSS class to apply for this node's icon. * * There are no default icon classes that come with Ext JS. */ /** * @cfg {String} icon * URL for this node's icon. * * There are no default icons that come with Ext JS. */ /** * @cfg {Boolean} root * True if this is the root node. */ /** * @cfg {Boolean} isLast * True if this is the last node. */ /** * @cfg {Boolean} isFirst * True if this is the first node. */ /** * @cfg {Boolean} [allowDrop=true] * Set to false to deny dropping on this node. */ /** * @cfg {Boolean} [allowDrag=true] * Set to false to deny dragging of this node. */ /** * @cfg {Boolean} [loaded=false] * True if the node has finished loading. */ /** * @cfg {Boolean} [loading=false] * True if the node is currently loading. */ /** * @cfg {String} href * An URL for a link that's created when this config is specified. */ /** * @cfg {String} hrefTarget * Target for link. Only applicable when {@link #href} also specified. */ /** * @cfg {String} qtip * Tooltip text to show on this node. */ /** * @cfg {String} qtitle * Tooltip title. */ /** * @cfg {Number} qshowDelay * Tooltip showDelay. */ /** * @cfg {String} text * The text to show on node label. */ /** * @cfg {Ext.data.NodeInterface[]} children * Array of child nodes. */ /** * @property {Ext.data.NodeInterface} nextSibling * A reference to this node's next sibling node. `null` if this node does not have a next sibling. */ /** * @property {Ext.data.NodeInterface} previousSibling * A reference to this node's previous sibling node. `null` if this node does not have a previous sibling. */ /** * @property {Ext.data.NodeInterface} parentNode * A reference to this node's parent node. `null` if this node is the root node. */ /** * @property {Ext.data.NodeInterface} lastChild * A reference to this node's last child node. `null` if this node has no children. */ /** * @property {Ext.data.NodeInterface} firstChild * A reference to this node's first child node. `null` if this node has no children. */ /** * @property {Ext.data.NodeInterface[]} childNodes * An array of this nodes children. Array will be empty if this node has no chidren. */ statics: { /** * This method allows you to decorate a Model's class to implement the NodeInterface. * This adds a set of methods, new events, new properties and new fields on every Record. * @param {Ext.Class/Ext.data.Model} model The Model class or an instance of the Model class you want to * decorate the prototype of. * @static */ decorate: function (modelClass) { var model = Ext.data.schema.Schema.lookupEntity(modelClass), proto = model.prototype, idName, idField, idType; if (!model.prototype.isObservable) { model.mixin(Ext.mixin.Observable.prototype.mixinId, Ext.mixin.Observable); } if (proto.isNode) { // if (already decorated) return; } idName = proto.idProperty; idField = model.getField(idName); idType = idField.type; model.override(this.getPrototypeBody()); model.addFields([ { name : 'parentId', type : idType, defaultValue : null, allowNull : idField.allowNull }, { name : 'index', type : 'int', defaultValue : -1, persist : false , convert: null }, { name : 'depth', type : 'int', defaultValue : 0, persist : false , convert: null }, { name : 'expanded', type : 'bool', defaultValue : false, persist : false , convert: null }, { name : 'expandable', type : 'bool', defaultValue : true, persist : false , convert: null }, { name : 'checked', type : 'auto', defaultValue : null, persist : false , convert: null }, { name : 'leaf', type : 'bool', defaultValue : false }, { name : 'cls', type : 'string', defaultValue : '', persist : false , convert: null }, { name : 'iconCls', type : 'string', defaultValue : '', persist : false , convert: null }, { name : 'icon', type : 'string', defaultValue : '', persist : false , convert: null }, { name : 'root', type : 'boolean', defaultValue : false, persist : false , convert: null }, { name : 'isLast', type : 'boolean', defaultValue : false, persist : false , convert: null }, { name : 'isFirst', type : 'boolean', defaultValue : false, persist : false , convert: null }, { name : 'allowDrop', type : 'boolean', defaultValue : true, persist : false , convert: null }, { name : 'allowDrag', type : 'boolean', defaultValue : true, persist : false , convert: null }, { name : 'loaded', type : 'boolean', defaultValue : false, persist : false , convert: null }, { name : 'loading', type : 'boolean', defaultValue : false, persist : false , convert: null }, { name : 'href', type : 'string', defaultValue : '', persist : false , convert: null }, { name : 'hrefTarget', type : 'string', defaultValue : '', persist : false , convert: null }, { name : 'qtip', type : 'string', defaultValue : '', persist : false , convert: null }, { name : 'qtitle', type : 'string', defaultValue : '', persist : false , convert: null }, { name : 'qshowDelay', type : 'int', defaultValue : 0, persist : false , convert: null }, { name : 'children', type : 'auto', defaultValue : null, persist : false , convert: null }, { name : 'visible', type : 'boolean', defaultValue : true, persist : false }, { name : 'text', type : 'string', persist : false } ]); }, getPrototypeBody: function() { var bubbledEvents = { idchanged : true, append : true, remove : true, move : true, insert : true, beforeappend : true, beforeremove : true, beforemove : true, beforeinsert : true, expand : true, collapse : true, beforeexpand : true, beforecollapse: true, sort : true }; return { /** * @property {Boolean} isNode * `true` in this class to identify an object as an instantiated Node, or subclass thereof. */ isNode: true, constructor: function() { var me = this; me.mixins.observable.constructor.call(me); me.callParent(arguments); me.firstChild = me.lastChild = me.parentNode = me.previousSibling = me.nextSibling = null; me.childNodes = []; // These events are fired on this node, and programatically bubble up the parentNode axis, ending up // walking off the top and firing on the owning Ext.data.TreeStore /** * @event append * Fires when a new child node is appended * @param {Ext.data.NodeInterface} this This node * @param {Ext.data.NodeInterface} node The newly appended node * @param {Number} index The index of the newly appended node */ /** * @event remove * Fires when a child node is removed * @param {Ext.data.NodeInterface} this This node * @param {Ext.data.NodeInterface} node The removed node * @param {Boolean} isMove `true` if the child node is being removed so it can be moved to another position in the tree. * (a side effect of calling {@link Ext.data.NodeInterface#appendChild appendChild} or * {@link Ext.data.NodeInterface#insertBefore insertBefore} with a node that already has a parentNode) */ /** * @event move * Fires when this node is moved to a new location in the tree * @param {Ext.data.NodeInterface} this This node * @param {Ext.data.NodeInterface} oldParent The old parent of this node * @param {Ext.data.NodeInterface} newParent The new parent of this node * @param {Number} index The index it was moved to */ /** * @event insert * Fires when a new child node is inserted. * @param {Ext.data.NodeInterface} this This node * @param {Ext.data.NodeInterface} node The child node inserted * @param {Ext.data.NodeInterface} refNode The child node the node was inserted before */ /** * @event beforeappend * Fires before a new child is appended, return false to cancel the append. * @param {Ext.data.NodeInterface} this This node * @param {Ext.data.NodeInterface} node The child node to be appended */ /** * @event beforeremove * Fires before a child is removed, return false to cancel the remove. * @param {Ext.data.NodeInterface} this This node * @param {Ext.data.NodeInterface} node The child node to be removed * @param {Boolean} isMove `true` if the child node is being removed so it can be moved to another position in the tree. * (a side effect of calling {@link Ext.data.NodeInterface#appendChild appendChild} or * {@link Ext.data.NodeInterface#insertBefore insertBefore} with a node that already has a parentNode) */ /** * @event beforemove * Fires before this node is moved to a new location in the tree. Return false to cancel the move. * @param {Ext.data.NodeInterface} this This node * @param {Ext.data.NodeInterface} oldParent The parent of this node * @param {Ext.data.NodeInterface} newParent The new parent this node is moving to * @param {Number} index The index it is being moved to */ /** * @event beforeinsert * Fires before a new child is inserted, return false to cancel the insert. * @param {Ext.data.NodeInterface} this This node * @param {Ext.data.NodeInterface} node The child node to be inserted * @param {Ext.data.NodeInterface} refNode The child node the node is being inserted before */ /** * @event expand * Fires when this node is expanded. * @param {Ext.data.NodeInterface} this The expanding node */ /** * @event collapse * Fires when this node is collapsed. * @param {Ext.data.NodeInterface} this The collapsing node */ /** * @event beforeexpand * Fires before this node is expanded. * @param {Ext.data.NodeInterface} this The expanding node */ /** * @event beforecollapse * Fires before this node is collapsed. * @param {Ext.data.NodeInterface} this The collapsing node */ /** * @event sort * Fires when this node's childNodes are sorted. * @param {Ext.data.NodeInterface} this This node. * @param {Ext.data.NodeInterface[]} childNodes The childNodes of this node. */ return me; }, /** * Ensures that the passed object is an instance of a Record with the NodeInterface applied * @return {Ext.data.NodeInterface} */ createNode: function (node) { var me = this, childType = me.childType, store, storeReader, nodeProxy, nodeReader, reader, typeProperty, T = me.self; // Passed node's internal data object if (!node.isModel) { // Check this node type's childType configuration if (childType) { T = me.schema.getEntity(childType); } // See if the reader has a typeProperty and use it if possible else { store = me.getTreeStore(); storeReader = store && store.getProxy().getReader(); nodeProxy = me.getProxy(); nodeReader = nodeProxy ? nodeProxy.getReader() : null; // If the node's reader was configured with a special typeProperty (property name which defines the child type name) use that. reader = !storeReader || (nodeReader && nodeReader.initialConfig.typeProperty) ? nodeReader : storeReader; if (reader) { typeProperty = reader.typeProperty; if (typeProperty) { T = me.schema.getEntity(node[typeProperty]); } } } node = new T(node); } // The node may already decorated, but may not have been // so when the model constructor was called. If not, // setup defaults here if (!node.childNodes) { node.firstChild = node.lastChild = node.parentNode = node.previousSibling = node.nextSibling = null; node.childNodes = []; } return node; }, /** * Returns true if this node is a leaf * @return {Boolean} */ isLeaf : function() { return this.get('leaf') === true; }, /** * Sets the first child of this node * @private * @param {Ext.data.NodeInterface} node */ setFirstChild : function(node) { this.firstChild = node; }, /** * Sets the last child of this node * @private * @param {Ext.data.NodeInterface} node */ setLastChild : function(node) { this.lastChild = node; }, /** * Updates general data of this node like isFirst, isLast, depth. This * method is internally called after a node is moved. This shouldn't * have to be called by the developer unless they are creating custom * Tree plugins. * @param {Boolean} commit * @param {Object} info The info to update. May contain any of the following * @param {Object} info.isFirst * @param {Object} info.isLast * @param {Object} info.index * @param {Object} info.depth * @param {Object} info.parentId */ updateInfo: function(commit, info) { var me = this, oldDepth = me.data.depth, childInfo = {}, children = me.childNodes, childCount = children.length, i, phantom = me.phantom, dataObject = me.data, fields = me.fields, modified = me.modified || (me.modified = {}), propName, newValue, field, currentValue, key, newParentId = info.parentId, settingIndexInNewParent, persistentField; if (!info) { Ext.Error.raise('NodeInterface expects update info to be passed'); } // Set the passed field values into the data object. // We do NOT need the expense of Model.set. We just need to ensure // that the dirty flag is set. for (propName in info) { field = fields[me.fieldOrdinals[propName]]; newValue = info[propName]; persistentField = field && field.persist; currentValue = dataObject[propName]; // If we are setting the index value, and the developer has changed it to be persistent, and the // new parent node is different to the starting one, it must be dirty. // The index may be the same value, but it's in a different parent. // This is so that a Writer can write the correct persistent fields which must include // the index to insert at if the parentId has changed. settingIndexInNewParent = persistentField && (propName === 'index') && (currentValue !== -1) && (newParentId && newParentId !== modified.parentId); // If new value is the same (unless we are setting the index in a new parent node), then skip the change. if (!settingIndexInNewParent && me.isEqual(currentValue, newValue)) { continue; } dataObject[propName] = newValue; // Only flag dirty when persistent fields are modified if (persistentField) { // Already modified, just check if we've reverted it back to start value (unless we are setting the index in a new parent node) if (!settingIndexInNewParent && modified.hasOwnProperty(propName)) { // If we have reverted to start value, possibly clear dirty flag if (me.isEqual(modified[propName], newValue)) { // The original value in me.modified equals the new value, so // the field is no longer modified: delete modified[propName]; // We might have removed the last modified field, so check to // see if there are any modified fields remaining and correct // me.dirty: me.dirty = false; for (key in modified) { if (modified.hasOwnProperty(key)){ me.dirty = true; break; } } } } // Not already modified, set dirty flag else { me.dirty = true; modified[propName] = currentValue; } } } if (commit) { me.commit(); me.phantom = phantom; } // The only way child data can be influenced is if this node has changed level in this update. if (me.data.depth !== oldDepth) { childInfo = { depth: me.data.depth + 1 }; for (i = 0; i < childCount; i++) { children[i].updateInfo(commit, childInfo); } } }, /** * Returns true if this node is the last child of its parent * @return {Boolean} */ isLast : function() { return this.get('isLast'); }, /** * Returns true if this node is the first child of its parent * @return {Boolean} */ isFirst : function() { return this.get('isFirst'); }, /** * Returns true if this node has one or more child nodes, else false. * @return {Boolean} */ hasChildNodes : function() { return !this.isLeaf() && this.childNodes.length > 0; }, /** * Returns true if this node has one or more child nodes, or if the <tt>expandable</tt> * node attribute is explicitly specified as true, otherwise returns false. * @return {Boolean} */ isExpandable : function() { var me = this; if (me.get('expandable')) { return !(me.isLeaf() || (me.isLoaded() && !me.phantom && !me.hasChildNodes())); } return false; }, triggerUIUpdate: function() { // This isn't ideal, however none of the underlying fields have changed // but we still need to update the UI this.callJoined('afterEdit', []); }, /** * Inserts node(s) as the last child node of this node. * * If the node was previously a child node of another parent node, it will be removed from that node first. * * @param {Ext.data.NodeInterface/Ext.data.NodeInterface[]/Object} node The node or Array of nodes to append * @param {Boolean} [suppressEvents=false] True to suppress firering of events. * @param {Boolean} [commit=false] * @return {Ext.data.NodeInterface} The appended node if single append, or null if an array was passed */ appendChild: function(node, suppressEvents, commit) { var me = this, i, ln, index, oldParent, previousSibling, childInfo = { isLast: true, parentId: me.getId(), depth: (me.data.depth||0) + 1 }, result; // Coalesce all layouts caused by node append Ext.suspendLayouts(); // if passed an array do them one by one if (Ext.isArray(node)) { ln = node.length; result = new Array(ln); // Suspend view updating and data syncing during update me.callJoined('beginFill'); for (i = 0; i < ln; i++) { result[i] = me.appendChild(node[i], suppressEvents, commit); } // Resume view updating and data syncing after appending all new children. // This will fire the add event to any views (if its the top level append) me.callJoined('endFill', [result]); } else { // Make sure it is a record node = me.createNode(node); if (suppressEvents !== true && me.fireEventArgs("beforeappend", [me, node]) === false) { return false; } index = me.childNodes.length; oldParent = node.parentNode; // it's a move, make sure we move it cleanly if (oldParent) { if (suppressEvents !== true && node.fireEventArgs("beforemove", [node, oldParent, me, index]) === false) { return false; } oldParent.removeChild(node, false, false, oldParent.getTreeStore() === me.getTreeStore()); } index = me.childNodes.length; if (index === 0) { me.setFirstChild(node); } me.childNodes[index] = node; node.parentNode = me; node.nextSibling = null; me.setLastChild(node); previousSibling = me.childNodes[index - 1]; if (previousSibling) { node.previousSibling = previousSibling; previousSibling.nextSibling = node; previousSibling.updateInfo(commit, { isLast: false }); previousSibling.triggerUIUpdate(); } else { node.previousSibling = null; } // Update the new child's info passing in info we already know childInfo.isFirst = index === 0; childInfo.index = index; node.updateInfo(commit, childInfo); // We stop being a leaf as soon as a node is appended if (me.isLeaf()) { me.set('leaf', false); } // As soon as we append a child to this node, we are loaded if (!me.isLoaded()) { me.set('loaded', true); } else if (me.childNodes.length === 1) { me.triggerUIUpdate(); } // Ensure connectors are correct by updating the UI on all intervening nodes (descendants) between last sibling and new node. if (index && me.childNodes[index - 1].isExpanded()) { me.childNodes[index - 1].cascadeBy(me.triggerUIUpdate); } if(!node.isLeaf() && node.phantom) { node.set('loaded', true); } // This node MUST fire its events first, so that if the TreeStore's // onNodeAppend loads and appends local children, the events are still in order; // This node appended this child first, before the descendant cascade. if (suppressEvents !== true) { me.fireEventArgs("append", [me, node, index]); if (oldParent) { node.fireEventArgs("move", [node, oldParent, me, index]); } } // Inform the TreeStore so that the node can be inserted // and registered. me.callJoined('onNodeAppend', [node, index]); result = node; } // Flush layouts caused by updating of the UI Ext.resumeLayouts(true); return result; }, /** * Returns the tree this node is in. * @return {Ext.tree.Panel} The tree panel which owns this node. */ getOwnerTree: function() { var store = this.getTreeStore(); if (store) { return store.ownerTree; } }, /** * Returns the {@link Ext.data.TreeStore} which owns this node. * @return {Ext.data.TreeStore} The TreeStore which owns this node. * */ getTreeStore: function() { return this.store; }, /** * Removes a child node from this node. * @param {Ext.data.NodeInterface} node The node to remove * @param {Boolean} [erase=false] True to erase the record using the * configured proxy. * @return {Ext.data.NodeInterface} The removed node */ removeChild: function(node, erase, suppressEvents, isMove) { var me = this, index = me.indexOf(node), i, childCount, previousSibling; if (index === -1 || (suppressEvents !== true && me.fireEventArgs("beforeremove", [me, node, !!isMove]) === false)) { return false; } // Coalesce all layouts caused by node removal Ext.suspendLayouts(); // remove it from childNodes collection Ext.Array.erase(me.childNodes, index, 1); // update child refs if (me.firstChild === node) { me.setFirstChild(node.nextSibling); } if (me.lastChild === node) { me.setLastChild(node.previousSibling); } // Update previous sibling to point to its new next. previousSibling = node.previousSibling; if (previousSibling) { node.previousSibling.nextSibling = node.nextSibling; } // Update the next sibling to point to its new previous if (node.nextSibling) { node.nextSibling.previousSibling = node.previousSibling; // And if it's the new first child, let it know if (index === 0) { node.nextSibling.updateInfo(false, { isFirst: true }); } // Update subsequent siblings' index values for (i = index, childCount = me.childNodes.length; i < childCount; i++) { me.childNodes[i].updateInfo(false, { index: i }); } } // If the removed node had no next sibling, but had a previous, // update the previous sibling so it knows it's the last else if (previousSibling) { previousSibling.updateInfo(false, { isLast: true }); // We're removing the last child. // Ensure connectors are correct by updating the UI on all intervening nodes (descendants) between previous sibling and new node. if (previousSibling.isExpanded()) { previousSibling.cascadeBy(me.triggerUIUpdate); } // No intervening descendant nodes, just update the previous sibling else { previousSibling.triggerUIUpdate(); } } // If this node suddenly doesnt have childnodes anymore, update myself if (!me.childNodes.length) { me.triggerUIUpdate(); } // Flush layouts caused by updating the UI Ext.resumeLayouts(true); if (suppressEvents !== true) { // Inform the TreeStore so that descendant nodes can be removed. me.callJoined('beforeNodeRemove', [[node], !!isMove]); node.previousSibling = node.nextSibling = node.parentNode = null; me.fireEventArgs('remove', [me, node, !!isMove]); // Inform the TreeStore so that the node unregistered and unjoined. me.callJoined('onNodeRemove', [[node], !!isMove]); } // Update removed node's pointers *after* firing event so that listsners // can tell where the removal took place if (erase) { node.erase(true); } else { node.clear(); } return node; }, /** * Creates a copy (clone) of this Node. * @param {String} [id] A new id, defaults to this Node's id. * @param {Boolean} [deep=false] True to recursively copy all child Nodes into the new Node. * False to copy without child Nodes. * @return {Ext.data.NodeInterface} A copy of this Node. */ copy: function(newId, deep) { var me = this, result = me.callParent(arguments), len = me.childNodes ? me.childNodes.length : 0, i; // Move child nodes across to the copy if required if (deep) { for (i = 0; i < len; i++) { result.appendChild(me.childNodes[i].copy(undefined, true)); } } return result; }, /** * Clears the node. * @private * @param {Boolean} [erase=false] True to erase the node using the configured * proxy. */ clear : function(erase) { var me = this; // clear any references from the node me.parentNode = me.previousSibling = me.nextSibling = null; if (erase) { me.firstChild = me.lastChild = null; } }, /** * Destroys the node. */ erase: function(silent) { /* * Silent is to be used in a number of cases * 1) When setRoot is called. * 2) When destroy on the tree is called * 3) For destroying child nodes on a node */ var me = this, options = me.destroyOptions, nodes = me.childNodes, nLen = nodes.length, n; if (silent === true) { me.clear(true); for (n = 0; n < nLen; n++) { nodes[n].erase(true); } me.childNodes = null; delete me.destroyOptions; me.callParent([options]); } else { me.destroyOptions = silent; // overridden method will be called, since remove will end up calling erase(true); me.remove(true); } }, /** * Inserts the first node before the second node in this nodes childNodes collection. * @param {Ext.data.NodeInterface/Ext.data.NodeInterface[]/Object} node The node to insert * @param {Ext.data.NodeInterface} refNode The node to insert before (if null the node is appended) * @return {Ext.data.NodeInterface} The inserted node */ insertBefore : function(node, refNode, suppressEvents) { var me = this, index = me.indexOf(refNode), oldParent = node.parentNode, refIndex = index, childCount, previousSibling, i; if (!refNode) { // like standard Dom, refNode can be null for append return me.appendChild(node); } // nothing to do if (node === refNode) { return false; } // Make sure it is a record with the NodeInterface node = me.createNode(node); if (suppressEvents !== true && me.fireEventArgs("beforeinsert", [me, node, refNode]) === false) { return false; } // when moving internally, indexes will change after remove if (oldParent === me && me.indexOf(node) < index) { refIndex--; } // it's a move, make sure we move it cleanly if (oldParent) { if (suppressEvents !== true && node.fireEventArgs("beforemove", [node, oldParent, me, index, refNode]) === false) { return false; } oldParent.removeChild(node, false, false, oldParent.getTreeStore() === me.getTreeStore()); } if (refIndex === 0) { me.setFirstChild(node); } Ext.Array.splice(me.childNodes, refIndex, 0, node); node.parentNode = me; node.nextSibling = refNode; refNode.previousSibling = node; previousSibling = me.childNodes[refIndex - 1]; if (previousSibling) { node.previousSibling = previousSibling; previousSibling.nextSibling = node; } else { node.previousSibling = null; } // Integrate the new node into its new position. node.updateInfo(false, { parentId: me.getId(), index: refIndex, isFirst: refIndex === 0, isLast: false, depth: (me.data.depth||0) + 1 }); // Update the index for all following siblings. for (i = refIndex + 1, childCount = me.childNodes.length; i < childCount; i++) { me.childNodes[i].updateInfo(false, { index: i }); } if (!me.isLoaded()) { me.set('loaded', true); } // If this node didnt have any childnodes before, update myself else if (me.childNodes.length === 1) { me.triggerUIUpdate(); } if(!node.isLeaf() && node.phantom) { node.set('loaded', true); } // This node MUST fire its events first, so that if the TreeStore's // onNodeInsert loads and appends local children, the events are still in order; // This node appended this child first, before the descendant cascade. if (suppressEvents !== true) { me.fireEventArgs("insert", [me, node, refNode]); if (oldParent) { node.fireEventArgs("move", [node, oldParent, me, refIndex, refNode]); } } // Inform the TreeStore so that the node can be registered and added me.callJoined('onNodeInsert', [node, refIndex]); return node; }, /** * Inserts a node into this node. * @param {Number} index The zero-based index to insert the node at * @param {Ext.data.NodeInterface} node The node to insert * @return {Ext.data.NodeInterface} The node you just inserted */ insertChild: function(index, node) { var sibling = this.childNodes[index]; if (sibling) { return this.insertBefore(node, sibling); } else { return this.appendChild(node); } }, /** * @private * Used by {@link Ext.tree.Column#initTemplateRendererData} to determine whether a node is the last *visible* * sibling. * */ isLastVisible: function() { var me = this, result = me.data.isLast, next = me.nextSibling; // If it is not the true last and the store is filtered // we need to see if any following siblings are visible. // If any are, return false. if (!result && me.getTreeStore().isFiltered()) { while (next) { if (next.data.visible) { return false; } next = next.nextSibling; } return true; } return result; }, /** * Removes this node from its parent * @param {Boolean} [erase=false] True to erase the node using the configured * proxy. * @return {Ext.data.NodeInterface} this */ remove : function(erase, suppressEvents) { var me = this, parentNode = me.parentNode; if (parentNode) { parentNode.removeChild(me, erase, suppressEvents); } else if (erase) { // If we don't have a parent, just erase it me.erase(true); } return me; }, /** * Removes all child nodes from this node. * @param {Boolean} [erase=false] True to erase the node using the configured * proxy. * @return {Ext.data.NodeInterface} this * @return {Ext.data.NodeInterface} this */ removeAll : function(erase, suppressEvents, fromParent) { // This method duplicates logic from removeChild for the sake of // speed since we can make a number of assumptions because we're // getting rid of everything var me = this, childNodes = me.childNodes, i = 0, len = childNodes.length, node; // Avoid all this if nothing to remove if (!len) { return; } // Inform the TreeStore so that descendant nodes can be removed. me.callJoined('beforeNodeRemove', [childNodes, false]); for (; i < len; ++i) { node = childNodes[i]; node.previousSibling = node.nextSibling = node.parentNode = null; me.fireEventArgs('remove', [me, node, false]); if (erase) { node.erase(true); } // Otherwise.... apparently, removeAll is always recursive. else { node.removeAll(false, suppressEvents, true); } } // Inform the TreeStore so that the node unregistered and unjoined. me.callJoined('onNodeRemove', [childNodes, false]); me.firstChild = me.lastChild = null; me.childNodes.length = 0; if (!fromParent) { me.triggerUIUpdate(); } return me; }, /** * Returns the child node at the specified index. * @param {Number} index * @return {Ext.data.NodeInterface} */ getChildAt : function(index) { return this.childNodes[index]; }, /** * Replaces one child node in this node with another. * @param {Ext.data.NodeInterface} newChild The replacement node * @param {Ext.data.NodeInterface} oldChild The node to replace * @return {Ext.data.NodeInterface} The replaced node */ replaceChild : function(newChild, oldChild, suppressEvents) { var s = oldChild ? oldChild.nextSibling : null; this.removeChild(oldChild, false, suppressEvents); this.insertBefore(newChild, s, suppressEvents); return oldChild; }, /** * Returns the index of a child node * @param {Ext.data.NodeInterface} node * @return {Number} The index of the node or -1 if it was not found */ indexOf : function(child) { return Ext.Array.indexOf(this.childNodes, child); }, /** * Returns the index of a child node that matches the id * @param {String} id The id of the node to find * @return {Number} The index of the node or -1 if it was not found */ indexOfId: function(id) { var childNodes = this.childNodes, len = childNodes.length, i = 0; for (; i < len; ++i) { if (childNodes[i].getId() === id) { return i; } } return -1; }, /** * Gets the hierarchical path from the root of the current node. * @param {String} [field] The field to construct the path from. Defaults to the model idProperty. * @param {String} [separator="/"] A separator to use. * @return {String} The node path */ getPath: function(field, separator) { field = field || this.idProperty; separator = separator || '/'; var path = [this.get(field)], parent = this.parentNode; while (parent) { path.unshift(parent.get(field)); parent = parent.parentNode; } return separator + path.join(separator); }, /** * Returns depth of this node (the root node has a depth of 0) * @return {Number} */ getDepth : function() { return this.get('depth'); }, /** * Bubbles up the tree from this node, calling the specified function with each node. The arguments to the function * will be the args provided or the current node. If the function returns false at any point, * the bubble is stopped. * @param {Function} fn The function to call * @param {Object} [scope] The scope (this reference) in which the function is executed. Defaults to the current Node. * @param {Array} [args] The args to call the function with. Defaults to passing the current Node. */ bubble : function(fn, scope, args) { var p = this; while (p) { if (fn.apply(scope || p, args || [p]) === false) { break; } p = p.parentNode; } }, //<deprecated since=0.99> cascade: function() { if (Ext.isDefined(Ext.global.console)) { Ext.global.console.warn('Ext.data.Node: cascade has been deprecated. Please use cascadeBy instead.'); } return this.cascadeBy.apply(this, arguments); }, //</deprecated> /** * Cascades down the tree from this node, calling the specified functions with each node. The arguments to the function * will be the args provided or the current node. If the `before` function returns false at any point, * the cascade is stopped on that branch. * * Note that the 3 argument form passing `fn, scope, args` is still supported. The `fn` function is as before, called * *before* cascading down into child nodes. If it returns `false`, the child nodes are not traversed. * * @param {Object} spec An object containing before and after functions, scope and an argument list. * @param {Function} [spec.before] A function to call on a node *before* cascading down into child nodes. * If it returns `false`, the child nodes are not traversed. * @param {Function} [spec.after] A function to call on a node *after* cascading down into child nodes. * @param {Object} [spec.scope] The scope (this reference) in which the functions are executed. Defaults to the current Node. * @param {Array} [spec.args] The args to call the function with. Defaults to passing the current Node. */ cascadeBy : function(before, scope, args, after) { var me = this; if (arguments.length === 1 && !Ext.isFunction(before)) { after = before.after; scope = before.scope; args = before.args; before = before.before; } if (!before || before.apply(scope || me, args || [me]) !== false) { var childNodes = me.childNodes, length = childNodes.length, i; for (i = 0; i < length; i++) { childNodes[i].cascadeBy.call(childNodes[i], before, scope, args, after); } if (after) { after.apply(scope || me, args || [me]); } } }, /** * Interates the child nodes of this node, calling the specified function with each node. The arguments to the function * will be the args provided or the current node. If the function returns false at any point, * the iteration stops. * @param {Function} fn The function to call * @param {Object} [scope] The scope (this reference) in which the function is executed. Defaults to the current Node in iteration. * @param {Array} [args] The args to call the function with. Defaults to passing the current Node. */ eachChild : function(fn, scope, args) { var childNodes = this.childNodes, length = childNodes.length, i; for (i = 0; i < length; i++) { if (fn.apply(scope || this, args || [childNodes[i]]) === false) { break; } } }, /** * Finds the first child that has the attribute with the specified value. * @param {String} attribute The attribute name * @param {Object} value The value to search for * @param {Boolean} [deep=false] True to search through nodes deeper than the immediate children * @return {Ext.data.NodeInterface} The found child or null if none was found */ findChild : function(attribute, value, deep) { return this.findChildBy(function() { return this.get(attribute) == value; }, null, deep); }, /** * Finds the first child by a custom function. The child matches if the function passed returns true. * @param {Function} fn A function which must return true if the passed Node is the required Node. * @param {Object} [scope] The scope (this reference) in which the function is executed. Defaults to the Node being tested. * @param {Boolean} [deep=false] True to search through nodes deeper than the immediate children * @return {Ext.data.NodeInterface} The found child or null if none was found */ findChildBy : function(fn, scope, deep) { var cs = this.childNodes, len = cs.length, i = 0, n, res; for (; i < len; i++) { n = cs[i]; if (fn.call(scope || n, n) === true) { return n; } else if (deep) { res = n.findChildBy(fn, scope, deep); if (res !== null) { return res; } } } return null; }, /** * Returns true if this node is an ancestor (at any point) of the passed node. * @param {Ext.data.NodeInterface} node * @return {Boolean} */ contains : function(node) { return node.isAncestor(this); }, /** * Returns true if the passed node is an ancestor (at any point) of this node. * @param {Ext.data.NodeInterface} node * @return {Boolean} */ isAncestor : function(node) { var p = this.parentNode; while (p) { if (p === node) { return true; } p = p.parentNode; } return false; }, /** * Sorts this nodes children using the supplied sort function. * @param {Function} [sortFn] A function which, when passed two Nodes, returns -1, 0 or 1 depending upon required sort order. * * It omitted, the node is sorted according to the existing sorters in the owning {@link Ext.data.TreeStore TreeStore}. * @param {Boolean} [recursive=false] True to apply this sort recursively * @param {Boolean} [suppressEvent=false] True to not fire a sort event. */ sort: function(sortFn, recursive, suppressEvent) { var me = this, childNodes = me.childNodes, ln = childNodes.length, i, n, info = { isFirst: true }; if (ln > 0) { if (!sortFn) { sortFn = me.getTreeStore().getSortFn(); } Ext.Array.sort(childNodes, sortFn); me.setFirstChild(childNodes[0]); me.setLastChild(childNodes[ln - 1]); for (i = 0; i < ln; i++) { n = childNodes[i]; n.previousSibling = childNodes[i-1]; n.nextSibling = childNodes[i+1]; // Update the index and first/last status of children info.isLast = (i === ln - 1); info.index = i; n.updateInfo(false, info); info.isFirst = false; if (recursive && !n.isLeaf()) { n.sort(sortFn, true, true); } } // The suppressEvent flag is basically used to indicate a recursive sort if (suppressEvent !== true) { me.fireEventArgs('sort', [me, childNodes]); // Inform the TreeStore that this node is sorted me.callJoined('onNodeSort', [childNodes]); } } }, /** * Returns `true` if this node is expanded. * @return {Boolean} */ isExpanded: function() { return this.get('expanded'); }, /** * Returns true if this node is loaded * @return {Boolean} */ isLoaded: function() { return this.get('loaded'); }, /** * Returns true if this node is loading * @return {Boolean} */ isLoading: function() { return this.get('loading'); }, /** * Returns true if this node is the root node * @return {Boolean} */ isRoot: function() { return !this.parentNode; }, /** * Returns true if this node is visible. Note that visibility refers to * the structure of the tree, the {@link Ext.tree.Panel#rootVisible} * configuration is not taken into account here. If this method is called * on the root node, it will always be visible. * @return {Boolean} */ isVisible: function() { var parent = this.parentNode; while (parent) { if (!parent.isExpanded()) { return false; } parent = parent.parentNode; } return true; }, /** * Expand this node. * @param {Boolean} [recursive=false] True to recursively expand all the children * @param {Function} [callback] The function to execute once the expand completes * @param {Object} [scope] The scope to run the callback in */ expand: function(recursive, callback, scope) { var me = this; // all paths must call the callback (eventually) or things like // selectPath fail // First we start by checking if this node is a parent if (!me.isLeaf()) { // If it's loading, wait until it loads before proceeding if (me.isLoading()) { me.on('expand', function() { me.expand(recursive, callback, scope); }, me, {single: true}); } else { // Now we check if this record is already expanding or expanded if (!me.isExpanded()) { if (me.fireEventArgs('beforeexpand', [me]) !== false) { // Inform the TreeStore that we intend to expand, and that it should call onChildNodesAvailable // when the child nodes are available me.callJoined('onBeforeNodeExpand', [me.onChildNodesAvailable, me, [recursive, callback, scope]]); } } else if (recursive) { // If it is is already expanded but we want to recursively expand then call expandChildren me.expandChildren(true, callback, scope); } else { Ext.callback(callback, scope || me, [me.childNodes]); } } } else { // If it's not then we fire the callback right away Ext.callback(callback, scope || me); // leaf = no childNodes } }, /** * @private * Called as a callback from the beforeexpand listener fired by {@link #method-expand} when the child nodes have been loaded and appended. */ onChildNodesAvailable: function(records, recursive, callback, scope) { var me = this; // Bracket expansion with layout suspension. // In optimum case, when recursive, child node data are loaded and expansion is synchronous within the suspension. Ext.suspendLayouts(); // Not structural. The TreeView's onUpdate listener just updates the [+] icon to [-] in response. me.set('expanded', true); // TreeStore's onNodeExpand inserts the child nodes below the parent me.callJoined('onNodeExpand', [records, false]); me.fireEventArgs('expand', [me, records]); // Call the expandChildren method if recursive was set to true if (recursive) { me.expandChildren(true, callback, scope); } else { Ext.callback(callback, scope || me, [me.childNodes]); } Ext.resumeLayouts(true); }, /** * Expand all the children of this node. * @param {Boolean} [recursive=false] True to recursively expand all the children * @param {Function} [callback] The function to execute once all the children are expanded * @param {Object} [scope] The scope to run the callback in */ expandChildren: function(recursive, callback, scope, /* private */ singleExpand) { var me = this, origCallback, i, allNodes, expandNodes, ln, node; // Ext 4.2.0 broke the API for this method by adding a singleExpand argument // at index 1. As of 4.2.3 The method signature has been reverted back // to its original pre-4.2.0 state, however, we must check to see if // the 4.2.0 version is being used for compatibility reasons. if (Ext.isBoolean(callback)) { origCallback = callback; callback = scope; scope = singleExpand; singleExpand = origCallback; } if (singleExpand === undefined) { singleExpand = me.getTreeStore().singleExpand; } allNodes = me.childNodes; expandNodes = []; ln = singleExpand ? Math.min(allNodes.length, 1) : allNodes.length; for (i = 0; i < ln; ++i) { node = allNodes[i]; if (!node.isLeaf()) { expandNodes[expandNodes.length] = node; } } ln = expandNodes.length; for (i = 0; i < ln; ++i) { expandNodes[i].expand(recursive); } if (callback) { Ext.callback(callback, scope || me, [me.childNodes]); } }, /** * Collapse this node. * @param {Boolean} [recursive=false] True to recursively collapse all the children * @param {Function} [callback] The function to execute once the collapse completes * @param {Object} [scope] The scope to run the callback in */ collapse: function(recursive, callback, scope) { var me = this, expanded = me.isExpanded(), len = me.childNodes.length, i, collapseChildren; // If this is a parent and // already collapsed but the recursive flag is passed to target child nodes // or // the collapse is not vetoed by a listener if (!me.isLeaf() && ((!expanded && recursive) || me.fireEventArgs('beforecollapse', [me]) !== false)) { // Bracket collapsing with layout suspension. // Collapsing is synchronous within the suspension. Ext.suspendLayouts(); // Inform listeners of a collapse event if we are still expanded. if (me.isExpanded()) { // Set up the callback to set non-leaf descendants to collapsed if necessary. // If recursive, we just need to set all non-leaf descendants to collapsed state. // We *DO NOT* call collapse on them. That would attempt to remove their descendants // from the UI, and that is done: THIS node is collapsed - ALL descendants are removed from the UI. // Descendant non-leaves just silently change state. if (recursive) { collapseChildren = function() { for (i = 0; i < len; i++) { me.childNodes[i].setCollapsed(true); } }; if (callback) { callback = Ext.Function.createSequence(collapseChildren, Ext.Function.bind(callback, scope, [me.childNodes])); } else { callback = collapseChildren; } } else if (callback) { callback = Ext.Function.bind(callback, scope, [me.childNodes]); } // Not structural. The TreeView's onUpdate listener just updates the [+] icon to [-] in response. me.set('expanded', false); // Call the TreeStore's onNodeCollapse which removes all descendant nodes to achieve UI collapse // and passes callback on in its beforecollapse event which is poked into the animWrap for // final calling in the animation callback. me.callJoined('onNodeCollapse', [me.childNodes, callback, scope]); me.fireEventArgs('collapse', [me, me.childNodes]); // So that it's not called at the end callback = null; } // If recursive, we just need to set all non-leaf descendants to collapsed state. // We *DO NOT* call collapse on them. That would attempt to remove their descendants // from the UI, and that is done: THIS node is collapsed - ALL descendants are removed from the UI. // Descendant non-leaves just silently change state. else if (recursive) { for (i = 0; i < len; i++) { me.childNodes[i].setCollapsed(true); } } Ext.resumeLayouts(true); } // Call the passed callback Ext.callback(callback, scope || me, [me.childNodes]); }, /** * @private Sets the node into the collapsed state without affecting the UI. * * This is called when a node is collapsed with the recursive flag. All the descendant * nodes will have been removed from the store, but descendant non-leaf nodes still * need to be set to the collapsed state without affecting the UI. */ setCollapsed: function(recursive) { var me = this, len = me.childNodes.length, i; // Only if we are not a leaf node and the collapse was not vetoed by a listener. if (!me.isLeaf() && me.fireEventArgs('beforecollapse', [me]) !== false) { // Update the state directly. me.data.expanded = false; // Listened for by NodeStore.onNodeCollapse, but will do nothing except pass on the // documented events because the records have already been removed from the store when // the ancestor node was collapsed. me.fireEventArgs('collapse', [me, me.childNodes]); if (recursive) { for (i = 0; i < len; i++) { me.childNodes[i].setCollapsed(true); } } } }, /** * Collapse all the children of this node. * @param {Function} [recursive=false] True to recursively collapse all the children * @param {Function} [callback] The function to execute once all the children are collapsed * @param {Object} [scope] The scope to run the callback in */ collapseChildren: function(recursive, callback, scope) { var me = this, i, allNodes = me.childNodes, ln = allNodes.length, collapseNodes = [], node; // Only bother with loaded, expanded, non-leaf nodes for (i = 0; i < ln; ++i) { node = allNodes[i]; if (!node.isLeaf() && node.isLoaded() && node.isExpanded()) { collapseNodes.push(node); } } ln = collapseNodes.length; if (ln) { // Collapse the collapsible children. // Pass our callback to the last one. for (i = 0; i < ln; ++i) { node = collapseNodes[i]; if (i === ln - 1) { node.collapse(recursive, callback, scope); } else { node.collapse(recursive); } } } else { // Nothing to collapse, so fire the callback Ext.callback(callback, scope); } }, /** * Fires the specified event with the passed parameters (minus the event name, plus the `options` object passed * to {@link Ext.mixin.Observable#addListener addListener}). * * An event may be set to bubble up an Observable parent hierarchy (See {@link Ext.Component#getBubbleTarget}) by * calling {@link Ext.mixin.Observable#enableBubble enableBubble}. * * @param {String} eventName The name of the event to fire. * @param {Object...} args Variable number of parameters are passed to handlers. * @return {Boolean} returns false if any of the handlers return false otherwise it returns true. */ fireEvent: function(eventName) { return this.fireEventArgs(eventName, Ext.Array.slice(arguments, 1)); }, // Node events always bubble, but events which bubble are always created, so bubble in a loop and // only fire when there are listeners at each level. // bubbled events always fire because they cannot tell if there is a listener at each level. fireEventArgs: function(eventName, args) { // Use the model prototype directly. If we have a BaseModel and then a SubModel, // if we access the superclass fireEventArgs it will just refer to the same method // and we end up in an infinite loop. var fireEventArgs = Ext.mixin.Observable.prototype.fireEventArgs, result, eventSource; // The event bubbles (all native NodeInterface events do)... if (bubbledEvents[eventName]) { for (eventSource = this; result !== false && eventSource; eventSource = eventSource.parentNode) { if (eventSource.hasListeners && eventSource.hasListeners[eventName]) { result = fireEventArgs.call(eventSource, eventName, args); } } return result; } // Event does not bubble - call superclass fireEventArgs method else { return fireEventArgs.apply(this, arguments); } }, /** * Creates an object representation of this node including its children. */ serialize: function() { var result = Ext.data.writer.Json.prototype.getRecordData(this), childNodes = this.childNodes, len = childNodes.length, children, i; if (len > 0) { children = []; for (i = 0; i < len; i++) { children.push(childNodes[i].serialize()); } result.children = children; } return result; } }; } } });
gpl-3.0
vipul-sharma20/oh-mainline
vendor/packages/sqlparse/tests/test_grouping.py
13177
# -*- coding: utf-8 -*- import pytest import sqlparse from sqlparse import sql from sqlparse import tokens as T from tests.utils import TestCaseBase class TestGrouping(TestCaseBase): def test_parenthesis(self): s = 'select (select (x3) x2) and (y2) bar' parsed = sqlparse.parse(s)[0] self.ndiffAssertEqual(s, str(parsed)) self.assertEqual(len(parsed.tokens), 9) self.assert_(isinstance(parsed.tokens[2], sql.Parenthesis)) self.assert_(isinstance(parsed.tokens[-3], sql.Parenthesis)) self.assertEqual(len(parsed.tokens[2].tokens), 7) self.assert_(isinstance(parsed.tokens[2].tokens[3], sql.Parenthesis)) self.assertEqual(len(parsed.tokens[2].tokens[3].tokens), 3) def test_comments(self): s = '/*\n * foo\n */ \n bar' parsed = sqlparse.parse(s)[0] self.ndiffAssertEqual(s, unicode(parsed)) self.assertEqual(len(parsed.tokens), 2) def test_assignment(self): s = 'foo := 1;' parsed = sqlparse.parse(s)[0] self.assertEqual(len(parsed.tokens), 1) self.assert_(isinstance(parsed.tokens[0], sql.Assignment)) s = 'foo := 1' parsed = sqlparse.parse(s)[0] self.assertEqual(len(parsed.tokens), 1) self.assert_(isinstance(parsed.tokens[0], sql.Assignment)) def test_identifiers(self): s = 'select foo.bar from "myscheme"."table" where fail. order' parsed = sqlparse.parse(s)[0] self.ndiffAssertEqual(s, unicode(parsed)) self.assert_(isinstance(parsed.tokens[2], sql.Identifier)) self.assert_(isinstance(parsed.tokens[6], sql.Identifier)) self.assert_(isinstance(parsed.tokens[8], sql.Where)) s = 'select * from foo where foo.id = 1' parsed = sqlparse.parse(s)[0] self.ndiffAssertEqual(s, unicode(parsed)) self.assert_(isinstance(parsed.tokens[-1].tokens[-1].tokens[0], sql.Identifier)) s = 'select * from (select "foo"."id" from foo)' parsed = sqlparse.parse(s)[0] self.ndiffAssertEqual(s, unicode(parsed)) self.assert_(isinstance(parsed.tokens[-1].tokens[3], sql.Identifier)) s = "INSERT INTO `test` VALUES('foo', 'bar');" parsed = sqlparse.parse(s)[0] types = [l.ttype for l in parsed.tokens if not l.is_whitespace()] self.assertEquals(types, [T.DML, T.Keyword, None, T.Keyword, None, T.Punctuation]) s = "select 1.0*(a+b) as col, sum(c)/sum(d) from myschema.mytable" parsed = sqlparse.parse(s)[0] self.assertEqual(len(parsed.tokens), 7) self.assert_(isinstance(parsed.tokens[2], sql.IdentifierList)) self.assertEqual(len(parsed.tokens[2].tokens), 4) identifiers = list(parsed.tokens[2].get_identifiers()) self.assertEqual(len(identifiers), 2) self.assertEquals(identifiers[0].get_alias(), u"col") def test_identifier_wildcard(self): p = sqlparse.parse('a.*, b.id')[0] self.assert_(isinstance(p.tokens[0], sql.IdentifierList)) self.assert_(isinstance(p.tokens[0].tokens[0], sql.Identifier)) self.assert_(isinstance(p.tokens[0].tokens[-1], sql.Identifier)) def test_identifier_name_wildcard(self): p = sqlparse.parse('a.*')[0] t = p.tokens[0] self.assertEqual(t.get_name(), '*') self.assertEqual(t.is_wildcard(), True) def test_identifier_invalid(self): p = sqlparse.parse('a.')[0] self.assert_(isinstance(p.tokens[0], sql.Identifier)) self.assertEqual(p.tokens[0].has_alias(), False) self.assertEqual(p.tokens[0].get_name(), None) self.assertEqual(p.tokens[0].get_real_name(), None) self.assertEqual(p.tokens[0].get_parent_name(), 'a') def test_identifier_as_invalid(self): # issue8 p = sqlparse.parse('foo as select *')[0] self.assert_(len(p.tokens), 5) self.assert_(isinstance(p.tokens[0], sql.Identifier)) self.assertEqual(len(p.tokens[0].tokens), 1) self.assertEqual(p.tokens[2].ttype, T.Keyword) def test_identifier_function(self): p = sqlparse.parse('foo() as bar')[0] self.assert_(isinstance(p.tokens[0], sql.Identifier)) self.assert_(isinstance(p.tokens[0].tokens[0], sql.Function)) p = sqlparse.parse('foo()||col2 bar')[0] self.assert_(isinstance(p.tokens[0], sql.Identifier)) self.assert_(isinstance(p.tokens[0].tokens[0], sql.Function)) def test_identifier_extended(self): # issue 15 p = sqlparse.parse('foo+100')[0] self.assert_(isinstance(p.tokens[0], sql.Identifier)) p = sqlparse.parse('foo + 100')[0] self.assert_(isinstance(p.tokens[0], sql.Identifier)) p = sqlparse.parse('foo*100')[0] self.assert_(isinstance(p.tokens[0], sql.Identifier)) def test_identifier_list(self): p = sqlparse.parse('a, b, c')[0] self.assert_(isinstance(p.tokens[0], sql.IdentifierList)) p = sqlparse.parse('(a, b, c)')[0] self.assert_(isinstance(p.tokens[0].tokens[1], sql.IdentifierList)) def test_identifier_list_case(self): p = sqlparse.parse('a, case when 1 then 2 else 3 end as b, c')[0] self.assert_(isinstance(p.tokens[0], sql.IdentifierList)) p = sqlparse.parse('(a, case when 1 then 2 else 3 end as b, c)')[0] self.assert_(isinstance(p.tokens[0].tokens[1], sql.IdentifierList)) def test_identifier_list_other(self): # issue2 p = sqlparse.parse("select *, null, 1, 'foo', bar from mytable, x")[0] self.assert_(isinstance(p.tokens[2], sql.IdentifierList)) l = p.tokens[2] self.assertEqual(len(l.tokens), 13) def test_where(self): s = 'select * from foo where bar = 1 order by id desc' p = sqlparse.parse(s)[0] self.ndiffAssertEqual(s, unicode(p)) self.assertTrue(len(p.tokens), 16) s = 'select x from (select y from foo where bar = 1) z' p = sqlparse.parse(s)[0] self.ndiffAssertEqual(s, unicode(p)) self.assertTrue(isinstance(p.tokens[-3].tokens[-2], sql.Where)) def test_typecast(self): s = 'select foo::integer from bar' p = sqlparse.parse(s)[0] self.ndiffAssertEqual(s, unicode(p)) self.assertEqual(p.tokens[2].get_typecast(), 'integer') self.assertEqual(p.tokens[2].get_name(), 'foo') s = 'select (current_database())::information_schema.sql_identifier' p = sqlparse.parse(s)[0] self.ndiffAssertEqual(s, unicode(p)) self.assertEqual(p.tokens[2].get_typecast(), 'information_schema.sql_identifier') def test_alias(self): s = 'select foo as bar from mytable' p = sqlparse.parse(s)[0] self.ndiffAssertEqual(s, unicode(p)) self.assertEqual(p.tokens[2].get_real_name(), 'foo') self.assertEqual(p.tokens[2].get_alias(), 'bar') s = 'select foo from mytable t1' p = sqlparse.parse(s)[0] self.ndiffAssertEqual(s, unicode(p)) self.assertEqual(p.tokens[6].get_real_name(), 'mytable') self.assertEqual(p.tokens[6].get_alias(), 't1') s = 'select foo::integer as bar from mytable' p = sqlparse.parse(s)[0] self.ndiffAssertEqual(s, unicode(p)) self.assertEqual(p.tokens[2].get_alias(), 'bar') s = ('SELECT DISTINCT ' '(current_database())::information_schema.sql_identifier AS view') p = sqlparse.parse(s)[0] self.ndiffAssertEqual(s, unicode(p)) self.assertEqual(p.tokens[4].get_alias(), 'view') def test_alias_case(self): # see issue46 p = sqlparse.parse('CASE WHEN 1 THEN 2 ELSE 3 END foo')[0] self.assertEqual(len(p.tokens), 1) self.assertEqual(p.tokens[0].get_alias(), 'foo') def test_idlist_function(self): # see issue10 too p = sqlparse.parse('foo(1) x, bar')[0] self.assert_(isinstance(p.tokens[0], sql.IdentifierList)) def test_comparison_exclude(self): # make sure operators are not handled too lazy p = sqlparse.parse('(=)')[0] self.assert_(isinstance(p.tokens[0], sql.Parenthesis)) self.assert_(not isinstance(p.tokens[0].tokens[1], sql.Comparison)) p = sqlparse.parse('(a=1)')[0] self.assert_(isinstance(p.tokens[0].tokens[1], sql.Comparison)) p = sqlparse.parse('(a>=1)')[0] self.assert_(isinstance(p.tokens[0].tokens[1], sql.Comparison)) def test_function(self): p = sqlparse.parse('foo()')[0] self.assert_(isinstance(p.tokens[0], sql.Function)) p = sqlparse.parse('foo(null, bar)')[0] self.assert_(isinstance(p.tokens[0], sql.Function)) self.assertEqual(len(list(p.tokens[0].get_parameters())), 2) def test_varchar(self): p = sqlparse.parse('"text" Varchar(50) NOT NULL')[0] self.assert_(isinstance(p.tokens[2], sql.Function)) class TestStatement(TestCaseBase): def test_get_type(self): f = lambda sql: sqlparse.parse(sql)[0] self.assertEqual(f('select * from foo').get_type(), 'SELECT') self.assertEqual(f('update foo').get_type(), 'UPDATE') self.assertEqual(f(' update foo').get_type(), 'UPDATE') self.assertEqual(f('\nupdate foo').get_type(), 'UPDATE') self.assertEqual(f('foo').get_type(), 'UNKNOWN') # Statements that have a whitespace after the closing semicolon # are parsed as two statements where later only consists of the # trailing whitespace. self.assertEqual(f('\n').get_type(), 'UNKNOWN') def test_identifier_with_operators(): # issue 53 p = sqlparse.parse('foo||bar')[0] assert len(p.tokens) == 1 assert isinstance(p.tokens[0], sql.Identifier) # again with whitespaces p = sqlparse.parse('foo || bar')[0] assert len(p.tokens) == 1 assert isinstance(p.tokens[0], sql.Identifier) def test_identifier_with_op_trailing_ws(): # make sure trailing whitespace isn't grouped with identifier p = sqlparse.parse('foo || bar ')[0] assert len(p.tokens) == 2 assert isinstance(p.tokens[0], sql.Identifier) assert p.tokens[1].ttype is T.Whitespace def test_identifier_with_string_literals(): p = sqlparse.parse('foo + \'bar\'')[0] assert len(p.tokens) == 1 assert isinstance(p.tokens[0], sql.Identifier) # This test seems to be wrong. It was introduced when fixing #53, but #111 # showed that this shouldn't be an identifier at all. I'm leaving this # commented in the source for a while. # def test_identifier_string_concat(): # p = sqlparse.parse('\'foo\' || bar')[0] # assert len(p.tokens) == 1 # assert isinstance(p.tokens[0], sql.Identifier) def test_identifier_consumes_ordering(): # issue89 p = sqlparse.parse('select * from foo order by c1 desc, c2, c3')[0] assert isinstance(p.tokens[-1], sql.IdentifierList) ids = list(p.tokens[-1].get_identifiers()) assert len(ids) == 3 assert ids[0].get_name() == 'c1' assert ids[0].get_ordering() == 'DESC' assert ids[1].get_name() == 'c2' assert ids[1].get_ordering() is None def test_comparison_with_keywords(): # issue90 # in fact these are assignments, but for now we don't distinguish them p = sqlparse.parse('foo = NULL')[0] assert len(p.tokens) == 1 assert isinstance(p.tokens[0], sql.Comparison) assert len(p.tokens[0].tokens) == 5 assert p.tokens[0].left.value == 'foo' assert p.tokens[0].right.value == 'NULL' # make sure it's case-insensitive p = sqlparse.parse('foo = null')[0] assert len(p.tokens) == 1 assert isinstance(p.tokens[0], sql.Comparison) def test_comparison_with_parenthesis(): # issue23 p = sqlparse.parse('(3 + 4) = 7')[0] assert len(p.tokens) == 1 assert isinstance(p.tokens[0], sql.Comparison) comp = p.tokens[0] assert isinstance(comp.left, sql.Parenthesis) assert comp.right.ttype is T.Number.Integer @pytest.mark.parametrize('start', ['FOR', 'FOREACH']) def test_forloops(start): p = sqlparse.parse('%s foo in bar LOOP foobar END LOOP' % start)[0] assert (len(p.tokens)) == 1 assert isinstance(p.tokens[0], sql.For) def test_nested_for(): p = sqlparse.parse('FOR foo LOOP FOR bar LOOP END LOOP END LOOP')[0] assert len(p.tokens) == 1 for1 = p.tokens[0] assert for1.tokens[0].value == 'FOR' assert for1.tokens[-1].value == 'END LOOP' for2 = for1.tokens[6] assert isinstance(for2, sql.For) assert for2.tokens[0].value == 'FOR' assert for2.tokens[-1].value == 'END LOOP' def test_begin(): p = sqlparse.parse('BEGIN foo END')[0] assert len(p.tokens) == 1 assert isinstance(p.tokens[0], sql.Begin) def test_nested_begin(): p = sqlparse.parse('BEGIN foo BEGIN bar END END')[0] assert len(p.tokens) == 1 outer = p.tokens[0] assert outer.tokens[0].value == 'BEGIN' assert outer.tokens[-1].value == 'END' inner = outer.tokens[4] assert inner.tokens[0].value == 'BEGIN' assert inner.tokens[-1].value == 'END' assert isinstance(inner, sql.Begin)
agpl-3.0
murugamsm/webmail-lite
libraries/OAuthClient/login_with_foursquare.php
2177
<?php /* * login_with_foursquare.php * * @(#) $Id: login_with_foursquare.php,v 1.1 2013/10/13 09:41:36 mlemos Exp $ * */ /* * Get the http.php file from http://www.phpclasses.org/httpclient */ require('http.php'); require('oauth_client.php'); $client = new oauth_client_class; $client->server = 'Foursquare'; $client->debug = true; $client->debug_http = true; $client->redirect_uri = 'http://'.$_SERVER['HTTP_HOST']. dirname(strtok($_SERVER['REQUEST_URI'],'?')).'/login_with_foursquare.php'; $client->client_id = ''; $application_line = __LINE__; $client->client_secret = ''; if(strlen($client->client_id) == 0 || strlen($client->client_secret) == 0) die('Please go to Foursquare user applications page '. 'https://foursquare.com/developers/apps , create a new application,'. ' and in the line '.$application_line.' set the client_id to Client ID'. ' and client_secret with Client Secret. '. ' The callback URL must be '.$client->redirect_uri); /* API permissions */ $client->scope = ''; if(($success = $client->Initialize())) { if(($success = $client->Process())) { if(strlen($client->authorization_error)) { $client->error = $client->authorization_error; $success = false; } elseif(strlen($client->access_token)) { $success = $client->CallAPI( 'https://api.foursquare.com/v2/users/self?v=20131013', 'GET', array(), array('FailOnAccessError'=>true), $user); } } $success = $client->Finalize($success); } if($client->exit) exit; if($success) { ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>Foursquare OAuth client results</title> </head> <body> <?php echo '<h1>', HtmlSpecialChars($user->response->user->firstName), ' you have logged in successfully with Foursquare!</h1>'; echo '<pre>', HtmlSpecialChars(print_r($user, 1)), '</pre>'; ?> </body> </html> <?php } else { ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>OAuth client error</title> </head> <body> <h1>OAuth client error</h1> <pre>Error: <?php echo HtmlSpecialChars($client->error); ?></pre> </body> </html> <?php } ?>
agpl-3.0
arildb/tiki-azure
lib/test/language/fixtures/language_writestringstofile_first_call.php
68
<?php // File header $lang = array( "Errors" => "Ошибки", );
lgpl-2.1
TomPradat/thelia
core/lib/Thelia/Action/ModuleHook.php
9507
<?php /*************************************************************************************/ /* This file is part of the Thelia package. */ /* */ /* Copyright (c) OpenStudio */ /* email : dev@thelia.net */ /* web : http://www.thelia.net */ /* */ /* For the full copyright and license information, please view the LICENSE.txt */ /* file that was distributed with this source code. */ /*************************************************************************************/ namespace Thelia\Action; use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Thelia\Core\Event\Cache\CacheEvent; use Thelia\Core\Event\Hook\HookToggleActivationEvent; use Thelia\Core\Event\Hook\HookUpdateEvent; use Thelia\Core\Event\Hook\ModuleHookCreateEvent; use Thelia\Core\Event\Hook\ModuleHookDeleteEvent; use Thelia\Core\Event\Hook\ModuleHookToggleActivationEvent; use Thelia\Core\Event\Hook\ModuleHookUpdateEvent; use Thelia\Core\Event\Module\ModuleDeleteEvent; use Thelia\Core\Event\Module\ModuleToggleActivationEvent; use Thelia\Core\Event\TheliaEvents; use Thelia\Core\Event\UpdatePositionEvent; use Thelia\Core\Translation\Translator; use Thelia\Model\Base\IgnoredModuleHookQuery; use Thelia\Model\HookQuery; use Thelia\Model\IgnoredModuleHook; use Thelia\Model\ModuleHook as ModuleHookModel; use Thelia\Model\ModuleHookQuery; use Thelia\Model\ModuleQuery; use Thelia\Module\BaseModule; /** * Class ModuleHook * @package Thelia\Action * @author Julien Chanséaume <jchanseaume@openstudio.fr> */ class ModuleHook extends BaseAction implements EventSubscriberInterface { /** @var string */ protected $cacheDir; public function __construct($cacheDir) { $this->cacheDir = $cacheDir; } public function toggleModuleActivation(ModuleToggleActivationEvent $event) { if (null !== $module = ModuleQuery::create()->findPk($event->getModuleId())) { ModuleHookQuery::create() ->filterByModuleId($module->getId()) ->update(array('ModuleActive' => ($module->getActivate() == BaseModule::IS_ACTIVATED))); } return $event; } public function deleteModule(ModuleDeleteEvent $event) { if ($event->getModuleId()) { ModuleHookQuery::create() ->filterByModuleId($event->getModuleId()) ->delete(); } return $event; } protected function isModuleActive($module_id) { if (null !== $module = ModuleQuery::create()->findPk($module_id)) { return $module->getActivate(); } return false; } protected function isHookActive($hook_id) { if (null !== $hook = HookQuery::create()->findPk($hook_id)) { return $hook->getActivate(); } return false; } protected function getLastPositionInHook($hook_id) { $result = ModuleHookQuery::create() ->filterByHookId($hook_id) ->withColumn('MAX(ModuleHook.position)', 'maxPos') ->groupBy('ModuleHook.hook_id') ->select(array('maxPos')) ->findOne(); return intval($result) + 1; } public function createModuleHook(ModuleHookCreateEvent $event) { $moduleHook = new ModuleHookModel(); // todo: test if classname and method exists $moduleHook ->setModuleId($event->getModuleId()) ->setHookId($event->getHookId()) ->setActive(false) ->setClassname($event->getClassname()) ->setMethod($event->getMethod()) ->setModuleActive($this->isModuleActive($event->getModuleId())) ->setHookActive($this->isHookActive($event->getHookId())) ->setPosition($this->getLastPositionInHook($event->getHookId())) ->setTemplates($event->getTemplates()) ->save(); // Be sure to delete this module hook from the ignored module hook table IgnoredModuleHookQuery::create() ->filterByHookId($event->getHookId()) ->filterByModuleId($event->getModuleId()) ->delete(); $event->setModuleHook($moduleHook); } public function updateModuleHook(ModuleHookUpdateEvent $event, $eventName, EventDispatcherInterface $dispatcher) { if (null !== $moduleHook = ModuleHookQuery::create()->findPk($event->getModuleHookId())) { // todo: test if classname and method exists $moduleHook ->setHookId($event->getHookId()) ->setModuleId($event->getModuleId()) ->setClassname($event->getClassname()) ->setMethod($event->getMethod()) ->setActive($event->getActive()) ->setHookActive($this->isHookActive($event->getHookId())) ->setTemplates($event->getTemplates()) ->save(); $event->setModuleHook($moduleHook); $this->cacheClear($dispatcher); } } public function deleteModuleHook(ModuleHookDeleteEvent $event, $eventName, EventDispatcherInterface $dispatcher) { if (null !== $moduleHook = ModuleHookQuery::create()->findPk($event->getModuleHookId())) { $moduleHook->delete(); $event->setModuleHook($moduleHook); // Prevent hook recreation by RegisterListenersPass::registerHook() // We store the method here to be able to retreive it when // we need to get all hook declared by a module $imh = new IgnoredModuleHook(); $imh ->setModuleId($moduleHook->getModuleId()) ->setHookId($moduleHook->getHookId()) ->setMethod($moduleHook->getMethod()) ->setClassname($moduleHook->getClassname()) ->save(); $this->cacheClear($dispatcher); } } public function toggleModuleHookActivation(ModuleHookToggleActivationEvent $event, $eventName, EventDispatcherInterface $dispatcher) { if (null !== $moduleHook = $event->getModuleHook()) { if ($moduleHook->getModuleActive()) { $moduleHook->setActive(!$moduleHook->getActive()); $moduleHook->save(); } else { throw new \LogicException(Translator::getInstance()->trans("The module has to be activated.")); } } $this->cacheClear($dispatcher); return $event; } /** * Changes position, selecting absolute ou relative change. * * @param UpdatePositionEvent $event * @param $eventName * @param EventDispatcherInterface $dispatcher * * @return UpdatePositionEvent $event */ public function updateModuleHookPosition(UpdatePositionEvent $event, $eventName, EventDispatcherInterface $dispatcher) { $this->genericUpdatePosition(ModuleHookQuery::create(), $event, $dispatcher); $this->cacheClear($dispatcher); return $event; } public function updateHook(HookUpdateEvent $event, $eventName, EventDispatcherInterface $dispatcher) { if ($event->hasHook()) { $hook = $event->getHook(); ModuleHookQuery::create() ->filterByHookId($hook->getId()) ->update(array('HookActive' => $hook->getActivate())); $this->cacheClear($dispatcher); } } public function toggleHookActivation(HookToggleActivationEvent $event, $eventName, EventDispatcherInterface $dispatcher) { if ($event->hasHook()) { $hook = $event->getHook(); ModuleHookQuery::create() ->filterByHookId($hook->getId()) ->update(array('HookActive' => $hook->getActivate())); $this->cacheClear($dispatcher); } } protected function cacheClear(EventDispatcherInterface $dispatcher) { $cacheEvent = new CacheEvent($this->cacheDir); $dispatcher->dispatch(TheliaEvents::CACHE_CLEAR, $cacheEvent); } /** * {@inheritdoc} */ public static function getSubscribedEvents() { return array( TheliaEvents::MODULE_HOOK_CREATE => array('createModuleHook', 128), TheliaEvents::MODULE_HOOK_UPDATE => array('updateModuleHook', 128), TheliaEvents::MODULE_HOOK_DELETE => array('deleteModuleHook', 128), TheliaEvents::MODULE_HOOK_UPDATE_POSITION => array('updateModuleHookPosition', 128), TheliaEvents::MODULE_HOOK_TOGGLE_ACTIVATION => array('toggleModuleHookActivation', 128), TheliaEvents::MODULE_TOGGLE_ACTIVATION => array('toggleModuleActivation', 64), TheliaEvents::MODULE_DELETE => array('deleteModule', 64), TheliaEvents::HOOK_TOGGLE_ACTIVATION => array('toggleHookActivation', 64), TheliaEvents::HOOK_UPDATE => array('updateHook', 64), ); } }
lgpl-3.0
jmluy/elasticsearch
client/rest-high-level/src/test/java/org/elasticsearch/client/ml/dataframe/stats/outlierdetection/ParametersTests.java
1435
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.client.ml.dataframe.stats.outlierdetection; import org.elasticsearch.test.AbstractXContentTestCase; import org.elasticsearch.xcontent.XContentParser; import java.io.IOException; public class ParametersTests extends AbstractXContentTestCase<Parameters> { @Override protected boolean supportsUnknownFields() { return true; } @Override protected Parameters doParseInstance(XContentParser parser) throws IOException { return Parameters.PARSER.apply(parser, null); } @Override protected Parameters createTestInstance() { return createRandom(); } public static Parameters createRandom() { return new Parameters( randomBoolean() ? null : randomIntBetween(1, Integer.MAX_VALUE), randomBoolean() ? null : randomAlphaOfLength(5), randomBoolean() ? null : randomBoolean(), randomBoolean() ? null : randomDouble(), randomBoolean() ? null : randomDouble(), randomBoolean() ? null : randomBoolean() ); } }
apache-2.0
kuali/kc-rice
rice-middleware/impl/src/main/java/org/kuali/rice/kew/rule/RuleValidationAttribute.java
1515
/** * Copyright 2005-2015 The Kuali Foundation * * Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php * * 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.kuali.rice.kew.rule; import org.kuali.rice.kew.api.validation.RuleValidationContext; import org.kuali.rice.kew.api.validation.ValidationResults; /** * A simple interface for handling validation of rules. Validation results are returned in a * ValidationResults object which consists of a series of error messages regarding the * rule. The user who is adding or editing the rule is passed to validate as well as the * rule to be validated. * * @author Kuali Rice Team (rice.collab@kuali.org) */ public interface RuleValidationAttribute { /** * Validates the rule within the given RuleValidationContext. * * @return a ValidationResults object representing the results of the validation, if this is * empty or <code>null</code> this signifies that validation was successful. */ public ValidationResults validate(RuleValidationContext validationContext); }
apache-2.0
changgyun-woo/webida-client
apps/ide/ProjectWizard-templates/presentation/google-html5/project/js/slide-controller.js
3847
/* * Copyright (c) 2012-2015 S-Core Co., Ltd. * * 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. */ (function(window) { var ORIGIN_ = location.protocol + '//' + location.host; function SlideController() { this.popup = null; this.isPopup = window.opener; if (this.setupDone()) { window.addEventListener('message', this.onMessage_.bind(this), false); // Close popups if we reload the main window. window.addEventListener('beforeunload', function(e) { if (this.popup) { this.popup.close(); } }.bind(this), false); } } SlideController.PRESENTER_MODE_PARAM = 'presentme'; SlideController.prototype.setupDone = function() { var params = location.search.substring(1).split('&').map(function(el) { return el.split('='); }); var presentMe = null; for (var i = 0, param; param = params[i]; ++i) { if (param[0].toLowerCase() == SlideController.PRESENTER_MODE_PARAM) { presentMe = param[1] == 'true'; break; } } if (presentMe !== null) { localStorage.ENABLE_PRESENTOR_MODE = presentMe; // TODO: use window.history.pushState to update URL instead of the redirect. if (window.history.replaceState) { window.history.replaceState({}, '', location.pathname); } else { location.replace(location.pathname); return false; } } var enablePresenterMode = localStorage.getItem('ENABLE_PRESENTOR_MODE'); if (enablePresenterMode && JSON.parse(enablePresenterMode)) { // Only open popup from main deck. Don't want recursive popup opening! if (!this.isPopup) { var opts = 'menubar=no,location=yes,resizable=yes,scrollbars=no,status=no'; this.popup = window.open(location.href, 'mywindow', opts); // Loading in the popup? Trigger the hotkey for turning presenter mode on. this.popup.addEventListener('load', function(e) { var evt = this.popup.document.createEvent('Event'); evt.initEvent('keydown', true, true); evt.keyCode = 'P'.charCodeAt(0); this.popup.document.dispatchEvent(evt); // this.popup.document.body.classList.add('with-notes'); // document.body.classList.add('popup'); }.bind(this), false); } } return true; } SlideController.prototype.onMessage_ = function(e) { var data = e.data; // Restrict messages to being from this origin. Allow local developmet // from file:// though. // TODO: It would be dope if FF implemented location.origin! if (e.origin != ORIGIN_ && ORIGIN_.indexOf('file://') != 0) { alert('Someone tried to postMessage from an unknown origin'); return; } // if (e.source.location.hostname != 'localhost') { // alert('Someone tried to postMessage from an unknown origin'); // return; // } if ('keyCode' in data) { var evt = document.createEvent('Event'); evt.initEvent('keydown', true, true); evt.keyCode = data.keyCode; document.dispatchEvent(evt); } }; SlideController.prototype.sendMsg = function(msg) { // // Send message to popup window. // if (this.popup) { // this.popup.postMessage(msg, ORIGIN_); // } // Send message to main window. if (this.isPopup) { // TODO: It would be dope if FF implemented location.origin. window.opener.postMessage(msg, '*'); } }; window.SlideController = SlideController; })(window);
apache-2.0
CesarPantoja/jena
jena-core/src/test/java/org/apache/jena/rdfxml/xmloutput/TestWriterInterface.java
3177
/* * 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 org.apache.jena.rdfxml.xmloutput; import java.io.ByteArrayOutputStream ; import java.io.StringWriter ; import org.apache.jena.rdf.model.Model ; import org.apache.jena.rdf.model.impl.NTripleWriter ; import org.apache.jena.rdf.model.test.ModelTestBase ; import org.apache.jena.rdfxml.xmloutput.impl.Abbreviated ; import org.apache.jena.rdfxml.xmloutput.impl.Basic ; public class TestWriterInterface extends ModelTestBase { private String lang; /** * Constructor requires that all tests be named * * @param name The name of this test */ public TestWriterInterface(String name, String lang) { super(name); this.lang = lang; //if ( lang!=null) //setName(name+"("+lang+")"); //this. } /** Introduced to cope with bug 832682: double spacing on windows platforms. Make sure the xmlns prefixes are introduced by the correct line separator. (Java doesn't appear to understand that the notion of "line separator" should be portable ... come back C, all is forgiven. Well, not *all* ...) */ public void testLineSeparator() { String newline = System.getProperty( "line.separator" ); String newline_XMLNS = newline + " xmlns"; Model m = modelWithStatements( "http://eh/spoo thingies something" ); m.setNsPrefix( "eh", "http://eh/" ); StringWriter sos = new StringWriter(); m.write( sos ); assertTrue( sos.toString().contains( newline_XMLNS ) ); } public void testInterface() { Model m1 = createMemModel(); assertTrue( "Default writer should be Basic.", m1.getWriter() instanceof Basic ); assertTrue( "RDF/XML writer should be Basic.", m1.getWriter() instanceof Basic ); assertTrue( "RDF/XML-ABBREV writer should be Abbreviated.", m1.getWriter("RDF/XML-ABBREV") instanceof Abbreviated); assertTrue( "N-TRIPLE writer should be NTripleWriter.", m1.getWriter("N-TRIPLE") instanceof NTripleWriter); } public void testWriting() { Model m1 = createMemModel(); try ( ByteArrayOutputStream out = new ByteArrayOutputStream() ) { m1.write(out, lang); out.reset() ; } catch (Exception e) { fail(e.getMessage()); } } }
apache-2.0
CesarPantoja/jena
jena-cmds/src/main/java/tdb/tdbrecovery.java
1731
/* * 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 tdb; import org.apache.jena.tdb.TDB ; import org.apache.jena.tdb.store.DatasetGraphTDB ; import org.apache.jena.tdb.transaction.JournalControl ; import tdb.cmdline.CmdTDB ; public class tdbrecovery extends CmdTDB { static public void main(String... argv) { CmdTDB.init() ; TDB.setOptimizerWarningFlag(false) ; new tdbrecovery(argv).mainRun() ; } protected tdbrecovery(String[] argv) { super(argv) ; } @Override protected String getSummary() { return getCommandName()+" --loc DIRECTORY\nRun database journal recovery." ; } @Override protected void exec() { DatasetGraphTDB dsg = super.getDatasetGraphTDB() ; // Just creating the DSG does a recovery so this is not (currently) necessary: // This may change (not immediately recovering on start up). JournalControl.recovery(dsg) ; } }
apache-2.0
spinolacastro/magento-scalable
php/app/code/core/Mage/Sales/Model/Entity/Order/Shipment/Item/Collection.php
1480
<?php /** * Magento * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@magentocommerce.com so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade Magento to newer * versions in the future. If you wish to customize Magento for your * needs please refer to http://www.magentocommerce.com for more information. * * @category Mage * @package Mage_Sales * @copyright Copyright (c) 2013 Magento Inc. (http://www.magentocommerce.com) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ /** * Order shipment items collection * * @category Mage * @package Mage_Sales * @author Magento Core Team <core@magentocommerce.com> */ class Mage_Sales_Model_Entity_Order_Shipment_Item_Collection extends Mage_Eav_Model_Entity_Collection_Abstract { protected function _construct() { $this->_init('sales/order_shipment_item'); } public function setShipmentFilter($shipmentId) { $this->addAttributeToFilter('parent_id', $shipmentId); return $this; } }
apache-2.0
cripure/openpne3
lib/vendor/Zend/Feed/Builder.php
17921
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Feed * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id: Builder.php 8064 2008-02-16 10:58:39Z thomas $ */ /** * @see Zend_Feed_Builder_Interface */ require_once 'Zend/Feed/Builder/Interface.php'; /** * @see Zend_Feed_Builder_Header */ require_once 'Zend/Feed/Builder/Header.php'; /** * @see Zend_Feed_Builder_Entry */ require_once 'Zend/Feed/Builder/Entry.php'; /** * A simple implementation of Zend_Feed_Builder_Interface. * * Users are encouraged to make their own classes to implement Zend_Feed_Builder_Interface * * @category Zend * @package Zend_Feed * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Feed_Builder implements Zend_Feed_Builder_Interface { /** * The data of the feed * * @var $_data array */ private $_data; /** * Header of the feed * * @var $_header Zend_Feed_Builder_Header */ private $_header; /** * List of the entries of the feed * * @var $_entries array */ private $_entries = array(); /** * Constructor. The $data array must conform to the following format: * <code> * array( * 'title' => 'title of the feed', //required * 'link' => 'canonical url to the feed', //required * 'lastUpdate' => 'timestamp of the update date', // optional * 'published' => 'timestamp of the publication date', //optional * 'charset' => 'charset', // required * 'description' => 'short description of the feed', //optional * 'author' => 'author/publisher of the feed', //optional * 'email' => 'email of the author', //optional * 'webmaster' => 'email address for person responsible for technical issues' // optional, ignored if atom is used * 'copyright' => 'copyright notice', //optional * 'image' => 'url to image', //optional * 'generator' => 'generator', // optional * 'language' => 'language the feed is written in', // optional * 'ttl' => 'how long in minutes a feed can be cached before refreshing', // optional, ignored if atom is used * 'rating' => 'The PICS rating for the channel.', // optional, ignored if atom is used * 'cloud' => array( * 'domain' => 'domain of the cloud, e.g. rpc.sys.com' // required * 'port' => 'port to connect to' // optional, default to 80 * 'path' => 'path of the cloud, e.g. /RPC2 //required * 'registerProcedure' => 'procedure to call, e.g. myCloud.rssPleaseNotify' // required * 'protocol' => 'protocol to use, e.g. soap or xml-rpc' // required * ), a cloud to be notified of updates // optional, ignored if atom is used * 'textInput' => array( * 'title' => 'the label of the Submit button in the text input area' // required, * 'description' => 'explains the text input area' // required * 'name' => 'the name of the text object in the text input area' // required * 'link' => 'the URL of the CGI script that processes text input requests' // required * ) // a text input box that can be displayed with the feed // optional, ignored if atom is used * 'skipHours' => array( * 'hour in 24 format', // e.g 13 (1pm) * // up to 24 rows whose value is a number between 0 and 23 * ) // Hint telling aggregators which hours they can skip // optional, ignored if atom is used * 'skipDays ' => array( * 'a day to skip', // e.g Monday * // up to 7 rows whose value is a Monday, Tuesday, Wednesday, Thursday, Friday, Saturday or Sunday * ) // Hint telling aggregators which days they can skip // optional, ignored if atom is used * 'itunes' => array( * 'author' => 'Artist column' // optional, default to the main author value * 'owner' => array( * 'name' => 'name of the owner' // optional, default to main author value * 'email' => 'email of the owner' // optional, default to main email value * ) // Owner of the podcast // optional * 'image' => 'album/podcast art' // optional, default to the main image value * 'subtitle' => 'short description' // optional, default to the main description value * 'summary' => 'longer description' // optional, default to the main description value * 'block' => 'Prevent an episode from appearing (yes|no)' // optional * 'category' => array( * array('main' => 'main category', // required * 'sub' => 'sub category' // optional * ), * // up to 3 rows * ) // 'Category column and in iTunes Music Store Browse' // required * 'explicit' => 'parental advisory graphic (yes|no|clean)' // optional * 'keywords' => 'a comma separated list of 12 keywords maximum' // optional * 'new-feed-url' => 'used to inform iTunes of new feed URL location' // optional * ) // Itunes extension data // optional, ignored if atom is used * 'entries' => array( * array( * 'title' => 'title of the feed entry', //required * 'link' => 'url to a feed entry', //required * 'description' => 'short version of a feed entry', // only text, no html, required * 'guid' => 'id of the article, if not given link value will used', //optional * 'content' => 'long version', // can contain html, optional * 'lastUpdate' => 'timestamp of the publication date', // optional * 'comments' => 'comments page of the feed entry', // optional * 'commentRss' => 'the feed url of the associated comments', // optional * 'source' => array( * 'title' => 'title of the original source' // required, * 'url' => 'url of the original source' // required * ) // original source of the feed entry // optional * 'category' => array( * array( * 'term' => 'first category label' // required, * 'scheme' => 'url that identifies a categorization scheme' // optional * ), * array( * //data for the second category and so on * ) * ) // list of the attached categories // optional * 'enclosure' => array( * array( * 'url' => 'url of the linked enclosure' // required * 'type' => 'mime type of the enclosure' // optional * 'length' => 'length of the linked content in octets' // optional * ), * array( * //data for the second enclosure and so on * ) * ) // list of the enclosures of the feed entry // optional * ), * array( * //data for the second entry and so on * ) * ) * ); * </code> * * @param array $data * @return void */ public function __construct(array $data) { $this->_data = $data; $this->_createHeader($data); if (isset($data['entries'])) { $this->_createEntries($data['entries']); } } /** * Returns an instance of Zend_Feed_Builder_Header * describing the header of the feed * * @return Zend_Feed_Builder_Header */ public function getHeader() { return $this->_header; } /** * Returns an array of Zend_Feed_Builder_Entry instances * describing the entries of the feed * * @return array of Zend_Feed_Builder_Entry */ public function getEntries() { return $this->_entries; } /** * Create the Zend_Feed_Builder_Header instance * * @param array $data * @throws Zend_Feed_Builder_Exception * @return void */ private function _createHeader(array $data) { $mandatories = array('title', 'link', 'charset'); foreach ($mandatories as $mandatory) { if (!isset($data[$mandatory])) { /** * @see Zend_Feed_Builder_Exception */ require_once 'Zend/Feed/Builder/Exception.php'; throw new Zend_Feed_Builder_Exception("$mandatory key is missing"); } } $this->_header = new Zend_Feed_Builder_Header($data['title'], $data['link'], $data['charset']); if (isset($data['lastUpdate'])) { $this->_header->setLastUpdate($data['lastUpdate']); } if (isset($data['published'])) { $this->_header->setPublishedDate($data['published']); } if (isset($data['description'])) { $this->_header->setDescription($data['description']); } if (isset($data['author'])) { $this->_header->setAuthor($data['author']); } if (isset($data['email'])) { $this->_header->setEmail($data['email']); } if (isset($data['webmaster'])) { $this->_header->setWebmaster($data['webmaster']); } if (isset($data['copyright'])) { $this->_header->setCopyright($data['copyright']); } if (isset($data['image'])) { $this->_header->setImage($data['image']); } if (isset($data['generator'])) { $this->_header->setGenerator($data['generator']); } if (isset($data['language'])) { $this->_header->setLanguage($data['language']); } if (isset($data['ttl'])) { $this->_header->setTtl($data['ttl']); } if (isset($data['rating'])) { $this->_header->setRating($data['rating']); } if (isset($data['cloud'])) { $mandatories = array('domain', 'path', 'registerProcedure', 'protocol'); foreach ($mandatories as $mandatory) { if (!isset($data['cloud'][$mandatory])) { /** * @see Zend_Feed_Builder_Exception */ require_once 'Zend/Feed/Builder/Exception.php'; throw new Zend_Feed_Builder_Exception("you have to define $mandatory property of your cloud"); } } $uri_str = 'http://' . $data['cloud']['domain'] . $data['cloud']['path']; $this->_header->setCloud($uri_str, $data['cloud']['registerProcedure'], $data['cloud']['protocol']); } if (isset($data['textInput'])) { $mandatories = array('title', 'description', 'name', 'link'); foreach ($mandatories as $mandatory) { if (!isset($data['textInput'][$mandatory])) { /** * @see Zend_Feed_Builder_Exception */ require_once 'Zend/Feed/Builder/Exception.php'; throw new Zend_Feed_Builder_Exception("you have to define $mandatory property of your textInput"); } } $this->_header->setTextInput($data['textInput']['title'], $data['textInput']['description'], $data['textInput']['name'], $data['textInput']['link']); } if (isset($data['skipHours'])) { $this->_header->setSkipHours($data['skipHours']); } if (isset($data['skipDays'])) { $this->_header->setSkipDays($data['skipDays']); } if (isset($data['itunes'])) { $itunes = new Zend_Feed_Builder_Header_Itunes($data['itunes']['category']); if (isset($data['itunes']['author'])) { $itunes->setAuthor($data['itunes']['author']); } if (isset($data['itunes']['owner'])) { $name = isset($data['itunes']['owner']['name']) ? $data['itunes']['owner']['name'] : ''; $email = isset($data['itunes']['owner']['email']) ? $data['itunes']['owner']['email'] : ''; $itunes->setOwner($name, $email); } if (isset($data['itunes']['image'])) { $itunes->setImage($data['itunes']['image']); } if (isset($data['itunes']['subtitle'])) { $itunes->setSubtitle($data['itunes']['subtitle']); } if (isset($data['itunes']['summary'])) { $itunes->setSummary($data['itunes']['summary']); } if (isset($data['itunes']['block'])) { $itunes->setBlock($data['itunes']['block']); } if (isset($data['itunes']['explicit'])) { $itunes->setExplicit($data['itunes']['explicit']); } if (isset($data['itunes']['keywords'])) { $itunes->setKeywords($data['itunes']['keywords']); } if (isset($data['itunes']['new-feed-url'])) { $itunes->setNewFeedUrl($data['itunes']['new-feed-url']); } $this->_header->setITunes($itunes); } } /** * Create the array of article entries * * @param array $data * @throws Zend_Feed_Builder_Exception * @return void */ private function _createEntries(array $data) { foreach ($data as $row) { $mandatories = array('title', 'link', 'description'); foreach ($mandatories as $mandatory) { if (!isset($row[$mandatory])) { /** * @see Zend_Feed_Builder_Exception */ require_once 'Zend/Feed/Builder/Exception.php'; throw new Zend_Feed_Builder_Exception("$mandatory key is missing"); } } $entry = new Zend_Feed_Builder_Entry($row['title'], $row['link'], $row['description']); if (isset($row['guid'])) { $entry->setId($row['guid']); } if (isset($row['content'])) { $entry->setContent($row['content']); } if (isset($row['lastUpdate'])) { $entry->setLastUpdate($row['lastUpdate']); } if (isset($row['comments'])) { $entry->setCommentsUrl($row['comments']); } if (isset($row['commentRss'])) { $entry->setCommentsRssUrl($row['commentRss']); } if (isset($row['source'])) { $mandatories = array('title', 'url'); foreach ($mandatories as $mandatory) { if (!isset($row['source'][$mandatory])) { /** * @see Zend_Feed_Builder_Exception */ require_once 'Zend/Feed/Builder/Exception.php'; throw new Zend_Feed_Builder_Exception("$mandatory key of source property is missing"); } } $entry->setSource($row['source']['title'], $row['source']['url']); } if (isset($row['category'])) { $entry->setCategories($row['category']); } if (isset($row['enclosure'])) { $entry->setEnclosures($row['enclosure']); } $this->_entries[] = $entry; } } }
apache-2.0
tr3vr/jena
jena-core/src/main/java/org/apache/jena/datatypes/xsd/impl/XSDDurationType.java
4469
/* * 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 org.apache.jena.datatypes.xsd.impl; import org.apache.jena.datatypes.* ; import org.apache.jena.datatypes.xsd.* ; /** * The XSD duration type, the only job of this extra layer is to * wrap the return value in a more convenient accessor type. We could * avoid this proliferation of trivial types by use of reflection but * since that causes allergic reactions in some we use brute force. * <p> * This class includees code derived from Xerces 2.6.0 * Copyright (c) 1999-2002 The Apache Software Foundation. * All rights reserved. * </p> */ public class XSDDurationType extends XSDAbstractDateTimeType { /** * Constructor */ public XSDDurationType() { super("duration"); javaClass = XSDDuration.class; } /** * Parse a validated date. This is invoked from * XSDDatatype.convertValidatedDataValue rather then from a local * parse method to make the implementation of XSDGenericType easier. */ @Override public Object parseValidated(String str) { int len = str.length(); int[] date=new int[TOTAL_SIZE]; int start = 0; char c=str.charAt(start++); if ( c!='P' && c!='-' ) { throw new DatatypeFormatException("Internal error: validated duration failed to parse(1)"); } else { date[utc]=(c=='-')?'-':0; if ( c=='-' && str.charAt(start++)!='P' ) { throw new DatatypeFormatException("Internal error: validated duration failed to parse(2)"); } } int negate = 1; //negative duration if ( date[utc]=='-' ) { negate = -1; } int endDate = indexOf (str, start, len, 'T'); if ( endDate == -1 ) { endDate = len; } //find 'Y' int end = indexOf (str, start, endDate, 'Y'); if ( end!=-1 ) { //scan year date[CY]=negate * parseInt(str,start,end); start = end+1; } end = indexOf (str, start, endDate, 'M'); if ( end!=-1 ) { //scan month date[M]=negate * parseInt(str,start,end); start = end+1; } end = indexOf (str, start, endDate, 'D'); if ( end!=-1 ) { //scan day date[D]=negate * parseInt(str,start,end); start = end+1; } if ( len == endDate && start!=len ) { throw new DatatypeFormatException("Internal error: validated duration failed to parse(3)"); } if ( len !=endDate ) { end = indexOf (str, ++start, len, 'H'); if ( end!=-1 ) { //scan hours date[h]=negate * parseInt(str,start,end); start=end+1; } end = indexOf (str, start, len, 'M'); if ( end!=-1 ) { //scan min date[m]=negate * parseInt(str,start,end); start=end+1; } end = indexOf (str, start, len, 'S'); if ( end!=-1 ) { //scan seconds int mlsec = indexOf (str, start, end, '.'); if ( mlsec >0 ) { date[s] = negate * parseInt (str, start, mlsec); int msEnd = end; while (str.charAt(msEnd-1) == '0') msEnd--; date[ms] = negate * parseInt(str, mlsec+1, msEnd); date[msscale] = msEnd - mlsec - 1; } else { date[s]=negate * parseInt(str, start,end); } start=end+1; } } return new XSDDuration(date); } }
apache-2.0
phreakocious/ohai
spec/unit/plugins/eucalyptus_spec.rb
5196
# # Author:: Tim Dysinger (<tim@dysinger.net>) # Author:: Christopher Brown (cb@opscode.com) # Copyright:: Copyright (c) 2008 Opscode, Inc. # License:: Apache License, Version 2.0 # # 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. # require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper.rb') require 'open-uri' describe Ohai::System, "plugin eucalyptus" do before(:each) do @plugin = get_plugin("eucalyptus") end shared_examples_for "!eucalyptus" do it "should NOT attempt to fetch the eucalyptus metadata" do expect(OpenURI).not_to receive(:open) @plugin.run end end shared_examples_for "eucalyptus" do before(:each) do @http_client = double("Net::HTTP client") allow(@plugin).to receive(:http_client).and_return(@http_client) expect(@http_client).to receive(:get). with("/").twice. and_return(double("Net::HTTP Response", :body => "2012-01-12", :code => "200")) expect(@http_client).to receive(:get). with("/2012-01-12/meta-data/"). and_return(double("Net::HTTP Response", :body => "instance_type\nami_id\nsecurity-groups", :code => "200")) expect(@http_client).to receive(:get). with("/2012-01-12/meta-data/instance_type"). and_return(double("Net::HTTP Response", :body => "c1.medium", :code => "200")) expect(@http_client).to receive(:get). with("/2012-01-12/meta-data/ami_id"). and_return(double("Net::HTTP Response", :body => "ami-5d2dc934", :code => "200")) expect(@http_client).to receive(:get). with("/2012-01-12/meta-data/security-groups"). and_return(double("Net::HTTP Response", :body => "group1\ngroup2", :code => "200")) expect(@http_client).to receive(:get). with("/2012-01-12/user-data/"). and_return(double("Net::HTTP Response", :body => "By the pricking of my thumb...", :code => "200")) end it "should recursively fetch all the eucalyptus metadata" do allow(IO).to receive(:select).and_return([[],[1],[]]) t = double("connection") allow(t).to receive(:connect_nonblock).and_raise(Errno::EINPROGRESS) allow(Socket).to receive(:new).and_return(t) @plugin.run expect(@plugin[:eucalyptus]).not_to be_nil expect(@plugin[:eucalyptus]['instance_type']).to eq("c1.medium") expect(@plugin[:eucalyptus]['ami_id']).to eq("ami-5d2dc934") expect(@plugin[:eucalyptus]['security_groups']).to eql ['group1', 'group2'] end end describe "with eucalyptus mac and metadata address connected" do it_should_behave_like "eucalyptus" before(:each) do allow(IO).to receive(:select).and_return([[],[1],[]]) @plugin[:network] = { "interfaces" => { "eth0" => { "addresses" => { "d0:0d:95:47:6E:ED"=> { "family" => "lladdr" } } } } } end end describe "without eucalyptus mac and metadata address connected" do it_should_behave_like "!eucalyptus" before(:each) do @plugin[:network] = { "interfaces" => { "eth0" => { "addresses" => { "ff:ff:95:47:6E:ED"=> { "family" => "lladdr" } } } } } end end describe "with eucalyptus cloud file" do it_should_behave_like "eucalyptus" before(:each) do allow(File).to receive(:exist?).with('/etc/chef/ohai/hints/eucalyptus.json').and_return(true) allow(File).to receive(:read).with('/etc/chef/ohai/hints/eucalyptus.json').and_return('') allow(File).to receive(:exist?).with('C:\chef\ohai\hints/eucalyptus.json').and_return(true) allow(File).to receive(:read).with('C:\chef\ohai\hints/eucalyptus.json').and_return('') end end describe "without cloud file" do it_should_behave_like "!eucalyptus" before(:each) do @plugin[:network] = {:interfaces => {}} allow(File).to receive(:exist?).with('/etc/chef/ohai/hints/eucalyptus.json').and_return(false) allow(File).to receive(:exist?).with('C:\chef\ohai\hints/eucalyptus.json').and_return(false) end end describe "with ec2 cloud file" do it_should_behave_like "!eucalyptus" before(:each) do @plugin[:network] = {:interfaces => {}} allow(File).to receive(:exist?).with('/etc/chef/ohai/hints/eucalyptus.json').and_return(false) allow(File).to receive(:exist?).with('C:\chef\ohai\hints/eucalyptus.json').and_return(false) allow(File).to receive(:exist?).with('C:\chef\ohai\hints/ec2.json').and_return(true) allow(File).to receive(:exist?).with('/etc/chef/ohai/hints/ec2.json').and_return(true) allow(File).to receive(:read).with('/etc/chef/ohai/hints/ec2.json').and_return('') allow(File).to receive(:read).with('C:\chef\ohai\hints/ec2.json').and_return('') end end end
apache-2.0
ueshin/apache-flink
flink-end-to-end-tests/flink-stream-state-ttl-test/src/main/java/org/apache/flink/streaming/tests/TtlStateUpdateSource.java
2835
/* * 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 org.apache.flink.streaming.tests; import org.apache.flink.streaming.api.functions.source.RichParallelSourceFunction; import org.apache.flink.streaming.tests.verify.TtlStateVerifier; import java.util.Map; import java.util.Random; import java.util.stream.Collectors; /** * Source of randomly generated keyed state updates. * * <p>Internal loop generates {@code sleepAfterElements} state updates * for each verifier from {@link TtlStateVerifier#VERIFIERS} using {@link TtlStateVerifier#generateRandomUpdate} * and waits for {@code sleepTime} to continue generation. */ class TtlStateUpdateSource extends RichParallelSourceFunction<TtlStateUpdate> { private static final long serialVersionUID = 1L; private final int maxKey; private final long sleepAfterElements; private final long sleepTime; /** Flag that determines if this source is running, i.e. generating events. */ private volatile boolean running = true; TtlStateUpdateSource(int maxKey, long sleepAfterElements, long sleepTime) { this.maxKey = maxKey; this.sleepAfterElements = sleepAfterElements; this.sleepTime = sleepTime; } @Override public void run(SourceContext<TtlStateUpdate> ctx) throws Exception { Random random = new Random(); long elementsBeforeSleep = sleepAfterElements; while (running) { for (int i = 0; i < sleepAfterElements; i++) { synchronized (ctx.getCheckpointLock()) { Map<String, Object> updates = TtlStateVerifier.VERIFIERS.stream() .collect(Collectors.toMap(TtlStateVerifier::getId, TtlStateVerifier::generateRandomUpdate)); ctx.collect(new TtlStateUpdate(random.nextInt(maxKey), updates)); } } if (sleepTime > 0) { if (elementsBeforeSleep == 1) { elementsBeforeSleep = sleepAfterElements; long rnd = sleepTime < Integer.MAX_VALUE ? random.nextInt((int) sleepTime) : 0L; Thread.sleep(rnd + sleepTime); } else if (elementsBeforeSleep > 1) { --elementsBeforeSleep; } } } } @Override public void cancel() { running = false; } }
apache-2.0
mehrdada/grpc
src/core/tsi/alts/handshaker/alts_handshaker_service_api_util.cc
5118
/* * * Copyright 2018 gRPC authors. * * 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. * */ #include <grpc/support/port_platform.h> #include "src/core/tsi/alts/handshaker/alts_handshaker_service_api_util.h" #include "src/core/lib/slice/slice_internal.h" void add_repeated_field(repeated_field** head, const void* data) { repeated_field* field = static_cast<repeated_field*>(gpr_zalloc(sizeof(*field))); field->data = data; if (*head == nullptr) { *head = field; (*head)->next = nullptr; } else { field->next = *head; *head = field; } } void destroy_repeated_field_list_identity(repeated_field* head) { repeated_field* field = head; while (field != nullptr) { repeated_field* next_field = field->next; const grpc_gcp_identity* identity = static_cast<const grpc_gcp_identity*>(field->data); destroy_slice(static_cast<grpc_slice*>(identity->hostname.arg)); destroy_slice(static_cast<grpc_slice*>(identity->service_account.arg)); gpr_free((void*)identity); gpr_free(field); field = next_field; } } void destroy_repeated_field_list_string(repeated_field* head) { repeated_field* field = head; while (field != nullptr) { repeated_field* next_field = field->next; destroy_slice((grpc_slice*)field->data); gpr_free(field); field = next_field; } } grpc_slice* create_slice(const char* data, size_t size) { grpc_slice slice = grpc_slice_from_copied_buffer(data, size); grpc_slice* cb_slice = static_cast<grpc_slice*>(gpr_zalloc(sizeof(*cb_slice))); memcpy(cb_slice, &slice, sizeof(*cb_slice)); return cb_slice; } void destroy_slice(grpc_slice* slice) { if (slice != nullptr) { grpc_slice_unref_internal(*slice); gpr_free(slice); } } bool encode_string_or_bytes_cb(pb_ostream_t* stream, const pb_field_t* field, void* const* arg) { grpc_slice* slice = static_cast<grpc_slice*>(*arg); if (!pb_encode_tag_for_field(stream, field)) return false; return pb_encode_string(stream, GRPC_SLICE_START_PTR(*slice), GRPC_SLICE_LENGTH(*slice)); } bool encode_repeated_identity_cb(pb_ostream_t* stream, const pb_field_t* field, void* const* arg) { repeated_field* var = static_cast<repeated_field*>(*arg); while (var != nullptr) { if (!pb_encode_tag_for_field(stream, field)) return false; if (!pb_encode_submessage(stream, grpc_gcp_Identity_fields, (grpc_gcp_identity*)var->data)) return false; var = var->next; } return true; } bool encode_repeated_string_cb(pb_ostream_t* stream, const pb_field_t* field, void* const* arg) { repeated_field* var = static_cast<repeated_field*>(*arg); while (var != nullptr) { if (!pb_encode_tag_for_field(stream, field)) return false; const grpc_slice* slice = static_cast<const grpc_slice*>(var->data); if (!pb_encode_string(stream, GRPC_SLICE_START_PTR(*slice), GRPC_SLICE_LENGTH(*slice))) return false; var = var->next; } return true; } bool decode_string_or_bytes_cb(pb_istream_t* stream, const pb_field_t* field, void** arg) { grpc_slice slice = grpc_slice_malloc(stream->bytes_left); grpc_slice* cb_slice = static_cast<grpc_slice*>(gpr_zalloc(sizeof(*cb_slice))); memcpy(cb_slice, &slice, sizeof(*cb_slice)); if (!pb_read(stream, GRPC_SLICE_START_PTR(*cb_slice), stream->bytes_left)) return false; *arg = cb_slice; return true; } bool decode_repeated_identity_cb(pb_istream_t* stream, const pb_field_t* field, void** arg) { grpc_gcp_identity* identity = static_cast<grpc_gcp_identity*>(gpr_zalloc(sizeof(*identity))); identity->hostname.funcs.decode = decode_string_or_bytes_cb; identity->service_account.funcs.decode = decode_string_or_bytes_cb; add_repeated_field(reinterpret_cast<repeated_field**>(arg), identity); if (!pb_decode(stream, grpc_gcp_Identity_fields, identity)) return false; return true; } bool decode_repeated_string_cb(pb_istream_t* stream, const pb_field_t* field, void** arg) { grpc_slice slice = grpc_slice_malloc(stream->bytes_left); grpc_slice* cb_slice = static_cast<grpc_slice*>(gpr_zalloc(sizeof(*cb_slice))); memcpy(cb_slice, &slice, sizeof(grpc_slice)); if (!pb_read(stream, GRPC_SLICE_START_PTR(*cb_slice), stream->bytes_left)) return false; add_repeated_field(reinterpret_cast<repeated_field**>(arg), cb_slice); return true; }
apache-2.0
SeanKilleen/elasticsearch-net
src/Nest/DSL/Query/MoreLikeThisQueryDescriptor.cs
9010
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Nest.Resolvers.Converters; using Newtonsoft.Json; using System.Linq.Expressions; namespace Nest { [JsonObject(MemberSerialization = MemberSerialization.OptIn)] [JsonConverter(typeof(ReadAsTypeConverter<MoreLikeThisQueryDescriptor<object>>))] public interface IMoreLikeThisQuery : IQuery { [JsonProperty(PropertyName = "fields")] IEnumerable<PropertyPathMarker> Fields { get; set; } [JsonProperty(PropertyName = "like_text")] string LikeText { get; set; } [JsonProperty(PropertyName = "percent_terms_to_match")] double? TermMatchPercentage { get; set; } [JsonProperty(PropertyName = "minimum_should_match")] string MinimumShouldMatch { get; set; } [JsonProperty(PropertyName = "stop_words")] IEnumerable<string> StopWords { get; set; } [JsonProperty(PropertyName = "min_term_freq")] int? MinTermFrequency { get; set; } [JsonProperty(PropertyName = "max_query_terms")] int? MaxQueryTerms { get; set; } [JsonProperty(PropertyName = "min_doc_freq")] int? MinDocumentFrequency { get; set; } [JsonProperty(PropertyName = "max_doc_freq")] int? MaxDocumentFrequency { get; set; } [JsonProperty(PropertyName = "min_word_len")] int? MinWordLength { get; set; } [JsonProperty(PropertyName = "max_word_len")] int? MaxWordLength { get; set; } [JsonProperty(PropertyName = "boost_terms")] double? BoostTerms { get; set; } [JsonProperty(PropertyName = "boost")] double? Boost { get; set; } [JsonProperty(PropertyName = "analyzer")] string Analyzer { get; set; } /// <summary> /// A list of document ids. This parameter is required if like_text is not specified. /// The texts are fetched from fields unless specified in each doc, and cannot be set to _all. /// <pre>Available from Elasticsearch 1.3.0</pre> /// </summary> [JsonProperty("ids")] IEnumerable<string> Ids { get; set; } /// <summary> /// A list of documents following the same syntax as the Multi GET API. This parameter is required if like_text is not specified. /// The texts are fetched from fields unless specified in each doc, and cannot be set to _all. /// <pre>Available from Elasticsearch 1.3.0</pre> /// </summary> [JsonProperty("docs")] IEnumerable<IMultiGetOperation> Documents { get; set; } [JsonProperty(PropertyName = "include")] bool? Include { get; set; } } public class MoreLikeThisQuery : PlainQuery, IMoreLikeThisQuery { protected override void WrapInContainer(IQueryContainer container) { container.MoreLikeThis = this; } bool IQuery.IsConditionless { get { return false; } } public string Name { get; set; } public IEnumerable<PropertyPathMarker> Fields { get; set; } public string LikeText { get; set; } public double? TermMatchPercentage { get; set; } public string MinimumShouldMatch { get; set; } public IEnumerable<string> StopWords { get; set; } public int? MinTermFrequency { get; set; } public int? MaxQueryTerms { get; set; } public int? MinDocumentFrequency { get; set; } public int? MaxDocumentFrequency { get; set; } public int? MinWordLength { get; set; } public int? MaxWordLength { get; set; } public double? BoostTerms { get; set; } public double? Boost { get; set; } public string Analyzer { get; set; } public IEnumerable<string> Ids { get; set; } public IEnumerable<IMultiGetOperation> Documents { get; set; } public bool? Include { get; set; } } public class MoreLikeThisQueryDescriptor<T> : IMoreLikeThisQuery where T : class { private IMoreLikeThisQuery Self { get { return this; }} IEnumerable<PropertyPathMarker> IMoreLikeThisQuery.Fields { get; set; } string IMoreLikeThisQuery.LikeText { get; set; } double? IMoreLikeThisQuery.TermMatchPercentage { get; set; } string IMoreLikeThisQuery.MinimumShouldMatch { get; set; } IEnumerable<string> IMoreLikeThisQuery.StopWords { get; set; } int? IMoreLikeThisQuery.MinTermFrequency { get; set; } int? IMoreLikeThisQuery.MaxQueryTerms { get; set; } int? IMoreLikeThisQuery.MinDocumentFrequency { get; set; } int? IMoreLikeThisQuery.MaxDocumentFrequency { get; set; } int? IMoreLikeThisQuery.MinWordLength { get; set; } int? IMoreLikeThisQuery.MaxWordLength { get; set; } double? IMoreLikeThisQuery.BoostTerms { get; set; } double? IMoreLikeThisQuery.Boost { get; set; } string IMoreLikeThisQuery.Analyzer { get; set; } IEnumerable<string> IMoreLikeThisQuery.Ids { get; set; } IEnumerable<IMultiGetOperation> IMoreLikeThisQuery.Documents { get; set; } bool? IMoreLikeThisQuery.Include { get; set; } bool IQuery.IsConditionless { get { return this.Self.LikeText.IsNullOrEmpty() && (this.Self.Ids == null || !this.Self.Ids.Any()) && (this.Self.Documents == null || !this.Self.Documents.Any()); } } string IQuery.Name { get; set; } public MoreLikeThisQueryDescriptor<T> Name(string name) { Self.Name = name; return this; } public MoreLikeThisQueryDescriptor<T> OnFields(IEnumerable<string> fields) { this.Self.Fields = fields.Select(f=>(PropertyPathMarker)f); return this; } public MoreLikeThisQueryDescriptor<T> OnFields( params Expression<Func<T, object>>[] objectPaths) { this.Self.Fields = objectPaths.Select(e=>(PropertyPathMarker)e); return this; } public MoreLikeThisQueryDescriptor<T> LikeText(string likeText) { this.Self.LikeText = likeText; return this; } public MoreLikeThisQueryDescriptor<T> StopWords(IEnumerable<string> stopWords) { this.Self.StopWords = stopWords; return this; } public MoreLikeThisQueryDescriptor<T> MaxQueryTerms(int maxQueryTerms) { this.Self.MaxQueryTerms = maxQueryTerms; return this; } public MoreLikeThisQueryDescriptor<T> MinTermFrequency(int minTermFrequency) { this.Self.MinTermFrequency = minTermFrequency; return this; } public MoreLikeThisQueryDescriptor<T> MinDocumentFrequency(int minDocumentFrequency) { this.Self.MinDocumentFrequency = minDocumentFrequency; return this; } public MoreLikeThisQueryDescriptor<T> MaxDocumentFrequency(int maxDocumentFrequency) { this.Self.MaxDocumentFrequency = maxDocumentFrequency; return this; } public MoreLikeThisQueryDescriptor<T> MinWordLength(int minWordLength) { this.Self.MinWordLength = minWordLength; return this; } public MoreLikeThisQueryDescriptor<T> MaxWordLength(int maxWordLength) { this.Self.MaxWordLength = maxWordLength; return this; } public MoreLikeThisQueryDescriptor<T> BoostTerms(double boostTerms) { this.Self.BoostTerms = boostTerms; return this; } public MoreLikeThisQueryDescriptor<T> TermMatchPercentage(double termMatchPercentage) { this.Self.TermMatchPercentage = termMatchPercentage; return this; } public MoreLikeThisQueryDescriptor<T> MinimumShouldMatch(string minMatch) { this.Self.MinimumShouldMatch = minMatch; return this; } public MoreLikeThisQueryDescriptor<T> MinimumShouldMatch(int minMatch) { this.Self.MinimumShouldMatch = minMatch.ToString(); return this; } public MoreLikeThisQueryDescriptor<T> Boost(double boost) { this.Self.Boost = boost; return this; } public MoreLikeThisQueryDescriptor<T> Analyzer(string analyzer) { this.Self.Analyzer = analyzer; return this; } public MoreLikeThisQueryDescriptor<T> Ids(IEnumerable<long> ids) { this.Self.Ids = ids.Select(i=>i.ToString(CultureInfo.InvariantCulture)); return this; } public MoreLikeThisQueryDescriptor<T> Ids(IEnumerable<string> ids) { this.Self.Ids = ids; return this; } /// <summary> /// Specify multiple documents to suply the more like this like text /// </summary> public MoreLikeThisQueryDescriptor<T> Documents(Func<MoreLikeThisQueryDocumentsDescriptor<T>, MoreLikeThisQueryDocumentsDescriptor<T>> getDocumentsSelector) { getDocumentsSelector.ThrowIfNull("getDocumentsSelector"); var descriptor = getDocumentsSelector(new MoreLikeThisQueryDocumentsDescriptor<T>(true)); descriptor.ThrowIfNull("descriptor"); Self.Documents = descriptor.GetOperations; return this; } /// <summary> /// Specify multiple documents to supply the more like this text, but do not generate index: and type: on the get operations. /// Useful if the node has rest.action.multi.allow_explicit_index set to false /// </summary> /// <param name="getDocumentsSelector"></param> /// <returns></returns> public MoreLikeThisQueryDescriptor<T> DocumentsExplicit(Func<MoreLikeThisQueryDocumentsDescriptor<T>, MoreLikeThisQueryDocumentsDescriptor<T>> getDocumentsSelector) { getDocumentsSelector.ThrowIfNull("getDocumentsSelector"); var descriptor = getDocumentsSelector(new MoreLikeThisQueryDocumentsDescriptor<T>(false)); descriptor.ThrowIfNull("descriptor"); Self.Documents = descriptor.GetOperations; return this; } } }
apache-2.0
vsekhar/elastic-go
src/vendor/golang_org/x/net/http2/hpack/tables.go
10348
// Copyright 2014 The Go 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 hpack import ( "fmt" ) // headerFieldTable implements a list of HeaderFields. // This is used to implement the static and dynamic tables. type headerFieldTable struct { // For static tables, entries are never evicted. // // For dynamic tables, entries are evicted from ents[0] and added to the end. // Each entry has a unique id that starts at one and increments for each // entry that is added. This unique id is stable across evictions, meaning // it can be used as a pointer to a specific entry. As in hpack, unique ids // are 1-based. The unique id for ents[k] is k + evictCount + 1. // // Zero is not a valid unique id. // // evictCount should not overflow in any remotely practical situation. In // practice, we will have one dynamic table per HTTP/2 connection. If we // assume a very powerful server that handles 1M QPS per connection and each // request adds (then evicts) 100 entries from the table, it would still take // 2M years for evictCount to overflow. ents []HeaderField evictCount uint64 // byName maps a HeaderField name to the unique id of the newest entry with // the same name. See above for a definition of "unique id". byName map[string]uint64 // byNameValue maps a HeaderField name/value pair to the unique id of the newest // entry with the same name and value. See above for a definition of "unique id". byNameValue map[pairNameValue]uint64 } type pairNameValue struct { name, value string } func (t *headerFieldTable) init() { t.byName = make(map[string]uint64) t.byNameValue = make(map[pairNameValue]uint64) } // len reports the number of entries in the table. func (t *headerFieldTable) len() int { return len(t.ents) } // addEntry adds a new entry. func (t *headerFieldTable) addEntry(f HeaderField) { id := uint64(t.len()) + t.evictCount + 1 t.byName[f.Name] = id t.byNameValue[pairNameValue{f.Name, f.Value}] = id t.ents = append(t.ents, f) } // evictOldest evicts the n oldest entries in the table. func (t *headerFieldTable) evictOldest(n int) { if n > t.len() { panic(fmt.Sprintf("evictOldest(%v) on table with %v entries", n, t.len())) } for k := 0; k < n; k++ { f := t.ents[k] id := t.evictCount + uint64(k) + 1 if t.byName[f.Name] == id { delete(t.byName, f.Name) } if p := (pairNameValue{f.Name, f.Value}); t.byNameValue[p] == id { delete(t.byNameValue, p) } } copy(t.ents, t.ents[n:]) for k := t.len() - n; k < t.len(); k++ { t.ents[k] = HeaderField{} // so strings can be garbage collected } t.ents = t.ents[:t.len()-n] if t.evictCount+uint64(n) < t.evictCount { panic("evictCount overflow") } t.evictCount += uint64(n) } // search finds f in the table. If there is no match, i is 0. // If both name and value match, i is the matched index and nameValueMatch // becomes true. If only name matches, i points to that index and // nameValueMatch becomes false. // // The returned index is a 1-based HPACK index. For dynamic tables, HPACK says // that index 1 should be the newest entry, but t.ents[0] is the oldest entry, // meaning t.ents is reversed for dynamic tables. Hence, when t is a dynamic // table, the return value i actually refers to the entry t.ents[t.len()-i]. // // All tables are assumed to be a dynamic tables except for the global // staticTable pointer. // // See Section 2.3.3. func (t *headerFieldTable) search(f HeaderField) (i uint64, nameValueMatch bool) { if !f.Sensitive { if id := t.byNameValue[pairNameValue{f.Name, f.Value}]; id != 0 { return t.idToIndex(id), true } } if id := t.byName[f.Name]; id != 0 { return t.idToIndex(id), false } return 0, false } // idToIndex converts a unique id to an HPACK index. // See Section 2.3.3. func (t *headerFieldTable) idToIndex(id uint64) uint64 { if id <= t.evictCount { panic(fmt.Sprintf("id (%v) <= evictCount (%v)", id, t.evictCount)) } k := id - t.evictCount - 1 // convert id to an index t.ents[k] if t != staticTable { return uint64(t.len()) - k // dynamic table } return k + 1 } // http://tools.ietf.org/html/draft-ietf-httpbis-header-compression-07#appendix-B var staticTable = newStaticTable() var staticTableEntries = [...]HeaderField{ HeaderField{Name: ":authority"}, HeaderField{Name: ":method", Value: "GET"}, HeaderField{Name: ":method", Value: "POST"}, HeaderField{Name: ":path", Value: "/"}, HeaderField{Name: ":path", Value: "/index.html"}, HeaderField{Name: ":scheme", Value: "http"}, HeaderField{Name: ":scheme", Value: "https"}, HeaderField{Name: ":status", Value: "200"}, HeaderField{Name: ":status", Value: "204"}, HeaderField{Name: ":status", Value: "206"}, HeaderField{Name: ":status", Value: "304"}, HeaderField{Name: ":status", Value: "400"}, HeaderField{Name: ":status", Value: "404"}, HeaderField{Name: ":status", Value: "500"}, HeaderField{Name: "accept-charset"}, HeaderField{Name: "accept-encoding", Value: "gzip, deflate"}, HeaderField{Name: "accept-language"}, HeaderField{Name: "accept-ranges"}, HeaderField{Name: "accept"}, HeaderField{Name: "access-control-allow-origin"}, HeaderField{Name: "age"}, HeaderField{Name: "allow"}, HeaderField{Name: "authorization"}, HeaderField{Name: "cache-control"}, HeaderField{Name: "content-disposition"}, HeaderField{Name: "content-encoding"}, HeaderField{Name: "content-language"}, HeaderField{Name: "content-length"}, HeaderField{Name: "content-location"}, HeaderField{Name: "content-range"}, HeaderField{Name: "content-type"}, HeaderField{Name: "cookie"}, HeaderField{Name: "date"}, HeaderField{Name: "etag"}, HeaderField{Name: "expect"}, HeaderField{Name: "expires"}, HeaderField{Name: "from"}, HeaderField{Name: "host"}, HeaderField{Name: "if-match"}, HeaderField{Name: "if-modified-since"}, HeaderField{Name: "if-none-match"}, HeaderField{Name: "if-range"}, HeaderField{Name: "if-unmodified-since"}, HeaderField{Name: "last-modified"}, HeaderField{Name: "link"}, HeaderField{Name: "location"}, HeaderField{Name: "max-forwards"}, HeaderField{Name: "proxy-authenticate"}, HeaderField{Name: "proxy-authorization"}, HeaderField{Name: "range"}, HeaderField{Name: "referer"}, HeaderField{Name: "refresh"}, HeaderField{Name: "retry-after"}, HeaderField{Name: "server"}, HeaderField{Name: "set-cookie"}, HeaderField{Name: "strict-transport-security"}, HeaderField{Name: "transfer-encoding"}, HeaderField{Name: "user-agent"}, HeaderField{Name: "vary"}, HeaderField{Name: "via"}, HeaderField{Name: "www-authenticate"}, } func newStaticTable() *headerFieldTable { t := &headerFieldTable{} t.init() for _, e := range staticTableEntries[:] { t.addEntry(e) } return t } var huffmanCodes = [256]uint32{ 0x1ff8, 0x7fffd8, 0xfffffe2, 0xfffffe3, 0xfffffe4, 0xfffffe5, 0xfffffe6, 0xfffffe7, 0xfffffe8, 0xffffea, 0x3ffffffc, 0xfffffe9, 0xfffffea, 0x3ffffffd, 0xfffffeb, 0xfffffec, 0xfffffed, 0xfffffee, 0xfffffef, 0xffffff0, 0xffffff1, 0xffffff2, 0x3ffffffe, 0xffffff3, 0xffffff4, 0xffffff5, 0xffffff6, 0xffffff7, 0xffffff8, 0xffffff9, 0xffffffa, 0xffffffb, 0x14, 0x3f8, 0x3f9, 0xffa, 0x1ff9, 0x15, 0xf8, 0x7fa, 0x3fa, 0x3fb, 0xf9, 0x7fb, 0xfa, 0x16, 0x17, 0x18, 0x0, 0x1, 0x2, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x5c, 0xfb, 0x7ffc, 0x20, 0xffb, 0x3fc, 0x1ffa, 0x21, 0x5d, 0x5e, 0x5f, 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0xfc, 0x73, 0xfd, 0x1ffb, 0x7fff0, 0x1ffc, 0x3ffc, 0x22, 0x7ffd, 0x3, 0x23, 0x4, 0x24, 0x5, 0x25, 0x26, 0x27, 0x6, 0x74, 0x75, 0x28, 0x29, 0x2a, 0x7, 0x2b, 0x76, 0x2c, 0x8, 0x9, 0x2d, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7ffe, 0x7fc, 0x3ffd, 0x1ffd, 0xffffffc, 0xfffe6, 0x3fffd2, 0xfffe7, 0xfffe8, 0x3fffd3, 0x3fffd4, 0x3fffd5, 0x7fffd9, 0x3fffd6, 0x7fffda, 0x7fffdb, 0x7fffdc, 0x7fffdd, 0x7fffde, 0xffffeb, 0x7fffdf, 0xffffec, 0xffffed, 0x3fffd7, 0x7fffe0, 0xffffee, 0x7fffe1, 0x7fffe2, 0x7fffe3, 0x7fffe4, 0x1fffdc, 0x3fffd8, 0x7fffe5, 0x3fffd9, 0x7fffe6, 0x7fffe7, 0xffffef, 0x3fffda, 0x1fffdd, 0xfffe9, 0x3fffdb, 0x3fffdc, 0x7fffe8, 0x7fffe9, 0x1fffde, 0x7fffea, 0x3fffdd, 0x3fffde, 0xfffff0, 0x1fffdf, 0x3fffdf, 0x7fffeb, 0x7fffec, 0x1fffe0, 0x1fffe1, 0x3fffe0, 0x1fffe2, 0x7fffed, 0x3fffe1, 0x7fffee, 0x7fffef, 0xfffea, 0x3fffe2, 0x3fffe3, 0x3fffe4, 0x7ffff0, 0x3fffe5, 0x3fffe6, 0x7ffff1, 0x3ffffe0, 0x3ffffe1, 0xfffeb, 0x7fff1, 0x3fffe7, 0x7ffff2, 0x3fffe8, 0x1ffffec, 0x3ffffe2, 0x3ffffe3, 0x3ffffe4, 0x7ffffde, 0x7ffffdf, 0x3ffffe5, 0xfffff1, 0x1ffffed, 0x7fff2, 0x1fffe3, 0x3ffffe6, 0x7ffffe0, 0x7ffffe1, 0x3ffffe7, 0x7ffffe2, 0xfffff2, 0x1fffe4, 0x1fffe5, 0x3ffffe8, 0x3ffffe9, 0xffffffd, 0x7ffffe3, 0x7ffffe4, 0x7ffffe5, 0xfffec, 0xfffff3, 0xfffed, 0x1fffe6, 0x3fffe9, 0x1fffe7, 0x1fffe8, 0x7ffff3, 0x3fffea, 0x3fffeb, 0x1ffffee, 0x1ffffef, 0xfffff4, 0xfffff5, 0x3ffffea, 0x7ffff4, 0x3ffffeb, 0x7ffffe6, 0x3ffffec, 0x3ffffed, 0x7ffffe7, 0x7ffffe8, 0x7ffffe9, 0x7ffffea, 0x7ffffeb, 0xffffffe, 0x7ffffec, 0x7ffffed, 0x7ffffee, 0x7ffffef, 0x7fffff0, 0x3ffffee, } var huffmanCodeLen = [256]uint8{ 13, 23, 28, 28, 28, 28, 28, 28, 28, 24, 30, 28, 28, 30, 28, 28, 28, 28, 28, 28, 28, 28, 30, 28, 28, 28, 28, 28, 28, 28, 28, 28, 6, 10, 10, 12, 13, 6, 8, 11, 10, 10, 8, 11, 8, 6, 6, 6, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 7, 8, 15, 6, 12, 10, 13, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 7, 8, 13, 19, 13, 14, 6, 15, 5, 6, 5, 6, 5, 6, 6, 6, 5, 7, 7, 6, 6, 6, 5, 6, 7, 6, 5, 5, 6, 7, 7, 7, 7, 7, 15, 11, 14, 13, 28, 20, 22, 20, 20, 22, 22, 22, 23, 22, 23, 23, 23, 23, 23, 24, 23, 24, 24, 22, 23, 24, 23, 23, 23, 23, 21, 22, 23, 22, 23, 23, 24, 22, 21, 20, 22, 22, 23, 23, 21, 23, 22, 22, 24, 21, 22, 23, 23, 21, 21, 22, 21, 23, 22, 23, 23, 20, 22, 22, 22, 23, 22, 22, 23, 26, 26, 20, 19, 22, 23, 22, 25, 26, 26, 26, 27, 27, 26, 24, 25, 19, 21, 26, 27, 27, 26, 27, 24, 21, 21, 26, 26, 28, 27, 27, 27, 20, 24, 20, 21, 22, 21, 21, 23, 22, 22, 25, 25, 24, 24, 26, 23, 26, 27, 26, 26, 27, 27, 27, 27, 27, 28, 27, 27, 27, 27, 27, 26, }
bsd-3-clause
binhdarkcu/Giggs
wp-includes/js/mce-view.js
20804
/* global tinymce */ /** * Note: this API is "experimental" meaning that it will probably change * in the next few releases based on feedback from 3.9.0. * If you decide to use it, please follow the development closely. */ // Ensure the global `wp` object exists. window.wp = window.wp || {}; ( function( $ ) { 'use strict'; var views = {}, instances = {}, media = wp.media, viewOptions = ['encodedText']; // Create the `wp.mce` object if necessary. wp.mce = wp.mce || {}; /** * wp.mce.View * * A Backbone-like View constructor intended for use when rendering a TinyMCE View. The main difference is * that the TinyMCE View is not tied to a particular DOM node. * * @param {Object} [options={}] */ wp.mce.View = function( options ) { options = options || {}; this.type = options.type; _.extend( this, _.pick( options, viewOptions ) ); this.initialize.apply( this, arguments ); }; _.extend( wp.mce.View.prototype, { initialize: function() {}, getHtml: function() { return ''; }, loadingPlaceholder: function() { return '' + '<div class="loading-placeholder">' + '<div class="dashicons dashicons-admin-media"></div>' + '<div class="wpview-loading"><ins></ins></div>' + '</div>'; }, render: function( force ) { if ( force || ! this.rendered() ) { this.unbind(); this.setContent( '<p class="wpview-selection-before">\u00a0</p>' + '<div class="wpview-body" contenteditable="false">' + '<div class="toolbar">' + ( _.isFunction( views[ this.type ].edit ) ? '<div class="dashicons dashicons-edit edit"></div>' : '' ) + '<div class="dashicons dashicons-no-alt remove"></div>' + '</div>' + '<div class="wpview-content wpview-type-' + this.type + '">' + ( this.getHtml() || this.loadingPlaceholder() ) + '</div>' + ( this.overlay ? '<div class="wpview-overlay"></div>' : '' ) + '</div>' + '<p class="wpview-selection-after">\u00a0</p>', 'wrap' ); $( this ).trigger( 'ready' ); this.rendered( true ); } }, unbind: function() {}, getEditors: function( callback ) { var editors = []; _.each( tinymce.editors, function( editor ) { if ( editor.plugins.wpview ) { if ( callback ) { callback( editor ); } editors.push( editor ); } }, this ); return editors; }, getNodes: function( callback ) { var nodes = [], self = this; this.getEditors( function( editor ) { $( editor.getBody() ) .find( '[data-wpview-text="' + self.encodedText + '"]' ) .each( function ( i, node ) { if ( callback ) { callback( editor, node, $( node ).find( '.wpview-content' ).get( 0 ) ); } nodes.push( node ); } ); } ); return nodes; }, setContent: function( html, option ) { this.getNodes( function ( editor, node, content ) { var el = ( option === 'wrap' || option === 'replace' ) ? node : content, insert = html; if ( _.isString( insert ) ) { insert = editor.dom.createFragment( insert ); } if ( option === 'replace' ) { editor.dom.replace( insert, el ); } else { el.innerHTML = ''; el.appendChild( insert ); } } ); }, /* jshint scripturl: true */ setIframes: function ( head, body ) { var MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver, importStyles = this.type === 'video' || this.type === 'audio' || this.type === 'playlist'; if ( head || body.indexOf( '<script' ) !== -1 ) { this.getNodes( function ( editor, node, content ) { var dom = editor.dom, styles = '', bodyClasses = editor.getBody().className || '', iframe, iframeDoc, i, resize; content.innerHTML = ''; head = head || ''; if ( importStyles ) { if ( ! wp.mce.views.sandboxStyles ) { tinymce.each( dom.$( 'link[rel="stylesheet"]', editor.getDoc().head ), function( link ) { if ( link.href && link.href.indexOf( 'skins/lightgray/content.min.css' ) === -1 && link.href.indexOf( 'skins/wordpress/wp-content.css' ) === -1 ) { styles += dom.getOuterHTML( link ) + '\n'; } }); wp.mce.views.sandboxStyles = styles; } else { styles = wp.mce.views.sandboxStyles; } } // Seems Firefox needs a bit of time to insert/set the view nodes, or the iframe will fail // especially when switching Text => Visual. setTimeout( function() { iframe = dom.add( content, 'iframe', { src: tinymce.Env.ie ? 'javascript:""' : '', frameBorder: '0', allowTransparency: 'true', scrolling: 'no', 'class': 'wpview-sandbox', style: { width: '100%', display: 'block' } } ); iframeDoc = iframe.contentWindow.document; iframeDoc.open(); iframeDoc.write( '<!DOCTYPE html>' + '<html>' + '<head>' + '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />' + head + styles + '<style>' + 'html {' + 'background: transparent;' + 'padding: 0;' + 'margin: 0;' + '}' + 'body#wpview-iframe-sandbox {' + 'background: transparent;' + 'padding: 1px 0 !important;' + 'margin: -1px 0 0 !important;' + '}' + 'body#wpview-iframe-sandbox:before,' + 'body#wpview-iframe-sandbox:after {' + 'display: none;' + 'content: "";' + '}' + '</style>' + '</head>' + '<body id="wpview-iframe-sandbox" class="' + bodyClasses + '">' + body + '</body>' + '</html>' ); iframeDoc.close(); resize = function() { // Make sure the iframe still exists. iframe.contentWindow && $( iframe ).height( $( iframeDoc.body ).height() ); }; if ( MutationObserver ) { new MutationObserver( _.debounce( function() { resize(); }, 100 ) ) .observe( iframeDoc.body, { attributes: true, childList: true, subtree: true } ); } else { for ( i = 1; i < 6; i++ ) { setTimeout( resize, i * 700 ); } } if ( importStyles ) { editor.on( 'wp-body-class-change', function() { iframeDoc.body.className = editor.getBody().className; }); } }, 50 ); }); } else { this.setContent( body ); } }, setError: function( message, dashicon ) { this.setContent( '<div class="wpview-error">' + '<div class="dashicons dashicons-' + ( dashicon ? dashicon : 'no' ) + '"></div>' + '<p>' + message + '</p>' + '</div>' ); }, rendered: function( value ) { var notRendered; this.getNodes( function( editor, node ) { if ( value != null ) { $( node ).data( 'rendered', value === true ); } else { notRendered = notRendered || ! $( node ).data( 'rendered' ); } } ); return ! notRendered; } } ); // take advantage of the Backbone extend method wp.mce.View.extend = Backbone.View.extend; /** * wp.mce.views * * A set of utilities that simplifies adding custom UI within a TinyMCE editor. * At its core, it serves as a series of converters, transforming text to a * custom UI, and back again. */ wp.mce.views = { /** * wp.mce.views.register( type, view ) * * Registers a new TinyMCE view. * * @param type * @param constructor * */ register: function( type, constructor ) { var defaultConstructor = { type: type, View: {}, toView: function( content ) { var match = wp.shortcode.next( this.type, content ); if ( ! match ) { return; } return { index: match.index, content: match.content, options: { shortcode: match.shortcode } }; } }; constructor = _.defaults( constructor, defaultConstructor ); constructor.View = wp.mce.View.extend( constructor.View ); views[ type ] = constructor; }, /** * wp.mce.views.get( id ) * * Returns a TinyMCE view constructor. * * @param type */ get: function( type ) { return views[ type ]; }, /** * wp.mce.views.unregister( type ) * * Unregisters a TinyMCE view. * * @param type */ unregister: function( type ) { delete views[ type ]; }, /** * wp.mce.views.unbind( editor ) * * The editor DOM is being rebuilt, run cleanup. */ unbind: function() { _.each( instances, function( instance ) { instance.unbind(); } ); }, /** * toViews( content ) * Scans a `content` string for each view's pattern, replacing any * matches with wrapper elements, and creates a new instance for * every match, which triggers the related data to be fetched. * * @param content */ toViews: function( content ) { var pieces = [ { content: content } ], current; _.each( views, function( view, viewType ) { current = pieces.slice(); pieces = []; _.each( current, function( piece ) { var remaining = piece.content, result; // Ignore processed pieces, but retain their location. if ( piece.processed ) { pieces.push( piece ); return; } // Iterate through the string progressively matching views // and slicing the string as we go. while ( remaining && (result = view.toView( remaining )) ) { // Any text before the match becomes an unprocessed piece. if ( result.index ) { pieces.push({ content: remaining.substring( 0, result.index ) }); } // Add the processed piece for the match. pieces.push({ content: wp.mce.views.toView( viewType, result.content, result.options ), processed: true }); // Update the remaining content. remaining = remaining.slice( result.index + result.content.length ); } // There are no additional matches. If any content remains, // add it as an unprocessed piece. if ( remaining ) { pieces.push({ content: remaining }); } }); }); return _.pluck( pieces, 'content' ).join(''); }, /** * Create a placeholder for a particular view type * * @param viewType * @param text * @param options * */ toView: function( viewType, text, options ) { var view = wp.mce.views.get( viewType ), encodedText = window.encodeURIComponent( text ), instance, viewOptions; if ( ! view ) { return text; } if ( ! wp.mce.views.getInstance( encodedText ) ) { viewOptions = options; viewOptions.type = viewType; viewOptions.encodedText = encodedText; instance = new view.View( viewOptions ); instances[ encodedText ] = instance; } return wp.html.string({ tag: 'div', attrs: { 'class': 'wpview-wrap', 'data-wpview-text': encodedText, 'data-wpview-type': viewType }, content: '\u00a0' }); }, /** * Refresh views after an update is made * * @param view {object} being refreshed * @param text {string} textual representation of the view */ refreshView: function( view, text ) { var encodedText = window.encodeURIComponent( text ), viewOptions, result, instance; instance = wp.mce.views.getInstance( encodedText ); if ( ! instance ) { result = view.toView( text ); viewOptions = result.options; viewOptions.type = view.type; viewOptions.encodedText = encodedText; instance = new view.View( viewOptions ); instances[ encodedText ] = instance; } instance.render(); }, getInstance: function( encodedText ) { return instances[ encodedText ]; }, /** * render( scope ) * * Renders any view instances inside a DOM node `scope`. * * View instances are detected by the presence of wrapper elements. * To generate wrapper elements, pass your content through * `wp.mce.view.toViews( content )`. */ render: function( force ) { _.each( instances, function( instance ) { instance.render( force ); } ); }, edit: function( node ) { var viewType = $( node ).data('wpview-type'), view = wp.mce.views.get( viewType ); if ( view ) { view.edit( node ); } } }; wp.mce.views.register( 'gallery', { View: { template: media.template( 'editor-gallery' ), // The fallback post ID to use as a parent for galleries that don't // specify the `ids` or `include` parameters. // // Uses the hidden input on the edit posts page by default. postID: $('#post_ID').val(), initialize: function( options ) { this.shortcode = options.shortcode; this.fetch(); }, fetch: function() { var self = this; this.attachments = wp.media.gallery.attachments( this.shortcode, this.postID ); this.dfd = this.attachments.more().done( function() { self.render( true ); } ); }, getHtml: function() { var attrs = this.shortcode.attrs.named, attachments = false, options; // Don't render errors while still fetching attachments if ( this.dfd && 'pending' === this.dfd.state() && ! this.attachments.length ) { return ''; } if ( this.attachments.length ) { attachments = this.attachments.toJSON(); _.each( attachments, function( attachment ) { if ( attachment.sizes ) { if ( attachment.sizes.thumbnail ) { attachment.thumbnail = attachment.sizes.thumbnail; } else if ( attachment.sizes.full ) { attachment.thumbnail = attachment.sizes.full; } } } ); } options = { attachments: attachments, columns: attrs.columns ? parseInt( attrs.columns, 10 ) : wp.media.galleryDefaults.columns }; return this.template( options ); } }, edit: function( node ) { var gallery = wp.media.gallery, self = this, frame, data; data = window.decodeURIComponent( $( node ).attr('data-wpview-text') ); frame = gallery.edit( data ); frame.state('gallery-edit').on( 'update', function( selection ) { var shortcode = gallery.shortcode( selection ).string(); $( node ).attr( 'data-wpview-text', window.encodeURIComponent( shortcode ) ); wp.mce.views.refreshView( self, shortcode ); }); frame.on( 'close', function() { frame.detach(); }); } } ); /** * These are base methods that are shared by the audio and video shortcode's MCE controller. * * @mixin */ wp.mce.av = { View: { overlay: true, action: 'parse-media-shortcode', initialize: function( options ) { var self = this; this.shortcode = options.shortcode; _.bindAll( this, 'setIframes', 'setNodes', 'fetch', 'stopPlayers' ); $( this ).on( 'ready', this.setNodes ); $( document ).on( 'media:edit', this.stopPlayers ); this.fetch(); this.getEditors( function( editor ) { editor.on( 'hide', self.stopPlayers ); }); }, setNodes: function () { if ( this.parsed ) { this.setIframes( this.parsed.head, this.parsed.body ); } else { this.fail(); } }, fetch: function () { var self = this; wp.ajax.send( this.action, { data: { post_ID: $( '#post_ID' ).val() || 0, type: this.shortcode.tag, shortcode: this.shortcode.string() } } ) .done( function( response ) { if ( response ) { self.parsed = response; self.setIframes( response.head, response.body ); } else { self.fail( true ); } } ) .fail( function( response ) { self.fail( response || true ); } ); }, fail: function( error ) { if ( ! this.error ) { if ( error ) { this.error = error; } else { return; } } if ( this.error.message ) { if ( ( this.error.type === 'not-embeddable' && this.type === 'embed' ) || this.error.type === 'not-ssl' || this.error.type === 'no-items' ) { this.setError( this.error.message, 'admin-media' ); } else { this.setContent( '<p>' + this.original + '</p>', 'replace' ); } } else if ( this.error.statusText ) { this.setError( this.error.statusText, 'admin-media' ); } else if ( this.original ) { this.setContent( '<p>' + this.original + '</p>', 'replace' ); } }, stopPlayers: function( remove ) { var rem = remove === 'remove'; this.getNodes( function( editor, node, content ) { var p, win, iframe = $( 'iframe.wpview-sandbox', content ).get(0); if ( iframe && ( win = iframe.contentWindow ) && win.mejs ) { // Sometimes ME.js may show a "Download File" placeholder and player.remove() doesn't exist there. try { for ( p in win.mejs.players ) { win.mejs.players[p].pause(); if ( rem ) { win.mejs.players[p].remove(); } } } catch( er ) {} } }); }, unbind: function() { this.stopPlayers( 'remove' ); } }, /** * Called when a TinyMCE view is clicked for editing. * - Parses the shortcode out of the element's data attribute * - Calls the `edit` method on the shortcode model * - Launches the model window * - Bind's an `update` callback which updates the element's data attribute * re-renders the view * * @param {HTMLElement} node */ edit: function( node ) { var media = wp.media[ this.type ], self = this, frame, data, callback; $( document ).trigger( 'media:edit' ); data = window.decodeURIComponent( $( node ).attr('data-wpview-text') ); frame = media.edit( data ); frame.on( 'close', function() { frame.detach(); } ); callback = function( selection ) { var shortcode = wp.media[ self.type ].shortcode( selection ).string(); $( node ).attr( 'data-wpview-text', window.encodeURIComponent( shortcode ) ); wp.mce.views.refreshView( self, shortcode ); frame.detach(); }; if ( _.isArray( self.state ) ) { _.each( self.state, function (state) { frame.state( state ).on( 'update', callback ); } ); } else { frame.state( self.state ).on( 'update', callback ); } frame.open(); } }; /** * TinyMCE handler for the video shortcode * * @mixes wp.mce.av */ wp.mce.views.register( 'video', _.extend( {}, wp.mce.av, { state: 'video-details' } ) ); /** * TinyMCE handler for the audio shortcode * * @mixes wp.mce.av */ wp.mce.views.register( 'audio', _.extend( {}, wp.mce.av, { state: 'audio-details' } ) ); /** * TinyMCE handler for the playlist shortcode * * @mixes wp.mce.av */ wp.mce.views.register( 'playlist', _.extend( {}, wp.mce.av, { state: [ 'playlist-edit', 'video-playlist-edit' ] } ) ); /** * TinyMCE handler for the embed shortcode */ wp.mce.embedMixin = { View: _.extend( {}, wp.mce.av.View, { overlay: true, action: 'parse-embed', initialize: function( options ) { this.content = options.content; this.original = options.url || options.shortcode.string(); if ( options.url ) { this.shortcode = media.embed.shortcode( { url: options.url } ); } else { this.shortcode = options.shortcode; } _.bindAll( this, 'setIframes', 'setNodes', 'fetch' ); $( this ).on( 'ready', this.setNodes ); this.fetch(); } } ), edit: function( node ) { var embed = media.embed, self = this, frame, data, isURL = 'embedURL' === this.type; $( document ).trigger( 'media:edit' ); data = window.decodeURIComponent( $( node ).attr('data-wpview-text') ); frame = embed.edit( data, isURL ); frame.on( 'close', function() { frame.detach(); } ); frame.state( 'embed' ).props.on( 'change:url', function (model, url) { if ( ! url ) { return; } frame.state( 'embed' ).metadata = model.toJSON(); } ); frame.state( 'embed' ).on( 'select', function() { var shortcode; if ( isURL ) { shortcode = frame.state( 'embed' ).metadata.url; } else { shortcode = embed.shortcode( frame.state( 'embed' ).metadata ).string(); } $( node ).attr( 'data-wpview-text', window.encodeURIComponent( shortcode ) ); wp.mce.views.refreshView( self, shortcode ); frame.detach(); } ); frame.open(); } }; wp.mce.views.register( 'embed', _.extend( {}, wp.mce.embedMixin ) ); wp.mce.views.register( 'embedURL', _.extend( {}, wp.mce.embedMixin, { toView: function( content ) { var re = /(?:^|<p>)(https?:\/\/[^\s"]+?)(?:<\/p>\s*|$)/gi, match = re.exec( tinymce.trim( content ) ); if ( ! match ) { return; } return { index: match.index, content: match[0], options: { url: match[1] } }; } } ) ); }(jQuery));
gpl-2.0
nickpellant/our-boxen
vendor/bundle/ruby/2.1.0/gems/puppet-3.7.1/lib/puppet/vendor/semantic/spec/unit/semantic/dependency/module_release_spec.rb
4200
require 'spec_helper' require 'semantic/dependency/module_release' describe Semantic::Dependency::ModuleRelease do def source @source ||= Semantic::Dependency::Source.new end def make_release(name, version, deps = {}) source.create_release(name, version, deps) end let(:no_dependencies) do make_release('module', '1.2.3') end let(:one_dependency) do make_release('module', '1.2.3', 'foo' => '1.0.0') end let(:three_dependencies) do dependencies = { 'foo' => '1.0.0', 'bar' => '2.0.0', 'baz' => '3.0.0' } make_release('module', '1.2.3', dependencies) end describe '#dependency_names' do it "lists the names of all the release's dependencies" do expect(no_dependencies.dependency_names).to match_array %w[] expect(one_dependency.dependency_names).to match_array %w[foo] expect(three_dependencies.dependency_names).to match_array %w[foo bar baz] end end describe '#to_s' do let(:name) { 'foobarbaz' } let(:version) { '1.2.3' } subject { make_release(name, version).to_s } it { should =~ /#{name}/ } it { should =~ /#{version}/ } end describe '#<<' do it 'marks matching dependencies as satisfied' do one_dependency << make_release('foo', '1.0.0') expect(one_dependency).to be_satisfied end it 'does not mark mis-matching dependency names as satisfied' do one_dependency << make_release('WAT', '1.0.0') expect(one_dependency).to_not be_satisfied end it 'does not mark mis-matching dependency versions as satisfied' do one_dependency << make_release('foo', '0.0.1') expect(one_dependency).to_not be_satisfied end end describe '#<=>' do it 'considers releases with greater version numbers greater' do expect(make_release('foo', '1.0.0')).to be > make_release('foo', '0.1.0') end it 'considers releases with lesser version numbers lesser' do expect(make_release('foo', '0.1.0')).to be < make_release('foo', '1.0.0') end it 'orders releases with different names lexographically' do expect(make_release('bar', '1.0.0')).to be < make_release('foo', '1.0.0') end it 'orders releases by name first' do expect(make_release('bar', '2.0.0')).to be < make_release('foo', '1.0.0') end end describe '#satisfied?' do it 'returns true when there are no dependencies to satisfy' do expect(no_dependencies).to be_satisfied end it 'returns false when no dependencies have been satisified' do expect(one_dependency).to_not be_satisfied end it 'returns false when not all dependencies have been satisified' do releases = %w[ 0.9.0 1.0.0 1.0.1 ].map { |ver| make_release('foo', ver) } three_dependencies << releases expect(three_dependencies).to_not be_satisfied end it 'returns false when not all dependency versions have been satisified' do releases = %w[ 0.9.0 1.0.1 ].map { |ver| make_release('foo', ver) } one_dependency << releases expect(one_dependency).to_not be_satisfied end it 'returns true when all dependencies have been satisified' do releases = %w[ 0.9.0 1.0.0 1.0.1 ].map { |ver| make_release('foo', ver) } one_dependency << releases expect(one_dependency).to be_satisfied end end describe '#satisfies_dependency?' do it 'returns false when there are no dependencies to satisfy' do release = make_release('foo', '1.0.0') expect(no_dependencies.satisfies_dependency?(release)).to_not be true end it 'returns false when the release does not match the dependency name' do release = make_release('bar', '1.0.0') expect(one_dependency.satisfies_dependency?(release)).to_not be true end it 'returns false when the release does not match the dependency version' do release = make_release('foo', '4.0.0') expect(one_dependency.satisfies_dependency?(release)).to_not be true end it 'returns true when the release matches the dependency' do release = make_release('foo', '1.0.0') expect(one_dependency.satisfies_dependency?(release)).to be true end end end
mit
maovt/p3_web
public/js/release/JBrowse/View/Export.js
1357
define("JBrowse/View/Export", [ 'dojo/_base/declare', 'dojo/_base/lang', 'dojo/_base/array' ], function( declare, lang, array ) { return declare( null, { /** * Data export driver base class. * @constructs */ constructor: function( args ) { args = args || {}; this.printFunc = args.print || function( line ) { this.output += line; }; this.refSeq = args.refSeq; this.output = ''; this.track = args.track; this.store = args.store; }, // will need to override this if you're not exporting regular features exportRegion: function( region, callback ) { var output = ''; this.store.getFeatures( region, dojo.hitch( this, 'writeFeature' ), dojo.hitch(this,function () { callback( this.output ); }), dojo.hitch( this, function( error ) { console.error(error); } ) ); }, print: function( l ) { if( lang.isArray( l ) ) { array.forEach( l, this.printFunc, this ); } else { this.printFunc( l ); } }, /** * Write the feature to the GFF3 under construction. * @returns nothing */ writeFeature: function(feature) { this.print( this.formatFeature(feature) ); } } ); });
mit
jonpstone/portfolio-project-rails-mean-movie-reviews
vendor/bundle/ruby/2.4.0/gems/nenv-0.3.0/lib/nenv/builder.rb
145
require 'nenv/environment' module Nenv module Builder def self.build(&block) Class.new(Nenv::Environment, &block) end end end
mit
alexhardwicke/GitVersion
src/GitVersionCore/VersioningModes/VersioningModeExtension.cs
651
namespace GitVersion { using System; using GitVersion.VersioningModes; public static class VersioningModeExtension { public static VersioningModeBase GetInstance(this VersioningMode _this) { switch (_this) { case VersioningMode.ContinuousDelivery: return new ContinuousDeliveryMode(); case VersioningMode.ContinuousDeployment: return new ContinuousDeploymentMode(); default: throw new ArgumentException("No instance exists for this versioning mode."); } } } }
mit
kevinsimper/isomorphic-apps-presentation
node_modules/surge/node_modules/moniker/lib/moniker.js
2558
var Fs = require('fs'), Path = require('path'); exports.choose = choose; exports.noun = noun; exports.verb = verb; exports.adjective = adjective; exports.read = read; exports.generator = generator; exports.Dictionary = Dictionary; exports.Generator = Generator; // ## Shortcuts ## function noun(opt) { return read(builtin('nouns'), opt); } function verb(opt) { return read(builtin('verbs'), opt); } function adjective(opt) { return read(builtin('adjectives'), opt); } function read(path, opt) { return (new Dictionary()).read(path, opt); } function generator(dicts, opt) { var gen = new Generator(opt); dicts.forEach(function(dict) { gen.use(dict, opt); }); return gen; } var _names; function choose() { if (!_names) _names = generator([adjective, noun]); return _names.choose(); } // ## Dictionary ## function Dictionary() { this.words = []; } Dictionary.prototype.read = function(path, opt) { var words = this.words, maxSize = opt && opt.maxSize, enc = (opt && opt.encoding) || 'utf-8', data = Fs.readFileSync(path, enc); data.split(/\s+/).forEach(function(word) { if (word && (!maxSize || word.length <= maxSize)) words.push(word); }); return this; }; Dictionary.prototype.choose = function() { return this.words[random(this.words.length)]; }; // ## Generator ## function Generator(opt) { this.dicts = []; this.glue = (opt && opt.glue) || '-'; } Generator.prototype.choose = function() { var dicts = this.dicts, size = dicts.length; if (size === 0) throw new Error('no available dictionaries.'); if (size === 1) return dicts[0].choose(); var probe, tries = 10, used = {}; var seq = dicts.map(function(dict) { for (var i = 0; i < tries; i++) { if (!used.hasOwnProperty(probe = dict.choose())) break; } if (i === tries) throw new Error('too many tries to find a unique word'); used[probe] = true; return probe; }); return seq.join(this.glue); }; Generator.prototype.use = function(dict, opt) { var dicts = this.dicts; if (dict instanceof Dictionary) dicts.push(dict); if (typeof dict == 'string') dicts.push((new Dictionary()).read(dict, opt)); else if (typeof dict == 'function') dicts.push(dict(opt)); else next(new Error('unrecognized dictionary type')); return this; }; // ## Helpers ## function builtin(name) { return Path.join(__dirname, '../dict', name + '.txt'); } function random(limit) { return Math.floor(Math.random() * limit); }
mit
bsherrill480/portfolio
gulp/tasks/development.js
230
import gulp from 'gulp'; import runSequence from 'run-sequence'; gulp.task('dev', ['clean'], function(cb) { global.isProd = false; runSequence(['styles', 'images', 'fonts', 'views'], 'browserify', 'watch', cb); });
mit
pombredanne/fuzzywuzzy
fuzzywuzzy/StringMatcher.py
2437
#!/usr/bin/env python # encoding: utf-8 """ StringMatcher.py ported from python-Levenshtein [https://github.com/miohtama/python-Levenshtein] License available here: https://github.com/miohtama/python-Levenshtein/blob/master/COPYING """ from Levenshtein import * from warnings import warn class StringMatcher: """A SequenceMatcher-like class built on the top of Levenshtein""" def _reset_cache(self): self._ratio = self._distance = None self._opcodes = self._editops = self._matching_blocks = None def __init__(self, isjunk=None, seq1='', seq2=''): if isjunk: warn("isjunk not NOT implemented, it will be ignored") self._str1, self._str2 = seq1, seq2 self._reset_cache() def set_seqs(self, seq1, seq2): self._str1, self._str2 = seq1, seq2 self._reset_cache() def set_seq1(self, seq1): self._str1 = seq1 self._reset_cache() def set_seq2(self, seq2): self._str2 = seq2 self._reset_cache() def get_opcodes(self): if not self._opcodes: if self._editops: self._opcodes = opcodes(self._editops, self._str1, self._str2) else: self._opcodes = opcodes(self._str1, self._str2) return self._opcodes def get_editops(self): if not self._editops: if self._opcodes: self._editops = editops(self._opcodes, self._str1, self._str2) else: self._editops = editops(self._str1, self._str2) return self._editops def get_matching_blocks(self): if not self._matching_blocks: self._matching_blocks = matching_blocks(self.get_opcodes(), self._str1, self._str2) return self._matching_blocks def ratio(self): if not self._ratio: self._ratio = ratio(self._str1, self._str2) return self._ratio def quick_ratio(self): # This is usually quick enough :o) if not self._ratio: self._ratio = ratio(self._str1, self._str2) return self._ratio def real_quick_ratio(self): len1, len2 = len(self._str1), len(self._str2) return 2.0 * min(len1, len2) / (len1 + len2) def distance(self): if not self._distance: self._distance = distance(self._str1, self._str2) return self._distance
mit
surkovalex/xbmc
xbmc/addons/GUIDialogAddonSettings.cpp
41956
/* * Copyright (C) 2005-2015 Team Kodi * http://kodi.tv * * This Program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This Program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Kodi; see the file COPYING. If not, see * <http://www.gnu.org/licenses/>. * */ #include "GUIDialogAddonSettings.h" #include "filesystem/PluginDirectory.h" #include "addons/IAddon.h" #include "addons/AddonManager.h" #include "dialogs/GUIDialogNumeric.h" #include "dialogs/GUIDialogFileBrowser.h" #include "dialogs/GUIDialogOK.h" #include "guilib/GUIControlGroupList.h" #include "guilib/GUISettingsSliderControl.h" #include "utils/URIUtils.h" #include "utils/StringUtils.h" #include "storage/MediaManager.h" #include "guilib/GUILabelControl.h" #include "guilib/GUIRadioButtonControl.h" #include "guilib/GUISpinControlEx.h" #include "guilib/GUIImage.h" #include "input/Key.h" #include "filesystem/Directory.h" #include "guilib/GUIWindowManager.h" #include "messaging/ApplicationMessenger.h" #include "guilib/GUIKeyboardFactory.h" #include "FileItem.h" #include "settings/AdvancedSettings.h" #include "settings/MediaSourceSettings.h" #include "GUIInfoManager.h" #include "GUIUserMessages.h" #include "dialogs/GUIDialogSelect.h" #include "GUIWindowAddonBrowser.h" #include "utils/log.h" #include "URL.h" #include "utils/XMLUtils.h" #include "utils/Variant.h" using namespace ADDON; using namespace KODI::MESSAGING; using XFILE::CDirectory; #define CONTROL_SETTINGS_AREA 2 #define CONTROL_DEFAULT_BUTTON 3 #define CONTROL_DEFAULT_RADIOBUTTON 4 #define CONTROL_DEFAULT_SPIN 5 #define CONTROL_DEFAULT_SEPARATOR 6 #define CONTROL_DEFAULT_LABEL_SEPARATOR 7 #define CONTROL_DEFAULT_SLIDER 8 #define CONTROL_SECTION_AREA 9 #define CONTROL_DEFAULT_SECTION_BUTTON 13 #define ID_BUTTON_OK 10 #define ID_BUTTON_CANCEL 11 #define ID_BUTTON_DEFAULT 12 #define CONTROL_HEADING_LABEL 20 #define CONTROL_START_SECTION 100 #define CONTROL_START_SETTING 200 CGUIDialogAddonSettings::CGUIDialogAddonSettings() : CGUIDialogBoxBase(WINDOW_DIALOG_ADDON_SETTINGS, "DialogAddonSettings.xml") { m_currentSection = 0; m_totalSections = 1; m_saveToDisk = false; } CGUIDialogAddonSettings::~CGUIDialogAddonSettings(void) { } bool CGUIDialogAddonSettings::OnMessage(CGUIMessage& message) { switch (message.GetMessage()) { case GUI_MSG_WINDOW_DEINIT: { FreeSections(); } break; case GUI_MSG_CLICKED: { int iControl = message.GetSenderId(); bool bCloseDialog = false; if (iControl == ID_BUTTON_DEFAULT) SetDefaultSettings(); else if (iControl != ID_BUTTON_OK) bCloseDialog = ShowVirtualKeyboard(iControl); if (iControl == ID_BUTTON_OK || iControl == ID_BUTTON_CANCEL || bCloseDialog) { if (iControl == ID_BUTTON_OK || bCloseDialog) { m_bConfirmed = true; SaveSettings(); } Close(); return true; } } break; case GUI_MSG_FOCUSED: { CGUIDialogBoxBase::OnMessage(message); int focusedControl = GetFocusedControlID(); if (focusedControl >= CONTROL_START_SECTION && focusedControl < (int)(CONTROL_START_SECTION + m_totalSections) && focusedControl - CONTROL_START_SECTION != (int)m_currentSection) { // changing section UpdateFromControls(); m_currentSection = focusedControl - CONTROL_START_SECTION; CreateControls(); } return true; } case GUI_MSG_SETTING_UPDATED: { std::string id = message.GetStringParam(0); std::string value = message.GetStringParam(1); m_settings[id] = value; if (GetFocusedControl()) { int iControl = GetFocusedControl()->GetID(); CreateControls(); CGUIMessage msg(GUI_MSG_SETFOCUS,GetID(),iControl); OnMessage(msg); } else CreateControls(); return true; } } return CGUIDialogBoxBase::OnMessage(message); } bool CGUIDialogAddonSettings::OnAction(const CAction& action) { if (action.GetID() == ACTION_DELETE_ITEM) { CGUIControl* pControl = GetFocusedControl(); if (pControl) { int iControl = pControl->GetID(); int controlId = CONTROL_START_SETTING; const TiXmlElement* setting = GetFirstSetting(); UpdateFromControls(); while (setting) { if (controlId == iControl) { const char* id = setting->Attribute("id"); const char* value = setting->Attribute("default"); if (id && value) m_settings[id] = value; CreateControls(); CGUIMessage msg(GUI_MSG_SETFOCUS,GetID(),iControl); OnMessage(msg); return true; } setting = setting->NextSiblingElement("setting"); controlId++; } } } return CGUIDialogBoxBase::OnAction(action); } void CGUIDialogAddonSettings::OnInitWindow() { m_currentSection = 0; m_totalSections = 1; CreateSections(); CreateControls(); CGUIDialogBoxBase::OnInitWindow(); SET_CONTROL_VISIBLE(ID_BUTTON_OK); SET_CONTROL_VISIBLE(ID_BUTTON_CANCEL); SET_CONTROL_VISIBLE(ID_BUTTON_DEFAULT); SET_CONTROL_VISIBLE(CONTROL_HEADING_LABEL); } // \brief Show CGUIDialogOK dialog, then wait for user to dismiss it. bool CGUIDialogAddonSettings::ShowAndGetInput(const AddonPtr &addon, bool saveToDisk /* = true */) { if (!addon) return false; if (!g_passwordManager.CheckMenuLock(WINDOW_ADDON_BROWSER)) return false; bool ret(false); if (addon->HasSettings()) { // Create the dialog CGUIDialogAddonSettings* pDialog = NULL; pDialog = (CGUIDialogAddonSettings*) g_windowManager.GetWindow(WINDOW_DIALOG_ADDON_SETTINGS); if (!pDialog) return false; // Set the heading std::string heading = StringUtils::Format("$LOCALIZE[10004] - %s", addon->Name().c_str()); // "Settings - AddonName" pDialog->m_strHeading = heading; pDialog->m_addon = addon; pDialog->m_saveToDisk = saveToDisk; pDialog->Open(); ret = true; } else { // addon does not support settings, inform user CGUIDialogOK::ShowAndGetInput(CVariant{24000}, CVariant{24030}); } return ret; } bool CGUIDialogAddonSettings::ShowVirtualKeyboard(int iControl) { int controlId = CONTROL_START_SETTING; bool bCloseDialog = false; const TiXmlElement *setting = GetFirstSetting(); while (setting) { if (controlId == iControl) { const CGUIControl* control = GetControl(controlId); const std::string id = XMLUtils::GetAttribute(setting, "id"); const std::string type = XMLUtils::GetAttribute(setting, "type"); //Special handling for actions: does not require id attribute. TODO: refactor me. if (control && control->GetControlType() == CGUIControl::GUICONTROL_BUTTON && type == "action") { const char *option = setting->Attribute("option"); std::string action = XMLUtils::GetAttribute(setting, "action"); if (!action.empty()) { // replace $CWD with the url of plugin/script StringUtils::Replace(action, "$CWD", m_addon->Path()); StringUtils::Replace(action, "$ID", m_addon->ID()); if (option) bCloseDialog = (strcmpi(option, "close") == 0); CApplicationMessenger::GetInstance().SendMsg(TMSG_EXECUTE_BUILT_IN, -1, -1, nullptr, action); } break; } if (control && control->GetControlType() == CGUIControl::GUICONTROL_BUTTON && !id.empty() && !type.empty()) { const char *option = setting->Attribute("option"); const char *source = setting->Attribute("source"); std::string value = m_buttonValues[id]; std::string label = GetString(setting->Attribute("label")); if (type == "text") { // get any options bool bHidden = false; bool bEncoded = false; if (option) { bHidden = (strstr(option, "hidden") != NULL); bEncoded = (strstr(option, "urlencoded") != NULL); } if (bEncoded) value = CURL::Decode(value); if (CGUIKeyboardFactory::ShowAndGetInput(value, CVariant{label}, true, bHidden)) { // if hidden hide input if (bHidden) { std::string hiddenText; hiddenText.append(value.size(), L'*'); ((CGUIButtonControl *)control)->SetLabel2(hiddenText); } else ((CGUIButtonControl*) control)->SetLabel2(value); if (bEncoded) value = CURL::Encode(value); } } else if (type == "number" && CGUIDialogNumeric::ShowAndGetNumber(value, label)) { ((CGUIButtonControl*) control)->SetLabel2(value); } else if (type == "ipaddress" && CGUIDialogNumeric::ShowAndGetIPAddress(value, label)) { ((CGUIButtonControl*) control)->SetLabel2(value); } else if (type == "select") { CGUIDialogSelect *pDlg = (CGUIDialogSelect*)g_windowManager.GetWindow(WINDOW_DIALOG_SELECT); if (pDlg) { pDlg->SetHeading(CVariant{label}); pDlg->Reset(); int selected = -1; std::vector<std::string> valuesVec; if (setting->Attribute("values")) StringUtils::Tokenize(setting->Attribute("values"), valuesVec, "|"); else if (setting->Attribute("lvalues")) { // localize StringUtils::Tokenize(setting->Attribute("lvalues"), valuesVec, "|"); for (unsigned int i = 0; i < valuesVec.size(); i++) { if (i == (unsigned int)atoi(value.c_str())) selected = i; std::string localized = g_localizeStrings.GetAddonString(m_addon->ID(), atoi(valuesVec[i].c_str())); if (localized.empty()) localized = g_localizeStrings.Get(atoi(valuesVec[i].c_str())); valuesVec[i] = localized; } } else if (source) { valuesVec = GetFileEnumValues(source, XMLUtils::GetAttribute(setting, "mask"), XMLUtils::GetAttribute(setting, "option")); } for (unsigned int i = 0; i < valuesVec.size(); i++) { pDlg->Add(valuesVec[i]); if (selected == (int)i || (selected < 0 && StringUtils::EqualsNoCase(valuesVec[i], value))) pDlg->SetSelected(i); // FIXME: the SetSelected() does not select "i", it always defaults to the first position } pDlg->Open(); int iSelected = pDlg->GetSelectedItem(); if (iSelected >= 0) { if (setting->Attribute("lvalues")) value = StringUtils::Format("%i", iSelected); else value = valuesVec[iSelected]; ((CGUIButtonControl*) control)->SetLabel2(valuesVec[iSelected]); } } } else if (type == "audio" || type == "video" || type == "image" || type == "executable" || type == "file" || type == "folder") { // setup the shares VECSOURCES *shares = NULL; if (source && strcmpi(source, "") != 0) shares = CMediaSourceSettings::GetInstance().GetSources(source); VECSOURCES localShares; if (!shares) { g_mediaManager.GetLocalDrives(localShares); if (!source || strcmpi(source, "local") != 0) g_mediaManager.GetNetworkLocations(localShares); } else // always append local drives { localShares = *shares; g_mediaManager.GetLocalDrives(localShares); } if (type == "folder") { // get any options bool bWriteOnly = false; if (option) bWriteOnly = (strcmpi(option, "writeable") == 0); if (CGUIDialogFileBrowser::ShowAndGetDirectory(localShares, label, value, bWriteOnly)) ((CGUIButtonControl*) control)->SetLabel2(value); } else if (type == "image") { if (CGUIDialogFileBrowser::ShowAndGetImage(localShares, label, value)) ((CGUIButtonControl*) control)->SetLabel2(value); } else { // set the proper mask std::string strMask; if (setting->Attribute("mask")) { strMask = setting->Attribute("mask"); // convert mask qualifiers StringUtils::Replace(strMask, "$AUDIO", g_advancedSettings.GetMusicExtensions()); StringUtils::Replace(strMask, "$VIDEO", g_advancedSettings.m_videoExtensions); StringUtils::Replace(strMask, "$IMAGE", g_advancedSettings.m_pictureExtensions); #if defined(_WIN32_WINNT) StringUtils::Replace(strMask, "$EXECUTABLE", ".exe|.bat|.cmd|.py"); #else StringUtils::Replace(strMask, "$EXECUTABLE", ""); #endif } else { if (type == "video") strMask = g_advancedSettings.m_videoExtensions; else if (type == "audio") strMask = g_advancedSettings.GetMusicExtensions(); else if (type == "executable") #if defined(_WIN32_WINNT) strMask = ".exe|.bat|.cmd|.py"; #else strMask = ""; #endif } // get any options bool bUseThumbs = false; bool bUseFileDirectories = false; if (option) { std::vector<std::string> options = StringUtils::Split(option, '|'); bUseThumbs = find(options.begin(), options.end(), "usethumbs") != options.end(); bUseFileDirectories = find(options.begin(), options.end(), "treatasfolder") != options.end(); } if (CGUIDialogFileBrowser::ShowAndGetFile(localShares, strMask, label, value, bUseThumbs, bUseFileDirectories)) ((CGUIButtonControl*) control)->SetLabel2(value); } } else if (type == "date") { CDateTime date; if (!value.empty()) date.SetFromDBDate(value); SYSTEMTIME timedate; date.GetAsSystemTime(timedate); if(CGUIDialogNumeric::ShowAndGetDate(timedate, label)) { date = timedate; value = date.GetAsDBDate(); ((CGUIButtonControl*) control)->SetLabel2(value); } } else if (type == "time") { SYSTEMTIME timedate; if (value.size() >= 5) { // assumes HH:MM timedate.wHour = atoi(value.substr(0, 2).c_str()); timedate.wMinute = atoi(value.substr(3, 2).c_str()); } if (CGUIDialogNumeric::ShowAndGetTime(timedate, label)) { value = StringUtils::Format("%02d:%02d", timedate.wHour, timedate.wMinute); ((CGUIButtonControl*) control)->SetLabel2(value); } } else if (type == "addon") { const char *strType = setting->Attribute("addontype"); if (strType) { std::vector<std::string> addonTypes = StringUtils::Split(strType, ','); std::vector<ADDON::TYPE> types; for (std::vector<std::string>::iterator i = addonTypes.begin(); i != addonTypes.end(); ++i) { StringUtils::Trim(*i); ADDON::TYPE type = TranslateType(*i); if (type != ADDON_UNKNOWN) types.push_back(type); } if (!types.empty()) { const char *strMultiselect = setting->Attribute("multiselect"); bool multiSelect = strMultiselect && strcmpi(strMultiselect, "true") == 0; if (multiSelect) { // construct vector of addon IDs (IDs are comma seperated in single string) std::vector<std::string> addonIDs = StringUtils::Split(value, ','); if (CGUIWindowAddonBrowser::SelectAddonID(types, addonIDs, false) == 1) { value = StringUtils::Join(addonIDs, ","); ((CGUIButtonControl*) control)->SetLabel2(GetAddonNames(value)); } } else // no need of string splitting/joining if we select only 1 addon if (CGUIWindowAddonBrowser::SelectAddonID(types, value, false) == 1) ((CGUIButtonControl*) control)->SetLabel2(GetAddonNames(value)); } } } m_buttonValues[id] = value; break; } } setting = setting->NextSiblingElement("setting"); controlId++; } EnableControls(); return bCloseDialog; } void CGUIDialogAddonSettings::UpdateFromControls() { int controlID = CONTROL_START_SETTING; const TiXmlElement *setting = GetFirstSetting(); while (setting) { const std::string id = XMLUtils::GetAttribute(setting, "id"); const std::string type = XMLUtils::GetAttribute(setting, "type"); const CGUIControl* control = GetControl(controlID++); if (control) { std::string value; switch (control->GetControlType()) { case CGUIControl::GUICONTROL_BUTTON: value = m_buttonValues[id]; break; case CGUIControl::GUICONTROL_RADIO: value = ((CGUIRadioButtonControl*) control)->IsSelected() ? "true" : "false"; break; case CGUIControl::GUICONTROL_SPINEX: if (type == "fileenum" || type == "labelenum") value = ((CGUISpinControlEx*) control)->GetLabel(); else value = StringUtils::Format("%i", ((CGUISpinControlEx*) control)->GetValue()); break; case CGUIControl::GUICONTROL_SETTINGS_SLIDER: { std::string option = XMLUtils::GetAttribute(setting, "option"); if (option.empty() || StringUtils::EqualsNoCase(option, "float")) value = StringUtils::Format("%f", ((CGUISettingsSliderControl *)control)->GetFloatValue()); else value = StringUtils::Format("%i", ((CGUISettingsSliderControl *)control)->GetIntValue()); } break; default: break; } m_settings[id] = value; } setting = setting->NextSiblingElement("setting"); } } void CGUIDialogAddonSettings::SaveSettings(void) { UpdateFromControls(); for (std::map<std::string, std::string>::iterator i = m_settings.begin(); i != m_settings.end(); ++i) m_addon->UpdateSetting(i->first, i->second); if (m_saveToDisk) { m_addon->SaveSettings(); } } void CGUIDialogAddonSettings::FreeSections() { CGUIControlGroupList *group = dynamic_cast<CGUIControlGroupList *>(GetControl(CONTROL_SECTION_AREA)); if (group) { group->FreeResources(); group->ClearAll(); } m_settings.clear(); m_buttonValues.clear(); FreeControls(); } void CGUIDialogAddonSettings::FreeControls() { // clear the category group CGUIControlGroupList *control = dynamic_cast<CGUIControlGroupList *>(GetControl(CONTROL_SETTINGS_AREA)); if (control) { control->FreeResources(); control->ClearAll(); } } void CGUIDialogAddonSettings::CreateSections() { CGUIControlGroupList *group = dynamic_cast<CGUIControlGroupList *>(GetControl(CONTROL_SECTION_AREA)); CGUIButtonControl *originalButton = dynamic_cast<CGUIButtonControl *>(GetControl(CONTROL_DEFAULT_SECTION_BUTTON)); if (!m_addon) return; if (originalButton) originalButton->SetVisible(false); // clear the category group FreeSections(); // grab our categories const TiXmlElement *category = m_addon->GetSettingsXML()->FirstChildElement("category"); if (!category) // add a default one... category = m_addon->GetSettingsXML(); int buttonID = CONTROL_START_SECTION; while (category) { // add a category CGUIButtonControl *button = originalButton ? originalButton->Clone() : NULL; std::string label = GetString(category->Attribute("label")); if (label.empty()) label = g_localizeStrings.Get(128); if (buttonID >= CONTROL_START_SETTING) { CLog::Log(LOGERROR, "%s - cannot have more than %d categories - simplify your addon!", __FUNCTION__, CONTROL_START_SETTING - CONTROL_START_SECTION); break; } // add the category button if (button && group) { button->SetID(buttonID++); button->SetLabel(label); button->SetVisible(true); group->AddControl(button); } // grab a local copy of all the settings in this category const TiXmlElement *setting = category->FirstChildElement("setting"); while (setting) { const std::string id = XMLUtils::GetAttribute(setting, "id"); if (!id.empty()) m_settings[id] = m_addon->GetSetting(id); setting = setting->NextSiblingElement("setting"); } category = category->NextSiblingElement("category"); } m_totalSections = buttonID - CONTROL_START_SECTION; } void CGUIDialogAddonSettings::CreateControls() { FreeControls(); CGUISpinControlEx *pOriginalSpin = dynamic_cast<CGUISpinControlEx*>(GetControl(CONTROL_DEFAULT_SPIN)); CGUIRadioButtonControl *pOriginalRadioButton = dynamic_cast<CGUIRadioButtonControl *>(GetControl(CONTROL_DEFAULT_RADIOBUTTON)); CGUIButtonControl *pOriginalButton = dynamic_cast<CGUIButtonControl *>(GetControl(CONTROL_DEFAULT_BUTTON)); CGUIImage *pOriginalImage = dynamic_cast<CGUIImage *>(GetControl(CONTROL_DEFAULT_SEPARATOR)); CGUILabelControl *pOriginalLabel = dynamic_cast<CGUILabelControl *>(GetControl(CONTROL_DEFAULT_LABEL_SEPARATOR)); CGUISettingsSliderControl *pOriginalSlider = dynamic_cast<CGUISettingsSliderControl *>(GetControl(CONTROL_DEFAULT_SLIDER)); if (!m_addon || !pOriginalSpin || !pOriginalRadioButton || !pOriginalButton || !pOriginalImage || !pOriginalLabel || !pOriginalSlider) return; pOriginalSpin->SetVisible(false); pOriginalRadioButton->SetVisible(false); pOriginalButton->SetVisible(false); pOriginalImage->SetVisible(false); pOriginalLabel->SetVisible(false); pOriginalSlider->SetVisible(false); CGUIControlGroupList *group = dynamic_cast<CGUIControlGroupList *>(GetControl(CONTROL_SETTINGS_AREA)); if (!group) return; // set our dialog heading SET_CONTROL_LABEL(CONTROL_HEADING_LABEL, m_strHeading); CGUIControl* pControl = NULL; int controlId = CONTROL_START_SETTING; const TiXmlElement *setting = GetFirstSetting(); while (setting) { const std::string type = XMLUtils::GetAttribute(setting, "type"); const std::string id = XMLUtils::GetAttribute(setting, "id"); const std::string values = XMLUtils::GetAttribute(setting, "values"); const std::string lvalues = XMLUtils::GetAttribute(setting, "lvalues"); const std::string entries = XMLUtils::GetAttribute(setting, "entries"); const std::string defaultVal = XMLUtils::GetAttribute(setting, "default"); const std::string subsetting = XMLUtils::GetAttribute(setting, "subsetting"); const std::string label = GetString(setting->Attribute("label"), subsetting == "true"); bool bSort = XMLUtils::GetAttribute(setting, "sort") == "yes"; if (!type.empty()) { bool isAddonSetting = false; if (type == "text" || type == "ipaddress" || type == "number" || type == "video" || type == "audio" || type == "image" || type == "folder" || type == "executable" || type == "file" || type == "action" || type == "date" || type == "time" || type == "select" || (isAddonSetting = type == "addon")) { pControl = new CGUIButtonControl(*pOriginalButton); if (!pControl) return; ((CGUIButtonControl *)pControl)->SetLabel(label); if (!id.empty()) { std::string value = m_settings[id]; m_buttonValues[id] = value; // get any option to test for hidden const std::string option = XMLUtils::GetAttribute(setting, "option"); if (option == "urlencoded") value = CURL::Decode(value); else if (option == "hidden") { std::string hiddenText; hiddenText.append(value.size(), L'*'); ((CGUIButtonControl *)pControl)->SetLabel2(hiddenText); } else { if (isAddonSetting) ((CGUIButtonControl *)pControl)->SetLabel2(GetAddonNames(value)); else if (type == "select" && !lvalues.empty()) { std::vector<std::string> valuesVec = StringUtils::Split(lvalues, '|'); int selected = atoi(value.c_str()); if (selected >= 0 && selected < (int)valuesVec.size()) { std::string label = g_localizeStrings.GetAddonString(m_addon->ID(), atoi(valuesVec[selected].c_str())); if (label.empty()) label = g_localizeStrings.Get(atoi(valuesVec[selected].c_str())); ((CGUIButtonControl *)pControl)->SetLabel2(label); } } else ((CGUIButtonControl *)pControl)->SetLabel2(value); } } else ((CGUIButtonControl *)pControl)->SetLabel2(defaultVal); } else if (type == "bool" && !id.empty()) { pControl = new CGUIRadioButtonControl(*pOriginalRadioButton); if (!pControl) return; ((CGUIRadioButtonControl *)pControl)->SetLabel(label); ((CGUIRadioButtonControl *)pControl)->SetSelected(m_settings[id] == "true"); } else if ((type == "enum" || type == "labelenum") && !id.empty()) { std::vector<std::string> valuesVec; std::vector<std::string> entryVec; pControl = new CGUISpinControlEx(*pOriginalSpin); if (!pControl) return; ((CGUISpinControlEx *)pControl)->SetText(label); if (!lvalues.empty()) StringUtils::Tokenize(lvalues, valuesVec, "|"); else if (values == "$HOURS") { for (unsigned int i = 0; i < 24; i++) { CDateTime time(2000, 1, 1, i, 0, 0); valuesVec.push_back(g_infoManager.LocalizeTime(time, TIME_FORMAT_HH_MM_XX)); } } else StringUtils::Tokenize(values, valuesVec, "|"); if (!entries.empty()) StringUtils::Tokenize(entries, entryVec, "|"); if(bSort && type == "labelenum") std::sort(valuesVec.begin(), valuesVec.end(), sortstringbyname()); for (unsigned int i = 0; i < valuesVec.size(); i++) { int iAdd = i; if (entryVec.size() > i) iAdd = atoi(entryVec[i].c_str()); if (!lvalues.empty()) { std::string replace = g_localizeStrings.GetAddonString(m_addon->ID(),atoi(valuesVec[i].c_str())); if (replace.empty()) replace = g_localizeStrings.Get(atoi(valuesVec[i].c_str())); ((CGUISpinControlEx *)pControl)->AddLabel(replace, iAdd); } else ((CGUISpinControlEx *)pControl)->AddLabel(valuesVec[i], iAdd); } if (type == "labelenum") { // need to run through all our settings and find the one that matches ((CGUISpinControlEx*) pControl)->SetValueFromLabel(m_settings[id]); } else ((CGUISpinControlEx*) pControl)->SetValue(atoi(m_settings[id].c_str())); } else if (type == "fileenum" && !id.empty()) { pControl = new CGUISpinControlEx(*pOriginalSpin); if (!pControl) return; ((CGUISpinControlEx *)pControl)->SetText(label); ((CGUISpinControlEx *)pControl)->SetFloatValue(1.0f); std::vector<std::string> items = GetFileEnumValues(values, XMLUtils::GetAttribute(setting, "mask"), XMLUtils::GetAttribute(setting, "option")); for (unsigned int i = 0; i < items.size(); ++i) { ((CGUISpinControlEx *)pControl)->AddLabel(items[i], i); if (StringUtils::EqualsNoCase(items[i], m_settings[id])) ((CGUISpinControlEx *)pControl)->SetValue(i); } } // Sample: <setting id="mysettingname" type="rangeofnum" label="30000" rangestart="0" rangeend="100" elements="11" valueformat="30001" default="0" /> // in strings.xml: <string id="30001">%2.0f mp</string> // creates 11 piece, text formated number labels from 0 to 100 else if (type == "rangeofnum" && !id.empty()) { pControl = new CGUISpinControlEx(*pOriginalSpin); if (!pControl) return; ((CGUISpinControlEx *)pControl)->SetText(label); ((CGUISpinControlEx *)pControl)->SetFloatValue(1.0f); double rangestart = 0, rangeend = 1; setting->Attribute("rangestart", &rangestart); setting->Attribute("rangeend", &rangeend); int elements = 2; setting->Attribute("elements", &elements); std::string valueformat; if (setting->Attribute("valueformat")) valueformat = g_localizeStrings.GetAddonString(m_addon->ID(), atoi(setting->Attribute("valueformat"))); for (int i = 0; i < elements; i++) { std::string valuestring; if (elements < 2) valuestring = StringUtils::Format(valueformat.c_str(), rangestart); else valuestring = StringUtils::Format(valueformat.c_str(), rangestart+(rangeend-rangestart)/(elements-1)*i); ((CGUISpinControlEx *)pControl)->AddLabel(valuestring, i); } ((CGUISpinControlEx *)pControl)->SetValue(atoi(m_settings[id].c_str())); } // Sample: <setting id="mysettingname" type="slider" label="30000" range="5,5,60" option="int" default="5"/> // to make ints from 5-60 with 5 steps else if (type == "slider" && !id.empty()) { pControl = new CGUISettingsSliderControl(*pOriginalSlider); if (!pControl) return; ((CGUISettingsSliderControl *)pControl)->SetText(label); float fMin = 0.0f; float fMax = 100.0f; float fInc = 1.0f; std::vector<std::string> range = StringUtils::Split(XMLUtils::GetAttribute(setting, "range"), ','); if (range.size() > 1) { fMin = (float)atof(range[0].c_str()); if (range.size() > 2) { fMax = (float)atof(range[2].c_str()); fInc = (float)atof(range[1].c_str()); } else fMax = (float)atof(range[1].c_str()); } std::string option = XMLUtils::GetAttribute(setting, "option"); int iType=0; if (option.empty() || StringUtils::EqualsNoCase(option, "float")) iType = SLIDER_CONTROL_TYPE_FLOAT; else if (StringUtils::EqualsNoCase(option, "int")) iType = SLIDER_CONTROL_TYPE_INT; else if (StringUtils::EqualsNoCase(option, "percent")) iType = SLIDER_CONTROL_TYPE_PERCENTAGE; ((CGUISettingsSliderControl *)pControl)->SetType(iType); ((CGUISettingsSliderControl *)pControl)->SetFloatRange(fMin, fMax); ((CGUISettingsSliderControl *)pControl)->SetFloatInterval(fInc); ((CGUISettingsSliderControl *)pControl)->SetFloatValue((float)atof(m_settings[id].c_str())); } else if (type == "lsep") { pControl = new CGUILabelControl(*pOriginalLabel); if (pControl) ((CGUILabelControl *)pControl)->SetLabel(label); } else if (type == "sep") pControl = new CGUIImage(*pOriginalImage); } if (pControl) { pControl->SetWidth(group->GetWidth()); pControl->SetVisible(true); pControl->SetID(controlId); pControl->AllocResources(); group->AddControl(pControl); pControl = NULL; } setting = setting->NextSiblingElement("setting"); controlId++; } EnableControls(); } std::string CGUIDialogAddonSettings::GetAddonNames(const std::string& addonIDslist) const { std::string retVal; std::vector<std::string> addons = StringUtils::Split(addonIDslist, ','); for (std::vector<std::string>::const_iterator it = addons.begin(); it != addons.end() ; ++it) { if (!retVal.empty()) retVal += ", "; AddonPtr addon; if (CAddonMgr::GetInstance().GetAddon(*it ,addon)) retVal += addon->Name(); else retVal += *it; } return retVal; } std::vector<std::string> CGUIDialogAddonSettings::GetFileEnumValues(const std::string &path, const std::string &mask, const std::string &options) const { // Create our base path, used for type "fileenum" settings // replace $PROFILE with the profile path of the plugin/script std::string fullPath = path; if (fullPath.find("$PROFILE") != std::string::npos) StringUtils::Replace(fullPath, "$PROFILE", m_addon->Profile()); else fullPath = URIUtils::AddFileToFolder(m_addon->Path(), path); bool hideExtensions = StringUtils::EqualsNoCase(options, "hideext"); // fetch directory CFileItemList items; if (!mask.empty()) CDirectory::GetDirectory(fullPath, items, mask, XFILE::DIR_FLAG_NO_FILE_DIRS); else CDirectory::GetDirectory(fullPath, items, "", XFILE::DIR_FLAG_NO_FILE_DIRS); std::vector<std::string> values; for (int i = 0; i < items.Size(); ++i) { CFileItemPtr pItem = items[i]; if ((mask == "/" && pItem->m_bIsFolder) || !pItem->m_bIsFolder) { if (hideExtensions) pItem->RemoveExtension(); values.push_back(pItem->GetLabel()); } } return values; } // Go over all the settings and set their enabled condition according to the values of the enabled attribute void CGUIDialogAddonSettings::EnableControls() { int controlId = CONTROL_START_SETTING; const TiXmlElement *setting = GetFirstSetting(); while (setting) { const CGUIControl* control = GetControl(controlId); if (control) { // set enable status const char *enable = setting->Attribute("enable"); if (enable) ((CGUIControl*) control)->SetEnabled(GetCondition(enable, controlId)); else ((CGUIControl*) control)->SetEnabled(true); // set visible status const char *visible = setting->Attribute("visible"); if (visible) ((CGUIControl*) control)->SetVisible(GetCondition(visible, controlId)); else ((CGUIControl*) control)->SetVisible(true); } setting = setting->NextSiblingElement("setting"); controlId++; } } bool CGUIDialogAddonSettings::GetCondition(const std::string &condition, const int controlId) { if (condition.empty()) return true; bool bCondition = true; bool bCompare = true; bool bControlDependend = false;//flag if the condition depends on another control std::vector<std::string> conditionVec; if (condition.find("+") != std::string::npos) StringUtils::Tokenize(condition, conditionVec, "+"); else { bCondition = false; bCompare = false; StringUtils::Tokenize(condition, conditionVec, "|"); } for (unsigned int i = 0; i < conditionVec.size(); i++) { std::vector<std::string> condVec; if (!TranslateSingleString(conditionVec[i], condVec)) continue; const CGUIControl* control2 = GetControl(controlId + atoi(condVec[1].c_str())); if (!control2) continue; bControlDependend = true; //once we are here - this condition depends on another control std::string value; switch (control2->GetControlType()) { case CGUIControl::GUICONTROL_BUTTON: value = ((CGUIButtonControl*) control2)->GetLabel2(); break; case CGUIControl::GUICONTROL_RADIO: value = ((CGUIRadioButtonControl*) control2)->IsSelected() ? "true" : "false"; break; case CGUIControl::GUICONTROL_SPINEX: if (((CGUISpinControlEx*) control2)->GetFloatValue() > 0.0f) value = ((CGUISpinControlEx*) control2)->GetLabel(); else value = StringUtils::Format("%i", ((CGUISpinControlEx*) control2)->GetValue()); break; default: break; } if (condVec[0] == "eq") { if (bCompare) bCondition &= StringUtils::EqualsNoCase(value, condVec[2]); else bCondition |= StringUtils::EqualsNoCase(value, condVec[2]); } else if (condVec[0] == "!eq") { if (bCompare) bCondition &= !StringUtils::EqualsNoCase(value, condVec[2]); else bCondition |= !StringUtils::EqualsNoCase(value, condVec[2]); } else if (condVec[0] == "gt") { if (bCompare) bCondition &= (atoi(value.c_str()) > atoi(condVec[2].c_str())); else bCondition |= (atoi(value.c_str()) > atoi(condVec[2].c_str())); } else if (condVec[0] == "lt") { if (bCompare) bCondition &= (atoi(value.c_str()) < atoi(condVec[2].c_str())); else bCondition |= (atoi(value.c_str()) < atoi(condVec[2].c_str())); } } if (!bControlDependend)//if condition doesn't depend on another control - try if its an infobool expression { bCondition = g_infoManager.EvaluateBool(condition); } return bCondition; } bool CGUIDialogAddonSettings::TranslateSingleString(const std::string &strCondition, std::vector<std::string> &condVec) { std::string strTest = strCondition; StringUtils::ToLower(strTest); StringUtils::Trim(strTest); size_t pos1 = strTest.find("("); size_t pos2 = strTest.find(",", pos1); size_t pos3 = strTest.find(")", pos2); if (pos1 != std::string::npos && pos2 != std::string::npos && pos3 != std::string::npos) { condVec.push_back(strTest.substr(0, pos1)); condVec.push_back(strTest.substr(pos1 + 1, pos2 - pos1 - 1)); condVec.push_back(strTest.substr(pos2 + 1, pos3 - pos2 - 1)); return true; } return false; } std::string CGUIDialogAddonSettings::GetString(const char *value, bool subSetting) const { if (!value) return ""; std::string prefix(subSetting ? "- " : ""); if (StringUtils::IsNaturalNumber(value)) return prefix + g_localizeStrings.GetAddonString(m_addon->ID(), atoi(value)); return prefix + value; } // Go over all the settings and set their default values void CGUIDialogAddonSettings::SetDefaultSettings() { if(!m_addon) return; const TiXmlElement *category = m_addon->GetSettingsXML()->FirstChildElement("category"); if (!category) // add a default one... category = m_addon->GetSettingsXML(); while (category) { const TiXmlElement *setting = category->FirstChildElement("setting"); while (setting) { const std::string id = XMLUtils::GetAttribute(setting, "id"); const std::string type = XMLUtils::GetAttribute(setting, "type"); const char *value = setting->Attribute("default"); if (!id.empty()) { if (value) m_settings[id] = value; else if (type == "bool") m_settings[id] = "false"; else if (type == "slider" || type == "enum") m_settings[id] = "0"; else m_settings[id] = ""; } setting = setting->NextSiblingElement("setting"); } category = category->NextSiblingElement("category"); } CreateControls(); } const TiXmlElement *CGUIDialogAddonSettings::GetFirstSetting() const { const TiXmlElement *category = m_addon->GetSettingsXML()->FirstChildElement("category"); if (!category) category = m_addon->GetSettingsXML(); for (unsigned int i = 0; i < m_currentSection && category; i++) category = category->NextSiblingElement("category"); if (category) return category->FirstChildElement("setting"); return NULL; } void CGUIDialogAddonSettings::DoProcess(unsigned int currentTime, CDirtyRegionList &dirtyregions) { // update status of current section button bool alphaFaded = false; CGUIControl *control = GetFirstFocusableControl(CONTROL_START_SECTION + m_currentSection); if (control && !control->HasFocus()) { if (control->GetControlType() == CGUIControl::GUICONTROL_BUTTON) { control->SetFocus(true); ((CGUIButtonControl *)control)->SetAlpha(0x80); alphaFaded = true; } else if (control->GetControlType() == CGUIControl::GUICONTROL_TOGGLEBUTTON) { control->SetFocus(true); ((CGUIButtonControl *)control)->SetSelected(true); alphaFaded = true; } } CGUIDialogBoxBase::DoProcess(currentTime, dirtyregions); if (alphaFaded && m_active) // dialog may close { control->SetFocus(false); if (control->GetControlType() == CGUIControl::GUICONTROL_BUTTON) ((CGUIButtonControl *)control)->SetAlpha(0xFF); else ((CGUIButtonControl *)control)->SetSelected(false); } } std::string CGUIDialogAddonSettings::GetCurrentID() const { if (m_addon) return m_addon->ID(); return ""; } int CGUIDialogAddonSettings::GetDefaultLabelID(int controlId) const { if (controlId == ID_BUTTON_OK) return 186; else if (controlId == ID_BUTTON_CANCEL) return 222; else if (controlId == ID_BUTTON_DEFAULT) return 409; return CGUIDialogBoxBase::GetDefaultLabelID(controlId); }
gpl-2.0
moio/spacewalk
java/code/src/com/redhat/rhn/frontend/action/schedule/ActionSystemsSetupAction.java
3602
/** * Copyright (c) 2009--2014 Red Hat, Inc. * * This software is licensed to you under the GNU General Public License, * version 2 (GPLv2). There is NO WARRANTY for this software, express or * implied, including the implied warranties of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2 * along with this software; if not, see * http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt. * * Red Hat trademarks are not licensed under GPLv2. No permission is * granted to use or replicate Red Hat trademarks that are incorporated * in this software or its documentation. */ package com.redhat.rhn.frontend.action.schedule; import com.redhat.rhn.common.db.datasource.DataResult; import com.redhat.rhn.domain.action.Action; import com.redhat.rhn.domain.action.ActionFormatter; import com.redhat.rhn.domain.rhnset.RhnSet; import com.redhat.rhn.domain.user.User; import com.redhat.rhn.frontend.listview.PageControl; import com.redhat.rhn.frontend.struts.RequestContext; import com.redhat.rhn.frontend.struts.RhnHelper; import com.redhat.rhn.frontend.struts.RhnListAction; import com.redhat.rhn.manager.action.ActionManager; import com.redhat.rhn.manager.rhnset.RhnSetDecl; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * ActionSystemsSetupAction - abstract class containing common logic * for a setupaction to display listviews with servers/actions * @version $Rev$ */ public abstract class ActionSystemsSetupAction extends RhnListAction { /** {@inheritDoc} */ public ActionForward execute(ActionMapping mapping, ActionForm formIn, HttpServletRequest request, HttpServletResponse response) { RequestContext requestContext = new RequestContext(request); Long aid = requestContext.getRequiredParam("aid"); User user = requestContext.getCurrentUser(); PageControl pc = new PageControl(); pc.setFilterColumn("earliest"); Action action = ActionManager.lookupAction(user, aid); request.setAttribute("canEdit", String.valueOf(action.getPrerequisite() == null)); clampListBounds(pc, request, user); DataResult dr = getDataResult(user, action, pc); ActionFormatter af = action.getFormatter(); request.setAttribute("actionname", af.getName()); request.setAttribute(RequestContext.PAGE_LIST, dr); request.setAttribute("user", user); request.setAttribute("action", action); RhnSet set = getSetDecl().get(user); request.setAttribute("set", set); request.setAttribute("newset", trackSet(set, request)); return mapping.findForward(RhnHelper.DEFAULT_FORWARD); } /** * Method that returns the correct data result for a * particular scheduled action * @param user The user in question * @param action The action in question * @param pc The page control for the page * @return Returns the DataResult for the page. */ protected abstract DataResult getDataResult(User user, Action action, PageControl pc); /** * The declaration of the set we are working with, must be one of the * constants from {@link RhnSetDecl} * @return the declaration of the set we are working with */ protected abstract RhnSetDecl getSetDecl(); }
gpl-2.0
gsmaxwell/phase_offset_rx
gnuradio-core/src/examples/pfb/channelize.py
6621
#!/usr/bin/env python # # Copyright 2009 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, blks2 import sys, time try: import scipy from scipy import fftpack except ImportError: print "Error: Program requires scipy (see: www.scipy.org)." sys.exit(1) try: import pylab from pylab import mlab except ImportError: print "Error: Program requires matplotlib (see: matplotlib.sourceforge.net)." sys.exit(1) class pfb_top_block(gr.top_block): def __init__(self): gr.top_block.__init__(self) self._N = 2000000 # number of samples to use self._fs = 9000 # initial sampling rate self._M = 9 # Number of channels to channelize # Create a set of taps for the PFB channelizer self._taps = gr.firdes.low_pass_2(1, self._fs, 475.50, 50, attenuation_dB=100, window=gr.firdes.WIN_BLACKMAN_hARRIS) # Calculate the number of taps per channel for our own information tpc = scipy.ceil(float(len(self._taps)) / float(self._M)) print "Number of taps: ", len(self._taps) print "Number of channels: ", self._M print "Taps per channel: ", tpc # Create a set of signals at different frequencies # freqs lists the frequencies of the signals that get stored # in the list "signals", which then get summed together self.signals = list() self.add = gr.add_cc() freqs = [-4070, -3050, -2030, -1010, 10, 1020, 2040, 3060, 4080] for i in xrange(len(freqs)): self.signals.append(gr.sig_source_c(self._fs, gr.GR_SIN_WAVE, freqs[i], 1)) self.connect(self.signals[i], (self.add,i)) self.head = gr.head(gr.sizeof_gr_complex, self._N) # Construct the channelizer filter self.pfb = blks2.pfb_channelizer_ccf(self._M, self._taps, 1) # Construct a vector sink for the input signal to the channelizer self.snk_i = gr.vector_sink_c() # Connect the blocks self.connect(self.add, self.head, self.pfb) self.connect(self.add, self.snk_i) # Use this to play with the channel mapping #self.pfb.set_channel_map([5,6,7,8,0,1,2,3,4]) # Create a vector sink for each of M output channels of the filter and connect it self.snks = list() for i in xrange(self._M): self.snks.append(gr.vector_sink_c()) self.connect((self.pfb, i), self.snks[i]) def main(): tstart = time.time() tb = pfb_top_block() tb.run() tend = time.time() print "Run time: %f" % (tend - tstart) if 1: fig_in = pylab.figure(1, figsize=(16,9), facecolor="w") fig1 = pylab.figure(2, figsize=(16,9), facecolor="w") fig2 = pylab.figure(3, figsize=(16,9), facecolor="w") Ns = 1000 Ne = 10000 fftlen = 8192 winfunc = scipy.blackman fs = tb._fs # Plot the input signal on its own figure d = tb.snk_i.data()[Ns:Ne] spin_f = fig_in.add_subplot(2, 1, 1) X,freq = mlab.psd(d, NFFT=fftlen, noverlap=fftlen/4, Fs=fs, window = lambda d: d*winfunc(fftlen), scale_by_freq=True) X_in = 10.0*scipy.log10(abs(X)) f_in = scipy.arange(-fs/2.0, fs/2.0, fs/float(X_in.size)) pin_f = spin_f.plot(f_in, X_in, "b") spin_f.set_xlim([min(f_in), max(f_in)+1]) spin_f.set_ylim([-200.0, 50.0]) spin_f.set_title("Input Signal", weight="bold") spin_f.set_xlabel("Frequency (Hz)") spin_f.set_ylabel("Power (dBW)") Ts = 1.0/fs Tmax = len(d)*Ts t_in = scipy.arange(0, Tmax, Ts) x_in = scipy.array(d) spin_t = fig_in.add_subplot(2, 1, 2) pin_t = spin_t.plot(t_in, x_in.real, "b") pin_t = spin_t.plot(t_in, x_in.imag, "r") spin_t.set_xlabel("Time (s)") spin_t.set_ylabel("Amplitude") Ncols = int(scipy.floor(scipy.sqrt(tb._M))) Nrows = int(scipy.floor(tb._M / Ncols)) if(tb._M % Ncols != 0): Nrows += 1 # Plot each of the channels outputs. Frequencies on Figure 2 and # time signals on Figure 3 fs_o = tb._fs / tb._M Ts_o = 1.0/fs_o Tmax_o = len(d)*Ts_o for i in xrange(len(tb.snks)): # remove issues with the transients at the beginning # also remove some corruption at the end of the stream # this is a bug, probably due to the corner cases d = tb.snks[i].data()[Ns:Ne] sp1_f = fig1.add_subplot(Nrows, Ncols, 1+i) X,freq = mlab.psd(d, NFFT=fftlen, noverlap=fftlen/4, Fs=fs_o, window = lambda d: d*winfunc(fftlen), scale_by_freq=True) X_o = 10.0*scipy.log10(abs(X)) f_o = scipy.arange(-fs_o/2.0, fs_o/2.0, fs_o/float(X_o.size)) p2_f = sp1_f.plot(f_o, X_o, "b") sp1_f.set_xlim([min(f_o), max(f_o)+1]) sp1_f.set_ylim([-200.0, 50.0]) sp1_f.set_title(("Channel %d" % i), weight="bold") sp1_f.set_xlabel("Frequency (Hz)") sp1_f.set_ylabel("Power (dBW)") x_o = scipy.array(d) t_o = scipy.arange(0, Tmax_o, Ts_o) sp2_o = fig2.add_subplot(Nrows, Ncols, 1+i) p2_o = sp2_o.plot(t_o, x_o.real, "b") p2_o = sp2_o.plot(t_o, x_o.imag, "r") sp2_o.set_xlim([min(t_o), max(t_o)+1]) sp2_o.set_ylim([-2, 2]) sp2_o.set_title(("Channel %d" % i), weight="bold") sp2_o.set_xlabel("Time (s)") sp2_o.set_ylabel("Amplitude") pylab.show() if __name__ == "__main__": try: main() except KeyboardInterrupt: pass
gpl-3.0
AHettinga/Rpg-Game
lib/slick/src/org/newdawn/slick/svg/inkscape/LineProcessor.java
3525
package org.newdawn.slick.svg.inkscape; import java.util.StringTokenizer; import org.newdawn.slick.geom.Line; import org.newdawn.slick.geom.Polygon; import org.newdawn.slick.geom.Transform; import org.newdawn.slick.svg.Diagram; import org.newdawn.slick.svg.Figure; import org.newdawn.slick.svg.Loader; import org.newdawn.slick.svg.NonGeometricData; import org.newdawn.slick.svg.ParsingException; import org.w3c.dom.Element; /** * A processor for the <line> element * * @author kevin */ public class LineProcessor implements ElementProcessor { /** * Process the points in a polygon definition * * @param poly The polygon being built * @param element The XML element being read * @param tokens The tokens representing the path * @return The number of points found * @throws ParsingException Indicates an invalid token in the path */ private static int processPoly(Polygon poly, Element element, StringTokenizer tokens) throws ParsingException { int count = 0; while (tokens.hasMoreTokens()) { String nextToken = tokens.nextToken(); if (nextToken.equals("L")) { continue; } if (nextToken.equals("z")) { break; } if (nextToken.equals("M")) { continue; } if (nextToken.equals("C")) { return 0; } String tokenX = nextToken; String tokenY = tokens.nextToken(); try { float x = Float.parseFloat(tokenX); float y = Float.parseFloat(tokenY); poly.addPoint(x,y); count++; } catch (NumberFormatException e) { throw new ParsingException(element.getAttribute("id"), "Invalid token in points list", e); } } return count; } /** * @see org.newdawn.slick.svg.inkscape.ElementProcessor#process(org.newdawn.slick.svg.Loader, org.w3c.dom.Element, org.newdawn.slick.svg.Diagram, org.newdawn.slick.geom.Transform) */ public void process(Loader loader, Element element, Diagram diagram, Transform t) throws ParsingException { Transform transform = Util.getTransform(element); transform = new Transform(t, transform); float x1; float y1; float x2; float y2; if (element.getNodeName().equals("line")) { x1 = Float.parseFloat(element.getAttribute("x1")); x2 = Float.parseFloat(element.getAttribute("x2")); y1 = Float.parseFloat(element.getAttribute("y1")); y2 = Float.parseFloat(element.getAttribute("y2")); } else { String points = element.getAttribute("d"); StringTokenizer tokens = new StringTokenizer(points, ", "); Polygon poly = new Polygon(); if (processPoly(poly, element, tokens) == 2) { x1 = poly.getPoint(0)[0]; y1 = poly.getPoint(0)[1]; x2 = poly.getPoint(1)[0]; y2 = poly.getPoint(1)[1]; } else { return; } } float[] in = new float[] {x1,y1,x2,y2}; float[] out = new float[4]; transform.transform(in,0,out,0,2); Line line = new Line(out[0],out[1],out[2],out[3]); NonGeometricData data = Util.getNonGeometricData(element); data.addAttribute("x1",""+x1); data.addAttribute("x2",""+x2); data.addAttribute("y1",""+y1); data.addAttribute("y2",""+y2); diagram.addFigure(new Figure(Figure.LINE, line, data, transform)); } /** * @see org.newdawn.slick.svg.inkscape.ElementProcessor#handles(org.w3c.dom.Element) */ public boolean handles(Element element) { if (element.getNodeName().equals("line")) { return true; } if (element.getNodeName().equals("path")) { if (!"arc".equals(element.getAttributeNS(Util.SODIPODI, "type"))) { return true; } } return false; } }
gpl-3.0
vidyacraghav/cplusdratchio
deps/boost_1_55_0/libs/asio/example/cpp03/http/server3/request_parser.cpp
6236
// // request_parser.cpp // ~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2013 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include "request_parser.hpp" #include "request.hpp" namespace http { namespace server3 { request_parser::request_parser() : state_(method_start) { } void request_parser::reset() { state_ = method_start; } boost::tribool request_parser::consume(request& req, char input) { switch (state_) { case method_start: if (!is_char(input) || is_ctl(input) || is_tspecial(input)) { return false; } else { state_ = method; req.method.push_back(input); return boost::indeterminate; } case method: if (input == ' ') { state_ = uri; return boost::indeterminate; } else if (!is_char(input) || is_ctl(input) || is_tspecial(input)) { return false; } else { req.method.push_back(input); return boost::indeterminate; } case uri: if (input == ' ') { state_ = http_version_h; return boost::indeterminate; } else if (is_ctl(input)) { return false; } else { req.uri.push_back(input); return boost::indeterminate; } case http_version_h: if (input == 'H') { state_ = http_version_t_1; return boost::indeterminate; } else { return false; } case http_version_t_1: if (input == 'T') { state_ = http_version_t_2; return boost::indeterminate; } else { return false; } case http_version_t_2: if (input == 'T') { state_ = http_version_p; return boost::indeterminate; } else { return false; } case http_version_p: if (input == 'P') { state_ = http_version_slash; return boost::indeterminate; } else { return false; } case http_version_slash: if (input == '/') { req.http_version_major = 0; req.http_version_minor = 0; state_ = http_version_major_start; return boost::indeterminate; } else { return false; } case http_version_major_start: if (is_digit(input)) { req.http_version_major = req.http_version_major * 10 + input - '0'; state_ = http_version_major; return boost::indeterminate; } else { return false; } case http_version_major: if (input == '.') { state_ = http_version_minor_start; return boost::indeterminate; } else if (is_digit(input)) { req.http_version_major = req.http_version_major * 10 + input - '0'; return boost::indeterminate; } else { return false; } case http_version_minor_start: if (is_digit(input)) { req.http_version_minor = req.http_version_minor * 10 + input - '0'; state_ = http_version_minor; return boost::indeterminate; } else { return false; } case http_version_minor: if (input == '\r') { state_ = expecting_newline_1; return boost::indeterminate; } else if (is_digit(input)) { req.http_version_minor = req.http_version_minor * 10 + input - '0'; return boost::indeterminate; } else { return false; } case expecting_newline_1: if (input == '\n') { state_ = header_line_start; return boost::indeterminate; } else { return false; } case header_line_start: if (input == '\r') { state_ = expecting_newline_3; return boost::indeterminate; } else if (!req.headers.empty() && (input == ' ' || input == '\t')) { state_ = header_lws; return boost::indeterminate; } else if (!is_char(input) || is_ctl(input) || is_tspecial(input)) { return false; } else { req.headers.push_back(header()); req.headers.back().name.push_back(input); state_ = header_name; return boost::indeterminate; } case header_lws: if (input == '\r') { state_ = expecting_newline_2; return boost::indeterminate; } else if (input == ' ' || input == '\t') { return boost::indeterminate; } else if (is_ctl(input)) { return false; } else { state_ = header_value; req.headers.back().value.push_back(input); return boost::indeterminate; } case header_name: if (input == ':') { state_ = space_before_header_value; return boost::indeterminate; } else if (!is_char(input) || is_ctl(input) || is_tspecial(input)) { return false; } else { req.headers.back().name.push_back(input); return boost::indeterminate; } case space_before_header_value: if (input == ' ') { state_ = header_value; return boost::indeterminate; } else { return false; } case header_value: if (input == '\r') { state_ = expecting_newline_2; return boost::indeterminate; } else if (is_ctl(input)) { return false; } else { req.headers.back().value.push_back(input); return boost::indeterminate; } case expecting_newline_2: if (input == '\n') { state_ = header_line_start; return boost::indeterminate; } else { return false; } case expecting_newline_3: return (input == '\n'); default: return false; } } bool request_parser::is_char(int c) { return c >= 0 && c <= 127; } bool request_parser::is_ctl(int c) { return (c >= 0 && c <= 31) || (c == 127); } bool request_parser::is_tspecial(int c) { switch (c) { case '(': case ')': case '<': case '>': case '@': case ',': case ';': case ':': case '\\': case '"': case '/': case '[': case ']': case '?': case '=': case '{': case '}': case ' ': case '\t': return true; default: return false; } } bool request_parser::is_digit(int c) { return c >= '0' && c <= '9'; } } // namespace server3 } // namespace http
gpl-3.0
kaikim/flamingo2
flamingo2-terminal-nodejs/term.js-0.0.4/example/index.js
2328
#!/usr/bin/env node /** * term.js * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License) */ var http = require('http') , express = require('express') , io = require('socket.io') , pty = require('pty.js') , terminal = require('../'); /** * term.js */ process.title = 'term.js'; /** * Dump */ var stream; if (process.argv[2] === '--dump') { stream = require('fs').createWriteStream(__dirname + '/dump.log'); } /** * Open Terminal */ var buff = [] , socket , term; term = pty.fork(process.env.SHELL || 'sh', [], { name: require('fs').existsSync('/usr/share/terminfo/x/xterm-256color') ? 'xterm-256color' : 'xterm', cols: 80, rows: 24, cwd: process.env.HOME }); term.on('data', function(data) { if (stream) stream.write('OUT: ' + data + '\n-\n'); return !socket ? buff.push(data) : socket.emit('data', data); }); console.log('' + 'Created shell with pty master/slave' + ' pair (master: %d, pid: %d)', term.fd, term.pid); /** * App & Server */ var app = express() , server = http.createServer(app); app.use(function(req, res, next) { var setHeader = res.setHeader; res.setHeader = function(name) { switch (name) { case 'Cache-Control': case 'Last-Modified': case 'ETag': return; } return setHeader.apply(res, arguments); }; next(); }); app.use(express.basicAuth(function(user, pass, next) { if (user !== 'foo' || pass !== 'bar') { return next(true); } return next(null, user); })); app.use(express.static(__dirname)); app.use(terminal.middleware()); if (!~process.argv.indexOf('-n')) { server.on('connection', function(socket) { var address = socket.remoteAddress; if (address !== '127.0.0.1' && address !== '::1') { try { socket.destroy(); } catch (e) { ; } console.log('Attempted connection from %s. Refused.', address); } }); } server.listen(8080); /** * Sockets */ io = io.listen(server, { log: false }); io.sockets.on('connection', function(sock) { socket = sock; socket.on('data', function(data) { if (stream) stream.write('IN: ' + data + '\n-\n'); term.write(data); }); socket.on('disconnect', function() { socket = null; }); while (buff.length) { socket.emit('data', buff.shift()); } });
gpl-3.0
deniz1a/OpenRA
OpenRA.Mods.Common/Traits/Voiced.cs
2075
#region Copyright & License Information /* * Copyright 2007-2015 The OpenRA Developers (see AUTHORS) * This file is part of OpenRA, which is free software. It is made * available to you under the terms of the GNU General Public License * as published by the Free Software Foundation. For more information, * see COPYING. */ #endregion using System.Collections.Generic; using System.Linq; using OpenRA.GameRules; using OpenRA.Traits; namespace OpenRA.Mods.Common.Traits { [Desc("This actor has a voice.")] public class VoicedInfo : ITraitInfo { [FieldLoader.Require] [Desc("Which voice set to use.")] [VoiceSetReference] public readonly string VoiceSet = null; [Desc("Multiply volume with this factor.")] public readonly float Volume = 1f; public object Create(ActorInitializer init) { return new Voiced(init.Self, this); } } public class Voiced : IVoiced { public readonly VoicedInfo Info; public Voiced(Actor self, VoicedInfo info) { Info = info; } public string VoiceSet { get { return Info.VoiceSet; } } public bool PlayVoice(Actor self, string phrase, string variant) { if (phrase == null) return false; if (string.IsNullOrEmpty(Info.VoiceSet)) return false; var type = Info.VoiceSet.ToLowerInvariant(); var volume = Info.Volume; return Sound.PlayPredefined(self.World.Map.Rules, null, self, type, phrase, variant, true, WPos.Zero, volume, true); } public bool PlayVoiceLocal(Actor self, string phrase, string variant, float volume) { if (phrase == null) return false; if (string.IsNullOrEmpty(Info.VoiceSet)) return false; var type = Info.VoiceSet.ToLowerInvariant(); return Sound.PlayPredefined(self.World.Map.Rules, null, self, type, phrase, variant, false, self.CenterPosition, volume, true); } public bool HasVoice(Actor self, string voice) { if (string.IsNullOrEmpty(Info.VoiceSet)) return false; var voices = self.World.Map.Rules.Voices[Info.VoiceSet.ToLowerInvariant()]; return voices != null && voices.Voices.ContainsKey(voice); } } }
gpl-3.0
nightauer/quickdic-dictionary.dictionary
jars/icu4j-52_1/main/tests/framework/src/com/ibm/icu/dev/test/AbstractTestLog.java
3718
/** ******************************************************************************* * Copyright (C) 2003-2011, International Business Machines Corporation and * others. All Rights Reserved. ******************************************************************************* */ package com.ibm.icu.dev.test; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import com.ibm.icu.util.VersionInfo; public abstract class AbstractTestLog implements TestLog { /** * Returns true if ICU_Version < major.minor. */ static public boolean isICUVersionBefore(int major, int minor) { return isICUVersionBefore(major, minor, 0); } /** * Returns true if ICU_Version < major.minor.milli. */ static public boolean isICUVersionBefore(int major, int minor, int milli) { return VersionInfo.ICU_VERSION.compareTo(VersionInfo.getInstance(major, minor, milli)) < 0; } /** * Returns true if ICU_Version >= major.minor. */ static public boolean isICUVersionAtLeast(int major, int minor) { return isICUVersionAtLeast(major, minor, 0); } /** * Returns true if ICU_Version >= major.minor.milli. */ static public boolean isICUVersionAtLeast(int major, int minor, int milli) { return !isICUVersionBefore(major, minor, milli); } /** * Add a message. */ public final void log(String message) { msg(message, LOG, true, false); } /** * Add a message and newline. */ public final void logln(String message) { msg(message, LOG, true, true); } /** * Report an error. */ public final void err(String message) { msg(message, ERR, true, false); } /** * Report an error and newline. */ public final void errln(String message) { msg(message, ERR, true, true); } /** * Report a warning (generally missing tests or data). */ public final void warn(String message) { msg(message, WARN, true, false); } /** * Report a warning (generally missing tests or data) and newline. */ public final void warnln(String message) { msg(message, WARN, true, true); } /** * Vector for logging. Callers can force the logging system to * not increment the error or warning level by passing false for incCount. * * @param message the message to output. * @param level the message level, either LOG, WARN, or ERR. * @param incCount if true, increments the warning or error count * @param newln if true, forces a newline after the message */ public abstract void msg(String message, int level, boolean incCount, boolean newln); /** * Not sure if this class is useful. This lets you log without first testing * if logging is enabled. The Delegating log will either silently ignore the * message, if the delegate is null, or forward it to the delegate. */ public static final class DelegatingLog extends AbstractTestLog { private TestLog delegate; public DelegatingLog(TestLog delegate) { this.delegate = delegate; } public void msg(String message, int level, boolean incCount, boolean newln) { if (delegate != null) { delegate.msg(message, level, incCount, newln); } } } public boolean isDateAtLeast(int year, int month, int day){ Date now = new Date(); Calendar c = new GregorianCalendar(year, month, day); Date dt = c.getTime(); if(now.compareTo(dt)>=0){ return true; } return false; } }
apache-2.0
bowdenk7/nodejstools
Nodejs/Product/Nodejs/Debugger/DebugEngine/AD7PendingBreakpoint.cs
11231
//*********************************************************// // Copyright (c) Microsoft. All rights reserved. // // Apache 2.0 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. // //*********************************************************// using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Debugger.Interop; using Microsoft.VisualStudioTools; namespace Microsoft.NodejsTools.Debugger.DebugEngine { // This class represents a pending breakpoint which is an abstract representation of a breakpoint before it is bound. // When a user creates a new breakpoint, the pending breakpoint is created and is later bound. The bound breakpoints // become children of the pending breakpoint. class AD7PendingBreakpoint : IDebugPendingBreakpoint2 { // The breakpoint request that resulted in this pending breakpoint being created. private readonly BreakpointManager _bpManager; private readonly IDebugBreakpointRequest2 _bpRequest; private readonly List<AD7BreakpointErrorEvent> _breakpointErrors = new List<AD7BreakpointErrorEvent>(); private readonly AD7Engine _engine; private BP_REQUEST_INFO _bpRequestInfo; private NodeBreakpoint _breakpoint; private string _documentName; private bool _enabled, _deleted; public AD7PendingBreakpoint(IDebugBreakpointRequest2 pBpRequest, AD7Engine engine, BreakpointManager bpManager) { _bpRequest = pBpRequest; var requestInfo = new BP_REQUEST_INFO[1]; EngineUtils.CheckOk(_bpRequest.GetRequestInfo(enum_BPREQI_FIELDS.BPREQI_BPLOCATION | enum_BPREQI_FIELDS.BPREQI_CONDITION | enum_BPREQI_FIELDS.BPREQI_ALLFIELDS, requestInfo)); _bpRequestInfo = requestInfo[0]; _engine = engine; _bpManager = bpManager; _enabled = true; _deleted = false; } public BP_PASSCOUNT PassCount { get { return _bpRequestInfo.bpPassCount; } } public string DocumentName { get { if (_documentName == null) { var docPosition = (IDebugDocumentPosition2)(Marshal.GetObjectForIUnknown(_bpRequestInfo.bpLocation.unionmember2)); EngineUtils.CheckOk(docPosition.GetFileName(out _documentName)); } return _documentName; } } #region IDebugPendingBreakpoint2 Members // Binds this pending breakpoint to one or more code locations. int IDebugPendingBreakpoint2.Bind() { if (CanBind()) { // Get the location in the document that the breakpoint is in. var startPosition = new TEXT_POSITION[1]; var endPosition = new TEXT_POSITION[1]; string fileName; var docPosition = (IDebugDocumentPosition2)(Marshal.GetObjectForIUnknown(_bpRequestInfo.bpLocation.unionmember2)); EngineUtils.CheckOk(docPosition.GetRange(startPosition, endPosition)); EngineUtils.CheckOk(docPosition.GetFileName(out fileName)); _breakpoint = _engine.Process.AddBreakpoint( fileName, (int)startPosition[0].dwLine, (int)startPosition[0].dwColumn, _enabled, AD7BoundBreakpoint.GetBreakOnForPassCount(_bpRequestInfo.bpPassCount), _bpRequestInfo.bpCondition.bstrCondition); _bpManager.AddPendingBreakpoint(_breakpoint, this); _breakpoint.BindAsync().WaitAsync(TimeSpan.FromSeconds(2)).Wait(); return VSConstants.S_OK; } // The breakpoint could not be bound. This may occur for many reasons such as an invalid location, an invalid expression, etc... // The sample engine does not support this, but a real world engine will want to send an instance of IDebugBreakpointErrorEvent2 to the // UI and return a valid instance of IDebugErrorBreakpoint2 from IDebugPendingBreakpoint2::EnumErrorBreakpoints. The debugger will then // display information about why the breakpoint did not bind to the user. return VSConstants.S_FALSE; } // Determines whether this pending breakpoint can bind to a code location. int IDebugPendingBreakpoint2.CanBind(out IEnumDebugErrorBreakpoints2 ppErrorEnum) { ppErrorEnum = null; if (!CanBind()) { // Called to determine if a pending breakpoint can be bound. // The breakpoint may not be bound for many reasons such as an invalid location, an invalid expression, etc... // The sample engine does not support this, but a real world engine will want to return a valid enumeration of IDebugErrorBreakpoint2. // The debugger will then display information about why the breakpoint did not bind to the user. return VSConstants.S_FALSE; } return VSConstants.S_OK; } // Deletes this pending breakpoint and all breakpoints bound from it. int IDebugPendingBreakpoint2.Delete() { ClearBreakpointBindingResults(); _deleted = true; return VSConstants.S_OK; } // Toggles the enabled state of this pending breakpoint. int IDebugPendingBreakpoint2.Enable(int fEnable) { _enabled = fEnable != 0; if (_breakpoint != null) { lock (_breakpoint) { foreach (NodeBreakpointBinding binding in _breakpoint.GetBindings()) { var boundBreakpoint = (IDebugBoundBreakpoint2)_bpManager.GetBoundBreakpoint(binding); boundBreakpoint.Enable(fEnable); } } } return VSConstants.S_OK; } // Enumerates all breakpoints bound from this pending breakpoint int IDebugPendingBreakpoint2.EnumBoundBreakpoints(out IEnumDebugBoundBreakpoints2 ppEnum) { ppEnum = null; if (_breakpoint != null) { lock (_breakpoint) { IDebugBoundBreakpoint2[] boundBreakpoints = _breakpoint.GetBindings() .Select(binding => _bpManager.GetBoundBreakpoint(binding)) .Cast<IDebugBoundBreakpoint2>().ToArray(); ppEnum = new AD7BoundBreakpointsEnum(boundBreakpoints); } } return VSConstants.S_OK; } // Enumerates all error breakpoints that resulted from this pending breakpoint. int IDebugPendingBreakpoint2.EnumErrorBreakpoints(enum_BP_ERROR_TYPE bpErrorType, out IEnumDebugErrorBreakpoints2 ppEnum) { // Called when a pending breakpoint could not be bound. This may occur for many reasons such as an invalid location, an invalid expression, etc... // Return a valid enumeration of IDebugErrorBreakpoint2 from IDebugPendingBreakpoint2::EnumErrorBreakpoints, allowing the debugger to // display information about why the breakpoint did not bind to the user. lock (_breakpointErrors) { IDebugErrorBreakpoint2[] breakpointErrors = _breakpointErrors.Cast<IDebugErrorBreakpoint2>().ToArray(); ppEnum = new AD7ErrorBreakpointsEnum(breakpointErrors); } return VSConstants.S_OK; } // Gets the breakpoint request that was used to create this pending breakpoint int IDebugPendingBreakpoint2.GetBreakpointRequest(out IDebugBreakpointRequest2 ppBpRequest) { ppBpRequest = _bpRequest; return VSConstants.S_OK; } // Gets the state of this pending breakpoint. int IDebugPendingBreakpoint2.GetState(PENDING_BP_STATE_INFO[] pState) { if (_deleted) { pState[0].state = (enum_PENDING_BP_STATE)enum_BP_STATE.BPS_DELETED; } else if (_enabled) { pState[0].state = (enum_PENDING_BP_STATE)enum_BP_STATE.BPS_ENABLED; } else { pState[0].state = (enum_PENDING_BP_STATE)enum_BP_STATE.BPS_DISABLED; } return VSConstants.S_OK; } int IDebugPendingBreakpoint2.SetCondition(BP_CONDITION bpCondition) { if (bpCondition.styleCondition == enum_BP_COND_STYLE.BP_COND_WHEN_CHANGED) { return VSConstants.E_NOTIMPL; } _bpRequestInfo.bpCondition = bpCondition; return VSConstants.S_OK; } int IDebugPendingBreakpoint2.SetPassCount(BP_PASSCOUNT bpPassCount) { _bpRequestInfo.bpPassCount = bpPassCount; return VSConstants.S_OK; } // Toggles the virtualized state of this pending breakpoint. When a pending breakpoint is virtualized, // the debug engine will attempt to bind it every time new code loads into the program. // The sample engine will does not support this. int IDebugPendingBreakpoint2.Virtualize(int fVirtualize) { return VSConstants.S_OK; } #endregion private bool CanBind() { // Reject binding breakpoints which are deleted, not code file line, and on condition changed if (_deleted || _bpRequestInfo.bpLocation.bpLocationType != (uint)enum_BP_LOCATION_TYPE.BPLT_CODE_FILE_LINE || _bpRequestInfo.bpCondition.styleCondition == enum_BP_COND_STYLE.BP_COND_WHEN_CHANGED) { return false; } return true; } public void AddBreakpointError(AD7BreakpointErrorEvent breakpointError) { _breakpointErrors.Add(breakpointError); } // Remove all of the bound breakpoints for this pending breakpoint public void ClearBreakpointBindingResults() { if (_breakpoint != null) { lock (_breakpoint) { foreach (NodeBreakpointBinding binding in _breakpoint.GetBindings()) { var boundBreakpoint = (IDebugBoundBreakpoint2)_bpManager.GetBoundBreakpoint(binding); if (boundBreakpoint != null) { boundBreakpoint.Delete(); binding.Remove().WaitAndUnwrapExceptions(); } } } _bpManager.RemovePendingBreakpoint(_breakpoint); _breakpoint.Deleted = true; _breakpoint = null; } _breakpointErrors.Clear(); } } }
apache-2.0
trekawek/sling
testing/mocks/sling-mock/src/test/java/org/apache/sling/testing/mock/sling/context/models/OsgiServiceModel.java
1241
/* * 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 org.apache.sling.testing.mock.sling.context.models; import javax.inject.Inject; import org.apache.sling.api.resource.ResourceResolver; import org.apache.sling.commons.mime.MimeTypeService; import org.apache.sling.models.annotations.Model; /** * For testing Sling Models support. */ @Model(adaptables = ResourceResolver.class) public interface OsgiServiceModel { @Inject MimeTypeService getMimeTypeService(); }
apache-2.0
nvoron23/titan
titan-core/src/main/java/com/thinkaurelius/titan/util/datastructures/IntHashSet.java
1799
package com.thinkaurelius.titan.util.datastructures; import com.carrotsearch.hppc.IntIntOpenHashMap; import com.carrotsearch.hppc.cursors.IntCursor; import java.util.Iterator; /** * Implementation of {@link IntSet} against {@link IntIntOpenHashMap}. * * @author Matthias Broecheler (me@matthiasb.com) */ public class IntHashSet extends IntIntOpenHashMap implements IntSet { private static final long serialVersionUID = -7297353805905443841L; private static final int defaultValue = 1; public IntHashSet() { super(); } public IntHashSet(int size) { super(size); } public boolean add(int value) { return super.put(value, defaultValue)==0; } public boolean addAll(int[] values) { boolean addedAll = true; for (int i = 0; i < values.length; i++) { if (!add(values[i])) addedAll = false; } return addedAll; } public boolean contains(int value) { return super.containsKey(value); } public int[] getAll() { KeysContainer keys = keys(); int[] all = new int[keys.size()]; Iterator<IntCursor> iter = keys.iterator(); int pos=0; while (iter.hasNext()) all[pos++]=iter.next().value; return all; } @Override public int size() { return super.size(); } @Override public int hashCode() { return ArraysUtil.sum(getAll()); } @Override public boolean equals(Object other) { if (this == other) return true; else if (!(other instanceof IntSet)) return false; IntSet oth = (IntSet) other; for (int i = 0; i < values.length; i++) { if (!oth.contains(values[i])) return false; } return size() == oth.size(); } }
apache-2.0
edombowsky/util
util-hashing/src/main/scala/com/twitter/hashing/Distributor.scala
364
package com.twitter.hashing trait Distributor[A] { def entryForHash(hash: Long): (Long, A) def nodeForHash(hash: Long): A def nodeCount: Int def nodes: Seq[A] } class SingletonDistributor[A](node: A) extends Distributor[A] { def entryForHash(hash: Long) = (hash, node) def nodeForHash(hash: Long) = node def nodeCount = 1 def nodes = Seq(node) }
apache-2.0
nwjs/blink
Source/platform/TaskSynchronizer.cpp
2644
/* * Copyright (C) 2007, 2008, 2013 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * 3. Neither the name of Apple Computer, Inc. ("Apple") 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 APPLE AND ITS 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 APPLE OR ITS 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. */ #include "config.h" #include "platform/TaskSynchronizer.h" #include "heap/ThreadState.h" namespace blink { TaskSynchronizer::TaskSynchronizer() : m_taskCompleted(false) { } void TaskSynchronizer::waitForTaskCompletion() { if (ThreadState::current()) { // Prevent the deadlock between park request by other threads and blocking // by m_synchronousCondition. ThreadState::SafePointScope scope(ThreadState::HeapPointersOnStack); waitForTaskCompletionInternal(); } else { // If this thread is already detached, we no longer need to enter a safe point scope. waitForTaskCompletionInternal(); } } void TaskSynchronizer::waitForTaskCompletionInternal() { m_synchronousMutex.lock(); while (!m_taskCompleted) m_synchronousCondition.wait(m_synchronousMutex); m_synchronousMutex.unlock(); } void TaskSynchronizer::taskCompleted() { m_synchronousMutex.lock(); m_taskCompleted = true; m_synchronousCondition.signal(); m_synchronousMutex.unlock(); } } // namespace blink
bsd-3-clause
MTDdk/FrameworkBenchmarks
frameworks/PHP/sw-fw-less/config/coroutine.php
138
<?php return [ 'enable_preemptive_scheduler' => envInt('COROUTINE_PREEMPTIVE_SCHEDULER', 0), 'hook_flags' => SWOOLE_HOOK_ALL, ];
bsd-3-clause
giantbits/conTainr
protected/modules/containr/extensions/bootstrap/widgets/TbJsonPickerColumn.php
2768
<?php /** * TbJsonPickerColumn class * * The TbJsonPickerColumn works with TbJsonGridView and allows you to create a column that will display a picker element * The picker is a special plugin that renders a dropdown on click, which contents can be dynamically updated. * * @author: antonio ramirez <antonio@clevertech.biz> * @copyright Copyright &copy; Clevertech 2012- * @license http://www.opensource.org/licenses/bsd-license.php New BSD License * @package YiiBooster bootstrap.widgets */ class TbJsonPickerColumn extends TbJsonDataColumn { /** * @var string $class the class name to use to display picker */ public $class = 'picker'; /** * @var array $pickerOptions the javascript options for the picker bootstrap plugin. The picker bootstrap plugin * extends from the tooltip plugin. * * Note that picker has also a 'width' just in case we display AJAX'ed content. * * @see http://twitter.github.com/bootstrap/javascript.html#tooltips */ public $pickerOptions = array(); /** * Initialization function */ public function init() { if (!$this->class) { $this->class = 'picker'; } $this->registerClientScript(); } /** * Renders a data cell content, wrapping the value with the link that will activate the picker * * @param int $row * @param mixed $data * * @return string|void */ public function renderDataCellContent($row, $data) { if ($this->value !== null) { $value = $this->evaluateExpression($this->value, array('data' => $data, 'row' => $row)); } else if ($this->name !== null) { $value = CHtml::value($data, $this->name); } $class = preg_replace('/\s+/', '.', $this->class); $value = !isset($value) ? $this->grid->nullDisplay : $this->grid->getFormatter()->format($value, $this->type); $value = CHtml::link($value, '#', array('class' => $class)); if ($this->grid->json) { return $value; } echo $value; } /** * Registers client script data */ public function registerClientScript() { $class = preg_replace('/\s+/', '.', $this->class); /** @var $cs CClientScript */ $cs = Yii::app()->getClientScript(); $assetsUrl = Yii::app()->bootstrap->getAssetsUrl(); $cs->registerCssFile($assetsUrl . '/css/bootstrap-picker.css'); $cs->registerScriptFile($assetsUrl . '/js/bootstrap.picker.js'); $cs->registerScript( __CLASS__ . '#' . $this->id, "$(document).on('click','#{$this->grid->id} a.{$class}', function(){ if ($(this).hasClass('pickeron')) { $(this).removeClass('pickeron').picker('toggle'); return; } $('#{$this->grid->id} a.pickeron').removeClass('pickeron').picker('toggle'); $(this).picker(" . CJavaScript::encode($this->pickerOptions) . ").picker('toggle').addClass('pickeron'); return false; })" ); } }
bsd-3-clause
ericpp/hippyvm
test_phpt/lang/operators/bitwiseOr_variationStr.phpt
12105
--TEST-- Test | operator : various numbers as strings --FILE-- <?php $strVals = array( "0","65","-44", "1.2", "-7.7", "abc", "123abc", "123e5", "123e5xyz", " 123abc", "123 abc", "123abc ", "3.4a", "a5.9" ); error_reporting(E_ERROR); foreach ($strVals as $strVal) { foreach($strVals as $otherVal) { echo "--- testing: '$strVal' | '$otherVal' ---\n"; var_dump(bin2hex($strVal|$otherVal)); } } ?> ===DONE=== --EXPECT-- --- testing: '0' | '0' --- string(2) "30" --- testing: '0' | '65' --- string(4) "3635" --- testing: '0' | '-44' --- string(6) "3d3434" --- testing: '0' | '1.2' --- string(6) "312e32" --- testing: '0' | '-7.7' --- string(8) "3d372e37" --- testing: '0' | 'abc' --- string(6) "716263" --- testing: '0' | '123abc' --- string(12) "313233616263" --- testing: '0' | '123e5' --- string(10) "3132336535" --- testing: '0' | '123e5xyz' --- string(16) "313233653578797a" --- testing: '0' | ' 123abc' --- string(14) "30313233616263" --- testing: '0' | '123 abc' --- string(14) "31323320616263" --- testing: '0' | '123abc ' --- string(14) "31323361626320" --- testing: '0' | '3.4a' --- string(8) "332e3461" --- testing: '0' | 'a5.9' --- string(8) "71352e39" --- testing: '65' | '0' --- string(4) "3635" --- testing: '65' | '65' --- string(4) "3635" --- testing: '65' | '-44' --- string(6) "3f3534" --- testing: '65' | '1.2' --- string(6) "373f32" --- testing: '65' | '-7.7' --- string(8) "3f372e37" --- testing: '65' | 'abc' --- string(6) "777763" --- testing: '65' | '123abc' --- string(12) "373733616263" --- testing: '65' | '123e5' --- string(10) "3737336535" --- testing: '65' | '123e5xyz' --- string(16) "373733653578797a" --- testing: '65' | ' 123abc' --- string(14) "36353233616263" --- testing: '65' | '123 abc' --- string(14) "37373320616263" --- testing: '65' | '123abc ' --- string(14) "37373361626320" --- testing: '65' | '3.4a' --- string(8) "373f3461" --- testing: '65' | 'a5.9' --- string(8) "77352e39" --- testing: '-44' | '0' --- string(6) "3d3434" --- testing: '-44' | '65' --- string(6) "3f3534" --- testing: '-44' | '-44' --- string(6) "2d3434" --- testing: '-44' | '1.2' --- string(6) "3d3e36" --- testing: '-44' | '-7.7' --- string(8) "2d373e37" --- testing: '-44' | 'abc' --- string(6) "6d7677" --- testing: '-44' | '123abc' --- string(12) "3d3637616263" --- testing: '-44' | '123e5' --- string(10) "3d36376535" --- testing: '-44' | '123e5xyz' --- string(16) "3d3637653578797a" --- testing: '-44' | ' 123abc' --- string(14) "2d353633616263" --- testing: '-44' | '123 abc' --- string(14) "3d363720616263" --- testing: '-44' | '123abc ' --- string(14) "3d363761626320" --- testing: '-44' | '3.4a' --- string(8) "3f3e3461" --- testing: '-44' | 'a5.9' --- string(8) "6d353e39" --- testing: '1.2' | '0' --- string(6) "312e32" --- testing: '1.2' | '65' --- string(6) "373f32" --- testing: '1.2' | '-44' --- string(6) "3d3e36" --- testing: '1.2' | '1.2' --- string(6) "312e32" --- testing: '1.2' | '-7.7' --- string(8) "3d3f3e37" --- testing: '1.2' | 'abc' --- string(6) "716e73" --- testing: '1.2' | '123abc' --- string(12) "313e33616263" --- testing: '1.2' | '123e5' --- string(10) "313e336535" --- testing: '1.2' | '123e5xyz' --- string(16) "313e33653578797a" --- testing: '1.2' | ' 123abc' --- string(14) "313f3233616263" --- testing: '1.2' | '123 abc' --- string(14) "313e3320616263" --- testing: '1.2' | '123abc ' --- string(14) "313e3361626320" --- testing: '1.2' | '3.4a' --- string(8) "332e3661" --- testing: '1.2' | 'a5.9' --- string(8) "713f3e39" --- testing: '-7.7' | '0' --- string(8) "3d372e37" --- testing: '-7.7' | '65' --- string(8) "3f372e37" --- testing: '-7.7' | '-44' --- string(8) "2d373e37" --- testing: '-7.7' | '1.2' --- string(8) "3d3f3e37" --- testing: '-7.7' | '-7.7' --- string(8) "2d372e37" --- testing: '-7.7' | 'abc' --- string(8) "6d776f37" --- testing: '-7.7' | '123abc' --- string(12) "3d373f776263" --- testing: '-7.7' | '123e5' --- string(10) "3d373f7735" --- testing: '-7.7' | '123e5xyz' --- string(16) "3d373f773578797a" --- testing: '-7.7' | ' 123abc' --- string(14) "2d373e37616263" --- testing: '-7.7' | '123 abc' --- string(14) "3d373f37616263" --- testing: '-7.7' | '123abc ' --- string(14) "3d373f77626320" --- testing: '-7.7' | '3.4a' --- string(8) "3f3f3e77" --- testing: '-7.7' | 'a5.9' --- string(8) "6d372e3f" --- testing: 'abc' | '0' --- string(6) "716263" --- testing: 'abc' | '65' --- string(6) "777763" --- testing: 'abc' | '-44' --- string(6) "6d7677" --- testing: 'abc' | '1.2' --- string(6) "716e73" --- testing: 'abc' | '-7.7' --- string(8) "6d776f37" --- testing: 'abc' | 'abc' --- string(6) "616263" --- testing: 'abc' | '123abc' --- string(12) "717273616263" --- testing: 'abc' | '123e5' --- string(10) "7172736535" --- testing: 'abc' | '123e5xyz' --- string(16) "717273653578797a" --- testing: 'abc' | ' 123abc' --- string(14) "61737333616263" --- testing: 'abc' | '123 abc' --- string(14) "71727320616263" --- testing: 'abc' | '123abc ' --- string(14) "71727361626320" --- testing: 'abc' | '3.4a' --- string(8) "736e7761" --- testing: 'abc' | 'a5.9' --- string(8) "61776f39" --- testing: '123abc' | '0' --- string(12) "313233616263" --- testing: '123abc' | '65' --- string(12) "373733616263" --- testing: '123abc' | '-44' --- string(12) "3d3637616263" --- testing: '123abc' | '1.2' --- string(12) "313e33616263" --- testing: '123abc' | '-7.7' --- string(12) "3d373f776263" --- testing: '123abc' | 'abc' --- string(12) "717273616263" --- testing: '123abc' | '123abc' --- string(12) "313233616263" --- testing: '123abc' | '123e5' --- string(12) "313233657763" --- testing: '123abc' | '123e5xyz' --- string(16) "31323365777b797a" --- testing: '123abc' | ' 123abc' --- string(14) "31333373636363" --- testing: '123abc' | '123 abc' --- string(14) "31323361636363" --- testing: '123abc' | '123abc ' --- string(14) "31323361626320" --- testing: '123abc' | '3.4a' --- string(12) "333e37616263" --- testing: '123abc' | 'a5.9' --- string(12) "71373f796263" --- testing: '123e5' | '0' --- string(10) "3132336535" --- testing: '123e5' | '65' --- string(10) "3737336535" --- testing: '123e5' | '-44' --- string(10) "3d36376535" --- testing: '123e5' | '1.2' --- string(10) "313e336535" --- testing: '123e5' | '-7.7' --- string(10) "3d373f7735" --- testing: '123e5' | 'abc' --- string(10) "7172736535" --- testing: '123e5' | '123abc' --- string(12) "313233657763" --- testing: '123e5' | '123e5' --- string(10) "3132336535" --- testing: '123e5' | '123e5xyz' --- string(16) "313233653578797a" --- testing: '123e5' | ' 123abc' --- string(14) "31333377756263" --- testing: '123e5' | '123 abc' --- string(14) "31323365756263" --- testing: '123e5' | '123abc ' --- string(14) "31323365776320" --- testing: '123e5' | '3.4a' --- string(10) "333e376535" --- testing: '123e5' | 'a5.9' --- string(10) "71373f7d35" --- testing: '123e5xyz' | '0' --- string(16) "313233653578797a" --- testing: '123e5xyz' | '65' --- string(16) "373733653578797a" --- testing: '123e5xyz' | '-44' --- string(16) "3d3637653578797a" --- testing: '123e5xyz' | '1.2' --- string(16) "313e33653578797a" --- testing: '123e5xyz' | '-7.7' --- string(16) "3d373f773578797a" --- testing: '123e5xyz' | 'abc' --- string(16) "717273653578797a" --- testing: '123e5xyz' | '123abc' --- string(16) "31323365777b797a" --- testing: '123e5xyz' | '123e5' --- string(16) "313233653578797a" --- testing: '123e5xyz' | '123e5xyz' --- string(16) "313233653578797a" --- testing: '123e5xyz' | ' 123abc' --- string(16) "31333377757a7b7a" --- testing: '123e5xyz' | '123 abc' --- string(16) "31323365757a7b7a" --- testing: '123e5xyz' | '123abc ' --- string(16) "31323365777b797a" --- testing: '123e5xyz' | '3.4a' --- string(16) "333e37653578797a" --- testing: '123e5xyz' | 'a5.9' --- string(16) "71373f7d3578797a" --- testing: ' 123abc' | '0' --- string(14) "30313233616263" --- testing: ' 123abc' | '65' --- string(14) "36353233616263" --- testing: ' 123abc' | '-44' --- string(14) "2d353633616263" --- testing: ' 123abc' | '1.2' --- string(14) "313f3233616263" --- testing: ' 123abc' | '-7.7' --- string(14) "2d373e37616263" --- testing: ' 123abc' | 'abc' --- string(14) "61737333616263" --- testing: ' 123abc' | '123abc' --- string(14) "31333373636363" --- testing: ' 123abc' | '123e5' --- string(14) "31333377756263" --- testing: ' 123abc' | '123e5xyz' --- string(16) "31333377757a7b7a" --- testing: ' 123abc' | ' 123abc' --- string(14) "20313233616263" --- testing: ' 123abc' | '123 abc' --- string(14) "31333333616263" --- testing: ' 123abc' | '123abc ' --- string(14) "31333373636363" --- testing: ' 123abc' | '3.4a' --- string(14) "333f3673616263" --- testing: ' 123abc' | 'a5.9' --- string(14) "61353e3b616263" --- testing: '123 abc' | '0' --- string(14) "31323320616263" --- testing: '123 abc' | '65' --- string(14) "37373320616263" --- testing: '123 abc' | '-44' --- string(14) "3d363720616263" --- testing: '123 abc' | '1.2' --- string(14) "313e3320616263" --- testing: '123 abc' | '-7.7' --- string(14) "3d373f37616263" --- testing: '123 abc' | 'abc' --- string(14) "71727320616263" --- testing: '123 abc' | '123abc' --- string(14) "31323361636363" --- testing: '123 abc' | '123e5' --- string(14) "31323365756263" --- testing: '123 abc' | '123e5xyz' --- string(16) "31323365757a7b7a" --- testing: '123 abc' | ' 123abc' --- string(14) "31333333616263" --- testing: '123 abc' | '123 abc' --- string(14) "31323320616263" --- testing: '123 abc' | '123abc ' --- string(14) "31323361636363" --- testing: '123 abc' | '3.4a' --- string(14) "333e3761616263" --- testing: '123 abc' | 'a5.9' --- string(14) "71373f39616263" --- testing: '123abc ' | '0' --- string(14) "31323361626320" --- testing: '123abc ' | '65' --- string(14) "37373361626320" --- testing: '123abc ' | '-44' --- string(14) "3d363761626320" --- testing: '123abc ' | '1.2' --- string(14) "313e3361626320" --- testing: '123abc ' | '-7.7' --- string(14) "3d373f77626320" --- testing: '123abc ' | 'abc' --- string(14) "71727361626320" --- testing: '123abc ' | '123abc' --- string(14) "31323361626320" --- testing: '123abc ' | '123e5' --- string(14) "31323365776320" --- testing: '123abc ' | '123e5xyz' --- string(16) "31323365777b797a" --- testing: '123abc ' | ' 123abc' --- string(14) "31333373636363" --- testing: '123abc ' | '123 abc' --- string(14) "31323361636363" --- testing: '123abc ' | '123abc ' --- string(14) "31323361626320" --- testing: '123abc ' | '3.4a' --- string(14) "333e3761626320" --- testing: '123abc ' | 'a5.9' --- string(14) "71373f79626320" --- testing: '3.4a' | '0' --- string(8) "332e3461" --- testing: '3.4a' | '65' --- string(8) "373f3461" --- testing: '3.4a' | '-44' --- string(8) "3f3e3461" --- testing: '3.4a' | '1.2' --- string(8) "332e3661" --- testing: '3.4a' | '-7.7' --- string(8) "3f3f3e77" --- testing: '3.4a' | 'abc' --- string(8) "736e7761" --- testing: '3.4a' | '123abc' --- string(12) "333e37616263" --- testing: '3.4a' | '123e5' --- string(10) "333e376535" --- testing: '3.4a' | '123e5xyz' --- string(16) "333e37653578797a" --- testing: '3.4a' | ' 123abc' --- string(14) "333f3673616263" --- testing: '3.4a' | '123 abc' --- string(14) "333e3761616263" --- testing: '3.4a' | '123abc ' --- string(14) "333e3761626320" --- testing: '3.4a' | '3.4a' --- string(8) "332e3461" --- testing: '3.4a' | 'a5.9' --- string(8) "733f3e79" --- testing: 'a5.9' | '0' --- string(8) "71352e39" --- testing: 'a5.9' | '65' --- string(8) "77352e39" --- testing: 'a5.9' | '-44' --- string(8) "6d353e39" --- testing: 'a5.9' | '1.2' --- string(8) "713f3e39" --- testing: 'a5.9' | '-7.7' --- string(8) "6d372e3f" --- testing: 'a5.9' | 'abc' --- string(8) "61776f39" --- testing: 'a5.9' | '123abc' --- string(12) "71373f796263" --- testing: 'a5.9' | '123e5' --- string(10) "71373f7d35" --- testing: 'a5.9' | '123e5xyz' --- string(16) "71373f7d3578797a" --- testing: 'a5.9' | ' 123abc' --- string(14) "61353e3b616263" --- testing: 'a5.9' | '123 abc' --- string(14) "71373f39616263" --- testing: 'a5.9' | '123abc ' --- string(14) "71373f79626320" --- testing: 'a5.9' | '3.4a' --- string(8) "733f3e79" --- testing: 'a5.9' | 'a5.9' --- string(8) "61352e39" ===DONE===
mit
markogresak/DefinitelyTyped
types/carbon__icons-react/next/TouchInteraction.d.ts
49
export { TouchInteraction as default } from "./";
mit
carlosefr/vagrant
test/unit/plugins/guests/coreos/cap/change_host_name_test.rb
1048
require_relative "../../../../base" describe "VagrantPlugins::GuestCoreOS::Cap::ChangeHostName" do let(:described_class) do VagrantPlugins::GuestCoreOS::Plugin .components .guest_capabilities[:coreos] .get(:change_host_name) end let(:machine) { double("machine") } let(:comm) { VagrantTests::DummyCommunicator::Communicator.new(machine) } before do allow(machine).to receive(:communicate).and_return(comm) end after do comm.verify_expectations! end describe ".change_host_name" do let(:name) { "banana-rama.example.com" } it "sets the hostname" do comm.stub_command("hostname -f | grep '^#{name}$'", exit_code: 1) comm.expect_command("hostname 'banana-rama'") described_class.change_host_name(machine, name) end it "does not change the hostname if already set" do comm.stub_command("hostname -f | grep '^#{name}$'", exit_code: 0) described_class.change_host_name(machine, name) expect(comm.received_commands.size).to eq(1) end end end
mit
labdogg1003/monotouch-samples
TransitionsDemo/TransitionsDemo/ViewController.cs
2340
// This file has been autogenerated from a class added in the UI designer. using System; using Foundation; using UIKit; using TransitionsDemo.AnimationControllers; using TransitionsDemo.InteractionControllers; namespace TransitionsDemo { public partial class ViewController : UIViewController, IUIViewControllerTransitioningDelegate { private static nuint colorIndex = 0; private NSArray colors; [Export ("initWithCoder:")] public ViewController (NSCoder coder) : base(coder) { WeakTransitioningDelegate = this; } public override void ViewDidLoad () { colors = NSArray.FromNSObjects (UIColor.Red, UIColor.Orange, UIColor.Yellow, UIColor.Green, UIColor.Blue, UIColor.Purple); View.BackgroundColor = colors.GetItem<UIColor> (colorIndex); colorIndex = (colorIndex + 1) % colors.Count; } public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender) { if (segue.Identifier == "ShowSettings") { UIViewController toViewController = segue.DestinationViewController; toViewController.WeakTransitioningDelegate = this; } base.PrepareForSegue (segue, sender); } [Export ("animationControllerForPresentedController:presentingController:sourceController:")] public IUIViewControllerAnimatedTransitioning PresentingController (UIViewController presented, UIViewController presenting, UIViewController source) { if (AppDelegate.SettingsInteractionController != null) { AppDelegate.SettingsInteractionController.WireToViewController (presented, CEInteractionOperation.Dismiss); } if (AppDelegate.SettingsAnimationController != null) AppDelegate.SettingsAnimationController.Reverse = false; return AppDelegate.SettingsAnimationController; } [Export ("animationControllerForDismissedController:")] public IUIViewControllerAnimatedTransitioning GetAnimationControllerForDismissedController (UIViewController dismissed) { if (AppDelegate.SettingsAnimationController != null) AppDelegate.SettingsAnimationController.Reverse = true; return AppDelegate.SettingsAnimationController; } } }
mit
markogresak/DefinitelyTyped
types/jslib-html5-camera-photo/jslib-html5-camera-photo-tests.ts
2821
import CameraPhoto, { FACING_MODES, IMAGE_TYPES, CaptureConfigOption } from 'jslib-html5-camera-photo'; const videoElement = document.createElement('video'); // pass the video element to the constructor. const cameraPhoto = new CameraPhoto(videoElement); // default camera and resolution cameraPhoto .startCamera() .then(stream => { /* ... */ }) .catch(error => { /* ... */ }); // environment (camera point to environment) cameraPhoto .startCamera(FACING_MODES.ENVIRONMENT, {}) .then(stream => { /* ... */ }) .catch(error => { /* ... */ }); // OR user (camera point to the user) cameraPhoto .startCamera(FACING_MODES.USER, {}) .then(stream => { /* ... */ }) .catch(error => { /* ... */ }); // example of ideal resolution 640 x 480 cameraPhoto .startCamera(FACING_MODES.ENVIRONMENT, { width: 640, height: 480 }) .then(stream => { /* ... */ }) .catch(error => { /* ... */ }); // example of resultion with non-numeric width and height cameraPhoto .startCamera(FACING_MODES.ENVIRONMENT, { width: { ideal: 3840 }, height: { ideal: 2160 } }) .then(stream => { /* ... */ }) .catch(error => { /* ... */ }); // It will try the best to get the maximum resolution with the specified facingMode cameraPhoto .startCameraMaxResolution(FACING_MODES.ENVIRONMENT) .then(stream => { /* ... */ }) .catch(error => { /* ... */ }); // Use all the default value const config1: CaptureConfigOption = {}; // $ExpectType string const dataUri1 = cameraPhoto.getDataUri(config1); const config2: CaptureConfigOption = { sizeFactor: 1, imageType: IMAGE_TYPES.JPG, imageCompression: 0.95, isImageMirror: false, }; // $ExpectType string const dataUri2 = cameraPhoto.getDataUri(config2); const cameraSettings = cameraPhoto.getCameraSettings(); if (cameraSettings) { const { aspectRatio, frameRate, height, width } = cameraSettings; const settingsStr = `aspectRatio:${aspectRatio} ` + `frameRate: ${frameRate} ` + `height: ${height} ` + `width: ${width}`; console.log(settingsStr); } // $ExpectType MediaDeviceInfo[] const inputVideoDeviceInfos = cameraPhoto.getInputVideoDeviceInfos(); inputVideoDeviceInfos.forEach(inputVideoDeviceInfo => { const { kind, label, deviceId } = inputVideoDeviceInfo; const inputVideoDeviceInfoStr = ` kind: ${kind} label: ${label} deviceId: ${deviceId} `; console.log(inputVideoDeviceInfoStr); }); // Stop the camera cameraPhoto .stopCamera() .then(() => { /* ... */ }) .catch(error => { /* ... */ }); if (cameraPhoto.mediaDevices) { cameraPhoto.mediaDevices.getUserMedia(); }
mit
brigand/react
fixtures/fiber-debugger/src/describeFibers.js
2574
let nextFiberID = 1; const fiberIDMap = new WeakMap(); function getFiberUniqueID(fiber) { if (!fiberIDMap.has(fiber)) { fiberIDMap.set(fiber, nextFiberID++); } return fiberIDMap.get(fiber); } function getFriendlyTag(tag) { switch (tag) { case 0: return '[indeterminate]'; case 1: return '[fn]'; case 2: return '[class]'; case 3: return '[root]'; case 4: return '[portal]'; case 5: return '[host]'; case 6: return '[text]'; case 7: return '[coroutine]'; case 8: return '[handler]'; case 9: return '[yield]'; case 10: return '[frag]'; default: throw new Error('Unknown tag.'); } } function getFriendlyEffect(effectTag) { const effects = { 1: 'Performed Work', 2: 'Placement', 4: 'Update', 8: 'Deletion', 16: 'Content reset', 32: 'Callback', 64: 'Err', 128: 'Ref', }; return Object.keys(effects) .filter(flag => flag & effectTag) .map(flag => effects[flag]) .join(' & '); } export default function describeFibers(rootFiber, workInProgress) { let descriptions = {}; function acknowledgeFiber(fiber) { if (!fiber) { return null; } if (!fiber.return && fiber.tag !== 3) { return null; } const id = getFiberUniqueID(fiber); if (descriptions[id]) { return id; } descriptions[id] = {}; Object.assign(descriptions[id], { ...fiber, id: id, tag: getFriendlyTag(fiber.tag), effectTag: getFriendlyEffect(fiber.effectTag), type: fiber.type && '<' + (fiber.type.name || fiber.type) + '>', stateNode: `[${typeof fiber.stateNode}]`, return: acknowledgeFiber(fiber.return), child: acknowledgeFiber(fiber.child), sibling: acknowledgeFiber(fiber.sibling), nextEffect: acknowledgeFiber(fiber.nextEffect), firstEffect: acknowledgeFiber(fiber.firstEffect), lastEffect: acknowledgeFiber(fiber.lastEffect), alternate: acknowledgeFiber(fiber.alternate), }); return id; } const rootID = acknowledgeFiber(rootFiber); const workInProgressID = acknowledgeFiber(workInProgress); let currentIDs = new Set(); function markAsCurent(id) { currentIDs.add(id); const fiber = descriptions[id]; if (fiber.sibling) { markAsCurent(fiber.sibling); } if (fiber.child) { markAsCurent(fiber.child); } } markAsCurent(rootID); return { descriptions, rootID, currentIDs: Array.from(currentIDs), workInProgressID, }; }
mit
GeraintEdwards/joomla-cms
administrator/templates/hathor/html/com_contact/contacts/default.php
10750
<?php /** * @package Joomla.Administrator * @subpackage Template.hathor * * @copyright Copyright (C) 2005 - 2017 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ defined('_JEXEC') or die; JHtml::addIncludePath(JPATH_COMPONENT.'/helpers/html'); JHtml::_('behavior.multiselect'); $app = JFactory::getApplication(); $user = JFactory::getUser(); $userId = $user->get('id'); $listOrder = $this->escape($this->state->get('list.ordering')); $listDirn = $this->escape($this->state->get('list.direction')); $canOrder = $user->authorise('core.edit.state', 'com_contact'); $saveOrder = $listOrder == 'a.ordering'; $assoc = JLanguageAssociations::isEnabled(); ?> <form action="<?php echo JRoute::_('index.php?option=com_contact'); ?>" method="post" name="adminForm" id="adminForm"> <?php if (!empty( $this->sidebar)) : ?> <div id="j-sidebar-container" class="span2"> <?php echo $this->sidebar; ?> </div> <div id="j-main-container" class="span10"> <?php else : ?> <div id="j-main-container"> <?php endif;?> <fieldset id="filter-bar"> <legend class="element-invisible"><?php echo JText::_('JSEARCH_FILTER_LABEL'); ?></legend> <div class="filter-search"> <label class="filter-search-lbl" for="filter_search"><?php echo JText::_('JSEARCH_FILTER_LABEL'); ?></label> <input type="text" name="filter_search" id="filter_search" value="<?php echo $this->escape($this->state->get('filter.search')); ?>" title="<?php echo JText::_('COM_CONTACT_SEARCH_IN_NAME'); ?>" /> <button type="submit"><?php echo JText::_('JSEARCH_FILTER_SUBMIT'); ?></button> <button type="button" onclick="document.getElementById('filter_search').value='';this.form.submit();"><?php echo JText::_('JSEARCH_FILTER_CLEAR'); ?></button> </div> <div class="filter-select"> <label class="selectlabel" for="filter_published"> <?php echo JText::_('JOPTION_SELECT_PUBLISHED'); ?> </label> <select name="filter_published" id="filter_published"> <option value=""><?php echo JText::_('JOPTION_SELECT_PUBLISHED');?></option> <?php echo JHtml::_('select.options', JHtml::_('jgrid.publishedOptions'), 'value', 'text', $this->state->get('filter.published'), true);?> </select> <label class="selectlabel" for="filter_category_id"> <?php echo JText::_('JOPTION_SELECT_CATEGORY'); ?> </label> <select name="filter_category_id" id="filter_category_id"> <option value=""><?php echo JText::_('JOPTION_SELECT_CATEGORY');?></option> <?php echo JHtml::_('select.options', JHtml::_('category.options', 'com_contact'), 'value', 'text', $this->state->get('filter.category_id'));?> </select> <label class="selectlabel" for="filter_access"> <?php echo JText::_('JOPTION_SELECT_ACCESS'); ?> </label> <select name="filter_access" id="filter_access"> <option value=""><?php echo JText::_('JOPTION_SELECT_ACCESS');?></option> <?php echo JHtml::_('select.options', JHtml::_('access.assetgroups'), 'value', 'text', $this->state->get('filter.access'));?> </select> <label class="selectlabel" for="filter_language"> <?php echo JText::_('JOPTION_SELECT_LANGUAGE'); ?> </label> <select name="filter_language" id="filter_language"> <option value=""><?php echo JText::_('JOPTION_SELECT_LANGUAGE');?></option> <?php echo JHtml::_('select.options', JHtml::_('contentlanguage.existing', true, true), 'value', 'text', $this->state->get('filter.language'));?> </select> <label class="selectlabel" for="filter_tag"> <?php echo JText::_('JOPTION_SELECT_TAG'); ?> </label> <select name="filter_tag" id="filter_tag"> <option value=""><?php echo JText::_('JOPTION_SELECT_TAG');?></option> <?php echo JHtml::_('select.options', JHtml::_('tag.options', true, true), 'value', 'text', $this->state->get('filter.tag'));?> </select> <button type="submit" id="filter-go"> <?php echo JText::_('JSUBMIT'); ?></button> </div> </fieldset> <div class="clr"> </div> <table class="adminlist"> <thead> <tr> <th class="checkmark-col"> <input type="checkbox" name="checkall-toggle" value="" title="<?php echo JText::_('JGLOBAL_CHECK_ALL'); ?>" onclick="Joomla.checkAll(this)" /> </th> <th class="title"> <?php echo JHtml::_('grid.sort', 'JGLOBAL_TITLE', 'a.name', $listDirn, $listOrder); ?> </th> <th> <?php echo JHtml::_('grid.sort', 'COM_CONTACT_FIELD_LINKED_USER_LABEL', 'ul.name', $listDirn, $listOrder); ?> </th> <th class="nowrap state-col"> <?php echo JHtml::_('grid.sort', 'JSTATUS', 'a.state', $listDirn, $listOrder); ?> </th> <th class="nowrap featured-col"> <?php echo JHtml::_('grid.sort', 'JFEATURED', 'a.featured', $listDirn, $listOrder, null, 'desc'); ?> </th> <th class="title category-col"> <?php echo JHtml::_('grid.sort', 'JCATEGORY', 'category_title', $listDirn, $listOrder); ?> </th> <th class="nowrap ordering-col"> <?php echo JHtml::_('grid.sort', 'JGRID_HEADING_ORDERING', 'a.ordering', $listDirn, $listOrder); ?> <?php if ($canOrder && $saveOrder) : ?> <?php echo JHtml::_('grid.order', $this->items, 'filesave.png', 'contacts.saveorder'); ?> <?php endif; ?> </th> <th class="title access-col"> <?php echo JHtml::_('grid.sort', 'JGRID_HEADING_ACCESS', 'access_level', $listDirn, $listOrder); ?> </th> <?php if ($assoc) : ?> <th width="5%"> <?php echo JHtml::_('grid.sort', 'COM_CONTACT_HEADING_ASSOCIATION', 'association', $listDirn, $listOrder); ?> </th> <?php endif;?> <th class="language-col"> <?php echo JHtml::_('grid.sort', 'JGRID_HEADING_LANGUAGE', 'a.language', $listDirn, $listOrder); ?> </th> <th class="nowrap id-col"> <?php echo JHtml::_('grid.sort', 'JGRID_HEADING_ID', 'a.id', $listDirn, $listOrder); ?> </th> </tr> </thead> <tbody> <?php $n = count($this->items); foreach ($this->items as $i => $item) : $ordering = $listOrder == 'a.ordering'; $canCreate = $user->authorise('core.create', 'com_contact.category.' . $item->catid); $canEdit = $user->authorise('core.edit', 'com_contact.category.' . $item->catid); $canCheckin = $user->authorise('core.manage', 'com_checkin') || $item->checked_out == $userId || $item->checked_out == 0; $canEditOwn = $user->authorise('core.edit.own', 'com_contact.category.' . $item->catid) && $item->created_by == $userId; $canChange = $user->authorise('core.edit.state', 'com_contact.category.' . $item->catid) && $canCheckin; $item->cat_link = JRoute::_('index.php?option=com_categories&extension=com_contact&task=edit&type=other&id='.$item->catid); ?> <tr class="row<?php echo $i % 2; ?>"> <td class="center"> <?php echo JHtml::_('grid.id', $i, $item->id); ?> </td> <td> <?php if ($item->checked_out) : ?> <?php echo JHtml::_('jgrid.checkedout', $i, $item->editor, $item->checked_out_time, 'contacts.', $canCheckin); ?> <?php endif; ?> <?php if ($canEdit || $canEditOwn) : ?> <a href="<?php echo JRoute::_('index.php?option=com_contact&task=contact.edit&id='.(int) $item->id); ?>"> <?php echo $this->escape($item->name); ?></a> <?php else : ?> <?php echo $this->escape($item->name); ?> <?php endif; ?> <p class="smallsub"> <?php echo JText::sprintf('JGLOBAL_LIST_ALIAS', $this->escape($item->alias));?></p> </td> <td align="center"> <?php if (!empty($item->linked_user)) : ?> <a href="<?php echo JRoute::_('index.php?option=com_users&task=user.edit&id='.$item->user_id);?>"><?php echo $item->linked_user;?></a> <?php endif; ?> </td> <td class="center"> <?php echo JHtml::_('jgrid.published', $item->published, $i, 'contacts.', $canChange, 'cb', $item->publish_up, $item->publish_down); ?> </td> <td class="center"> <?php echo JHtml::_('contact.featured', $item->featured, $i, $canChange); ?> </td> <td class="center"> <?php echo $item->category_title; ?> </td> <td class="order"> <?php if ($canChange) : ?> <?php if ($saveOrder) : ?> <?php if ($listDirn == 'asc') : ?> <span><?php echo $this->pagination->orderUpIcon($i, ($item->catid == @$this->items[$i - 1]->catid), 'contacts.orderup', 'JLIB_HTML_MOVE_UP', $ordering); ?></span> <span><?php echo $this->pagination->orderDownIcon($i, $this->pagination->total, ($item->catid == @$this->items[$i + 1]->catid), 'contacts.orderdown', 'JLIB_HTML_MOVE_DOWN', $ordering); ?></span> <?php elseif ($listDirn == 'desc') : ?> <span><?php echo $this->pagination->orderUpIcon($i, ($item->catid == @$this->items[$i - 1]->catid), 'contacts.orderdown', 'JLIB_HTML_MOVE_UP', $ordering); ?></span> <span><?php echo $this->pagination->orderDownIcon($i, $this->pagination->total, ($item->catid == @$this->items[$i + 1]->catid), 'contacts.orderup', 'JLIB_HTML_MOVE_DOWN', $ordering); ?></span> <?php endif; ?> <?php endif; ?> <?php $disabled = $saveOrder ? '' : 'disabled="disabled"'; ?> <input type="text" name="order[]" value="<?php echo $item->ordering; ?>" <?php echo $disabled; ?> class="text-area-order" title="<?php echo $item->name; ?> order" /> <?php else : ?> <?php echo $item->ordering; ?> <?php endif; ?> </td> <td class="center"> <?php echo $item->access_level; ?> </td> <?php if ($assoc) : ?> <td class="center"> <?php if ($item->association) : ?> <?php echo JHtml::_('contact.association', $item->id); ?> <?php endif; ?> </td> <?php endif;?> <td class="center"> <?php echo JLayoutHelper::render('joomla.content.language', $item); ?> </td> <td class="center"> <?php echo $item->id; ?> </td> </tr> <?php endforeach; ?> </tbody> </table> <?php //Load the batch processing form. ?> <?php if ($user->authorise('core.create', 'com_contact') && $user->authorise('core.edit', 'com_contact') && $user->authorise('core.edit.state', 'com_contact')) : ?> <?php echo JHtml::_( 'bootstrap.renderModal', 'collapseModal', array( 'title' => JText::_('COM_CONTACT_BATCH_OPTIONS'), 'footer' => $this->loadTemplate('batch_footer'), ), $this->loadTemplate('batch_body') ); ?> <?php endif; ?> <?php echo $this->pagination->getListFooter(); ?> <input type="hidden" name="task" value="" /> <input type="hidden" name="boxchecked" value="0" /> <input type="hidden" name="filter_order" value="<?php echo $listOrder; ?>" /> <input type="hidden" name="filter_order_Dir" value="<?php echo $listDirn; ?>" /> <?php echo JHtml::_('form.token'); ?> </div> </form>
gpl-2.0
malaporte/kaziranga
src/jdk/internal/dynalink/linker/MethodTypeConversionStrategy.java
4644
/* * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file, and Oracle licenses the original version of this file under the BSD * license: */ /* Copyright 2014 Attila Szegedi Licensed under both the Apache License, Version 2.0 (the "Apache License") and the BSD License (the "BSD License"), with licensee being free to choose either of the two at their discretion. You may not use this file except in compliance with either the Apache License or the BSD License. If you choose to use this file in compliance with the Apache License, the following notice applies to you: You may obtain a copy of the Apache 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. If you choose to use this file in compliance with the BSD License, the following notice applies to you: 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 the copyright holder nor the names of contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 COPYRIGHT HOLDER 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. */ package jdk.internal.dynalink.linker; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodType; /** * Interface for objects representing a strategy for converting a method handle to a new type. */ public interface MethodTypeConversionStrategy { /** * Converts a method handle to a new type. * @param target target method handle * @param newType new type * @return target converted to the new type. */ public MethodHandle asType(final MethodHandle target, final MethodType newType); }
gpl-2.0
bxm156/Teach-Pilot
mod/voicepodcaster/lib/php/common/XmlArchive.php
4364
<?php /* * Created on May 30, 2007 * * To change the template for this generated file go to * Window - Preferences - PHPeclipse - PHP - Code Templates */ class XmlArchive{ var $id; var $nameDisplay; var $preview; var $url; var $param; var $url_params; var $tooltipAvailability; var $tooltipDial; var $parent; var $canDownloadMp3; var $canDownloadMp4; /* * Constructor * @param id : id of the archive * @param nameDisplay : name of the archive * @param preview : avaibility of the room * @param url : path of the file which manage the launch of the archive * @param url_params : parameters needed to be able to call the specific file */ function XmlArchive( $id, $nameDisplay, $preview,$canDownloadMp3, $canDownloadMp4, $url, $url_params) { $this->id = $id; $this->nameDisplay = $nameDisplay; if ($preview == false) { $this->preview = "available"; } else { $this->preview = "unavailable"; } $this->url = $url; $this->url_params = $url_params; $this->canDownloadMp3=$canDownloadMp3; $this->canDownloadMp4=$canDownloadMp4; } /* * Return the xml element of the object */ function getXml($xml){ $element = $xml->create_element('archive'); $product = $xml->create_element("product"); $product->append_child($xml->create_text_node("liveclassroom")); $type = $xml->create_element("type"); $type->append_child($xml->create_text_node("archive")); $id = $xml->create_element("id"); $id->append_child($xml->create_text_node($this->id)); $nameDisplay = $xml->create_element("nameDisplay"); $nameDisplay->append_child($xml->create_text_node($this->nameDisplay)); $tooltipAvailability = $xml->create_element("tooltipAvailability"); $tooltipAvailability->append_child($xml->create_text_node($this->tooltipAvailability)); $tooltipDial = $xml->create_element("tooltipDial"); $tooltipDial->append_child($xml->create_text_node($this->tooltipDial)); $preview = $xml->create_element("preview"); $preview->append_child($xml->create_text_node($this->preview)); $url = $xml->create_element("url"); $url->append_child($xml->create_text_node($this->url)); $parent = $xml->create_element("parent"); $parent->append_child($xml->create_text_node($this->parent)); $canDownloadMp3 = $xml->create_element("canDownloadMp3"); $canDownloadMp3->append_child($xml->create_text_node($this->canDownloadMp3)); $canDownloadMp4 = $xml->create_element("canDownloadMp4"); $canDownloadMp4->append_child($xml->create_text_node($this->canDownloadMp4)); $param = $xml->create_element("param"); $param->append_child($xml->create_text_node($this->param)); $element->append_child($product); $element->append_child($id); $element->append_child($nameDisplay); $element->append_child($preview); $element->append_child($tooltipAvailability); $element->append_child($tooltipDial); $element->append_child($url); $element->append_child($canDownloadMp3); $element->append_child($canDownloadMp4); $element->append_child($param); $element->append_child($type); $element->append_child($parent); return $element; } function getId() { return $this->id; } function getAvailability() { return $this->preview; } function getName() { return $this->nameDisplay; } function setTooltipDial($tooltipDial) { $this->tooltipDial = $tooltipDial; } function setParent($parent) { $this->parent = $parent; } function setTooltipAvailability($tooltipAvailability) { $this->tooltipAvailability = $tooltipAvailability; } function getTooltipDial() { return $this->tooltipDial; } function getTooltipAvailability() { return $this->tooltipAvailability; } function canDownloadMp3() { return $this->canDownloadMp3; } function canDownloadMp4() { return $this->canDownloadMp4; } } ?>
gpl-2.0
justinwm/astor
examples/math_0c1e6fb/src/main/java/org/apache/commons/math3/optim/nonlinear/vector/JacobianMultivariateVectorOptimizer.java
4527
/* * 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 org.apache.commons.math3.optim.nonlinear.vector; import org.apache.commons.math3.analysis.MultivariateMatrixFunction; import org.apache.commons.math3.optim.ConvergenceChecker; import org.apache.commons.math3.optim.OptimizationData; import org.apache.commons.math3.optim.PointVectorValuePair; import org.apache.commons.math3.exception.TooManyEvaluationsException; import org.apache.commons.math3.exception.DimensionMismatchException; /** * Base class for implementing optimizers for multivariate vector * differentiable functions. * It contains boiler-plate code for dealing with Jacobian evaluation. * It assumes that the rows of the Jacobian matrix iterate on the model * functions while the columns iterate on the parameters; thus, the numbers * of rows is equal to the dimension of the {@link Target} while the * number of columns is equal to the dimension of the * {@link org.apache.commons.math3.optim.InitialGuess InitialGuess}. * * @since 3.1 * @deprecated All classes and interfaces in this package are deprecated. * The optimizers that were provided here were moved to the * {@link org.apache.commons.math3.fitting.leastsquares} package * (cf. MATH-1008). */ @Deprecated public abstract class JacobianMultivariateVectorOptimizer extends MultivariateVectorOptimizer { /** * Jacobian of the model function. */ private MultivariateMatrixFunction jacobian; /** * @param checker Convergence checker. */ protected JacobianMultivariateVectorOptimizer(ConvergenceChecker<PointVectorValuePair> checker) { super(checker); } /** * Computes the Jacobian matrix. * * @param params Point at which the Jacobian must be evaluated. * @return the Jacobian at the specified point. */ protected double[][] computeJacobian(final double[] params) { return jacobian.value(params); } /** * {@inheritDoc} * * @param optData Optimization data. In addition to those documented in * {@link MultivariateVectorOptimizer#optimize(OptimizationData...)} * MultivariateOptimizer}, this method will register the following data: * <ul> * <li>{@link ModelFunctionJacobian}</li> * </ul> * @return {@inheritDoc} * @throws TooManyEvaluationsException if the maximal number of * evaluations is exceeded. * @throws DimensionMismatchException if the initial guess, target, and weight * arguments have inconsistent dimensions. */ @Override public PointVectorValuePair optimize(OptimizationData... optData) throws TooManyEvaluationsException, DimensionMismatchException { // Set up base class and perform computation. return super.optimize(optData); } /** * Scans the list of (required and optional) optimization data that * characterize the problem. * * @param optData Optimization data. * The following data will be looked for: * <ul> * <li>{@link ModelFunctionJacobian}</li> * </ul> */ @Override protected void parseOptimizationData(OptimizationData... optData) { // Allow base class to register its own data. super.parseOptimizationData(optData); // The existing values (as set by the previous call) are reused if // not provided in the argument list. for (OptimizationData data : optData) { if (data instanceof ModelFunctionJacobian) { jacobian = ((ModelFunctionJacobian) data).getModelFunctionJacobian(); // If more data must be parsed, this statement _must_ be // changed to "continue". break; } } } }
gpl-2.0
Almish/CekeAlmish
components/com_jce/editor/libraries/js/tree.js
5530
/* JCE Editor - 2.4.6 | 19 January 2015 | http://www.joomlacontenteditor.net | Copyright (C) 2006 - 2014 Ryan Demmer. All rights reserved | GNU/GPL Version 2 or later - http://www.gnu.org/licenses/gpl-2.0.html */ (function($){$.widget("ui.tree",{options:{rootName:'Root',rootClass:'root',loaderClass:'load',collapseTree:false,charLength:false},_init:function(){var self=this;if(!this.element) return;this._trigger('onInit',null,function(){self._nodeEvents();});},_nodeEvents:function(parent){var self=this;if(!parent){parent=this.element;} $('ul:first',parent).attr({'role':'tree'}).children('li').attr('aria-level',1);$('li',parent).attr({'role':'treeitem'}).attr('aria-expanded',function(){return $(this).hasClass('open')?true:false;}).attr('aria-level',function(i,v){if(!v){return parseFloat($(this.parentNode.parentNode).attr('aria-level'))+1;}});$('ul:gt(0)',parent).attr({'role':'group'});$('div.tree-image',parent).attr('role','presentation').each(function(){var p=self._findParent(this);$(this).click(function(e){self.toggleNode(e,p);});});$('span',parent).attr('role','presentation').each(function(){if(!$.support.cssFloat){this.onselectstart=function(){return false;};}}).click(function(e){var p=self._findParent(this);self._trigger('onNodeClick',e,p);});},_hasNodes:function(parent){if($.type(parent)=='string'){parent=this._findParent(parent);} var c=$('li',parent);return c.length>1||(c.length==1&&!$(c).is('.spacer'));},_isNode:function(id,parent){var n=this._findNode(id,parent);return n.length?true:false;},_getNode:function(parent){if($.type(parent)=='string'){parent=this._findParent(parent);} return $(parent).find('ul.tree-node');},_resetNodes:function(){$('span, div.tree-image',this.element).removeClass('open');},renameNode:function(id,name){var parent=$.String.dirname(id);var node=this._findNode(id,parent);$(node).attr('id',name);$('a:first',node).html($.String.basename(name));$('li[id^="'+this._escape(encodeURI(id))+'"]',node).each(function(n){var nt=$(n).attr('id');$(n).attr('id',nt.replace(id,name));});},removeNode:function(id){var parent=$.String.dirname(id);var node=this._findNode(id,parent);var ul=$(node).parent('ul');$(node).remove();if(ul&&!this._hasNodes(ul)){$(ul).remove();}},createNode:function(nodes,parent){var self=this;var e,p,h,l,np,i;if(!nodes.length){return;} if(!parent){parent=$.String.dirname($(nodes[0]).attr('id'));} if($.type(parent)=='string'){parent=this._findParent(parent);} if(nodes&&nodes.length){var ul=$('ul.tree-node:first',parent)||null;if(!ul.length){ul=document.createElement('ul');$(ul).attr({'role':'group'}).addClass('tree-node').append('<li class="spacer" role="treeitem" aria-expanded="false"></li>');$(parent).append(ul);} $.each(nodes,function(i,node){if(!self._isNode(node.id,parent)){if(!node['class']){node['class']='folder';} var title=node.name||node.id;title=$.String.decode(title);name=title;len=self.options.charLength;if(len&&name.length>len){name=name.substring(0,len)+'...';} var img=/folder/.test(node['class'])?'tree-image':'tree-noimage';var url=!node.url?'javascript:;':node.url;var li=document.createElement('li');$(li).attr({'id':self._escape(encodeURI(node.id))}).append('<div class="tree-row">' +'<div role="presentation" class="'+img +'"></div>'+'<span role="presentation" class="' +node['class']+'">' +'<a href="'+url +'" title="'+title+'">' +name+'</a>'+'</span>' +'</div>').attr('aria-level',parseFloat($(parent).attr('aria-level'))+1);$(ul).append(li);$('div.tree-row',li).hover(function(){$(this).addClass('hover');},function(){$(this).removeClass('hover');});$('div.tree-image',li).click(function(e){self.toggleNode(e,li);});$('span',li).click(function(e){self._trigger('onNodeClick',e,li);});self.toggleNodeState(parent,1);self._trigger('onNodeCreate');}else{self.toggleNodeState(parent,1);}});}else{this.toggleNodeState(parent,1);}},_findParent:function(el){if($.type(el)=='string'){return $('li[id="'+this._encode(el)+'"]:first',this.element);}else{return $(el).parents('li:first');}},_findNode:function(id,parent){if(!parent||parent=='/'){parent=this.element;} if($.type(parent)=='string'){parent=this._findParent(parent);} return $('li[id="'+this._escape(this._encode(id))+'"]:first',parent);},toggleLoader:function(node){$('span:first',node).toggleClass(this.options.loaderClass);},_collapseNodes:function(ex){var self=this;if(!ex) this._resetNodes();var parent=$(ex).parent();$('li',parent).each(function(el){if(el!=ex){if($(el).parent()==parent){self.toggleNodeState(el,0);var child=self._getNode(el);if(child){$(child).addClass('hide');}}}});},toggleNodeState:function(node,state){if(state==1){$(node).addClass('open').attr('aria-expanded',true);}else{$(node).removeClass('open').attr('aria-expanded',false);} if(state==1){if(node.id=='/'){return;} var c=$('ul.tree-node',node);if(c.length){if($(node).hasClass('open')){$(c).removeClass('hide');}else{$(c).addClass('hide');}}}},toggleNode:function(e,node){if(e.shiftKey){return this._trigger('onNodeLoad',e,node);} var child=this._getNode(node);if(!child.length){if($('div.tree-image',node).hasClass('open')){this.toggleNodeState(node);}else{this._trigger('onNodeLoad',e,node);}}else{$(child).toggleClass('hide');this.toggleNodeState(node);} if(this.options.collapseTree){this._collapseNodes(node);}},_encode:function(s){s=decodeURIComponent(s);return encodeURIComponent(s).replace(/%2F/gi,'\/');},_escape:function(s){return s.replace(/'/,'%27');},destroy:function(){$.Widget.prototype.destroy.apply(this,arguments);}});$.extend($.ui.tree,{version:"2.4.6"});})(jQuery);
gpl-2.0
kasobus/EDENS-Mautic
vendor/rackspace/php-opencloud/lib/OpenCloud/CloudMonitoring/Exception/CheckException.php
717
<?php /** * Copyright 2012-2014 Rackspace US, 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. */ namespace OpenCloud\CloudMonitoring\Exception; class CheckException extends CloudMonitoringException { }
gpl-3.0