hunk
dict | file
stringlengths 0
11.8M
| file_path
stringlengths 2
234
| label
int64 0
1
| commit_url
stringlengths 74
103
| dependency_score
sequencelengths 5
5
|
---|---|---|---|---|---|
{
"id": 1,
"code_window": [
" status: 'success',\n",
" data: [\n",
" {\n",
" exemplars: [\n",
" {\n",
" timestamp: 1610449070000,\n",
" value: 5,\n",
" },\n",
" {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" timestamp: 1610449070.0,\n"
],
"file_path": "public/app/plugins/datasource/prometheus/result_transformer.test.ts",
"type": "replace",
"edit_start_line_idx": 519
} | package login
import (
"time"
"github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/models"
)
var (
maxInvalidLoginAttempts int64 = 5
loginAttemptsWindow = time.Minute * 5
)
var validateLoginAttempts = func(query *models.LoginUserQuery) error {
if query.Cfg.DisableBruteForceLoginProtection {
return nil
}
loginAttemptCountQuery := models.GetUserLoginAttemptCountQuery{
Username: query.Username,
Since: time.Now().Add(-loginAttemptsWindow),
}
if err := bus.Dispatch(&loginAttemptCountQuery); err != nil {
return err
}
if loginAttemptCountQuery.Result >= maxInvalidLoginAttempts {
return ErrTooManyLoginAttempts
}
return nil
}
var saveInvalidLoginAttempt = func(query *models.LoginUserQuery) error {
if query.Cfg.DisableBruteForceLoginProtection {
return nil
}
loginAttemptCommand := models.CreateLoginAttemptCommand{
Username: query.Username,
IpAddress: query.IpAddress,
}
return bus.Dispatch(&loginAttemptCommand)
}
| pkg/login/brute_force_login_protection.go | 0 | https://github.com/grafana/grafana/commit/8c35ed40147946c36ae318b54cfe29275553ceea | [
0.0002008118317462504,
0.00017930804460775107,
0.0001632436760701239,
0.0001672033395152539,
0.00001655903361097444
] |
{
"id": 1,
"code_window": [
" status: 'success',\n",
" data: [\n",
" {\n",
" exemplars: [\n",
" {\n",
" timestamp: 1610449070000,\n",
" value: 5,\n",
" },\n",
" {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" timestamp: 1610449070.0,\n"
],
"file_path": "public/app/plugins/datasource/prometheus/result_transformer.test.ts",
"type": "replace",
"edit_start_line_idx": 519
} | # GitHub & grafanabot automation
The bot is configured via [commands.json](https://github.com/grafana/grafana/blob/master/.github/commands.json) and some other GitHub workflows [workflows](https://github.com/grafana/grafana/tree/master/.github/workflows).
Comment commands:
* Write the word `/duplicate #<number>` anywhere in a comment and the bot will add the correct label and standard message.
* Write the word `/needsMoreInfo` anywhere in a comment and the bot will add the correct label and standard message.
Label commands:
* Add label `bot/question` the the bot will close with standard question message and add label `type/question`
* Add label `bot/duplicate` the the bot will close with standard duplicate message and add label `type/duplicate`
* Add label `bot/needs more info` for bot to request more info (or use comment command mentioned above)
* Add label `bot/close feature request` for bot to close a feature request with standard message and adds label `not implemented`
* Add label `bot/no new info` for bot to close an issue where we asked for more info but has not received any updates in at least 14 days.
## Metrics
Metrics are configured in [metrics-collector.json](https://github.com/grafana/grafana/blob/master/.github/metrics-collector.json) and are also defined in the
[metrics-collector](https://github.com/grafana/grafana-github-actions/blob/main/metrics-collector/index.ts) GitHub action.
## Backport PR
To automatically backport a PR to a release branch like v7.3.x add a label named `backport v7.3.x`. The label name should follow the pattern `backport <branch-name>`. Once merged grafanabot will automatically
try to cherry-pick the PR merge commit into that branch and open a PR. It will sync the milestone with the source PR so make sure the source PR also is assigned the milestone for the patch release. If the PR is already merged you can still add this label and trigger the backport automation.
If there are merge conflicts the bot will write a comment on the source PR saying the cherry-pick failed. In this case you have to do the cherry pick and backport PR manually.
The backport logic is written [here](https://github.com/grafana/grafana-github-actions/blob/main/backport/backport.ts)
| .github/bot.md | 0 | https://github.com/grafana/grafana/commit/8c35ed40147946c36ae318b54cfe29275553ceea | [
0.0001665930321905762,
0.00016491347923874855,
0.0001620132097741589,
0.0001655238156672567,
0.0000017737280586516135
] |
{
"id": 2,
"code_window": [
" value: 5,\n",
" },\n",
" {\n",
" timestamp: 1610449070000,\n",
" value: 1,\n",
" },\n",
" {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" timestamp: 1610449070.0,\n"
],
"file_path": "public/app/plugins/datasource/prometheus/result_transformer.test.ts",
"type": "replace",
"edit_start_line_idx": 523
} | import { DataFrame, FieldType } from '@grafana/data';
import { transform } from './result_transformer';
jest.mock('@grafana/runtime', () => ({
getTemplateSrv: () => ({
replace: (str: string) => str,
}),
getDataSourceSrv: () => {
return {
getInstanceSettings: () => {
return { name: 'Tempo' };
},
};
},
}));
const matrixResponse = {
status: 'success',
data: {
resultType: 'matrix',
result: [
{
metric: { __name__: 'test', job: 'testjob' },
values: [
[1, '10'],
[2, '0'],
],
},
],
},
};
describe('Prometheus Result Transformer', () => {
const options: any = { target: {}, query: {} };
describe('When nothing is returned', () => {
it('should return empty array', () => {
const response = {
status: 'success',
data: {
resultType: '',
result: null,
},
};
const series = transform({ data: response } as any, options);
expect(series).toEqual([]);
});
it('should return empty array', () => {
const response = {
status: 'success',
data: {
resultType: '',
result: null,
},
};
const result = transform({ data: response } as any, { ...options, target: { format: 'table' } });
expect(result).toHaveLength(0);
});
});
describe('When resultFormat is table', () => {
const response = {
status: 'success',
data: {
resultType: 'matrix',
result: [
{
metric: { __name__: 'test', job: 'testjob' },
values: [
[1443454528, '3846'],
[1443454530, '3848'],
],
},
{
metric: {
__name__: 'test2',
instance: 'localhost:8080',
job: 'otherjob',
},
values: [
[1443454529, '3847'],
[1443454531, '3849'],
],
},
],
},
};
it('should return data frame', () => {
const result = transform({ data: response } as any, {
...options,
target: {
responseListLength: 0,
refId: 'A',
format: 'table',
},
});
expect(result[0].fields[0].values.toArray()).toEqual([
1443454528000,
1443454530000,
1443454529000,
1443454531000,
]);
expect(result[0].fields[0].name).toBe('Time');
expect(result[0].fields[0].type).toBe(FieldType.time);
expect(result[0].fields[1].values.toArray()).toEqual(['test', 'test', 'test2', 'test2']);
expect(result[0].fields[1].name).toBe('__name__');
expect(result[0].fields[1].config.filterable).toBe(true);
expect(result[0].fields[1].type).toBe(FieldType.string);
expect(result[0].fields[2].values.toArray()).toEqual(['', '', 'localhost:8080', 'localhost:8080']);
expect(result[0].fields[2].name).toBe('instance');
expect(result[0].fields[2].type).toBe(FieldType.string);
expect(result[0].fields[3].values.toArray()).toEqual(['testjob', 'testjob', 'otherjob', 'otherjob']);
expect(result[0].fields[3].name).toBe('job');
expect(result[0].fields[3].type).toBe(FieldType.string);
expect(result[0].fields[4].values.toArray()).toEqual([3846, 3848, 3847, 3849]);
expect(result[0].fields[4].name).toEqual('Value');
expect(result[0].fields[4].type).toBe(FieldType.number);
expect(result[0].refId).toBe('A');
});
it('should include refId if response count is more than 2', () => {
const result = transform({ data: response } as any, {
...options,
target: {
refId: 'B',
format: 'table',
},
responseListLength: 2,
});
expect(result[0].fields[4].name).toEqual('Value #B');
});
});
describe('When resultFormat is table and instant = true', () => {
const response = {
status: 'success',
data: {
resultType: 'vector',
result: [
{
metric: { __name__: 'test', job: 'testjob' },
value: [1443454528, '3846'],
},
],
},
};
it('should return data frame', () => {
const result = transform({ data: response } as any, { ...options, target: { format: 'table' } });
expect(result[0].fields[0].values.toArray()).toEqual([1443454528000]);
expect(result[0].fields[0].name).toBe('Time');
expect(result[0].fields[1].values.toArray()).toEqual(['test']);
expect(result[0].fields[1].name).toBe('__name__');
expect(result[0].fields[2].values.toArray()).toEqual(['testjob']);
expect(result[0].fields[2].name).toBe('job');
expect(result[0].fields[3].values.toArray()).toEqual([3846]);
expect(result[0].fields[3].name).toEqual('Value');
});
it('should return le label values parsed as numbers', () => {
const response = {
status: 'success',
data: {
resultType: 'vector',
result: [
{
metric: { le: '102' },
value: [1594908838, '0'],
},
],
},
};
const result = transform({ data: response } as any, { ...options, target: { format: 'table' } });
expect(result[0].fields[1].values.toArray()).toEqual([102]);
expect(result[0].fields[1].type).toEqual(FieldType.number);
});
});
describe('When instant = true', () => {
const response = {
status: 'success',
data: {
resultType: 'vector',
result: [
{
metric: { __name__: 'test', job: 'testjob' },
value: [1443454528, '3846'],
},
],
},
};
it('should return data frame', () => {
const result: DataFrame[] = transform({ data: response } as any, { ...options, query: { instant: true } });
expect(result[0].name).toBe('test{job="testjob"}');
});
});
describe('When resultFormat is heatmap', () => {
const getResponse = (result: any) => ({
status: 'success',
data: {
resultType: 'matrix',
result,
},
});
const options = {
format: 'heatmap',
start: 1445000010,
end: 1445000030,
legendFormat: '{{le}}',
};
it('should convert cumulative histogram to regular', () => {
const response = getResponse([
{
metric: { __name__: 'test', job: 'testjob', le: '1' },
values: [
[1445000010, '10'],
[1445000020, '10'],
[1445000030, '0'],
],
},
{
metric: { __name__: 'test', job: 'testjob', le: '2' },
values: [
[1445000010, '20'],
[1445000020, '10'],
[1445000030, '30'],
],
},
{
metric: { __name__: 'test', job: 'testjob', le: '3' },
values: [
[1445000010, '30'],
[1445000020, '10'],
[1445000030, '40'],
],
},
]);
const result = transform({ data: response } as any, { query: options, target: options } as any);
expect(result[0].fields[0].values.toArray()).toEqual([1445000010000, 1445000020000, 1445000030000]);
expect(result[0].fields[1].values.toArray()).toEqual([10, 10, 0]);
expect(result[1].fields[0].values.toArray()).toEqual([1445000010000, 1445000020000, 1445000030000]);
expect(result[1].fields[1].values.toArray()).toEqual([10, 0, 30]);
expect(result[2].fields[0].values.toArray()).toEqual([1445000010000, 1445000020000, 1445000030000]);
expect(result[2].fields[1].values.toArray()).toEqual([10, 0, 10]);
});
it('should handle missing datapoints', () => {
const response = getResponse([
{
metric: { __name__: 'test', job: 'testjob', le: '1' },
values: [
[1445000010, '1'],
[1445000020, '2'],
],
},
{
metric: { __name__: 'test', job: 'testjob', le: '2' },
values: [
[1445000010, '2'],
[1445000020, '5'],
[1445000030, '1'],
],
},
{
metric: { __name__: 'test', job: 'testjob', le: '3' },
values: [
[1445000010, '3'],
[1445000020, '7'],
],
},
]);
const result = transform({ data: response } as any, { query: options, target: options } as any);
expect(result[0].fields[1].values.toArray()).toEqual([1, 2]);
expect(result[1].fields[1].values.toArray()).toEqual([1, 3, 1]);
expect(result[2].fields[1].values.toArray()).toEqual([1, 2]);
});
});
describe('When the response is a matrix', () => {
it('should have labels with the value field', () => {
const response = {
status: 'success',
data: {
resultType: 'matrix',
result: [
{
metric: { __name__: 'test', job: 'testjob', instance: 'testinstance' },
values: [
[0, '10'],
[1, '10'],
[2, '0'],
],
},
],
},
};
const result: DataFrame[] = transform({ data: response } as any, {
...options,
});
expect(result[0].fields[1].labels).toBeDefined();
expect(result[0].fields[1].labels?.instance).toBe('testinstance');
expect(result[0].fields[1].labels?.job).toBe('testjob');
});
it('should transform into a data frame', () => {
const response = {
status: 'success',
data: {
resultType: 'matrix',
result: [
{
metric: { __name__: 'test', job: 'testjob' },
values: [
[0, '10'],
[1, '10'],
[2, '0'],
],
},
],
},
};
const result: DataFrame[] = transform({ data: response } as any, {
...options,
query: {
start: 0,
end: 2,
},
});
expect(result[0].fields[0].values.toArray()).toEqual([0, 1000, 2000]);
expect(result[0].fields[1].values.toArray()).toEqual([10, 10, 0]);
expect(result[0].name).toBe('test{job="testjob"}');
});
it('should fill null values', () => {
const result = transform({ data: matrixResponse } as any, { ...options, query: { step: 1, start: 0, end: 2 } });
expect(result[0].fields[0].values.toArray()).toEqual([0, 1000, 2000]);
expect(result[0].fields[1].values.toArray()).toEqual([null, 10, 0]);
});
it('should use __name__ label as series name', () => {
const result = transform({ data: matrixResponse } as any, {
...options,
query: {
step: 1,
start: 0,
end: 2,
},
});
expect(result[0].name).toEqual('test{job="testjob"}');
});
it('should use query as series name when __name__ is not available and metric is empty', () => {
const response = {
status: 'success',
data: {
resultType: 'matrix',
result: [
{
metric: {},
values: [[0, '10']],
},
],
},
};
const expr = 'histogram_quantile(0.95, sum(rate(tns_request_duration_seconds_bucket[5m])) by (le))';
const result = transform({ data: response } as any, {
...options,
query: {
step: 1,
start: 0,
end: 2,
expr,
},
});
expect(result[0].name).toEqual(expr);
});
it('should set frame name to undefined if no __name__ label but there are other labels', () => {
const response = {
status: 'success',
data: {
resultType: 'matrix',
result: [
{
metric: { job: 'testjob' },
values: [
[1, '10'],
[2, '0'],
],
},
],
},
};
const result = transform({ data: response } as any, {
...options,
query: {
step: 1,
start: 0,
end: 2,
},
});
expect(result[0].name).toBe('{job="testjob"}');
});
it('should not set displayName for ValueFields', () => {
const result = transform({ data: matrixResponse } as any, options);
expect(result[0].fields[1].config.displayName).toBeUndefined();
expect(result[0].fields[1].config.displayNameFromDS).toBe('test{job="testjob"}');
});
it('should align null values with step', () => {
const response = {
status: 'success',
data: {
resultType: 'matrix',
result: [
{
metric: { __name__: 'test', job: 'testjob' },
values: [
[4, '10'],
[8, '10'],
],
},
],
},
};
const result = transform({ data: response } as any, { ...options, query: { step: 2, start: 0, end: 8 } });
expect(result[0].fields[0].values.toArray()).toEqual([0, 2000, 4000, 6000, 8000]);
expect(result[0].fields[1].values.toArray()).toEqual([null, null, 10, null, 10]);
});
});
describe('When infinity values are returned', () => {
describe('When resultType is scalar', () => {
const response = {
status: 'success',
data: {
resultType: 'scalar',
result: [1443454528, '+Inf'],
},
};
it('should correctly parse values', () => {
const result: DataFrame[] = transform({ data: response } as any, { ...options, target: { format: 'table' } });
expect(result[0].fields[1].values.toArray()).toEqual([Number.POSITIVE_INFINITY]);
});
});
describe('When resultType is vector', () => {
const response = {
status: 'success',
data: {
resultType: 'vector',
result: [
{
metric: { __name__: 'test', job: 'testjob' },
value: [1443454528, '+Inf'],
},
{
metric: { __name__: 'test', job: 'testjob' },
value: [1443454528, '-Inf'],
},
],
},
};
describe('When format is table', () => {
it('should correctly parse values', () => {
const result: DataFrame[] = transform({ data: response } as any, { ...options, target: { format: 'table' } });
expect(result[0].fields[3].values.toArray()).toEqual([Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY]);
});
});
});
});
const exemplarsResponse = {
status: 'success',
data: [
{
seriesLabels: { __name__: 'test' },
exemplars: [
{
timestamp: 1610449069957,
labels: { traceID: '5020b5bc45117f07' },
value: 0.002074123,
},
],
},
],
};
describe('When the response is exemplar data', () => {
it('should return as an data frame with a dataTopic annotations', () => {
const result = transform({ data: exemplarsResponse } as any, options);
expect(result[0].meta?.dataTopic).toBe('annotations');
expect(result[0].fields.length).toBe(4); // __name__, traceID, Time, Value
expect(result[0].length).toBe(1);
});
it('should remove exemplars that are too close to each other', () => {
const response = {
status: 'success',
data: [
{
exemplars: [
{
timestamp: 1610449070000,
value: 5,
},
{
timestamp: 1610449070000,
value: 1,
},
{
timestamp: 1610449070500,
value: 13,
},
{
timestamp: 1610449070300,
value: 20,
},
],
},
],
};
/**
* the standard deviation for the above values is 8.4 this means that we show the highest
* value (20) and then the next value should be 2 times the standard deviation which is 1
**/
const result = transform({ data: response } as any, options);
expect(result[0].length).toBe(2);
});
describe('data link', () => {
it('should be added to the field if found with url', () => {
const result = transform({ data: exemplarsResponse } as any, {
...options,
exemplarTraceIdDestinations: [{ name: 'traceID', url: 'http://localhost' }],
});
expect(result[0].fields.some((f) => f.config.links?.length)).toBe(true);
});
it('should be added to the field if found with internal link', () => {
const result = transform({ data: exemplarsResponse } as any, {
...options,
exemplarTraceIdDestinations: [{ name: 'traceID', datasourceUid: 'jaeger' }],
});
expect(result[0].fields.some((f) => f.config.links?.length)).toBe(true);
});
it('should not add link if exemplarTraceIdDestinations is not configured', () => {
const result = transform({ data: exemplarsResponse } as any, options);
expect(result[0].fields.some((f) => f.config.links?.length)).toBe(false);
});
});
});
});
| public/app/plugins/datasource/prometheus/result_transformer.test.ts | 1 | https://github.com/grafana/grafana/commit/8c35ed40147946c36ae318b54cfe29275553ceea | [
0.989059567451477,
0.017786050215363503,
0.0001644792646402493,
0.00016866353689692914,
0.12869130074977875
] |
{
"id": 2,
"code_window": [
" value: 5,\n",
" },\n",
" {\n",
" timestamp: 1610449070000,\n",
" value: 1,\n",
" },\n",
" {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" timestamp: 1610449070.0,\n"
],
"file_path": "public/app/plugins/datasource/prometheus/result_transformer.test.ts",
"type": "replace",
"edit_start_line_idx": 523
} | // Copyright (c) 2017 Uber Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import { ApiError } from './api-error';
export type TraceArchive = {
isLoading?: boolean;
isArchived?: boolean;
isError?: boolean;
error?: ApiError;
isAcknowledged?: boolean;
};
export type TracesArchive = Record<string, TraceArchive>;
| packages/jaeger-ui-components/src/types/archive.tsx | 0 | https://github.com/grafana/grafana/commit/8c35ed40147946c36ae318b54cfe29275553ceea | [
0.00017272531113121659,
0.00016947240510489792,
0.00016577950736973435,
0.00016991241136565804,
0.0000028526301321107894
] |
{
"id": 2,
"code_window": [
" value: 5,\n",
" },\n",
" {\n",
" timestamp: 1610449070000,\n",
" value: 1,\n",
" },\n",
" {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" timestamp: 1610449070.0,\n"
],
"file_path": "public/app/plugins/datasource/prometheus/result_transformer.test.ts",
"type": "replace",
"edit_start_line_idx": 523
} | {
"annotations": {
"list": [
{
"builtIn": 1,
"datasource": "-- Grafana --",
"enable": true,
"hide": true,
"iconColor": "rgba(0, 211, 255, 1)",
"name": "Annotations & Alerts",
"type": "dashboard"
}
]
},
"editable": true,
"gnetId": null,
"graphTooltip": 0,
"id": 28,
"links": [],
"panels": [
{
"aliasColors": {},
"bars": false,
"dashLength": 10,
"dashes": false,
"datasource": "gdev-testdata",
"editable": true,
"error": false,
"fieldConfig": {
"defaults": {
"custom": {}
},
"overrides": []
},
"fill": 1,
"fillGradient": 0,
"gridPos": {
"h": 7,
"w": 12,
"x": 0,
"y": 0
},
"hiddenSeries": false,
"id": 4,
"legend": {
"avg": false,
"current": false,
"max": false,
"min": false,
"show": true,
"total": false,
"values": false
},
"lines": true,
"linewidth": 2,
"links": [],
"nullPointMode": "connected",
"options": {
"dataLinks": []
},
"percentage": false,
"pointradius": 5,
"points": false,
"renderer": "flot",
"seriesOverrides": [],
"spaceLength": 10,
"stack": false,
"steppedLine": false,
"targets": [
{
"refId": "A",
"scenario": "random_walk",
"scenarioId": "random_walk",
"target": ""
}
],
"thresholds": [],
"timeFrom": "2s",
"timeRegions": [],
"timeShift": null,
"title": "Millisecond res x-axis and tooltip",
"tooltip": {
"msResolution": false,
"shared": true,
"sort": 0,
"value_type": "cumulative"
},
"type": "graph",
"xaxis": {
"buckets": null,
"mode": "time",
"name": null,
"show": true,
"values": []
},
"yaxes": [
{
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
},
{
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
}
],
"yaxis": {
"align": false,
"alignLevel": null
}
},
{
"aliasColors": {},
"bars": false,
"dashLength": 10,
"dashes": false,
"datasource": "gdev-testdata",
"editable": true,
"error": false,
"fieldConfig": {
"defaults": {
"custom": {}
},
"overrides": []
},
"fill": 1,
"fillGradient": 0,
"gridPos": {
"h": 7,
"w": 12,
"x": 12,
"y": 0
},
"hiddenSeries": false,
"id": 3,
"legend": {
"avg": false,
"current": false,
"max": false,
"min": false,
"show": true,
"total": false,
"values": false
},
"lines": true,
"linewidth": 2,
"links": [],
"nullPointMode": "connected",
"options": {
"dataLinks": []
},
"percentage": false,
"pointradius": 5,
"points": false,
"renderer": "flot",
"seriesOverrides": [],
"spaceLength": 10,
"stack": false,
"steppedLine": false,
"targets": [
{
"refId": "A",
"scenario": "random_walk",
"scenarioId": "random_walk",
"target": ""
}
],
"thresholds": [],
"timeFrom": null,
"timeRegions": [],
"timeShift": null,
"title": "Random walk series",
"tooltip": {
"msResolution": false,
"shared": true,
"sort": 0,
"value_type": "cumulative"
},
"type": "graph",
"xaxis": {
"buckets": null,
"mode": "time",
"name": null,
"show": true,
"values": []
},
"yaxes": [
{
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
},
{
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
}
],
"yaxis": {
"align": false,
"alignLevel": null
}
},
{
"aliasColors": {},
"bars": false,
"dashLength": 10,
"dashes": false,
"datasource": "gdev-testdata",
"editable": true,
"error": false,
"fieldConfig": {
"defaults": {
"custom": {}
},
"overrides": []
},
"fill": 1,
"fillGradient": 0,
"gridPos": {
"h": 8,
"w": 12,
"x": 0,
"y": 7
},
"hiddenSeries": false,
"id": 5,
"legend": {
"avg": false,
"current": false,
"max": false,
"min": false,
"show": true,
"total": false,
"values": false
},
"lines": true,
"linewidth": 2,
"links": [],
"nullPointMode": "connected",
"options": {
"dataLinks": []
},
"percentage": false,
"pointradius": 5,
"points": false,
"renderer": "flot",
"seriesOverrides": [
{
"alias": "B-series",
"yaxis": 2
}
],
"spaceLength": 10,
"stack": false,
"steppedLine": false,
"targets": [
{
"refId": "A",
"scenarioId": "csv_metric_values",
"stringInput": "1,20,90,30,5,0",
"target": ""
},
{
"refId": "B",
"scenarioId": "csv_metric_values",
"stringInput": "2000,3000,4000,1000,3000,10000",
"target": ""
}
],
"thresholds": [],
"timeFrom": null,
"timeRegions": [],
"timeShift": null,
"title": "2 yaxis and axis labels",
"tooltip": {
"msResolution": false,
"shared": true,
"sort": 0,
"value_type": "cumulative"
},
"type": "graph",
"xaxis": {
"buckets": null,
"mode": "time",
"name": null,
"show": true,
"values": []
},
"yaxes": [
{
"format": "percent",
"label": "Perecent",
"logBase": 1,
"max": null,
"min": null,
"show": true
},
{
"format": "short",
"label": "Pressure",
"logBase": 1,
"max": null,
"min": null,
"show": true
}
],
"yaxis": {
"align": false,
"alignLevel": null
}
},
{
"aliasColors": {},
"bars": false,
"dashLength": 10,
"dashes": false,
"datasource": "gdev-testdata",
"editable": true,
"error": false,
"fieldConfig": {
"defaults": {
"custom": {}
},
"overrides": []
},
"fill": 1,
"fillGradient": 0,
"gridPos": {
"h": 8,
"w": 12,
"x": 12,
"y": 7
},
"hiddenSeries": false,
"id": 9,
"legend": {
"avg": false,
"current": false,
"max": false,
"min": false,
"show": true,
"total": false,
"values": false
},
"lines": true,
"linewidth": 2,
"links": [],
"nullPointMode": "null",
"options": {
"dataLinks": []
},
"percentage": false,
"pointradius": 5,
"points": false,
"renderer": "flot",
"seriesOverrides": [
{
"alias": "B-series",
"zindex": -3
}
],
"spaceLength": 10,
"stack": true,
"steppedLine": false,
"targets": [
{
"hide": false,
"refId": "B",
"scenarioId": "csv_metric_values",
"stringInput": "1,20,null,null,null,null,null,null,100,10,10,20,30,40,10",
"target": ""
},
{
"alias": "",
"hide": false,
"refId": "A",
"scenarioId": "csv_metric_values",
"stringInput": "1,20,90,30,5,10,20,30,40,40,40,100,10,20,20",
"target": ""
},
{
"alias": "",
"hide": false,
"refId": "C",
"scenarioId": "csv_metric_values",
"stringInput": "1,20,90,30,5,10,20,30,40,40,40,100,10,20,20",
"target": ""
}
],
"thresholds": [],
"timeFrom": null,
"timeRegions": [],
"timeShift": null,
"title": "Stacking value ontop of nulls",
"tooltip": {
"msResolution": false,
"shared": true,
"sort": 0,
"value_type": "cumulative"
},
"type": "graph",
"xaxis": {
"buckets": null,
"mode": "time",
"name": null,
"show": true,
"values": []
},
"yaxes": [
{
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
},
{
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
}
],
"yaxis": {
"align": false,
"alignLevel": null
}
},
{
"aliasColors": {},
"bars": false,
"dashLength": 10,
"dashes": false,
"datasource": "gdev-testdata",
"editable": true,
"error": false,
"fieldConfig": {
"defaults": {
"custom": {}
},
"overrides": []
},
"fill": 0,
"fillGradient": 0,
"gridPos": {
"h": 7,
"w": 12,
"x": 0,
"y": 15
},
"hiddenSeries": false,
"id": 21,
"legend": {
"avg": false,
"current": false,
"max": false,
"min": false,
"show": true,
"total": false,
"values": false
},
"lines": true,
"linewidth": 2,
"links": [],
"nullPointMode": "null",
"options": {
"dataLinks": []
},
"percentage": false,
"pointradius": 5,
"points": false,
"renderer": "flot",
"seriesOverrides": [
{
"alias": "C-series",
"steppedLine": true
}
],
"spaceLength": 10,
"stack": false,
"steppedLine": false,
"targets": [
{
"alias": "",
"hide": false,
"refId": "B",
"scenarioId": "csv_metric_values",
"stringInput": "1,null,40,null,90,null,null,100,null,null,100,null,null,80,null",
"target": ""
},
{
"alias": "",
"hide": false,
"refId": "C",
"scenarioId": "csv_metric_values",
"stringInput": "20,null40,null,null,50,null,70,null,100,null,10,null,30,null",
"target": ""
}
],
"thresholds": [],
"timeFrom": null,
"timeRegions": [],
"timeShift": null,
"title": "Null between points",
"tooltip": {
"msResolution": false,
"shared": true,
"sort": 0,
"value_type": "cumulative"
},
"type": "graph",
"xaxis": {
"buckets": null,
"mode": "time",
"name": null,
"show": true,
"values": []
},
"yaxes": [
{
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
},
{
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
}
],
"yaxis": {
"align": false,
"alignLevel": null
}
},
{
"aliasColors": {},
"bars": false,
"dashLength": 10,
"dashes": false,
"datasource": "gdev-testdata",
"decimals": 3,
"fieldConfig": {
"defaults": {
"custom": {}
},
"overrides": []
},
"fill": 1,
"fillGradient": 0,
"gridPos": {
"h": 7,
"w": 12,
"x": 12,
"y": 15
},
"hiddenSeries": false,
"id": 16,
"legend": {
"alignAsTable": true,
"avg": true,
"current": true,
"max": true,
"min": true,
"show": true,
"total": true,
"values": true
},
"lines": true,
"linewidth": 1,
"links": [],
"nullPointMode": "null",
"options": {
"dataLinks": []
},
"percentage": false,
"pointradius": 5,
"points": false,
"renderer": "flot",
"seriesOverrides": [],
"spaceLength": 10,
"stack": false,
"steppedLine": false,
"targets": [
{
"refId": "A",
"scenarioId": "csv_metric_values",
"stringInput": "1,20,90,30,5,0",
"target": ""
},
{
"refId": "B",
"scenarioId": "csv_metric_values",
"stringInput": "1,20,90,30,5,0",
"target": ""
},
{
"refId": "C",
"scenarioId": "csv_metric_values",
"stringInput": "1,20,90,30,5,0",
"target": ""
},
{
"refId": "D",
"scenarioId": "csv_metric_values",
"stringInput": "1,20,90,30,5,0",
"target": ""
}
],
"thresholds": [],
"timeFrom": null,
"timeRegions": [],
"timeShift": null,
"title": "Legend Table No Scroll Visible",
"tooltip": {
"shared": true,
"sort": 0,
"value_type": "individual"
},
"type": "graph",
"xaxis": {
"buckets": null,
"mode": "time",
"name": null,
"show": true,
"values": []
},
"yaxes": [
{
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
},
{
"format": "short",
"label": null,
"logBase": 1,
"max": null,
"min": null,
"show": true
}
],
"yaxis": {
"align": false,
"alignLevel": null
}
}
],
"refresh": false,
"revision": 8,
"schemaVersion": 25,
"style": "dark",
"tags": ["gdev", "panel-tests", "graph", "table"],
"templating": {
"list": []
},
"time": {
"from": "now-1h",
"to": "now"
},
"timepicker": {
"refresh_intervals": ["10s", "30s", "1m", "5m", "15m", "30m", "1h", "2h", "1d"],
"time_options": ["5m", "15m", "1h", "6h", "12h", "24h", "2d", "7d", "30d"]
},
"timezone": "utc",
"title": "Panel Tests - Time zone support",
"uid": "5SdHCasdf",
"version": 1
}
| devenv/dev-dashboards/scenarios/time_zone_support.json | 0 | https://github.com/grafana/grafana/commit/8c35ed40147946c36ae318b54cfe29275553ceea | [
0.00020294070418458432,
0.00016856617003213614,
0.00016327093180734664,
0.00016698021499905735,
0.00000705677939549787
] |
{
"id": 2,
"code_window": [
" value: 5,\n",
" },\n",
" {\n",
" timestamp: 1610449070000,\n",
" value: 1,\n",
" },\n",
" {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" timestamp: 1610449070.0,\n"
],
"file_path": "public/app/plugins/datasource/prometheus/result_transformer.test.ts",
"type": "replace",
"edit_start_line_idx": 523
} | import { AlertTabCtrl } from './AlertTabCtrl';
interface Args {
notifications?: Array<{ uid?: string; id?: number; isDefault: boolean }>;
}
function setupTestContext({ notifications = [] }: Args = {}) {
const panel = {
alert: { notifications },
options: [],
title: 'Testing Alerts',
};
const $scope = {
ctrl: {
panel,
render: jest.fn(),
},
};
const dashboardSrv: any = {};
const uiSegmentSrv: any = {};
const datasourceSrv: any = {};
const controller = new AlertTabCtrl($scope, dashboardSrv, uiSegmentSrv, datasourceSrv);
controller.notifications = notifications;
controller.alertNotifications = [];
controller.initModel();
return { controller };
}
describe('AlertTabCtrl', () => {
describe('when removeNotification is called with an uid', () => {
it('then the correct notifier should be removed', () => {
const { controller } = setupTestContext({
notifications: [
{ id: 1, uid: 'one', isDefault: true },
{ id: 2, uid: 'two', isDefault: false },
],
});
expect(controller.alert.notifications).toEqual([
{ id: 1, uid: 'one', isDefault: true, iconClass: 'bell' },
{ id: 2, uid: 'two', isDefault: false, iconClass: 'bell' },
]);
expect(controller.alertNotifications).toEqual([
{ id: 2, uid: 'two', isDefault: false, iconClass: 'bell' },
{ id: 1, uid: 'one', isDefault: true, iconClass: 'bell' },
]);
controller.removeNotification({ uid: 'one' });
expect(controller.alert.notifications).toEqual([{ id: 2, uid: 'two', isDefault: false, iconClass: 'bell' }]);
expect(controller.alertNotifications).toEqual([{ id: 2, uid: 'two', isDefault: false, iconClass: 'bell' }]);
});
});
describe('when removeNotification is called with an id', () => {
it('then the correct notifier should be removed', () => {
const { controller } = setupTestContext({
notifications: [
{ id: 1, uid: 'one', isDefault: true },
{ id: 2, uid: 'two', isDefault: false },
],
});
expect(controller.alert.notifications).toEqual([
{ id: 1, uid: 'one', isDefault: true, iconClass: 'bell' },
{ id: 2, uid: 'two', isDefault: false, iconClass: 'bell' },
]);
expect(controller.alertNotifications).toEqual([
{ id: 2, uid: 'two', isDefault: false, iconClass: 'bell' },
{ id: 1, uid: 'one', isDefault: true, iconClass: 'bell' },
]);
controller.removeNotification({ id: 2 });
expect(controller.alert.notifications).toEqual([{ id: 1, uid: 'one', isDefault: true, iconClass: 'bell' }]);
expect(controller.alertNotifications).toEqual([{ id: 1, uid: 'one', isDefault: true, iconClass: 'bell' }]);
});
});
});
| public/app/features/alerting/AlertTabCtrl.test.ts | 0 | https://github.com/grafana/grafana/commit/8c35ed40147946c36ae318b54cfe29275553ceea | [
0.0001712066150503233,
0.00016847162623889744,
0.00016509724082425237,
0.00016852238331921399,
0.0000016650881207169732
] |
{
"id": 3,
"code_window": [
" value: 1,\n",
" },\n",
" {\n",
" timestamp: 1610449070500,\n",
" value: 13,\n",
" },\n",
" {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" timestamp: 1610449070.5,\n"
],
"file_path": "public/app/plugins/datasource/prometheus/result_transformer.test.ts",
"type": "replace",
"edit_start_line_idx": 527
} | import { DataFrame, FieldType } from '@grafana/data';
import { transform } from './result_transformer';
jest.mock('@grafana/runtime', () => ({
getTemplateSrv: () => ({
replace: (str: string) => str,
}),
getDataSourceSrv: () => {
return {
getInstanceSettings: () => {
return { name: 'Tempo' };
},
};
},
}));
const matrixResponse = {
status: 'success',
data: {
resultType: 'matrix',
result: [
{
metric: { __name__: 'test', job: 'testjob' },
values: [
[1, '10'],
[2, '0'],
],
},
],
},
};
describe('Prometheus Result Transformer', () => {
const options: any = { target: {}, query: {} };
describe('When nothing is returned', () => {
it('should return empty array', () => {
const response = {
status: 'success',
data: {
resultType: '',
result: null,
},
};
const series = transform({ data: response } as any, options);
expect(series).toEqual([]);
});
it('should return empty array', () => {
const response = {
status: 'success',
data: {
resultType: '',
result: null,
},
};
const result = transform({ data: response } as any, { ...options, target: { format: 'table' } });
expect(result).toHaveLength(0);
});
});
describe('When resultFormat is table', () => {
const response = {
status: 'success',
data: {
resultType: 'matrix',
result: [
{
metric: { __name__: 'test', job: 'testjob' },
values: [
[1443454528, '3846'],
[1443454530, '3848'],
],
},
{
metric: {
__name__: 'test2',
instance: 'localhost:8080',
job: 'otherjob',
},
values: [
[1443454529, '3847'],
[1443454531, '3849'],
],
},
],
},
};
it('should return data frame', () => {
const result = transform({ data: response } as any, {
...options,
target: {
responseListLength: 0,
refId: 'A',
format: 'table',
},
});
expect(result[0].fields[0].values.toArray()).toEqual([
1443454528000,
1443454530000,
1443454529000,
1443454531000,
]);
expect(result[0].fields[0].name).toBe('Time');
expect(result[0].fields[0].type).toBe(FieldType.time);
expect(result[0].fields[1].values.toArray()).toEqual(['test', 'test', 'test2', 'test2']);
expect(result[0].fields[1].name).toBe('__name__');
expect(result[0].fields[1].config.filterable).toBe(true);
expect(result[0].fields[1].type).toBe(FieldType.string);
expect(result[0].fields[2].values.toArray()).toEqual(['', '', 'localhost:8080', 'localhost:8080']);
expect(result[0].fields[2].name).toBe('instance');
expect(result[0].fields[2].type).toBe(FieldType.string);
expect(result[0].fields[3].values.toArray()).toEqual(['testjob', 'testjob', 'otherjob', 'otherjob']);
expect(result[0].fields[3].name).toBe('job');
expect(result[0].fields[3].type).toBe(FieldType.string);
expect(result[0].fields[4].values.toArray()).toEqual([3846, 3848, 3847, 3849]);
expect(result[0].fields[4].name).toEqual('Value');
expect(result[0].fields[4].type).toBe(FieldType.number);
expect(result[0].refId).toBe('A');
});
it('should include refId if response count is more than 2', () => {
const result = transform({ data: response } as any, {
...options,
target: {
refId: 'B',
format: 'table',
},
responseListLength: 2,
});
expect(result[0].fields[4].name).toEqual('Value #B');
});
});
describe('When resultFormat is table and instant = true', () => {
const response = {
status: 'success',
data: {
resultType: 'vector',
result: [
{
metric: { __name__: 'test', job: 'testjob' },
value: [1443454528, '3846'],
},
],
},
};
it('should return data frame', () => {
const result = transform({ data: response } as any, { ...options, target: { format: 'table' } });
expect(result[0].fields[0].values.toArray()).toEqual([1443454528000]);
expect(result[0].fields[0].name).toBe('Time');
expect(result[0].fields[1].values.toArray()).toEqual(['test']);
expect(result[0].fields[1].name).toBe('__name__');
expect(result[0].fields[2].values.toArray()).toEqual(['testjob']);
expect(result[0].fields[2].name).toBe('job');
expect(result[0].fields[3].values.toArray()).toEqual([3846]);
expect(result[0].fields[3].name).toEqual('Value');
});
it('should return le label values parsed as numbers', () => {
const response = {
status: 'success',
data: {
resultType: 'vector',
result: [
{
metric: { le: '102' },
value: [1594908838, '0'],
},
],
},
};
const result = transform({ data: response } as any, { ...options, target: { format: 'table' } });
expect(result[0].fields[1].values.toArray()).toEqual([102]);
expect(result[0].fields[1].type).toEqual(FieldType.number);
});
});
describe('When instant = true', () => {
const response = {
status: 'success',
data: {
resultType: 'vector',
result: [
{
metric: { __name__: 'test', job: 'testjob' },
value: [1443454528, '3846'],
},
],
},
};
it('should return data frame', () => {
const result: DataFrame[] = transform({ data: response } as any, { ...options, query: { instant: true } });
expect(result[0].name).toBe('test{job="testjob"}');
});
});
describe('When resultFormat is heatmap', () => {
const getResponse = (result: any) => ({
status: 'success',
data: {
resultType: 'matrix',
result,
},
});
const options = {
format: 'heatmap',
start: 1445000010,
end: 1445000030,
legendFormat: '{{le}}',
};
it('should convert cumulative histogram to regular', () => {
const response = getResponse([
{
metric: { __name__: 'test', job: 'testjob', le: '1' },
values: [
[1445000010, '10'],
[1445000020, '10'],
[1445000030, '0'],
],
},
{
metric: { __name__: 'test', job: 'testjob', le: '2' },
values: [
[1445000010, '20'],
[1445000020, '10'],
[1445000030, '30'],
],
},
{
metric: { __name__: 'test', job: 'testjob', le: '3' },
values: [
[1445000010, '30'],
[1445000020, '10'],
[1445000030, '40'],
],
},
]);
const result = transform({ data: response } as any, { query: options, target: options } as any);
expect(result[0].fields[0].values.toArray()).toEqual([1445000010000, 1445000020000, 1445000030000]);
expect(result[0].fields[1].values.toArray()).toEqual([10, 10, 0]);
expect(result[1].fields[0].values.toArray()).toEqual([1445000010000, 1445000020000, 1445000030000]);
expect(result[1].fields[1].values.toArray()).toEqual([10, 0, 30]);
expect(result[2].fields[0].values.toArray()).toEqual([1445000010000, 1445000020000, 1445000030000]);
expect(result[2].fields[1].values.toArray()).toEqual([10, 0, 10]);
});
it('should handle missing datapoints', () => {
const response = getResponse([
{
metric: { __name__: 'test', job: 'testjob', le: '1' },
values: [
[1445000010, '1'],
[1445000020, '2'],
],
},
{
metric: { __name__: 'test', job: 'testjob', le: '2' },
values: [
[1445000010, '2'],
[1445000020, '5'],
[1445000030, '1'],
],
},
{
metric: { __name__: 'test', job: 'testjob', le: '3' },
values: [
[1445000010, '3'],
[1445000020, '7'],
],
},
]);
const result = transform({ data: response } as any, { query: options, target: options } as any);
expect(result[0].fields[1].values.toArray()).toEqual([1, 2]);
expect(result[1].fields[1].values.toArray()).toEqual([1, 3, 1]);
expect(result[2].fields[1].values.toArray()).toEqual([1, 2]);
});
});
describe('When the response is a matrix', () => {
it('should have labels with the value field', () => {
const response = {
status: 'success',
data: {
resultType: 'matrix',
result: [
{
metric: { __name__: 'test', job: 'testjob', instance: 'testinstance' },
values: [
[0, '10'],
[1, '10'],
[2, '0'],
],
},
],
},
};
const result: DataFrame[] = transform({ data: response } as any, {
...options,
});
expect(result[0].fields[1].labels).toBeDefined();
expect(result[0].fields[1].labels?.instance).toBe('testinstance');
expect(result[0].fields[1].labels?.job).toBe('testjob');
});
it('should transform into a data frame', () => {
const response = {
status: 'success',
data: {
resultType: 'matrix',
result: [
{
metric: { __name__: 'test', job: 'testjob' },
values: [
[0, '10'],
[1, '10'],
[2, '0'],
],
},
],
},
};
const result: DataFrame[] = transform({ data: response } as any, {
...options,
query: {
start: 0,
end: 2,
},
});
expect(result[0].fields[0].values.toArray()).toEqual([0, 1000, 2000]);
expect(result[0].fields[1].values.toArray()).toEqual([10, 10, 0]);
expect(result[0].name).toBe('test{job="testjob"}');
});
it('should fill null values', () => {
const result = transform({ data: matrixResponse } as any, { ...options, query: { step: 1, start: 0, end: 2 } });
expect(result[0].fields[0].values.toArray()).toEqual([0, 1000, 2000]);
expect(result[0].fields[1].values.toArray()).toEqual([null, 10, 0]);
});
it('should use __name__ label as series name', () => {
const result = transform({ data: matrixResponse } as any, {
...options,
query: {
step: 1,
start: 0,
end: 2,
},
});
expect(result[0].name).toEqual('test{job="testjob"}');
});
it('should use query as series name when __name__ is not available and metric is empty', () => {
const response = {
status: 'success',
data: {
resultType: 'matrix',
result: [
{
metric: {},
values: [[0, '10']],
},
],
},
};
const expr = 'histogram_quantile(0.95, sum(rate(tns_request_duration_seconds_bucket[5m])) by (le))';
const result = transform({ data: response } as any, {
...options,
query: {
step: 1,
start: 0,
end: 2,
expr,
},
});
expect(result[0].name).toEqual(expr);
});
it('should set frame name to undefined if no __name__ label but there are other labels', () => {
const response = {
status: 'success',
data: {
resultType: 'matrix',
result: [
{
metric: { job: 'testjob' },
values: [
[1, '10'],
[2, '0'],
],
},
],
},
};
const result = transform({ data: response } as any, {
...options,
query: {
step: 1,
start: 0,
end: 2,
},
});
expect(result[0].name).toBe('{job="testjob"}');
});
it('should not set displayName for ValueFields', () => {
const result = transform({ data: matrixResponse } as any, options);
expect(result[0].fields[1].config.displayName).toBeUndefined();
expect(result[0].fields[1].config.displayNameFromDS).toBe('test{job="testjob"}');
});
it('should align null values with step', () => {
const response = {
status: 'success',
data: {
resultType: 'matrix',
result: [
{
metric: { __name__: 'test', job: 'testjob' },
values: [
[4, '10'],
[8, '10'],
],
},
],
},
};
const result = transform({ data: response } as any, { ...options, query: { step: 2, start: 0, end: 8 } });
expect(result[0].fields[0].values.toArray()).toEqual([0, 2000, 4000, 6000, 8000]);
expect(result[0].fields[1].values.toArray()).toEqual([null, null, 10, null, 10]);
});
});
describe('When infinity values are returned', () => {
describe('When resultType is scalar', () => {
const response = {
status: 'success',
data: {
resultType: 'scalar',
result: [1443454528, '+Inf'],
},
};
it('should correctly parse values', () => {
const result: DataFrame[] = transform({ data: response } as any, { ...options, target: { format: 'table' } });
expect(result[0].fields[1].values.toArray()).toEqual([Number.POSITIVE_INFINITY]);
});
});
describe('When resultType is vector', () => {
const response = {
status: 'success',
data: {
resultType: 'vector',
result: [
{
metric: { __name__: 'test', job: 'testjob' },
value: [1443454528, '+Inf'],
},
{
metric: { __name__: 'test', job: 'testjob' },
value: [1443454528, '-Inf'],
},
],
},
};
describe('When format is table', () => {
it('should correctly parse values', () => {
const result: DataFrame[] = transform({ data: response } as any, { ...options, target: { format: 'table' } });
expect(result[0].fields[3].values.toArray()).toEqual([Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY]);
});
});
});
});
const exemplarsResponse = {
status: 'success',
data: [
{
seriesLabels: { __name__: 'test' },
exemplars: [
{
timestamp: 1610449069957,
labels: { traceID: '5020b5bc45117f07' },
value: 0.002074123,
},
],
},
],
};
describe('When the response is exemplar data', () => {
it('should return as an data frame with a dataTopic annotations', () => {
const result = transform({ data: exemplarsResponse } as any, options);
expect(result[0].meta?.dataTopic).toBe('annotations');
expect(result[0].fields.length).toBe(4); // __name__, traceID, Time, Value
expect(result[0].length).toBe(1);
});
it('should remove exemplars that are too close to each other', () => {
const response = {
status: 'success',
data: [
{
exemplars: [
{
timestamp: 1610449070000,
value: 5,
},
{
timestamp: 1610449070000,
value: 1,
},
{
timestamp: 1610449070500,
value: 13,
},
{
timestamp: 1610449070300,
value: 20,
},
],
},
],
};
/**
* the standard deviation for the above values is 8.4 this means that we show the highest
* value (20) and then the next value should be 2 times the standard deviation which is 1
**/
const result = transform({ data: response } as any, options);
expect(result[0].length).toBe(2);
});
describe('data link', () => {
it('should be added to the field if found with url', () => {
const result = transform({ data: exemplarsResponse } as any, {
...options,
exemplarTraceIdDestinations: [{ name: 'traceID', url: 'http://localhost' }],
});
expect(result[0].fields.some((f) => f.config.links?.length)).toBe(true);
});
it('should be added to the field if found with internal link', () => {
const result = transform({ data: exemplarsResponse } as any, {
...options,
exemplarTraceIdDestinations: [{ name: 'traceID', datasourceUid: 'jaeger' }],
});
expect(result[0].fields.some((f) => f.config.links?.length)).toBe(true);
});
it('should not add link if exemplarTraceIdDestinations is not configured', () => {
const result = transform({ data: exemplarsResponse } as any, options);
expect(result[0].fields.some((f) => f.config.links?.length)).toBe(false);
});
});
});
});
| public/app/plugins/datasource/prometheus/result_transformer.test.ts | 1 | https://github.com/grafana/grafana/commit/8c35ed40147946c36ae318b54cfe29275553ceea | [
0.9820765256881714,
0.01710733026266098,
0.00016439755563624203,
0.00016784397303126752,
0.12781330943107605
] |
{
"id": 3,
"code_window": [
" value: 1,\n",
" },\n",
" {\n",
" timestamp: 1610449070500,\n",
" value: 13,\n",
" },\n",
" {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" timestamp: 1610449070.5,\n"
],
"file_path": "public/app/plugins/datasource/prometheus/result_transformer.test.ts",
"type": "replace",
"edit_start_line_idx": 527
} | package prometheus
import "time"
type PrometheusQuery struct {
Expr string
Step time.Duration
LegendFormat string
Start time.Time
End time.Time
RefId string
}
| pkg/tsdb/prometheus/types.go | 0 | https://github.com/grafana/grafana/commit/8c35ed40147946c36ae318b54cfe29275553ceea | [
0.0009630770655348897,
0.000570337928365916,
0.0001775987766450271,
0.000570337928365916,
0.0003927391371689737
] |
{
"id": 3,
"code_window": [
" value: 1,\n",
" },\n",
" {\n",
" timestamp: 1610449070500,\n",
" value: 13,\n",
" },\n",
" {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" timestamp: 1610449070.5,\n"
],
"file_path": "public/app/plugins/datasource/prometheus/result_transformer.test.ts",
"type": "replace",
"edit_start_line_idx": 527
} | # ldap-admin
dn: cn=ldap-admin,ou=users,dc=grafana,dc=org
mail: [email protected]
userPassword: grafana
objectClass: person
objectClass: top
objectClass: inetOrgPerson
objectClass: organizationalPerson
sn: ldap-admin
cn: ldap-admin
dn: cn=ldap-editor,ou=users,dc=grafana,dc=org
mail: [email protected]
userPassword: grafana
objectClass: person
objectClass: top
objectClass: inetOrgPerson
objectClass: organizationalPerson
sn: ldap-editor
cn: ldap-editor
dn: cn=ldap-viewer,ou=users,dc=grafana,dc=org
mail: [email protected]
userPassword: grafana
objectClass: person
objectClass: top
objectClass: inetOrgPerson
objectClass: organizationalPerson
sn: ldap-viewer
cn: ldap-viewer
dn: cn=ldap-carl,ou=users,dc=grafana,dc=org
mail: [email protected]
userPassword: grafana
objectClass: person
objectClass: top
objectClass: inetOrgPerson
objectClass: organizationalPerson
sn: ldap-carl
cn: ldap-carl
dn: cn=ldap-daniel,ou=users,dc=grafana,dc=org
mail: [email protected]
userPassword: grafana
objectClass: person
objectClass: top
objectClass: inetOrgPerson
objectClass: organizationalPerson
sn: ldap-daniel
cn: ldap-daniel
dn: cn=ldap-leo,ou=users,dc=grafana,dc=org
mail: [email protected]
userPassword: grafana
objectClass: person
objectClass: top
objectClass: inetOrgPerson
objectClass: organizationalPerson
sn: ldap-leo
cn: ldap-leo
dn: cn=ldap-tobias,ou=users,dc=grafana,dc=org
mail: [email protected]
userPassword: grafana
objectClass: person
objectClass: top
objectClass: inetOrgPerson
objectClass: organizationalPerson
sn: ldap-tobias
cn: ldap-tobias
dn: cn=ldap-torkel,ou=users,dc=grafana,dc=org
mail: [email protected]
userPassword: grafana
objectClass: person
objectClass: top
objectClass: inetOrgPerson
objectClass: organizationalPerson
sn: ldap-torkel
cn: ldap-torkel
# admin for posix group (without support for memberOf attribute)
dn: uid=ldap-posix-admin,ou=users,dc=grafana,dc=org
mail: [email protected]
userPassword: grafana
objectclass: top
objectclass: posixAccount
objectclass: inetOrgPerson
homedirectory: /home/ldap-posix-admin
sn: ldap-posix-admin
cn: ldap-posix-admin
uid: ldap-posix-admin
uidnumber: 1
gidnumber: 1
# user for posix group (without support for memberOf attribute)
dn: uid=ldap-posix,ou=users,dc=grafana,dc=org
mail: [email protected]
userPassword: grafana
objectclass: top
objectclass: posixAccount
objectclass: inetOrgPerson
homedirectory: /home/ldap-posix
sn: ldap-posix
cn: ldap-posix
uid: ldap-posix
uidnumber: 2
gidnumber: 2
| devenv/docker/blocks/openldap/prepopulate/2_users.ldif | 0 | https://github.com/grafana/grafana/commit/8c35ed40147946c36ae318b54cfe29275553ceea | [
0.00048789760330691934,
0.00019639260426629335,
0.00015900253492873162,
0.0001684369199210778,
0.00009223456436302513
] |
{
"id": 3,
"code_window": [
" value: 1,\n",
" },\n",
" {\n",
" timestamp: 1610449070500,\n",
" value: 13,\n",
" },\n",
" {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" timestamp: 1610449070.5,\n"
],
"file_path": "public/app/plugins/datasource/prometheus/result_transformer.test.ts",
"type": "replace",
"edit_start_line_idx": 527
} | <page-header model="ctrl.navModel"></page-header>
<div class="page-container page-body" ng-form="ctrl.playlistEditForm">
<h3 class="page-sub-heading" ng-hide="ctrl.isNew">Edit Playlist</h3>
<h3 class="page-sub-heading" ng-show="ctrl.isNew">New Playlist</h3>
<p class="playlist-description">
A playlist rotates through a pre-selected list of Dashboards. A Playlist can be a great way to build situational
awareness, or just show off your metrics to your team or visitors.
</p>
<div class="gf-form-group">
<div class="gf-form">
<span class="gf-form-label width-7">Name</span>
<input type="text" required ng-model="ctrl.playlist.name" class="gf-form-input max-width-21" />
</div>
<div class="gf-form">
<span class="gf-form-label width-7">Interval</span>
<input
type="text"
required
ng-model="ctrl.playlist.interval"
placeholder="5m"
class="gf-form-input max-width-21"
/>
</div>
</div>
<div class="gf-form-group">
<h3 class="page-headering">Dashboards</h3>
<table class="filter-table playlist-available-list">
<tr ng-repeat="playlistItem in ctrl.playlistItems">
<td ng-if="playlistItem.type === 'dashboard_by_id'">
<icon name="'apps'"></icon> {{playlistItem.title}}
</td>
<td ng-if="playlistItem.type === 'dashboard_by_tag'">
<a class="search-result-tag label label-tag" tag-color-from-name="playlistItem.title">
<icon name="'tag-alt'"></icon>
<span>{{playlistItem.title}}</span>
</a>
</td>
<td class="selected-playlistitem-settings">
<button class="btn btn-inverse btn-small" ng-hide="$first" ng-click="ctrl.movePlaylistItemUp(playlistItem)">
<icon name="'arrow-up'"></icon>
</button>
<button class="btn btn-inverse btn-small" ng-hide="$last" ng-click="ctrl.movePlaylistItemDown(playlistItem)">
<icon name="'arrow-down'"></icon>
</button>
<button class="btn btn-inverse btn-small" ng-click="ctrl.removePlaylistItem(playlistItem)">
<icon name="'times'"></icon>
</button>
</td>
</tr>
<tr ng-if="ctrl.playlistItems.length === 0">
<td><em>Playlist is empty, add dashboards below.</em></td>
</tr>
</table>
</div>
<div class="gf-form-group">
<h3 class="page-headering">Add dashboards</h3>
<playlist-search class="playlist-search-container" search-started="ctrl.searchStarted(promise)"></playlist-search>
<div ng-if="ctrl.filteredDashboards.length > 0">
<table class="filter-table playlist-available-list">
<tr ng-repeat="playlistItem in ctrl.filteredDashboards">
<td>
<icon name="'apps'"></icon>
{{playlistItem.title}}
<icon name="'favorite'" type="'mono'" ng-show="playlistItem.isStarred"></icon>
</td>
<td class="add-dashboard">
<button class="btn btn-inverse btn-small pull-right" ng-click="ctrl.addPlaylistItem(playlistItem)">
<icon name="'plus'"></icon>
Add to playlist
</button>
</td>
</tr>
</table>
</div>
<div class="playlist-search-results-container" ng-if="ctrl.filteredTags.length > 0;">
<table class="filter-table playlist-available-list">
<tr ng-repeat="tag in ctrl.filteredTags">
<td>
<a class="search-result-tag label label-tag" tag-color-from-name="tag.term">
<icon name="'tag-alt'"></icon>
<span>{{tag.term}} ({{tag.count}})</span>
</a>
</td>
<td class="add-dashboard">
<button class="btn btn-inverse btn-small pull-right" ng-click="ctrl.addTagPlaylistItem(tag)">
<icon name="'plus'"></icon>
Add to playlist
</button>
</td>
</tr>
</table>
</div>
</div>
<div class="clearfix"></div>
<div class="gf-form-button-row">
<a
class="btn btn-primary"
ng-show="ctrl.isNew"
ng-disabled="ctrl.playlistEditForm.$invalid || ctrl.isPlaylistEmpty()"
ng-click="ctrl.savePlaylist(ctrl.playlist, ctrl.playlistItems)"
>Create</a
>
<a
class="btn btn-primary"
ng-show="!ctrl.isNew"
ng-disabled="ctrl.playlistEditForm.$invalid || ctrl.isPlaylistEmpty()"
ng-click="ctrl.savePlaylist(ctrl.playlist, ctrl.playlistItems)"
>Save</a
>
<a class="btn-text" ng-click="ctrl.backToList()">Cancel</a>
</div>
</div>
<footer />
| public/app/features/playlist/partials/playlist.html | 0 | https://github.com/grafana/grafana/commit/8c35ed40147946c36ae318b54cfe29275553ceea | [
0.00017537528765387833,
0.0001665910385781899,
0.00016382655303459615,
0.00016609895101282746,
0.00000286226190837624
] |
{
"id": 4,
"code_window": [
" value: 13,\n",
" },\n",
" {\n",
" timestamp: 1610449070300,\n",
" value: 20,\n",
" },\n",
" ],\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" timestamp: 1610449070.3,\n"
],
"file_path": "public/app/plugins/datasource/prometheus/result_transformer.test.ts",
"type": "replace",
"edit_start_line_idx": 531
} | import { DataFrame, FieldType } from '@grafana/data';
import { transform } from './result_transformer';
jest.mock('@grafana/runtime', () => ({
getTemplateSrv: () => ({
replace: (str: string) => str,
}),
getDataSourceSrv: () => {
return {
getInstanceSettings: () => {
return { name: 'Tempo' };
},
};
},
}));
const matrixResponse = {
status: 'success',
data: {
resultType: 'matrix',
result: [
{
metric: { __name__: 'test', job: 'testjob' },
values: [
[1, '10'],
[2, '0'],
],
},
],
},
};
describe('Prometheus Result Transformer', () => {
const options: any = { target: {}, query: {} };
describe('When nothing is returned', () => {
it('should return empty array', () => {
const response = {
status: 'success',
data: {
resultType: '',
result: null,
},
};
const series = transform({ data: response } as any, options);
expect(series).toEqual([]);
});
it('should return empty array', () => {
const response = {
status: 'success',
data: {
resultType: '',
result: null,
},
};
const result = transform({ data: response } as any, { ...options, target: { format: 'table' } });
expect(result).toHaveLength(0);
});
});
describe('When resultFormat is table', () => {
const response = {
status: 'success',
data: {
resultType: 'matrix',
result: [
{
metric: { __name__: 'test', job: 'testjob' },
values: [
[1443454528, '3846'],
[1443454530, '3848'],
],
},
{
metric: {
__name__: 'test2',
instance: 'localhost:8080',
job: 'otherjob',
},
values: [
[1443454529, '3847'],
[1443454531, '3849'],
],
},
],
},
};
it('should return data frame', () => {
const result = transform({ data: response } as any, {
...options,
target: {
responseListLength: 0,
refId: 'A',
format: 'table',
},
});
expect(result[0].fields[0].values.toArray()).toEqual([
1443454528000,
1443454530000,
1443454529000,
1443454531000,
]);
expect(result[0].fields[0].name).toBe('Time');
expect(result[0].fields[0].type).toBe(FieldType.time);
expect(result[0].fields[1].values.toArray()).toEqual(['test', 'test', 'test2', 'test2']);
expect(result[0].fields[1].name).toBe('__name__');
expect(result[0].fields[1].config.filterable).toBe(true);
expect(result[0].fields[1].type).toBe(FieldType.string);
expect(result[0].fields[2].values.toArray()).toEqual(['', '', 'localhost:8080', 'localhost:8080']);
expect(result[0].fields[2].name).toBe('instance');
expect(result[0].fields[2].type).toBe(FieldType.string);
expect(result[0].fields[3].values.toArray()).toEqual(['testjob', 'testjob', 'otherjob', 'otherjob']);
expect(result[0].fields[3].name).toBe('job');
expect(result[0].fields[3].type).toBe(FieldType.string);
expect(result[0].fields[4].values.toArray()).toEqual([3846, 3848, 3847, 3849]);
expect(result[0].fields[4].name).toEqual('Value');
expect(result[0].fields[4].type).toBe(FieldType.number);
expect(result[0].refId).toBe('A');
});
it('should include refId if response count is more than 2', () => {
const result = transform({ data: response } as any, {
...options,
target: {
refId: 'B',
format: 'table',
},
responseListLength: 2,
});
expect(result[0].fields[4].name).toEqual('Value #B');
});
});
describe('When resultFormat is table and instant = true', () => {
const response = {
status: 'success',
data: {
resultType: 'vector',
result: [
{
metric: { __name__: 'test', job: 'testjob' },
value: [1443454528, '3846'],
},
],
},
};
it('should return data frame', () => {
const result = transform({ data: response } as any, { ...options, target: { format: 'table' } });
expect(result[0].fields[0].values.toArray()).toEqual([1443454528000]);
expect(result[0].fields[0].name).toBe('Time');
expect(result[0].fields[1].values.toArray()).toEqual(['test']);
expect(result[0].fields[1].name).toBe('__name__');
expect(result[0].fields[2].values.toArray()).toEqual(['testjob']);
expect(result[0].fields[2].name).toBe('job');
expect(result[0].fields[3].values.toArray()).toEqual([3846]);
expect(result[0].fields[3].name).toEqual('Value');
});
it('should return le label values parsed as numbers', () => {
const response = {
status: 'success',
data: {
resultType: 'vector',
result: [
{
metric: { le: '102' },
value: [1594908838, '0'],
},
],
},
};
const result = transform({ data: response } as any, { ...options, target: { format: 'table' } });
expect(result[0].fields[1].values.toArray()).toEqual([102]);
expect(result[0].fields[1].type).toEqual(FieldType.number);
});
});
describe('When instant = true', () => {
const response = {
status: 'success',
data: {
resultType: 'vector',
result: [
{
metric: { __name__: 'test', job: 'testjob' },
value: [1443454528, '3846'],
},
],
},
};
it('should return data frame', () => {
const result: DataFrame[] = transform({ data: response } as any, { ...options, query: { instant: true } });
expect(result[0].name).toBe('test{job="testjob"}');
});
});
describe('When resultFormat is heatmap', () => {
const getResponse = (result: any) => ({
status: 'success',
data: {
resultType: 'matrix',
result,
},
});
const options = {
format: 'heatmap',
start: 1445000010,
end: 1445000030,
legendFormat: '{{le}}',
};
it('should convert cumulative histogram to regular', () => {
const response = getResponse([
{
metric: { __name__: 'test', job: 'testjob', le: '1' },
values: [
[1445000010, '10'],
[1445000020, '10'],
[1445000030, '0'],
],
},
{
metric: { __name__: 'test', job: 'testjob', le: '2' },
values: [
[1445000010, '20'],
[1445000020, '10'],
[1445000030, '30'],
],
},
{
metric: { __name__: 'test', job: 'testjob', le: '3' },
values: [
[1445000010, '30'],
[1445000020, '10'],
[1445000030, '40'],
],
},
]);
const result = transform({ data: response } as any, { query: options, target: options } as any);
expect(result[0].fields[0].values.toArray()).toEqual([1445000010000, 1445000020000, 1445000030000]);
expect(result[0].fields[1].values.toArray()).toEqual([10, 10, 0]);
expect(result[1].fields[0].values.toArray()).toEqual([1445000010000, 1445000020000, 1445000030000]);
expect(result[1].fields[1].values.toArray()).toEqual([10, 0, 30]);
expect(result[2].fields[0].values.toArray()).toEqual([1445000010000, 1445000020000, 1445000030000]);
expect(result[2].fields[1].values.toArray()).toEqual([10, 0, 10]);
});
it('should handle missing datapoints', () => {
const response = getResponse([
{
metric: { __name__: 'test', job: 'testjob', le: '1' },
values: [
[1445000010, '1'],
[1445000020, '2'],
],
},
{
metric: { __name__: 'test', job: 'testjob', le: '2' },
values: [
[1445000010, '2'],
[1445000020, '5'],
[1445000030, '1'],
],
},
{
metric: { __name__: 'test', job: 'testjob', le: '3' },
values: [
[1445000010, '3'],
[1445000020, '7'],
],
},
]);
const result = transform({ data: response } as any, { query: options, target: options } as any);
expect(result[0].fields[1].values.toArray()).toEqual([1, 2]);
expect(result[1].fields[1].values.toArray()).toEqual([1, 3, 1]);
expect(result[2].fields[1].values.toArray()).toEqual([1, 2]);
});
});
describe('When the response is a matrix', () => {
it('should have labels with the value field', () => {
const response = {
status: 'success',
data: {
resultType: 'matrix',
result: [
{
metric: { __name__: 'test', job: 'testjob', instance: 'testinstance' },
values: [
[0, '10'],
[1, '10'],
[2, '0'],
],
},
],
},
};
const result: DataFrame[] = transform({ data: response } as any, {
...options,
});
expect(result[0].fields[1].labels).toBeDefined();
expect(result[0].fields[1].labels?.instance).toBe('testinstance');
expect(result[0].fields[1].labels?.job).toBe('testjob');
});
it('should transform into a data frame', () => {
const response = {
status: 'success',
data: {
resultType: 'matrix',
result: [
{
metric: { __name__: 'test', job: 'testjob' },
values: [
[0, '10'],
[1, '10'],
[2, '0'],
],
},
],
},
};
const result: DataFrame[] = transform({ data: response } as any, {
...options,
query: {
start: 0,
end: 2,
},
});
expect(result[0].fields[0].values.toArray()).toEqual([0, 1000, 2000]);
expect(result[0].fields[1].values.toArray()).toEqual([10, 10, 0]);
expect(result[0].name).toBe('test{job="testjob"}');
});
it('should fill null values', () => {
const result = transform({ data: matrixResponse } as any, { ...options, query: { step: 1, start: 0, end: 2 } });
expect(result[0].fields[0].values.toArray()).toEqual([0, 1000, 2000]);
expect(result[0].fields[1].values.toArray()).toEqual([null, 10, 0]);
});
it('should use __name__ label as series name', () => {
const result = transform({ data: matrixResponse } as any, {
...options,
query: {
step: 1,
start: 0,
end: 2,
},
});
expect(result[0].name).toEqual('test{job="testjob"}');
});
it('should use query as series name when __name__ is not available and metric is empty', () => {
const response = {
status: 'success',
data: {
resultType: 'matrix',
result: [
{
metric: {},
values: [[0, '10']],
},
],
},
};
const expr = 'histogram_quantile(0.95, sum(rate(tns_request_duration_seconds_bucket[5m])) by (le))';
const result = transform({ data: response } as any, {
...options,
query: {
step: 1,
start: 0,
end: 2,
expr,
},
});
expect(result[0].name).toEqual(expr);
});
it('should set frame name to undefined if no __name__ label but there are other labels', () => {
const response = {
status: 'success',
data: {
resultType: 'matrix',
result: [
{
metric: { job: 'testjob' },
values: [
[1, '10'],
[2, '0'],
],
},
],
},
};
const result = transform({ data: response } as any, {
...options,
query: {
step: 1,
start: 0,
end: 2,
},
});
expect(result[0].name).toBe('{job="testjob"}');
});
it('should not set displayName for ValueFields', () => {
const result = transform({ data: matrixResponse } as any, options);
expect(result[0].fields[1].config.displayName).toBeUndefined();
expect(result[0].fields[1].config.displayNameFromDS).toBe('test{job="testjob"}');
});
it('should align null values with step', () => {
const response = {
status: 'success',
data: {
resultType: 'matrix',
result: [
{
metric: { __name__: 'test', job: 'testjob' },
values: [
[4, '10'],
[8, '10'],
],
},
],
},
};
const result = transform({ data: response } as any, { ...options, query: { step: 2, start: 0, end: 8 } });
expect(result[0].fields[0].values.toArray()).toEqual([0, 2000, 4000, 6000, 8000]);
expect(result[0].fields[1].values.toArray()).toEqual([null, null, 10, null, 10]);
});
});
describe('When infinity values are returned', () => {
describe('When resultType is scalar', () => {
const response = {
status: 'success',
data: {
resultType: 'scalar',
result: [1443454528, '+Inf'],
},
};
it('should correctly parse values', () => {
const result: DataFrame[] = transform({ data: response } as any, { ...options, target: { format: 'table' } });
expect(result[0].fields[1].values.toArray()).toEqual([Number.POSITIVE_INFINITY]);
});
});
describe('When resultType is vector', () => {
const response = {
status: 'success',
data: {
resultType: 'vector',
result: [
{
metric: { __name__: 'test', job: 'testjob' },
value: [1443454528, '+Inf'],
},
{
metric: { __name__: 'test', job: 'testjob' },
value: [1443454528, '-Inf'],
},
],
},
};
describe('When format is table', () => {
it('should correctly parse values', () => {
const result: DataFrame[] = transform({ data: response } as any, { ...options, target: { format: 'table' } });
expect(result[0].fields[3].values.toArray()).toEqual([Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY]);
});
});
});
});
const exemplarsResponse = {
status: 'success',
data: [
{
seriesLabels: { __name__: 'test' },
exemplars: [
{
timestamp: 1610449069957,
labels: { traceID: '5020b5bc45117f07' },
value: 0.002074123,
},
],
},
],
};
describe('When the response is exemplar data', () => {
it('should return as an data frame with a dataTopic annotations', () => {
const result = transform({ data: exemplarsResponse } as any, options);
expect(result[0].meta?.dataTopic).toBe('annotations');
expect(result[0].fields.length).toBe(4); // __name__, traceID, Time, Value
expect(result[0].length).toBe(1);
});
it('should remove exemplars that are too close to each other', () => {
const response = {
status: 'success',
data: [
{
exemplars: [
{
timestamp: 1610449070000,
value: 5,
},
{
timestamp: 1610449070000,
value: 1,
},
{
timestamp: 1610449070500,
value: 13,
},
{
timestamp: 1610449070300,
value: 20,
},
],
},
],
};
/**
* the standard deviation for the above values is 8.4 this means that we show the highest
* value (20) and then the next value should be 2 times the standard deviation which is 1
**/
const result = transform({ data: response } as any, options);
expect(result[0].length).toBe(2);
});
describe('data link', () => {
it('should be added to the field if found with url', () => {
const result = transform({ data: exemplarsResponse } as any, {
...options,
exemplarTraceIdDestinations: [{ name: 'traceID', url: 'http://localhost' }],
});
expect(result[0].fields.some((f) => f.config.links?.length)).toBe(true);
});
it('should be added to the field if found with internal link', () => {
const result = transform({ data: exemplarsResponse } as any, {
...options,
exemplarTraceIdDestinations: [{ name: 'traceID', datasourceUid: 'jaeger' }],
});
expect(result[0].fields.some((f) => f.config.links?.length)).toBe(true);
});
it('should not add link if exemplarTraceIdDestinations is not configured', () => {
const result = transform({ data: exemplarsResponse } as any, options);
expect(result[0].fields.some((f) => f.config.links?.length)).toBe(false);
});
});
});
});
| public/app/plugins/datasource/prometheus/result_transformer.test.ts | 1 | https://github.com/grafana/grafana/commit/8c35ed40147946c36ae318b54cfe29275553ceea | [
0.8836032748222351,
0.020280050113797188,
0.00016580337251070887,
0.00017006728739943355,
0.12013334780931473
] |
{
"id": 4,
"code_window": [
" value: 13,\n",
" },\n",
" {\n",
" timestamp: 1610449070300,\n",
" value: 20,\n",
" },\n",
" ],\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" timestamp: 1610449070.3,\n"
],
"file_path": "public/app/plugins/datasource/prometheus/result_transformer.test.ts",
"type": "replace",
"edit_start_line_idx": 531
} | +++
title = "Enhanced LDAP Integration"
description = "Grafana Enhanced LDAP Integration Guide "
keywords = ["grafana", "configuration", "documentation", "ldap", "active directory", "enterprise"]
weight = 300
+++
# Enhanced LDAP integration
The enhanced LDAP integration adds additional functionality on top of the [LDAP integration]({{< relref "../auth/ldap.md" >}}) available in the open source edition of Grafana.
> Enhanced LDAP integration is only available in Grafana Enterprise.
## LDAP group synchronization for teams
{{< docs-imagebox img="/img/docs/enterprise/team_members_ldap.png" class="docs-image--no-shadow docs-image--right" max-width= "600px" >}}
With enhanced LDAP integration, you can set up synchronization between LDAP groups and teams. This enables LDAP users that are members
of certain LDAP groups to automatically be added or removed as members to certain teams in Grafana.
Grafana keeps track of all synchronized users in teams, and you can see which users have been synchronized from LDAP in the team members list, see `LDAP` label in screenshot.
This mechanism allows Grafana to remove an existing synchronized user from a team when its LDAP group membership changes. This mechanism also allows you to manually add
a user as member of a team, and it will not be removed when the user signs in. This gives you flexibility to combine LDAP group memberships and Grafana team memberships.
[Learn more about team sync.]({{< relref "team-sync.md">}})
<div class="clearfix"></div>
## Active LDAP synchronization
In the open source version of Grafana, user data from LDAP is synchronized only during the login process when authenticating using LDAP.
With active LDAP synchronization, available in Grafana Enterprise v6.3+, you can configure Grafana to actively sync users with LDAP servers in the background. Only users that have logged into Grafana at least once are synchronized.
Users with updated role and team membership will need to refresh the page to get access to the new features.
Removed users are automatically logged out and their account disabled. These accounts are displayed in the Server Admin > Users page with a `disabled` label. Disabled users keep their custom permissions on dashboards, folders, and data sources, so if you add them back in your LDAP database, they have access to the application with the same custom permissions as before.
```bash
[auth.ldap]
...
# You can use the Cron syntax or several predefined schedulers -
# @yearly (or @annually) | Run once a year, midnight, Jan. 1st | 0 0 0 1 1 *
# @monthly | Run once a month, midnight, first of month | 0 0 0 1 * *
# @weekly | Run once a week, midnight between Sat/Sun | 0 0 0 * * 0
# @daily (or @midnight) | Run once a day, midnight | 0 0 0 * * *
# @hourly | Run once an hour, beginning of hour | 0 0 * * * *
sync_cron = "0 0 1 * * *" # This is default value (At 1 am every day)
# This cron expression format uses 6 space-separated fields (including seconds), for example
# sync_cron = "* */10 * * * *"
# This will run the LDAP Synchronization every 10th minute, which is also the minimal interval between the Grafana sync times i.e. you cannot set it for every 9th minute
# You can also disable active LDAP synchronization
active_sync_enabled = true # enabled by default
```
Single bind configuration (as in the [Single bind example]({{< relref "../auth/ldap.md#single-bind-example">}})) is not supported with active LDAP synchronization because Grafana needs user information to perform LDAP searches.
| docs/sources/enterprise/enhanced_ldap.md | 0 | https://github.com/grafana/grafana/commit/8c35ed40147946c36ae318b54cfe29275553ceea | [
0.00016655586659908295,
0.00016497606702614576,
0.00016342605522368103,
0.0001649622427066788,
0.0000011408050113459467
] |
{
"id": 4,
"code_window": [
" value: 13,\n",
" },\n",
" {\n",
" timestamp: 1610449070300,\n",
" value: 20,\n",
" },\n",
" ],\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" timestamp: 1610449070.3,\n"
],
"file_path": "public/app/plugins/datasource/prometheus/result_transformer.test.ts",
"type": "replace",
"edit_start_line_idx": 531
} | package sqlstore
import (
"time"
"github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/util"
)
func init() {
bus.AddHandler("sql", GetPluginSettings)
bus.AddHandler("sql", GetPluginSettingById)
bus.AddHandler("sql", UpdatePluginSetting)
bus.AddHandler("sql", UpdatePluginSettingVersion)
}
func GetPluginSettings(query *models.GetPluginSettingsQuery) error {
sql := `SELECT org_id, plugin_id, enabled, pinned, plugin_version
FROM plugin_setting `
params := make([]interface{}, 0)
if query.OrgId != 0 {
sql += "WHERE org_id=?"
params = append(params, query.OrgId)
}
sess := x.SQL(sql, params...)
query.Result = make([]*models.PluginSettingInfoDTO, 0)
return sess.Find(&query.Result)
}
func GetPluginSettingById(query *models.GetPluginSettingByIdQuery) error {
pluginSetting := models.PluginSetting{OrgId: query.OrgId, PluginId: query.PluginId}
has, err := x.Get(&pluginSetting)
if err != nil {
return err
} else if !has {
return models.ErrPluginSettingNotFound
}
query.Result = &pluginSetting
return nil
}
func UpdatePluginSetting(cmd *models.UpdatePluginSettingCmd) error {
return inTransaction(func(sess *DBSession) error {
var pluginSetting models.PluginSetting
exists, err := sess.Where("org_id=? and plugin_id=?", cmd.OrgId, cmd.PluginId).Get(&pluginSetting)
if err != nil {
return err
}
sess.UseBool("enabled")
sess.UseBool("pinned")
if !exists {
pluginSetting = models.PluginSetting{
PluginId: cmd.PluginId,
OrgId: cmd.OrgId,
Enabled: cmd.Enabled,
Pinned: cmd.Pinned,
JsonData: cmd.JsonData,
PluginVersion: cmd.PluginVersion,
SecureJsonData: cmd.GetEncryptedJsonData(),
Created: time.Now(),
Updated: time.Now(),
}
// add state change event on commit success
sess.events = append(sess.events, &models.PluginStateChangedEvent{
PluginId: cmd.PluginId,
OrgId: cmd.OrgId,
Enabled: cmd.Enabled,
})
_, err = sess.Insert(&pluginSetting)
return err
}
for key, data := range cmd.SecureJsonData {
encryptedData, err := util.Encrypt([]byte(data), setting.SecretKey)
if err != nil {
return err
}
pluginSetting.SecureJsonData[key] = encryptedData
}
// add state change event on commit success
if pluginSetting.Enabled != cmd.Enabled {
sess.events = append(sess.events, &models.PluginStateChangedEvent{
PluginId: cmd.PluginId,
OrgId: cmd.OrgId,
Enabled: cmd.Enabled,
})
}
pluginSetting.Updated = time.Now()
pluginSetting.Enabled = cmd.Enabled
pluginSetting.JsonData = cmd.JsonData
pluginSetting.Pinned = cmd.Pinned
pluginSetting.PluginVersion = cmd.PluginVersion
_, err = sess.ID(pluginSetting.Id).Update(&pluginSetting)
return err
})
}
func UpdatePluginSettingVersion(cmd *models.UpdatePluginSettingVersionCmd) error {
return inTransaction(func(sess *DBSession) error {
_, err := sess.Exec("UPDATE plugin_setting SET plugin_version=? WHERE org_id=? AND plugin_id=?", cmd.PluginVersion, cmd.OrgId, cmd.PluginId)
return err
})
}
| pkg/services/sqlstore/plugin_setting.go | 0 | https://github.com/grafana/grafana/commit/8c35ed40147946c36ae318b54cfe29275553ceea | [
0.00020097600645385683,
0.00017312481941189617,
0.00016271266213152558,
0.00016973486344795674,
0.000011384674508008175
] |
{
"id": 4,
"code_window": [
" value: 13,\n",
" },\n",
" {\n",
" timestamp: 1610449070300,\n",
" value: 20,\n",
" },\n",
" ],\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" timestamp: 1610449070.3,\n"
],
"file_path": "public/app/plugins/datasource/prometheus/result_transformer.test.ts",
"type": "replace",
"edit_start_line_idx": 531
} | test/cypress/report.json
test/cypress/screenshots/actual
test/cypress/videos/
| packages/grafana-e2e/.gitignore | 0 | https://github.com/grafana/grafana/commit/8c35ed40147946c36ae318b54cfe29275553ceea | [
0.0001694223756203428,
0.0001694223756203428,
0.0001694223756203428,
0.0001694223756203428,
0
] |
{
"id": 5,
"code_window": [
" const events: TimeAndValue[] = [];\n",
" prometheusResult.forEach((exemplarData) => {\n",
" const data = exemplarData.exemplars.map((exemplar) => {\n",
" return {\n",
" [TIME_SERIES_TIME_FIELD_NAME]: exemplar.timestamp,\n",
" [TIME_SERIES_VALUE_FIELD_NAME]: exemplar.value,\n",
" ...exemplar.labels,\n",
" ...exemplarData.seriesLabels,\n",
" };\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" [TIME_SERIES_TIME_FIELD_NAME]: exemplar.timestamp * 1000,\n"
],
"file_path": "public/app/plugins/datasource/prometheus/result_transformer.ts",
"type": "replace",
"edit_start_line_idx": 80
} | import {
ArrayDataFrame,
ArrayVector,
DataFrame,
DataLink,
DataTopic,
Field,
FieldType,
formatLabels,
getDisplayProcessor,
Labels,
MutableField,
ScopedVars,
TIME_SERIES_TIME_FIELD_NAME,
TIME_SERIES_VALUE_FIELD_NAME,
} from '@grafana/data';
import { FetchResponse, getDataSourceSrv, getTemplateSrv } from '@grafana/runtime';
import { descending, deviation } from 'd3';
import {
ExemplarTraceIdDestination,
isExemplarData,
isMatrixData,
MatrixOrVectorResult,
PromDataSuccessResponse,
PromMetric,
PromQuery,
PromQueryRequest,
PromValue,
TransformOptions,
} from './types';
const POSITIVE_INFINITY_SAMPLE_VALUE = '+Inf';
const NEGATIVE_INFINITY_SAMPLE_VALUE = '-Inf';
interface TimeAndValue {
[TIME_SERIES_TIME_FIELD_NAME]: number;
[TIME_SERIES_VALUE_FIELD_NAME]: number;
}
export function transform(
response: FetchResponse<PromDataSuccessResponse>,
transformOptions: {
query: PromQueryRequest;
exemplarTraceIdDestinations?: ExemplarTraceIdDestination[];
target: PromQuery;
responseListLength: number;
scopedVars?: ScopedVars;
mixedQueries?: boolean;
}
) {
// Create options object from transformOptions
const options: TransformOptions = {
format: transformOptions.target.format,
step: transformOptions.query.step,
legendFormat: transformOptions.target.legendFormat,
start: transformOptions.query.start,
end: transformOptions.query.end,
query: transformOptions.query.expr,
responseListLength: transformOptions.responseListLength,
scopedVars: transformOptions.scopedVars,
refId: transformOptions.target.refId,
valueWithRefId: transformOptions.target.valueWithRefId,
meta: {
/**
* Fix for showing of Prometheus results in Explore table.
* We want to show result of instant query always in table and result of range query based on target.runAll;
*/
preferredVisualisationType: getPreferredVisualisationType(
transformOptions.query.instant,
transformOptions.mixedQueries
),
},
};
const prometheusResult = response.data.data;
if (isExemplarData(prometheusResult)) {
const events: TimeAndValue[] = [];
prometheusResult.forEach((exemplarData) => {
const data = exemplarData.exemplars.map((exemplar) => {
return {
[TIME_SERIES_TIME_FIELD_NAME]: exemplar.timestamp,
[TIME_SERIES_VALUE_FIELD_NAME]: exemplar.value,
...exemplar.labels,
...exemplarData.seriesLabels,
};
});
events.push(...data);
});
// Grouping exemplars by step
const sampledExemplars = sampleExemplars(events, options);
const dataFrame = new ArrayDataFrame(sampledExemplars);
dataFrame.meta = { dataTopic: DataTopic.Annotations };
// Add data links if configured
if (transformOptions.exemplarTraceIdDestinations?.length) {
for (const exemplarTraceIdDestination of transformOptions.exemplarTraceIdDestinations) {
const traceIDField = dataFrame.fields.find((field) => field.name === exemplarTraceIdDestination!.name);
if (traceIDField) {
const links = getDataLinks(exemplarTraceIdDestination);
traceIDField.config.links = traceIDField.config.links?.length
? [...traceIDField.config.links, ...links]
: links;
}
}
}
return [dataFrame];
}
if (!prometheusResult?.result) {
return [];
}
// Return early if result type is scalar
if (prometheusResult.resultType === 'scalar') {
return [
{
meta: options.meta,
refId: options.refId,
length: 1,
fields: [getTimeField([prometheusResult.result]), getValueField({ data: [prometheusResult.result] })],
},
];
}
// Return early again if the format is table, this needs special transformation.
if (options.format === 'table') {
const tableData = transformMetricDataToTable(prometheusResult.result, options);
return [tableData];
}
// Process matrix and vector results to DataFrame
const dataFrame: DataFrame[] = [];
prometheusResult.result.forEach((data: MatrixOrVectorResult) => dataFrame.push(transformToDataFrame(data, options)));
// When format is heatmap use the already created data frames and transform it more
if (options.format === 'heatmap') {
dataFrame.sort(sortSeriesByLabel);
const seriesList = transformToHistogramOverTime(dataFrame);
return seriesList;
}
// Return matrix or vector result as DataFrame[]
return dataFrame;
}
function getDataLinks(options: ExemplarTraceIdDestination): DataLink[] {
const dataLinks: DataLink[] = [];
if (options.datasourceUid) {
const dataSourceSrv = getDataSourceSrv();
const dsSettings = dataSourceSrv.getInstanceSettings(options.datasourceUid);
dataLinks.push({
title: `Query with ${dsSettings?.name}`,
url: '',
internal: {
query: { query: '${__value.raw}', queryType: 'getTrace' },
datasourceUid: options.datasourceUid,
datasourceName: dsSettings?.name ?? 'Data source not found',
},
});
}
if (options.url) {
dataLinks.push({
title: `Go to ${options.url}`,
url: options.url,
targetBlank: true,
});
}
return dataLinks;
}
/**
* Reduce the density of the exemplars by making sure that the highest value exemplar is included
* and then only the ones that are 2 times the standard deviation of the all the values.
* This makes sure not to show too many dots near each other.
*/
function sampleExemplars(events: TimeAndValue[], options: TransformOptions) {
const step = options.step || 15;
const bucketedExemplars: { [ts: string]: TimeAndValue[] } = {};
const values: number[] = [];
for (const exemplar of events) {
// Align exemplar timestamp to nearest step second
const alignedTs = String(Math.floor(exemplar[TIME_SERIES_TIME_FIELD_NAME] / 1000 / step) * step * 1000);
if (!bucketedExemplars[alignedTs]) {
// New bucket found
bucketedExemplars[alignedTs] = [];
}
bucketedExemplars[alignedTs].push(exemplar);
values.push(exemplar[TIME_SERIES_VALUE_FIELD_NAME]);
}
// Getting exemplars from each bucket
const standardDeviation = deviation(values);
const sampledBuckets = Object.keys(bucketedExemplars).sort();
const sampledExemplars = [];
for (const ts of sampledBuckets) {
const exemplarsInBucket = bucketedExemplars[ts];
if (exemplarsInBucket.length === 1) {
sampledExemplars.push(exemplarsInBucket[0]);
} else {
// Choose which values to sample
const bucketValues = exemplarsInBucket.map((ex) => ex[TIME_SERIES_VALUE_FIELD_NAME]).sort(descending);
const sampledBucketValues = bucketValues.reduce((acc: number[], curr) => {
if (acc.length === 0) {
// First value is max and is always added
acc.push(curr);
} else {
// Then take values only when at least 2 standard deviation distance to previously taken value
const prev = acc[acc.length - 1];
if (standardDeviation && prev - curr >= 2 * standardDeviation) {
acc.push(curr);
}
}
return acc;
}, []);
// Find the exemplars for the sampled values
sampledExemplars.push(
...sampledBucketValues.map(
(value) => exemplarsInBucket.find((ex) => ex[TIME_SERIES_VALUE_FIELD_NAME] === value)!
)
);
}
}
return sampledExemplars;
}
function getPreferredVisualisationType(isInstantQuery?: boolean, mixedQueries?: boolean) {
if (isInstantQuery) {
return 'table';
}
return mixedQueries ? 'graph' : undefined;
}
/**
* Transforms matrix and vector result from Prometheus result to DataFrame
*/
function transformToDataFrame(data: MatrixOrVectorResult, options: TransformOptions): DataFrame {
const { name, labels } = createLabelInfo(data.metric, options);
const fields: Field[] = [];
if (isMatrixData(data)) {
const stepMs = options.step ? options.step * 1000 : NaN;
let baseTimestamp = options.start * 1000;
const dps: PromValue[] = [];
for (const value of data.values) {
let dpValue: number | null = parseSampleValue(value[1]);
if (isNaN(dpValue)) {
dpValue = null;
}
const timestamp = value[0] * 1000;
for (let t = baseTimestamp; t < timestamp; t += stepMs) {
dps.push([t, null]);
}
baseTimestamp = timestamp + stepMs;
dps.push([timestamp, dpValue]);
}
const endTimestamp = options.end * 1000;
for (let t = baseTimestamp; t <= endTimestamp; t += stepMs) {
dps.push([t, null]);
}
fields.push(getTimeField(dps, true));
fields.push(getValueField({ data: dps, parseValue: false, labels, displayNameFromDS: name }));
} else {
fields.push(getTimeField([data.value]));
fields.push(getValueField({ data: [data.value], labels, displayNameFromDS: name }));
}
return {
meta: options.meta,
refId: options.refId,
length: fields[0].values.length,
fields,
name,
};
}
function transformMetricDataToTable(md: MatrixOrVectorResult[], options: TransformOptions): DataFrame {
if (!md || md.length === 0) {
return {
meta: options.meta,
refId: options.refId,
length: 0,
fields: [],
};
}
const valueText = options.responseListLength > 1 || options.valueWithRefId ? `Value #${options.refId}` : 'Value';
const timeField = getTimeField([]);
const metricFields = Object.keys(md.reduce((acc, series) => ({ ...acc, ...series.metric }), {}))
.sort()
.map((label) => {
// Labels have string field type, otherwise table tries to figure out the type which can result in unexpected results
// Only "le" label has a number field type
const numberField = label === 'le';
return {
name: label,
config: { filterable: true },
type: numberField ? FieldType.number : FieldType.string,
values: new ArrayVector(),
};
});
const valueField = getValueField({ data: [], valueName: valueText });
md.forEach((d) => {
if (isMatrixData(d)) {
d.values.forEach((val) => {
timeField.values.add(val[0] * 1000);
metricFields.forEach((metricField) => metricField.values.add(getLabelValue(d.metric, metricField.name)));
valueField.values.add(parseSampleValue(val[1]));
});
} else {
timeField.values.add(d.value[0] * 1000);
metricFields.forEach((metricField) => metricField.values.add(getLabelValue(d.metric, metricField.name)));
valueField.values.add(parseSampleValue(d.value[1]));
}
});
return {
meta: options.meta,
refId: options.refId,
length: timeField.values.length,
fields: [timeField, ...metricFields, valueField],
};
}
function getLabelValue(metric: PromMetric, label: string): string | number {
if (metric.hasOwnProperty(label)) {
if (label === 'le') {
return parseSampleValue(metric[label]);
}
return metric[label];
}
return '';
}
function getTimeField(data: PromValue[], isMs = false): MutableField {
return {
name: TIME_SERIES_TIME_FIELD_NAME,
type: FieldType.time,
config: {},
values: new ArrayVector<number>(data.map((val) => (isMs ? val[0] : val[0] * 1000))),
};
}
type ValueFieldOptions = {
data: PromValue[];
valueName?: string;
parseValue?: boolean;
labels?: Labels;
displayNameFromDS?: string;
};
function getValueField({
data,
valueName = TIME_SERIES_VALUE_FIELD_NAME,
parseValue = true,
labels,
displayNameFromDS,
}: ValueFieldOptions): MutableField {
return {
name: valueName,
type: FieldType.number,
display: getDisplayProcessor(),
config: {
displayNameFromDS,
},
labels,
values: new ArrayVector<number | null>(data.map((val) => (parseValue ? parseSampleValue(val[1]) : val[1]))),
};
}
function createLabelInfo(labels: { [key: string]: string }, options: TransformOptions) {
if (options?.legendFormat) {
const title = renderTemplate(getTemplateSrv().replace(options.legendFormat, options?.scopedVars), labels);
return { name: title, labels };
}
const { __name__, ...labelsWithoutName } = labels;
const labelPart = formatLabels(labelsWithoutName);
let title = `${__name__ ?? ''}${labelPart}`;
if (!title) {
title = options.query;
}
return { name: title, labels: labelsWithoutName };
}
export function getOriginalMetricName(labelData: { [key: string]: string }) {
const metricName = labelData.__name__ || '';
delete labelData.__name__;
const labelPart = Object.entries(labelData)
.map((label) => `${label[0]}="${label[1]}"`)
.join(',');
return `${metricName}{${labelPart}}`;
}
export function renderTemplate(aliasPattern: string, aliasData: { [key: string]: string }) {
const aliasRegex = /\{\{\s*(.+?)\s*\}\}/g;
return aliasPattern.replace(aliasRegex, (_match, g1) => {
if (aliasData[g1]) {
return aliasData[g1];
}
return '';
});
}
function transformToHistogramOverTime(seriesList: DataFrame[]) {
/* t1 = timestamp1, t2 = timestamp2 etc.
t1 t2 t3 t1 t2 t3
le10 10 10 0 => 10 10 0
le20 20 10 30 => 10 0 30
le30 30 10 35 => 10 0 5
*/
for (let i = seriesList.length - 1; i > 0; i--) {
const topSeries = seriesList[i].fields.find((s) => s.name === TIME_SERIES_VALUE_FIELD_NAME);
const bottomSeries = seriesList[i - 1].fields.find((s) => s.name === TIME_SERIES_VALUE_FIELD_NAME);
if (!topSeries || !bottomSeries) {
throw new Error('Prometheus heatmap transform error: data should be a time series');
}
for (let j = 0; j < topSeries.values.length; j++) {
const bottomPoint = bottomSeries.values.get(j) || [0];
topSeries.values.toArray()[j] -= bottomPoint;
}
}
return seriesList;
}
function sortSeriesByLabel(s1: DataFrame, s2: DataFrame): number {
let le1, le2;
try {
// fail if not integer. might happen with bad queries
le1 = parseSampleValue(s1.name ?? '');
le2 = parseSampleValue(s2.name ?? '');
} catch (err) {
console.error(err);
return 0;
}
if (le1 > le2) {
return 1;
}
if (le1 < le2) {
return -1;
}
return 0;
}
function parseSampleValue(value: string): number {
switch (value) {
case POSITIVE_INFINITY_SAMPLE_VALUE:
return Number.POSITIVE_INFINITY;
case NEGATIVE_INFINITY_SAMPLE_VALUE:
return Number.NEGATIVE_INFINITY;
default:
return parseFloat(value);
}
}
| public/app/plugins/datasource/prometheus/result_transformer.ts | 1 | https://github.com/grafana/grafana/commit/8c35ed40147946c36ae318b54cfe29275553ceea | [
0.9978347420692444,
0.043155770748853683,
0.00016518715710844845,
0.0001882751821540296,
0.19902323186397552
] |
{
"id": 5,
"code_window": [
" const events: TimeAndValue[] = [];\n",
" prometheusResult.forEach((exemplarData) => {\n",
" const data = exemplarData.exemplars.map((exemplar) => {\n",
" return {\n",
" [TIME_SERIES_TIME_FIELD_NAME]: exemplar.timestamp,\n",
" [TIME_SERIES_VALUE_FIELD_NAME]: exemplar.value,\n",
" ...exemplar.labels,\n",
" ...exemplarData.seriesLabels,\n",
" };\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" [TIME_SERIES_TIME_FIELD_NAME]: exemplar.timestamp * 1000,\n"
],
"file_path": "public/app/plugins/datasource/prometheus/result_transformer.ts",
"type": "replace",
"edit_start_line_idx": 80
} | import { EchoBackend, EchoMeta, EchoEvent, EchoSrv } from '@grafana/runtime';
import { contextSrv } from '../context_srv';
interface EchoConfig {
// How often should metrics be reported
flushInterval: number;
// Enables debug mode
debug: boolean;
}
/**
* Echo is a service for collecting events from Grafana client-app
* It collects events, distributes them across registered backend and flushes once per configured interval
* It's up to the registered backend to decide what to do with a given type of metric
*/
export class Echo implements EchoSrv {
private config: EchoConfig = {
flushInterval: 10000, // By default Echo flushes every 10s
debug: false,
};
private backends: EchoBackend[] = [];
// meta data added to every event collected
constructor(config?: Partial<EchoConfig>) {
this.config = {
...this.config,
...config,
};
setInterval(this.flush, this.config.flushInterval);
}
logDebug = (...msg: any) => {
if (this.config.debug) {
// eslint-disable-next-line
// console.debug('ECHO:', ...msg);
}
};
flush = () => {
for (const backend of this.backends) {
backend.flush();
}
};
addBackend = (backend: EchoBackend) => {
this.logDebug('Adding backend', backend);
this.backends.push(backend);
};
addEvent = <T extends EchoEvent>(event: Omit<T, 'meta'>, _meta?: {}) => {
const meta = this.getMeta();
const _event = {
...event,
meta: {
...meta,
..._meta,
},
};
for (const backend of this.backends) {
if (backend.supportedEvents.length === 0 || backend.supportedEvents.indexOf(_event.type) > -1) {
backend.addEvent(_event);
}
}
this.logDebug('Adding event', _event);
};
getMeta = (): EchoMeta => {
return {
sessionId: '',
userId: contextSrv.user.id,
userLogin: contextSrv.user.login,
userSignedIn: contextSrv.user.isSignedIn,
screenSize: {
width: window.innerWidth,
height: window.innerHeight,
},
windowSize: {
width: window.screen.width,
height: window.screen.height,
},
userAgent: window.navigator.userAgent,
ts: new Date().getTime(),
timeSinceNavigationStart: performance.now(),
url: window.location.href,
};
};
}
| public/app/core/services/echo/Echo.ts | 0 | https://github.com/grafana/grafana/commit/8c35ed40147946c36ae318b54cfe29275553ceea | [
0.00017429504077881575,
0.00017031084280461073,
0.0001622251293156296,
0.00017191175720654428,
0.000003881552402162924
] |
{
"id": 5,
"code_window": [
" const events: TimeAndValue[] = [];\n",
" prometheusResult.forEach((exemplarData) => {\n",
" const data = exemplarData.exemplars.map((exemplar) => {\n",
" return {\n",
" [TIME_SERIES_TIME_FIELD_NAME]: exemplar.timestamp,\n",
" [TIME_SERIES_VALUE_FIELD_NAME]: exemplar.value,\n",
" ...exemplar.labels,\n",
" ...exemplarData.seriesLabels,\n",
" };\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" [TIME_SERIES_TIME_FIELD_NAME]: exemplar.timestamp * 1000,\n"
],
"file_path": "public/app/plugins/datasource/prometheus/result_transformer.ts",
"type": "replace",
"edit_start_line_idx": 80
} | // ==========================================================================
// FILTER TABLE
// ==========================================================================
// Table
// --------------------------------------------------------------------------
.filter-table * {
box-sizing: border-box;
}
.filter-table {
width: 100%;
border-collapse: separate;
tbody {
tr:nth-child(odd) {
background: $table-bg-odd;
}
}
th {
width: auto;
padding: $space-inset-squish-md;
text-align: left;
line-height: 30px;
height: 30px;
white-space: nowrap;
}
td {
padding: $space-inset-squish-md;
line-height: 30px;
height: 30px;
white-space: nowrap;
&.filter-table__switch-cell {
padding: 0;
border-right: 3px solid $page-bg;
}
}
.link-td {
padding: 0;
line-height: 30px;
height: 30px;
white-space: nowrap;
&.filter-table__switch-cell {
padding: 0;
border-right: 3px solid $page-bg;
}
a {
display: block;
padding: $space-inset-squish-md;
}
}
.ellipsis {
display: block;
width: 100%;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.expanded {
border-color: $panel-bg;
}
.expanded > td {
padding-bottom: 0;
}
.filter-table__avatar {
width: 25px;
height: 25px;
border-radius: 50%;
}
&--hover {
tbody tr:hover {
background: $table-bg-hover;
}
}
}
.filter-table__weak-italic {
font-style: italic;
color: $text-color-weak;
}
| public/sass/components/_filter-table.scss | 0 | https://github.com/grafana/grafana/commit/8c35ed40147946c36ae318b54cfe29275553ceea | [
0.00017696672875899822,
0.00017423501412849873,
0.0001691100769676268,
0.0001747786591295153,
0.0000023068091650202405
] |
{
"id": 5,
"code_window": [
" const events: TimeAndValue[] = [];\n",
" prometheusResult.forEach((exemplarData) => {\n",
" const data = exemplarData.exemplars.map((exemplar) => {\n",
" return {\n",
" [TIME_SERIES_TIME_FIELD_NAME]: exemplar.timestamp,\n",
" [TIME_SERIES_VALUE_FIELD_NAME]: exemplar.value,\n",
" ...exemplar.labels,\n",
" ...exemplarData.seriesLabels,\n",
" };\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" [TIME_SERIES_TIME_FIELD_NAME]: exemplar.timestamp * 1000,\n"
],
"file_path": "public/app/plugins/datasource/prometheus/result_transformer.ts",
"type": "replace",
"edit_start_line_idx": 80
} | import React, { PureComponent } from 'react';
import { hot } from 'react-hot-loader';
import { connect } from 'react-redux';
import { NavModel } from '@grafana/data';
import { Alert, LegacyForms } from '@grafana/ui';
const { FormField } = LegacyForms;
import { getNavModel } from 'app/core/selectors/navModel';
import config from 'app/core/config';
import Page from 'app/core/components/Page/Page';
import { LdapConnectionStatus } from './LdapConnectionStatus';
import { LdapSyncInfo } from './LdapSyncInfo';
import { LdapUserInfo } from './LdapUserInfo';
import { AppNotificationSeverity, LdapError, LdapUser, StoreState, SyncInfo, LdapConnectionInfo } from 'app/types';
import {
loadLdapState,
loadLdapSyncStatus,
loadUserMapping,
clearUserError,
clearUserMappingInfo,
} from '../state/actions';
interface Props {
navModel: NavModel;
ldapConnectionInfo: LdapConnectionInfo;
ldapUser: LdapUser;
ldapSyncInfo: SyncInfo;
ldapError: LdapError;
userError?: LdapError;
username?: string;
loadLdapState: typeof loadLdapState;
loadLdapSyncStatus: typeof loadLdapSyncStatus;
loadUserMapping: typeof loadUserMapping;
clearUserError: typeof clearUserError;
clearUserMappingInfo: typeof clearUserMappingInfo;
}
interface State {
isLoading: boolean;
}
export class LdapPage extends PureComponent<Props, State> {
state = {
isLoading: true,
};
async componentDidMount() {
const { username, clearUserMappingInfo, loadUserMapping } = this.props;
await clearUserMappingInfo();
await this.fetchLDAPStatus();
if (username) {
await loadUserMapping(username);
}
this.setState({ isLoading: false });
}
async fetchLDAPStatus() {
const { loadLdapState, loadLdapSyncStatus } = this.props;
return Promise.all([loadLdapState(), loadLdapSyncStatus()]);
}
async fetchUserMapping(username: string) {
const { loadUserMapping } = this.props;
return await loadUserMapping(username);
}
search = (event: any) => {
event.preventDefault();
const username = event.target.elements['username'].value;
if (username) {
this.fetchUserMapping(username);
}
};
onClearUserError = () => {
this.props.clearUserError();
};
render() {
const { ldapUser, userError, ldapError, ldapSyncInfo, ldapConnectionInfo, navModel, username } = this.props;
const { isLoading } = this.state;
return (
<Page navModel={navModel}>
<Page.Contents isLoading={isLoading}>
<>
{ldapError && ldapError.title && (
<div className="gf-form-group">
<Alert title={ldapError.title} severity={AppNotificationSeverity.Error}>
{ldapError.body}
</Alert>
</div>
)}
<LdapConnectionStatus ldapConnectionInfo={ldapConnectionInfo} />
{config.licenseInfo.hasLicense && ldapSyncInfo && <LdapSyncInfo ldapSyncInfo={ldapSyncInfo} />}
<h3 className="page-heading">Test user mapping</h3>
<div className="gf-form-group">
<form onSubmit={this.search} className="gf-form-inline">
<FormField
label="Username"
labelWidth={8}
inputWidth={30}
type="text"
id="username"
name="username"
defaultValue={username}
/>
<button type="submit" className="btn btn-primary">
Run
</button>
</form>
</div>
{userError && userError.title && (
<div className="gf-form-group">
<Alert
title={userError.title}
severity={AppNotificationSeverity.Error}
onRemove={this.onClearUserError}
>
{userError.body}
</Alert>
</div>
)}
{ldapUser && <LdapUserInfo ldapUser={ldapUser} showAttributeMapping={true} />}
</>
</Page.Contents>
</Page>
);
}
}
const mapStateToProps = (state: StoreState) => ({
navModel: getNavModel(state.navIndex, 'ldap'),
username: state.location.routeParams.user,
ldapConnectionInfo: state.ldap.connectionInfo,
ldapUser: state.ldap.user,
ldapSyncInfo: state.ldap.syncInfo,
userError: state.ldap.userError,
ldapError: state.ldap.ldapError,
});
const mapDispatchToProps = {
loadLdapState,
loadLdapSyncStatus,
loadUserMapping,
clearUserError,
clearUserMappingInfo,
};
export default hot(module)(connect(mapStateToProps, mapDispatchToProps)(LdapPage));
| public/app/features/admin/ldap/LdapPage.tsx | 0 | https://github.com/grafana/grafana/commit/8c35ed40147946c36ae318b54cfe29275553ceea | [
0.00017821777146309614,
0.00017294127610512078,
0.0001675127714406699,
0.00017296193982474506,
0.0000024637533897475805
] |
{
"id": 0,
"code_window": [
"# playwright-chromium\n",
"This packagage contains the [Chromium](https://www.chromium.org/) flavor of [Playwright](http://github.com/microsoft/playwright).\n"
],
"labels": [
"keep",
"replace"
],
"after_edit": [
"This package contains the [Chromium](https://www.chromium.org/) flavor of [Playwright](http://github.com/microsoft/playwright)."
],
"file_path": "packages/playwright-chromium/README.md",
"type": "replace",
"edit_start_line_idx": 1
} | # playwright-webkit
This packagage contains the [WebKit](https://www.webkit.org/) flavor of [Playwright](http://github.com/microsoft/playwright).
| packages/playwright-webkit/README.md | 1 | https://github.com/microsoft/playwright/commit/ff302354bbf69c7bbb1ad94fd347c32855fb492f | [
0.0327586755156517,
0.0327586755156517,
0.0327586755156517,
0.0327586755156517,
0
] |
{
"id": 0,
"code_window": [
"# playwright-chromium\n",
"This packagage contains the [Chromium](https://www.chromium.org/) flavor of [Playwright](http://github.com/microsoft/playwright).\n"
],
"labels": [
"keep",
"replace"
],
"after_edit": [
"This package contains the [Chromium](https://www.chromium.org/) flavor of [Playwright](http://github.com/microsoft/playwright)."
],
"file_path": "packages/playwright-chromium/README.md",
"type": "replace",
"edit_start_line_idx": 1
} | <style>
@charset "utf-8";
@namespace svg url(http://www.w3.org/2000/svg);
@font-face {
font-family: "Example Font";
src: url("./Dosis-Regular.ttf");
}
#fluffy {
border: 1px solid black;
z-index: 1;
/* -webkit-disabled-property: rgb(1, 2, 3) */
-lol-cats: "dogs" /* non-existing property */
}
@media (min-width: 1px) {
span {
-webkit-border-radius: 10px;
font-family: "Example Font";
animation: 1s identifier;
}
}
</style>
<div id="fluffy">woof!</div>
<span>fancy text</span>
| test/assets/csscoverage/involved.html | 0 | https://github.com/microsoft/playwright/commit/ff302354bbf69c7bbb1ad94fd347c32855fb492f | [
0.0001691347424639389,
0.00016824505291879177,
0.00016775555559433997,
0.00016784484614618123,
6.301641519712575e-7
] |
{
"id": 0,
"code_window": [
"# playwright-chromium\n",
"This packagage contains the [Chromium](https://www.chromium.org/) flavor of [Playwright](http://github.com/microsoft/playwright).\n"
],
"labels": [
"keep",
"replace"
],
"after_edit": [
"This package contains the [Chromium](https://www.chromium.org/) flavor of [Playwright](http://github.com/microsoft/playwright)."
],
"file_path": "packages/playwright-chromium/README.md",
"type": "replace",
"edit_start_line_idx": 1
} | # this ignores everything by default, except for package.json and LICENSE and README.md
# see https://docs.npmjs.com/misc/developers
**/*
# include sources from lib except for injected, but not map files
!lib/**/*.js
# Injected files are included via lib/generated, see src/injected/README.md
lib/injected/
#types
!lib/**/*.d.ts
!index.d.ts
# used for npm install scripts
!download-browser.js
# root for "playwright-core" package
!index.js
# root for "playwright-core/web"
!web.js
| .npmignore | 0 | https://github.com/microsoft/playwright/commit/ff302354bbf69c7bbb1ad94fd347c32855fb492f | [
0.00020178110571578145,
0.00017852654855232686,
0.0001637434761505574,
0.00017005503468681127,
0.000016644120478304103
] |
{
"id": 0,
"code_window": [
"# playwright-chromium\n",
"This packagage contains the [Chromium](https://www.chromium.org/) flavor of [Playwright](http://github.com/microsoft/playwright).\n"
],
"labels": [
"keep",
"replace"
],
"after_edit": [
"This package contains the [Chromium](https://www.chromium.org/) flavor of [Playwright](http://github.com/microsoft/playwright)."
],
"file_path": "packages/playwright-chromium/README.md",
"type": "replace",
"edit_start_line_idx": 1
} | /**
* Copyright 2017 Google Inc. All rights reserved.
* Modifications copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { Page } from './page';
import * as network from './network';
import * as types from './types';
import { helper } from './helper';
export interface BrowserContextDelegate {
pages(): Promise<Page[]>;
existingPages(): Page[];
newPage(): Promise<Page>;
close(): Promise<void>;
cookies(): Promise<network.NetworkCookie[]>;
setCookies(cookies: network.SetNetworkCookieParam[]): Promise<void>;
clearCookies(): Promise<void>;
setPermissions(origin: string, permissions: string[]): Promise<void>;
clearPermissions(): Promise<void>;
setGeolocation(geolocation: types.Geolocation | null): Promise<void>;
}
export type BrowserContextOptions = {
viewport?: types.Viewport | null,
ignoreHTTPSErrors?: boolean,
javaScriptEnabled?: boolean,
bypassCSP?: boolean,
userAgent?: string,
timezoneId?: string,
geolocation?: types.Geolocation,
permissions?: { [key: string]: string[] };
};
export class BrowserContext {
private readonly _delegate: BrowserContextDelegate;
readonly _options: BrowserContextOptions;
private _closed = false;
constructor(delegate: BrowserContextDelegate, options: BrowserContextOptions) {
this._delegate = delegate;
this._options = { ...options };
if (!this._options.viewport && this._options.viewport !== null)
this._options.viewport = { width: 800, height: 600 };
if (this._options.viewport)
this._options.viewport = { ...this._options.viewport };
if (this._options.geolocation)
this._options.geolocation = verifyGeolocation(this._options.geolocation);
}
async _initialize() {
const entries = Object.entries(this._options.permissions || {});
await Promise.all(entries.map(entry => this.setPermissions(entry[0], entry[1])));
if (this._options.geolocation)
await this.setGeolocation(this._options.geolocation);
}
_existingPages(): Page[] {
return this._delegate.existingPages();
}
async pages(): Promise<Page[]> {
return this._delegate.pages();
}
async newPage(url?: string): Promise<Page> {
const page = await this._delegate.newPage();
if (url)
await page.goto(url);
return page;
}
async cookies(...urls: string[]): Promise<network.NetworkCookie[]> {
return network.filterCookies(await this._delegate.cookies(), urls);
}
async setCookies(cookies: network.SetNetworkCookieParam[]) {
await this._delegate.setCookies(network.rewriteCookies(cookies));
}
async clearCookies() {
await this._delegate.clearCookies();
}
async setPermissions(origin: string, permissions: string[]): Promise<void> {
await this._delegate.setPermissions(origin, permissions);
}
async clearPermissions() {
await this._delegate.clearPermissions();
}
async setGeolocation(geolocation: types.Geolocation | null): Promise<void> {
if (geolocation)
geolocation = verifyGeolocation(geolocation);
this._options.geolocation = geolocation || undefined;
await this._delegate.setGeolocation(geolocation);
}
async close() {
if (this._closed)
return;
await this._delegate.close();
this._closed = true;
}
static validateOptions(options: BrowserContextOptions) {
if (options.geolocation)
verifyGeolocation(options.geolocation);
}
}
function verifyGeolocation(geolocation: types.Geolocation): types.Geolocation {
const result = { ...geolocation };
result.accuracy = result.accuracy || 0;
const { longitude, latitude, accuracy } = result;
if (!helper.isNumber(longitude) || longitude < -180 || longitude > 180)
throw new Error(`Invalid longitude "${longitude}": precondition -180 <= LONGITUDE <= 180 failed.`);
if (!helper.isNumber(latitude) || latitude < -90 || latitude > 90)
throw new Error(`Invalid latitude "${latitude}": precondition -90 <= LATITUDE <= 90 failed.`);
if (!helper.isNumber(accuracy) || accuracy < 0)
throw new Error(`Invalid accuracy "${accuracy}": precondition 0 <= ACCURACY failed.`);
return result;
}
| src/browserContext.ts | 0 | https://github.com/microsoft/playwright/commit/ff302354bbf69c7bbb1ad94fd347c32855fb492f | [
0.0004047997354064137,
0.00018925884796772152,
0.0001652616774663329,
0.00016747473273426294,
0.00006174934969749302
] |
{
"id": 1,
"code_window": [
"# playwright-firefox\n",
"This packagage contains the [Firefox](https://www.mozilla.org/firefox/) flavor of [Playwright](http://github.com/microsoft/playwright).\n"
],
"labels": [
"keep",
"replace"
],
"after_edit": [
"This package contains the [Firefox](https://www.mozilla.org/firefox/) flavor of [Playwright](http://github.com/microsoft/playwright)."
],
"file_path": "packages/playwright-firefox/README.md",
"type": "replace",
"edit_start_line_idx": 1
} | # playwright-firefox
This packagage contains the [Firefox](https://www.mozilla.org/firefox/) flavor of [Playwright](http://github.com/microsoft/playwright).
| packages/playwright-firefox/README.md | 1 | https://github.com/microsoft/playwright/commit/ff302354bbf69c7bbb1ad94fd347c32855fb492f | [
0.9418522715568542,
0.9418522715568542,
0.9418522715568542,
0.9418522715568542,
0
] |
{
"id": 1,
"code_window": [
"# playwright-firefox\n",
"This packagage contains the [Firefox](https://www.mozilla.org/firefox/) flavor of [Playwright](http://github.com/microsoft/playwright).\n"
],
"labels": [
"keep",
"replace"
],
"after_edit": [
"This package contains the [Firefox](https://www.mozilla.org/firefox/) flavor of [Playwright](http://github.com/microsoft/playwright)."
],
"file_path": "packages/playwright-firefox/README.md",
"type": "replace",
"edit_start_line_idx": 1
} | /**
* Copyright 2018 Google Inc. All rights reserved.
* Modifications copyright (c) Microsoft Corporation.
*
* 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.
*/
module.exports.describe = function({testRunner, expect, FFOX, CHROMIUM, WEBKIT, MAC}) {
const {describe, xdescribe, fdescribe} = testRunner;
const {it, fit, xit, dit} = testRunner;
const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;
describe('Accessibility', function() {
it('should work', async function({page}) {
await page.setContent(`
<head>
<title>Accessibility Test</title>
</head>
<body>
<h1>Inputs</h1>
<input placeholder="Empty input" autofocus />
<input placeholder="readonly input" readonly />
<input placeholder="disabled input" disabled />
<input aria-label="Input with whitespace" value=" " />
<input value="value only" />
<input aria-placeholder="placeholder" value="and a value" />
<div aria-hidden="true" id="desc">This is a description!</div>
<input aria-placeholder="placeholder" value="and a value" aria-describedby="desc" />
</body>`);
// autofocus happens after a delay in chrome these days
await page.waitForFunction(() => document.activeElement.hasAttribute('autofocus'));
const golden = FFOX ? {
role: 'document',
name: 'Accessibility Test',
children: [
{role: 'heading', name: 'Inputs', level: 1},
{role: 'textbox', name: 'Empty input', focused: true},
{role: 'textbox', name: 'readonly input', readonly: true},
{role: 'textbox', name: 'disabled input', disabled: true},
{role: 'textbox', name: 'Input with whitespace', value: ' '},
{role: 'textbox', name: '', value: 'value only'},
{role: 'textbox', name: '', value: 'and a value'}, // firefox doesn't use aria-placeholder for the name
{role: 'textbox', name: '', value: 'and a value', description: 'This is a description!'}, // and here
]
} : CHROMIUM ? {
role: 'WebArea',
name: 'Accessibility Test',
children: [
{role: 'heading', name: 'Inputs', level: 1},
{role: 'textbox', name: 'Empty input', focused: true},
{role: 'textbox', name: 'readonly input', readonly: true},
{role: 'textbox', name: 'disabled input', disabled: true},
{role: 'textbox', name: 'Input with whitespace', value: ' '},
{role: 'textbox', name: '', value: 'value only'},
{role: 'textbox', name: 'placeholder', value: 'and a value'},
{role: 'textbox', name: 'placeholder', value: 'and a value', description: 'This is a description!'},
]
} : {
role: 'WebArea',
name: 'Accessibility Test',
children: [
{role: 'heading', name: 'Inputs', level: 1},
{role: 'textbox', name: 'Empty input', focused: true},
{role: 'textbox', name: 'readonly input', readonly: true},
{role: 'textbox', name: 'disabled input', disabled: true},
{role: 'textbox', name: 'Input with whitespace', value: ' ' },
{role: 'textbox', name: '', value: 'value only' },
{role: 'textbox', name: 'placeholder', value: 'and a value'},
{role: 'textbox', name: 'This is a description!',value: 'and a value'}, // webkit uses the description over placeholder for the name
]
};
expect(await page.accessibility.snapshot()).toEqual(golden);
});
it.skip(WEBKIT && !MAC)('should work with regular text', async({page}) => {
await page.setContent(`<div>Hello World</div>`);
const snapshot = await page.accessibility.snapshot();
expect(snapshot.children[0]).toEqual({
role: FFOX ? 'text leaf' : 'text',
name: 'Hello World',
});
});
it('roledescription', async({page}) => {
await page.setContent('<div tabIndex=-1 aria-roledescription="foo">Hi</div>');
const snapshot = await page.accessibility.snapshot();
expect(snapshot.children[0].roledescription).toEqual('foo');
});
it('orientation', async({page}) => {
await page.setContent('<a href="" role="slider" aria-orientation="vertical">11</a>');
const snapshot = await page.accessibility.snapshot();
expect(snapshot.children[0].orientation).toEqual('vertical');
});
it('autocomplete', async({page}) => {
await page.setContent('<div role="textbox" aria-autocomplete="list">hi</div>');
const snapshot = await page.accessibility.snapshot();
expect(snapshot.children[0].autocomplete).toEqual('list');
});
it('multiselectable', async({page}) => {
await page.setContent('<div role="grid" tabIndex=-1 aria-multiselectable=true>hey</div>');
const snapshot = await page.accessibility.snapshot();
expect(snapshot.children[0].multiselectable).toEqual(true);
});
it('keyshortcuts', async({page}) => {
await page.setContent('<div role="grid" tabIndex=-1 aria-keyshortcuts="foo">hey</div>');
const snapshot = await page.accessibility.snapshot();
expect(snapshot.children[0].keyshortcuts).toEqual('foo');
});
describe('filtering children of leaf nodes', function() {
it('should not report text nodes inside controls', async function({page}) {
await page.setContent(`
<div role="tablist">
<div role="tab" aria-selected="true"><b>Tab1</b></div>
<div role="tab">Tab2</div>
</div>`);
const golden = {
role: FFOX ? 'document' : 'WebArea',
name: '',
children: [{
role: 'tab',
name: 'Tab1',
selected: true
}, {
role: 'tab',
name: 'Tab2'
}]
};
expect(await page.accessibility.snapshot()).toEqual(golden);
});
// WebKit rich text accessibility is iffy
!WEBKIT && it('rich text editable fields should have children', async function({page}) {
await page.setContent(`
<div contenteditable="true">
Edit this image: <img src="fakeimage.png" alt="my fake image">
</div>`);
const golden = FFOX ? {
role: 'section',
name: '',
children: [{
role: 'text leaf',
name: 'Edit this image: '
}, {
role: 'text',
name: 'my fake image'
}]
} : {
role: 'generic',
name: '',
value: 'Edit this image: ',
children: [{
role: 'text',
name: 'Edit this image:'
}, {
role: 'img',
name: 'my fake image'
}]
};
const snapshot = await page.accessibility.snapshot();
expect(snapshot.children[0]).toEqual(golden);
});
// WebKit rich text accessibility is iffy
!WEBKIT && it('rich text editable fields with role should have children', async function({page}) {
await page.setContent(`
<div contenteditable="true" role='textbox'>
Edit this image: <img src="fakeimage.png" alt="my fake image">
</div>`);
const golden = FFOX ? {
role: 'textbox',
name: '',
value: 'Edit this image: my fake image',
children: [{
role: 'text',
name: 'my fake image'
}]
} : {
role: 'textbox',
name: '',
value: 'Edit this image: ',
children: [{
role: 'text',
name: 'Edit this image:'
}, {
role: 'img',
name: 'my fake image'
}]
};
const snapshot = await page.accessibility.snapshot();
expect(snapshot.children[0]).toEqual(golden);
});
// Firefox does not support contenteditable="plaintext-only".
// WebKit rich text accessibility is iffy
!FFOX && !WEBKIT && describe('plaintext contenteditable', function() {
it('plain text field with role should not have children', async function({page}) {
await page.setContent(`
<div contenteditable="plaintext-only" role='textbox'>Edit this image:<img src="fakeimage.png" alt="my fake image"></div>`);
const snapshot = await page.accessibility.snapshot();
expect(snapshot.children[0]).toEqual({
role: 'textbox',
name: '',
value: 'Edit this image:'
});
});
it('plain text field without role should not have content', async function({page}) {
await page.setContent(`
<div contenteditable="plaintext-only">Edit this image:<img src="fakeimage.png" alt="my fake image"></div>`);
const snapshot = await page.accessibility.snapshot();
expect(snapshot.children[0]).toEqual({
role: 'generic',
name: ''
});
});
it('plain text field with tabindex and without role should not have content', async function({page}) {
await page.setContent(`
<div contenteditable="plaintext-only" tabIndex=0>Edit this image:<img src="fakeimage.png" alt="my fake image"></div>`);
const snapshot = await page.accessibility.snapshot();
expect(snapshot.children[0]).toEqual({
role: 'generic',
name: ''
});
});
});
it('non editable textbox with role and tabIndex and label should not have children', async function({page}) {
await page.setContent(`
<div role="textbox" tabIndex=0 aria-checked="true" aria-label="my favorite textbox">
this is the inner content
<img alt="yo" src="fakeimg.png">
</div>`);
const golden = FFOX ? {
role: 'textbox',
name: 'my favorite textbox',
value: 'this is the inner content yo'
} : CHROMIUM ? {
role: 'textbox',
name: 'my favorite textbox',
value: 'this is the inner content '
} : {
role: 'textbox',
name: 'my favorite textbox',
value: 'this is the inner content ',
};
const snapshot = await page.accessibility.snapshot();
expect(snapshot.children[0]).toEqual(golden);
});
it('checkbox with and tabIndex and label should not have children', async function({page}) {
await page.setContent(`
<div role="checkbox" tabIndex=0 aria-checked="true" aria-label="my favorite checkbox">
this is the inner content
<img alt="yo" src="fakeimg.png">
</div>`);
const golden = {
role: 'checkbox',
name: 'my favorite checkbox',
checked: true
};
const snapshot = await page.accessibility.snapshot();
expect(snapshot.children[0]).toEqual(golden);
});
it('checkbox without label should not have children', async function({page}) {
await page.setContent(`
<div role="checkbox" aria-checked="true">
this is the inner content
<img alt="yo" src="fakeimg.png">
</div>`);
const golden = FFOX ? {
role: 'checkbox',
name: 'this is the inner content yo',
checked: true
} : {
role: 'checkbox',
name: 'this is the inner content yo',
checked: true
};
const snapshot = await page.accessibility.snapshot();
expect(snapshot.children[0]).toEqual(golden);
});
describe('root option', function() {
it('should work a button', async({page}) => {
await page.setContent(`<button>My Button</button>`);
const button = await page.$('button');
expect(await page.accessibility.snapshot({root: button})).toEqual({
role: 'button',
name: 'My Button'
});
});
it('should work an input', async({page}) => {
await page.setContent(`<input title="My Input" value="My Value">`);
const input = await page.$('input');
expect(await page.accessibility.snapshot({root: input})).toEqual({
role: 'textbox',
name: 'My Input',
value: 'My Value'
});
});
it('should work on a menu', async({page}) => {
await page.setContent(`
<div role="menu" title="My Menu">
<div role="menuitem">First Item</div>
<div role="menuitem">Second Item</div>
<div role="menuitem">Third Item</div>
</div>
`);
const menu = await page.$('div[role="menu"]');
expect(await page.accessibility.snapshot({root: menu})).toEqual({
role: 'menu',
name: 'My Menu',
children:
[ { role: 'menuitem', name: 'First Item' },
{ role: 'menuitem', name: 'Second Item' },
{ role: 'menuitem', name: 'Third Item' } ],
orientation: WEBKIT ? 'vertical' : undefined
});
});
it('should return null when the element is no longer in DOM', async({page}) => {
await page.setContent(`<button>My Button</button>`);
const button = await page.$('button');
await page.$eval('button', button => button.remove());
expect(await page.accessibility.snapshot({root: button})).toEqual(null);
});
it('should show uninteresting nodes', async({page}) => {
await page.setContent(`
<div id="root" role="textbox">
<div>
hello
<div>
world
</div>
</div>
</div>
`);
const root = await page.$('#root');
const snapshot = await page.accessibility.snapshot({root, interestingOnly: false});
expect(snapshot.role).toBe('textbox');
expect(snapshot.value).toContain('hello');
expect(snapshot.value).toContain('world');
expect(!!snapshot.children).toBe(true);
});
});
});
});
};
| test/accessibility.spec.js | 0 | https://github.com/microsoft/playwright/commit/ff302354bbf69c7bbb1ad94fd347c32855fb492f | [
0.43029627203941345,
0.013012748211622238,
0.0001638626417843625,
0.00016579951625317335,
0.07071782648563385
] |
{
"id": 1,
"code_window": [
"# playwright-firefox\n",
"This packagage contains the [Firefox](https://www.mozilla.org/firefox/) flavor of [Playwright](http://github.com/microsoft/playwright).\n"
],
"labels": [
"keep",
"replace"
],
"after_edit": [
"This package contains the [Firefox](https://www.mozilla.org/firefox/) flavor of [Playwright](http://github.com/microsoft/playwright)."
],
"file_path": "packages/playwright-firefox/README.md",
"type": "replace",
"edit_start_line_idx": 1
} | /**
* Copyright (c) Microsoft Corporation.
*
* 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.
*/
module.exports.describe = function({testRunner, expect, defaultBrowserOptions, playwright, product, CHROMIUM, FFOX}) {
const {describe, xdescribe, fdescribe} = testRunner;
const {it, fit, xit, dit} = testRunner;
const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;
(CHROMIUM || FFOX) && describe('Web SDK', function() {
beforeAll(async state => {
state.controlledBrowserApp = await playwright.launchBrowserApp({ ...defaultBrowserOptions, webSocket: true });
state.hostBrowserApp = await playwright.launchBrowserApp(defaultBrowserOptions);
state.hostBrowser = await playwright.connect(state.hostBrowserApp.connectOptions());
});
afterAll(async state => {
await state.hostBrowserApp.close();
state.hostBrowser = null;
state.hostBrowserApp = null;
await state.controlledBrowserApp.close();
state.controlledBrowserApp = null;
state.webUrl = null;
});
beforeEach(async state => {
state.page = await state.hostBrowser.defaultContext().newPage();
state.page.on('console', message => console.log('TEST: ' + message.text()));
await state.page.goto(state.sourceServer.PREFIX + '/test/assets/playwrightweb.html');
await state.page.evaluate((product, connectOptions) => setup(product, connectOptions), product.toLowerCase(), state.controlledBrowserApp.connectOptions());
});
afterEach(async state => {
await state.page.evaluate(() => teardown());
await state.page.close();
state.page = null;
});
it('should navigate', async({page, server}) => {
const url = await page.evaluate(async url => {
await page.goto(url);
return page.evaluate(() => window.location.href);
}, server.EMPTY_PAGE);
expect(url).toBe(server.EMPTY_PAGE);
});
it('should receive events', async({page, server}) => {
const logs = await page.evaluate(async url => {
const logs = [];
page.on('console', message => logs.push(message.text()));
await page.evaluate(() => console.log('hello'));
await page.evaluate(() => console.log('world'));
return logs;
}, server.EMPTY_PAGE);
expect(logs).toEqual(['hello', 'world']);
});
it('should take screenshot', async({page, server}) => {
const { base64, bufferClassName } = await page.evaluate(async url => {
await page.setViewport({width: 500, height: 500});
await page.goto(url);
const screenshot = await page.screenshot();
return { base64: screenshot.toString('base64'), bufferClassName: screenshot.constructor.name };
}, server.PREFIX + '/grid.html');
const screenshot = Buffer.from(base64, 'base64');
expect(screenshot).toBeGolden('screenshot-sanity.png');
// Verify that we use web versions of node-specific classes.
expect(bufferClassName).toBe('BufferImpl');
});
});
};
| test/web.spec.js | 0 | https://github.com/microsoft/playwright/commit/ff302354bbf69c7bbb1ad94fd347c32855fb492f | [
0.00026538787642493844,
0.00017894303891807795,
0.00016511566354893148,
0.00016821960161905736,
0.00003072725667152554
] |
{
"id": 1,
"code_window": [
"# playwright-firefox\n",
"This packagage contains the [Firefox](https://www.mozilla.org/firefox/) flavor of [Playwright](http://github.com/microsoft/playwright).\n"
],
"labels": [
"keep",
"replace"
],
"after_edit": [
"This package contains the [Firefox](https://www.mozilla.org/firefox/) flavor of [Playwright](http://github.com/microsoft/playwright)."
],
"file_path": "packages/playwright-firefox/README.md",
"type": "replace",
"edit_start_line_idx": 1
} | // Copyright (c) 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.
/**
* @unrestricted
*/
class ESTreeWalker {
/**
* @param {function(!ESTree.Node):(!Object|undefined)} beforeVisit
* @param {function(!ESTree.Node)=} afterVisit
*/
constructor(beforeVisit, afterVisit) {
this._beforeVisit = beforeVisit;
this._afterVisit = afterVisit || new Function();
}
/**
* @param {!ESTree.Node} ast
*/
walk(ast) {
this._innerWalk(ast, null);
}
/**
* @param {!ESTree.Node} node
* @param {?ESTree.Node} parent
*/
_innerWalk(node, parent) {
if (!node)
return;
node.parent = parent;
if (this._beforeVisit.call(null, node) === ESTreeWalker.SkipSubtree) {
this._afterVisit.call(null, node);
return;
}
const walkOrder = ESTreeWalker._walkOrder[node.type];
if (!walkOrder)
return;
if (node.type === 'TemplateLiteral') {
const templateLiteral = /** @type {!ESTree.TemplateLiteralNode} */ (node);
const expressionsLength = templateLiteral.expressions.length;
for (let i = 0; i < expressionsLength; ++i) {
this._innerWalk(templateLiteral.quasis[i], templateLiteral);
this._innerWalk(templateLiteral.expressions[i], templateLiteral);
}
this._innerWalk(templateLiteral.quasis[expressionsLength], templateLiteral);
} else {
for (let i = 0; i < walkOrder.length; ++i) {
const entity = node[walkOrder[i]];
if (Array.isArray(entity))
this._walkArray(entity, node);
else
this._innerWalk(entity, node);
}
}
this._afterVisit.call(null, node);
}
/**
* @param {!Array.<!ESTree.Node>} nodeArray
* @param {?ESTree.Node} parentNode
*/
_walkArray(nodeArray, parentNode) {
for (let i = 0; i < nodeArray.length; ++i)
this._innerWalk(nodeArray[i], parentNode);
}
}
/** @typedef {!Object} ESTreeWalker.SkipSubtree */
ESTreeWalker.SkipSubtree = {};
/** @enum {!Array.<string>} */
ESTreeWalker._walkOrder = {
'AwaitExpression': ['argument'],
'ArrayExpression': ['elements'],
'ArrowFunctionExpression': ['params', 'body'],
'AssignmentExpression': ['left', 'right'],
'AssignmentPattern': ['left', 'right'],
'BinaryExpression': ['left', 'right'],
'BlockStatement': ['body'],
'BreakStatement': ['label'],
'CallExpression': ['callee', 'arguments'],
'CatchClause': ['param', 'body'],
'ClassBody': ['body'],
'ClassDeclaration': ['id', 'superClass', 'body'],
'ClassExpression': ['id', 'superClass', 'body'],
'ConditionalExpression': ['test', 'consequent', 'alternate'],
'ContinueStatement': ['label'],
'DebuggerStatement': [],
'DoWhileStatement': ['body', 'test'],
'EmptyStatement': [],
'ExpressionStatement': ['expression'],
'ForInStatement': ['left', 'right', 'body'],
'ForOfStatement': ['left', 'right', 'body'],
'ForStatement': ['init', 'test', 'update', 'body'],
'FunctionDeclaration': ['id', 'params', 'body'],
'FunctionExpression': ['id', 'params', 'body'],
'Identifier': [],
'IfStatement': ['test', 'consequent', 'alternate'],
'LabeledStatement': ['label', 'body'],
'Literal': [],
'LogicalExpression': ['left', 'right'],
'MemberExpression': ['object', 'property'],
'MethodDefinition': ['key', 'value'],
'NewExpression': ['callee', 'arguments'],
'ObjectExpression': ['properties'],
'ObjectPattern': ['properties'],
'ParenthesizedExpression': ['expression'],
'Program': ['body'],
'Property': ['key', 'value'],
'ReturnStatement': ['argument'],
'SequenceExpression': ['expressions'],
'Super': [],
'SwitchCase': ['test', 'consequent'],
'SwitchStatement': ['discriminant', 'cases'],
'TaggedTemplateExpression': ['tag', 'quasi'],
'TemplateElement': [],
'TemplateLiteral': ['quasis', 'expressions'],
'ThisExpression': [],
'ThrowStatement': ['argument'],
'TryStatement': ['block', 'handler', 'finalizer'],
'UnaryExpression': ['argument'],
'UpdateExpression': ['argument'],
'VariableDeclaration': ['declarations'],
'VariableDeclarator': ['id', 'init'],
'WhileStatement': ['test', 'body'],
'WithStatement': ['object', 'body'],
'YieldExpression': ['argument']
};
module.exports = ESTreeWalker;
| utils/ESTreeWalker.js | 0 | https://github.com/microsoft/playwright/commit/ff302354bbf69c7bbb1ad94fd347c32855fb492f | [
0.00016885307559277862,
0.00016606457938905805,
0.0001640413247514516,
0.00016577546193730086,
0.0000013708009873880656
] |
{
"id": 2,
"code_window": [
"# playwright-webkit\n",
"This packagage contains the [WebKit](https://www.webkit.org/) flavor of [Playwright](http://github.com/microsoft/playwright).\n"
],
"labels": [
"keep",
"replace"
],
"after_edit": [
"This package contains the [WebKit](https://www.webkit.org/) flavor of [Playwright](http://github.com/microsoft/playwright)."
],
"file_path": "packages/playwright-webkit/README.md",
"type": "replace",
"edit_start_line_idx": 1
} | # playwright-firefox
This packagage contains the [Firefox](https://www.mozilla.org/firefox/) flavor of [Playwright](http://github.com/microsoft/playwright).
| packages/playwright-firefox/README.md | 1 | https://github.com/microsoft/playwright/commit/ff302354bbf69c7bbb1ad94fd347c32855fb492f | [
0.06974387913942337,
0.06974387913942337,
0.06974387913942337,
0.06974387913942337,
0
] |
{
"id": 2,
"code_window": [
"# playwright-webkit\n",
"This packagage contains the [WebKit](https://www.webkit.org/) flavor of [Playwright](http://github.com/microsoft/playwright).\n"
],
"labels": [
"keep",
"replace"
],
"after_edit": [
"This package contains the [WebKit](https://www.webkit.org/) flavor of [Playwright](http://github.com/microsoft/playwright)."
],
"file_path": "packages/playwright-webkit/README.md",
"type": "replace",
"edit_start_line_idx": 1
} | ### class: Foo
#### foo.asyncFunction()
#### foo.return42()
#### foo.returnNothing()
- returns: <[number]>
#### foo.www()
- returns <[string]>
[string]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type "String"
[number]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type "Number"
| utils/doclint/check_public_api/test/check-returns/doc.md | 0 | https://github.com/microsoft/playwright/commit/ff302354bbf69c7bbb1ad94fd347c32855fb492f | [
0.00016760893049649894,
0.00016589704318903387,
0.00016418514132965356,
0.00016589704318903387,
0.0000017118945834226906
] |
{
"id": 2,
"code_window": [
"# playwright-webkit\n",
"This packagage contains the [WebKit](https://www.webkit.org/) flavor of [Playwright](http://github.com/microsoft/playwright).\n"
],
"labels": [
"keep",
"replace"
],
"after_edit": [
"This package contains the [WebKit](https://www.webkit.org/) flavor of [Playwright](http://github.com/microsoft/playwright)."
],
"file_path": "packages/playwright-webkit/README.md",
"type": "replace",
"edit_start_line_idx": 1
} | /**
* Copyright 2019 Google Inc. All rights reserved.
* Modifications copyright (c) Microsoft Corporation.
*
* 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.
*/
const fs = require('fs');
const path = require('path');
const os = require('os');
const rm = require('rimraf').sync;
const GoldenUtils = require('./golden-utils');
const {Matchers} = require('../utils/testrunner/');
const YELLOW_COLOR = '\x1b[33m';
const RESET_COLOR = '\x1b[0m';
module.exports.describe = ({testRunner, product, playwrightPath}) => {
const {describe, xdescribe, fdescribe} = testRunner;
const {it, fit, xit, dit} = testRunner;
const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;
const CHROMIUM = product === 'Chromium';
const FFOX = product === 'Firefox';
const WEBKIT = product === 'WebKit';
const MAC = os.platform() === 'darwin';
const LINUX = os.platform() === 'linux';
const WIN = os.platform() === 'win32';
const playwright = require(playwrightPath)[product.toLowerCase()];
const headless = (process.env.HEADLESS || 'true').trim().toLowerCase() === 'true';
const slowMo = parseInt((process.env.SLOW_MO || '0').trim(), 10);
const executablePath = {
'Chromium': process.env.CRPATH,
'Firefox': process.env.FFPATH,
'WebKit': process.env.WKPATH,
}[product];
const defaultBrowserOptions = {
handleSIGINT: false,
executablePath,
slowMo,
headless,
dumpio: !!process.env.DUMPIO,
};
if (defaultBrowserOptions.executablePath) {
console.warn(`${YELLOW_COLOR}WARN: running ${product} tests with ${defaultBrowserOptions.executablePath}${RESET_COLOR}`);
} else {
// Make sure the `npm install` was run after the chromium roll.
if (!fs.existsSync(playwright.executablePath()))
throw new Error(`Browser is not downloaded. Run 'npm install' and try to re-run tests`);
}
const GOLDEN_DIR = path.join(__dirname, 'golden-' + product.toLowerCase());
const OUTPUT_DIR = path.join(__dirname, 'output-' + product.toLowerCase());
const ASSETS_DIR = path.join(__dirname, 'assets');
if (fs.existsSync(OUTPUT_DIR))
rm(OUTPUT_DIR);
const {expect} = new Matchers({
toBeGolden: GoldenUtils.compare.bind(null, GOLDEN_DIR, OUTPUT_DIR)
});
const testOptions = {
testRunner,
product,
FFOX,
WEBKIT,
CHROMIUM,
MAC,
LINUX,
WIN,
playwright,
expect,
defaultBrowserOptions,
playwrightPath,
headless: !!defaultBrowserOptions.headless,
ASSETS_DIR,
};
describe('Browser', function() {
beforeAll(async state => {
state.browserApp = await playwright.launchBrowserApp(defaultBrowserOptions);
state.browser = await playwright.connect(state.browserApp.connectOptions());
});
afterAll(async state => {
await state.browserApp.close();
state.browser = null;
state.browserApp = null;
});
beforeEach(async(state, test) => {
const contexts = [];
const onLine = (line) => test.output += line + '\n';
let rl;
if (state.browserApp.process().stderr) {
rl = require('readline').createInterface({ input: state.browserApp.process().stderr });
test.output = '';
rl.on('line', onLine);
}
state.tearDown = async () => {
await Promise.all(contexts.map(c => c.close()));
if (rl) {
rl.removeListener('line', onLine);
rl.close();
}
};
state.newContext = async (options) => {
const context = await state.browser.newContext(options);
contexts.push(context);
return context;
};
state.newPage = async (options) => {
const context = await state.newContext(options);
return await context.newPage();
};
});
afterEach(async state => {
await state.tearDown();
});
describe('Page', function() {
beforeEach(async state => {
state.context = await state.newContext();
state.page = await state.context.newPage();
});
afterEach(async state => {
state.context = null;
state.page = null;
});
// Page-level tests that are given a browser, a context and a page.
// Each test is launched in a new browser context.
testRunner.loadTests(require('./accessibility.spec.js'), testOptions);
testRunner.loadTests(require('./click.spec.js'), testOptions);
testRunner.loadTests(require('./cookies.spec.js'), testOptions);
testRunner.loadTests(require('./dialog.spec.js'), testOptions);
testRunner.loadTests(require('./elementhandle.spec.js'), testOptions);
testRunner.loadTests(require('./emulation.spec.js'), testOptions);
testRunner.loadTests(require('./evaluation.spec.js'), testOptions);
testRunner.loadTests(require('./frame.spec.js'), testOptions);
testRunner.loadTests(require('./input.spec.js'), testOptions);
testRunner.loadTests(require('./jshandle.spec.js'), testOptions);
testRunner.loadTests(require('./keyboard.spec.js'), testOptions);
testRunner.loadTests(require('./mouse.spec.js'), testOptions);
testRunner.loadTests(require('./navigation.spec.js'), testOptions);
testRunner.loadTests(require('./network.spec.js'), testOptions);
testRunner.loadTests(require('./page.spec.js'), testOptions);
testRunner.loadTests(require('./queryselector.spec.js'), testOptions);
testRunner.loadTests(require('./screenshot.spec.js'), testOptions);
testRunner.loadTests(require('./waittask.spec.js'), testOptions);
testRunner.loadTests(require('./interception.spec.js'), testOptions);
testRunner.loadTests(require('./geolocation.spec.js'), testOptions);
testRunner.loadTests(require('./workers.spec.js'), testOptions);
if (CHROMIUM) {
testRunner.loadTests(require('./chromium/chromium.spec.js'), testOptions);
testRunner.loadTests(require('./chromium/coverage.spec.js'), testOptions);
testRunner.loadTests(require('./chromium/pdf.spec.js'), testOptions);
testRunner.loadTests(require('./chromium/session.spec.js'), testOptions);
}
if (CHROMIUM || FFOX) {
testRunner.loadTests(require('./features/permissions.spec.js'), testOptions);
}
if (WEBKIT) {
testRunner.loadTests(require('./webkit/provisional.spec.js'), testOptions);
}
});
// Browser-level tests that are given a browser.
testRunner.loadTests(require('./browsercontext.spec.js'), testOptions);
testRunner.loadTests(require('./ignorehttpserrors.spec.js'), testOptions);
});
// Top-level tests that launch Browser themselves.
testRunner.loadTests(require('./defaultbrowsercontext.spec.js'), testOptions);
testRunner.loadTests(require('./fixtures.spec.js'), testOptions);
testRunner.loadTests(require('./launcher.spec.js'), testOptions);
if (CHROMIUM) {
testRunner.loadTests(require('./chromium/launcher.spec.js'), testOptions);
testRunner.loadTests(require('./chromium/headful.spec.js'), testOptions);
testRunner.loadTests(require('./chromium/oopif.spec.js'), testOptions);
testRunner.loadTests(require('./chromium/tracing.spec.js'), testOptions);
}
if (CHROMIUM || FFOX) {
testRunner.loadTests(require('./multiclient.spec.js'), testOptions);
}
testRunner.loadTests(require('./web.spec.js'), testOptions);
};
| test/playwright.spec.js | 0 | https://github.com/microsoft/playwright/commit/ff302354bbf69c7bbb1ad94fd347c32855fb492f | [
0.0007012602291069925,
0.00020303063502069563,
0.00016503034566994756,
0.00017029375885613263,
0.00011137968249386176
] |
{
"id": 2,
"code_window": [
"# playwright-webkit\n",
"This packagage contains the [WebKit](https://www.webkit.org/) flavor of [Playwright](http://github.com/microsoft/playwright).\n"
],
"labels": [
"keep",
"replace"
],
"after_edit": [
"This package contains the [WebKit](https://www.webkit.org/) flavor of [Playwright](http://github.com/microsoft/playwright)."
],
"file_path": "packages/playwright-webkit/README.md",
"type": "replace",
"edit_start_line_idx": 1
} | <link rel="stylesheet" href="stylesheet1.css">
<link rel="stylesheet" href="stylesheet2.css">
<script>
window.addEventListener('DOMContentLoaded', () => {
// Force stylesheets to load.
console.log(window.getComputedStyle(document.body).color);
}, false);
</script>
| test/assets/csscoverage/multiple.html | 0 | https://github.com/microsoft/playwright/commit/ff302354bbf69c7bbb1ad94fd347c32855fb492f | [
0.00016612095350865275,
0.00016612095350865275,
0.00016612095350865275,
0.00016612095350865275,
0
] |
{
"id": 0,
"code_window": [
"google-auth==2.27.0\n",
" # via shillelagh\n",
"greenlet==3.0.3\n",
" # via shillelagh\n",
"gunicorn==21.2.0\n",
" # via apache-superset\n",
"hashids==1.3.1\n",
" # via apache-superset\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" # via\n",
" # shillelagh\n",
" # sqlalchemy\n"
],
"file_path": "requirements/base.txt",
"type": "replace",
"edit_start_line_idx": 145
} | # SHA1:e35d6e709dc86002ca35ad59f7119aa6cc1e7179
#
# This file is autogenerated by pip-compile-multi
# To update, run:
#
# pip-compile-multi
#
-r base.txt
-e file:.
# via
# -r requirements/base.in
# -r requirements/development.in
appnope==0.1.3
# via ipython
astroid==2.15.8
# via pylint
asttokens==2.2.1
# via stack-data
backcall==0.2.0
# via ipython
boto3==1.26.130
# via tabulator
botocore==1.29.130
# via
# boto3
# s3transfer
cached-property==1.5.2
# via tableschema
chardet==5.1.0
# via tabulator
decorator==5.1.1
# via ipython
dill==0.3.6
# via pylint
et-xmlfile==1.1.0
# via openpyxl
executing==1.2.0
# via stack-data
flask-cors==3.0.10
# via apache-superset
future==0.18.3
# via pyhive
ijson==3.2.0.post0
# via tabulator
ipython==8.12.2
# via -r requirements/development.in
isort==5.12.0
# via pylint
jedi==0.18.2
# via ipython
jmespath==1.0.1
# via
# boto3
# botocore
jsonlines==3.1.0
# via tabulator
lazy-object-proxy==1.9.0
# via astroid
linear-tsv==1.1.0
# via tabulator
matplotlib-inline==0.1.6
# via ipython
mccabe==0.7.0
# via pylint
mysqlclient==2.1.0
# via apache-superset
openpyxl==3.1.2
# via tabulator
parso==0.8.3
# via jedi
pexpect==4.8.0
# via ipython
pickleshare==0.7.5
# via ipython
pillow==10.2.0
# via apache-superset
progress==1.6
# via -r requirements/development.in
psycopg2-binary==2.9.6
# via apache-superset
ptyprocess==0.7.0
# via pexpect
pure-eval==0.2.2
# via stack-data
pure-sasl==0.6.2
# via
# pyhive
# thrift-sasl
pydruid==0.6.5
# via apache-superset
pyhive[hive_pure_sasl]==0.7.0
# via apache-superset
pyinstrument==4.4.0
# via -r requirements/development.in
pylint==2.17.7
# via -r requirements/development.in
python-ldap==3.4.3
# via -r requirements/development.in
rfc3986==2.0.0
# via tableschema
s3transfer==0.6.1
# via boto3
sqloxide==0.1.33
# via -r requirements/development.in
stack-data==0.6.2
# via ipython
tableschema==1.20.2
# via apache-superset
tabulator==1.53.5
# via tableschema
thrift==0.16.0
# via
# apache-superset
# pyhive
# thrift-sasl
thrift-sasl==0.4.3
# via pyhive
tomlkit==0.11.8
# via pylint
traitlets==5.9.0
# via
# ipython
# matplotlib-inline
unicodecsv==0.14.1
# via
# tableschema
# tabulator
xlrd==2.0.1
# via tabulator
# The following packages are considered to be unsafe in a requirements file:
# setuptools
| requirements/development.txt | 1 | https://github.com/apache/superset/commit/11760d3fbf683e10ecbf2c9161248697c1acb6fc | [
0.003101472742855549,
0.0007547756540589035,
0.00016403225890826434,
0.0002624796761665493,
0.0009170864359475672
] |
{
"id": 0,
"code_window": [
"google-auth==2.27.0\n",
" # via shillelagh\n",
"greenlet==3.0.3\n",
" # via shillelagh\n",
"gunicorn==21.2.0\n",
" # via apache-superset\n",
"hashids==1.3.1\n",
" # via apache-superset\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" # via\n",
" # shillelagh\n",
" # sqlalchemy\n"
],
"file_path": "requirements/base.txt",
"type": "replace",
"edit_start_line_idx": 145
} | # SHA1:f00a57c70a52607d638c19f64f426f887382927e
#
# This file is autogenerated by pip-compile-multi
# To update, run:
#
# pip-compile-multi
#
-r base.txt
-e file:.
# via
# -r requirements/base.in
# -r requirements/docker.in
gevent==23.9.1
# via apache-superset
psycopg2-binary==2.9.6
# via apache-superset
zope-event==4.5.0
# via gevent
zope-interface==5.4.0
# via gevent
# The following packages are considered to be unsafe in a requirements file:
# setuptools
| requirements/docker.txt | 0 | https://github.com/apache/superset/commit/11760d3fbf683e10ecbf2c9161248697c1acb6fc | [
0.000470342201879248,
0.0002670134126674384,
0.0001649837795412168,
0.0001657142274780199,
0.0001437754835933447
] |
{
"id": 0,
"code_window": [
"google-auth==2.27.0\n",
" # via shillelagh\n",
"greenlet==3.0.3\n",
" # via shillelagh\n",
"gunicorn==21.2.0\n",
" # via apache-superset\n",
"hashids==1.3.1\n",
" # via apache-superset\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" # via\n",
" # shillelagh\n",
" # sqlalchemy\n"
],
"file_path": "requirements/base.txt",
"type": "replace",
"edit_start_line_idx": 145
} | /**
* 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 React, { createContext, useContext, useState } from 'react';
import { URL_PARAMS } from 'src/constants';
import { getUrlParam } from 'src/utils/urlUtils';
interface UiConfigType {
hideTitle: boolean;
hideTab: boolean;
hideNav: boolean;
hideChartControls: boolean;
}
interface EmbeddedUiConfigProviderProps {
children: JSX.Element;
}
export const UiConfigContext = createContext<UiConfigType>({
hideTitle: false,
hideTab: false,
hideNav: false,
hideChartControls: false,
});
export const useUiConfig = () => useContext(UiConfigContext);
export const EmbeddedUiConfigProvider: React.FC<
EmbeddedUiConfigProviderProps
> = ({ children }) => {
const config = getUrlParam(URL_PARAMS.uiConfig) || 0;
const [embeddedConfig] = useState({
hideTitle: (config & 1) !== 0,
hideTab: (config & 2) !== 0,
hideNav: (config & 4) !== 0,
hideChartControls: (config & 8) !== 0,
});
return (
<UiConfigContext.Provider value={embeddedConfig}>
{children}
</UiConfigContext.Provider>
);
};
| superset-frontend/src/components/UiConfigContext/index.tsx | 0 | https://github.com/apache/superset/commit/11760d3fbf683e10ecbf2c9161248697c1acb6fc | [
0.00017944085993804038,
0.0001731088268570602,
0.00016911572311073542,
0.00017242900503333658,
0.000003114910896329093
] |
{
"id": 0,
"code_window": [
"google-auth==2.27.0\n",
" # via shillelagh\n",
"greenlet==3.0.3\n",
" # via shillelagh\n",
"gunicorn==21.2.0\n",
" # via apache-superset\n",
"hashids==1.3.1\n",
" # via apache-superset\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" # via\n",
" # shillelagh\n",
" # sqlalchemy\n"
],
"file_path": "requirements/base.txt",
"type": "replace",
"edit_start_line_idx": 145
} | # 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.
"""add indexes to report models
Revision ID: 65a167d4c62e
Revises: 06dd9ff00fe8
Create Date: 2024-01-05 16:20:31.598995
"""
# revision identifiers, used by Alembic.
revision = "65a167d4c62e"
down_revision = "06dd9ff00fe8"
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import postgresql
def upgrade():
op.create_index(
"ix_report_execution_log_report_schedule_id",
"report_execution_log",
["report_schedule_id"],
unique=False,
)
op.create_index(
"ix_report_execution_log_start_dttm",
"report_execution_log",
["start_dttm"],
unique=False,
)
op.create_index(
"ix_report_recipient_report_schedule_id",
"report_recipient",
["report_schedule_id"],
unique=False,
)
def downgrade():
op.drop_index(
"ix_report_recipient_report_schedule_id", table_name="report_recipient"
)
op.drop_index(
"ix_report_execution_log_start_dttm", table_name="report_execution_log"
)
op.drop_index(
"ix_report_execution_log_report_schedule_id", table_name="report_execution_log"
)
| superset/migrations/versions/2024-01-05_16-20_65a167d4c62e_add_indexes_to_report_models.py | 0 | https://github.com/apache/superset/commit/11760d3fbf683e10ecbf2c9161248697c1acb6fc | [
0.00017446745187044144,
0.0001704280002741143,
0.0001656210224609822,
0.00017125690646935254,
0.0000032926468520599883
] |
{
"id": 1,
"code_window": [
" # via pexpect\n",
"pure-eval==0.2.2\n",
" # via stack-data\n",
"pure-sasl==0.6.2\n",
" # via\n",
" # pyhive\n",
" # thrift-sasl\n",
"pydruid==0.6.5\n",
" # via apache-superset\n",
"pyhive[hive_pure_sasl]==0.7.0\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "requirements/development.txt",
"type": "replace",
"edit_start_line_idx": 84
} | # 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 json
import os
import subprocess
from setuptools import find_packages, setup
BASE_DIR = os.path.abspath(os.path.dirname(__file__))
PACKAGE_JSON = os.path.join(BASE_DIR, "superset-frontend", "package.json")
with open(PACKAGE_JSON) as package_file:
version_string = json.load(package_file)["version"]
with open("README.md", encoding="utf-8") as f:
long_description = f.read()
def get_git_sha() -> str:
try:
s = subprocess.check_output(["git", "rev-parse", "HEAD"])
return s.decode().strip()
except Exception:
return ""
GIT_SHA = get_git_sha()
version_info = {"GIT_SHA": GIT_SHA, "version": version_string}
print("-==-" * 15)
print("VERSION: " + version_string)
print("GIT SHA: " + GIT_SHA)
print("-==-" * 15)
VERSION_INFO_FILE = os.path.join(BASE_DIR, "superset", "static", "version_info.json")
with open(VERSION_INFO_FILE, "w") as version_file:
json.dump(version_info, version_file)
setup(
name="apache-superset",
description="A modern, enterprise-ready business intelligence web application",
long_description=long_description,
long_description_content_type="text/markdown",
version=version_string,
packages=find_packages(),
include_package_data=True,
zip_safe=False,
entry_points={
"console_scripts": ["superset=superset.cli.main:superset"],
# the `postgres` and `postgres+psycopg2://` schemes were removed in SQLAlchemy 1.4
# add an alias here to prevent breaking existing databases
"sqlalchemy.dialects": [
"postgres.psycopg2 = sqlalchemy.dialects.postgresql:dialect",
"postgres = sqlalchemy.dialects.postgresql:dialect",
"superset = superset.extensions.metadb:SupersetAPSWDialect",
],
"shillelagh.adapter": [
"superset=superset.extensions.metadb:SupersetShillelaghAdapter"
],
},
install_requires=[
"backoff>=1.8.0",
"celery>=5.3.6, <6.0.0",
"click>=8.0.3",
"click-option-group",
"colorama",
"croniter>=0.3.28",
"cron-descriptor",
# snowflake-connector-python as of 3.7.0 doesn't support >=42.* therefore lowering the min to 41.0.2
"cryptography>=41.0.2, <43.0.0",
"deprecation>=2.1.0, <2.2.0",
"flask>=2.2.5, <3.0.0",
"flask-appbuilder>=4.4.1, <5.0.0",
"flask-caching>=2.1.0, <3",
"flask-compress>=1.13, <2.0",
"flask-talisman>=1.0.0, <2.0",
"flask-login>=0.6.0, < 1.0",
"flask-migrate>=3.1.0, <4.0",
"flask-session>=0.4.0, <1.0",
"flask-wtf>=1.1.0, <2.0",
"func_timeout",
"geopy",
"gunicorn>=21.2.0, <22.0; sys_platform != 'win32'",
"hashids>=1.3.1, <2",
"holidays>=0.25, <0.26",
"humanize",
"importlib_metadata",
"isodate",
"Mako>=1.2.2",
"markdown>=3.0",
"msgpack>=1.0.0, <1.1",
"nh3>=0.2.11, <0.3",
"numpy==1.23.5",
"packaging",
"pandas[performance]>=2.0.3, <2.1",
"parsedatetime",
"paramiko>=3.4.0",
"pgsanity",
"polyline>=2.0.0, <3.0",
"pyparsing>=3.0.6, <4",
"python-dateutil",
"python-dotenv",
"python-geohash",
"pyarrow>=14.0.1, <15",
"pyyaml>=6.0.0, <7.0.0",
"PyJWT>=2.4.0, <3.0",
"redis>=4.5.4, <5.0",
"selenium>=3.141.0, <4.10.0",
"shillelagh[gsheetsapi]>=1.2.10, <2.0",
"shortid",
"sshtunnel>=0.4.0, <0.5",
"simplejson>=3.15.0",
"slack_sdk>=3.19.0, <4",
"sqlalchemy>=1.4, <2",
"sqlalchemy-utils>=0.38.3, <0.39",
"sqlglot>=20,<21",
"sqlparse>=0.4.4, <0.5",
"tabulate>=0.8.9, <0.9",
"typing-extensions>=4, <5",
"waitress; sys_platform == 'win32'",
"wtforms>=2.3.3, <4",
"wtforms-json",
"xlsxwriter>=3.0.7, <3.1",
],
extras_require={
"athena": ["pyathena[pandas]>=2, <3"],
"aurora-data-api": ["preset-sqlalchemy-aurora-data-api>=0.2.8,<0.3"],
"bigquery": [
"pandas-gbq>=0.19.1",
"sqlalchemy-bigquery>=1.6.1",
"google-cloud-bigquery>=3.10.0",
],
"clickhouse": ["clickhouse-connect>=0.5.14, <1.0"],
"cockroachdb": ["cockroachdb>=0.3.5, <0.4"],
"cors": ["flask-cors>=2.0.0"],
"crate": ["crate[sqlalchemy]>=0.26.0, <0.27"],
"databend": ["databend-sqlalchemy>=0.3.2, <1.0"],
"databricks": [
"databricks-sql-connector>=2.0.2, <3",
"sqlalchemy-databricks>=0.2.0",
],
"db2": ["ibm-db-sa>0.3.8, <=0.4.0"],
"dremio": ["sqlalchemy-dremio>=1.1.5, <1.3"],
"drill": ["sqlalchemy-drill>=1.1.4, <2"],
"druid": ["pydruid>=0.6.5,<0.7"],
"duckdb": ["duckdb-engine>=0.9.5, <0.10"],
"dynamodb": ["pydynamodb>=0.4.2"],
"solr": ["sqlalchemy-solr >= 0.2.0"],
"elasticsearch": ["elasticsearch-dbapi>=0.2.9, <0.3.0"],
"exasol": ["sqlalchemy-exasol >= 2.4.0, <3.0"],
"excel": ["xlrd>=1.2.0, <1.3"],
"firebird": ["sqlalchemy-firebird>=0.7.0, <0.8"],
"firebolt": ["firebolt-sqlalchemy>=1.0.0, <2"],
"gevent": ["gevent>=23.9.1"],
"gsheets": ["shillelagh[gsheetsapi]>=1.2.10, <2"],
"hana": ["hdbcli==2.4.162", "sqlalchemy_hana==0.4.0"],
"hive": [
"pyhive[hive]>=0.6.5;python_version<'3.11'",
"pyhive[hive_pure_sasl]>=0.7.0",
"tableschema",
"thrift>=0.14.1, <1.0.0",
],
"impala": ["impyla>0.16.2, <0.17"],
"kusto": ["sqlalchemy-kusto>=2.0.0, <3"],
"kylin": ["kylinpy>=2.8.1, <2.9"],
"mssql": ["pymssql>=2.2.8, <3"],
"mysql": ["mysqlclient>=2.1.0, <3"],
"ocient": [
"sqlalchemy-ocient>=1.0.0",
"pyocient>=1.0.15, <2",
"shapely",
"geojson",
],
"oracle": ["cx-Oracle>8.0.0, <8.1"],
"pinot": ["pinotdb>=0.3.3, <0.4"],
"playwright": ["playwright>=1.37.0, <2"],
"postgres": ["psycopg2-binary==2.9.6"],
"presto": ["pyhive[presto]>=0.6.5"],
"trino": ["trino>=0.324.0"],
"prophet": ["prophet>=1.1.5, <2"],
"redshift": ["sqlalchemy-redshift>=0.8.1, <0.9"],
"rockset": ["rockset-sqlalchemy>=0.0.1, <1"],
"shillelagh": ["shillelagh[all]>=1.2.10, <2"],
"snowflake": ["snowflake-sqlalchemy>=1.2.4, <2"],
"spark": [
"pyhive[hive]>=0.6.5;python_version<'3.11'",
"pyhive[hive_pure_sasl]>=0.7",
"tableschema",
"thrift>=0.14.1, <1",
],
"teradata": ["teradatasql>=16.20.0.23"],
"thumbnails": ["Pillow>=10.0.1, <11"],
"vertica": ["sqlalchemy-vertica-python>=0.5.9, < 0.6"],
"netezza": ["nzalchemy>=11.0.2"],
"starrocks": ["starrocks>=1.0.0"],
"doris": ["pydoris>=1.0.0, <2.0.0"],
},
python_requires="~=3.9",
author="Apache Software Foundation",
author_email="[email protected]",
url="https://superset.apache.org/",
download_url="https://www.apache.org/dist/superset/" + version_string,
classifiers=[
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
],
)
| setup.py | 1 | https://github.com/apache/superset/commit/11760d3fbf683e10ecbf2c9161248697c1acb6fc | [
0.004335888661444187,
0.0003778582322411239,
0.00016382687317673117,
0.0001743143075145781,
0.0008465938153676689
] |
{
"id": 1,
"code_window": [
" # via pexpect\n",
"pure-eval==0.2.2\n",
" # via stack-data\n",
"pure-sasl==0.6.2\n",
" # via\n",
" # pyhive\n",
" # thrift-sasl\n",
"pydruid==0.6.5\n",
" # via apache-superset\n",
"pyhive[hive_pure_sasl]==0.7.0\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "requirements/development.txt",
"type": "replace",
"edit_start_line_idx": 84
} | # 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.
#
# This file is included in the final Docker image and SHOULD be overridden when
# deploying the image to prod. Settings configured here are intended for use in local
# development environments. Also note that superset_config_docker.py is imported
# as a final step as a means to override "defaults" configured here
#
import logging
import os
from celery.schedules import crontab
from flask_caching.backends.filesystemcache import FileSystemCache
logger = logging.getLogger()
DATABASE_DIALECT = os.getenv("DATABASE_DIALECT")
DATABASE_USER = os.getenv("DATABASE_USER")
DATABASE_PASSWORD = os.getenv("DATABASE_PASSWORD")
DATABASE_HOST = os.getenv("DATABASE_HOST")
DATABASE_PORT = os.getenv("DATABASE_PORT")
DATABASE_DB = os.getenv("DATABASE_DB")
EXAMPLES_USER = os.getenv("EXAMPLES_USER")
EXAMPLES_PASSWORD = os.getenv("EXAMPLES_PASSWORD")
EXAMPLES_HOST = os.getenv("EXAMPLES_HOST")
EXAMPLES_PORT = os.getenv("EXAMPLES_PORT")
EXAMPLES_DB = os.getenv("EXAMPLES_DB")
# The SQLAlchemy connection string.
SQLALCHEMY_DATABASE_URI = (
f"{DATABASE_DIALECT}://"
f"{DATABASE_USER}:{DATABASE_PASSWORD}@"
f"{DATABASE_HOST}:{DATABASE_PORT}/{DATABASE_DB}"
)
SQLALCHEMY_EXAMPLES_URI = (
f"{DATABASE_DIALECT}://"
f"{EXAMPLES_USER}:{EXAMPLES_PASSWORD}@"
f"{EXAMPLES_HOST}:{EXAMPLES_PORT}/{EXAMPLES_DB}"
)
REDIS_HOST = os.getenv("REDIS_HOST", "redis")
REDIS_PORT = os.getenv("REDIS_PORT", "6379")
REDIS_CELERY_DB = os.getenv("REDIS_CELERY_DB", "0")
REDIS_RESULTS_DB = os.getenv("REDIS_RESULTS_DB", "1")
RESULTS_BACKEND = FileSystemCache("/app/superset_home/sqllab")
CACHE_CONFIG = {
"CACHE_TYPE": "RedisCache",
"CACHE_DEFAULT_TIMEOUT": 300,
"CACHE_KEY_PREFIX": "superset_",
"CACHE_REDIS_HOST": REDIS_HOST,
"CACHE_REDIS_PORT": REDIS_PORT,
"CACHE_REDIS_DB": REDIS_RESULTS_DB,
}
DATA_CACHE_CONFIG = CACHE_CONFIG
class CeleryConfig:
broker_url = f"redis://{REDIS_HOST}:{REDIS_PORT}/{REDIS_CELERY_DB}"
imports = ("superset.sql_lab",)
result_backend = f"redis://{REDIS_HOST}:{REDIS_PORT}/{REDIS_RESULTS_DB}"
worker_prefetch_multiplier = 1
task_acks_late = False
beat_schedule = {
"reports.scheduler": {
"task": "reports.scheduler",
"schedule": crontab(minute="*", hour="*"),
},
"reports.prune_log": {
"task": "reports.prune_log",
"schedule": crontab(minute=10, hour=0),
},
}
CELERY_CONFIG = CeleryConfig
FEATURE_FLAGS = {"ALERT_REPORTS": True}
ALERT_REPORTS_NOTIFICATION_DRY_RUN = True
WEBDRIVER_BASEURL = "http://superset:8088/"
# The base URL for the email report hyperlinks.
WEBDRIVER_BASEURL_USER_FRIENDLY = WEBDRIVER_BASEURL
SQLLAB_CTAS_NO_LIMIT = True
#
# Optionally import superset_config_docker.py (which will have been included on
# the PYTHONPATH) in order to allow for local settings to be overridden
#
try:
import superset_config_docker
from superset_config_docker import * # noqa
logger.info(
f"Loaded your Docker configuration at " f"[{superset_config_docker.__file__}]"
)
except ImportError:
logger.info("Using default Docker config...")
| docker/pythonpath_dev/superset_config.py | 0 | https://github.com/apache/superset/commit/11760d3fbf683e10ecbf2c9161248697c1acb6fc | [
0.02173878438770771,
0.0032882096711546183,
0.00016393375699408352,
0.000430125801358372,
0.0061115240678191185
] |
{
"id": 1,
"code_window": [
" # via pexpect\n",
"pure-eval==0.2.2\n",
" # via stack-data\n",
"pure-sasl==0.6.2\n",
" # via\n",
" # pyhive\n",
" # thrift-sasl\n",
"pydruid==0.6.5\n",
" # via apache-superset\n",
"pyhive[hive_pure_sasl]==0.7.0\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "requirements/development.txt",
"type": "replace",
"edit_start_line_idx": 84
} | # 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 logging
from typing import Any, Optional
from flask import Response
from flask_appbuilder.api import expose, permission_name, protect, rison, safe
from flask_appbuilder.api.schemas import get_item_schema, get_list_schema
from flask_appbuilder.hooks import before_request
from flask_appbuilder.models.sqla.interface import SQLAInterface
from superset import is_feature_enabled
from superset.constants import MODEL_API_RW_METHOD_PERMISSION_MAP, RouteMethod
from superset.reports.logs.schemas import openapi_spec_methods_override
from superset.reports.models import ReportExecutionLog
from superset.views.base_api import BaseSupersetModelRestApi
logger = logging.getLogger(__name__)
class ReportExecutionLogRestApi(BaseSupersetModelRestApi):
datamodel = SQLAInterface(ReportExecutionLog)
@before_request
def ensure_alert_reports_enabled(self) -> Optional[Response]:
if not is_feature_enabled("ALERT_REPORTS"):
return self.response_404()
return None
include_route_methods = {RouteMethod.GET, RouteMethod.GET_LIST}
method_permission_name = MODEL_API_RW_METHOD_PERMISSION_MAP
class_permission_name = "ReportSchedule"
resource_name = "report"
allow_browser_login = True
show_columns = [
"id",
"scheduled_dttm",
"end_dttm",
"start_dttm",
"value",
"value_row_json",
"state",
"error_message",
"uuid",
]
list_columns = [
"id",
"scheduled_dttm",
"end_dttm",
"start_dttm",
"value",
"value_row_json",
"state",
"error_message",
"uuid",
]
order_columns = [
"state",
"value",
"error_message",
"end_dttm",
"start_dttm",
"scheduled_dttm",
]
openapi_spec_tag = "Report Schedules"
openapi_spec_methods = openapi_spec_methods_override
@staticmethod
def _apply_layered_relation_to_rison( # pylint: disable=invalid-name
layer_id: int, rison_parameters: dict[str, Any]
) -> None:
if "filters" not in rison_parameters:
rison_parameters["filters"] = []
rison_parameters["filters"].append(
{"col": "report_schedule", "opr": "rel_o_m", "value": layer_id}
)
@expose("/<int:pk>/log/", methods=("GET",))
@protect()
@safe
@permission_name("get")
@rison(get_list_schema)
def get_list( # pylint: disable=arguments-differ
self, pk: int, **kwargs: Any
) -> Response:
"""Get a list of report schedule logs.
---
get:
summary: Get a list of report schedule logs
parameters:
- in: path
schema:
type: integer
description: The report schedule id for these logs
name: pk
- in: query
name: q
content:
application/json:
schema:
$ref: '#/components/schemas/get_list_schema'
responses:
200:
description: Items from logs
content:
application/json:
schema:
type: object
properties:
ids:
description: >-
A list of log ids
type: array
items:
type: string
count:
description: >-
The total record count on the backend
type: number
result:
description: >-
The result from the get list query
type: array
items:
$ref: '#/components/schemas/{{self.__class__.__name__}}.get_list' # pylint: disable=line-too-long
400:
$ref: '#/components/responses/400'
401:
$ref: '#/components/responses/401'
422:
$ref: '#/components/responses/422'
500:
$ref: '#/components/responses/500'
"""
self._apply_layered_relation_to_rison(pk, kwargs["rison"])
return self.get_list_headless(**kwargs)
@expose("/<int:pk>/log/<int:log_id>", methods=("GET",))
@protect()
@safe
@permission_name("get")
@rison(get_item_schema)
def get( # pylint: disable=arguments-differ
self, pk: int, log_id: int, **kwargs: Any
) -> Response:
"""Get a report schedule log.
---
get:
summary: Get a report schedule log
parameters:
- in: path
schema:
type: integer
name: pk
description: The report schedule pk for log
- in: path
schema:
type: integer
name: log_id
description: The log pk
- in: query
name: q
content:
application/json:
schema:
$ref: '#/components/schemas/get_item_schema'
responses:
200:
description: Item log
content:
application/json:
schema:
type: object
properties:
id:
description: The log id
type: string
result:
$ref: '#/components/schemas/{{self.__class__.__name__}}.get'
400:
$ref: '#/components/responses/400'
401:
$ref: '#/components/responses/401'
404:
$ref: '#/components/responses/404'
422:
$ref: '#/components/responses/422'
500:
$ref: '#/components/responses/500'
"""
self._apply_layered_relation_to_rison(pk, kwargs["rison"])
return self.get_headless(log_id, **kwargs)
| superset/reports/logs/api.py | 0 | https://github.com/apache/superset/commit/11760d3fbf683e10ecbf2c9161248697c1acb6fc | [
0.00026017575873993337,
0.00017642017337493598,
0.00016496631724294275,
0.00017268414376303554,
0.000019069886548095383
] |
{
"id": 1,
"code_window": [
" # via pexpect\n",
"pure-eval==0.2.2\n",
" # via stack-data\n",
"pure-sasl==0.6.2\n",
" # via\n",
" # pyhive\n",
" # thrift-sasl\n",
"pydruid==0.6.5\n",
" # via apache-superset\n",
"pyhive[hive_pure_sasl]==0.7.0\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "requirements/development.txt",
"type": "replace",
"edit_start_line_idx": 84
} | /**
* 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 React from 'react';
import { t } from '@superset-ui/core';
import {
ControlPanelSectionConfig,
ControlSubSectionHeader,
} from '@superset-ui/chart-controls';
export const datasourceAndVizType: ControlPanelSectionConfig = {
controlSetRows: [
['datasource'],
['viz_type'],
[
{
name: 'slice_id',
config: {
type: 'HiddenControl',
label: t('Chart ID'),
hidden: true,
description: t('The id of the active chart'),
},
},
{
name: 'cache_timeout',
config: {
type: 'HiddenControl',
label: t('Cache Timeout (seconds)'),
hidden: true,
description: t('The number of seconds before expiring the cache'),
},
},
{
name: 'url_params',
config: {
type: 'HiddenControl',
label: t('URL parameters'),
hidden: true,
description: t('Extra parameters for use in jinja templated queries'),
},
},
],
],
};
export const colorScheme: ControlPanelSectionConfig = {
label: t('Color scheme'),
controlSetRows: [['color_scheme']],
};
export const sqlaTimeSeries: ControlPanelSectionConfig = {
label: t('Time'),
description: t('Time related form attributes'),
expanded: true,
controlSetRows: [['granularity_sqla'], ['time_range']],
};
export const annotations: ControlPanelSectionConfig = {
label: t('Annotations and layers'),
tabOverride: 'data',
expanded: true,
controlSetRows: [
[
{
name: 'annotation_layers',
config: {
type: 'AnnotationLayerControl',
label: '',
default: [],
description: t('Annotation layers'),
renderTrigger: true,
tabOverride: 'data',
},
},
],
],
};
export const NVD3TimeSeries: ControlPanelSectionConfig[] = [
{
label: t('Query'),
expanded: true,
controlSetRows: [
['metrics'],
['adhoc_filters'],
['groupby'],
['limit', 'timeseries_limit_metric'],
['order_desc'],
[
{
name: 'contribution',
config: {
type: 'CheckboxControl',
label: t('Contribution'),
default: false,
description: t('Compute the contribution to the total'),
},
},
],
['row_limit', null],
],
},
{
label: t('Advanced analytics'),
tabOverride: 'data',
description: t(
'This section contains options ' +
'that allow for advanced analytical post processing ' +
'of query results',
),
controlSetRows: [
[
<ControlSubSectionHeader>
{t('Rolling window')}
</ControlSubSectionHeader>,
],
[
{
name: 'rolling_type',
config: {
type: 'SelectControl',
label: t('Rolling function'),
default: 'None',
choices: [
['None', t('None')],
['mean', t('mean')],
['sum', t('sum')],
['std', t('std')],
['cumsum', t('cumsum')],
],
description: t(
'Defines a rolling window function to apply, works along ' +
'with the [Periods] text box',
),
},
},
{
name: 'rolling_periods',
config: {
type: 'TextControl',
label: t('Periods'),
isInt: true,
description: t(
'Defines the size of the rolling window function, ' +
'relative to the time granularity selected',
),
},
},
{
name: 'min_periods',
config: {
type: 'TextControl',
label: t('Min periods'),
isInt: true,
description: t(
'The minimum number of rolling periods required to show ' +
'a value. For instance if you do a cumulative sum on 7 days ' +
'you may want your "Min Period" to be 7, so that all data points ' +
'shown are the total of 7 periods. This will hide the "ramp up" ' +
'taking place over the first 7 periods',
),
},
},
],
[
<ControlSubSectionHeader>
{t('Time comparison')}
</ControlSubSectionHeader>,
],
[
{
name: 'time_compare',
config: {
type: 'SelectControl',
multi: true,
freeForm: true,
label: t('Time shift'),
choices: [
['1 day', t('1 day')],
['1 week', t('1 week')],
['28 days', t('28 days')],
['30 days', t('30 days')],
['52 weeks', t('52 weeks')],
['1 year', t('1 year')],
['104 weeks', t('104 weeks')],
['2 years', t('2 years')],
['156 weeks', t('156 weeks')],
['3 years', t('3 years')],
],
description: t(
'Overlay one or more timeseries from a ' +
'relative time period. Expects relative time deltas ' +
'in natural language (example: 24 hours, 7 days, ' +
'52 weeks, 365 days). Free text is supported.',
),
},
},
{
name: 'comparison_type',
config: {
type: 'SelectControl',
label: t('Calculation type'),
default: 'values',
choices: [
['values', t('Actual values')],
['absolute', t('Difference')],
['percentage', t('Percentage change')],
['ratio', t('Ratio')],
],
description: t(
'How to display time shifts: as individual lines; as the ' +
'difference between the main time series and each time shift; ' +
'as the percentage change; or as the ratio between series and time shifts.',
),
},
},
],
[<ControlSubSectionHeader>{t('Resample')}</ControlSubSectionHeader>],
[
{
name: 'resample_rule',
config: {
type: 'SelectControl',
freeForm: true,
label: t('Rule'),
default: null,
choices: [
['1T', t('1T')],
['1H', t('1H')],
['1D', t('1D')],
['7D', t('7D')],
['1M', t('1M')],
['1AS', t('1AS')],
],
description: t('Pandas resample rule'),
},
},
{
name: 'resample_method',
config: {
type: 'SelectControl',
freeForm: true,
label: t('Method'),
default: null,
choices: [
['asfreq', t('asfreq')],
['bfill', t('bfill')],
['ffill', t('ffill')],
['median', t('median')],
['mean', t('mean')],
['sum', t('sum')],
],
description: t('Pandas resample method'),
},
},
],
],
},
];
| superset-frontend/src/explore/controlPanels/sections.tsx | 0 | https://github.com/apache/superset/commit/11760d3fbf683e10ecbf2c9161248697c1acb6fc | [
0.00017606122128199786,
0.00017285077774431556,
0.00016830013191793114,
0.0001732119417283684,
0.0000017804292156142765
] |
{
"id": 2,
"code_window": [
"tableschema==1.20.2\n",
" # via apache-superset\n",
"tabulator==1.53.5\n",
" # via tableschema\n",
"thrift==0.16.0\n",
" # via\n",
" # apache-superset\n",
" # pyhive\n",
" # thrift-sasl\n",
"thrift-sasl==0.4.3\n",
" # via pyhive\n",
"tomlkit==0.11.8\n",
" # via pylint\n",
"traitlets==5.9.0\n",
" # via\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" # via apache-superset\n"
],
"file_path": "requirements/development.txt",
"type": "replace",
"edit_start_line_idx": 111
} | # 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 json
import os
import subprocess
from setuptools import find_packages, setup
BASE_DIR = os.path.abspath(os.path.dirname(__file__))
PACKAGE_JSON = os.path.join(BASE_DIR, "superset-frontend", "package.json")
with open(PACKAGE_JSON) as package_file:
version_string = json.load(package_file)["version"]
with open("README.md", encoding="utf-8") as f:
long_description = f.read()
def get_git_sha() -> str:
try:
s = subprocess.check_output(["git", "rev-parse", "HEAD"])
return s.decode().strip()
except Exception:
return ""
GIT_SHA = get_git_sha()
version_info = {"GIT_SHA": GIT_SHA, "version": version_string}
print("-==-" * 15)
print("VERSION: " + version_string)
print("GIT SHA: " + GIT_SHA)
print("-==-" * 15)
VERSION_INFO_FILE = os.path.join(BASE_DIR, "superset", "static", "version_info.json")
with open(VERSION_INFO_FILE, "w") as version_file:
json.dump(version_info, version_file)
setup(
name="apache-superset",
description="A modern, enterprise-ready business intelligence web application",
long_description=long_description,
long_description_content_type="text/markdown",
version=version_string,
packages=find_packages(),
include_package_data=True,
zip_safe=False,
entry_points={
"console_scripts": ["superset=superset.cli.main:superset"],
# the `postgres` and `postgres+psycopg2://` schemes were removed in SQLAlchemy 1.4
# add an alias here to prevent breaking existing databases
"sqlalchemy.dialects": [
"postgres.psycopg2 = sqlalchemy.dialects.postgresql:dialect",
"postgres = sqlalchemy.dialects.postgresql:dialect",
"superset = superset.extensions.metadb:SupersetAPSWDialect",
],
"shillelagh.adapter": [
"superset=superset.extensions.metadb:SupersetShillelaghAdapter"
],
},
install_requires=[
"backoff>=1.8.0",
"celery>=5.3.6, <6.0.0",
"click>=8.0.3",
"click-option-group",
"colorama",
"croniter>=0.3.28",
"cron-descriptor",
# snowflake-connector-python as of 3.7.0 doesn't support >=42.* therefore lowering the min to 41.0.2
"cryptography>=41.0.2, <43.0.0",
"deprecation>=2.1.0, <2.2.0",
"flask>=2.2.5, <3.0.0",
"flask-appbuilder>=4.4.1, <5.0.0",
"flask-caching>=2.1.0, <3",
"flask-compress>=1.13, <2.0",
"flask-talisman>=1.0.0, <2.0",
"flask-login>=0.6.0, < 1.0",
"flask-migrate>=3.1.0, <4.0",
"flask-session>=0.4.0, <1.0",
"flask-wtf>=1.1.0, <2.0",
"func_timeout",
"geopy",
"gunicorn>=21.2.0, <22.0; sys_platform != 'win32'",
"hashids>=1.3.1, <2",
"holidays>=0.25, <0.26",
"humanize",
"importlib_metadata",
"isodate",
"Mako>=1.2.2",
"markdown>=3.0",
"msgpack>=1.0.0, <1.1",
"nh3>=0.2.11, <0.3",
"numpy==1.23.5",
"packaging",
"pandas[performance]>=2.0.3, <2.1",
"parsedatetime",
"paramiko>=3.4.0",
"pgsanity",
"polyline>=2.0.0, <3.0",
"pyparsing>=3.0.6, <4",
"python-dateutil",
"python-dotenv",
"python-geohash",
"pyarrow>=14.0.1, <15",
"pyyaml>=6.0.0, <7.0.0",
"PyJWT>=2.4.0, <3.0",
"redis>=4.5.4, <5.0",
"selenium>=3.141.0, <4.10.0",
"shillelagh[gsheetsapi]>=1.2.10, <2.0",
"shortid",
"sshtunnel>=0.4.0, <0.5",
"simplejson>=3.15.0",
"slack_sdk>=3.19.0, <4",
"sqlalchemy>=1.4, <2",
"sqlalchemy-utils>=0.38.3, <0.39",
"sqlglot>=20,<21",
"sqlparse>=0.4.4, <0.5",
"tabulate>=0.8.9, <0.9",
"typing-extensions>=4, <5",
"waitress; sys_platform == 'win32'",
"wtforms>=2.3.3, <4",
"wtforms-json",
"xlsxwriter>=3.0.7, <3.1",
],
extras_require={
"athena": ["pyathena[pandas]>=2, <3"],
"aurora-data-api": ["preset-sqlalchemy-aurora-data-api>=0.2.8,<0.3"],
"bigquery": [
"pandas-gbq>=0.19.1",
"sqlalchemy-bigquery>=1.6.1",
"google-cloud-bigquery>=3.10.0",
],
"clickhouse": ["clickhouse-connect>=0.5.14, <1.0"],
"cockroachdb": ["cockroachdb>=0.3.5, <0.4"],
"cors": ["flask-cors>=2.0.0"],
"crate": ["crate[sqlalchemy]>=0.26.0, <0.27"],
"databend": ["databend-sqlalchemy>=0.3.2, <1.0"],
"databricks": [
"databricks-sql-connector>=2.0.2, <3",
"sqlalchemy-databricks>=0.2.0",
],
"db2": ["ibm-db-sa>0.3.8, <=0.4.0"],
"dremio": ["sqlalchemy-dremio>=1.1.5, <1.3"],
"drill": ["sqlalchemy-drill>=1.1.4, <2"],
"druid": ["pydruid>=0.6.5,<0.7"],
"duckdb": ["duckdb-engine>=0.9.5, <0.10"],
"dynamodb": ["pydynamodb>=0.4.2"],
"solr": ["sqlalchemy-solr >= 0.2.0"],
"elasticsearch": ["elasticsearch-dbapi>=0.2.9, <0.3.0"],
"exasol": ["sqlalchemy-exasol >= 2.4.0, <3.0"],
"excel": ["xlrd>=1.2.0, <1.3"],
"firebird": ["sqlalchemy-firebird>=0.7.0, <0.8"],
"firebolt": ["firebolt-sqlalchemy>=1.0.0, <2"],
"gevent": ["gevent>=23.9.1"],
"gsheets": ["shillelagh[gsheetsapi]>=1.2.10, <2"],
"hana": ["hdbcli==2.4.162", "sqlalchemy_hana==0.4.0"],
"hive": [
"pyhive[hive]>=0.6.5;python_version<'3.11'",
"pyhive[hive_pure_sasl]>=0.7.0",
"tableschema",
"thrift>=0.14.1, <1.0.0",
],
"impala": ["impyla>0.16.2, <0.17"],
"kusto": ["sqlalchemy-kusto>=2.0.0, <3"],
"kylin": ["kylinpy>=2.8.1, <2.9"],
"mssql": ["pymssql>=2.2.8, <3"],
"mysql": ["mysqlclient>=2.1.0, <3"],
"ocient": [
"sqlalchemy-ocient>=1.0.0",
"pyocient>=1.0.15, <2",
"shapely",
"geojson",
],
"oracle": ["cx-Oracle>8.0.0, <8.1"],
"pinot": ["pinotdb>=0.3.3, <0.4"],
"playwright": ["playwright>=1.37.0, <2"],
"postgres": ["psycopg2-binary==2.9.6"],
"presto": ["pyhive[presto]>=0.6.5"],
"trino": ["trino>=0.324.0"],
"prophet": ["prophet>=1.1.5, <2"],
"redshift": ["sqlalchemy-redshift>=0.8.1, <0.9"],
"rockset": ["rockset-sqlalchemy>=0.0.1, <1"],
"shillelagh": ["shillelagh[all]>=1.2.10, <2"],
"snowflake": ["snowflake-sqlalchemy>=1.2.4, <2"],
"spark": [
"pyhive[hive]>=0.6.5;python_version<'3.11'",
"pyhive[hive_pure_sasl]>=0.7",
"tableschema",
"thrift>=0.14.1, <1",
],
"teradata": ["teradatasql>=16.20.0.23"],
"thumbnails": ["Pillow>=10.0.1, <11"],
"vertica": ["sqlalchemy-vertica-python>=0.5.9, < 0.6"],
"netezza": ["nzalchemy>=11.0.2"],
"starrocks": ["starrocks>=1.0.0"],
"doris": ["pydoris>=1.0.0, <2.0.0"],
},
python_requires="~=3.9",
author="Apache Software Foundation",
author_email="[email protected]",
url="https://superset.apache.org/",
download_url="https://www.apache.org/dist/superset/" + version_string,
classifiers=[
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
],
)
| setup.py | 1 | https://github.com/apache/superset/commit/11760d3fbf683e10ecbf2c9161248697c1acb6fc | [
0.0003407998301554471,
0.00018701088265515864,
0.00016122632951010019,
0.00016850775864440948,
0.000046024062612559646
] |
{
"id": 2,
"code_window": [
"tableschema==1.20.2\n",
" # via apache-superset\n",
"tabulator==1.53.5\n",
" # via tableschema\n",
"thrift==0.16.0\n",
" # via\n",
" # apache-superset\n",
" # pyhive\n",
" # thrift-sasl\n",
"thrift-sasl==0.4.3\n",
" # via pyhive\n",
"tomlkit==0.11.8\n",
" # via pylint\n",
"traitlets==5.9.0\n",
" # via\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" # via apache-superset\n"
],
"file_path": "requirements/development.txt",
"type": "replace",
"edit_start_line_idx": 111
} | /**
* 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 React from 'react';
import userEvent from '@testing-library/user-event';
import { render, screen, waitFor } from 'spec/helpers/testing-library';
import { ExportToCSVDropdown } from './index';
const exportCSVOriginal = jest.fn();
const exportCSVPivoted = jest.fn();
const waitForRender = () => {
waitFor(() =>
render(
<ExportToCSVDropdown
exportCSVOriginal={exportCSVOriginal}
exportCSVPivoted={exportCSVPivoted}
>
<div>.CSV</div>
</ExportToCSVDropdown>,
),
);
};
test('Dropdown button with menu renders', () => {
waitForRender();
expect(screen.getByText('.CSV')).toBeVisible();
userEvent.click(screen.getByText('.CSV'));
expect(screen.getByRole('menu')).toBeInTheDocument();
expect(screen.getByText('Original')).toBeInTheDocument();
expect(screen.getByText('Pivoted')).toBeInTheDocument();
});
test('Call export csv original on click', () => {
waitForRender();
userEvent.click(screen.getByText('.CSV'));
userEvent.click(screen.getByText('Original'));
expect(exportCSVOriginal).toHaveBeenCalled();
});
test('Call export csv pivoted on click', () => {
waitForRender();
userEvent.click(screen.getByText('.CSV'));
userEvent.click(screen.getByText('Pivoted'));
expect(exportCSVPivoted).toHaveBeenCalled();
});
| superset-frontend/src/explore/components/ExportToCSVDropdown/ExportToCSVDropdown.test.tsx | 0 | https://github.com/apache/superset/commit/11760d3fbf683e10ecbf2c9161248697c1acb6fc | [
0.00017641529848333448,
0.00017516897059977055,
0.00017413572641089559,
0.00017452951578889042,
9.166958534478908e-7
] |
{
"id": 2,
"code_window": [
"tableschema==1.20.2\n",
" # via apache-superset\n",
"tabulator==1.53.5\n",
" # via tableschema\n",
"thrift==0.16.0\n",
" # via\n",
" # apache-superset\n",
" # pyhive\n",
" # thrift-sasl\n",
"thrift-sasl==0.4.3\n",
" # via pyhive\n",
"tomlkit==0.11.8\n",
" # via pylint\n",
"traitlets==5.9.0\n",
" # via\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" # via apache-superset\n"
],
"file_path": "requirements/development.txt",
"type": "replace",
"edit_start_line_idx": 111
} | /**
* 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 React from 'react';
import { render, screen } from 'spec/helpers/testing-library';
import { FilterBarOrientation } from 'src/dashboard/types';
import { IndicatorStatus } from '../../selectors';
import CrossFilter from './CrossFilter';
const mockedProps = {
filter: {
name: 'test',
emitterId: 1,
column: 'country_name',
value: 'Italy',
status: IndicatorStatus.CrossFilterApplied,
path: ['test-path'],
},
orientation: FilterBarOrientation.Horizontal,
last: false,
};
const setup = (props: typeof mockedProps) =>
render(<CrossFilter {...props} />, {
useRedux: true,
});
test('CrossFilter should render', () => {
const { container } = setup(mockedProps);
expect(container).toBeInTheDocument();
});
test('Title should render', () => {
setup(mockedProps);
expect(screen.getByText('test')).toBeInTheDocument();
});
test('Search icon should be visible', () => {
setup(mockedProps);
expect(
screen.getByTestId('cross-filters-highlight-emitter'),
).toBeInTheDocument();
});
test('Column and value should be visible', () => {
setup(mockedProps);
expect(screen.getByText('country_name')).toBeInTheDocument();
expect(screen.getByText('Italy')).toBeInTheDocument();
});
test('Tag should be closable', () => {
setup(mockedProps);
expect(screen.getByRole('img', { name: 'close' })).toBeInTheDocument();
});
test('Divider should not be visible', () => {
setup(mockedProps);
expect(screen.queryByTestId('cross-filters-divider')).not.toBeInTheDocument();
});
test('Divider should be visible', () => {
setup({
...mockedProps,
last: true,
});
expect(screen.getByTestId('cross-filters-divider')).toBeInTheDocument();
});
| superset-frontend/src/dashboard/components/nativeFilters/FilterBar/CrossFilters/CrossFilter.test.tsx | 0 | https://github.com/apache/superset/commit/11760d3fbf683e10ecbf2c9161248697c1acb6fc | [
0.0001771916140569374,
0.00017446212586946785,
0.00017179416317958385,
0.00017445397679693997,
0.0000015966294313329854
] |
{
"id": 2,
"code_window": [
"tableschema==1.20.2\n",
" # via apache-superset\n",
"tabulator==1.53.5\n",
" # via tableschema\n",
"thrift==0.16.0\n",
" # via\n",
" # apache-superset\n",
" # pyhive\n",
" # thrift-sasl\n",
"thrift-sasl==0.4.3\n",
" # via pyhive\n",
"tomlkit==0.11.8\n",
" # via pylint\n",
"traitlets==5.9.0\n",
" # via\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" # via apache-superset\n"
],
"file_path": "requirements/development.txt",
"type": "replace",
"edit_start_line_idx": 111
} | # 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 logging
from typing import Any, Optional
from flask_appbuilder.models.sqla import Model
from marshmallow import ValidationError
from superset.commands.base import BaseCommand, CreateMixin
from superset.commands.dashboard.exceptions import (
DashboardCreateFailedError,
DashboardInvalidError,
DashboardSlugExistsValidationError,
)
from superset.commands.utils import populate_roles
from superset.daos.dashboard import DashboardDAO
from superset.daos.exceptions import DAOCreateFailedError
logger = logging.getLogger(__name__)
class CreateDashboardCommand(CreateMixin, BaseCommand):
def __init__(self, data: dict[str, Any]):
self._properties = data.copy()
def run(self) -> Model:
self.validate()
try:
dashboard = DashboardDAO.create(attributes=self._properties, commit=True)
except DAOCreateFailedError as ex:
logger.exception(ex.exception)
raise DashboardCreateFailedError() from ex
return dashboard
def validate(self) -> None:
exceptions: list[ValidationError] = []
owner_ids: Optional[list[int]] = self._properties.get("owners")
role_ids: Optional[list[int]] = self._properties.get("roles")
slug: str = self._properties.get("slug", "")
# Validate slug uniqueness
if not DashboardDAO.validate_slug_uniqueness(slug):
exceptions.append(DashboardSlugExistsValidationError())
try:
owners = self.populate_owners(owner_ids)
self._properties["owners"] = owners
except ValidationError as ex:
exceptions.append(ex)
if exceptions:
raise DashboardInvalidError(exceptions=exceptions)
try:
roles = populate_roles(role_ids)
self._properties["roles"] = roles
except ValidationError as ex:
exceptions.append(ex)
if exceptions:
raise DashboardInvalidError(exceptions=exceptions)
| superset/commands/dashboard/create.py | 0 | https://github.com/apache/superset/commit/11760d3fbf683e10ecbf2c9161248697c1acb6fc | [
0.00018246209947392344,
0.00017299651517532766,
0.00016575484187342227,
0.00017253447731491178,
0.000004850331606576219
] |
{
"id": 3,
"code_window": [
" # via\n",
" # cmdstanpy\n",
" # prophet\n",
"trino==0.324.0\n",
" # via apache-superset\n",
"tzlocal==4.3\n",
" # via trino\n",
"websocket-client==1.5.1\n",
" # via docker\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"trino==0.328.0\n"
],
"file_path": "requirements/testing.txt",
"type": "replace",
"edit_start_line_idx": 135
} | # SHA1:e35d6e709dc86002ca35ad59f7119aa6cc1e7179
#
# This file is autogenerated by pip-compile-multi
# To update, run:
#
# pip-compile-multi
#
-r base.txt
-e file:.
# via
# -r requirements/base.in
# -r requirements/development.in
appnope==0.1.3
# via ipython
astroid==2.15.8
# via pylint
asttokens==2.2.1
# via stack-data
backcall==0.2.0
# via ipython
boto3==1.26.130
# via tabulator
botocore==1.29.130
# via
# boto3
# s3transfer
cached-property==1.5.2
# via tableschema
chardet==5.1.0
# via tabulator
decorator==5.1.1
# via ipython
dill==0.3.6
# via pylint
et-xmlfile==1.1.0
# via openpyxl
executing==1.2.0
# via stack-data
flask-cors==3.0.10
# via apache-superset
future==0.18.3
# via pyhive
ijson==3.2.0.post0
# via tabulator
ipython==8.12.2
# via -r requirements/development.in
isort==5.12.0
# via pylint
jedi==0.18.2
# via ipython
jmespath==1.0.1
# via
# boto3
# botocore
jsonlines==3.1.0
# via tabulator
lazy-object-proxy==1.9.0
# via astroid
linear-tsv==1.1.0
# via tabulator
matplotlib-inline==0.1.6
# via ipython
mccabe==0.7.0
# via pylint
mysqlclient==2.1.0
# via apache-superset
openpyxl==3.1.2
# via tabulator
parso==0.8.3
# via jedi
pexpect==4.8.0
# via ipython
pickleshare==0.7.5
# via ipython
pillow==10.2.0
# via apache-superset
progress==1.6
# via -r requirements/development.in
psycopg2-binary==2.9.6
# via apache-superset
ptyprocess==0.7.0
# via pexpect
pure-eval==0.2.2
# via stack-data
pure-sasl==0.6.2
# via
# pyhive
# thrift-sasl
pydruid==0.6.5
# via apache-superset
pyhive[hive_pure_sasl]==0.7.0
# via apache-superset
pyinstrument==4.4.0
# via -r requirements/development.in
pylint==2.17.7
# via -r requirements/development.in
python-ldap==3.4.3
# via -r requirements/development.in
rfc3986==2.0.0
# via tableschema
s3transfer==0.6.1
# via boto3
sqloxide==0.1.33
# via -r requirements/development.in
stack-data==0.6.2
# via ipython
tableschema==1.20.2
# via apache-superset
tabulator==1.53.5
# via tableschema
thrift==0.16.0
# via
# apache-superset
# pyhive
# thrift-sasl
thrift-sasl==0.4.3
# via pyhive
tomlkit==0.11.8
# via pylint
traitlets==5.9.0
# via
# ipython
# matplotlib-inline
unicodecsv==0.14.1
# via
# tableschema
# tabulator
xlrd==2.0.1
# via tabulator
# The following packages are considered to be unsafe in a requirements file:
# setuptools
| requirements/development.txt | 1 | https://github.com/apache/superset/commit/11760d3fbf683e10ecbf2c9161248697c1acb6fc | [
0.005250835325568914,
0.0011615788098424673,
0.00016420595056843013,
0.00028922606725245714,
0.001622479408979416
] |
{
"id": 3,
"code_window": [
" # via\n",
" # cmdstanpy\n",
" # prophet\n",
"trino==0.324.0\n",
" # via apache-superset\n",
"tzlocal==4.3\n",
" # via trino\n",
"websocket-client==1.5.1\n",
" # via docker\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"trino==0.328.0\n"
],
"file_path": "requirements/testing.txt",
"type": "replace",
"edit_start_line_idx": 135
} | #!/usr/bin/env bash
#
# 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.
#
set -eo pipefail
REQUIREMENTS_LOCAL="/app/docker/requirements-local.txt"
# If Cypress run – overwrite the password for admin and export env variables
if [ "$CYPRESS_CONFIG" == "true" ]; then
export SUPERSET_CONFIG=tests.integration_tests.superset_test_config
export SUPERSET_TESTENV=true
export SUPERSET__SQLALCHEMY_DATABASE_URI=postgresql+psycopg2://superset:superset@db:5432/superset
fi
#
# Make sure we have dev requirements installed
#
if [ -f "${REQUIREMENTS_LOCAL}" ]; then
echo "Installing local overrides at ${REQUIREMENTS_LOCAL}"
pip install --no-cache-dir -r "${REQUIREMENTS_LOCAL}"
else
echo "Skipping local overrides"
fi
#
# playwright is an optional package - run only if it is installed
#
if command -v playwright > /dev/null 2>&1; then
playwright install-deps
playwright install chromium
fi
case "${1}" in
worker)
echo "Starting Celery worker..."
celery --app=superset.tasks.celery_app:app worker -O fair -l INFO
;;
beat)
echo "Starting Celery beat..."
rm -f /tmp/celerybeat.pid
celery --app=superset.tasks.celery_app:app beat --pidfile /tmp/celerybeat.pid -l INFO -s "${SUPERSET_HOME}"/celerybeat-schedule
;;
app)
echo "Starting web app (using development server)..."
flask run -p 8088 --with-threads --reload --debugger --host=0.0.0.0
;;
app-gunicorn)
echo "Starting web app..."
/usr/bin/run-server.sh
;;
*)
echo "Unknown Operation!!!"
;;
esac
| docker/docker-bootstrap.sh | 0 | https://github.com/apache/superset/commit/11760d3fbf683e10ecbf2c9161248697c1acb6fc | [
0.0004542821552604437,
0.00021095408010296524,
0.00016416760627180338,
0.00017095051589421928,
0.00009941111056832597
] |
{
"id": 3,
"code_window": [
" # via\n",
" # cmdstanpy\n",
" # prophet\n",
"trino==0.324.0\n",
" # via apache-superset\n",
"tzlocal==4.3\n",
" # via trino\n",
"websocket-client==1.5.1\n",
" # via docker\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"trino==0.328.0\n"
],
"file_path": "requirements/testing.txt",
"type": "replace",
"edit_start_line_idx": 135
} | /**
* 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 React, { useState, useEffect } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { isEmpty } from 'lodash';
import {
t,
SupersetTheme,
css,
styled,
useTheme,
FeatureFlag,
isFeatureEnabled,
getExtensionsRegistry,
usePrevious,
} from '@superset-ui/core';
import Icons from 'src/components/Icons';
import { Switch } from 'src/components/Switch';
import { AlertObject } from 'src/features/alerts/types';
import { Menu } from 'src/components/Menu';
import Checkbox from 'src/components/Checkbox';
import { noOp } from 'src/utils/common';
import { NoAnimationDropdown } from 'src/components/Dropdown';
import DeleteModal from 'src/components/DeleteModal';
import ReportModal from 'src/features/reports/ReportModal';
import { ChartState } from 'src/explore/types';
import { UserWithPermissionsAndRoles } from 'src/types/bootstrapTypes';
import {
fetchUISpecificReport,
toggleActive,
deleteActiveReport,
} from 'src/features/reports/ReportModal/actions';
import { reportSelector } from 'src/views/CRUD/hooks';
import { MenuItemWithCheckboxContainer } from 'src/explore/components/useExploreAdditionalActionsMenu/index';
const extensionsRegistry = getExtensionsRegistry();
const deleteColor = (theme: SupersetTheme) => css`
color: ${theme.colors.error.base};
`;
const onMenuHover = (theme: SupersetTheme) => css`
& .ant-menu-item {
padding: 5px 12px;
margin-top: 0px;
margin-bottom: 4px;
:hover {
color: ${theme.colors.grayscale.dark1};
}
}
:hover {
background-color: ${theme.colors.secondary.light5};
}
`;
const onMenuItemHover = (theme: SupersetTheme) => css`
&:hover {
color: ${theme.colors.grayscale.dark1};
background-color: ${theme.colors.secondary.light5};
}
`;
const StyledDropdownItemWithIcon = styled.div`
display: flex;
flex-direction: row;
justify-content: space-between;
align-items: center;
> *:first-child {
margin-right: ${({ theme }) => theme.gridUnit}px;
}
`;
const DropdownItemExtension = extensionsRegistry.get(
'report-modal.dropdown.item.icon',
);
export enum CreationMethod {
Charts = 'charts',
Dashboards = 'dashboards',
}
export interface HeaderReportProps {
dashboardId?: number;
chart?: ChartState;
useTextMenu?: boolean;
setShowReportSubMenu?: (show: boolean) => void;
setIsDropdownVisible?: (visible: boolean) => void;
isDropdownVisible?: boolean;
showReportSubMenu?: boolean;
}
// Same instance to be used in useEffects
const EMPTY_OBJECT = {};
export default function HeaderReportDropDown({
dashboardId,
chart,
useTextMenu = false,
setShowReportSubMenu,
setIsDropdownVisible,
isDropdownVisible,
...rest
}: HeaderReportProps) {
const dispatch = useDispatch();
const report = useSelector<any, AlertObject>(state => {
const resourceType = dashboardId
? CreationMethod.Dashboards
: CreationMethod.Charts;
return (
reportSelector(state, resourceType, dashboardId || chart?.id) ||
EMPTY_OBJECT
);
});
const isReportActive: boolean = report?.active || false;
const user: UserWithPermissionsAndRoles = useSelector<
any,
UserWithPermissionsAndRoles
>(state => state.user);
const canAddReports = () => {
if (!isFeatureEnabled(FeatureFlag.AlertReports)) {
return false;
}
if (!user?.userId) {
// this is in the case that there is an anonymous user.
return false;
}
// Cannot add reports if the resource is not saved
if (!(dashboardId || chart?.id)) {
return false;
}
const roles = Object.keys(user.roles || []);
const permissions = roles.map(key =>
user.roles[key].filter(
perms => perms[0] === 'menu_access' && perms[1] === 'Manage',
),
);
return permissions.some(permission => permission.length > 0);
};
const [currentReportDeleting, setCurrentReportDeleting] =
useState<AlertObject | null>(null);
const theme = useTheme();
const prevDashboard = usePrevious(dashboardId);
const [showModal, setShowModal] = useState<boolean>(false);
const toggleActiveKey = async (data: AlertObject, checked: boolean) => {
if (data?.id) {
dispatch(toggleActive(data, checked));
}
};
const handleReportDelete = async (report: AlertObject) => {
await dispatch(deleteActiveReport(report));
setCurrentReportDeleting(null);
};
const shouldFetch =
canAddReports() &&
!!((dashboardId && prevDashboard !== dashboardId) || chart?.id);
useEffect(() => {
if (shouldFetch) {
dispatch(
fetchUISpecificReport({
userId: user.userId,
filterField: dashboardId ? 'dashboard_id' : 'chart_id',
creationMethod: dashboardId ? 'dashboards' : 'charts',
resourceId: dashboardId || chart?.id,
}),
);
}
}, []);
const showReportSubMenu = report && setShowReportSubMenu && canAddReports();
// @z-index-below-dashboard-header (100) - 1 = 99
const dropdownOverlayStyle = {
zIndex: 99,
animationDuration: '0s',
};
useEffect(() => {
if (showReportSubMenu) {
setShowReportSubMenu(true);
} else if (!report && setShowReportSubMenu) {
setShowReportSubMenu(false);
}
}, [report]);
const handleShowMenu = () => {
if (setIsDropdownVisible) {
setIsDropdownVisible(false);
setShowModal(true);
}
};
const handleDeleteMenuClick = () => {
if (setIsDropdownVisible) {
setIsDropdownVisible(false);
setCurrentReportDeleting(report);
}
};
const textMenu = () =>
isEmpty(report) ? (
<Menu selectable={false} {...rest} css={onMenuHover}>
<Menu.Item onClick={handleShowMenu}>
{DropdownItemExtension ? (
<StyledDropdownItemWithIcon>
<div>{t('Set up an email report')}</div>
<DropdownItemExtension />
</StyledDropdownItemWithIcon>
) : (
t('Set up an email report')
)}
</Menu.Item>
<Menu.Divider />
</Menu>
) : (
isDropdownVisible && (
<Menu selectable={false} css={{ border: 'none' }}>
<Menu.Item
css={onMenuItemHover}
onClick={() => toggleActiveKey(report, !isReportActive)}
>
<MenuItemWithCheckboxContainer>
<Checkbox checked={isReportActive} onChange={noOp} />
{t('Email reports active')}
</MenuItemWithCheckboxContainer>
</Menu.Item>
<Menu.Item css={onMenuItemHover} onClick={handleShowMenu}>
{t('Edit email report')}
</Menu.Item>
<Menu.Item css={onMenuItemHover} onClick={handleDeleteMenuClick}>
{t('Delete email report')}
</Menu.Item>
</Menu>
)
);
const menu = () => (
<Menu selectable={false} css={{ width: '200px' }}>
<Menu.Item>
{t('Email reports active')}
<Switch
data-test="toggle-active"
checked={isReportActive}
onClick={(checked: boolean) => toggleActiveKey(report, checked)}
size="small"
css={{ marginLeft: theme.gridUnit * 2 }}
/>
</Menu.Item>
<Menu.Item onClick={() => setShowModal(true)}>
{t('Edit email report')}
</Menu.Item>
<Menu.Item
onClick={() => setCurrentReportDeleting(report)}
css={deleteColor}
>
{t('Delete email report')}
</Menu.Item>
</Menu>
);
const iconMenu = () =>
isEmpty(report) ? (
<span
role="button"
title={t('Schedule email report')}
tabIndex={0}
className="action-button action-schedule-report"
onClick={() => setShowModal(true)}
>
<Icons.Calendar />
</span>
) : (
<>
<NoAnimationDropdown
overlay={menu()}
overlayStyle={dropdownOverlayStyle}
trigger={['click']}
getPopupContainer={(triggerNode: any) =>
triggerNode.closest('.action-button')
}
>
<span
role="button"
className="action-button action-schedule-report"
tabIndex={0}
>
<Icons.Calendar />
</span>
</NoAnimationDropdown>
</>
);
return (
<>
{canAddReports() && (
<>
<ReportModal
userId={user.userId}
show={showModal}
onHide={() => setShowModal(false)}
userEmail={user.email}
dashboardId={dashboardId}
chart={chart}
creationMethod={
dashboardId ? CreationMethod.Dashboards : CreationMethod.Charts
}
/>
{useTextMenu ? textMenu() : iconMenu()}
{currentReportDeleting && (
<DeleteModal
description={t(
'This action will permanently delete %s.',
currentReportDeleting?.name,
)}
onConfirm={() => {
if (currentReportDeleting) {
handleReportDelete(currentReportDeleting);
}
}}
onHide={() => setCurrentReportDeleting(null)}
open
title={t('Delete Report?')}
/>
)}
</>
)}
</>
);
}
| superset-frontend/src/features/reports/ReportModal/HeaderReportDropdown/index.tsx | 0 | https://github.com/apache/superset/commit/11760d3fbf683e10ecbf2c9161248697c1acb6fc | [
0.0003060133894905448,
0.0001771755050867796,
0.00016593621694482863,
0.0001723820314509794,
0.0000233201717492193
] |
{
"id": 3,
"code_window": [
" # via\n",
" # cmdstanpy\n",
" # prophet\n",
"trino==0.324.0\n",
" # via apache-superset\n",
"tzlocal==4.3\n",
" # via trino\n",
"websocket-client==1.5.1\n",
" # via docker\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"trino==0.328.0\n"
],
"file_path": "requirements/testing.txt",
"type": "replace",
"edit_start_line_idx": 135
} | /**
* 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 React, { SyntheticEvent } from 'react';
import { render, screen, waitFor } from 'spec/helpers/testing-library';
import userEvent from '@testing-library/user-event';
import { Menu } from 'src/components/Menu';
import downloadAsImage from 'src/utils/downloadAsImage';
import DownloadAsImage from './DownloadAsImage';
jest.mock('src/utils/downloadAsImage', () => ({
__esModule: true,
default: jest.fn(() => (_e: SyntheticEvent) => {}),
}));
const createProps = () => ({
addDangerToast: jest.fn(),
text: 'Download as Image',
dashboardTitle: 'Test Dashboard',
logEvent: jest.fn(),
});
const renderComponent = () => {
render(
<Menu>
<DownloadAsImage {...createProps()} />
</Menu>,
);
};
test('Should call download image on click', async () => {
const props = createProps();
renderComponent();
await waitFor(() => {
expect(downloadAsImage).toBeCalledTimes(0);
expect(props.addDangerToast).toBeCalledTimes(0);
});
userEvent.click(screen.getByRole('button', { name: 'Download as Image' }));
await waitFor(() => {
expect(downloadAsImage).toBeCalledTimes(1);
expect(props.addDangerToast).toBeCalledTimes(0);
});
});
| superset-frontend/src/dashboard/components/menu/DownloadMenuItems/DownloadAsImage.test.tsx | 0 | https://github.com/apache/superset/commit/11760d3fbf683e10ecbf2c9161248697c1acb6fc | [
0.00017774396110326052,
0.00017396698240190744,
0.00016991805750876665,
0.00017405356629751623,
0.0000021604741959890816
] |
{
"id": 4,
"code_window": [
" \"playwright\": [\"playwright>=1.37.0, <2\"],\n",
" \"postgres\": [\"psycopg2-binary==2.9.6\"],\n",
" \"presto\": [\"pyhive[presto]>=0.6.5\"],\n",
" \"trino\": [\"trino>=0.324.0\"],\n",
" \"prophet\": [\"prophet>=1.1.5, <2\"],\n",
" \"redshift\": [\"sqlalchemy-redshift>=0.8.1, <0.9\"],\n",
" \"rockset\": [\"rockset-sqlalchemy>=0.0.1, <1\"],\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"trino\": [\"trino>=0.328.0\"],\n"
],
"file_path": "setup.py",
"type": "replace",
"edit_start_line_idx": 192
} | # SHA1:60b260247b40133819664dc998d9e2da48e9a592
#
# This file is autogenerated by pip-compile-multi
# To update, run:
#
# pip-compile-multi
#
-e file:.
# via -r requirements/base.in
alembic==1.6.5
# via flask-migrate
amqp==5.1.1
# via kombu
apispec[yaml]==6.3.0
# via flask-appbuilder
apsw==3.42.0.1
# via shillelagh
async-timeout==4.0.2
# via redis
attrs==23.1.0
# via
# cattrs
# jsonschema
# requests-cache
babel==2.9.1
# via flask-babel
backoff==1.11.1
# via apache-superset
bcrypt==4.0.1
# via paramiko
billiard==4.2.0
# via celery
bottleneck==1.3.7
# via pandas
brotli==1.0.9
# via flask-compress
cachelib==0.9.0
# via
# flask-caching
# flask-session
cachetools==5.3.2
# via google-auth
cattrs==23.2.1
# via requests-cache
celery==5.3.6
# via apache-superset
certifi==2023.7.22
# via requests
cffi==1.15.1
# via
# cryptography
# pynacl
charset-normalizer==3.2.0
# via requests
click==8.1.3
# via
# apache-superset
# celery
# click-didyoumean
# click-option-group
# click-plugins
# click-repl
# flask
# flask-appbuilder
click-didyoumean==0.3.0
# via celery
click-option-group==0.5.5
# via apache-superset
click-plugins==1.1.1
# via celery
click-repl==0.2.0
# via celery
colorama==0.4.6
# via
# apache-superset
# flask-appbuilder
cron-descriptor==1.2.24
# via apache-superset
croniter==1.0.15
# via apache-superset
cryptography==42.0.2
# via
# apache-superset
# paramiko
deprecated==1.2.13
# via limits
deprecation==2.1.0
# via apache-superset
dnspython==2.1.0
# via email-validator
email-validator==1.1.3
# via flask-appbuilder
flask==2.2.5
# via
# apache-superset
# flask-appbuilder
# flask-babel
# flask-caching
# flask-compress
# flask-jwt-extended
# flask-limiter
# flask-login
# flask-migrate
# flask-session
# flask-sqlalchemy
# flask-wtf
flask-appbuilder==4.4.1
# via apache-superset
flask-babel==1.0.0
# via flask-appbuilder
flask-caching==2.1.0
# via apache-superset
flask-compress==1.13
# via apache-superset
flask-jwt-extended==4.3.1
# via flask-appbuilder
flask-limiter==3.3.1
# via flask-appbuilder
flask-login==0.6.3
# via
# apache-superset
# flask-appbuilder
flask-migrate==3.1.0
# via apache-superset
flask-session==0.5.0
# via apache-superset
flask-sqlalchemy==2.5.1
# via
# flask-appbuilder
# flask-migrate
flask-talisman==1.0.0
# via apache-superset
flask-wtf==1.2.1
# via
# apache-superset
# flask-appbuilder
func-timeout==4.3.5
# via apache-superset
geographiclib==1.52
# via geopy
geopy==2.2.0
# via apache-superset
google-auth==2.27.0
# via shillelagh
greenlet==3.0.3
# via shillelagh
gunicorn==21.2.0
# via apache-superset
hashids==1.3.1
# via apache-superset
holidays==0.25
# via apache-superset
humanize==3.11.0
# via apache-superset
idna==3.2
# via
# email-validator
# requests
importlib-metadata==6.6.0
# via apache-superset
importlib-resources==5.12.0
# via limits
isodate==0.6.0
# via apache-superset
itsdangerous==2.1.2
# via
# flask
# flask-wtf
jinja2==3.1.3
# via
# flask
# flask-babel
jsonschema==4.17.3
# via flask-appbuilder
kombu==5.3.4
# via celery
korean-lunar-calendar==0.3.1
# via holidays
limits==3.4.0
# via flask-limiter
llvmlite==0.40.1
# via numba
mako==1.2.4
# via
# alembic
# apache-superset
markdown==3.3.4
# via apache-superset
markdown-it-py==2.2.0
# via rich
markupsafe==2.1.1
# via
# jinja2
# mako
# werkzeug
# wtforms
marshmallow==3.19.0
# via
# flask-appbuilder
# marshmallow-sqlalchemy
marshmallow-sqlalchemy==0.23.1
# via flask-appbuilder
mdurl==0.1.2
# via markdown-it-py
msgpack==1.0.2
# via apache-superset
nh3==0.2.11
# via apache-superset
numba==0.57.1
# via pandas
numexpr==2.8.4
# via pandas
numpy==1.23.5
# via
# apache-superset
# bottleneck
# numba
# numexpr
# pandas
# pyarrow
ordered-set==4.1.0
# via flask-limiter
packaging==23.1
# via
# apache-superset
# apispec
# deprecation
# gunicorn
# limits
# marshmallow
# shillelagh
pandas[performance]==2.0.3
# via apache-superset
paramiko==3.4.0
# via
# apache-superset
# sshtunnel
parsedatetime==2.6
# via apache-superset
pgsanity==0.2.9
# via apache-superset
platformdirs==3.8.1
# via requests-cache
polyline==2.0.0
# via apache-superset
prison==0.2.1
# via flask-appbuilder
prompt-toolkit==3.0.38
# via click-repl
pyarrow==14.0.1
# via apache-superset
pyasn1==0.5.1
# via
# pyasn1-modules
# rsa
pyasn1-modules==0.3.0
# via google-auth
pycparser==2.20
# via cffi
pygments==2.15.0
# via rich
pyjwt==2.4.0
# via
# apache-superset
# flask-appbuilder
# flask-jwt-extended
pynacl==1.5.0
# via paramiko
pyparsing==3.0.6
# via apache-superset
pyrsistent==0.19.3
# via jsonschema
python-dateutil==2.8.2
# via
# alembic
# apache-superset
# celery
# croniter
# flask-appbuilder
# holidays
# pandas
# shillelagh
python-dotenv==0.19.0
# via apache-superset
python-editor==1.0.4
# via alembic
python-geohash==0.8.5
# via apache-superset
pytz==2021.3
# via
# babel
# flask-babel
# pandas
pyyaml==6.0.1
# via
# apache-superset
# apispec
redis==4.5.4
# via apache-superset
requests==2.31.0
# via
# requests-cache
# shillelagh
requests-cache==1.1.1
# via shillelagh
rich==13.3.4
# via flask-limiter
rsa==4.9
# via google-auth
selenium==3.141.0
# via apache-superset
shillelagh[gsheetsapi]==1.2.10
# via apache-superset
shortid==0.1.2
# via apache-superset
simplejson==3.17.3
# via apache-superset
six==1.16.0
# via
# click-repl
# isodate
# prison
# python-dateutil
# url-normalize
# wtforms-json
slack-sdk==3.21.3
# via apache-superset
sqlalchemy==1.4.36
# via
# alembic
# apache-superset
# flask-appbuilder
# flask-sqlalchemy
# marshmallow-sqlalchemy
# shillelagh
# sqlalchemy-utils
sqlalchemy-utils==0.38.3
# via
# apache-superset
# flask-appbuilder
sqlglot==20.8.0
# via apache-superset
sqlparse==0.4.4
# via apache-superset
sshtunnel==0.4.0
# via apache-superset
tabulate==0.8.9
# via apache-superset
typing-extensions==4.4.0
# via
# apache-superset
# flask-limiter
# limits
# shillelagh
tzdata==2023.3
# via
# celery
# pandas
url-normalize==1.4.3
# via requests-cache
urllib3==1.26.18
# via
# -r requirements/base.in
# requests
# requests-cache
# selenium
vine==5.1.0
# via
# amqp
# celery
# kombu
wcwidth==0.2.5
# via prompt-toolkit
werkzeug==3.0.1
# via
# -r requirements/base.in
# flask
# flask-appbuilder
# flask-jwt-extended
# flask-login
wrapt==1.15.0
# via deprecated
wtforms==2.3.3
# via
# apache-superset
# flask-appbuilder
# flask-wtf
# wtforms-json
wtforms-json==0.3.5
# via apache-superset
xlsxwriter==3.0.7
# via apache-superset
zipp==3.15.0
# via importlib-metadata
# The following packages are considered to be unsafe in a requirements file:
# setuptools
| requirements/base.txt | 1 | https://github.com/apache/superset/commit/11760d3fbf683e10ecbf2c9161248697c1acb6fc | [
0.00021762429969385266,
0.00017106448649428785,
0.00016135060286615044,
0.0001696595863904804,
0.000009244094144378323
] |
{
"id": 4,
"code_window": [
" \"playwright\": [\"playwright>=1.37.0, <2\"],\n",
" \"postgres\": [\"psycopg2-binary==2.9.6\"],\n",
" \"presto\": [\"pyhive[presto]>=0.6.5\"],\n",
" \"trino\": [\"trino>=0.324.0\"],\n",
" \"prophet\": [\"prophet>=1.1.5, <2\"],\n",
" \"redshift\": [\"sqlalchemy-redshift>=0.8.1, <0.9\"],\n",
" \"rockset\": [\"rockset-sqlalchemy>=0.0.1, <1\"],\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"trino\": [\"trino>=0.328.0\"],\n"
],
"file_path": "setup.py",
"type": "replace",
"edit_start_line_idx": 192
} | # 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.
"""empty message
Revision ID: c18bd4186f15
Revises: ('46ba6aaaac97', 'ec1f88a35cc6')
Create Date: 2018-07-24 14:29:41.341098
"""
# revision identifiers, used by Alembic.
revision = "c18bd4186f15"
down_revision = ("46ba6aaaac97", "ec1f88a35cc6")
def upgrade():
pass
def downgrade():
pass
| superset/migrations/versions/2018-07-24_14-29_c18bd4186f15_.py | 0 | https://github.com/apache/superset/commit/11760d3fbf683e10ecbf2c9161248697c1acb6fc | [
0.00017667486099526286,
0.00017303333152085543,
0.0001703166199149564,
0.00017257092986255884,
0.0000027875762498297263
] |
{
"id": 4,
"code_window": [
" \"playwright\": [\"playwright>=1.37.0, <2\"],\n",
" \"postgres\": [\"psycopg2-binary==2.9.6\"],\n",
" \"presto\": [\"pyhive[presto]>=0.6.5\"],\n",
" \"trino\": [\"trino>=0.324.0\"],\n",
" \"prophet\": [\"prophet>=1.1.5, <2\"],\n",
" \"redshift\": [\"sqlalchemy-redshift>=0.8.1, <0.9\"],\n",
" \"rockset\": [\"rockset-sqlalchemy>=0.0.1, <1\"],\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"trino\": [\"trino>=0.328.0\"],\n"
],
"file_path": "setup.py",
"type": "replace",
"edit_start_line_idx": 192
} | # 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.
"""d3format_by_metric
Revision ID: f162a1dea4c4
Revises: 960c69cb1f5b
Create Date: 2016-07-06 22:04:28.685100
"""
# revision identifiers, used by Alembic.
revision = "f162a1dea4c4"
down_revision = "960c69cb1f5b"
import sqlalchemy as sa
from alembic import op
def upgrade():
op.add_column(
"metrics", sa.Column("d3format", sa.String(length=128), nullable=True)
)
op.add_column(
"sql_metrics", sa.Column("d3format", sa.String(length=128), nullable=True)
)
def downgrade():
op.drop_column("sql_metrics", "d3format")
op.drop_column("metrics", "d3format")
| superset/migrations/versions/2016-07-06_22-04_f162a1dea4c4_d3format_by_metric.py | 0 | https://github.com/apache/superset/commit/11760d3fbf683e10ecbf2c9161248697c1acb6fc | [
0.00020065030548721552,
0.00017674159607850015,
0.00016579181829001755,
0.00017472867330070585,
0.000012758826414938085
] |
{
"id": 4,
"code_window": [
" \"playwright\": [\"playwright>=1.37.0, <2\"],\n",
" \"postgres\": [\"psycopg2-binary==2.9.6\"],\n",
" \"presto\": [\"pyhive[presto]>=0.6.5\"],\n",
" \"trino\": [\"trino>=0.324.0\"],\n",
" \"prophet\": [\"prophet>=1.1.5, <2\"],\n",
" \"redshift\": [\"sqlalchemy-redshift>=0.8.1, <0.9\"],\n",
" \"rockset\": [\"rockset-sqlalchemy>=0.0.1, <1\"],\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" \"trino\": [\"trino>=0.328.0\"],\n"
],
"file_path": "setup.py",
"type": "replace",
"edit_start_line_idx": 192
} | /**
* 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 { AnnotationType, Behavior, t } from '@superset-ui/core';
import {
EchartsTimeseriesChartProps,
EchartsTimeseriesFormData,
EchartsTimeseriesSeriesType,
} from '../../types';
import { EchartsChartPlugin } from '../../../types';
import buildQuery from '../../buildQuery';
import controlPanel from './controlPanel';
import transformProps from '../../transformProps';
import thumbnail from './images/thumbnail.png';
import example1 from './images/Bar1.png';
import example2 from './images/Bar2.png';
import example3 from './images/Bar3.png';
const barTransformProps = (chartProps: EchartsTimeseriesChartProps) =>
transformProps({
...chartProps,
formData: {
...chartProps.formData,
seriesType: EchartsTimeseriesSeriesType.Bar,
},
});
export default class EchartsTimeseriesBarChartPlugin extends EchartsChartPlugin<
EchartsTimeseriesFormData,
EchartsTimeseriesChartProps
> {
constructor() {
super({
buildQuery,
controlPanel,
loadChart: () => import('../../EchartsTimeseries'),
metadata: {
behaviors: [
Behavior.InteractiveChart,
Behavior.DrillToDetail,
Behavior.DrillBy,
],
category: t('Evolution'),
credits: ['https://echarts.apache.org'],
description: t(
'Bar Charts are used to show metrics as a series of bars.',
),
exampleGallery: [
{ url: example1 },
{ url: example2 },
{ url: example3 },
],
supportedAnnotationTypes: [
AnnotationType.Event,
AnnotationType.Formula,
AnnotationType.Interval,
AnnotationType.Timeseries,
],
name: t('Bar Chart'),
tags: [
t('ECharts'),
t('Predictive'),
t('Advanced-Analytics'),
t('Aesthetic'),
t('Time'),
t('Transformable'),
t('Stacked'),
t('Vertical'),
t('Bar'),
t('Popular'),
],
thumbnail,
},
transformProps: barTransformProps,
});
}
}
| superset-frontend/plugins/plugin-chart-echarts/src/Timeseries/Regular/Bar/index.ts | 0 | https://github.com/apache/superset/commit/11760d3fbf683e10ecbf2c9161248697c1acb6fc | [
0.0001780076854629442,
0.00017346450476907194,
0.00016540229262318462,
0.00017504215065855533,
0.000004202881427772809
] |
{
"id": 0,
"code_window": [
"import { HttpStatus } from '../enums/http-status.enum';\n",
"import { HttpException } from './http.exception';\n",
"\n",
"/**\n",
" * Defines an HTTP exception for *Unprocessable Entity* type errors.\n",
" *\n",
" * @see [Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions)\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { HttpException, HttpExceptionOptions } from './http.exception';\n"
],
"file_path": "packages/common/exceptions/unprocessable-entity.exception.ts",
"type": "replace",
"edit_start_line_idx": 1
} | import { HttpStatus } from '../enums/http-status.enum';
import { HttpException } from './http.exception';
/**
* Defines an HTTP exception for *Unprocessable Entity* type errors.
*
* @see [Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions)
*
* @publicApi
*/
export class UnprocessableEntityException extends HttpException {
/**
* Instantiate an `UnprocessableEntityException` Exception.
*
* @example
* `throw new UnprocessableEntityException()`
*
* @usageNotes
* The HTTP response status code will be 422.
* - The `objectOrError` argument defines the JSON response body or the message string.
* - The `description` argument contains a short description of the HTTP error.
*
* By default, the JSON response body contains two properties:
* - `statusCode`: this will be the value 422.
* - `message`: the string `'Unprocessable Entity'` by default; override this by supplying
* a string in the `objectOrError` parameter.
*
* If the parameter `objectOrError` is a string, the response body will contain an
* additional property, `error`, with a short description of the HTTP error. To override the
* entire JSON response body, pass an object instead. Nest will serialize the object
* and return it as the JSON response body.
*
* @param objectOrError string or object describing the error condition.
* @param description a short description of the HTTP error.
*/
constructor(
objectOrError?: string | object | any,
description = 'Unprocessable Entity',
) {
super(
HttpException.createBody(
objectOrError,
description,
HttpStatus.UNPROCESSABLE_ENTITY,
),
HttpStatus.UNPROCESSABLE_ENTITY,
);
}
}
| packages/common/exceptions/unprocessable-entity.exception.ts | 1 | https://github.com/nestjs/nest/commit/b4aca5d01facba08fceeea657454f9c92dbb7269 | [
0.0025070628616958857,
0.0006939481827430427,
0.00017039687372744083,
0.000186512028449215,
0.0009115940774790943
] |
{
"id": 0,
"code_window": [
"import { HttpStatus } from '../enums/http-status.enum';\n",
"import { HttpException } from './http.exception';\n",
"\n",
"/**\n",
" * Defines an HTTP exception for *Unprocessable Entity* type errors.\n",
" *\n",
" * @see [Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions)\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { HttpException, HttpExceptionOptions } from './http.exception';\n"
],
"file_path": "packages/common/exceptions/unprocessable-entity.exception.ts",
"type": "replace",
"edit_start_line_idx": 1
} | import {
ArgumentMetadata,
BadRequestException,
Injectable,
PipeTransform,
Type,
} from '@nestjs/common';
import { plainToClass } from 'class-transformer';
import { validate } from 'class-validator';
@Injectable()
export class ValidationPipe implements PipeTransform<any> {
async transform(value: any, metadata: ArgumentMetadata) {
const { metatype } = metadata;
if (!metatype || !this.toValidate(metatype)) {
return value;
}
const object = plainToClass(metatype, value);
const errors = await validate(object);
if (errors.length > 0) {
throw new BadRequestException('Validation failed');
}
return value;
}
private toValidate(metatype: Type<any>): boolean {
const types = [String, Boolean, Number, Array, Object];
return !types.find(type => metatype === type);
}
}
| sample/01-cats-app/src/common/pipes/validation.pipe.ts | 0 | https://github.com/nestjs/nest/commit/b4aca5d01facba08fceeea657454f9c92dbb7269 | [
0.0001728861388983205,
0.00017016120546031743,
0.00016792888345662504,
0.00016991491429507732,
0.00000185673059149849
] |
{
"id": 0,
"code_window": [
"import { HttpStatus } from '../enums/http-status.enum';\n",
"import { HttpException } from './http.exception';\n",
"\n",
"/**\n",
" * Defines an HTTP exception for *Unprocessable Entity* type errors.\n",
" *\n",
" * @see [Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions)\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { HttpException, HttpExceptionOptions } from './http.exception';\n"
],
"file_path": "packages/common/exceptions/unprocessable-entity.exception.ts",
"type": "replace",
"edit_start_line_idx": 1
} | import {
RESPONSE_PASSTHROUGH_METADATA,
ROUTE_ARGS_METADATA,
} from '../../constants';
import { RouteParamtypes } from '../../enums/route-paramtypes.enum';
import { PipeTransform } from '../../index';
import { Type } from '../../interfaces';
import { isNil, isString } from '../../utils/shared.utils';
/**
* The `@Response()`/`@Res` parameter decorator options.
*/
export interface ResponseDecoratorOptions {
/**
* Determines whether the response will be sent manually within the route handler,
* with the use of native response handling methods exposed by the platform-specific response object,
* or if it should passthrough Nest response processing pipeline.
*
* @default false
*/
passthrough: boolean;
}
export type ParamData = object | string | number;
export interface RouteParamMetadata {
index: number;
data?: ParamData;
}
export function assignMetadata<TParamtype = any, TArgs = any>(
args: TArgs,
paramtype: TParamtype,
index: number,
data?: ParamData,
...pipes: (Type<PipeTransform> | PipeTransform)[]
) {
return {
...args,
[`${paramtype}:${index}`]: {
index,
data,
pipes,
},
};
}
function createRouteParamDecorator(paramtype: RouteParamtypes) {
return (data?: ParamData): ParameterDecorator =>
(target, key, index) => {
const args =
Reflect.getMetadata(ROUTE_ARGS_METADATA, target.constructor, key) || {};
Reflect.defineMetadata(
ROUTE_ARGS_METADATA,
assignMetadata<RouteParamtypes, Record<number, RouteParamMetadata>>(
args,
paramtype,
index,
data,
),
target.constructor,
key,
);
};
}
const createPipesRouteParamDecorator =
(paramtype: RouteParamtypes) =>
(
data?: any,
...pipes: (Type<PipeTransform> | PipeTransform)[]
): ParameterDecorator =>
(target, key, index) => {
const args =
Reflect.getMetadata(ROUTE_ARGS_METADATA, target.constructor, key) || {};
const hasParamData = isNil(data) || isString(data);
const paramData = hasParamData ? data : undefined;
const paramPipes = hasParamData ? pipes : [data, ...pipes];
Reflect.defineMetadata(
ROUTE_ARGS_METADATA,
assignMetadata(args, paramtype, index, paramData, ...paramPipes),
target.constructor,
key,
);
};
/**
* Route handler parameter decorator. Extracts the `Request`
* object from the underlying platform and populates the decorated
* parameter with the value of `Request`.
*
* Example: `logout(@Request() req)`
*
* @see [Request object](https://docs.nestjs.com/controllers#request-object)
*
* @publicApi
*/
export const Request: () => ParameterDecorator = createRouteParamDecorator(
RouteParamtypes.REQUEST,
);
/**
* Route handler parameter decorator. Extracts the `Response`
* object from the underlying platform and populates the decorated
* parameter with the value of `Response`.
*
* Example: `logout(@Response() res)`
*
* @publicApi
*/
export const Response: (
options?: ResponseDecoratorOptions,
) => ParameterDecorator =
(options?: ResponseDecoratorOptions) => (target, key, index) => {
if (options?.passthrough) {
Reflect.defineMetadata(
RESPONSE_PASSTHROUGH_METADATA,
options?.passthrough,
target.constructor,
key,
);
}
return createRouteParamDecorator(RouteParamtypes.RESPONSE)()(
target,
key,
index,
);
};
/**
* Route handler parameter decorator. Extracts reference to the `Next` function
* from the underlying platform and populates the decorated
* parameter with the value of `Next`.
*
* @publicApi
*/
export const Next: () => ParameterDecorator = createRouteParamDecorator(
RouteParamtypes.NEXT,
);
/**
* Route handler parameter decorator. Extracts the `Ip` property
* from the `req` object and populates the decorated
* parameter with the value of `ip`.
*
* @see [Request object](https://docs.nestjs.com/controllers#request-object)
*
* @publicApi
*/
export const Ip: () => ParameterDecorator = createRouteParamDecorator(
RouteParamtypes.IP,
);
/**
* Route handler parameter decorator. Extracts the `Session` object
* from the underlying platform and populates the decorated
* parameter with the value of `Session`.
*
* @see [Request object](https://docs.nestjs.com/controllers#request-object)
*
* @publicApi
*/
export const Session: () => ParameterDecorator = createRouteParamDecorator(
RouteParamtypes.SESSION,
);
/**
* Route handler parameter decorator. Extracts the `file` object
* and populates the decorated parameter with the value of `file`.
* Used in conjunction with
* [multer middleware](https://github.com/expressjs/multer) for Express-based applications.
*
* For example:
* ```typescript
* uploadFile(@UploadedFile() file) {
* console.log(file);
* }
* ```
* @see [Request object](https://docs.nestjs.com/techniques/file-upload)
*
* @publicApi
*/
export function UploadedFile(): ParameterDecorator;
/**
* Route handler parameter decorator. Extracts the `file` object
* and populates the decorated parameter with the value of `file`.
* Used in conjunction with
* [multer middleware](https://github.com/expressjs/multer) for Express-based applications.
*
* For example:
* ```typescript
* uploadFile(@UploadedFile() file) {
* console.log(file);
* }
* ```
* @see [Request object](https://docs.nestjs.com/techniques/file-upload)
*
* @publicApi
*/
export function UploadedFile(
...pipes: (Type<PipeTransform> | PipeTransform)[]
): ParameterDecorator;
/**
* Route handler parameter decorator. Extracts the `file` object
* and populates the decorated parameter with the value of `file`.
* Used in conjunction with
* [multer middleware](https://github.com/expressjs/multer) for Express-based applications.
*
* For example:
* ```typescript
* uploadFile(@UploadedFile() file) {
* console.log(file);
* }
* ```
* @see [Request object](https://docs.nestjs.com/techniques/file-upload)
*
* @publicApi
*/
export function UploadedFile(
fileKey?: string,
...pipes: (Type<PipeTransform> | PipeTransform)[]
): ParameterDecorator;
/**
* Route handler parameter decorator. Extracts the `file` object
* and populates the decorated parameter with the value of `file`.
* Used in conjunction with
* [multer middleware](https://github.com/expressjs/multer) for Express-based applications.
*
* For example:
* ```typescript
* uploadFile(@UploadedFile() file) {
* console.log(file);
* }
* ```
* @see [Request object](https://docs.nestjs.com/techniques/file-upload)
*
* @publicApi
*/
export function UploadedFile(
fileKey?: string | (Type<PipeTransform> | PipeTransform),
...pipes: (Type<PipeTransform> | PipeTransform)[]
): ParameterDecorator {
return createPipesRouteParamDecorator(RouteParamtypes.FILE)(
fileKey,
...pipes,
);
}
/**
* Route handler parameter decorator. Extracts the `files` object
* and populates the decorated parameter with the value of `files`.
* Used in conjunction with
* [multer middleware](https://github.com/expressjs/multer) for Express-based applications.
*
* For example:
* ```typescript
* uploadFile(@UploadedFiles() files) {
* console.log(files);
* }
* ```
* @see [Request object](https://docs.nestjs.com/techniques/file-upload)
*
* @publicApi
*/
export function UploadedFiles(): ParameterDecorator;
/**
* Route handler parameter decorator. Extracts the `files` object
* and populates the decorated parameter with the value of `files`.
* Used in conjunction with
* [multer middleware](https://github.com/expressjs/multer) for Express-based applications.
*
* For example:
* ```typescript
* uploadFile(@UploadedFiles() files) {
* console.log(files);
* }
* ```
* @see [Request object](https://docs.nestjs.com/techniques/file-upload)
*
* @publicApi
*/
export function UploadedFiles(
...pipes: (Type<PipeTransform> | PipeTransform)[]
): ParameterDecorator;
/**
* Route handler parameter decorator. Extracts the `files` object
* and populates the decorated parameter with the value of `files`.
* Used in conjunction with
* [multer middleware](https://github.com/expressjs/multer) for Express-based applications.
*
* For example:
* ```typescript
* uploadFile(@UploadedFiles() files) {
* console.log(files);
* }
* ```
* @see [Request object](https://docs.nestjs.com/techniques/file-upload)
*
* @publicApi
*/
export function UploadedFiles(
...pipes: (Type<PipeTransform> | PipeTransform)[]
): ParameterDecorator {
return createPipesRouteParamDecorator(RouteParamtypes.FILES)(
undefined,
...pipes,
);
}
/**
* Route handler parameter decorator. Extracts the `headers`
* property from the `req` object and populates the decorated
* parameter with the value of `headers`.
*
* For example: `async update(@Headers('Cache-Control') cacheControl: string)`
*
* @param property name of single header property to extract.
*
* @see [Request object](https://docs.nestjs.com/controllers#request-object)
*
* @publicApi
*/
export const Headers: (property?: string) => ParameterDecorator =
createRouteParamDecorator(RouteParamtypes.HEADERS);
/**
* Route handler parameter decorator. Extracts the `query`
* property from the `req` object and populates the decorated
* parameter with the value of `query`. May also apply pipes to the bound
* query parameter.
*
* For example:
* ```typescript
* async find(@Query('user') user: string)
* ```
*
* @param property name of single property to extract from the `query` object
* @param pipes one or more pipes to apply to the bound query parameter
*
* @see [Request object](https://docs.nestjs.com/controllers#request-object)
*
* @publicApi
*/
export function Query(): ParameterDecorator;
/**
* Route handler parameter decorator. Extracts the `query`
* property from the `req` object and populates the decorated
* parameter with the value of `query`. May also apply pipes to the bound
* query parameter.
*
* For example:
* ```typescript
* async find(@Query('user') user: string)
* ```
*
* @param property name of single property to extract from the `query` object
* @param pipes one or more pipes to apply to the bound query parameter
*
* @see [Request object](https://docs.nestjs.com/controllers#request-object)
*
* @publicApi
*/
export function Query(
...pipes: (Type<PipeTransform> | PipeTransform)[]
): ParameterDecorator;
/**
* Route handler parameter decorator. Extracts the `query`
* property from the `req` object and populates the decorated
* parameter with the value of `query`. May also apply pipes to the bound
* query parameter.
*
* For example:
* ```typescript
* async find(@Query('user') user: string)
* ```
*
* @param property name of single property to extract from the `query` object
* @param pipes one or more pipes to apply to the bound query parameter
*
* @see [Request object](https://docs.nestjs.com/controllers#request-object)
*
* @publicApi
*/
export function Query(
property: string,
...pipes: (Type<PipeTransform> | PipeTransform)[]
): ParameterDecorator;
/**
* Route handler parameter decorator. Extracts the `query`
* property from the `req` object and populates the decorated
* parameter with the value of `query`. May also apply pipes to the bound
* query parameter.
*
* For example:
* ```typescript
* async find(@Query('user') user: string)
* ```
*
* @param property name of single property to extract from the `query` object
* @param pipes one or more pipes to apply to the bound query parameter
*
* @see [Request object](https://docs.nestjs.com/controllers#request-object)
*
* @publicApi
*/
export function Query(
property?: string | (Type<PipeTransform> | PipeTransform),
...pipes: (Type<PipeTransform> | PipeTransform)[]
): ParameterDecorator {
return createPipesRouteParamDecorator(RouteParamtypes.QUERY)(
property,
...pipes,
);
}
/**
* Route handler parameter decorator. Extracts the entire `body`
* object from the `req` object and populates the decorated
* parameter with the value of `body`.
*
* For example:
* ```typescript
* async create(@Body() createDto: CreateCatDto)
* ```
*
* @see [Request object](https://docs.nestjs.com/controllers#request-object)
*
* @publicApi
*/
export function Body(): ParameterDecorator;
/**
* Route handler parameter decorator. Extracts the entire `body`
* object from the `req` object and populates the decorated
* parameter with the value of `body`. Also applies the specified
* pipes to that parameter.
*
* For example:
* ```typescript
* async create(@Body(new ValidationPipe()) createDto: CreateCatDto)
* ```
*
* @param pipes one or more pipes - either instances or classes - to apply to
* the bound body parameter.
*
* @see [Request object](https://docs.nestjs.com/controllers#request-object)
* @see [Working with pipes](https://docs.nestjs.com/custom-decorators#working-with-pipes)
*
* @publicApi
*/
export function Body(
...pipes: (Type<PipeTransform> | PipeTransform)[]
): ParameterDecorator;
/**
* Route handler parameter decorator. Extracts a single property from
* the `body` object property of the `req` object and populates the decorated
* parameter with the value of that property. Also applies pipes to the bound
* body parameter.
*
* For example:
* ```typescript
* async create(@Body('role', new ValidationPipe()) role: string)
* ```
*
* @param property name of single property to extract from the `body` object
* @param pipes one or more pipes - either instances or classes - to apply to
* the bound body parameter.
*
* @see [Request object](https://docs.nestjs.com/controllers#request-object)
* @see [Working with pipes](https://docs.nestjs.com/custom-decorators#working-with-pipes)
*
* @publicApi
*/
export function Body(
property: string,
...pipes: (Type<PipeTransform> | PipeTransform)[]
): ParameterDecorator;
/**
* Route handler parameter decorator. Extracts the entire `body` object
* property, or optionally a named property of the `body` object, from
* the `req` object and populates the decorated parameter with that value.
* Also applies pipes to the bound body parameter.
*
* For example:
* ```typescript
* async create(@Body('role', new ValidationPipe()) role: string)
* ```
*
* @param property name of single property to extract from the `body` object
* @param pipes one or more pipes - either instances or classes - to apply to
* the bound body parameter.
*
* @see [Request object](https://docs.nestjs.com/controllers#request-object)
* @see [Working with pipes](https://docs.nestjs.com/custom-decorators#working-with-pipes)
*
* @publicApi
*/
export function Body(
property?: string | (Type<PipeTransform> | PipeTransform),
...pipes: (Type<PipeTransform> | PipeTransform)[]
): ParameterDecorator {
return createPipesRouteParamDecorator(RouteParamtypes.BODY)(
property,
...pipes,
);
}
/**
* Route handler parameter decorator. Extracts the `params`
* property from the `req` object and populates the decorated
* parameter with the value of `params`. May also apply pipes to the bound
* parameter.
*
* For example, extracting all params:
* ```typescript
* findOne(@Param() params: string[])
* ```
*
* For example, extracting a single param:
* ```typescript
* findOne(@Param('id') id: string)
* ```
* @param property name of single property to extract from the `req` object
* @param pipes one or more pipes - either instances or classes - to apply to
* the bound parameter.
*
* @see [Request object](https://docs.nestjs.com/controllers#request-object)
* @see [Working with pipes](https://docs.nestjs.com/custom-decorators#working-with-pipes)
*
* @publicApi
*/
export function Param(): ParameterDecorator;
/**
* Route handler parameter decorator. Extracts the `params`
* property from the `req` object and populates the decorated
* parameter with the value of `params`. May also apply pipes to the bound
* parameter.
*
* For example, extracting all params:
* ```typescript
* findOne(@Param() params: string[])
* ```
*
* For example, extracting a single param:
* ```typescript
* findOne(@Param('id') id: string)
* ```
* @param property name of single property to extract from the `req` object
* @param pipes one or more pipes - either instances or classes - to apply to
* the bound parameter.
*
* @see [Request object](https://docs.nestjs.com/controllers#request-object)
* @see [Working with pipes](https://docs.nestjs.com/custom-decorators#working-with-pipes)
*
* @publicApi
*/
export function Param(
...pipes: (Type<PipeTransform> | PipeTransform)[]
): ParameterDecorator;
/**
* Route handler parameter decorator. Extracts the `params`
* property from the `req` object and populates the decorated
* parameter with the value of `params`. May also apply pipes to the bound
* parameter.
*
* For example, extracting all params:
* ```typescript
* findOne(@Param() params: string[])
* ```
*
* For example, extracting a single param:
* ```typescript
* findOne(@Param('id') id: string)
* ```
* @param property name of single property to extract from the `req` object
* @param pipes one or more pipes - either instances or classes - to apply to
* the bound parameter.
*
* @see [Request object](https://docs.nestjs.com/controllers#request-object)
* @see [Working with pipes](https://docs.nestjs.com/custom-decorators#working-with-pipes)
*
* @publicApi
*/
export function Param(
property: string,
...pipes: (Type<PipeTransform> | PipeTransform)[]
): ParameterDecorator;
/**
* Route handler parameter decorator. Extracts the `params`
* property from the `req` object and populates the decorated
* parameter with the value of `params`. May also apply pipes to the bound
* parameter.
*
* For example, extracting all params:
* ```typescript
* findOne(@Param() params: string[])
* ```
*
* For example, extracting a single param:
* ```typescript
* findOne(@Param('id') id: string)
* ```
* @param property name of single property to extract from the `req` object
* @param pipes one or more pipes - either instances or classes - to apply to
* the bound parameter.
*
* @see [Request object](https://docs.nestjs.com/controllers#request-object)
* @see [Working with pipes](https://docs.nestjs.com/custom-decorators#working-with-pipes)
*
* @publicApi
*/
export function Param(
property?: string | (Type<PipeTransform> | PipeTransform),
...pipes: (Type<PipeTransform> | PipeTransform)[]
): ParameterDecorator {
return createPipesRouteParamDecorator(RouteParamtypes.PARAM)(
property,
...pipes,
);
}
/**
* Route handler parameter decorator. Extracts the `hosts`
* property from the `req` object and populates the decorated
* parameter with the value of `hosts`. May also apply pipes to the bound
* parameter.
*
* For example, extracting all params:
* ```typescript
* findOne(@HostParam() params: string[])
* ```
*
* For example, extracting a single param:
* ```typescript
* findOne(@HostParam('id') id: string)
* ```
* @param property name of single property to extract from the `req` object
*
* @see [Request object](https://docs.nestjs.com/controllers#request-object)
*
* @publicApi
*/
export function HostParam(): ParameterDecorator;
/**
* Route handler parameter decorator. Extracts the `hosts`
* property from the `req` object and populates the decorated
* parameter with the value of `hosts`. May also apply pipes to the bound
* parameter.
*
* For example, extracting all params:
* ```typescript
* findOne(@HostParam() params: string[])
* ```
*
* For example, extracting a single param:
* ```typescript
* findOne(@HostParam('id') id: string)
* ```
* @param property name of single property to extract from the `req` object
*
* @see [Request object](https://docs.nestjs.com/controllers#request-object)
*
* @publicApi
*/
export function HostParam(property: string): ParameterDecorator;
/**
* Route handler parameter decorator. Extracts the `hosts`
* property from the `req` object and populates the decorated
* parameter with the value of `params`. May also apply pipes to the bound
* parameter.
*
* For example, extracting all params:
* ```typescript
* findOne(@HostParam() params: string[])
* ```
*
* For example, extracting a single param:
* ```typescript
* findOne(@HostParam('id') id: string)
* ```
* @param property name of single property to extract from the `req` object
*
* @see [Request object](https://docs.nestjs.com/controllers#request-object)
*
* @publicApi
*/
export function HostParam(
property?: string | (Type<PipeTransform> | PipeTransform),
): ParameterDecorator {
return createRouteParamDecorator(RouteParamtypes.HOST)(property);
}
export const Req = Request;
export const Res = Response;
| packages/common/decorators/http/route-params.decorator.ts | 0 | https://github.com/nestjs/nest/commit/b4aca5d01facba08fceeea657454f9c92dbb7269 | [
0.00030252052238211036,
0.0001731817319523543,
0.00016412409604527056,
0.00016675752704031765,
0.000020922776457155123
] |
{
"id": 0,
"code_window": [
"import { HttpStatus } from '../enums/http-status.enum';\n",
"import { HttpException } from './http.exception';\n",
"\n",
"/**\n",
" * Defines an HTTP exception for *Unprocessable Entity* type errors.\n",
" *\n",
" * @see [Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions)\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { HttpException, HttpExceptionOptions } from './http.exception';\n"
],
"file_path": "packages/common/exceptions/unprocessable-entity.exception.ts",
"type": "replace",
"edit_start_line_idx": 1
} | import { codechecks, CodeChecksReport } from '@codechecks/client';
import * as bytes from 'bytes';
import { Benchmarks, getBenchmarks, LIBS } from './get-benchmarks';
const markdownTable = require('markdown-table');
const benchmarksKey = 'nest/performance-benchmark';
export default async function checkBenchmarks() {
const currentBenchmarks = await getBenchmarks();
await codechecks.saveValue(benchmarksKey, currentBenchmarks);
if (!codechecks.isPr()) {
return;
}
const baselineBenchmarks = await codechecks.getValue<Benchmarks>(
benchmarksKey,
);
const report = getCodechecksReport(currentBenchmarks, baselineBenchmarks);
await codechecks.report(report);
}
function getCodechecksReport(
current: Benchmarks,
baseline: Benchmarks | undefined,
): CodeChecksReport {
const diff = getDiff(current, baseline);
const shortDescription = getShortDescription(baseline, diff);
const longDescription = getLongDescription(current, baseline, diff);
return {
name: 'Benchmarks',
status: 'success',
shortDescription,
longDescription,
};
}
function getShortDescription(
baseline: Benchmarks | undefined,
diff: BenchmarksDiff,
): string {
if (!baseline) {
return 'New benchmarks generated';
}
const avgDiff = getAverageDiff(diff);
if (avgDiff > 0) {
return `Performance improved by ${avgDiff.toFixed(
2,
)}% on average, good job!`;
}
if (avgDiff === 0) {
return `No changes in performance detected`;
}
if (avgDiff < 0) {
return `Performance decreased by ${avgDiff.toFixed(
2,
)}% on average, be careful!`;
}
}
function getLongDescription(
current: Benchmarks,
baseline: Benchmarks | undefined,
diff: BenchmarksDiff,
): string {
function printTableRow(id: string, label: string): string[] {
return [
label,
current[id].requestsPerSec.toFixed(0),
current[id].transferPerSec,
baseline ? formatPerc(diff[id].requestsPerSecDiff) : '-',
baseline ? formatPerc(diff[id].transferPerSecDiff) : '-',
];
}
const table = [
['', 'Req/sec', 'Trans/sec', 'Req/sec DIFF', 'Trans/sec DIFF'],
printTableRow('nest', 'Nest-Express'),
printTableRow('nest-fastify', 'Nest-Fastify'),
printTableRow('express', 'Express'),
printTableRow('fastify', 'Fastify'),
];
return markdownTable(table);
}
function getDiff(
current: Benchmarks,
baseline: Benchmarks | undefined,
): BenchmarksDiff {
const diff: BenchmarksDiff = {};
for (const l of LIBS) {
if (!baseline) {
diff[l] = undefined;
continue;
}
const currentValue = current[l];
const baselineValue = baseline[l];
diff[l] = {
requestsPerSecDiff: getRequestDiff(
currentValue.requestsPerSec,
baselineValue.requestsPerSec,
),
transferPerSecDiff: getTransferDiff(
currentValue.transferPerSec,
baselineValue.transferPerSec,
),
};
}
return diff;
}
function getTransferDiff(
currentTransfer: string,
baselineTransfer: string,
): number {
return 1 - bytes.parse(currentTransfer) / bytes.parse(baselineTransfer);
}
function getAverageDiff(diff: BenchmarksDiff) {
return (
(diff['nest'].transferPerSecDiff +
diff['nest'].requestsPerSecDiff +
diff['nest-fastify'].transferPerSecDiff +
diff['nest-fastify'].requestsPerSecDiff) /
4
);
}
function getRequestDiff(currentRequest: number, baselineRequest: number) {
return 1 - currentRequest / baselineRequest;
}
interface BenchmarkDiff {
transferPerSecDiff: number | undefined;
requestsPerSecDiff: number | undefined;
}
interface BenchmarksDiff {
[lib: string]: BenchmarkDiff;
}
function formatPerc(n: number) {
return (n > 0 ? '+' : '') + (n * 100).toFixed(2) + '%';
}
| tools/benchmarks/check-benchmarks.ts | 0 | https://github.com/nestjs/nest/commit/b4aca5d01facba08fceeea657454f9c92dbb7269 | [
0.00017105699225794524,
0.00016801334277261049,
0.00016620320093352348,
0.00016811906243674457,
0.000001231667283718707
] |
{
"id": 1,
"code_window": [
" * @usageNotes\n",
" * The HTTP response status code will be 422.\n",
" * - The `objectOrError` argument defines the JSON response body or the message string.\n",
" * - The `description` argument contains a short description of the HTTP error.\n",
" *\n",
" * By default, the JSON response body contains two properties:\n",
" * - `statusCode`: this will be the value 422.\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" * - The `descriptionOrOptions` argument contains either a short description of the HTTP error or an options object used to provide an underlying error cause.\n"
],
"file_path": "packages/common/exceptions/unprocessable-entity.exception.ts",
"type": "replace",
"edit_start_line_idx": 20
} | import { HttpStatus } from '../enums/http-status.enum';
import { HttpException } from './http.exception';
/**
* Defines an HTTP exception for *Unprocessable Entity* type errors.
*
* @see [Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions)
*
* @publicApi
*/
export class UnprocessableEntityException extends HttpException {
/**
* Instantiate an `UnprocessableEntityException` Exception.
*
* @example
* `throw new UnprocessableEntityException()`
*
* @usageNotes
* The HTTP response status code will be 422.
* - The `objectOrError` argument defines the JSON response body or the message string.
* - The `description` argument contains a short description of the HTTP error.
*
* By default, the JSON response body contains two properties:
* - `statusCode`: this will be the value 422.
* - `message`: the string `'Unprocessable Entity'` by default; override this by supplying
* a string in the `objectOrError` parameter.
*
* If the parameter `objectOrError` is a string, the response body will contain an
* additional property, `error`, with a short description of the HTTP error. To override the
* entire JSON response body, pass an object instead. Nest will serialize the object
* and return it as the JSON response body.
*
* @param objectOrError string or object describing the error condition.
* @param description a short description of the HTTP error.
*/
constructor(
objectOrError?: string | object | any,
description = 'Unprocessable Entity',
) {
super(
HttpException.createBody(
objectOrError,
description,
HttpStatus.UNPROCESSABLE_ENTITY,
),
HttpStatus.UNPROCESSABLE_ENTITY,
);
}
}
| packages/common/exceptions/unprocessable-entity.exception.ts | 1 | https://github.com/nestjs/nest/commit/b4aca5d01facba08fceeea657454f9c92dbb7269 | [
0.001477522891946137,
0.0006708122091367841,
0.00017666324856691062,
0.0006562811904586852,
0.00047238715342245996
] |
{
"id": 1,
"code_window": [
" * @usageNotes\n",
" * The HTTP response status code will be 422.\n",
" * - The `objectOrError` argument defines the JSON response body or the message string.\n",
" * - The `description` argument contains a short description of the HTTP error.\n",
" *\n",
" * By default, the JSON response body contains two properties:\n",
" * - `statusCode`: this will be the value 422.\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" * - The `descriptionOrOptions` argument contains either a short description of the HTTP error or an options object used to provide an underlying error cause.\n"
],
"file_path": "packages/common/exceptions/unprocessable-entity.exception.ts",
"type": "replace",
"edit_start_line_idx": 20
} | import { expect } from 'chai';
import { Module } from '../../decorators/modules/module.decorator';
describe('@Module', () => {
const moduleProps = {
providers: ['Test'],
imports: ['Test'],
exports: ['Test'],
controllers: ['Test'],
};
@Module(moduleProps as any)
class TestModule {}
it('should enhance class with expected module metadata', () => {
const imports = Reflect.getMetadata('imports', TestModule);
const providers = Reflect.getMetadata('providers', TestModule);
const exports = Reflect.getMetadata('exports', TestModule);
const controllers = Reflect.getMetadata('controllers', TestModule);
expect(imports).to.be.eql(moduleProps.imports);
expect(providers).to.be.eql(moduleProps.providers);
expect(controllers).to.be.eql(moduleProps.controllers);
expect(exports).to.be.eql(moduleProps.exports);
});
it('should throw exception when module properties are invalid', () => {
const invalidProps = {
...moduleProps,
test: [],
};
expect(Module.bind(null, invalidProps)).to.throw(Error);
});
});
| packages/common/test/decorators/module.decorator.spec.ts | 0 | https://github.com/nestjs/nest/commit/b4aca5d01facba08fceeea657454f9c92dbb7269 | [
0.00017094024224206805,
0.00016901885101106018,
0.00016778467397671193,
0.00016867523663677275,
0.0000012561267794808373
] |
{
"id": 1,
"code_window": [
" * @usageNotes\n",
" * The HTTP response status code will be 422.\n",
" * - The `objectOrError` argument defines the JSON response body or the message string.\n",
" * - The `description` argument contains a short description of the HTTP error.\n",
" *\n",
" * By default, the JSON response body contains two properties:\n",
" * - `statusCode`: this will be the value 422.\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" * - The `descriptionOrOptions` argument contains either a short description of the HTTP error or an options object used to provide an underlying error cause.\n"
],
"file_path": "packages/common/exceptions/unprocessable-entity.exception.ts",
"type": "replace",
"edit_start_line_idx": 20
} | import { getDirs } from './util/task-helpers';
// All paths are related to the base dir
export const source = 'packages';
export const samplePath = 'sample';
export const packagePaths = getDirs(source);
| tools/gulp/config.ts | 0 | https://github.com/nestjs/nest/commit/b4aca5d01facba08fceeea657454f9c92dbb7269 | [
0.0001722015585983172,
0.0001722015585983172,
0.0001722015585983172,
0.0001722015585983172,
0
] |
{
"id": 1,
"code_window": [
" * @usageNotes\n",
" * The HTTP response status code will be 422.\n",
" * - The `objectOrError` argument defines the JSON response body or the message string.\n",
" * - The `description` argument contains a short description of the HTTP error.\n",
" *\n",
" * By default, the JSON response body contains two properties:\n",
" * - `statusCode`: this will be the value 422.\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" * - The `descriptionOrOptions` argument contains either a short description of the HTTP error or an options object used to provide an underlying error cause.\n"
],
"file_path": "packages/common/exceptions/unprocessable-entity.exception.ts",
"type": "replace",
"edit_start_line_idx": 20
} | import { Injectable } from '@nestjs/common';
import { Cat } from './interfaces/cat.interface';
@Injectable()
export class CatsService {
private readonly cats: Cat[] = [];
create(cat: Cat) {
this.cats.push(cat);
}
findAll(): Cat[] {
return this.cats;
}
}
| sample/10-fastify/src/cats/cats.service.ts | 0 | https://github.com/nestjs/nest/commit/b4aca5d01facba08fceeea657454f9c92dbb7269 | [
0.0001696436811471358,
0.000169266015291214,
0.00016888834943529218,
0.000169266015291214,
3.776658559218049e-7
] |
{
"id": 2,
"code_window": [
" * entire JSON response body, pass an object instead. Nest will serialize the object\n",
" * and return it as the JSON response body.\n",
" *\n",
" * @param objectOrError string or object describing the error condition.\n",
" * @param description a short description of the HTTP error.\n",
" */\n",
" constructor(\n",
" objectOrError?: string | object | any,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" * @param descriptionOrOptions either a short description of the HTTP error or an options object used to provide an underlying error cause\n"
],
"file_path": "packages/common/exceptions/unprocessable-entity.exception.ts",
"type": "replace",
"edit_start_line_idx": 33
} | import { HttpStatus } from '../enums/http-status.enum';
import { HttpException } from './http.exception';
/**
* Defines an HTTP exception for *Unprocessable Entity* type errors.
*
* @see [Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions)
*
* @publicApi
*/
export class UnprocessableEntityException extends HttpException {
/**
* Instantiate an `UnprocessableEntityException` Exception.
*
* @example
* `throw new UnprocessableEntityException()`
*
* @usageNotes
* The HTTP response status code will be 422.
* - The `objectOrError` argument defines the JSON response body or the message string.
* - The `description` argument contains a short description of the HTTP error.
*
* By default, the JSON response body contains two properties:
* - `statusCode`: this will be the value 422.
* - `message`: the string `'Unprocessable Entity'` by default; override this by supplying
* a string in the `objectOrError` parameter.
*
* If the parameter `objectOrError` is a string, the response body will contain an
* additional property, `error`, with a short description of the HTTP error. To override the
* entire JSON response body, pass an object instead. Nest will serialize the object
* and return it as the JSON response body.
*
* @param objectOrError string or object describing the error condition.
* @param description a short description of the HTTP error.
*/
constructor(
objectOrError?: string | object | any,
description = 'Unprocessable Entity',
) {
super(
HttpException.createBody(
objectOrError,
description,
HttpStatus.UNPROCESSABLE_ENTITY,
),
HttpStatus.UNPROCESSABLE_ENTITY,
);
}
}
| packages/common/exceptions/unprocessable-entity.exception.ts | 1 | https://github.com/nestjs/nest/commit/b4aca5d01facba08fceeea657454f9c92dbb7269 | [
0.9672165513038635,
0.42919570207595825,
0.00016502579092048109,
0.4403199851512909,
0.3808682858943939
] |
{
"id": 2,
"code_window": [
" * entire JSON response body, pass an object instead. Nest will serialize the object\n",
" * and return it as the JSON response body.\n",
" *\n",
" * @param objectOrError string or object describing the error condition.\n",
" * @param description a short description of the HTTP error.\n",
" */\n",
" constructor(\n",
" objectOrError?: string | object | any,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" * @param descriptionOrOptions either a short description of the HTTP error or an options object used to provide an underlying error cause\n"
],
"file_path": "packages/common/exceptions/unprocessable-entity.exception.ts",
"type": "replace",
"edit_start_line_idx": 33
} | {
"compilerOptions": {
"deleteOutDir": true
}
}
| sample/08-webpack/nest-cli.json | 0 | https://github.com/nestjs/nest/commit/b4aca5d01facba08fceeea657454f9c92dbb7269 | [
0.00017228416982106864,
0.00017228416982106864,
0.00017228416982106864,
0.00017228416982106864,
0
] |
{
"id": 2,
"code_window": [
" * entire JSON response body, pass an object instead. Nest will serialize the object\n",
" * and return it as the JSON response body.\n",
" *\n",
" * @param objectOrError string or object describing the error condition.\n",
" * @param description a short description of the HTTP error.\n",
" */\n",
" constructor(\n",
" objectOrError?: string | object | any,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" * @param descriptionOrOptions either a short description of the HTTP error or an options object used to provide an underlying error cause\n"
],
"file_path": "packages/common/exceptions/unprocessable-entity.exception.ts",
"type": "replace",
"edit_start_line_idx": 33
} | import { INestApplicationContext, WebSocketAdapter } from '@nestjs/common';
import { WsMessageHandler } from '@nestjs/common/interfaces';
import { isFunction } from '@nestjs/common/utils/shared.utils';
import { NestApplication } from '@nestjs/core';
import { Observable } from 'rxjs';
import { CONNECTION_EVENT, DISCONNECT_EVENT } from '../constants';
export interface BaseWsInstance {
on: (event: string, callback: Function) => void;
close: Function;
}
export abstract class AbstractWsAdapter<
TServer extends BaseWsInstance = any,
TClient extends BaseWsInstance = any,
TOptions = any,
> implements WebSocketAdapter<TServer, TClient, TOptions>
{
protected readonly httpServer: any;
constructor(appOrHttpServer?: INestApplicationContext | any) {
if (appOrHttpServer && appOrHttpServer instanceof NestApplication) {
this.httpServer = appOrHttpServer.getUnderlyingHttpServer();
} else {
this.httpServer = appOrHttpServer;
}
}
public bindClientConnect(server: TServer, callback: Function) {
server.on(CONNECTION_EVENT, callback);
}
public bindClientDisconnect(client: TClient, callback: Function) {
client.on(DISCONNECT_EVENT, callback);
}
public async close(server: TServer) {
const isCallable = server && isFunction(server.close);
isCallable && (await new Promise(resolve => server.close(resolve)));
}
// eslint-disable-next-line @typescript-eslint/no-empty-function
public async dispose() {}
public abstract create(port: number, options?: TOptions): TServer;
public abstract bindMessageHandlers(
client: TClient,
handlers: WsMessageHandler[],
transform: (data: any) => Observable<any>,
);
}
| packages/websockets/adapters/ws-adapter.ts | 0 | https://github.com/nestjs/nest/commit/b4aca5d01facba08fceeea657454f9c92dbb7269 | [
0.9895114302635193,
0.16507728397846222,
0.00017034943448379636,
0.00019390074885450304,
0.3686981499195099
] |
{
"id": 2,
"code_window": [
" * entire JSON response body, pass an object instead. Nest will serialize the object\n",
" * and return it as the JSON response body.\n",
" *\n",
" * @param objectOrError string or object describing the error condition.\n",
" * @param description a short description of the HTTP error.\n",
" */\n",
" constructor(\n",
" objectOrError?: string | object | any,\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" * @param descriptionOrOptions either a short description of the HTTP error or an options object used to provide an underlying error cause\n"
],
"file_path": "packages/common/exceptions/unprocessable-entity.exception.ts",
"type": "replace",
"edit_start_line_idx": 33
} | export const FORBIDDEN_MESSAGE = 'Forbidden resource';
| packages/core/guards/constants.ts | 0 | https://github.com/nestjs/nest/commit/b4aca5d01facba08fceeea657454f9c92dbb7269 | [
0.00030892007634975016,
0.00030892007634975016,
0.00030892007634975016,
0.00030892007634975016,
0
] |
{
"id": 3,
"code_window": [
" */\n",
" constructor(\n",
" objectOrError?: string | object | any,\n",
" description = 'Unprocessable Entity',\n",
" ) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" descriptionOrOptions:\n",
" | string\n",
" | HttpExceptionOptions = 'Unprocessable Entity',\n"
],
"file_path": "packages/common/exceptions/unprocessable-entity.exception.ts",
"type": "replace",
"edit_start_line_idx": 37
} | import { HttpStatus } from '../enums/http-status.enum';
import { HttpException } from './http.exception';
/**
* Defines an HTTP exception for *Unprocessable Entity* type errors.
*
* @see [Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions)
*
* @publicApi
*/
export class UnprocessableEntityException extends HttpException {
/**
* Instantiate an `UnprocessableEntityException` Exception.
*
* @example
* `throw new UnprocessableEntityException()`
*
* @usageNotes
* The HTTP response status code will be 422.
* - The `objectOrError` argument defines the JSON response body or the message string.
* - The `description` argument contains a short description of the HTTP error.
*
* By default, the JSON response body contains two properties:
* - `statusCode`: this will be the value 422.
* - `message`: the string `'Unprocessable Entity'` by default; override this by supplying
* a string in the `objectOrError` parameter.
*
* If the parameter `objectOrError` is a string, the response body will contain an
* additional property, `error`, with a short description of the HTTP error. To override the
* entire JSON response body, pass an object instead. Nest will serialize the object
* and return it as the JSON response body.
*
* @param objectOrError string or object describing the error condition.
* @param description a short description of the HTTP error.
*/
constructor(
objectOrError?: string | object | any,
description = 'Unprocessable Entity',
) {
super(
HttpException.createBody(
objectOrError,
description,
HttpStatus.UNPROCESSABLE_ENTITY,
),
HttpStatus.UNPROCESSABLE_ENTITY,
);
}
}
| packages/common/exceptions/unprocessable-entity.exception.ts | 1 | https://github.com/nestjs/nest/commit/b4aca5d01facba08fceeea657454f9c92dbb7269 | [
0.9971116781234741,
0.297940194606781,
0.0002103615115629509,
0.0033797684591263533,
0.39703884720802307
] |
{
"id": 3,
"code_window": [
" */\n",
" constructor(\n",
" objectOrError?: string | object | any,\n",
" description = 'Unprocessable Entity',\n",
" ) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" descriptionOrOptions:\n",
" | string\n",
" | HttpExceptionOptions = 'Unprocessable Entity',\n"
],
"file_path": "packages/common/exceptions/unprocessable-entity.exception.ts",
"type": "replace",
"edit_start_line_idx": 37
} | import { Injectable, Scope } from '@nestjs/common';
import { LoggerService } from './logger.service';
@Injectable({ scope: Scope.REQUEST })
export class RequestLoggerService {
constructor(public loggerService: LoggerService) {}
}
| integration/scopes/src/resolve-scoped/request-logger.service.ts | 0 | https://github.com/nestjs/nest/commit/b4aca5d01facba08fceeea657454f9c92dbb7269 | [
0.9845221042633057,
0.9845221042633057,
0.9845221042633057,
0.9845221042633057,
0
] |
{
"id": 3,
"code_window": [
" */\n",
" constructor(\n",
" objectOrError?: string | object | any,\n",
" description = 'Unprocessable Entity',\n",
" ) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" descriptionOrOptions:\n",
" | string\n",
" | HttpExceptionOptions = 'Unprocessable Entity',\n"
],
"file_path": "packages/common/exceptions/unprocessable-entity.exception.ts",
"type": "replace",
"edit_start_line_idx": 37
} | export * from './inquirer-constants';
| packages/core/injector/inquirer/index.ts | 0 | https://github.com/nestjs/nest/commit/b4aca5d01facba08fceeea657454f9c92dbb7269 | [
0.00017503400158602744,
0.00017503400158602744,
0.00017503400158602744,
0.00017503400158602744,
0
] |
{
"id": 3,
"code_window": [
" */\n",
" constructor(\n",
" objectOrError?: string | object | any,\n",
" description = 'Unprocessable Entity',\n",
" ) {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep"
],
"after_edit": [
" descriptionOrOptions:\n",
" | string\n",
" | HttpExceptionOptions = 'Unprocessable Entity',\n"
],
"file_path": "packages/common/exceptions/unprocessable-entity.exception.ts",
"type": "replace",
"edit_start_line_idx": 37
} | import { Document } from 'mongoose';
export interface Cat extends Document {
readonly name: string;
readonly age: number;
readonly breed: string;
}
| sample/14-mongoose-base/src/cats/interfaces/cat.interface.ts | 0 | https://github.com/nestjs/nest/commit/b4aca5d01facba08fceeea657454f9c92dbb7269 | [
0.00016997559578157961,
0.00016997559578157961,
0.00016997559578157961,
0.00016997559578157961,
0
] |
{
"id": 4,
"code_window": [
" ) {\n",
" super(\n",
" HttpException.createBody(\n",
" objectOrError,\n",
" description,\n"
],
"labels": [
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const { description, httpExceptionOptions } =\n",
" HttpException.extractDescriptionAndOptionsFrom(descriptionOrOptions);\n",
"\n"
],
"file_path": "packages/common/exceptions/unprocessable-entity.exception.ts",
"type": "add",
"edit_start_line_idx": 39
} | import { HttpStatus } from '../enums/http-status.enum';
import { HttpException } from './http.exception';
/**
* Defines an HTTP exception for *Unprocessable Entity* type errors.
*
* @see [Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions)
*
* @publicApi
*/
export class UnprocessableEntityException extends HttpException {
/**
* Instantiate an `UnprocessableEntityException` Exception.
*
* @example
* `throw new UnprocessableEntityException()`
*
* @usageNotes
* The HTTP response status code will be 422.
* - The `objectOrError` argument defines the JSON response body or the message string.
* - The `description` argument contains a short description of the HTTP error.
*
* By default, the JSON response body contains two properties:
* - `statusCode`: this will be the value 422.
* - `message`: the string `'Unprocessable Entity'` by default; override this by supplying
* a string in the `objectOrError` parameter.
*
* If the parameter `objectOrError` is a string, the response body will contain an
* additional property, `error`, with a short description of the HTTP error. To override the
* entire JSON response body, pass an object instead. Nest will serialize the object
* and return it as the JSON response body.
*
* @param objectOrError string or object describing the error condition.
* @param description a short description of the HTTP error.
*/
constructor(
objectOrError?: string | object | any,
description = 'Unprocessable Entity',
) {
super(
HttpException.createBody(
objectOrError,
description,
HttpStatus.UNPROCESSABLE_ENTITY,
),
HttpStatus.UNPROCESSABLE_ENTITY,
);
}
}
| packages/common/exceptions/unprocessable-entity.exception.ts | 1 | https://github.com/nestjs/nest/commit/b4aca5d01facba08fceeea657454f9c92dbb7269 | [
0.026045797392725945,
0.006250162608921528,
0.0001856842718552798,
0.0007995120249688625,
0.00996372289955616
] |
{
"id": 4,
"code_window": [
" ) {\n",
" super(\n",
" HttpException.createBody(\n",
" objectOrError,\n",
" description,\n"
],
"labels": [
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const { description, httpExceptionOptions } =\n",
" HttpException.extractDescriptionAndOptionsFrom(descriptionOrOptions);\n",
"\n"
],
"file_path": "packages/common/exceptions/unprocessable-entity.exception.ts",
"type": "add",
"edit_start_line_idx": 39
} | import { HttpStatus } from '../enums/http-status.enum';
import { HttpException, HttpExceptionOptions } from './http.exception';
/**
* Defines an HTTP exception for *Gone* type errors.
*
* @see [Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions)
*
* @publicApi
*/
export class GoneException extends HttpException {
/**
* Instantiate a `GoneException` Exception.
*
* @example
* `throw new GoneException()`
*
* @usageNotes
* The HTTP response status code will be 410.
* - The `objectOrError` argument defines the JSON response body or the message string.
* - The `descriptionOrOptions` argument contains either a short description of the HTTP error or an options object used to provide an underlying error cause.
*
* By default, the JSON response body contains two properties:
* - `statusCode`: this will be the value 410.
* - `message`: the string `'Gone'` by default; override this by supplying
* a string in the `objectOrError` parameter.
*
* If the parameter `objectOrError` is a string, the response body will contain an
* additional property, `error`, with a short description of the HTTP error. To override the
* entire JSON response body, pass an object instead. Nest will serialize the object
* and return it as the JSON response body.
*
* @param objectOrError string or object describing the error condition.
* @param descriptionOrOptions either a short description of the HTTP error or an options object used to provide an underlying error cause
*/
constructor(
objectOrError?: string | object | any,
descriptionOrOptions: string | HttpExceptionOptions = 'Gone',
) {
const { description, httpExceptionOptions } =
HttpException.extractDescriptionAndOptionsFrom(descriptionOrOptions);
super(
HttpException.createBody(objectOrError, description, HttpStatus.GONE),
HttpStatus.GONE,
httpExceptionOptions,
);
}
}
| packages/common/exceptions/gone.exception.ts | 0 | https://github.com/nestjs/nest/commit/b4aca5d01facba08fceeea657454f9c92dbb7269 | [
0.3132491409778595,
0.06358950585126877,
0.00020646203483920544,
0.0013327592751011252,
0.12483234703540802
] |
{
"id": 4,
"code_window": [
" ) {\n",
" super(\n",
" HttpException.createBody(\n",
" objectOrError,\n",
" description,\n"
],
"labels": [
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const { description, httpExceptionOptions } =\n",
" HttpException.extractDescriptionAndOptionsFrom(descriptionOrOptions);\n",
"\n"
],
"file_path": "packages/common/exceptions/unprocessable-entity.exception.ts",
"type": "add",
"edit_start_line_idx": 39
} | import { INestApplication } from '@nestjs/common';
import { Test } from '@nestjs/testing';
import * as request from 'supertest';
import { AppModule } from '../src/app.module';
describe('GraphQL - Code-first', () => {
let app: INestApplication;
beforeEach(async () => {
const module = await Test.createTestingModule({
imports: [AppModule],
}).compile();
app = module.createNestApplication();
await app.init();
});
it(`should return query result`, () => {
return request(app.getHttpServer())
.post('/graphql')
.send({
operationName: null,
variables: {},
query: '{\n recipes {\n id\n }\n}\n',
})
.expect(200, {
data: {
recipes: [],
},
});
});
afterEach(async () => {
await app.close();
});
});
| integration/graphql-code-first/e2e/code-first.spec.ts | 0 | https://github.com/nestjs/nest/commit/b4aca5d01facba08fceeea657454f9c92dbb7269 | [
0.0001727834460325539,
0.0001710972865112126,
0.0001691065263003111,
0.00017124958685599267,
0.0000013635997220262652
] |
{
"id": 4,
"code_window": [
" ) {\n",
" super(\n",
" HttpException.createBody(\n",
" objectOrError,\n",
" description,\n"
],
"labels": [
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const { description, httpExceptionOptions } =\n",
" HttpException.extractDescriptionAndOptionsFrom(descriptionOrOptions);\n",
"\n"
],
"file_path": "packages/common/exceptions/unprocessable-entity.exception.ts",
"type": "add",
"edit_start_line_idx": 39
} | import { expect } from 'chai';
import {
addLeadingSlash,
isConstructor,
isEmpty,
isFunction,
isNil,
isNumber,
isObject,
isPlainObject,
isString,
isSymbol,
isUndefined,
normalizePath,
stripEndSlash,
} from '../../utils/shared.utils';
function Foo(a) {
this.a = 1;
}
describe('Shared utils', () => {
describe('isUndefined', () => {
it('should return true when obj is undefined', () => {
expect(isUndefined(undefined)).to.be.true;
});
it('should return false when object is not undefined', () => {
expect(isUndefined({})).to.be.false;
});
});
describe('isFunction', () => {
it('should return true when obj is function', () => {
expect(isFunction(() => ({}))).to.be.true;
});
it('should return false when object is not function', () => {
expect(isFunction(null)).to.be.false;
expect(isFunction(undefined)).to.be.false;
});
});
describe('isObject', () => {
it('should return true when obj is object', () => {
expect(isObject({})).to.be.true;
});
it('should return false when object is not object', () => {
expect(isObject(3)).to.be.false;
expect(isObject(null)).to.be.false;
expect(isObject(undefined)).to.be.false;
});
});
describe('isPlainObject', () => {
it('should return true when obj is plain object', () => {
expect(isPlainObject({})).to.be.true;
expect(isPlainObject({ prop: true })).to.be.true;
expect(
isPlainObject({
constructor: Foo,
}),
).to.be.true;
expect(isPlainObject(Object.create(null))).to.be.true;
});
it('should return false when object is not object', () => {
expect(isPlainObject(3)).to.be.false;
expect(isPlainObject(null)).to.be.false;
expect(isPlainObject(undefined)).to.be.false;
expect(isPlainObject([1, 2, 3])).to.be.false;
expect(isPlainObject(new Date())).to.be.false;
expect(isPlainObject(new Foo(1))).to.be.false;
});
});
describe('isString', () => {
it('should return true when val is a string', () => {
expect(isString('true')).to.be.true;
});
it('should return false when val is not a string', () => {
expect(isString(new String('fine'))).to.be.false;
expect(isString(false)).to.be.false;
expect(isString(null)).to.be.false;
expect(isString(undefined)).to.be.false;
});
});
describe('isSymbol', () => {
it('should return true when val is a Symbol', () => {
expect(isSymbol(Symbol())).to.be.true;
});
it('should return false when val is not a symbol', () => {
expect(isSymbol('Symbol()')).to.be.false;
expect(isSymbol(false)).to.be.false;
expect(isSymbol(null)).to.be.false;
expect(isSymbol(undefined)).to.be.false;
});
});
describe('isNumber', () => {
it('should return true when val is a number or NaN', () => {
expect(isNumber(1)).to.be.true;
expect(isNumber(1.23)).to.be.true; // with decimals
expect(isNumber(123e-5)).to.be.true; // scientific (exponent) notation
expect(isNumber(0o1)).to.be.true; // octal notation
expect(isNumber(0b1)).to.be.true; // binary notation
expect(isNumber(0x1)).to.be.true; // hexadecimal notation
expect(isNumber(NaN)).to.be.true;
});
it('should return false when val is not a number', () => {
// expect(isNumber(1n)).to.be.false; // big int (available on ES2020)
expect(isNumber('1')).to.be.false; // string
expect(isNumber(undefined)).to.be.false; // nullish
expect(isNumber(null)).to.be.false; // nullish
});
});
describe('isConstructor', () => {
it('should return true when string is equal to constructor', () => {
expect(isConstructor('constructor')).to.be.true;
});
it('should return false when string is not equal to constructor', () => {
expect(isConstructor('nope')).to.be.false;
});
});
describe('addLeadingSlash', () => {
it('should return the validated path ("add / if not exists")', () => {
expect(addLeadingSlash('nope')).to.be.eql('/nope');
});
it('should return the same path', () => {
expect(addLeadingSlash('/nope')).to.be.eql('/nope');
});
it('should return empty path', () => {
expect(addLeadingSlash('')).to.be.eql('');
expect(addLeadingSlash(null)).to.be.eql('');
expect(addLeadingSlash(undefined)).to.be.eql('');
});
});
describe('normalizePath', () => {
it('should remove all trailing slashes at the end of the path', () => {
expect(normalizePath('path/')).to.be.eql('/path');
expect(normalizePath('path///')).to.be.eql('/path');
expect(normalizePath('/path/path///')).to.be.eql('/path/path');
});
it('should replace all slashes with only one slash', () => {
expect(normalizePath('////path/')).to.be.eql('/path');
expect(normalizePath('///')).to.be.eql('/');
expect(normalizePath('/path////path///')).to.be.eql('/path/path');
});
it('should return / for empty path', () => {
expect(normalizePath('')).to.be.eql('/');
expect(normalizePath(null)).to.be.eql('/');
expect(normalizePath(undefined)).to.be.eql('/');
});
});
describe('isNil', () => {
it('should return true when obj is undefined or null', () => {
expect(isNil(undefined)).to.be.true;
expect(isNil(null)).to.be.true;
});
it('should return false when object is not undefined and null', () => {
expect(isNil('3')).to.be.false;
});
});
describe('isEmpty', () => {
it('should return true when array is empty or not exists', () => {
expect(isEmpty([])).to.be.true;
expect(isEmpty(null)).to.be.true;
expect(isEmpty(undefined)).to.be.true;
});
it('should return false when array is not empty', () => {
expect(isEmpty([1, 2])).to.be.false;
});
});
describe('stripEndSlash', () => {
it('should strip end slash if present', () => {
expect(stripEndSlash('/cats/')).to.equal('/cats');
expect(stripEndSlash('/cats')).to.equal('/cats');
});
});
});
| packages/common/test/utils/shared.utils.spec.ts | 0 | https://github.com/nestjs/nest/commit/b4aca5d01facba08fceeea657454f9c92dbb7269 | [
0.00017643194587435573,
0.00017097235831897706,
0.0001680705026956275,
0.00017029243463184685,
0.0000020779282294824952
] |
{
"id": 5,
"code_window": [
" description,\n",
" HttpStatus.UNPROCESSABLE_ENTITY,\n",
" ),\n",
" HttpStatus.UNPROCESSABLE_ENTITY,\n",
" );\n",
" }\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" httpExceptionOptions,\n"
],
"file_path": "packages/common/exceptions/unprocessable-entity.exception.ts",
"type": "add",
"edit_start_line_idx": 46
} | import { HttpStatus } from '../enums/http-status.enum';
import { HttpException } from './http.exception';
/**
* Defines an HTTP exception for *Unprocessable Entity* type errors.
*
* @see [Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions)
*
* @publicApi
*/
export class UnprocessableEntityException extends HttpException {
/**
* Instantiate an `UnprocessableEntityException` Exception.
*
* @example
* `throw new UnprocessableEntityException()`
*
* @usageNotes
* The HTTP response status code will be 422.
* - The `objectOrError` argument defines the JSON response body or the message string.
* - The `description` argument contains a short description of the HTTP error.
*
* By default, the JSON response body contains two properties:
* - `statusCode`: this will be the value 422.
* - `message`: the string `'Unprocessable Entity'` by default; override this by supplying
* a string in the `objectOrError` parameter.
*
* If the parameter `objectOrError` is a string, the response body will contain an
* additional property, `error`, with a short description of the HTTP error. To override the
* entire JSON response body, pass an object instead. Nest will serialize the object
* and return it as the JSON response body.
*
* @param objectOrError string or object describing the error condition.
* @param description a short description of the HTTP error.
*/
constructor(
objectOrError?: string | object | any,
description = 'Unprocessable Entity',
) {
super(
HttpException.createBody(
objectOrError,
description,
HttpStatus.UNPROCESSABLE_ENTITY,
),
HttpStatus.UNPROCESSABLE_ENTITY,
);
}
}
| packages/common/exceptions/unprocessable-entity.exception.ts | 1 | https://github.com/nestjs/nest/commit/b4aca5d01facba08fceeea657454f9c92dbb7269 | [
0.5656909346580505,
0.11328457295894623,
0.00016515864990651608,
0.00019319640705361962,
0.22620317339897156
] |
{
"id": 5,
"code_window": [
" description,\n",
" HttpStatus.UNPROCESSABLE_ENTITY,\n",
" ),\n",
" HttpStatus.UNPROCESSABLE_ENTITY,\n",
" );\n",
" }\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" httpExceptionOptions,\n"
],
"file_path": "packages/common/exceptions/unprocessable-entity.exception.ts",
"type": "add",
"edit_start_line_idx": 46
} | import { CanActivate } from '@nestjs/common';
import { ContextType, Controller } from '@nestjs/common/interfaces';
import { isEmpty } from '@nestjs/common/utils/shared.utils';
import { lastValueFrom, Observable } from 'rxjs';
import { ExecutionContextHost } from '../helpers/execution-context-host';
export class GuardsConsumer {
public async tryActivate<TContext extends string = ContextType>(
guards: CanActivate[],
args: unknown[],
instance: Controller,
callback: (...args: unknown[]) => unknown,
type?: TContext,
): Promise<boolean> {
if (!guards || isEmpty(guards)) {
return true;
}
const context = this.createContext(args, instance, callback);
context.setType<TContext>(type);
for (const guard of guards) {
const result = guard.canActivate(context);
if (await this.pickResult(result)) {
continue;
}
return false;
}
return true;
}
public createContext(
args: unknown[],
instance: Controller,
callback: (...args: unknown[]) => unknown,
): ExecutionContextHost {
return new ExecutionContextHost(
args,
instance.constructor as any,
callback,
);
}
public async pickResult(
result: boolean | Promise<boolean> | Observable<boolean>,
): Promise<boolean> {
if (result instanceof Observable) {
return lastValueFrom(result);
}
return result;
}
}
| packages/core/guards/guards-consumer.ts | 0 | https://github.com/nestjs/nest/commit/b4aca5d01facba08fceeea657454f9c92dbb7269 | [
0.00017743762873578817,
0.0001736855338094756,
0.00017155861132778227,
0.0001730975927785039,
0.0000020366239823488286
] |
{
"id": 5,
"code_window": [
" description,\n",
" HttpStatus.UNPROCESSABLE_ENTITY,\n",
" ),\n",
" HttpStatus.UNPROCESSABLE_ENTITY,\n",
" );\n",
" }\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" httpExceptionOptions,\n"
],
"file_path": "packages/common/exceptions/unprocessable-entity.exception.ts",
"type": "add",
"edit_start_line_idx": 46
} | # compiled output
/dist
/node_modules
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# OS
.DS_Store
# Tests
/coverage
/.nyc_output
# IDEs and editors
/.idea
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
# IDE - VSCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json | sample/27-scheduling/.gitignore | 0 | https://github.com/nestjs/nest/commit/b4aca5d01facba08fceeea657454f9c92dbb7269 | [
0.00017336451855953783,
0.00017088324239011854,
0.00016829741070978343,
0.0001709354983177036,
0.0000018682038671613554
] |
{
"id": 5,
"code_window": [
" description,\n",
" HttpStatus.UNPROCESSABLE_ENTITY,\n",
" ),\n",
" HttpStatus.UNPROCESSABLE_ENTITY,\n",
" );\n",
" }\n",
"}"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" httpExceptionOptions,\n"
],
"file_path": "packages/common/exceptions/unprocessable-entity.exception.ts",
"type": "add",
"edit_start_line_idx": 46
} | import { ConfigurableModuleAsyncOptions } from './configurable-module-async-options.interface';
import { ConfigurableModuleCls } from './configurable-module-cls.interface';
/**
* Configurable module host. See properties for more details
*
* @publicApi
*/
export interface ConfigurableModuleHost<
ModuleOptions = Record<string, unknown>,
MethodKey extends string = string,
FactoryClassMethodKey extends string = string,
ExtraModuleDefinitionOptions = {},
> {
/**
* Class that represents a blueprint/prototype for a configurable Nest module.
* This class provides static methods for constructing dynamic modules. Their names
* can be controlled through the "MethodKey" type argument.
*
* Your module class should inherit from this class to make the static methods available.
*
* @example
* ```typescript
* @Module({})
* class IntegrationModule extends ConfigurableModuleCls {
* // ...
* }
* ```
*/
ConfigurableModuleClass: ConfigurableModuleCls<
ModuleOptions,
MethodKey,
FactoryClassMethodKey,
ExtraModuleDefinitionOptions
>;
/**
* Module options provider token. Can be used to inject the "options object" to
* providers registered within the host module.
*/
MODULE_OPTIONS_TOKEN: string | symbol;
/**
* Can be used to auto-infer the compound "async module options" type.
* Note: this property is not supposed to be used as a value.
*
* @example
* ```typescript
* @Module({})
* class IntegrationModule extends ConfigurableModuleCls {
* static module = initializer(IntegrationModule);
*
* static registerAsync(options: typeof ASYNC_OPTIONS_TYPE): DynamicModule {
* return super.registerAsync(options);
* }
* ```
*/
ASYNC_OPTIONS_TYPE: ConfigurableModuleAsyncOptions<
ModuleOptions,
FactoryClassMethodKey
> &
Partial<ExtraModuleDefinitionOptions>;
/**
* Can be used to auto-infer the compound "module options" type (options interface + extra module definition options).
* Note: this property is not supposed to be used as a value.
*
* @example
* ```typescript
* @Module({})
* class IntegrationModule extends ConfigurableModuleCls {
* static module = initializer(IntegrationModule);
*
* static register(options: typeof OPTIONS_TYPE): DynamicModule {
* return super.register(options);
* }
* ```
*/
OPTIONS_TYPE: ModuleOptions & Partial<ExtraModuleDefinitionOptions>;
}
| packages/common/module-utils/interfaces/configurable-module-host.interface.ts | 0 | https://github.com/nestjs/nest/commit/b4aca5d01facba08fceeea657454f9c92dbb7269 | [
0.00035094679333269596,
0.00019310772768221796,
0.00016609927115496248,
0.00016988485003821552,
0.00005983813025522977
] |
{
"id": 6,
"code_window": [
" PayloadTooLargeException,\n",
" PreconditionFailedException,\n",
" RequestTimeoutException,\n",
" ServiceUnavailableException,\n",
" UnauthorizedException,\n",
"} from '../../exceptions';\n",
"\n",
"describe('HttpException', () => {\n",
" describe('getResponse', () => {\n",
" it('should return a response as a string when input is a string', () => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" UnprocessableEntityException,\n"
],
"file_path": "packages/common/test/exceptions/http.exception.spec.ts",
"type": "add",
"edit_start_line_idx": 22
} | import { HttpStatus } from '../enums/http-status.enum';
import { HttpException } from './http.exception';
/**
* Defines an HTTP exception for *Unprocessable Entity* type errors.
*
* @see [Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions)
*
* @publicApi
*/
export class UnprocessableEntityException extends HttpException {
/**
* Instantiate an `UnprocessableEntityException` Exception.
*
* @example
* `throw new UnprocessableEntityException()`
*
* @usageNotes
* The HTTP response status code will be 422.
* - The `objectOrError` argument defines the JSON response body or the message string.
* - The `description` argument contains a short description of the HTTP error.
*
* By default, the JSON response body contains two properties:
* - `statusCode`: this will be the value 422.
* - `message`: the string `'Unprocessable Entity'` by default; override this by supplying
* a string in the `objectOrError` parameter.
*
* If the parameter `objectOrError` is a string, the response body will contain an
* additional property, `error`, with a short description of the HTTP error. To override the
* entire JSON response body, pass an object instead. Nest will serialize the object
* and return it as the JSON response body.
*
* @param objectOrError string or object describing the error condition.
* @param description a short description of the HTTP error.
*/
constructor(
objectOrError?: string | object | any,
description = 'Unprocessable Entity',
) {
super(
HttpException.createBody(
objectOrError,
description,
HttpStatus.UNPROCESSABLE_ENTITY,
),
HttpStatus.UNPROCESSABLE_ENTITY,
);
}
}
| packages/common/exceptions/unprocessable-entity.exception.ts | 1 | https://github.com/nestjs/nest/commit/b4aca5d01facba08fceeea657454f9c92dbb7269 | [
0.0006909486255608499,
0.0002993909874930978,
0.00017431397282052785,
0.00020754639990627766,
0.0001969132717931643
] |
{
"id": 6,
"code_window": [
" PayloadTooLargeException,\n",
" PreconditionFailedException,\n",
" RequestTimeoutException,\n",
" ServiceUnavailableException,\n",
" UnauthorizedException,\n",
"} from '../../exceptions';\n",
"\n",
"describe('HttpException', () => {\n",
" describe('getResponse', () => {\n",
" it('should return a response as a string when input is a string', () => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" UnprocessableEntityException,\n"
],
"file_path": "packages/common/test/exceptions/http.exception.spec.ts",
"type": "add",
"edit_start_line_idx": 22
} | import { expect } from 'chai';
import * as sinon from 'sinon';
import { MetadataScanner } from '../../core/metadata-scanner';
import { WebSocketServer } from '../decorators/gateway-server.decorator';
import { WebSocketGateway } from '../decorators/socket-gateway.decorator';
import { SubscribeMessage } from '../decorators/subscribe-message.decorator';
import { GatewayMetadataExplorer } from '../gateway-metadata-explorer';
describe('GatewayMetadataExplorer', () => {
const message = 'test';
const secMessage = 'test2';
@WebSocketGateway()
class Test {
@WebSocketServer() public server;
@WebSocketServer() public anotherServer;
get testGet() {
return 0;
}
set testSet(val) {}
constructor() {}
@SubscribeMessage(message)
public test() {}
@SubscribeMessage(secMessage)
public testSec() {}
public noMessage() {}
}
let instance: GatewayMetadataExplorer;
let scanner: MetadataScanner;
beforeEach(() => {
scanner = new MetadataScanner();
instance = new GatewayMetadataExplorer(scanner);
});
describe('explore', () => {
let scanFromPrototype: sinon.SinonSpy;
beforeEach(() => {
scanFromPrototype = sinon.spy(scanner, 'scanFromPrototype');
});
it(`should call "scanFromPrototype" with expected arguments`, () => {
const obj = new Test();
instance.explore(obj as any);
const [argObj, argProto] = scanFromPrototype.getCall(0).args;
expect(argObj).to.be.eql(obj);
expect(argProto).to.be.eql(Object.getPrototypeOf(obj));
});
});
describe('exploreMethodMetadata', () => {
let test: Test;
beforeEach(() => {
test = new Test();
});
it(`should return null when "isMessageMapping" metadata is undefined`, () => {
const metadata = instance.exploreMethodMetadata(test, 'noMessage');
expect(metadata).to.eq(null);
});
it(`should return message mapping properties when "isMessageMapping" metadata is not undefined`, () => {
const metadata = instance.exploreMethodMetadata(test, 'test');
expect(metadata).to.have.keys(['callback', 'message', 'methodName']);
expect(metadata.message).to.eql(message);
});
});
describe('scanForServerHooks', () => {
it(`should return properties with @Client decorator`, () => {
const obj = new Test();
const servers = [...instance.scanForServerHooks(obj as any)];
expect(servers).to.have.length(2);
expect(servers).to.deep.eq(['server', 'anotherServer']);
});
});
});
| packages/websockets/test/gateway-metadata-explorer.spec.ts | 0 | https://github.com/nestjs/nest/commit/b4aca5d01facba08fceeea657454f9c92dbb7269 | [
0.0001808291708584875,
0.00017357550677843392,
0.0001658504770603031,
0.0001734360121190548,
0.000005150050128577277
] |
{
"id": 6,
"code_window": [
" PayloadTooLargeException,\n",
" PreconditionFailedException,\n",
" RequestTimeoutException,\n",
" ServiceUnavailableException,\n",
" UnauthorizedException,\n",
"} from '../../exceptions';\n",
"\n",
"describe('HttpException', () => {\n",
" describe('getResponse', () => {\n",
" it('should return a response as a string when input is a string', () => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" UnprocessableEntityException,\n"
],
"file_path": "packages/common/test/exceptions/http.exception.spec.ts",
"type": "add",
"edit_start_line_idx": 22
} | import { expect } from 'chai';
import * as sinon from 'sinon';
import { HttpException } from '../../../common/exceptions/http.exception';
import { ExternalExceptionsHandler } from '../../exceptions/external-exceptions-handler';
import { ExternalErrorProxy } from '../../helpers/external-proxy';
describe('ExternalErrorProxy', () => {
let externalErrorProxy: ExternalErrorProxy;
let handlerMock: sinon.SinonMock;
let handler: ExternalExceptionsHandler;
beforeEach(() => {
handler = new ExternalExceptionsHandler();
handlerMock = sinon.mock(handler);
externalErrorProxy = new ExternalErrorProxy();
});
describe('createProxy', () => {
it('should method return thunk', () => {
const proxy = externalErrorProxy.createProxy(() => {}, handler);
expect(typeof proxy === 'function').to.be.true;
});
it('should method encapsulate callback passed as argument', () => {
const expectation = handlerMock.expects('next').once();
const proxy = externalErrorProxy.createProxy((req, res, next) => {
throw new HttpException('test', 500);
}, handler);
proxy(null, null, null);
expectation.verify();
});
it('should method encapsulate async callback passed as argument', done => {
const expectation = handlerMock.expects('next').once();
const proxy = externalErrorProxy.createProxy(async (req, res, next) => {
throw new HttpException('test', 500);
}, handler);
proxy(null, null, null);
setTimeout(() => {
expectation.verify();
done();
}, 0);
});
});
});
| packages/core/test/helpers/external-proxy.spec.ts | 0 | https://github.com/nestjs/nest/commit/b4aca5d01facba08fceeea657454f9c92dbb7269 | [
0.0002379894576733932,
0.0002066957822535187,
0.00017216181731782854,
0.00022329477360472083,
0.000026940402676700614
] |
{
"id": 6,
"code_window": [
" PayloadTooLargeException,\n",
" PreconditionFailedException,\n",
" RequestTimeoutException,\n",
" ServiceUnavailableException,\n",
" UnauthorizedException,\n",
"} from '../../exceptions';\n",
"\n",
"describe('HttpException', () => {\n",
" describe('getResponse', () => {\n",
" it('should return a response as a string when input is a string', () => {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" UnprocessableEntityException,\n"
],
"file_path": "packages/common/test/exceptions/http.exception.spec.ts",
"type": "add",
"edit_start_line_idx": 22
} | import { expect } from 'chai';
import { Injectable } from '../../../common';
import { Controller } from '../../../common/decorators/core/controller.decorator';
import { RequestMapping } from '../../../common/decorators/http/request-mapping.decorator';
import { RequestMethod } from '../../../common/enums/request-method.enum';
import { MiddlewareConfiguration } from '../../../common/interfaces/middleware/middleware-configuration.interface';
import { NestMiddleware } from '../../../common/interfaces/middleware/nest-middleware.interface';
import { NestContainer } from '../../injector';
import { InstanceWrapper } from '../../injector/instance-wrapper';
import { Module } from '../../injector/module';
import { MiddlewareContainer } from '../../middleware/container';
describe('MiddlewareContainer', () => {
class ExampleModule {}
@Controller('test')
class TestRoute {
@RequestMapping({ path: 'test' })
public getTest() {}
@RequestMapping({ path: 'another', method: RequestMethod.DELETE })
public getAnother() {}
}
@Injectable()
class TestMiddleware implements NestMiddleware {
public use(req, res, next) {}
}
let container: MiddlewareContainer;
beforeEach(() => {
const nestContainer = new NestContainer();
const modules = nestContainer.getModules();
modules.set('Module', new Module(ExampleModule, nestContainer));
modules.set('Test', new Module(ExampleModule, nestContainer));
container = new MiddlewareContainer(nestContainer);
});
it('should store expected configurations for given module', () => {
const config: MiddlewareConfiguration[] = [
{
middleware: [TestMiddleware],
forRoutes: [TestRoute, 'test'],
},
];
container.insertConfig(config, 'Module');
expect([...container.getConfigurations().get('Module')]).to.deep.equal(
config,
);
});
it('should store expected middleware for given module', () => {
const config: MiddlewareConfiguration[] = [
{
middleware: TestMiddleware,
forRoutes: [TestRoute],
},
];
const key = 'Test';
container.insertConfig(config, key);
const collection = container.getMiddlewareCollection(key);
const insertedMiddleware = collection.get(TestMiddleware);
expect(collection.size).to.eql(config.length);
expect(insertedMiddleware).to.be.instanceOf(InstanceWrapper);
expect(insertedMiddleware.scope).to.be.undefined;
expect(insertedMiddleware.metatype).to.be.eql(TestMiddleware);
});
});
| packages/core/test/middleware/container.spec.ts | 0 | https://github.com/nestjs/nest/commit/b4aca5d01facba08fceeea657454f9c92dbb7269 | [
0.00017712455883156508,
0.00017155327077489346,
0.0001672329963184893,
0.0001698082487564534,
0.0000036451660889724735
] |
{
"id": 7,
"code_window": [
" PayloadTooLargeException,\n",
" PreconditionFailedException,\n",
" RequestTimeoutException,\n",
" ServiceUnavailableException,\n",
" UnauthorizedException,\n",
" ];\n",
"\n",
" builtInErrorClasses.forEach(ExceptionClass => {\n",
" const error = new ExceptionClass(customDescription, {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" UnprocessableEntityException,\n"
],
"file_path": "packages/common/test/exceptions/http.exception.spec.ts",
"type": "add",
"edit_start_line_idx": 214
} | import { HttpStatus } from '../enums/http-status.enum';
import { HttpException } from './http.exception';
/**
* Defines an HTTP exception for *Unprocessable Entity* type errors.
*
* @see [Built-in HTTP exceptions](https://docs.nestjs.com/exception-filters#built-in-http-exceptions)
*
* @publicApi
*/
export class UnprocessableEntityException extends HttpException {
/**
* Instantiate an `UnprocessableEntityException` Exception.
*
* @example
* `throw new UnprocessableEntityException()`
*
* @usageNotes
* The HTTP response status code will be 422.
* - The `objectOrError` argument defines the JSON response body or the message string.
* - The `description` argument contains a short description of the HTTP error.
*
* By default, the JSON response body contains two properties:
* - `statusCode`: this will be the value 422.
* - `message`: the string `'Unprocessable Entity'` by default; override this by supplying
* a string in the `objectOrError` parameter.
*
* If the parameter `objectOrError` is a string, the response body will contain an
* additional property, `error`, with a short description of the HTTP error. To override the
* entire JSON response body, pass an object instead. Nest will serialize the object
* and return it as the JSON response body.
*
* @param objectOrError string or object describing the error condition.
* @param description a short description of the HTTP error.
*/
constructor(
objectOrError?: string | object | any,
description = 'Unprocessable Entity',
) {
super(
HttpException.createBody(
objectOrError,
description,
HttpStatus.UNPROCESSABLE_ENTITY,
),
HttpStatus.UNPROCESSABLE_ENTITY,
);
}
}
| packages/common/exceptions/unprocessable-entity.exception.ts | 1 | https://github.com/nestjs/nest/commit/b4aca5d01facba08fceeea657454f9c92dbb7269 | [
0.0001972843165276572,
0.00017215334810316563,
0.00016151931777130812,
0.00016602579853497446,
0.000013267483154777437
] |
{
"id": 7,
"code_window": [
" PayloadTooLargeException,\n",
" PreconditionFailedException,\n",
" RequestTimeoutException,\n",
" ServiceUnavailableException,\n",
" UnauthorizedException,\n",
" ];\n",
"\n",
" builtInErrorClasses.forEach(ExceptionClass => {\n",
" const error = new ExceptionClass(customDescription, {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" UnprocessableEntityException,\n"
],
"file_path": "packages/common/test/exceptions/http.exception.spec.ts",
"type": "add",
"edit_start_line_idx": 214
} | /**
* Validation error description.
* @see https://github.com/typestack/class-validator
*
* [email protected]
*
* @publicApi
*/
export interface ValidationError {
/**
* Object that was validated.
*
* OPTIONAL - configurable via the ValidatorOptions.validationError.target option
*/
target?: Record<string, any>;
/**
* Object's property that hasn't passed validation.
*/
property: string;
/**
* Value that haven't pass a validation.
*
* OPTIONAL - configurable via the ValidatorOptions.validationError.value option
*/
value?: any;
/**
* Constraints that failed validation with error messages.
*/
constraints?: {
[type: string]: string;
};
/**
* Contains all nested validation errors of the property.
*/
children?: ValidationError[];
/**
* A transient set of data passed through to the validation result for response mapping
*/
contexts?: {
[type: string]: any;
};
}
| packages/common/interfaces/external/validation-error.interface.ts | 0 | https://github.com/nestjs/nest/commit/b4aca5d01facba08fceeea657454f9c92dbb7269 | [
0.00017660751473158598,
0.00017250240489374846,
0.00016823981422930956,
0.00017256563296541572,
0.000002867677039830596
] |
{
"id": 7,
"code_window": [
" PayloadTooLargeException,\n",
" PreconditionFailedException,\n",
" RequestTimeoutException,\n",
" ServiceUnavailableException,\n",
" UnauthorizedException,\n",
" ];\n",
"\n",
" builtInErrorClasses.forEach(ExceptionClass => {\n",
" const error = new ExceptionClass(customDescription, {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" UnprocessableEntityException,\n"
],
"file_path": "packages/common/test/exceptions/http.exception.spec.ts",
"type": "add",
"edit_start_line_idx": 214
} | import {
CanActivate,
ExecutionContext,
Injectable,
Scope,
} from '@nestjs/common';
import { Observable } from 'rxjs';
@Injectable({ scope: Scope.TRANSIENT })
export class Guard implements CanActivate {
static COUNTER = 0;
constructor() {
Guard.COUNTER++;
}
canActivate(
context: ExecutionContext,
): boolean | Promise<boolean> | Observable<boolean> {
return true;
}
}
| integration/scopes/src/circular-transient/guards/request-scoped.guard.ts | 0 | https://github.com/nestjs/nest/commit/b4aca5d01facba08fceeea657454f9c92dbb7269 | [
0.00017909608141053468,
0.0001766210625646636,
0.00017237487190868706,
0.00017839219071902335,
0.0000030162200346239842
] |
{
"id": 7,
"code_window": [
" PayloadTooLargeException,\n",
" PreconditionFailedException,\n",
" RequestTimeoutException,\n",
" ServiceUnavailableException,\n",
" UnauthorizedException,\n",
" ];\n",
"\n",
" builtInErrorClasses.forEach(ExceptionClass => {\n",
" const error = new ExceptionClass(customDescription, {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" UnprocessableEntityException,\n"
],
"file_path": "packages/common/test/exceptions/http.exception.spec.ts",
"type": "add",
"edit_start_line_idx": 214
} | import { EventEmitter } from 'events';
/**
* @see https://github.com/mqttjs/MQTT.js/
*/
export declare class MqttClient extends EventEmitter {
public connected: boolean;
public disconnecting: boolean;
public disconnected: boolean;
public reconnecting: boolean;
public incomingStore: any;
public outgoingStore: any;
public options: any;
public queueQoSZero: boolean;
constructor(streamBuilder: (client: MqttClient) => any, options: any);
public on(event: 'message', cb: any): this;
public on(event: 'packetsend' | 'packetreceive', cb: any): this;
public on(event: 'error', cb: any): this;
public on(event: string, cb: Function): this;
public once(event: 'message', cb: any): this;
public once(event: 'packetsend' | 'packetreceive', cb: any): this;
public once(event: 'error', cb: any): this;
public once(event: string, cb: Function): this;
/**
* publish - publish <message> to <topic>
*
* @param {String} topic - topic to publish to
* @param {(String|Buffer)} message - message to publish
*
* @param {Object} [opts] - publish options, includes:
* @param {Number} [opts.qos] - qos level to publish on
* @param {Boolean} [opts.retain] - whether or not to retain the message
*
* @param {Function} [callback] - function(err){}
* called when publish succeeds or fails
* @returns {Client} this - for chaining
* @api public
*
* @example client.publish('topic', 'message')
* @example
* client.publish('topic', 'message', {qos: 1, retain: true})
* @example client.publish('topic', 'message', console.log)
*/
public publish(
topic: string,
message: string | Buffer,
opts: any,
callback?: any,
): this;
public publish(topic: string, message: string | Buffer, callback?: any): this;
/**
* subscribe - subscribe to <topic>
*
* @param {String, Array, Object} topic - topic(s) to subscribe to, supports objects in the form {'topic': qos}
* @param {Object} [opts] - optional subscription options, includes:
* @param {Number} [opts.qos] - subscribe qos level
* @param {Function} [callback] - function(err, granted){} where:
* {Error} err - subscription error (none at the moment!)
* {Array} granted - array of {topic: 't', qos: 0}
* @returns {MqttClient} this - for chaining
* @api public
* @example client.subscribe('topic')
* @example client.subscribe('topic', {qos: 1})
* @example client.subscribe({'topic': 0, 'topic2': 1}, console.log)
* @example client.subscribe('topic', console.log)
*/
public subscribe(topic: string | string[], opts: any, callback?: any): this;
public subscribe(topic: string | string[] | any, callback?: any): this;
/**
* unsubscribe - unsubscribe from topic(s)
*
* @param {String, Array} topic - topics to unsubscribe from
* @param {Function} [callback] - callback fired on unsuback
* @returns {MqttClient} this - for chaining
* @api public
* @example client.unsubscribe('topic')
* @example client.unsubscribe('topic', console.log)
*/
public unsubscribe(topic: string | string[], callback?: any): this;
/**
* end - close connection
*
* @returns {MqttClient} this - for chaining
* @param {Boolean} force - do not wait for all in-flight messages to be acked
* @param {Function} cb - called when the client has been closed
*
* @api public
*/
public end(force?: boolean, cb?: any): this;
/**
* removeOutgoingMessage - remove a message in outgoing store
* the outgoing callback will be called withe Error('Message removed') if the message is removed
*
* @param {Number} mid - messageId to remove message
* @returns {MqttClient} this - for chaining
* @api public
*
* @example client.removeOutgoingMessage(client.getLastMessageId());
*/
public removeOutgoingMessage(mid: number): this;
/**
* reconnect - connect again using the same options as connect()
*
* @param {Object} [opts] - optional reconnect options, includes:
* {any} incomingStore - a store for the incoming packets
* {any} outgoingStore - a store for the outgoing packets
* if opts is not given, current stores are used
*
* @returns {MqttClient} this - for chaining
*
* @api public
*/
public reconnect(opts?: any): this;
/**
* Handle messages with backpressure support, one at a time.
* Override at will.
*
* @param packet packet the packet
* @param callback callback call when finished
* @api public
*/
public handleMessage(packet: any, callback: any): void;
/**
* getLastMessageId
*/
public getLastMessageId(): number;
}
| packages/microservices/external/mqtt-client.interface.ts | 0 | https://github.com/nestjs/nest/commit/b4aca5d01facba08fceeea657454f9c92dbb7269 | [
0.00017656457202974707,
0.00017005221161525697,
0.00015948890359140933,
0.00017137003305833787,
0.000005340736151993042
] |
{
"id": 0,
"code_window": [
"interface Props {\n",
" modelValue: number | string | null | undefined\n",
" showValidationError?: boolean\n",
"}\n",
"\n",
"const { modelValue, showValidationError = true } = defineProps<Props>()\n",
"\n",
"const emit = defineEmits(['update:modelValue'])\n",
"\n",
"const { t } = useI18n()\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"const { modelValue, showValidationError } = withDefaults(defineProps<Props>(), { showValidationError: true })\n"
],
"file_path": "packages/nc-gui/components/cell/Duration.vue",
"type": "replace",
"edit_start_line_idx": 22
} | <script lang="ts" setup>
import { computed } from '#imports'
interface Props {
url: string
socialMedias: string[]
title?: string
summary?: string
hashTags?: string
css?: string
iconClass?: string
width?: string
}
const {
url,
socialMedias,
title = 'NocoDB',
summary,
hashTags = '',
css = '',
iconClass = '',
width = '45px',
} = defineProps<Props>()
const summaryArr = [
'Instant #Rest & #GraphQL APIs on any #SQL Database (Supports : MySQL, PostgresSQL, MsSQL, SQLite, MariaDB) #nocodb ',
'Instantly generate #Rest & #GraphQL APIs on any #SQL Database (Supports : MySQL, PostgresSQL, MsSQL, SQLite, MariaDB) #nocodb',
'Instant #serverless Rest & #GraphQL APIs on any Database #nocodb',
'Instant APIs on any SQL Database (Supports : #REST #GraphQL #MySQL, #PostgresSQL, #MsSQL, #SQLite, #MariaDB) #nocodb',
'Generate Instant APIs on any SQL Database (Supports : #REST #GraphQL #MySQL, #PostgresSQL, #MsSQL, #SQLite, #MariaDB) #nocodb',
]
const shareUrl = computed(() => encodeURIComponent(url))
const encodedTitle = computed(() => encodeURIComponent(title || 'NocoDB'))
const encodedSummary = computed(() => encodeURIComponent(summary || summaryArr[Math.floor(Math.random() * summaryArr.length)]))
const fbHashTags = computed(() => hashTags && `%23${hashTags}`)
const openUrl = (url: string) => {
window.open(url, '_blank', 'noopener,noreferrer')
}
</script>
<template>
<div class="flex gap-2">
<a
v-if="!socialMedias || !socialMedias.length || socialMedias.includes('twitter')"
href="#"
:class="iconClass"
class="px-2"
@click.prevent="openUrl(`https://twitter.com/intent/tweet?url=${shareUrl}&text=${encodedSummary}&hashtags=${hashTags}`)"
>
<img
src="~/assets/img/social/twitter.png"
class="img-responsive"
alt="Twitter"
:width="width"
:style="css"
title="Social Media Share"
/>
</a>
<a
v-if="!socialMedias || !socialMedias.length || socialMedias.includes('linkedin')"
href="#"
:class="iconClass"
class="px-2"
@click.prevent="
openUrl(`https://www.linkedin.com/shareArticle?mini=true&url=${shareUrl}&title=${encodedTitle}&summary=${encodedSummary}`)
"
>
<img
src="~/assets/img/social/linkedin.png"
class="img-responsive"
alt="Linkedin"
:width="width"
:style="css"
title="Social Media Share"
/>
</a>
<a
v-if="!socialMedias || !socialMedias.length || socialMedias.includes('facebook')"
href="#"
:class="iconClass"
class="px-2"
@click.prevent="
openUrl(
`https://www.facebook.com/sharer/sharer.php?u=${shareUrl}&title=${encodedTitle}&summary=${encodedSummary}"e=${encodedTitle}&hashtag=${fbHashTags}`,
)
"
>
<img
src="~/assets/img/social/facebook.png"
class="img-responsive"
alt="Facebook"
:width="width"
:style="css"
title="Social Media Share"
/>
</a>
<a
v-if="!socialMedias || !socialMedias.length || socialMedias.includes('reddit')"
href="#"
:class="iconClass"
class="px-2"
@click.prevent="openUrl(`https://www.reddit.com/submit?url=${shareUrl}&title=${encodedSummary}`)"
>
<img
src="~/assets/img/social/reddit.png"
class="img-responsive"
alt="Reddit"
:width="width"
:style="css"
title="Social Media Share"
/>
</a>
<a
v-if="!socialMedias || !socialMedias.length || socialMedias.includes('pinterest')"
href="#"
:class="iconClass"
class="px-2"
@click.prevent="openUrl(`https://pinterest.com/pin/create/button/?url=${shareUrl}&description==${encodedSummary}`)"
>
<img
src="~/assets/img/social/pinterest.png"
class="img-responsive"
alt="Printrest"
:width="width"
:style="css"
title="Social Media Share"
/>
</a>
<a
v-if="!socialMedias || !socialMedias.length || socialMedias.includes('whatsapp')"
href="#"
:class="iconClass"
class="px-2"
@click.prevent="openUrl(`https://api.whatsapp.com/send?text=${encodedSummary}%0D%0A${shareUrl}`)"
>
<img
src="~/assets/img/social/whatsapp.png"
class="img-responsive"
alt="Whatsapp"
:width="width"
:style="css"
title="Social Media Share"
/>
</a>
<a
v-if="!socialMedias || !socialMedias.length || socialMedias.includes('telegram')"
href="#"
:class="iconClass"
class="px-2"
@click.prevent="openUrl(`https://telegram.me/share/url?url=${shareUrl}&text=${encodedSummary}`)"
>
<img
src="~/assets/img/social/png/telegram.png"
class="img-responsive"
alt="Telegram"
:width="width"
:style="css"
title="Social Media Share"
/>
</a>
<a
v-if="!socialMedias || !socialMedias.length || socialMedias.includes('wechat')"
:class="iconClass"
class="px-2"
@click.prevent="openUrl(`https://www.addtoany.com/add_to/wechat?linkurl=${shareUrl}&linkname=${encodedTitle}`)"
>
<img
src="~/assets/img/social/png/wechat.png"
class="img-responsive"
alt="Wechat"
:width="width"
:style="css"
title="Social Media Share"
/>
</a>
<a v-if="!socialMedias || !socialMedias.length || socialMedias.includes('line')" href="#" :class="iconClass" class="px-2">
<img
src="~/assets/img/social/png/line.png"
class="img-responsive"
alt="Line"
:width="width"
:style="css"
title="Social Media Share"
@click.prevent="openUrl(`http://line.me/R/msg/text/?${encodedTitle}%0D%0A${shareUrl}`)"
/>
</a>
<a
v-if="!socialMedias || !socialMedias.length || socialMedias.includes('odnoklassniki')"
href="#"
:class="iconClass"
class="px-2"
>
<img
src="~/assets/img/social/png/odnoklassniki.png"
class="img-responsive"
alt="Odnoklassniki"
:width="width"
:style="css"
title="Social Media Share"
@click.prevent="
openUrl(`https://connect.ok.ru/dk?st.cmd=WidgetSharePreview&st.shareUrl=${shareUrl}&st.comments=${encodedSummary}`)
"
/>
</a>
<a
v-if="!socialMedias || !socialMedias.length || socialMedias.includes('weibo')"
href="#"
:class="iconClass"
class="px-2"
@click.prevent="openUrl(`http://service.weibo.com/share/share.php?url=${shareUrl})&title=${encodedTitle}`)"
>
<img
src="~/assets/img/social/png/weibo.png"
class="img-responsive"
alt="Weibo"
:width="width"
:style="css"
title="Social Media Share"
/>
</a>
<a
v-if="!socialMedias || !socialMedias.length || socialMedias.includes('renren')"
:class="iconClass"
class="px-2"
@click.prevent="
openUrl(
`http://widget.renren.com/dialog/share?resourceUrl=${shareUrl}&srcUrl=${shareUrl}&title=${encodedTitle}&description=${encodedSummary}`,
)
"
>
<img
src="~/assets/img/social/png/renren.png"
class="img-responsive"
alt="Renren"
:width="width"
:style="css"
title="Social Media Share"
/>
</a>
<a
v-if="!socialMedias || !socialMedias.length || socialMedias.includes('douban')"
:class="iconClass"
class="px-2"
@click.prevent="openUrl(`http://www.douban.com/recommend/?url=${shareUrl}&title=${encodedTitle}`)"
>
<img
src="~/assets/img/social/png/douban.png"
class="img-responsive"
alt="Douban"
:width="width"
:style="css"
title="Social Media Share"
/>
</a>
<a
v-if="!socialMedias || !socialMedias.length || socialMedias.includes('vk')"
href="#"
:class="iconClass"
class="px-2"
@click.prevent="
openUrl(`https://vk.com/share.php?url=${shareUrl})&title=${encodedTitle}&description=${encodedSummary}&noparse=true`)
"
>
<img
src="~/assets/img/social/png/vk.png"
class="img-responsive"
alt="VK"
:width="width"
:style="css"
title="Social Media Share"
/>
</a>
<a
v-if="!socialMedias || !socialMedias.length || socialMedias.includes('wykop')"
:class="iconClass"
class="px-2"
@click.prevent="openUrl(`https://www.addtoany.com/add_to/wykop?linkurl=${shareUrl}&linkname=${encodedTitle}`)"
>
<img
src="~/assets/img/social/png/wykop.jpg"
class="img-responsive"
alt="Wykop"
:width="width"
:style="css"
title="Social Media Share"
/>
</a>
</div>
</template>
<style scoped>
.img-responsive {
width: 30px;
}
.small .img-responsive {
width: 25px;
}
a {
@apply cursor-pointer text-3xl rounded-full p-2 bg-gray-100 shadow-md hover:(shadow-lg bg-gray-200);
}
</style>
| packages/nc-gui/components/general/Share.vue | 1 | https://github.com/nocodb/nocodb/commit/b862043ce25ff49926754ea05282a300278ec746 | [
0.011314665898680687,
0.0006264541880227625,
0.00016202741244342178,
0.00017834441678132862,
0.0020016792695969343
] |
{
"id": 0,
"code_window": [
"interface Props {\n",
" modelValue: number | string | null | undefined\n",
" showValidationError?: boolean\n",
"}\n",
"\n",
"const { modelValue, showValidationError = true } = defineProps<Props>()\n",
"\n",
"const emit = defineEmits(['update:modelValue'])\n",
"\n",
"const { t } = useI18n()\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"const { modelValue, showValidationError } = withDefaults(defineProps<Props>(), { showValidationError: true })\n"
],
"file_path": "packages/nc-gui/components/cell/Duration.vue",
"type": "replace",
"edit_start_line_idx": 22
} | ---
title: 'Keyboard Maneuver'
description: 'Keyboard shortcuts'
---
## Shortcuts
| Key | Behaviour |
|----------:|:------------------------|
| `ALT` `t` | Insert new table |
| `ALT` `r` | Insert new row |
| `ALT` `c` | Insert new column |
| `ALT` `f` | Toggle fullscreen mode |
| `ALT` `i` | Invite a member to team |
| `ALT` `,` | Open `Team & Settings` menu |
## Grid view
| Key | Behaviour |
|----------------:|:-------------------------------------------------------------------------------------|
| `⌘` `↑` | Jump to first record in this column (in same page) |
| `⌘` `↓` | Jump to last record in this column (in same page) |
| `⌘` `C` | Copy cell contents |
| `Enter` | Switch cell in focus to EDIT mode; opens modal/picker if cell is associated with one |
| `Esc` | Exit cell EDIT mode |
| `Delete` | Clear cell |
| `Space` | Expand current row |
| `←` `→` `↑` `↓` | General cell navigation |
| `Tab` | Move to next cell horizontally; if on last cell, move to next row beginning |
## Column type specific
| Datatype | Key | Behaviour |
|:----------------------:|------------:|:-----------------------------------|
| Text / Numerical cells | `←` `→` | Move cursor to the left / right |
| | `↑` `↓` | Move cursor to the beginning / end |
| Single Select | `↑` `↓` | Move between options |
| | `Enter` | Select option |
| Multi Select | `↑` `↓` | Move between options |
| | `Enter` | Select / deselect option |
| DateTime | `Ctrl` `;` | Select current date time |
| Link | `↑` `↓` | Move between options |
| | `Enter` | Link current selection |
| Checkbox | `Enter` | Toggle |
| Rating | `<0 ~ Max>` | Enter number to toggle rating |
## Expanded form
| Key | Behaviour |
|------------:|:-------------------------------|
| `⌘` `Enter` | Save current expanded form item |
| packages/noco-docs/versioned_docs/version-0.109.7/030.setup-and-usages/150.keyboard-maneuver.md | 0 | https://github.com/nocodb/nocodb/commit/b862043ce25ff49926754ea05282a300278ec746 | [
0.00017625640612095594,
0.0001741726155159995,
0.00017118017422035336,
0.0001739590079523623,
0.00000172742636550538
] |
{
"id": 0,
"code_window": [
"interface Props {\n",
" modelValue: number | string | null | undefined\n",
" showValidationError?: boolean\n",
"}\n",
"\n",
"const { modelValue, showValidationError = true } = defineProps<Props>()\n",
"\n",
"const emit = defineEmits(['update:modelValue'])\n",
"\n",
"const { t } = useI18n()\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"const { modelValue, showValidationError } = withDefaults(defineProps<Props>(), { showValidationError: true })\n"
],
"file_path": "packages/nc-gui/components/cell/Duration.vue",
"type": "replace",
"edit_start_line_idx": 22
} | import { test } from '@playwright/test';
import { AccountPage } from '../../../pages/Account';
import { AccountTokenPage } from '../../../pages/Account/Token';
import setup, { unsetup } from '../../../setup';
test.describe('User roles', () => {
let accountTokenPage: AccountTokenPage;
let accountPage: AccountPage;
// @ts-ignore
let context: any;
test.beforeEach(async ({ page }) => {
context = await setup({ page, isEmptyProject: true });
accountPage = new AccountPage(page);
accountTokenPage = new AccountTokenPage(accountPage);
});
test.afterEach(async () => {
await unsetup(context);
});
test('Create and Delete token', async () => {
test.slow();
const parallelId = process.env.TEST_PARALLEL_INDEX ?? '0';
await accountTokenPage.goto();
await accountTokenPage.createToken({ description: `nc_test_${parallelId} test token` });
await accountTokenPage.deleteToken({ description: `nc_test_${parallelId} test token` });
});
});
| tests/playwright/tests/db/usersAccounts/accountTokenManagement.spec.ts | 0 | https://github.com/nocodb/nocodb/commit/b862043ce25ff49926754ea05282a300278ec746 | [
0.0001776243298081681,
0.00017553976795170456,
0.0001731231895973906,
0.00017587181355338544,
0.0000018525211089581717
] |
{
"id": 0,
"code_window": [
"interface Props {\n",
" modelValue: number | string | null | undefined\n",
" showValidationError?: boolean\n",
"}\n",
"\n",
"const { modelValue, showValidationError = true } = defineProps<Props>()\n",
"\n",
"const emit = defineEmits(['update:modelValue'])\n",
"\n",
"const { t } = useI18n()\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"const { modelValue, showValidationError } = withDefaults(defineProps<Props>(), { showValidationError: true })\n"
],
"file_path": "packages/nc-gui/components/cell/Duration.vue",
"type": "replace",
"edit_start_line_idx": 22
} | <script setup lang="ts">
import { computed, currencyCodes, currencyLocales, useVModel, validateCurrencyCode, validateCurrencyLocale } from '#imports'
interface Option {
label: string
value: string
}
const props = defineProps<{
value: any
}>()
const emit = defineEmits(['update:value'])
const { t } = useI18n()
const vModel = useVModel(props, 'value', emit)
const validators = {
'meta.currency_locale': [
{
validator: (_: any, locale: any) => {
return new Promise<void>((resolve, reject) => {
if (!validateCurrencyLocale(locale)) {
return reject(new Error(t('msg.invalidLocale')))
}
resolve()
})
},
},
],
'meta.currency_code': [
{
validator: (_: any, currencyCode: any) => {
return new Promise<void>((resolve, reject) => {
if (!validateCurrencyCode(currencyCode)) {
return reject(new Error(t('msg.invalidCurrencyCode')))
}
resolve()
})
},
},
],
}
const { setAdditionalValidations, validateInfos, isPg } = useColumnCreateStoreOrThrow()
setAdditionalValidations({
...validators,
})
const currencyList = currencyCodes || []
const currencyLocaleList = ref<{ text: string; value: string }[]>([])
const isMoney = computed(() => vModel.value.dt === 'money')
const message = computed(() => {
if (isMoney.value && isPg.value) return t('msg.postgresHasItsOwnCurrencySettings')
return ''
})
function filterOption(input: string, option: Option) {
return option.value.toUpperCase().includes(input.toUpperCase())
}
// set default value
vModel.value.meta = {
currency_locale: 'en-US',
currency_code: 'USD',
...vModel.value.meta,
}
currencyLocales().then((locales) => {
currencyLocaleList.value.push(...locales)
})
</script>
<template>
<a-row gutter="8">
<a-col :span="12">
<a-form-item v-bind="validateInfos['meta.currency_locale']" :label="$t('title.currencyLocale')">
<a-select
v-model:value="vModel.meta.currency_locale"
class="w-52"
show-search
:filter-option="filterOption"
:disabled="isMoney && isPg"
dropdown-class-name="nc-dropdown-currency-cell-locale"
>
<a-select-option v-for="(currencyLocale, i) of currencyLocaleList" :key="i" :value="currencyLocale.value">
<div class="flex gap-2 w-full truncate items-center">
<NcTooltip show-on-truncate-only class="flex-1 truncate">
<template #title>{{ currencyLocale.text }}</template>
{{ currencyLocale.text }}
</NcTooltip>
<component
:is="iconMap.check"
v-if="vModel.meta.currency_locale === currencyLocale.value"
id="nc-selected-item-icon"
class="text-primary w-4 h-4"
/>
</div>
</a-select-option>
</a-select>
</a-form-item>
</a-col>
<a-col :span="12">
<a-form-item v-bind="validateInfos['meta.currency_code']" :label="$t('title.currencyCode')">
<a-select
v-model:value="vModel.meta.currency_code"
class="w-52"
show-search
:filter-option="filterOption"
:disabled="isMoney && isPg"
dropdown-class-name="nc-dropdown-currency-cell-code"
>
<a-select-option v-for="(currencyCode, i) of currencyList" :key="i" :value="currencyCode">
<div class="flex gap-2 w-full justify-between items-center">
{{ currencyCode }}
<component
:is="iconMap.check"
v-if="vModel.meta.currency_code === currencyCode"
id="nc-selected-item-icon"
class="text-primary w-4 h-4"
/>
</div>
</a-select-option>
</a-select>
</a-form-item>
</a-col>
<a-col v-if="isMoney && isPg">
<span class="text-[#FB8C00]">{{ message }}</span>
</a-col>
</a-row>
</template>
| packages/nc-gui/components/smartsheet/column/CurrencyOptions.vue | 0 | https://github.com/nocodb/nocodb/commit/b862043ce25ff49926754ea05282a300278ec746 | [
0.9883058071136475,
0.1360778510570526,
0.00016578580834902823,
0.00017635850235819817,
0.3297043442726135
] |
{
"id": 1,
"code_window": [
" isPk?: boolean\n",
"}\n",
"\n",
"const { modelValue, isPk = false } = defineProps<Props>()\n",
"\n",
"const emit = defineEmits(['update:modelValue'])\n",
"\n",
"const { showNull } = useGlobal()\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"const { modelValue, isPk = false } = withDefaults(defineProps<Props>(), { isPk: false })\n"
],
"file_path": "packages/nc-gui/components/cell/YearPicker.vue",
"type": "replace",
"edit_start_line_idx": 20
} | <script setup lang="ts">
import dayjs from 'dayjs'
import {
ActiveCellInj,
EditColumnInj,
IsExpandedFormOpenInj,
ReadonlyInj,
computed,
inject,
onClickOutside,
ref,
useSelectedCellKeyupListener,
watch,
} from '#imports'
interface Props {
modelValue?: number | string | null
isPk?: boolean
}
const { modelValue, isPk = false } = defineProps<Props>()
const emit = defineEmits(['update:modelValue'])
const { showNull } = useGlobal()
const readOnly = inject(ReadonlyInj, ref(false))
const active = inject(ActiveCellInj, ref(false))
const editable = inject(EditModeInj, ref(false))
const isEditColumn = inject(EditColumnInj, ref(false))
const isExpandedFormOpen = inject(IsExpandedFormOpenInj, ref(false))!
const isYearInvalid = ref(false)
const { t } = useI18n()
const localState = computed({
get() {
if (!modelValue) {
return undefined
}
const yearDate = dayjs(modelValue.toString(), 'YYYY')
if (!yearDate.isValid()) {
isYearInvalid.value = true
return undefined
}
return yearDate
},
set(val?: dayjs.Dayjs) {
if (!val) {
emit('update:modelValue', null)
return
}
if (val?.isValid()) {
emit('update:modelValue', val.format('YYYY'))
}
},
})
const open = ref<boolean>(false)
const randomClass = `picker_${Math.floor(Math.random() * 99999)}`
watch(
open,
(next) => {
if (next) {
onClickOutside(document.querySelector(`.${randomClass}`)! as HTMLDivElement, () => (open.value = false))
} else {
editable.value = false
}
},
{ flush: 'post' },
)
const placeholder = computed(() => {
if (isEditColumn.value && (modelValue === '' || modelValue === null)) {
return t('labels.optional')
} else if (modelValue === null && showNull.value) {
return t('general.null')
} else if (isYearInvalid.value) {
return t('msg.invalidTime')
} else {
return ''
}
})
const isOpen = computed(() => {
if (readOnly.value) return false
return (readOnly.value || (localState.value && isPk)) && !active.value && !editable.value ? false : open.value
})
useSelectedCellKeyupListener(active, (e: KeyboardEvent) => {
switch (e.key) {
case 'Enter':
e.stopPropagation()
open.value = true
break
case 'Escape':
if (open.value) {
e.stopPropagation()
open.value = false
}
break
}
})
</script>
<template>
<a-date-picker
v-model:value="localState"
:tabindex="0"
picker="year"
:bordered="false"
class="!w-full !py-1 !border-none"
:class="{ 'nc-null': modelValue === null && showNull, '!px-2': isExpandedFormOpen, '!px-0': !isExpandedFormOpen }"
:placeholder="placeholder"
:allow-clear="(!readOnly && !localState && !isPk) || isEditColumn"
:input-read-only="true"
:open="isOpen"
:dropdown-class-name="`${randomClass} nc-picker-year children:border-1 children:border-gray-200 ${open ? 'active' : ''}`"
@click="open = (active || editable) && !open"
@change="open = (active || editable) && !open"
@ok="open = !open"
@keydown.enter="open = !open"
>
<template #suffixIcon></template>
</a-date-picker>
</template>
<style scoped>
:deep(.ant-picker-input > input[disabled]) {
@apply !text-current;
}
</style>
| packages/nc-gui/components/cell/YearPicker.vue | 1 | https://github.com/nocodb/nocodb/commit/b862043ce25ff49926754ea05282a300278ec746 | [
0.9983287453651428,
0.4631669819355011,
0.0001708372583379969,
0.007445376832038164,
0.4940943419933319
] |
{
"id": 1,
"code_window": [
" isPk?: boolean\n",
"}\n",
"\n",
"const { modelValue, isPk = false } = defineProps<Props>()\n",
"\n",
"const emit = defineEmits(['update:modelValue'])\n",
"\n",
"const { showNull } = useGlobal()\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"const { modelValue, isPk = false } = withDefaults(defineProps<Props>(), { isPk: false })\n"
],
"file_path": "packages/nc-gui/components/cell/YearPicker.vue",
"type": "replace",
"edit_start_line_idx": 20
} | import { Injectable } from '@nestjs/common';
import { extractRolesObj, OrgUserRoles, ProjectRoles } from 'nocodb-sdk';
import type { Observable } from 'rxjs';
import type {
CallHandler,
ExecutionContext,
NestInterceptor,
} from '@nestjs/common';
import Noco from '~/Noco';
import { NcError } from '~/helpers/catchError';
import { MetaTable } from '~/utils/globals';
@Injectable()
export class UploadAllowedInterceptor implements NestInterceptor {
async intercept(
context: ExecutionContext,
next: CallHandler,
): Promise<Observable<any>> {
const request = context.switchToHttp().getRequest();
if (!request['user']?.id) {
if (!request['user']?.isPublicBase) {
NcError.unauthorized('Unauthorized');
}
}
try {
if (
extractRolesObj(request['user'].roles)[OrgUserRoles.SUPER_ADMIN] ||
extractRolesObj(request['user'].roles)[OrgUserRoles.CREATOR] ||
extractRolesObj(request['user'].roles)[ProjectRoles.EDITOR] ||
!!(await Noco.ncMeta
.knex(MetaTable.PROJECT_USERS)
.where(function () {
this.where('roles', ProjectRoles.OWNER);
this.orWhere('roles', ProjectRoles.CREATOR);
this.orWhere('roles', ProjectRoles.EDITOR);
})
.andWhere('fk_user_id', request['user'].id)
.first())
) {
return next.handle();
}
} catch {}
NcError.badRequest('Upload not allowed');
}
}
| packages/nocodb/src/interceptors/is-upload-allowed/is-upload-allowed.interceptor.ts | 0 | https://github.com/nocodb/nocodb/commit/b862043ce25ff49926754ea05282a300278ec746 | [
0.00017659251170698553,
0.00017412319721188396,
0.0001722324377624318,
0.00017304725770372897,
0.00000195273537428875
] |
{
"id": 1,
"code_window": [
" isPk?: boolean\n",
"}\n",
"\n",
"const { modelValue, isPk = false } = defineProps<Props>()\n",
"\n",
"const emit = defineEmits(['update:modelValue'])\n",
"\n",
"const { showNull } = useGlobal()\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"const { modelValue, isPk = false } = withDefaults(defineProps<Props>(), { isPk: false })\n"
],
"file_path": "packages/nc-gui/components/cell/YearPicker.vue",
"type": "replace",
"edit_start_line_idx": 20
} | ---
title: 'Date'
description: 'This article explains how to create & work with a Date field.'
tags: ['Fields', 'Field types', 'Date & Time']
keywords: ['Fields', 'Field types', 'Date & Time', 'Create date field']
---
`Date` field type is used to store date values. NocoDB supports a wide range of date formats, as detailed in the table below.
## Create a date field
1. Click on `+` icon to the right of `Fields header`
2. On the dropdown modal, enter the field name (Optional).
3. Select the field type as `Date` from the dropdown.
4. Configure `Date Format`
5. Configure default value (Optional)
6. Click on `Save Field` button.

### Supported date formats
| Format | Example |
|--------------|--------------|
| YYYY-MM-DD | 2023-09-22 |
| YYYY/MM/DD | 2023/09/22 |
| DD-MM-YYYY | 22-09-2023 |
| MM-DD-YYYY | 09-22-2023 |
| DD/MM/YYYY | 22/09/2023 |
| MM/DD/YYYY | 09/22/2023 |
| DD MM YYYY | 22 09 2023 |
| MM DD YYYY | 09 22 2023 |
| YYYY MM DD | 2023 09 22 |
## Related fields
- [DateTime](010.date-time.md)
- [Time](030.time.md)
- [Duration](040.duration.md) | packages/noco-docs/docs/070.fields/040.field-types/070.date-time-based/020.date.md | 0 | https://github.com/nocodb/nocodb/commit/b862043ce25ff49926754ea05282a300278ec746 | [
0.00017643951287027448,
0.00017243345791939646,
0.00017058674711734056,
0.00017135377856902778,
0.000002334814098503557
] |
{
"id": 1,
"code_window": [
" isPk?: boolean\n",
"}\n",
"\n",
"const { modelValue, isPk = false } = defineProps<Props>()\n",
"\n",
"const emit = defineEmits(['update:modelValue'])\n",
"\n",
"const { showNull } = useGlobal()\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"const { modelValue, isPk = false } = withDefaults(defineProps<Props>(), { isPk: false })\n"
],
"file_path": "packages/nc-gui/components/cell/YearPicker.vue",
"type": "replace",
"edit_start_line_idx": 20
} | import type { Knex } from 'knex';
import { MetaTable, MetaTableOldV2 } from '~/utils/globals';
const up = async (knex: Knex) => {
if (!(await knex.schema.hasColumn(MetaTableOldV2.BASES, 'erd_uuid'))) {
await knex.schema.alterTable(MetaTableOldV2.BASES, (table) => {
table.string('erd_uuid');
});
}
if (!(await knex.schema.hasTable(MetaTable.NOTIFICATION))) {
await knex.schema.createTable(MetaTable.NOTIFICATION, (table) => {
table.string('id', 20).primary().notNullable();
table.string('type', 40);
table.text('body');
table.boolean('is_read').defaultTo(false);
table.boolean('is_deleted').defaultTo(false);
table.string('fk_user_id', 20).index();
table.timestamps(true, true);
table.index('created_at');
});
}
await knex.schema.alterTable(MetaTable.FILTER_EXP, (table) => {
table.text('value').alter();
});
};
const down = async (knex) => {
await knex.schema.alterTable(MetaTableOldV2.BASES, (table) => {
table.dropColumn('erd_uuid');
});
knex.schema.dropTable(MetaTable.NOTIFICATION);
await knex.schema.alterTable(MetaTable.FILTER_EXP, (table) => {
table.string('value', 255).alter();
});
};
export { up, down };
| packages/nocodb/src/meta/migrations/v2/nc_034_erd_filter_and_notification.ts | 0 | https://github.com/nocodb/nocodb/commit/b862043ce25ff49926754ea05282a300278ec746 | [
0.00017724587814882398,
0.00017359967750962824,
0.0001678408298175782,
0.00017368252156302333,
0.000003241444119339576
] |
{
"id": 2,
"code_window": [
" importDataOnly?: boolean\n",
"}\n",
"\n",
"const { importType, importDataOnly = false, sourceId, ...rest } = defineProps<Props>()\n",
"\n",
"const emit = defineEmits(['update:modelValue'])\n",
"\n",
"const { $api } = useNuxtApp()\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"const { importType, importDataOnly, sourceId, ...rest } = withDefaults(defineProps<Props>(), { importDataOnly: false })\n"
],
"file_path": "packages/nc-gui/components/dlg/QuickImport.vue",
"type": "replace",
"edit_start_line_idx": 47
} | <script lang="ts" setup>
interface Props {
nav?: boolean
}
const { nav = false } = defineProps<Props>()
</script>
<template>
<a-card class="w-[300px] shadow-sm !rounded-lg">
<template #cover>
<img class="max-h-[180px] !rounded-t-lg" alt="cover" src="~/assets/img/ants-leaf-cutter.jpeg" />
</template>
<a-card-meta>
<template #title>
<span v-if="!nav" class="text-xl pb-4">
{{ $t('msg.info.sponsor.header') }}
</span>
</template>
</a-card-meta>
<div v-if="!nav" class="py-5 text-sm">
{{ $t('msg.info.sponsor.message') }}
</div>
<div class="flex justify-center">
<nuxt-link no-prefetch no-rel href="https://github.com/sponsors/nocodb" target="_blank">
<a-button class="!shadow rounded" size="large">
<div class="flex items-center">
<mdi-cards-heart class="text-red-500 mr-2" />
{{ $t('activity.sponsorUs') }}
</div>
</a-button>
</nuxt-link>
</div>
</a-card>
</template>
| packages/nc-gui/components/general/Sponsors.vue | 1 | https://github.com/nocodb/nocodb/commit/b862043ce25ff49926754ea05282a300278ec746 | [
0.003322577802464366,
0.0009596436866559088,
0.00017125168233178556,
0.00017237267456948757,
0.001364240888506174
] |
{
"id": 2,
"code_window": [
" importDataOnly?: boolean\n",
"}\n",
"\n",
"const { importType, importDataOnly = false, sourceId, ...rest } = defineProps<Props>()\n",
"\n",
"const emit = defineEmits(['update:modelValue'])\n",
"\n",
"const { $api } = useNuxtApp()\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"const { importType, importDataOnly, sourceId, ...rest } = withDefaults(defineProps<Props>(), { importDataOnly: false })\n"
],
"file_path": "packages/nc-gui/components/dlg/QuickImport.vue",
"type": "replace",
"edit_start_line_idx": 47
} | import { UITypes } from 'nocodb-sdk';
import { throwTimeoutError } from './ncUpgradeErrors';
import type { XKnex } from '~/db/CustomKnex';
import type { Knex } from 'knex';
import type { NcUpgraderCtx } from './NcUpgrader';
import type { SourceType } from 'nocodb-sdk';
import NcConnectionMgrv2 from '~/utils/common/NcConnectionMgrv2';
import Model from '~/models/Model';
import Source from '~/models/Source';
import { MetaTable } from '~/utils/globals';
// after 0101002 upgrader, the attachment object would become broken when
// (1) switching views after updating a singleSelect field
// since `url` will be enriched the attachment cell, and `saveOrUpdateRecords` in Grid.vue will be triggered
// in this way, the attachment value will be corrupted like
// {"{\"path\":\"download/noco/xcdb2/attachment2/a/JRubxMQgPlcumdm3jL.jpeg\",\"title\":\"haha.jpeg\",\"mimetype\":\"image/jpeg\",\"size\":6494,\"url\":\"http://localhost:8080/download/noco/xcdb2/attachment2/a/JRubxMQgPlcumdm3jL.jpeg\"}"}
// while the expected one is
// [{"path":"download/noco/xcdb2/attachment2/a/JRubxMQgPlcumdm3jL.jpeg","title":"haha.jpeg","mimetype":"image/jpeg","size":6494}]
// (2) or reordering attachments
// since the incoming value is not string, the value will be broken
// hence, this upgrader is to revert back these corrupted values
function getTnPath(knex: XKnex, tb: Model) {
const schema = (knex as any).searchPath?.();
const clientType = knex.clientType();
if (clientType === 'mssql' && schema) {
return knex.raw('??.??', [schema, tb.table_name]).toQuery();
} else if (clientType === 'snowflake') {
return [
knex.client.config.connection.database,
knex.client.config.connection.schema,
tb.table_name,
].join('.');
} else {
return tb.table_name;
}
}
export default async function ({ ncMeta }: NcUpgraderCtx) {
const sources: SourceType[] = await ncMeta.metaList2(
null,
null,
MetaTable.BASES,
);
for (const _base of sources) {
const source = new Source(_base);
// skip if the base_id is missing
if (!source.base_id) {
continue;
}
const base = await ncMeta.metaGet2(null, null, MetaTable.PROJECT, {
id: source.base_id,
});
// skip if the base is missing
if (!base) {
continue;
}
const isProjectDeleted = base.deleted;
const knex: Knex = source.is_meta
? ncMeta.knexConnection
: await NcConnectionMgrv2.get(source);
const models = await source.getModels(ncMeta);
// used in timeout error message
const timeoutErrorInfo = {
baseTitle: base.title,
connection: knex.client.config.connection,
};
for (const model of models) {
try {
// if the table is missing in database, skip
if (!(await knex.schema.hasTable(getTnPath(knex, model)))) {
continue;
}
const updateRecords = [];
// get all attachment & primary key columns
// and filter out the columns that are missing in database
const columns = await (await Model.get(model.id, ncMeta))
.getColumns(ncMeta)
.then(async (columns) => {
const filteredColumns = [];
for (const column of columns) {
if (column.uidt !== UITypes.Attachment && !column.pk) continue;
if (
!(await knex.schema.hasColumn(
getTnPath(knex, model),
column.column_name,
))
)
continue;
filteredColumns.push(column);
}
return filteredColumns;
});
const attachmentColumns = columns
.filter((c) => c.uidt === UITypes.Attachment)
.map((c) => c.column_name);
if (attachmentColumns.length === 0) {
continue;
}
const primaryKeys = columns
.filter((c) => c.pk)
.map((c) => c.column_name);
const records = await knex(getTnPath(knex, model)).select();
for (const record of records) {
const where = primaryKeys
.map((key) => {
return { [key]: record[key] };
})
.reduce((acc, val) => Object.assign(acc, val), {});
for (const attachmentColumn of attachmentColumns) {
if (typeof record[attachmentColumn] === 'string') {
// potentially corrupted
try {
JSON.parse(record[attachmentColumn]);
// it works fine - skip
continue;
} catch {
try {
// corrupted
let corruptedAttachment = record[attachmentColumn];
// replace the first and last character with `[` and `]`
// and parse it again
corruptedAttachment = JSON.parse(
`[${corruptedAttachment.slice(
1,
corruptedAttachment.length - 1,
)}]`,
);
const newAttachmentMeta = [];
for (const attachment of corruptedAttachment) {
newAttachmentMeta.push(JSON.parse(attachment));
}
updateRecords.push(
await knex(getTnPath(knex, model))
.update({
[attachmentColumn]: JSON.stringify(newAttachmentMeta),
})
.where(where),
);
} catch {
// if parsing failed ignore the cell
continue;
}
}
}
}
}
await Promise.all(updateRecords);
} catch (e) {
// ignore the error related to deleted base
if (!isProjectDeleted) {
// throw the custom timeout error message if applicable
throwTimeoutError(e, timeoutErrorInfo);
// throw general error
throw e;
}
}
}
}
}
| packages/nocodb/src/version-upgrader/ncAttachmentUpgrader_0104002.ts | 0 | https://github.com/nocodb/nocodb/commit/b862043ce25ff49926754ea05282a300278ec746 | [
0.00030187229276634753,
0.00017673702677711844,
0.0001656652457313612,
0.00016969977878034115,
0.00003047987775062211
] |
{
"id": 2,
"code_window": [
" importDataOnly?: boolean\n",
"}\n",
"\n",
"const { importType, importDataOnly = false, sourceId, ...rest } = defineProps<Props>()\n",
"\n",
"const emit = defineEmits(['update:modelValue'])\n",
"\n",
"const { $api } = useNuxtApp()\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"const { importType, importDataOnly, sourceId, ...rest } = withDefaults(defineProps<Props>(), { importDataOnly: false })\n"
],
"file_path": "packages/nc-gui/components/dlg/QuickImport.vue",
"type": "replace",
"edit_start_line_idx": 47
} | <script lang="ts" setup>
import { computed, iconMap, navigateTo, storeToRefs, useBase, useGlobal, useRoute, useSidebar } from '#imports'
const { signOut, signedIn, user, currentVersion } = useGlobal()
const { isOpen } = useSidebar('nc-mini-sidebar', { isOpen: true })
const { base } = storeToRefs(useBase())
const route = useRoute()
const email = computed(() => user.value?.email ?? '---')
const logout = async () => {
await signOut(false)
await navigateTo('/signin')
}
</script>
<template>
<a-layout-sider
:collapsed="isOpen"
width="50"
collapsed-width="0"
class="nc-mini-sidebar !bg-primary h-full"
:trigger="null"
collapsible
theme="light"
>
<a-dropdown placement="bottom" :trigger="['click']" overlay-class-name="nc-dropdown">
<div class="transition-all duration-200 p-2 cursor-pointer transform hover:scale-105 nc-noco-brand-icon">
<a-tooltip placement="bottom">
<template #title>
{{ currentVersion }}
</template>
<img width="35" alt="NocoDB" src="~/assets/img/icons/256x256-trans.png" />
</a-tooltip>
</div>
<template v-if="signedIn" #overlay>
<a-menu class="ml-2 !py-0 min-w-32 leading-8 !rounded nc-menu-account">
<a-menu-item-group title="User Settings">
<a-menu-item key="email" class="!rounded-t">
<nuxt-link v-e="['c:navbar:user:email']" class="group flex items-center no-underline py-2" to="/user">
<component :is="iconMap.at" class="mt-1 group-hover:text-success" />
<span class="prose group-hover:text-black nc-user-menu-email">{{ email }}</span>
</nuxt-link>
</a-menu-item>
<a-menu-divider class="!m-0" />
<a-menu-item key="signout" class="!rounded-b">
<div v-e="['a:navbar:user:sign-out']" class="group flex items-center py-2" @click="logout">
<component :is="iconMap.signout" class="group-hover:(!text-red-500)" />
<span class="prose font-semibold text-gray-500 group-hover:text-black nc-user-menu-signout">
{{ $t('general.signOut') }}
</span>
</div>
</a-menu-item>
</a-menu-item-group>
</a-menu>
</template>
</a-dropdown>
<div id="sidebar" ref="sidebar" class="text-white flex-auto flex flex-col items-center w-full">
<a-dropdown :trigger="['contextmenu']" placement="right" overlay-class-name="nc-dropdown">
<div :class="[route.name === 'index' ? 'active' : '']" class="nc-mini-sidebar-item" @click="navigateTo('/')">
<component :is="iconMap.folder" class="cursor-pointer transform hover:scale-105 text-2xl" />
</div>
<template #overlay>
<a-menu class="mt-6 select-none !py-0 min-w-32 leading-8 !rounded">
<a-menu-item-group>
<template #title>
<span class="cursor-pointer prose-sm text-gray-500 hover:text-primary" @click="navigateTo('/')">
{{ $t('objects.projects') }}
</span>
</template>
<a-menu-item class="active:(ring ring-accent ring-opacity-100)">
<div
v-e="['c:base:create:xcdb']"
class="group flex items-center gap-2 py-2 hover:text-primary"
@click="navigateTo('/base/create')"
>
<component :is="iconMap.plus" class="text-lg group-hover:text-accent" />
{{ $t('activity.createProject') }}
</div>
</a-menu-item>
<a-menu-item class="rounded-b active:(ring ring-accent)">
<div
v-e="['c:base:create:extdb']"
class="group flex items-center gap-2 py-2 hover:text-primary"
@click="navigateTo('/base/create-external')"
>
<component :is="iconMap.database" class="text-lg group-hover:text-accent" />
<div v-html="$t('activity.createProjectExtended.extDB')" />
</div>
</a-menu-item>
</a-menu-item-group>
</a-menu>
</template>
</a-dropdown>
<a-tooltip placement="right">
<template v-if="base" #title>{{ base.title }}</template>
<div
:class="[route.name.includes('nc-baseId') ? 'active' : 'pointer-events-none !text-gray-400']"
class="nc-mini-sidebar-item"
@click="navigateTo(`/${route.params.baseType}/${route.params.baseId}`)"
>
<component :is="iconMap.database" class="cursor-pointer transform hover:scale-105 text-2xl" />
</div>
</a-tooltip>
</div>
</a-layout-sider>
</template>
<style lang="scss" scoped>
.nc-mini-sidebar {
:deep(.ant-layout-sider-children) {
@apply flex flex-col items-center;
}
.nc-mini-sidebar-item {
@apply flex w-full justify-center items-center h-12 group p-2;
&.active {
@apply bg-accent border-t-1 border-b-1;
}
}
}
</style>
| packages/nc-gui/components/general/MiniSidebar.vue | 0 | https://github.com/nocodb/nocodb/commit/b862043ce25ff49926754ea05282a300278ec746 | [
0.00017490620666649193,
0.00017184227181132883,
0.00016908541147131473,
0.00017214770196005702,
0.000001790899887055275
] |
{
"id": 2,
"code_window": [
" importDataOnly?: boolean\n",
"}\n",
"\n",
"const { importType, importDataOnly = false, sourceId, ...rest } = defineProps<Props>()\n",
"\n",
"const emit = defineEmits(['update:modelValue'])\n",
"\n",
"const { $api } = useNuxtApp()\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"const { importType, importDataOnly, sourceId, ...rest } = withDefaults(defineProps<Props>(), { importDataOnly: false })\n"
],
"file_path": "packages/nc-gui/components/dlg/QuickImport.vue",
"type": "replace",
"edit_start_line_idx": 47
} | import fs from 'fs';
import { promisify } from 'util';
import AWS from 'aws-sdk';
import axios from 'axios';
import { useAgent } from 'request-filtering-agent';
import type { IStorageAdapterV2, XcFile } from 'nc-plugin';
import type { Readable } from 'stream';
import { generateTempFilePath, waitForStreamClose } from '~/utils/pluginUtils';
export default class Spaces implements IStorageAdapterV2 {
private s3Client: AWS.S3;
private input: any;
constructor(input: any) {
this.input = input;
}
async fileCreate(key: string, file: XcFile): Promise<any> {
const uploadParams: any = {
ACL: 'public-read',
ContentType: file.mimetype,
};
return new Promise((resolve, reject) => {
// Configure the file stream and obtain the upload parameters
const fileStream = fs.createReadStream(file.path);
fileStream.on('error', (err) => {
console.log('File Error', err);
reject(err);
});
uploadParams.Body = fileStream;
uploadParams.Key = key;
// call S3 to retrieve upload file to specified bucket
this.s3Client.upload(uploadParams, (err, data) => {
if (err) {
console.log('Error', err);
reject(err);
}
if (data) {
resolve(data.Location);
}
});
});
}
async fileCreateByUrl(key: string, url: string): Promise<any> {
const uploadParams: any = {
ACL: 'public-read',
};
return new Promise((resolve, reject) => {
axios
.get(url, {
httpAgent: useAgent(url, { stopPortScanningByUrlRedirection: true }),
httpsAgent: useAgent(url, { stopPortScanningByUrlRedirection: true }),
// TODO - use stream instead of buffer
responseType: 'arraybuffer',
})
.then((response) => {
uploadParams.Body = response.data;
uploadParams.Key = key;
uploadParams.ContentType = response.headers['content-type'];
// call S3 to retrieve upload file to specified bucket
this.s3Client.upload(uploadParams, (err1, data) => {
if (err1) {
console.log('Error', err1);
reject(err1);
}
if (data) {
resolve(data.Location);
}
});
})
.catch((error) => {
reject(error);
});
});
}
// TODO - implement
fileCreateByStream(_key: string, _stream: Readable): Promise<void> {
return Promise.resolve(undefined);
}
// TODO - implement
fileReadByStream(_key: string): Promise<Readable> {
return Promise.resolve(undefined);
}
// TODO - implement
getDirectoryList(_path: string): Promise<string[]> {
return Promise.resolve(undefined);
}
public async fileDelete(_path: string): Promise<any> {
return Promise.resolve(undefined);
}
public async fileRead(key: string): Promise<any> {
return new Promise((resolve, reject) => {
this.s3Client.getObject({ Key: key } as any, (err, data) => {
if (err) {
return reject(err);
}
if (!data?.Body) {
return reject(data);
}
return resolve(data.Body);
});
});
}
public async init(): Promise<any> {
// const s3Options: any = {
// params: {Bucket: process.env.NC_S3_BUCKET},
// region: process.env.NC_S3_REGION
// };
//
// s3Options.accessKeyId = process.env.NC_S3_KEY;
// s3Options.secretAccessKey = process.env.NC_S3_SECRET;
const s3Options: any = {
params: { Bucket: this.input.bucket },
region: this.input.region,
};
s3Options.accessKeyId = this.input.access_key;
s3Options.secretAccessKey = this.input.access_secret;
s3Options.endpoint = new AWS.Endpoint(
`${this.input.region || 'nyc3'}.digitaloceanspaces.com`,
);
this.s3Client = new AWS.S3(s3Options);
}
public async test(): Promise<boolean> {
try {
const tempFile = generateTempFilePath();
const createStream = fs.createWriteStream(tempFile);
await waitForStreamClose(createStream);
await this.fileCreate('nc-test-file.txt', {
path: tempFile,
mimetype: 'text/plain',
originalname: 'temp.txt',
size: '',
});
await promisify(fs.unlink)(tempFile);
return true;
} catch (e) {
throw e;
}
}
}
| packages/nocodb/src/plugins/spaces/Spaces.ts | 0 | https://github.com/nocodb/nocodb/commit/b862043ce25ff49926754ea05282a300278ec746 | [
0.00017797152395360172,
0.00017267257499042898,
0.00016907750978134573,
0.0001726126210996881,
0.000002608463546494022
] |
{
"id": 3,
"code_window": [
" (event: 'open'): void\n",
"}\n",
"\n",
"const { transition = true, teleportDisabled = false, inline = false, target, zIndex = 100, ...rest } = defineProps<Props>()\n",
"\n",
"const emits = defineEmits<Emits>()\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"const { transition, teleportDisabled, inline, target, zIndex, ...rest } = withDefaults(defineProps<Props>(), {\n",
" transition: true,\n",
" teleportDisabled: false,\n",
" inline: false,\n",
" zIndex: 100,\n",
"})\n"
],
"file_path": "packages/nc-gui/components/general/Overlay.vue",
"type": "replace",
"edit_start_line_idx": 24
} | <script lang="ts" setup>
import type { ColumnType } from 'nocodb-sdk'
import { UITypes, isVirtualCol } from 'nocodb-sdk'
import {
ActiveCellInj,
IsFormInj,
ReadonlyInj,
iconMap,
inject,
isAttachment,
ref,
useExpandedFormDetached,
useLTARStoreOrThrow,
} from '#imports'
interface Props {
value: string | number | boolean
item: any
column: any
showUnlinkButton?: boolean
border?: boolean
readonly?: boolean
}
const { value, item, column, showUnlinkButton, border = true, readonly: readonlyProp } = defineProps<Props>()
const emit = defineEmits(['unlink'])
const { relatedTableMeta } = useLTARStoreOrThrow()!
const { isUIAllowed } = useRoles()
const readOnly = inject(ReadonlyInj, ref(false))
const active = inject(ActiveCellInj, ref(false))
const isForm = inject(IsFormInj)!
const { open } = useExpandedFormDetached()
function openExpandedForm() {
const rowId = extractPkFromRow(item, relatedTableMeta.value.columns as ColumnType[])
if (!readOnly.value && !readonlyProp && rowId) {
open({
isOpen: true,
row: { row: item, rowMeta: {}, oldRow: { ...item } },
meta: relatedTableMeta.value,
rowId,
useMetaFields: true,
})
}
}
</script>
<script lang="ts">
export default {
name: 'ItemChip',
}
</script>
<template>
<div
v-e="['c:row-expand:open']"
class="chip group mr-1 my-1 flex items-center rounded-[2px] flex-row"
:class="{ active, 'border-1 py-1 px-2': isAttachment(column) }"
@click="openExpandedForm"
>
<span class="name">
<!-- Render virtual cell -->
<div v-if="isVirtualCol(column)">
<template v-if="column.uidt === UITypes.LinkToAnotherRecord">
<LazySmartsheetVirtualCell :edit-enabled="false" :model-value="value" :column="column" :read-only="true" />
</template>
<LazySmartsheetVirtualCell v-else :edit-enabled="false" :read-only="true" :model-value="value" :column="column" />
</div>
<!-- Render normal cell -->
<template v-else>
<div v-if="isAttachment(column) && value && !Array.isArray(value) && typeof value === 'object'">
<LazySmartsheetCell :model-value="value" :column="column" :edit-enabled="false" :read-only="true" />
</div>
<!-- For attachment cell avoid adding chip style -->
<template v-else>
<div
class="min-w-max"
:class="{
'px-1 rounded-full flex-1': !isAttachment(column),
'border-gray-200 rounded border-1':
border && ![UITypes.Attachment, UITypes.MultiSelect, UITypes.SingleSelect].includes(column.uidt),
}"
>
<LazySmartsheetCell :model-value="value" :column="column" :edit-enabled="false" :virtual="true" :read-only="true" />
</div>
</template>
</template>
</span>
<div v-show="active || isForm" v-if="showUnlinkButton && !readOnly && isUIAllowed('dataEdit')" class="flex items-center">
<component
:is="iconMap.closeThick"
class="nc-icon unlink-icon text-xs text-gray-500/50 group-hover:text-gray-500"
@click.stop="emit('unlink')"
/>
</div>
</div>
</template>
<style scoped lang="scss">
.chip {
max-width: max(100%, 60px);
.name {
text-overflow: ellipsis;
overflow: hidden;
white-space: nowrap;
}
}
</style>
| packages/nc-gui/components/virtual-cell/components/ItemChip.vue | 1 | https://github.com/nocodb/nocodb/commit/b862043ce25ff49926754ea05282a300278ec746 | [
0.01025657169520855,
0.0014051358448341489,
0.00016815272101666778,
0.0001714346872176975,
0.0027603250928223133
] |
{
"id": 3,
"code_window": [
" (event: 'open'): void\n",
"}\n",
"\n",
"const { transition = true, teleportDisabled = false, inline = false, target, zIndex = 100, ...rest } = defineProps<Props>()\n",
"\n",
"const emits = defineEmits<Emits>()\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"const { transition, teleportDisabled, inline, target, zIndex, ...rest } = withDefaults(defineProps<Props>(), {\n",
" transition: true,\n",
" teleportDisabled: false,\n",
" inline: false,\n",
" zIndex: 100,\n",
"})\n"
],
"file_path": "packages/nc-gui/components/general/Overlay.vue",
"type": "replace",
"edit_start_line_idx": 24
} | import mapKeys from 'lodash/mapKeys';
import Debug from '../../../util/Debug';
import Result from '../../../util/Result';
import MysqlClient from './MysqlClient';
const log = new Debug('TidbClient');
class Tidb extends MysqlClient {
/**
*
* @param {Object} - args - Input arguments
* @param {Object} - args.tn -
* @returns {Object[]} - indexes
* @property {String} - indexes[].cstn -
* @property {String} - indexes[].cn -
* @property {String} - indexes[].op -
* @property {String} - indexes[].puc -
* @property {String} - indexes[].cst -
*/
async constraintList(args: any = {}) {
const func = this.constraintList.name;
const result = new Result();
log.api(`${func}:args:`, args);
try {
const response = await this.sqlClient.raw(
`select *, TABLE_NAME as tn from INFORMATION_SCHEMA.KEY_COLUMN_USAGE where CONSTRAINT_SCHEMA=? and TABLE_NAME=?`,
[this.connectionConfig.connection.database, args.tn],
);
if (response.length === 2) {
const indexes = [];
for (let i = 0; i < response[0].length; ++i) {
let index = response[0][i];
index = mapKeys(index, function (_v, k) {
return k.toLowerCase();
});
indexes.push(index);
}
result.data.list = indexes;
} else {
log.debug(
'Unknown response for databaseList:',
result.data.list.length,
);
result.data.list = [];
}
} catch (e) {
log.ppe(e, func);
throw e;
}
log.api(`${func}: result`, result);
return result;
}
}
export default Tidb;
| packages/nocodb/src/db/sql-client/lib/mysql/TidbClient.ts | 0 | https://github.com/nocodb/nocodb/commit/b862043ce25ff49926754ea05282a300278ec746 | [
0.00017477916844654828,
0.00017255079001188278,
0.0001695131795713678,
0.00017296429723501205,
0.0000014889608337398386
] |
{
"id": 3,
"code_window": [
" (event: 'open'): void\n",
"}\n",
"\n",
"const { transition = true, teleportDisabled = false, inline = false, target, zIndex = 100, ...rest } = defineProps<Props>()\n",
"\n",
"const emits = defineEmits<Emits>()\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"const { transition, teleportDisabled, inline, target, zIndex, ...rest } = withDefaults(defineProps<Props>(), {\n",
" transition: true,\n",
" teleportDisabled: false,\n",
" inline: false,\n",
" zIndex: 100,\n",
"})\n"
],
"file_path": "packages/nc-gui/components/general/Overlay.vue",
"type": "replace",
"edit_start_line_idx": 24
} | import { Test } from '@nestjs/testing';
import { FormColumnsService } from './form-columns.service';
import type { TestingModule } from '@nestjs/testing';
describe('FormColumnsService', () => {
let service: FormColumnsService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [FormColumnsService],
}).compile();
service = module.get<FormColumnsService>(FormColumnsService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});
| packages/nocodb/src/services/form-columns.service.spec.ts | 0 | https://github.com/nocodb/nocodb/commit/b862043ce25ff49926754ea05282a300278ec746 | [
0.00017202792514581233,
0.0001715166145004332,
0.00017100528930313885,
0.0001715166145004332,
5.113179213367403e-7
] |
{
"id": 3,
"code_window": [
" (event: 'open'): void\n",
"}\n",
"\n",
"const { transition = true, teleportDisabled = false, inline = false, target, zIndex = 100, ...rest } = defineProps<Props>()\n",
"\n",
"const emits = defineEmits<Emits>()\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"const { transition, teleportDisabled, inline, target, zIndex, ...rest } = withDefaults(defineProps<Props>(), {\n",
" transition: true,\n",
" teleportDisabled: false,\n",
" inline: false,\n",
" zIndex: 100,\n",
"})\n"
],
"file_path": "packages/nc-gui/components/general/Overlay.vue",
"type": "replace",
"edit_start_line_idx": 24
} | <script lang="ts" setup>
import { onKeyStroke } from '@vueuse/core'
import { OrderedWorkspaceRoles, WorkspaceUserRoles } from 'nocodb-sdk'
import { extractSdkResponseErrorMsg, useWorkspace } from '#imports'
import { validateEmail } from '~/utils/validation'
const inviteData = reactive({
email: '',
roles: WorkspaceUserRoles.VIEWER,
})
const focusRef = ref<HTMLInputElement>()
const isDivFocused = ref(false)
const divRef = ref<HTMLDivElement>()
const emailValidation = reactive({
isError: true,
message: '',
})
const singleEmailValue = ref('')
const workspaceStore = useWorkspace()
const { inviteCollaborator: _inviteCollaborator } = workspaceStore
const { isInvitingCollaborators } = storeToRefs(workspaceStore)
const { workspaceRoles } = useRoles()
// all user input emails are stored here
const emailBadges = ref<Array<string>>([])
const insertOrUpdateString = (str: string) => {
// Check if the string already exists in the array
const index = emailBadges.value.indexOf(str)
if (index !== -1) {
// If the string exists, remove it
emailBadges.value.splice(index, 1)
}
// Add the new string to the array
emailBadges.value.push(str)
}
const emailInputValidation = (input: string): boolean => {
if (!input.length) {
emailValidation.isError = true
emailValidation.message = 'Email should not be empty'
return false
}
if (!validateEmail(input.trim())) {
emailValidation.isError = true
emailValidation.message = 'Invalid Email'
return false
}
return true
}
const isInvitButtonDiabled = computed(() => {
if (!emailBadges.value.length && !singleEmailValue.value.length) {
return true
}
if (emailBadges.value.length && inviteData.email) {
return true
}
})
watch(inviteData, (newVal) => {
// when user only want to enter a single email
// we dont convert that as badge
const isSingleEmailValid = validateEmail(newVal.email)
if (isSingleEmailValid && !emailBadges.value.length) {
singleEmailValue.value = newVal.email
emailValidation.isError = false
return
}
singleEmailValue.value = ''
// when user enters multiple emails comma sepearted or space sepearted
const isNewEmail = newVal.email.charAt(newVal.email.length - 1) === ',' || newVal.email.charAt(newVal.email.length - 1) === ' '
if (isNewEmail && newVal.email.trim().length) {
const emailToAdd = newVal.email.split(',')[0].trim() || newVal.email.split(' ')[0].trim()
if (!validateEmail(emailToAdd)) {
emailValidation.isError = true
emailValidation.message = 'Invalid Email'
return
}
/**
if email is already enterd we delete the already
existing email and add new one
**/
if (emailBadges.value.includes(emailToAdd)) {
insertOrUpdateString(emailToAdd)
inviteData.email = ''
return
}
emailBadges.value.push(emailToAdd)
inviteData.email = ''
singleEmailValue.value = ''
}
if (!newVal.email.length && emailValidation.isError) {
emailValidation.isError = false
}
})
const handleEnter = () => {
const isEmailIsValid = emailInputValidation(inviteData.email)
if (!isEmailIsValid) return
inviteData.email += ' '
emailValidation.isError = false
emailValidation.message = ''
}
const inviteCollaborator = async () => {
try {
const payloadData = singleEmailValue.value || emailBadges.value.join(',')
if (!payloadData.includes(',')) {
const validationStatus = validateEmail(payloadData)
if (!validationStatus) {
emailValidation.isError = true
emailValidation.message = 'invalid email'
}
}
await _inviteCollaborator(payloadData, inviteData.roles)
message.success('Invitation sent successfully')
inviteData.email = ''
emailBadges.value = []
} catch (e: any) {
message.error(await extractSdkResponseErrorMsg(e))
} finally {
singleEmailValue.value = ''
}
}
// allow only lower roles to be assigned
const allowedRoles = ref<WorkspaceUserRoles[]>([])
onMounted(async () => {
try {
const currentRoleIndex = OrderedWorkspaceRoles.findIndex(
(role) => workspaceRoles.value && Object.keys(workspaceRoles.value).includes(role),
)
if (currentRoleIndex !== -1) {
allowedRoles.value = OrderedWorkspaceRoles.slice(currentRoleIndex + 1).filter((r) => r)
}
} catch (e: any) {
message.error(await extractSdkResponseErrorMsg(e))
}
})
const focusOnDiv = () => {
focusRef.value?.focus()
isDivFocused.value = true
}
// remove one email per backspace
onKeyStroke('Backspace', () => {
if (isDivFocused.value && inviteData.email.length < 1) {
emailBadges.value.pop()
}
})
// when bulk email is pasted
const onPaste = (e: ClipboardEvent) => {
const pastedText = e.clipboardData?.getData('text')
const inputArray = pastedText?.split(',') || pastedText?.split(' ')
// if data is pasted to a already existing text in input
// we add existingInput + pasted data
if (inputArray?.length === 1 && inviteData.email.length) {
inputArray[0] = inviteData.email += inputArray[0]
}
inputArray?.forEach((el) => {
const isEmailIsValid = emailInputValidation(el)
if (!isEmailIsValid) return
/**
if email is already enterd we delete the already
existing email and add new one
**/
if (emailBadges.value.includes(el)) {
insertOrUpdateString(el)
return
}
emailBadges.value.push(el)
inviteData.email = ''
})
inviteData.email = ''
}
</script>
<template>
<div class="my-2 pt-3 ml-2" data-testid="invite">
<div class="flex gap-2">
<div class="flex flex-col">
<div
ref="divRef"
class="flex w-130 border-1 gap-1 items-center flex-wrap min-h-8 max-h-30 rounded-lg nc-scrollbar-md"
tabindex="0"
:class="{
'border-primary/100': isDivFocused,
'p-1': emailBadges.length > 1,
}"
@click="focusOnDiv"
@blur="isDivFocused = false"
>
<span
v-for="(email, index) in emailBadges"
:key="email"
class="leading-4 border-1 text-brand-500 bg-brand-50 rounded-md ml-1 p-0.5"
>
{{ email }}
<component
:is="iconMap.close"
class="ml-0.5 hover:cursor-pointer w-3.5 h-3.5"
@click="emailBadges.splice(index, 1)"
/>
</span>
<input
id="email"
ref="focusRef"
v-model="inviteData.email"
:placeholder="emailBadges.length < 1 ? 'Enter emails to send invitation' : ''"
class="min-w-60 outline-0 ml-2 mr-3 flex-grow-1"
data-testid="email-input"
@keyup.enter="handleEnter"
@blur="isDivFocused = false"
@paste.prevent="onPaste"
/>
</div>
<span v-if="emailValidation.isError" class="ml-2 text-red-500 text-[10px] mt-1.5">{{ emailValidation.message }}</span>
</div>
<RolesSelector
size="md"
class="px-1"
:role="inviteData.roles"
:roles="allowedRoles"
:on-role-change="(role: WorkspaceUserRoles) => (inviteData.roles = role)"
:description="true"
/>
<NcButton
type="primary"
size="small"
:disabled="isInvitButtonDiabled || isInvitingCollaborators || emailValidation.isError"
:loading="isInvitingCollaborators"
@click="inviteCollaborator"
>
<MdiPlus />
{{ isInvitingCollaborators ? 'Adding' : 'Add' }} Member(s)
</NcButton>
</div>
</div>
</template>
<style scoped>
:deep(.ant-select .ant-select-selector) {
@apply rounded;
}
.badge-text {
@apply text-[14px] pt-1 text-center;
}
:deep(.ant-select-selection-item) {
@apply mt-0.75;
}
</style>
| packages/nc-gui/components/workspace/InviteSection.vue | 0 | https://github.com/nocodb/nocodb/commit/b862043ce25ff49926754ea05282a300278ec746 | [
0.0002612197131384164,
0.00017659891454968601,
0.00016860257892403752,
0.00017193576786667109,
0.00001727012568153441
] |
{
"id": 4,
"code_window": [
" width?: string\n",
"}\n",
"\n",
"const {\n",
" url,\n",
" socialMedias,\n",
" title = 'NocoDB',\n",
" summary,\n",
" hashTags = '',\n",
" css = '',\n",
" iconClass = '',\n",
" width = '45px',\n",
"} = defineProps<Props>()\n",
"\n",
"const summaryArr = [\n",
" 'Instant #Rest & #GraphQL APIs on any #SQL Database (Supports : MySQL, PostgresSQL, MsSQL, SQLite, MariaDB) #nocodb ',\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"const { url, socialMedias, title, summary, hashTags, css, iconClass, width } = withDefaults(defineProps<Props>(), {\n",
" title: 'NocoDB',\n",
" hashTags: '',\n",
" css: '',\n",
" iconClass: '',\n",
" width: '45px',\n",
"})\n"
],
"file_path": "packages/nc-gui/components/general/Share.vue",
"type": "replace",
"edit_start_line_idx": 14
} | <script lang="ts" setup>
import { computed } from '#imports'
interface Props {
url: string
socialMedias: string[]
title?: string
summary?: string
hashTags?: string
css?: string
iconClass?: string
width?: string
}
const {
url,
socialMedias,
title = 'NocoDB',
summary,
hashTags = '',
css = '',
iconClass = '',
width = '45px',
} = defineProps<Props>()
const summaryArr = [
'Instant #Rest & #GraphQL APIs on any #SQL Database (Supports : MySQL, PostgresSQL, MsSQL, SQLite, MariaDB) #nocodb ',
'Instantly generate #Rest & #GraphQL APIs on any #SQL Database (Supports : MySQL, PostgresSQL, MsSQL, SQLite, MariaDB) #nocodb',
'Instant #serverless Rest & #GraphQL APIs on any Database #nocodb',
'Instant APIs on any SQL Database (Supports : #REST #GraphQL #MySQL, #PostgresSQL, #MsSQL, #SQLite, #MariaDB) #nocodb',
'Generate Instant APIs on any SQL Database (Supports : #REST #GraphQL #MySQL, #PostgresSQL, #MsSQL, #SQLite, #MariaDB) #nocodb',
]
const shareUrl = computed(() => encodeURIComponent(url))
const encodedTitle = computed(() => encodeURIComponent(title || 'NocoDB'))
const encodedSummary = computed(() => encodeURIComponent(summary || summaryArr[Math.floor(Math.random() * summaryArr.length)]))
const fbHashTags = computed(() => hashTags && `%23${hashTags}`)
const openUrl = (url: string) => {
window.open(url, '_blank', 'noopener,noreferrer')
}
</script>
<template>
<div class="flex gap-2">
<a
v-if="!socialMedias || !socialMedias.length || socialMedias.includes('twitter')"
href="#"
:class="iconClass"
class="px-2"
@click.prevent="openUrl(`https://twitter.com/intent/tweet?url=${shareUrl}&text=${encodedSummary}&hashtags=${hashTags}`)"
>
<img
src="~/assets/img/social/twitter.png"
class="img-responsive"
alt="Twitter"
:width="width"
:style="css"
title="Social Media Share"
/>
</a>
<a
v-if="!socialMedias || !socialMedias.length || socialMedias.includes('linkedin')"
href="#"
:class="iconClass"
class="px-2"
@click.prevent="
openUrl(`https://www.linkedin.com/shareArticle?mini=true&url=${shareUrl}&title=${encodedTitle}&summary=${encodedSummary}`)
"
>
<img
src="~/assets/img/social/linkedin.png"
class="img-responsive"
alt="Linkedin"
:width="width"
:style="css"
title="Social Media Share"
/>
</a>
<a
v-if="!socialMedias || !socialMedias.length || socialMedias.includes('facebook')"
href="#"
:class="iconClass"
class="px-2"
@click.prevent="
openUrl(
`https://www.facebook.com/sharer/sharer.php?u=${shareUrl}&title=${encodedTitle}&summary=${encodedSummary}"e=${encodedTitle}&hashtag=${fbHashTags}`,
)
"
>
<img
src="~/assets/img/social/facebook.png"
class="img-responsive"
alt="Facebook"
:width="width"
:style="css"
title="Social Media Share"
/>
</a>
<a
v-if="!socialMedias || !socialMedias.length || socialMedias.includes('reddit')"
href="#"
:class="iconClass"
class="px-2"
@click.prevent="openUrl(`https://www.reddit.com/submit?url=${shareUrl}&title=${encodedSummary}`)"
>
<img
src="~/assets/img/social/reddit.png"
class="img-responsive"
alt="Reddit"
:width="width"
:style="css"
title="Social Media Share"
/>
</a>
<a
v-if="!socialMedias || !socialMedias.length || socialMedias.includes('pinterest')"
href="#"
:class="iconClass"
class="px-2"
@click.prevent="openUrl(`https://pinterest.com/pin/create/button/?url=${shareUrl}&description==${encodedSummary}`)"
>
<img
src="~/assets/img/social/pinterest.png"
class="img-responsive"
alt="Printrest"
:width="width"
:style="css"
title="Social Media Share"
/>
</a>
<a
v-if="!socialMedias || !socialMedias.length || socialMedias.includes('whatsapp')"
href="#"
:class="iconClass"
class="px-2"
@click.prevent="openUrl(`https://api.whatsapp.com/send?text=${encodedSummary}%0D%0A${shareUrl}`)"
>
<img
src="~/assets/img/social/whatsapp.png"
class="img-responsive"
alt="Whatsapp"
:width="width"
:style="css"
title="Social Media Share"
/>
</a>
<a
v-if="!socialMedias || !socialMedias.length || socialMedias.includes('telegram')"
href="#"
:class="iconClass"
class="px-2"
@click.prevent="openUrl(`https://telegram.me/share/url?url=${shareUrl}&text=${encodedSummary}`)"
>
<img
src="~/assets/img/social/png/telegram.png"
class="img-responsive"
alt="Telegram"
:width="width"
:style="css"
title="Social Media Share"
/>
</a>
<a
v-if="!socialMedias || !socialMedias.length || socialMedias.includes('wechat')"
:class="iconClass"
class="px-2"
@click.prevent="openUrl(`https://www.addtoany.com/add_to/wechat?linkurl=${shareUrl}&linkname=${encodedTitle}`)"
>
<img
src="~/assets/img/social/png/wechat.png"
class="img-responsive"
alt="Wechat"
:width="width"
:style="css"
title="Social Media Share"
/>
</a>
<a v-if="!socialMedias || !socialMedias.length || socialMedias.includes('line')" href="#" :class="iconClass" class="px-2">
<img
src="~/assets/img/social/png/line.png"
class="img-responsive"
alt="Line"
:width="width"
:style="css"
title="Social Media Share"
@click.prevent="openUrl(`http://line.me/R/msg/text/?${encodedTitle}%0D%0A${shareUrl}`)"
/>
</a>
<a
v-if="!socialMedias || !socialMedias.length || socialMedias.includes('odnoklassniki')"
href="#"
:class="iconClass"
class="px-2"
>
<img
src="~/assets/img/social/png/odnoklassniki.png"
class="img-responsive"
alt="Odnoklassniki"
:width="width"
:style="css"
title="Social Media Share"
@click.prevent="
openUrl(`https://connect.ok.ru/dk?st.cmd=WidgetSharePreview&st.shareUrl=${shareUrl}&st.comments=${encodedSummary}`)
"
/>
</a>
<a
v-if="!socialMedias || !socialMedias.length || socialMedias.includes('weibo')"
href="#"
:class="iconClass"
class="px-2"
@click.prevent="openUrl(`http://service.weibo.com/share/share.php?url=${shareUrl})&title=${encodedTitle}`)"
>
<img
src="~/assets/img/social/png/weibo.png"
class="img-responsive"
alt="Weibo"
:width="width"
:style="css"
title="Social Media Share"
/>
</a>
<a
v-if="!socialMedias || !socialMedias.length || socialMedias.includes('renren')"
:class="iconClass"
class="px-2"
@click.prevent="
openUrl(
`http://widget.renren.com/dialog/share?resourceUrl=${shareUrl}&srcUrl=${shareUrl}&title=${encodedTitle}&description=${encodedSummary}`,
)
"
>
<img
src="~/assets/img/social/png/renren.png"
class="img-responsive"
alt="Renren"
:width="width"
:style="css"
title="Social Media Share"
/>
</a>
<a
v-if="!socialMedias || !socialMedias.length || socialMedias.includes('douban')"
:class="iconClass"
class="px-2"
@click.prevent="openUrl(`http://www.douban.com/recommend/?url=${shareUrl}&title=${encodedTitle}`)"
>
<img
src="~/assets/img/social/png/douban.png"
class="img-responsive"
alt="Douban"
:width="width"
:style="css"
title="Social Media Share"
/>
</a>
<a
v-if="!socialMedias || !socialMedias.length || socialMedias.includes('vk')"
href="#"
:class="iconClass"
class="px-2"
@click.prevent="
openUrl(`https://vk.com/share.php?url=${shareUrl})&title=${encodedTitle}&description=${encodedSummary}&noparse=true`)
"
>
<img
src="~/assets/img/social/png/vk.png"
class="img-responsive"
alt="VK"
:width="width"
:style="css"
title="Social Media Share"
/>
</a>
<a
v-if="!socialMedias || !socialMedias.length || socialMedias.includes('wykop')"
:class="iconClass"
class="px-2"
@click.prevent="openUrl(`https://www.addtoany.com/add_to/wykop?linkurl=${shareUrl}&linkname=${encodedTitle}`)"
>
<img
src="~/assets/img/social/png/wykop.jpg"
class="img-responsive"
alt="Wykop"
:width="width"
:style="css"
title="Social Media Share"
/>
</a>
</div>
</template>
<style scoped>
.img-responsive {
width: 30px;
}
.small .img-responsive {
width: 25px;
}
a {
@apply cursor-pointer text-3xl rounded-full p-2 bg-gray-100 shadow-md hover:(shadow-lg bg-gray-200);
}
</style>
| packages/nc-gui/components/general/Share.vue | 1 | https://github.com/nocodb/nocodb/commit/b862043ce25ff49926754ea05282a300278ec746 | [
0.9987086057662964,
0.5616109371185303,
0.00016777652490418404,
0.9916204810142517,
0.49250414967536926
] |
{
"id": 4,
"code_window": [
" width?: string\n",
"}\n",
"\n",
"const {\n",
" url,\n",
" socialMedias,\n",
" title = 'NocoDB',\n",
" summary,\n",
" hashTags = '',\n",
" css = '',\n",
" iconClass = '',\n",
" width = '45px',\n",
"} = defineProps<Props>()\n",
"\n",
"const summaryArr = [\n",
" 'Instant #Rest & #GraphQL APIs on any #SQL Database (Supports : MySQL, PostgresSQL, MsSQL, SQLite, MariaDB) #nocodb ',\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"const { url, socialMedias, title, summary, hashTags, css, iconClass, width } = withDefaults(defineProps<Props>(), {\n",
" title: 'NocoDB',\n",
" hashTags: '',\n",
" css: '',\n",
" iconClass: '',\n",
" width: '45px',\n",
"})\n"
],
"file_path": "packages/nc-gui/components/general/Share.vue",
"type": "replace",
"edit_start_line_idx": 14
} | <script setup lang="ts">
import { iconMap, useVModel } from '#imports'
const props = defineProps<{
modelValue: any[]
}>()
const emits = defineEmits(['update:modelValue'])
interface Option {
value: string
}
const vModel = useVModel(props, 'modelValue', emits)
const headerList = ref<Option[]>([
{ value: 'A-IM' },
{ value: 'Accept' },
{ value: 'Accept-Charset' },
{ value: 'Accept-Encoding' },
{ value: 'Accept-Language' },
{ value: 'Accept-Datetime' },
{ value: 'Access-Control-Request-Method' },
{ value: 'Access-Control-Request-Headers' },
{ value: 'Authorization' },
{ value: 'Cache-Control' },
{ value: 'Connection' },
{ value: 'Content-Length' },
{ value: 'Content-Type' },
{ value: 'Cookie' },
{ value: 'Date' },
{ value: 'Expect' },
{ value: 'Forwarded' },
{ value: 'From' },
{ value: 'Host' },
{ value: 'If-Match' },
{ value: 'If-Modified-Since' },
{ value: 'If-None-Match' },
{ value: 'If-Range' },
{ value: 'If-Unmodified-Since' },
{ value: 'Max-Forwards' },
{ value: 'Origin' },
{ value: 'Pragma' },
{ value: 'Proxy-Authorization' },
{ value: 'Range' },
{ value: 'Referer' },
{ value: 'TE' },
{ value: 'User-Agent' },
{ value: 'Upgrade' },
{ value: 'Via' },
{ value: 'Warning' },
{ value: 'Non-standard headers' },
{ value: 'Dnt' },
{ value: 'X-Requested-With' },
{ value: 'X-CSRF-Token' },
])
const addHeaderRow = () => vModel.value.push({})
const deleteHeaderRow = (i: number) => vModel.value.splice(i, 1)
const filterOption = (input: string, option: Option) => option.value.toUpperCase().includes(input.toUpperCase())
</script>
<template>
<div class="flex flex-row justify-between w-full">
<table class="w-full nc-webhooks-params">
<thead class="h-8">
<tr>
<th></th>
<th>
<div class="text-left font-normal ml-2" data-rec="true">{{ $t('labels.headerName') }}</div>
</th>
<th>
<div class="text-left font-normal ml-2" data-rec="true">{{ $t('placeholder.value') }}</div>
</th>
<th class="w-8"></th>
</tr>
</thead>
<tbody>
<tr v-for="(headerRow, idx) in vModel" :key="idx" class="!h-2 overflow-hidden">
<td class="px-2 nc-hook-header-tab-checkbox">
<a-form-item class="form-item">
<a-checkbox v-model:checked="headerRow.enabled" />
</a-form-item>
</td>
<td class="px-2">
<a-form-item class="form-item">
<a-auto-complete
v-model:value="headerRow.name"
class="nc-input-hook-header-key"
:options="headerList"
:placeholder="$t('placeholder.key')"
:filter-option="filterOption"
dropdown-class-name="border-1 border-gray-200"
/>
</a-form-item>
</td>
<td class="px-2">
<a-form-item class="form-item">
<a-input
v-model:value="headerRow.value"
:placeholder="$t('placeholder.value')"
class="!rounded-md nc-input-hook-header-value"
/>
</a-form-item>
</td>
<td class="relative">
<div
v-if="idx !== 0"
class="absolute left-0 top-0.25 py-1 px-1.5 rounded-md border-1 border-gray-100"
:class="{
'text-gray-400 cursor-not-allowed bg-gray-50': vModel.length === 1,
'text-gray-600 cursor-pointer hover:bg-gray-50 hover:text-black': vModel.length !== 1,
}"
@click="deleteHeaderRow(idx)"
>
<component :is="iconMap.delete" />
</div>
</td>
</tr>
<tr>
<td :colspan="12" class="">
<NcButton size="small" type="secondary" @click="addHeaderRow">
<div class="flex flex-row items-center gap-x-1">
<div data-rec="true">{{ $t('labels.addHeader') }}</div>
<component :is="iconMap.plus" class="flex mx-auto" />
</div>
</NcButton>
</td>
</tr>
</tbody>
</table>
</div>
</template>
<style lang="scss" scoped>
.form-item {
@apply !mb-3;
}
</style>
| packages/nc-gui/components/api-client/Headers.vue | 0 | https://github.com/nocodb/nocodb/commit/b862043ce25ff49926754ea05282a300278ec746 | [
0.0014581347350031137,
0.00025958108017221093,
0.000169466802617535,
0.00017258274601772428,
0.0003203742962796241
] |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.