hunk
dict | file
stringlengths 0
11.8M
| file_path
stringlengths 2
234
| label
int64 0
1
| commit_url
stringlengths 74
103
| dependency_score
listlengths 5
5
|
---|---|---|---|---|---|
{
"id": 2,
"code_window": [
" color_scheme: {\n",
" description: t(\n",
" 'When only a primary metric is provided, a categorical color scale is used.',\n",
" ),\n",
" },\n",
" linear_color_scheme: {\n",
" description: t(\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" visibility: ({ controls }: ControlPanelsContainerProps) =>\n",
" Boolean(\n",
" !controls?.secondary_metric?.value ||\n",
" controls?.secondary_metric?.value === controls?.metric.value,\n",
" ),\n"
],
"file_path": "superset-frontend/plugins/legacy-plugin-chart-sunburst/src/controlPanel.ts",
"type": "add",
"edit_start_line_idx": 73
}
|
/*
* 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.
*/
export default function isDefined(x: unknown) {
return x !== null && x !== undefined;
}
|
superset-frontend/packages/superset-ui-core/src/utils/isDefined.ts
| 0 |
https://github.com/apache/superset/commit/9646591d240516a7eb1515e70cfb8768352e4f30
|
[
0.0001744508190313354,
0.00017414607282262295,
0.00017390110588166863,
0.00017408626445103437,
2.2836819368876604e-7
] |
{
"id": 2,
"code_window": [
" color_scheme: {\n",
" description: t(\n",
" 'When only a primary metric is provided, a categorical color scale is used.',\n",
" ),\n",
" },\n",
" linear_color_scheme: {\n",
" description: t(\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" visibility: ({ controls }: ControlPanelsContainerProps) =>\n",
" Boolean(\n",
" !controls?.secondary_metric?.value ||\n",
" controls?.secondary_metric?.value === controls?.metric.value,\n",
" ),\n"
],
"file_path": "superset-frontend/plugins/legacy-plugin-chart-sunburst/src/controlPanel.ts",
"type": "add",
"edit_start_line_idx": 73
}
|
{
"type": "FeatureCollection",
"crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:OGC:1.3:CRS84" } },
"features": [
{ "type": "Feature", "properties": { "ISO": "ZM-10", "NAME_1": "Muchinga" }, "geometry": { "type": "Polygon", "coordinates": [ [ [ 32.920863485000098, -9.407900085999913 ], [ 32.927788127000042, -9.479833678999867 ], [ 32.961894572000119, -9.480350443999896 ], [ 32.991970255000126, -9.50184783999994 ], [ 32.974710327000082, -9.601273294999942 ], [ 32.986905965000119, -9.628455098999936 ], [ 33.035740194000084, -9.616982929999921 ], [ 33.058322794000048, -9.654293313999858 ], [ 33.08044030700006, -9.662251484999913 ], [ 33.098320353000076, -9.588457539999879 ], [ 33.175421590000042, -9.602306823999925 ], [ 33.214282267000101, -9.654706725999873 ], [ 33.204567098000041, -9.698114928999956 ], [ 33.21671106000008, -9.727053730999927 ], [ 33.287766154000053, -9.803844908999892 ], [ 33.343473348000089, -9.831440123999897 ], [ 33.365590861000044, -9.898826191999902 ], [ 33.309987020000108, -10.012721048999936 ], [ 33.304095907000089, -10.063777363999918 ], [ 33.480519246000142, -10.177052103999898 ], [ 33.533280884000078, -10.231209004999911 ], [ 33.529301799000109, -10.318645527999962 ], [ 33.559170776000087, -10.404325052999937 ], [ 33.638184042000091, -10.511605325999895 ], [ 33.665417522000098, -10.51511932399994 ], [ 33.674202515000047, -10.577027688999877 ], [ 33.528268270000126, -10.711593118999929 ], [ 33.500983113000075, -10.769160664999973 ], [ 33.434010458000103, -10.808124694999961 ], [ 33.385537964000036, -10.800889993999903 ], [ 33.319082072000072, -10.81814992199989 ], [ 33.288127889000066, -10.856700540999952 ], [ 33.241412394000065, -10.865692240999905 ], [ 33.232575725000061, -10.883262226999875 ], [ 33.239603719000058, -10.903105976999967 ], [ 33.280324747000066, -10.913337910999942 ], [ 33.303682495000089, -11.034570820999889 ], [ 33.390912313000115, -11.164795430999959 ], [ 33.298308146000124, -11.329229837999947 ], [ 33.298928264000097, -11.353104349999938 ], [ 33.273503459000096, -11.369640807999929 ], [ 33.265183553000043, -11.423074238999945 ], [ 33.239707072000101, -11.402403665999927 ], [ 33.230301961000066, -11.416563008999972 ], [ 33.233815959000083, -11.514024758999952 ], [ 33.212628621000079, -11.563840840999902 ], [ 33.283218628000043, -11.578413594999859 ], [ 33.305048860801634, -11.644026180450906 ], [ 33.216345951004826, -11.673335567982065 ], [ 33.197443350030539, -11.701553682156714 ], [ 33.197443350030539, -11.748648440173383 ], [ 33.088224243454079, -11.950283713022941 ], [ 32.726961044916266, -12.059502819599459 ], [ 32.542128711470809, -12.067904289751198 ], [ 32.500121362510868, -12.10991163781182 ], [ 32.483318423106709, -12.168721926175976 ], [ 32.432909604894348, -12.219130744388337 ], [ 32.291290318093672, -12.20116708689153 ], [ 32.276355829058218, -12.263592218206327 ], [ 32.193776889791593, -12.346171155674313 ], [ 32.140808547076745, -12.443374525613876 ], [ 32.067789748298253, -12.784645683551446 ], [ 32.044173617918091, -12.797409763150029 ], [ 32.007121616169627, -12.886241550107457 ], [ 31.954825067023194, -12.901072685456086 ], [ 31.913225539027394, -12.935179132311134 ], [ 31.913225539027394, -13.030780530896777 ], [ 31.872297803700633, -13.036981702643459 ], [ 31.769254999018983, -13.106486504848306 ], [ 31.755560744332854, -13.092223808482004 ], [ 31.714529657117964, -13.174389336598608 ], [ 31.675100538558979, -13.200537611621485 ], [ 31.63810021275458, -13.335619805609554 ], [ 31.613760613761315, -13.366573989298161 ], [ 31.5182625670638, -13.431944674607053 ], [ 31.461366814826647, -13.421816095136705 ], [ 31.429120720844594, -13.435717054498468 ], [ 31.425813428946583, -13.324819430772095 ], [ 31.364990268985707, -13.228597913662782 ], [ 31.335844761326655, -12.976985364982625 ], [ 31.282618036193412, -12.949235121303786 ], [ 31.219624464997025, -12.948046562898583 ], [ 31.183761020754503, -12.966288343831991 ], [ 31.159886508855266, -13.034191175582293 ], [ 31.120767449558116, -13.040702405691491 ], [ 31.020515171038312, -12.950837090859068 ], [ 30.906620313776443, -12.927789402159192 ], [ 30.849672885595169, -12.933473809069028 ], [ 30.750195754330605, -12.871462090702948 ], [ 30.727251418418177, -12.76025440771474 ], [ 30.765285272097628, -12.691576429608574 ], [ 30.762959832130548, -12.668115329758677 ], [ 30.71670942599917, -12.63617929413914 ], [ 30.686582066409244, -12.588533624027548 ], [ 30.634750604356896, -12.625172213726671 ], [ 30.564470655796129, -12.574012546142114 ], [ 30.56989668118689, -12.509003595139802 ], [ 30.497291293558305, -12.450712578922378 ], [ 30.513104281737185, -12.34090015991444 ], [ 30.500081820619528, -12.309377537243563 ], [ 30.448560417829015, -12.308499037200818 ], [ 30.412852004116701, -12.273359062470774 ], [ 30.361382277270252, -12.272222181808274 ], [ 30.161807896217397, -12.202303968453407 ], [ 30.142119175359653, -12.174553724774569 ], [ 30.078505487438292, -12.139827162093866 ], [ 30.029774610809625, -12.034252210970749 ], [ 29.997321812151881, -12.000507501120296 ], [ 29.862653029313833, -12.044484145027297 ], [ 29.838881870202101, -12.133781019978073 ], [ 29.799582314000133, -12.159035937999903 ], [ 29.816557651014762, -12.133264255141285 ], [ 29.816557651014762, -12.085463556298066 ], [ 29.781779413289257, -12.037662855656265 ], [ 29.778678826966257, -11.910125420551708 ], [ 30.261440057112907, -11.818864840839751 ], [ 30.447630242741468, -11.589989922496954 ], [ 30.455846795193452, -11.501726575421117 ], [ 30.522064649064305, -11.461114190967123 ], [ 30.548757357466059, -11.399834893965192 ], [ 30.588145378806189, -11.385674737399199 ], [ 30.617686393911924, -11.330743097316088 ], [ 30.662038607295869, -11.330743097316088 ], [ 30.706309441027884, -11.290459893509308 ], [ 30.84856204480252, -11.056573174812172 ], [ 30.867279493353919, -11.042982680306466 ], [ 30.893809440653172, -11.059095961109733 ], [ 30.878916862723031, -11.02971770620718 ], [ 30.970632357297404, -10.999362888286669 ], [ 31.000987175217915, -10.920098565896126 ], [ 31.021657748006646, -10.919854425141637 ], [ 31.010752800001683, -10.932468357528705 ], [ 31.037608269505995, -10.948907159637713 ], [ 31.052744988190625, -10.944349867652249 ], [ 31.058848503455636, -10.911065362476506 ], [ 31.076670769540385, -10.941745700803438 ], [ 31.063405795441099, -10.961439711473531 ], [ 31.085378451654208, -10.961358330922224 ], [ 31.145274284680454, -10.916843357335097 ], [ 31.17090905041232, -10.8732235653153 ], [ 31.143565300298349, -10.826674086040271 ], [ 31.20419355558812, -10.810723565440185 ], [ 31.19214928436196, -10.783054294919793 ], [ 31.157481316109852, -10.788099867514859 ], [ 31.130625847504859, -10.750013930498483 ], [ 31.20728600394591, -10.708184503412099 ], [ 31.275482618128308, -10.728041274285374 ], [ 31.309662305770757, -10.70134856588362 ], [ 31.309662305770757, -10.6498348936654 ], [ 31.33895918102138, -10.637058201075149 ], [ 31.334971550196883, -10.612481378013172 ], [ 31.43702233161531, -10.577813409761063 ], [ 31.461192253719503, -10.550469659647092 ], [ 31.488373242730972, -10.570977472232585 ], [ 31.552826367742682, -10.558038018539719 ], [ 31.549758256838061, -10.30875174979343 ], [ 31.516229482304766, -10.275222975260135 ], [ 31.340203413756512, -10.183018843944524 ], [ 31.264763669707577, -9.9566996135963 ], [ 31.189323926557961, -9.830966707747393 ], [ 31.113884182508968, -9.755526963698401 ], [ 31.180941732474935, -9.671705026465816 ], [ 31.20608831382458, -9.613029670582819 ], [ 31.365349995106158, -9.504061152000588 ], [ 31.432407545072124, -9.545972120616852 ], [ 31.508067253401009, -9.540052992451649 ], [ 31.574904838187706, -9.571118701966554 ], [ 31.600051419537351, -9.504061152000588 ], [ 31.675491162686967, -9.529207733350233 ], [ 31.75093090673596, -9.520825539267207 ], [ 31.901810393934511, -9.437003602034622 ], [ 32.019161105700448, -9.420239214767946 ], [ 32.329302274180577, -9.462150183384267 ], [ 32.320920080097608, -9.361563857985686 ], [ 32.231448201573244, -9.133808288022067 ], [ 32.423426148000146, -9.143833516999862 ], [ 32.459703003000072, -9.168018086999936 ], [ 32.518045695000126, -9.25824513799995 ], [ 32.71322758000008, -9.285840352999941 ], [ 32.752294962000065, -9.337413430999959 ], [ 32.784334351000098, -9.339687194999968 ], [ 32.920863485000098, -9.407900085999913 ] ] ] } },
{ "type": "Feature", "properties": { "ISO": "ZM-03", "NAME_1": "Eastern" }, "geometry": { "type": "Polygon", "coordinates": [ [ [ 33.305048860801634, -11.644026180450906 ], [ 33.314017781000075, -11.772200215999902 ], [ 33.297481323000113, -11.862530618999941 ], [ 33.312674194000124, -11.898704120999881 ], [ 33.254899943000055, -12.072646992999935 ], [ 33.252729533000036, -12.139516295999911 ], [ 33.29996179200009, -12.195946959999944 ], [ 33.349467814000036, -12.327928567999905 ], [ 33.384607788000096, -12.340020852999885 ], [ 33.458298381000077, -12.31811004599993 ], [ 33.52558109600011, -12.335266621999892 ], [ 33.5271313880001, -12.355627135999924 ], [ 33.465326376000121, -12.409060566999941 ], [ 33.451115356000059, -12.452985533999879 ], [ 33.35039799000009, -12.532670592999935 ], [ 33.255106648000094, -12.531947122999938 ], [ 33.226994670000067, -12.579076029999939 ], [ 33.173251180000079, -12.620003763999961 ], [ 33.13035974100012, -12.583726908999907 ], [ 33.081267130000072, -12.604810892999936 ], [ 33.057702678000055, -12.583416848999917 ], [ 33.024836466000124, -12.612665710999877 ], [ 32.941120646000059, -12.769865416999977 ], [ 32.947011760000066, -12.843245950999915 ], [ 33.013571004000084, -12.917246601999921 ], [ 32.981531616000041, -13.006130065999884 ], [ 32.965925334000133, -13.116820983999943 ], [ 32.998171427000102, -13.202448831999916 ], [ 32.937865031000115, -13.255882262999933 ], [ 32.892131388000053, -13.404813740999899 ], [ 32.874251342000036, -13.443157653999918 ], [ 32.819060913000044, -13.471683043999874 ], [ 32.813066447000097, -13.528217060999921 ], [ 32.722839396000097, -13.5733822629999 ], [ 32.677260783000065, -13.567801207999892 ], [ 32.663308147000123, -13.596326598999937 ], [ 32.675090372000113, -13.628055927999952 ], [ 32.769864950000056, -13.646866149999966 ], [ 32.813376506000054, -13.711151631999925 ], [ 32.757359253000061, -13.750219013999939 ], [ 32.763043660000108, -13.777194111999876 ], [ 32.874147990000097, -13.820602314999874 ], [ 32.923912394000126, -13.880443622999934 ], [ 32.936159709000037, -13.926228941999881 ], [ 32.976260620000119, -13.94452239999994 ], [ 32.971299683000098, -14.005914000999923 ], [ 32.999825074000057, -14.050459085999918 ], [ 33.018170206000036, -14.046221618999965 ], [ 33.062973673000101, -13.981729430999863 ], [ 33.111601196000095, -13.964572854999886 ], [ 33.140281616000095, -13.92498870799993 ], [ 33.202706747000036, -14.013872171999893 ], [ 31.658408244000043, -14.519577737999981 ], [ 31.410878133000097, -14.633575947999958 ], [ 30.815772339000034, -14.768244730999953 ], [ 30.485559937000119, -14.88596364299994 ], [ 30.318438355000069, -14.966992289999951 ], [ 30.214420897000082, -14.981965750999933 ], [ 30.206508009636934, -14.830670667916991 ], [ 30.062020704791678, -14.698430677833528 ], [ 30.000112339213047, -14.617350356233942 ], [ 30.000267367944673, -14.556733900948757 ], [ 30.034580518576036, -14.442425631637605 ], [ 30.069462110887685, -14.415140475952228 ], [ 30.083621453567218, -14.377881767729377 ], [ 30.122998895282763, -14.372559096025441 ], [ 30.218755324398671, -14.257940769251093 ], [ 30.291515740758825, -14.2068327776106 ], [ 30.319007602918532, -14.131333510133402 ], [ 30.278338250010222, -14.08177581120475 ], [ 30.184442172867989, -14.047204278154936 ], [ 30.14878543509974, -13.951189466620576 ], [ 30.097729120302631, -13.931862480968732 ], [ 30.892202589577835, -13.922095635804965 ], [ 30.936902703896635, -13.860032239696125 ], [ 30.959330274972217, -13.852590833600118 ], [ 30.970699089691209, -13.812231540852906 ], [ 31.061597935096586, -13.773525892705777 ], [ 31.056068556019, -13.757609551739449 ], [ 31.098598260001665, -13.713839614306778 ], [ 31.135185173756724, -13.607489515928421 ], [ 31.183295932761041, -13.578240654582544 ], [ 31.222414992058191, -13.582271416892354 ], [ 31.258898553025801, -13.513645114730252 ], [ 31.283238152918386, -13.517417493722348 ], [ 31.359357538019935, -13.461090183165425 ], [ 31.461366814826647, -13.421816095136705 ], [ 31.53464399602359, -13.425226738922845 ], [ 31.63810021275458, -13.335619805609554 ], [ 31.675100538558979, -13.200537611621485 ], [ 31.714529657117964, -13.174389336598608 ], [ 31.755560744332854, -13.092223808482004 ], [ 31.769254999018983, -13.106486504848306 ], [ 31.872297803700633, -13.036981702643459 ], [ 31.913225539027394, -13.030780530896777 ], [ 31.913225539027394, -12.935179132311134 ], [ 31.954825067023194, -12.901072685456086 ], [ 32.007121616169627, -12.886241550107457 ], [ 32.044173617918091, -12.797409763150029 ], [ 32.067789748298253, -12.784645683551446 ], [ 32.140808547076745, -12.443374525613876 ], [ 32.193776889791593, -12.346171155674313 ], [ 32.276355829058218, -12.263592218206327 ], [ 32.291290318093672, -12.20116708689153 ], [ 32.432909604894348, -12.219130744388337 ], [ 32.483318423106709, -12.168721926175976 ], [ 32.500121362510868, -12.10991163781182 ], [ 32.542128711470809, -12.067904289751198 ], [ 32.726961044916266, -12.059502819599459 ], [ 33.088224243454079, -11.950283713022941 ], [ 33.197443350030539, -11.748648440173383 ], [ 33.197443350030539, -11.701553682156714 ], [ 33.216345951004826, -11.673335567982065 ], [ 33.305048860801634, -11.644026180450906 ] ] ] } },
{ "type": "Feature", "properties": { "ISO": "ZM-05", "NAME_1": "Northern" }, "geometry": { "type": "Polygon", "coordinates": [ [ [ 30.752106975000117, -8.194124042999917 ], [ 30.77825524900004, -8.289105325999927 ], [ 30.828278036000086, -8.388117369999932 ], [ 30.891891724000118, -8.479171244999876 ], [ 30.992350708000117, -8.575909525999947 ], [ 31.077823527000135, -8.616320494999925 ], [ 31.119836467000141, -8.616630553999912 ], [ 31.206756226000039, -8.580767109999968 ], [ 31.260913127000038, -8.623968607999913 ], [ 31.353310587000067, -8.587174987999916 ], [ 31.38597009300014, -8.632546894999848 ], [ 31.427517945000147, -8.633477070999987 ], [ 31.539035685000044, -8.703550312999937 ], [ 31.553350057000046, -8.809073587999904 ], [ 31.672670939000056, -8.913046568999945 ], [ 31.70977461800004, -8.91966115299995 ], [ 31.787599324000041, -8.892169290999973 ], [ 31.936634155000036, -8.932580260999956 ], [ 31.917823934000069, -8.973094583999881 ], [ 31.91772058100014, -9.022497252999898 ], [ 31.938081095000143, -9.061771341999957 ], [ 31.980559122000102, -9.071899921999915 ], [ 32.031718791000117, -9.045958353999964 ], [ 32.096417684000073, -9.069109394999955 ], [ 32.134141480000039, -9.064148457999906 ], [ 32.231448201573244, -9.133808288022067 ], [ 32.320920080097608, -9.361563857985686 ], [ 32.329302274180577, -9.462150183384267 ], [ 32.019161105700448, -9.420239214767946 ], [ 31.901810393934511, -9.437003602034622 ], [ 31.75093090673596, -9.520825539267207 ], [ 31.675491162686967, -9.529207733350233 ], [ 31.600051419537351, -9.504061152000588 ], [ 31.574904838187706, -9.571118701966554 ], [ 31.508067253401009, -9.540052992451649 ], [ 31.432407545072124, -9.545972120616852 ], [ 31.365349995106158, -9.504061152000588 ], [ 31.20608831382458, -9.613029670582819 ], [ 31.180941732474935, -9.671705026465816 ], [ 31.113884182508968, -9.755526963698401 ], [ 31.189323926557961, -9.830966707747393 ], [ 31.264763669707577, -9.9566996135963 ], [ 31.340203413756512, -10.183018843944524 ], [ 31.516229482304766, -10.275222975260135 ], [ 31.549758256838061, -10.30875174979343 ], [ 31.552826367742682, -10.558038018539719 ], [ 31.488373242730972, -10.570977472232585 ], [ 31.461192253719503, -10.550469659647092 ], [ 31.43702233161531, -10.577813409761063 ], [ 31.334971550196883, -10.612481378013172 ], [ 31.33895918102138, -10.637058201075149 ], [ 31.309662305770757, -10.6498348936654 ], [ 31.309662305770757, -10.70134856588362 ], [ 31.275482618128308, -10.728041274285374 ], [ 31.20728600394591, -10.708184503412099 ], [ 31.130625847504859, -10.750013930498483 ], [ 31.157481316109852, -10.788099867514859 ], [ 31.19214928436196, -10.783054294919793 ], [ 31.20419355558812, -10.810723565440185 ], [ 31.143565300298349, -10.826674086040271 ], [ 31.17090905041232, -10.8732235653153 ], [ 31.145274284680454, -10.916843357335097 ], [ 31.085378451654208, -10.961358330922224 ], [ 31.063405795441099, -10.961439711473531 ], [ 31.076670769540385, -10.941745700803438 ], [ 31.058848503455636, -10.911065362476506 ], [ 31.052744988190625, -10.944349867652249 ], [ 31.037608269505995, -10.948907159637713 ], [ 31.010752800001683, -10.932468357528705 ], [ 31.021657748006646, -10.919854425141637 ], [ 31.000987175217915, -10.920098565896126 ], [ 30.970632357297404, -10.999362888286669 ], [ 30.878916862723031, -11.02971770620718 ], [ 30.893809440653172, -11.059095961109733 ], [ 30.867279493353919, -11.042982680306466 ], [ 30.84856204480252, -11.056573174812172 ], [ 30.706309441027884, -11.290459893509308 ], [ 30.662038607295869, -11.330743097316088 ], [ 30.617686393911924, -11.330743097316088 ], [ 30.588145378806189, -11.385674737399199 ], [ 30.548757357466059, -11.399834893965192 ], [ 30.522064649064305, -11.461114190967123 ], [ 30.4843856130056, -11.491062107030643 ], [ 30.455846795193452, -11.501726575421117 ], [ 30.449180536352628, -11.475474948510055 ], [ 30.104705438405233, -11.242414239125821 ], [ 29.959908075197518, -11.246445000536369 ], [ 29.880016310204553, -11.361373385673232 ], [ 29.834696079160722, -11.395324801998015 ], [ 29.892573683328806, -11.019275404536302 ], [ 29.888852980280774, -10.965738621040543 ], [ 29.857020298348061, -10.899334405158697 ], [ 29.81283694796673, -10.863109225710218 ], [ 29.775733270274202, -10.799082126638837 ], [ 29.649126011156454, -10.737225437004327 ], [ 29.34935102662854, -10.895045260430436 ], [ 29.337827183177922, -10.908016045604029 ], [ 29.36423383971993, -10.958917331669511 ], [ 29.365629102800824, -10.998656507691692 ], [ 29.397100051326277, -11.042374770079562 ], [ 29.382062208603998, -11.119062595062701 ], [ 29.318293491051747, -11.09095061617802 ], [ 29.273748407263156, -11.0901754698221 ], [ 29.180162387584119, -10.999276624416666 ], [ 29.084302605680705, -10.957832126951132 ], [ 29.161403842713128, -10.8727727189858 ], [ 29.163884312311154, -10.742083021614178 ], [ 29.307596469901171, -10.640900567107508 ], [ 29.357257520718008, -10.630410251531885 ], [ 29.414515008161061, -10.526902357957454 ], [ 29.396014845708521, -10.480496921295867 ], [ 29.430017937977425, -10.433833103115205 ], [ 29.441335076752353, -10.380761406713532 ], [ 29.506809115748069, -10.329084975191449 ], [ 29.615743035612581, -10.286245211947005 ], [ 29.697701857254913, -10.222786553656533 ], [ 29.85350630087504, -10.229917900490705 ], [ 29.879396192580202, -10.199583834426448 ], [ 29.899239943068892, -10.114627781047261 ], [ 29.937583856010122, -10.072511488214616 ], [ 29.905286086084004, -9.991947930552556 ], [ 29.937893915271957, -9.891075535307721 ], [ 29.919445427864162, -9.838572279686957 ], [ 29.876295607156521, -9.819503675554188 ], [ 29.799762810904951, -9.70870940461532 ], [ 29.737544386963862, -9.708244316621915 ], [ 29.543292677614943, -9.650573418928161 ], [ 29.478438755344257, -9.601222425574463 ], [ 29.438079460798463, -9.546600436461006 ], [ 29.36903974838566, -9.536988620928128 ], [ 29.324649693328638, -9.433274020879367 ], [ 29.328060337114835, -9.395860283924947 ], [ 29.358807814329168, -9.356379489421897 ], [ 29.334106480129947, -9.216491387667418 ], [ 29.30852664588798, -9.217318209967402 ], [ 29.243517693986348, -9.157580254724962 ], [ 29.202228224353064, -9.156340019476318 ], [ 29.120114373079844, -9.107092379809501 ], [ 29.116858758025217, -9.052315361964418 ], [ 29.147296176877035, -9.036967461778943 ], [ 29.176131626173571, -8.948755791546546 ], [ 29.228428176219325, -8.92818857154532 ], [ 29.25049401208895, -8.901161798278395 ], [ 29.305581089195869, -8.721172783497195 ], [ 29.393069289016466, -8.550640556416568 ], [ 29.419010857565013, -8.520771580144299 ], [ 29.523914015119658, -8.472919202659057 ], [ 29.575844324000059, -8.372729113999895 ], [ 30.752106975000117, -8.194124042999917 ] ] ] } },
{ "type": "Feature", "properties": { "ISO": "ZM-09", "NAME_1": "Lusaka" }, "geometry": { "type": "Polygon", "coordinates": [ [ [ 30.010653524000077, -15.646227314999905 ], [ 29.837330770000051, -15.614808044999876 ], [ 29.672793009000145, -15.663280537999938 ], [ 29.587216838000131, -15.655735778999897 ], [ 29.508461955000087, -15.703588154999892 ], [ 29.406969442000047, -15.714233499999892 ], [ 29.186311076000067, -15.812832132999873 ], [ 29.086162150000064, -15.884559019999955 ], [ 29.042340536000069, -15.946260680999927 ], [ 28.946861598783755, -15.957235194648547 ], [ 28.887312046114005, -15.926417738487828 ], [ 28.808557162682916, -15.956700127708757 ], [ 28.753935173569403, -15.95189421994229 ], [ 28.676937290223748, -15.895308526067652 ], [ 28.583609652963105, -15.890295911826854 ], [ 28.506560092774066, -15.823736668112758 ], [ 28.410700310870652, -15.788751723013604 ], [ 28.291534457848911, -15.790663750931344 ], [ 28.236137323278854, -15.818620701084512 ], [ 28.178259719110713, -15.777796318545256 ], [ 28.040593702737169, -15.731752617988946 ], [ 28.007210728092616, -15.682970065416214 ], [ 27.970675490281621, -15.665916842888009 ], [ 27.929592726223291, -15.664263196489344 ], [ 27.856418897813853, -15.689791354787189 ], [ 27.8230359231693, -15.651705824264411 ], [ 27.756786736918343, -15.648863621259125 ], [ 27.799316440901009, -15.561013686232627 ], [ 27.905614862435925, -15.531661472099245 ], [ 27.934760370094978, -15.495539645438271 ], [ 27.891765578118907, -15.374255058923836 ], [ 27.787224154870842, -15.343249200190428 ], [ 27.767018670075572, -15.320563245797189 ], [ 27.827996859667337, -15.266354668732959 ], [ 27.862465040828965, -15.260618584979738 ], [ 28.033462355003678, -15.287283623940084 ], [ 28.259856804647825, -15.35255095826011 ], [ 28.290759312392311, -15.341698906579268 ], [ 28.375612012983993, -15.162536715896749 ], [ 28.404344110392344, -15.145690198943555 ], [ 28.569140251921056, -15.188271579769605 ], [ 28.74385827004312, -15.175714206645353 ], [ 28.823129917411734, -15.149359226047466 ], [ 28.94679161983737, -15.041510511800709 ], [ 29.001103549689049, -15.018514499944217 ], [ 29.228118116957489, -14.956709487153091 ], [ 29.311627232210981, -14.977431735885887 ], [ 29.459783563260828, -14.963117363575464 ], [ 29.530425246128175, -14.810671888696731 ], [ 29.576313917952916, -14.808914889510561 ], [ 29.668969760745824, -14.749848727836536 ], [ 29.781314325295853, -14.719359633040654 ], [ 29.812526889604271, -14.696932061065752 ], [ 29.877225783143331, -14.697190443484203 ], [ 29.904200881365568, -14.654402357982462 ], [ 29.971121860285621, -14.64913136222259 ], [ 30.000112339213047, -14.66783823025014 ], [ 30.051168654010155, -14.671197198092216 ], [ 30.062020704791678, -14.698430677833528 ], [ 30.206508009636934, -14.830670667916991 ], [ 30.225834188000135, -15.10631195099991 ], [ 30.287949260000119, -15.278911233999906 ], [ 30.334871460000045, -15.304749450999921 ], [ 30.364947143000109, -15.354152119999938 ], [ 30.371768432000067, -15.439831644999927 ], [ 30.392852417000086, -15.480759378999949 ], [ 30.367427613000075, -15.561271259999927 ], [ 30.412696167000092, -15.627933857999935 ], [ 30.356678915000089, -15.651498310999941 ], [ 30.254876343000035, -15.628864033999974 ], [ 30.207230672000094, -15.653151956999892 ], [ 30.130129435000129, -15.623696390999982 ], [ 30.010653524000077, -15.646227314999905 ] ] ] } },
{ "type": "Feature", "properties": { "ISO": "ZM-07", "NAME_1": "Southern" }, "geometry": { "type": "Polygon", "coordinates": [ [ [ 28.946861598783755, -15.957235194648547 ], [ 28.898886760000096, -15.995456643999901 ], [ 28.857235555000074, -16.060465595999958 ], [ 28.87098148600009, -16.087233988999927 ], [ 28.847106975000116, -16.202679138 ], [ 28.864160197000047, -16.231204528999939 ], [ 28.836771688000113, -16.306342060999953 ], [ 28.857235555000074, -16.38819753 ], [ 28.808866414000107, -16.486279397999866 ], [ 28.732850382000066, -16.558109638999966 ], [ 28.643295126000055, -16.568754984999956 ], [ 28.28011316000007, -16.706524352999892 ], [ 28.113921753000113, -16.827550557999885 ], [ 27.816885620000107, -16.959635517999871 ], [ 27.641185751000052, -17.198483987999865 ], [ 27.577313680000088, -17.363125101999898 ], [ 27.157080932000042, -17.769301859999956 ], [ 27.149019409000118, -17.842475686999933 ], [ 27.021275269000114, -17.958540953999972 ], [ 26.959160197000131, -17.964742126999866 ], [ 26.912031291000034, -17.992027281999881 ], [ 26.888260132000084, -17.984585875999954 ], [ 26.753591350000079, -18.032955017 ], [ 26.700002889000132, -18.069231871999946 ], [ 26.628844442000087, -18.0491814169999 ], [ 26.570243367000074, -18.002879332999925 ], [ 26.40859948700006, -17.939007262999965 ], [ 26.318269084000121, -17.934356383999912 ], [ 26.239204142000119, -17.910171813999938 ], [ 26.211918986000114, -17.88278330499989 ], [ 26.095233602000121, -17.938077086999911 ], [ 26.095233602000121, -17.958540953999972 ], [ 25.9785482180001, -17.998951924999957 ], [ 25.924494670000115, -17.998951924999957 ], [ 25.853491252000111, -17.959987894999969 ], [ 25.847496785000089, -17.929395445999958 ], [ 25.863619832000069, -17.92381439199994 ], [ 25.849667196000098, -17.906657815999978 ], [ 25.681408732000079, -17.811469827999915 ], [ 25.516457561000067, -17.862319437999929 ], [ 25.335538371000098, -17.841235452999911 ], [ 25.242417440000082, -17.770335387999936 ], [ 25.190741007000071, -17.755349222999968 ], [ 25.13854781100008, -17.686102803999944 ], [ 25.122631469000055, -17.697885029999952 ], [ 25.088525024000091, -17.64269460099996 ], [ 25.033851359000039, -17.608484801999865 ], [ 25.036951945000084, -17.581199645999945 ], [ 24.99850468000011, -17.588020934999903 ], [ 24.969987329651531, -17.559962479085129 ], [ 24.986051467001573, -17.469941095005538 ], [ 25.025273879086228, -17.419918308083481 ], [ 25.025273879086228, -17.31656544413994 ], [ 25.098396029752962, -17.221894219742467 ], [ 25.084236687972748, -17.175178724718364 ], [ 25.09141971165036, -17.138333428544911 ], [ 25.155343458833556, -17.079473971546577 ], [ 25.159219190613157, -17.013896579763355 ], [ 25.237870721256741, -16.975862725184641 ], [ 25.279005161259192, -16.905479424735688 ], [ 25.241746453935662, -16.790137627549484 ], [ 25.251358270367859, -16.705698337208503 ], [ 25.2124459157464, -16.685234469994782 ], [ 25.100876499350932, -16.670403333746833 ], [ 25.075089958634692, -16.609063408949169 ], [ 25.000779249562697, -16.551030776049458 ], [ 24.997833692870586, -16.532168877491699 ], [ 25.041448601571688, -16.51196339269643 ], [ 25.149917433442795, -16.373935642016249 ], [ 25.289857212040658, -16.29264861394239 ], [ 25.3557963399291, -16.164181002851024 ], [ 25.428143345139233, -16.092919203258646 ], [ 25.349595168182475, -16.044084974741793 ], [ 25.33440229672857, -16.008996676855134 ], [ 25.358586866990322, -15.96967091198303 ], [ 25.350370313639019, -15.927502944105584 ], [ 25.381582878846757, -15.876239922834202 ], [ 25.396155632676312, -15.7509245740099 ], [ 25.360757277326456, -15.723484388693578 ], [ 25.320139601261587, -15.760071302448637 ], [ 25.278385043634842, -15.748702487729645 ], [ 25.251823358361264, -15.698472996131898 ], [ 25.277764926909811, -15.668293958799154 ], [ 25.277764926909811, -15.644781183005193 ], [ 25.223297967427243, -15.59382822009627 ], [ 25.26892825683359, -15.538224379051883 ], [ 25.244692009728453, -15.484894301131078 ], [ 25.296678501411691, -15.468047784177884 ], [ 25.318744338180636, -15.381644789075779 ], [ 25.343238966804847, -15.352705986991737 ], [ 25.324790480296429, -15.298859145133463 ], [ 26.746305779887791, -15.336066175613496 ], [ 26.843922560078056, -15.351620782273301 ], [ 26.987272984260812, -15.435181572571537 ], [ 26.958592563695845, -15.467686048971984 ], [ 27.202195264599766, -15.482207126857418 ], [ 27.227671746953547, -15.497089939049431 ], [ 27.279503208106576, -15.727050063009983 ], [ 27.300897251307106, -15.744413343900703 ], [ 27.409831170272298, -15.568093357122734 ], [ 27.45918216272662, -15.579307143110157 ], [ 27.504502393770451, -15.540704847750533 ], [ 27.534112990322228, -15.487374769829785 ], [ 27.561604851582615, -15.478951510903528 ], [ 27.569046257678622, -15.499725436479707 ], [ 27.626303745121731, -15.518949070243423 ], [ 27.65979007255379, -15.557654717491232 ], [ 27.66537112757544, -15.600287774261403 ], [ 27.651108433007778, -15.621475111886923 ], [ 27.691932813748338, -15.669327487573526 ], [ 27.799988233570105, -15.64783009158549 ], [ 27.842156203246191, -15.663126315826844 ], [ 27.856418897813853, -15.689791354787189 ], [ 27.929592726223291, -15.664263196489344 ], [ 27.970675490281621, -15.665916842888009 ], [ 28.007210728092616, -15.682970065416214 ], [ 28.040593702737169, -15.731752617988946 ], [ 28.178259719110713, -15.777796318545256 ], [ 28.236137323278854, -15.818620701084512 ], [ 28.291534457848911, -15.790663750931344 ], [ 28.391114942800357, -15.784359225497838 ], [ 28.506560092774066, -15.823736668112758 ], [ 28.583609652963105, -15.890295911826854 ], [ 28.676937290223748, -15.895308526067652 ], [ 28.753935173569403, -15.95189421994229 ], [ 28.808557162682916, -15.956700127708757 ], [ 28.887312046114005, -15.926417738487828 ], [ 28.946861598783755, -15.957235194648547 ] ] ] } },
{ "type": "Feature", "properties": { "ISO": "ZM-01", "NAME_1": "Western" }, "geometry": { "type": "Polygon", "coordinates": [ [ [ 22.019875122000116, -16.253115335999908 ], [ 22.045196574000101, -16.252288512999968 ], [ 21.981531210000099, -16.144284769999928 ], [ 21.980353099615854, -13.694822054793974 ], [ 22.085711704431617, -13.758539726826939 ], [ 22.119198031863675, -13.76164031314994 ], [ 22.168549025217317, -13.74257170991649 ], [ 22.22162072071967, -13.683350517712256 ], [ 22.250817905222107, -13.686554456822705 ], [ 22.499381545322024, -13.866130058655301 ], [ 22.516331414163403, -13.893621920815008 ], [ 22.610020785730683, -13.927676689927296 ], [ 22.632293328973958, -13.960956312683663 ], [ 22.710273065149806, -13.990360202761167 ], [ 22.728721550758962, -13.977699476849409 ], [ 22.747996859567422, -13.905300794795835 ], [ 22.805409376641421, -13.899668063830063 ], [ 22.852900018021387, -13.869540704240137 ], [ 22.964779493678691, -13.935583184016707 ], [ 23.000746290708719, -13.992840670560497 ], [ 23.082240025256965, -13.980283297436245 ], [ 23.125234816333716, -14.059038180867333 ], [ 23.226985710721976, -14.076349785813989 ], [ 23.182595655664954, -14.154846286826682 ], [ 23.22357506693578, -14.140583590460324 ], [ 23.22357506693578, -14.168488864669371 ], [ 23.264554478206605, -14.168488864669371 ], [ 23.32320722783129, -14.133710626044547 ], [ 23.367597283787575, -14.133710626044547 ], [ 23.436740349887202, -14.085651543883671 ], [ 23.539524773949154, -14.059244886442343 ], [ 23.667682325778685, -13.994804376220998 ], [ 23.733259719360547, -14.012322685843287 ], [ 23.833718702556041, -13.956202080861374 ], [ 23.833098585831067, -13.975684096144107 ], [ 23.855681187436858, -13.990876966698636 ], [ 24.001460401676184, -14.000282077555823 ], [ 24.04802086796866, -13.96633066213036 ], [ 24.071585320606061, -13.976459241600708 ], [ 24.08791507272241, -13.946228530122596 ], [ 24.12667239771298, -13.955581964136343 ], [ 24.222428826828889, -13.905869235576745 ], [ 24.299995150955453, -13.938167005502919 ], [ 24.290538364154145, -13.912690524947777 ], [ 24.30531782355871, -13.892226657734057 ], [ 24.334928420110487, -13.94224944375685 ], [ 24.381488884604323, -13.958217461566619 ], [ 24.404123163053498, -13.946383558854166 ], [ 24.416422152860036, -13.963333428594865 ], [ 24.470682406767651, -13.952481377813342 ], [ 24.465411411007778, -13.932379245805578 ], [ 24.488562453394479, -13.917909844763528 ], [ 24.553881462759307, -13.982918795765841 ], [ 24.586954379940664, -13.988499850787491 ], [ 24.590985142250474, -13.96343678048305 ], [ 24.615789829237201, -13.96555551487512 ], [ 24.619510532285233, -14.000127047924934 ], [ 24.635633578826571, -13.969792982759941 ], [ 24.661265089911979, -13.958527519929135 ], [ 24.713406610326786, -14.012787773836692 ], [ 24.745807733040408, -14.120326429720933 ], [ 24.878202751855497, -14.156241549907634 ], [ 25.008220655658704, -14.217684827492803 ], [ 25.063772820759027, -14.214274183706607 ], [ 25.081756219274098, -14.232050876646667 ], [ 25.087492303027318, -14.290393568808156 ], [ 25.059121941724186, -14.350183200894037 ], [ 25.051060418003885, -14.421806735692314 ], [ 24.963985630232628, -14.480562839003824 ], [ 24.962900424614872, -14.564278659832269 ], [ 25.010236037263269, -14.623758232656314 ], [ 25.040208368121682, -14.635953870574667 ], [ 25.151622755785525, -14.628512464478661 ], [ 25.315282016651736, -14.577352796894047 ], [ 25.45124270978323, -14.60365610064855 ], [ 25.548394402879353, -14.585207615039394 ], [ 25.523072951055838, -14.602829277449189 ], [ 25.478682895998816, -14.683496188798074 ], [ 25.480129835923151, -14.784471937729734 ], [ 25.450002476333225, -14.806641127286184 ], [ 25.425146111603738, -14.86632740568524 ], [ 25.425662876440583, -14.913611341490196 ], [ 25.456513706442365, -14.97055876967147 ], [ 25.45604861844896, -15.019599704662653 ], [ 25.414139032090645, -15.080577895153738 ], [ 25.41057335777424, -15.131427503476516 ], [ 25.367888625060004, -15.137525322435692 ], [ 25.324170362672078, -15.178659762438087 ], [ 25.324790480296429, -15.298859145133463 ], [ 25.345254346610773, -15.34562631610163 ], [ 25.318744338180636, -15.381644789075779 ], [ 25.296678501411691, -15.468047784177884 ], [ 25.244692009728453, -15.484894301131078 ], [ 25.26892825683359, -15.538224379051883 ], [ 25.223297967427243, -15.59382822009627 ], [ 25.277764926909811, -15.644781183005193 ], [ 25.277764926909811, -15.668293958799154 ], [ 25.251823358361264, -15.698472996131898 ], [ 25.278385043634842, -15.748702487729645 ], [ 25.320139601261587, -15.760071302448637 ], [ 25.360757277326456, -15.723484388693578 ], [ 25.396155632676312, -15.7509245740099 ], [ 25.381582878846757, -15.876239922834202 ], [ 25.350370313639019, -15.927502944105584 ], [ 25.358586866990322, -15.96967091198303 ], [ 25.33440229672857, -16.008996676855134 ], [ 25.349595168182475, -16.044084974741793 ], [ 25.428143345139233, -16.092919203258646 ], [ 25.3557963399291, -16.164181002851024 ], [ 25.289857212040658, -16.29264861394239 ], [ 25.149917433442795, -16.373935642016249 ], [ 25.041448601571688, -16.51196339269643 ], [ 24.996903516883776, -16.536974786157487 ], [ 25.075089958634692, -16.609063408949169 ], [ 25.100876499350932, -16.670403333746833 ], [ 25.2124459157464, -16.685234469994782 ], [ 25.251358270367859, -16.705698337208503 ], [ 25.241746453935662, -16.790137627549484 ], [ 25.279005161259192, -16.905479424735688 ], [ 25.237870721256741, -16.975862725184641 ], [ 25.159219190613157, -17.013896579763355 ], [ 25.155343458833556, -17.079473971546577 ], [ 25.09141971165036, -17.138333428544911 ], [ 25.084236687972748, -17.175178724718364 ], [ 25.098396029752962, -17.221894219742467 ], [ 25.025273879086228, -17.31656544413994 ], [ 25.025273879086228, -17.419918308083481 ], [ 24.986051467001573, -17.469941095005538 ], [ 24.969987329651531, -17.559962479085129 ], [ 24.937629842000092, -17.560735778999899 ], [ 24.898252400000075, -17.531073506999931 ], [ 24.684415324000071, -17.492419534999925 ], [ 24.629741659000047, -17.495520120999871 ], [ 24.571243937000133, -17.533450622999879 ], [ 24.388929484000101, -17.471335549999907 ], [ 24.321336711000129, -17.488698831999912 ], [ 24.238757771000081, -17.478156839999954 ], [ 23.381652466000105, -17.641144306999934 ], [ 23.382272583000088, -17.601043395999938 ], [ 23.320157512000094, -17.546369730999885 ], [ 23.189726196000066, -17.536551207999921 ], [ 23.176186971000078, -17.478156839999954 ], [ 23.097638794000147, -17.432164814999865 ], [ 22.998626750000142, -17.293775328999956 ], [ 22.87615360500007, -17.248093362999938 ], [ 22.765152628000095, -17.169648538999922 ], [ 22.710478963000043, -17.055443623999906 ], [ 22.651671183000076, -16.998702900999973 ], [ 22.573433064000113, -16.971004332999954 ], [ 22.554519491000065, -16.924185485999928 ], [ 22.508527466000089, -16.906202087999944 ], [ 22.416646769000124, -16.75448008199993 ], [ 22.377992798, -16.73484303799998 ], [ 22.333654419000055, -16.673658141999866 ], [ 22.290762980000096, -16.656398213999879 ], [ 22.237742961000095, -16.665493265999942 ], [ 22.151650025, -16.597693786999926 ], [ 22.138110799000032, -16.552631937999891 ], [ 22.104004354000068, -16.536715595999866 ], [ 22.107311646000056, -16.512324319999934 ], [ 22.079923136000019, -16.45775400799991 ], [ 22.105554646000087, -16.379412536999922 ], [ 22.055841919000073, -16.364633076999908 ], [ 22.019875122000116, -16.253115335999908 ] ] ] } },
{ "type": "Feature", "properties": { "ISO": "ZM-06", "NAME_1": "North-Western" }, "geometry": { "type": "Polygon", "coordinates": [ [ [ 21.980353099615854, -13.694822054793974 ], [ 21.979877563000059, -13.001479186999916 ], [ 24.000632772000102, -13.001479186999916 ], [ 23.971797322000072, -12.933369649999904 ], [ 23.895109497000107, -12.849757181999891 ], [ 23.865653931000111, -12.78970916699997 ], [ 23.928699178000045, -12.561609394999891 ], [ 24.030811808000095, -12.385082702999924 ], [ 24.016859171000107, -12.278939310999888 ], [ 23.959601685000052, -12.19667043099993 ], [ 23.954330689000102, -12.151918639999877 ], [ 23.967043091000079, -11.882891132999887 ], [ 23.990194132000056, -11.82408335399991 ], [ 23.954640747000099, -11.636911315999939 ], [ 24.009727824000066, -11.523429869999916 ], [ 24.009934530000123, -11.459454446999928 ], [ 24.061714315000103, -11.406951191999966 ], [ 24.011174764000145, -11.272902525999939 ], [ 24.01530887800007, -11.130482278999949 ], [ 23.990090779000127, -11.113532408999944 ], [ 24.003733358000119, -10.982480977999927 ], [ 23.96745650200009, -10.872306822999903 ], [ 24.048381796000058, -10.882332051999924 ], [ 24.114217570000051, -10.919229023999947 ], [ 24.124242797000079, -11.043252461999941 ], [ 24.181293579000084, -11.03446746799996 ], [ 24.293844848000077, -11.050280456999957 ], [ 24.370532674000088, -11.100199889999914 ], [ 24.381798136000072, -11.120560403999946 ], [ 24.361747680000121, -11.164692077999945 ], [ 24.396577596000071, -11.21740203799996 ], [ 24.39223677600009, -11.279103698999933 ], [ 24.339940226000095, -11.358065286999889 ], [ 24.285473266000082, -11.381216328999884 ], [ 24.31007124900006, -11.40664113299988 ], [ 24.370222615000102, -11.410155130999939 ], [ 24.446497030000046, -11.463588561999956 ], [ 24.564732707000076, -11.444674987999917 ], [ 24.593258097000103, -11.399613138999968 ], [ 24.635219360000121, -11.385867207999937 ], [ 24.674080037000067, -11.341632180999923 ], [ 24.712527303000115, -11.326025899999877 ], [ 24.826732218000046, -11.317550963999878 ], [ 24.942900838000099, -11.268561706999961 ], [ 25.184023071000126, -11.246650898999917 ], [ 25.310320272000041, -11.194767760999909 ], [ 25.32251591000005, -11.205413105999909 ], [ 25.324893025000108, -11.283651223999868 ], [ 25.284688761000069, -11.307319030999892 ], [ 25.306496216000113, -11.333053893999889 ], [ 25.277970825000068, -11.37181121799992 ], [ 25.279004354000051, -11.396305846999965 ], [ 25.316728149000085, -11.472993671999916 ], [ 25.300398397000066, -11.535005390999871 ], [ 25.344943482000048, -11.642182311999889 ], [ 25.386387980000109, -11.649830423999958 ], [ 25.481162557000061, -11.715252786999926 ], [ 25.474134562000046, -11.756180520999948 ], [ 25.495580281000088, -11.776541035999884 ], [ 25.561002645000144, -11.75328664099996 ], [ 25.575678752000044, -11.72734507199992 ], [ 25.621464071000077, -11.728895365999932 ], [ 25.725643758000103, -11.800518899999901 ], [ 25.850700724000063, -11.793800963999971 ], [ 25.981132039000101, -11.903044941999951 ], [ 26.166650431000107, -11.902424824999898 ], [ 26.229592326000017, -11.933120625999933 ], [ 26.298011922000114, -11.941182148999914 ], [ 26.339146362000093, -11.918961282999888 ], [ 26.414593953000093, -11.911829934999943 ], [ 26.489111369000028, -11.960819192999864 ], [ 26.643520548000083, -11.985520527999967 ], [ 26.697057333000117, -12.017456562999939 ], [ 26.717417847000064, -12.013012389999929 ], [ 26.759379109000065, -11.968674010999891 ], [ 26.874204143000071, -11.964333190999909 ], [ 26.947688029000119, -11.909142760999913 ], [ 26.967325073000069, -11.870385436999882 ], [ 26.981071004000086, -11.749049173999921 ], [ 27.021481975000086, -11.69788950599991 ], [ 27.010268189000044, -11.609832864999888 ], [ 27.023755738000091, -11.595570169999917 ], [ 27.18012862100008, -11.569628600999877 ], [ 27.207620483000142, -11.639391783999926 ], [ 27.209997599000104, -11.72197072299987 ], [ 27.234182169000064, -11.809097187999924 ], [ 27.420734090000053, -11.921958516999894 ], [ 27.467552938000068, -12.001643574999946 ], [ 27.520469605000073, -12.179617206999907 ], [ 27.589820184154178, -12.242973320462397 ], [ 27.510548536785507, -12.300695895898855 ], [ 27.467398716077867, -12.288913669130523 ], [ 27.466003452097596, -12.270413506677983 ], [ 27.413396843689384, -12.247830905971512 ], [ 27.276505974571023, -12.345706068580228 ], [ 27.051506788907147, -12.33418222423029 ], [ 27.066131218680766, -12.387408948464213 ], [ 27.054917432693344, -12.46270151126572 ], [ 27.07682824073072, -12.515979913242404 ], [ 27.009183791398812, -12.538045750011349 ], [ 26.946655308195886, -12.618092542836564 ], [ 26.886245557586392, -12.637574558119354 ], [ 26.867487012715458, -12.663102715517937 ], [ 26.845007764796492, -12.738757012626024 ], [ 26.906916131274443, -12.819682305493984 ], [ 26.883144972162711, -12.892339369066633 ], [ 27.009648879392273, -12.9556946745696 ], [ 27.043910353180252, -12.996932468258819 ], [ 27.094191521621383, -13.00080820093774 ], [ 27.06101525165252, -13.130257663960037 ], [ 26.965103793805042, -13.211027927197108 ], [ 26.973630404619485, -13.334844659253633 ], [ 26.906140984918522, -13.416751804052524 ], [ 26.859115430632585, -13.439282728814874 ], [ 26.838186476324779, -13.508942558852027 ], [ 26.793331333274409, -13.57875741852007 ], [ 26.799067417027629, -13.676064141247139 ], [ 26.868572219232533, -13.7261902809567 ], [ 26.906296013650092, -13.790269056871466 ], [ 26.954561802285355, -13.821740003598279 ], [ 26.912187127034258, -13.910003349774797 ], [ 26.907536247999417, -14.009583835625506 ], [ 26.85772016755169, -14.037747490454308 ], [ 26.913427362282903, -14.076091404294857 ], [ 26.979056430909566, -14.169057305450281 ], [ 26.97890140127862, -14.209468275940196 ], [ 26.952236362318274, -14.253083183741921 ], [ 26.955957066265569, -14.373954360005712 ], [ 26.927690056850622, -14.409921156136477 ], [ 26.804648472049337, -14.414933769477898 ], [ 26.736073845831299, -14.449040215433627 ], [ 26.555464715224389, -14.450693861832235 ], [ 26.492161085665543, -14.531619154700252 ], [ 26.387412956842468, -14.62696217176682 ], [ 26.369842970376737, -14.699205824189448 ], [ 26.334961378964465, -14.713985283593956 ], [ 26.197915480215215, -14.654505710769968 ], [ 26.17373090995352, -14.621071059281974 ], [ 25.620999789608561, -14.555441989756048 ], [ 25.483023715771822, -14.601330661580789 ], [ 25.315282016651736, -14.577352796894047 ], [ 25.151622755785525, -14.628512464478661 ], [ 25.025738967079633, -14.632284845269396 ], [ 24.966931186924739, -14.573942153107907 ], [ 24.963520542239223, -14.483250014176804 ], [ 25.051060418003885, -14.421806735692314 ], [ 25.059121941724186, -14.350183200894037 ], [ 25.087492303027318, -14.290393568808156 ], [ 25.081756219274098, -14.232050876646667 ], [ 25.063772820759027, -14.214274183706607 ], [ 25.008220655658704, -14.217684827492803 ], [ 24.878202751855497, -14.156241549907634 ], [ 24.745807733040408, -14.120326429720933 ], [ 24.713406610326786, -14.012787773836692 ], [ 24.664675733698118, -13.960181165428423 ], [ 24.635633578826571, -13.969792982759941 ], [ 24.617340121949042, -13.999765312719035 ], [ 24.615789829237201, -13.96555551487512 ], [ 24.590985142250474, -13.96343678048305 ], [ 24.586954379940664, -13.988499850787491 ], [ 24.553881462759307, -13.982918795765841 ], [ 24.488562453394479, -13.917909844763528 ], [ 24.465411411007778, -13.932379245805578 ], [ 24.470682406767651, -13.952481377813342 ], [ 24.416422152860036, -13.963333428594865 ], [ 24.404123163053498, -13.946383558854166 ], [ 24.381488884604323, -13.958217461566619 ], [ 24.334928420110487, -13.94224944375685 ], [ 24.322060987724399, -13.905145766064265 ], [ 24.301080356573152, -13.892433364208387 ], [ 24.290538364154145, -13.912690524947777 ], [ 24.299995150955453, -13.938167005502919 ], [ 24.222428826828889, -13.905869235576745 ], [ 24.12667239771298, -13.955581964136343 ], [ 24.08791507272241, -13.946228530122596 ], [ 24.071585320606061, -13.976459241600708 ], [ 24.04802086796866, -13.96633066213036 ], [ 23.99231367413671, -14.001522311905148 ], [ 23.947768589448799, -13.987156263650661 ], [ 23.910716586801016, -14.000282077555823 ], [ 23.855681187436858, -13.990876966698636 ], [ 23.833098585831067, -13.975684096144107 ], [ 23.833718702556041, -13.956202080861374 ], [ 23.733259719360547, -14.012322685843287 ], [ 23.667682325778685, -13.994804376220998 ], [ 23.539524773949154, -14.059244886442343 ], [ 23.436740349887202, -14.085651543883671 ], [ 23.367597283787575, -14.133710626044547 ], [ 23.32320722783129, -14.133710626044547 ], [ 23.264554478206605, -14.168488864669371 ], [ 23.22357506693578, -14.168488864669371 ], [ 23.22357506693578, -14.140583590460324 ], [ 23.182595655664954, -14.154846286826682 ], [ 23.226985710721976, -14.076349785813989 ], [ 23.125234816333716, -14.059038180867333 ], [ 23.082240025256965, -13.980283297436245 ], [ 23.000746290708719, -13.992840670560497 ], [ 22.964779493678691, -13.935583184016707 ], [ 22.852900018021387, -13.869540704240137 ], [ 22.805409376641421, -13.899668063830063 ], [ 22.747996859567422, -13.905300794795835 ], [ 22.728721550758962, -13.977699476849409 ], [ 22.710273065149806, -13.990360202761167 ], [ 22.632293328973958, -13.960956312683663 ], [ 22.610020785730683, -13.927676689927296 ], [ 22.516331414163403, -13.893621920815008 ], [ 22.499381545322024, -13.866130058655301 ], [ 22.250817905222107, -13.686554456822705 ], [ 22.22162072071967, -13.683350517712256 ], [ 22.168549025217317, -13.74257170991649 ], [ 22.119198031863675, -13.76164031314994 ], [ 22.085711704431617, -13.758539726826939 ], [ 21.980353099615854, -13.694822054793974 ] ] ] } },
{ "type": "Feature", "properties": { "ISO": "ZM-04", "NAME_1": "Luapula" }, "geometry": { "type": "Polygon", "coordinates": [ [ [ 28.586296021000067, -9.544015807999898 ], [ 28.562783244000059, -9.484897969999935 ], [ 28.519685099000043, -9.44562388099996 ], [ 28.515964396000129, -9.378341165999885 ], [ 28.495397176000068, -9.353226419999956 ], [ 28.368531535000074, -9.308577981999917 ], [ 28.35246016500011, -9.271991067999892 ], [ 28.372303914000099, -9.235094094999866 ], [ 28.599060099000013, -9.09639455099996 ], [ 28.765406534000107, -8.93402720099995 ], [ 28.893098999000102, -8.765768736999931 ], [ 28.930461059000066, -8.679882506999903 ], [ 28.935473673000018, -8.5907923379999 ], [ 28.889171590000046, -8.483098652999928 ], [ 29.575844324000059, -8.372729113999895 ], [ 29.523914015119658, -8.472919202659057 ], [ 29.419010857565013, -8.520771580144299 ], [ 29.393069289016466, -8.550640556416568 ], [ 29.305581089195869, -8.721172783497195 ], [ 29.25049401208895, -8.901161798278395 ], [ 29.228428176219325, -8.92818857154532 ], [ 29.176131626173571, -8.948755791546546 ], [ 29.147296176877035, -9.036967461778943 ], [ 29.119029168361408, -9.047044366204545 ], [ 29.109882439922671, -9.091021010111547 ], [ 29.193391554276786, -9.152464287696716 ], [ 29.243517693986348, -9.157580254724962 ], [ 29.30852664588798, -9.217318209967402 ], [ 29.334106480129947, -9.216491387667418 ], [ 29.358807814329168, -9.356379489421897 ], [ 29.328060337114835, -9.395860283924947 ], [ 29.324649693328638, -9.433274020879367 ], [ 29.36903974838566, -9.536988620928128 ], [ 29.438079460798463, -9.546600436461006 ], [ 29.478438755344257, -9.601222425574463 ], [ 29.543292677614943, -9.650573418928161 ], [ 29.737544386963862, -9.708244316621915 ], [ 29.799762810904951, -9.70870940461532 ], [ 29.876295607156521, -9.819503675554188 ], [ 29.919445427864162, -9.838572279686957 ], [ 29.937893915271957, -9.891075535307721 ], [ 29.905286086084004, -9.991947930552556 ], [ 29.937583856010122, -10.072511488214616 ], [ 29.899239943068892, -10.114627781047261 ], [ 29.879396192580202, -10.199583834426448 ], [ 29.85350630087504, -10.229917900490705 ], [ 29.697701857254913, -10.222786553656533 ], [ 29.615743035612581, -10.286245211947005 ], [ 29.506809115748069, -10.329084975191449 ], [ 29.441335076752353, -10.380761406713532 ], [ 29.430017937977425, -10.433833103115205 ], [ 29.396014845708521, -10.480496921295867 ], [ 29.414515008161061, -10.526902357957454 ], [ 29.357257520718008, -10.630410251531885 ], [ 29.307596469901171, -10.640900567107508 ], [ 29.163884312311154, -10.742083021614178 ], [ 29.161403842713128, -10.8727727189858 ], [ 29.084302605680705, -10.957832126951132 ], [ 29.180162387584119, -10.999276624416666 ], [ 29.273748407263156, -11.0901754698221 ], [ 29.318293491051747, -11.09095061617802 ], [ 29.382062208603998, -11.119062595062701 ], [ 29.397100051326277, -11.042374770079562 ], [ 29.365629102800824, -10.998656507691692 ], [ 29.36423383971993, -10.958917331669511 ], [ 29.337827183177922, -10.908016045604029 ], [ 29.654862094909731, -10.738258965778641 ], [ 29.780694206772182, -10.803577976042789 ], [ 29.885752393957773, -10.949460543968939 ], [ 29.892573683328806, -11.019275404536302 ], [ 29.834696079160722, -11.395324801998015 ], [ 29.880016310204553, -11.361373385673232 ], [ 29.959908075197518, -11.246445000536369 ], [ 30.104705438405233, -11.242414239125821 ], [ 30.449180536352628, -11.475474948510055 ], [ 30.456931999911831, -11.496455579661301 ], [ 30.447630242741468, -11.589989922496954 ], [ 30.261440057112907, -11.818864840839751 ], [ 29.78953087684846, -11.89901498825111 ], [ 29.773252800676175, -11.924801528068087 ], [ 29.778162062129468, -12.020299573866225 ], [ 29.816557651014762, -12.085463556298066 ], [ 29.813508742434522, -12.14008554361294 ], [ 29.648918498000057, -12.21279347699992 ], [ 29.576726522000058, -12.188092141999903 ], [ 29.474252157000137, -12.24266245499993 ], [ 29.446553589000075, -12.335059915999935 ], [ 29.480453328000124, -12.380535175999896 ], [ 29.523448120000069, -12.392524108999865 ], [ 29.524688355000137, -12.429214374999916 ], [ 29.499676961000034, -12.453088886999907 ], [ 29.364388062000046, -12.409267272999898 ], [ 29.304856811000093, -12.404823099999902 ], [ 29.254989054000134, -12.366169127999896 ], [ 29.173391967000072, -12.36761606799989 ], [ 29.111070191000124, -12.393454284999905 ], [ 29.100218140000095, -12.374023945999923 ], [ 29.030351603000099, -12.376194355999914 ], [ 28.944672079000043, -12.20607554099989 ], [ 28.859509318000079, -12.141790058999931 ], [ 28.821475463000041, -12.075747578999881 ], [ 28.759877156000101, -12.035233255999884 ], [ 28.751092163000123, -11.992238463999897 ], [ 28.686031535000041, -11.984073587999973 ], [ 28.623864787000059, -11.947796731999915 ], [ 28.592652222000083, -11.90046112099995 ], [ 28.569191121000102, -11.913690286999952 ], [ 28.540562377000128, -11.87203908199993 ], [ 28.507851196000047, -11.87276255299993 ], [ 28.488885946000096, -11.808683776999914 ], [ 28.452505737000109, -11.78077850399994 ], [ 28.405480183000122, -11.60518198599992 ], [ 28.360314982000148, -11.533558451999866 ], [ 28.357007690000046, -11.446948750999937 ], [ 28.439586629000075, -11.348246764999914 ], [ 28.436175985000148, -11.28912892699995 ], [ 28.473693074000067, -11.225670266999913 ], [ 28.48733565200007, -11.153426614999972 ], [ 28.476793661000102, -11.077979023999973 ], [ 28.547176961000019, -10.913751322999957 ], [ 28.554411662000092, -10.834996438999951 ], [ 28.623244670000076, -10.716864114999865 ], [ 28.665877726000076, -10.697433776999972 ], [ 28.699622436000141, -10.643173522999945 ], [ 28.665515991000063, -10.608963724999853 ], [ 28.672337280000136, -10.564315286999914 ], [ 28.63492354300007, -10.519460143999922 ], [ 28.646085653000085, -10.438431497999915 ], [ 28.620867554000142, -10.373319192999915 ], [ 28.623864787000059, -10.276374205999971 ], [ 28.569914592000089, -10.219633483999957 ], [ 28.628515665000123, -10.102741393999906 ], [ 28.627947224000081, -9.929418639999909 ], [ 28.668461548000067, -9.821621601999922 ], [ 28.698485555000047, -9.791959329999955 ], [ 28.63125451600007, -9.715581562999915 ], [ 28.621797730000083, -9.638273620999911 ], [ 28.583557169000102, -9.563756204999947 ], [ 28.617766968000097, -9.543292337999986 ], [ 28.586296021000067, -9.544015807999898 ] ] ] } },
{ "type": "Feature", "properties": { "ISO": "ZM-08", "NAME_1": "Copperbelt" }, "geometry": { "type": "Polygon", "coordinates": [ [ [ 27.589820184154178, -12.242973320462397 ], [ 27.63818851700006, -12.29361541699997 ], [ 27.710742228000072, -12.306327819999936 ], [ 27.788308553000036, -12.296509296999957 ], [ 27.831406698000137, -12.259922383999921 ], [ 27.856676473000107, -12.262402851999894 ], [ 27.933881062000097, -12.30333058699992 ], [ 27.958685750000114, -12.367822774999937 ], [ 28.087670125000074, -12.377537943999883 ], [ 28.131285034000115, -12.429214374999916 ], [ 28.185751994000015, -12.402445983999939 ], [ 28.237531779000079, -12.437069192999957 ], [ 28.303677612000058, -12.435415547999909 ], [ 28.339747762000059, -12.450505065999906 ], [ 28.422740112000099, -12.521301777999938 ], [ 28.512295370000061, -12.668372905 ], [ 28.511623575000073, -12.694417825999977 ], [ 28.474003133000053, -12.736482441999911 ], [ 28.53942549700011, -12.833840840999954 ], [ 28.542836141000038, -12.885620625999934 ], [ 28.583970581000102, -12.888721210999876 ], [ 28.621177612000025, -12.839421895999877 ], [ 28.667893107000111, -12.849343769999876 ], [ 28.800598185000069, -13.00240936299987 ], [ 28.809434855000092, -13.038376159999927 ], [ 28.830880574000105, -13.051812031999887 ], [ 28.825816284000041, -13.092843118999937 ], [ 28.844213094000025, -13.102351582999916 ], [ 28.853669881000087, -13.137078144999947 ], [ 28.903434285000117, -13.162296243999904 ], [ 28.950356486000061, -13.350966897999868 ], [ 28.993971395000102, -13.395925394999978 ], [ 29.065386147000112, -13.388676477999894 ], [ 28.954077997201807, -13.519897962421055 ], [ 28.871860793141082, -13.560153904179344 ], [ 28.818479038376893, -13.620356946515869 ], [ 28.671201205571151, -13.731202895197441 ], [ 28.669495884127741, -13.856053155129018 ], [ 28.435194940394183, -13.890883070597226 ], [ 28.190196973711352, -13.86607838271118 ], [ 28.140380894162888, -13.891193128959742 ], [ 27.943907097634451, -13.919511813419433 ], [ 27.900188836145844, -13.880031019815704 ], [ 27.808308139708856, -13.685055840954305 ], [ 27.704645217402856, -13.673015231767522 ], [ 27.63669070790985, -13.647745456787391 ], [ 27.621859571661901, -13.663093356972865 ], [ 27.623668246792136, -13.702367445900904 ], [ 27.595711296639024, -13.709188735271937 ], [ 27.595711296639024, -13.736473890957313 ], [ 27.554318475117498, -13.813368421515463 ], [ 27.541554396418235, -13.817502536612778 ], [ 27.52315758585388, -13.789080498466262 ], [ 27.489877963996832, -13.794816583118802 ], [ 27.483935173769225, -13.867938734684856 ], [ 27.41680748927422, -13.919615167106258 ], [ 27.393708122831583, -13.897859388699828 ], [ 27.376758253990204, -13.823393649996945 ], [ 27.352883742091024, -13.793111260776072 ], [ 27.347147658337747, -13.740349622736915 ], [ 26.852604201422764, -13.716578463625183 ], [ 26.799067417027629, -13.676064141247139 ], [ 26.788990512602084, -13.64371469447758 ], [ 26.804028355324306, -13.545271091088011 ], [ 26.838186476324779, -13.508942558852027 ], [ 26.859115430632585, -13.439282728814874 ], [ 26.906140984918522, -13.416751804052524 ], [ 26.973630404619485, -13.334844659253633 ], [ 26.965103793805042, -13.211027927197108 ], [ 27.06101525165252, -13.130257663960037 ], [ 27.094191521621383, -13.00080820093774 ], [ 27.043910353180252, -12.996932468258819 ], [ 27.009648879392273, -12.9556946745696 ], [ 26.883144972162711, -12.892339369066633 ], [ 26.906916131274443, -12.819682305493984 ], [ 26.845007764796492, -12.738757012626024 ], [ 26.870587599038458, -12.657418307708724 ], [ 26.886245557586392, -12.637574558119354 ], [ 26.946655308195886, -12.618092542836564 ], [ 27.017400343850795, -12.532361342202194 ], [ 27.07682824073072, -12.515979913242404 ], [ 27.054917432693344, -12.46270151126572 ], [ 27.066131218680766, -12.387408948464213 ], [ 27.051506788907147, -12.33418222423029 ], [ 27.276505974571023, -12.345706068580228 ], [ 27.413396843689384, -12.247830905971512 ], [ 27.466003452097596, -12.270413506677983 ], [ 27.467398716077867, -12.288913669130523 ], [ 27.510548536785507, -12.300695895898855 ], [ 27.589820184154178, -12.242973320462397 ] ] ] } },
{ "type": "Feature", "properties": { "ISO": "ZM-02", "NAME_1": "Central" }, "geometry": { "type": "Polygon", "coordinates": [ [ [ 29.767154175000087, -13.45835052399994 ], [ 29.797643270000094, -13.424244078999976 ], [ 29.799582314000133, -12.159035937999903 ], [ 29.838881870202101, -12.133781019978073 ], [ 29.862653029313833, -12.044484145027297 ], [ 29.992050816392066, -12.00055917706436 ], [ 30.029774610809625, -12.034252210970749 ], [ 30.084551628654708, -12.147165216301687 ], [ 30.142119175359653, -12.174553724774569 ], [ 30.161807896217397, -12.202303968453407 ], [ 30.361382277270252, -12.272222181808274 ], [ 30.412852004116701, -12.273359062470774 ], [ 30.448560417829015, -12.308499037200818 ], [ 30.505197787647774, -12.314596856159994 ], [ 30.511553989025344, -12.385393568658287 ], [ 30.497291293558305, -12.450712578922378 ], [ 30.56989668118689, -12.509003595139802 ], [ 30.564470655796129, -12.574012546142114 ], [ 30.634750604356896, -12.625172213726671 ], [ 30.686582066409244, -12.588533624027548 ], [ 30.71670942599917, -12.63617929413914 ], [ 30.762959832130548, -12.668115329758677 ], [ 30.765285272097628, -12.691576429608574 ], [ 30.727251418418177, -12.76025440771474 ], [ 30.750195754330605, -12.871462090702948 ], [ 30.849672885595169, -12.933473809069028 ], [ 30.906620313776443, -12.927789402159192 ], [ 31.020515171038312, -12.950837090859068 ], [ 31.120767449558116, -13.040702405691491 ], [ 31.159886508855266, -13.034191175582293 ], [ 31.183761020754503, -12.966288343831991 ], [ 31.219624464997025, -12.948046562898583 ], [ 31.282618036193412, -12.949235121303786 ], [ 31.335844761326655, -12.976985364982625 ], [ 31.364990268985707, -13.228597913662782 ], [ 31.429430780106372, -13.352517998506812 ], [ 31.429120720844594, -13.435717054498468 ], [ 31.359357538019935, -13.461090183165425 ], [ 31.283238152918386, -13.517417493722348 ], [ 31.258898553025801, -13.513645114730252 ], [ 31.222414992058191, -13.582271416892354 ], [ 31.183295932761041, -13.578240654582544 ], [ 31.135185173756724, -13.607489515928421 ], [ 31.098598260001665, -13.713839614306778 ], [ 31.056068556019, -13.757609551739449 ], [ 31.061597935096586, -13.773525892705777 ], [ 30.970699089691209, -13.812231540852906 ], [ 30.959330274972217, -13.852590833600118 ], [ 30.936902703896635, -13.860032239696125 ], [ 30.882487420358132, -13.927211601933891 ], [ 30.097729120302631, -13.931862480968732 ], [ 30.14878543509974, -13.951189466620576 ], [ 30.184442172867989, -14.047204278154936 ], [ 30.278338250010222, -14.08177581120475 ], [ 30.305778436225808, -14.103841647973695 ], [ 30.320247837267857, -14.142754001695835 ], [ 30.291515740758825, -14.2068327776106 ], [ 30.218755324398671, -14.257940769251093 ], [ 30.122998895282763, -14.372559096025441 ], [ 30.083621453567218, -14.377881767729377 ], [ 30.069462110887685, -14.415140475952228 ], [ 30.034580518576036, -14.442425631637605 ], [ 29.994221225828881, -14.607066746233386 ], [ 30.051168654010155, -14.671197198092216 ], [ 30.000112339213047, -14.66783823025014 ], [ 29.971121860285621, -14.64913136222259 ], [ 29.904200881365568, -14.654402357982462 ], [ 29.877225783143331, -14.697190443484203 ], [ 29.812526889604271, -14.696932061065752 ], [ 29.781314325295853, -14.719359633040654 ], [ 29.668969760745824, -14.749848727836536 ], [ 29.576313917952916, -14.808914889510561 ], [ 29.521846957571029, -14.816407972449952 ], [ 29.459783563260828, -14.963117363575464 ], [ 29.311627232210981, -14.977431735885887 ], [ 29.228118116957489, -14.956709487153091 ], [ 29.001103549689049, -15.018514499944217 ], [ 28.94679161983737, -15.041510511800709 ], [ 28.823129917411734, -15.149359226047466 ], [ 28.74385827004312, -15.175714206645353 ], [ 28.569140251921056, -15.188271579769605 ], [ 28.404344110392344, -15.145690198943555 ], [ 28.375612012983993, -15.162536715896749 ], [ 28.290759312392311, -15.341698906579268 ], [ 28.259856804647825, -15.35255095826011 ], [ 28.033462355003678, -15.287283623940084 ], [ 27.827996859667337, -15.266354668732959 ], [ 27.777715692125469, -15.299479261858437 ], [ 27.773374872352463, -15.334929294051676 ], [ 27.891765578118907, -15.374255058923836 ], [ 27.934295282101573, -15.500862318940847 ], [ 27.905614862435925, -15.531661472099245 ], [ 27.799316440901009, -15.561013686232627 ], [ 27.743144159075655, -15.663126315826844 ], [ 27.708055861188996, -15.656305026455811 ], [ 27.691932813748338, -15.669327487573526 ], [ 27.651108433007778, -15.621475111886923 ], [ 27.66537112757544, -15.600287774261403 ], [ 27.65979007255379, -15.557654717491232 ], [ 27.626303745121731, -15.518949070243423 ], [ 27.546515333815591, -15.479881686890337 ], [ 27.45918216272662, -15.579307143110157 ], [ 27.409831170272298, -15.568093357122734 ], [ 27.300897251307106, -15.744413343900703 ], [ 27.279503208106576, -15.727050063009983 ], [ 27.227671746953547, -15.497089939049431 ], [ 27.202195264599766, -15.482207126857418 ], [ 26.958592563695845, -15.467686048971984 ], [ 26.987272984260812, -15.435181572571537 ], [ 26.843922560078056, -15.351620782273301 ], [ 26.804183384055932, -15.342990817772034 ], [ 25.324790480296429, -15.298859145133463 ], [ 25.324170362672078, -15.178659762438087 ], [ 25.367888625060004, -15.137525322435692 ], [ 25.41057335777424, -15.131427503476516 ], [ 25.414139032090645, -15.080577895153738 ], [ 25.45604861844896, -15.019599704662653 ], [ 25.456513706442365, -14.97055876967147 ], [ 25.425662876440583, -14.913611341490196 ], [ 25.423182406842557, -14.876455986954227 ], [ 25.450002476333225, -14.806641127286184 ], [ 25.480129835923151, -14.784471937729734 ], [ 25.478682895998816, -14.683496188798074 ], [ 25.523072951055838, -14.602829277449189 ], [ 25.585601434258763, -14.559369399278353 ], [ 26.17373090995352, -14.621071059281974 ], [ 26.197915480215215, -14.654505710769968 ], [ 26.294136997324529, -14.68861215582632 ], [ 26.324832797695422, -14.716569105979488 ], [ 26.369842970376737, -14.699205824189448 ], [ 26.387412956842468, -14.62696217176682 ], [ 26.492161085665543, -14.531619154700252 ], [ 26.555464715224389, -14.450693861832235 ], [ 26.736073845831299, -14.449040215433627 ], [ 26.804648472049337, -14.414933769477898 ], [ 26.927690056850622, -14.409921156136477 ], [ 26.944329868228806, -14.395606784725317 ], [ 26.955957066265569, -14.373954360005712 ], [ 26.952236362318274, -14.253083183741921 ], [ 26.97890140127862, -14.209468275940196 ], [ 26.979056430909566, -14.169057305450281 ], [ 26.913427362282903, -14.076091404294857 ], [ 26.85772016755169, -14.037747490454308 ], [ 26.907536247999417, -14.009583835625506 ], [ 26.912187127034258, -13.910003349774797 ], [ 26.954561802285355, -13.821740003598279 ], [ 26.906296013650092, -13.790269056871466 ], [ 26.852604201422764, -13.716578463625183 ], [ 27.347147658337747, -13.740349622736915 ], [ 27.352883742091024, -13.793111260776072 ], [ 27.376758253990204, -13.823393649996945 ], [ 27.393708122831583, -13.897859388699828 ], [ 27.41680748927422, -13.919615167106258 ], [ 27.483935173769225, -13.867938734684856 ], [ 27.489877963996832, -13.794816583118802 ], [ 27.52315758585388, -13.789080498466262 ], [ 27.541554396418235, -13.817502536612778 ], [ 27.554318475117498, -13.813368421515463 ], [ 27.595711296639024, -13.736473890957313 ], [ 27.595711296639024, -13.709188735271937 ], [ 27.623668246792136, -13.702367445900904 ], [ 27.621859571661901, -13.663093356972865 ], [ 27.63669070790985, -13.647745456787391 ], [ 27.704645217402856, -13.673015231767522 ], [ 27.808308139708856, -13.685055840954305 ], [ 27.900188836145844, -13.880031019815704 ], [ 27.943907097634451, -13.919511813419433 ], [ 28.140380894162888, -13.891193128959742 ], [ 28.190196973711352, -13.86607838271118 ], [ 28.280940790385159, -13.885146986843949 ], [ 28.360109084066949, -13.874656671268383 ], [ 28.435194940394183, -13.890883070597226 ], [ 28.500358921027384, -13.885612073938091 ], [ 28.669495884127741, -13.856053155129018 ], [ 28.671201205571151, -13.731202895197441 ], [ 28.818479038376893, -13.620356946515869 ], [ 28.871860793141082, -13.560153904179344 ], [ 28.954077997201807, -13.519897962421055 ], [ 29.065386147000112, -13.388676477999894 ], [ 29.122128947000135, -13.384349873999938 ], [ 29.184140665000086, -13.4368531289999 ], [ 29.308267456000124, -13.353654072999902 ], [ 29.449550822000106, -13.300323994999914 ], [ 29.551043335000088, -13.224152933999918 ], [ 29.666591837000055, -13.271178486999887 ], [ 29.658892049000087, -13.309522399999906 ], [ 29.62659427900013, -13.326368916999883 ], [ 29.625147339000137, -13.364196064999959 ], [ 29.60168623900006, -13.374427998999934 ], [ 29.617395874000124, -13.421246846999864 ], [ 29.702868693000141, -13.457627054999946 ], [ 29.767154175000087, -13.45835052399994 ] ] ] } }
]
}
|
superset-frontend/plugins/legacy-plugin-chart-country-map/src/countries/zambia.geojson
| 0 |
https://github.com/apache/superset/commit/9646591d240516a7eb1515e70cfb8768352e4f30
|
[
0.001691950368694961,
0.0015732909087091684,
0.001454631332308054,
0.0015732909087091684,
0.00011865951819345355
] |
{
"id": 3,
"code_window": [
" linear_color_scheme: {\n",
" description: t(\n",
" 'When a secondary metric is provided, a linear color scale is used.',\n",
" ),\n",
" },\n",
" groupby: {\n",
" label: t('Hierarchy'),\n",
" description: t('This defines the level of the hierarchy'),\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" visibility: ({ controls }: ControlPanelsContainerProps) =>\n",
" Boolean(\n",
" controls?.secondary_metric?.value &&\n",
" controls?.secondary_metric?.value !== controls?.metric.value,\n",
" ),\n"
],
"file_path": "superset-frontend/plugins/legacy-plugin-chart-sunburst/src/controlPanel.ts",
"type": "add",
"edit_start_line_idx": 78
}
|
/**
* 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 { t } from '@superset-ui/core';
import { ControlPanelConfig, sections } from '@superset-ui/chart-controls';
const config: ControlPanelConfig = {
controlPanelSections: [
sections.legacyRegularTime,
{
label: t('Query'),
expanded: true,
controlSetRows: [
['groupby'],
['metric'],
['secondary_metric'],
['adhoc_filters'],
['row_limit'],
[
{
name: 'sort_by_metric',
config: {
type: 'CheckboxControl',
label: t('Sort by metric'),
description: t(
'Whether to sort results by the selected metric in descending order.',
),
},
},
],
],
},
{
label: t('Chart Options'),
expanded: true,
controlSetRows: [['color_scheme'], ['linear_color_scheme']],
},
],
controlOverrides: {
metric: {
label: t('Primary Metric'),
description: t(
'The primary metric is used to define the arc segment sizes',
),
},
secondary_metric: {
label: t('Secondary Metric'),
default: null,
description: t(
'[optional] this secondary metric is used to ' +
'define the color as a ratio against the primary metric. ' +
'When omitted, the color is categorical and based on labels',
),
},
color_scheme: {
description: t(
'When only a primary metric is provided, a categorical color scale is used.',
),
},
linear_color_scheme: {
description: t(
'When a secondary metric is provided, a linear color scale is used.',
),
},
groupby: {
label: t('Hierarchy'),
description: t('This defines the level of the hierarchy'),
},
},
};
export default config;
|
superset-frontend/plugins/legacy-plugin-chart-sunburst/src/controlPanel.ts
| 1 |
https://github.com/apache/superset/commit/9646591d240516a7eb1515e70cfb8768352e4f30
|
[
0.9848632216453552,
0.129208043217659,
0.00017320606275461614,
0.0013425990473479033,
0.30517005920410156
] |
{
"id": 3,
"code_window": [
" linear_color_scheme: {\n",
" description: t(\n",
" 'When a secondary metric is provided, a linear color scale is used.',\n",
" ),\n",
" },\n",
" groupby: {\n",
" label: t('Hierarchy'),\n",
" description: t('This defines the level of the hierarchy'),\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" visibility: ({ controls }: ControlPanelsContainerProps) =>\n",
" Boolean(\n",
" controls?.secondary_metric?.value &&\n",
" controls?.secondary_metric?.value !== controls?.metric.value,\n",
" ),\n"
],
"file_path": "superset-frontend/plugins/legacy-plugin-chart-sunburst/src/controlPanel.ts",
"type": "add",
"edit_start_line_idx": 78
}
|
/**
* 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 fetchMock from 'fetch-mock';
import WS from 'jest-websocket-mock';
import sinon from 'sinon';
import * as featureFlags from 'src/featureFlags';
import { parseErrorJson } from 'src/utils/getClientErrorObject';
import * as asyncEvent from 'src/middleware/asyncEvent';
describe('asyncEvent middleware', () => {
const asyncPendingEvent = {
status: 'pending',
result_url: null,
job_id: 'foo123',
channel_id: '999',
errors: [],
};
const asyncDoneEvent = {
id: '1518951480106-0',
status: 'done',
result_url: '/api/v1/chart/data/cache-key-1',
job_id: 'foo123',
channel_id: '999',
errors: [],
};
const asyncErrorEvent = {
id: '1518951480107-0',
status: 'error',
result_url: null,
job_id: 'foo123',
channel_id: '999',
errors: [{ message: "Error: relation 'foo' does not exist" }],
};
const chartData = {
result: [
{
cache_key: '199f01f81f99c98693694821e4458111',
cached_dttm: null,
cache_timeout: 86400,
annotation_data: {},
error: null,
is_cached: false,
query:
'SELECT product_line AS product_line,\n sum(sales) AS "(Sales)"\nFROM cleaned_sales_data\nGROUP BY product_line\nLIMIT 50000',
status: 'success',
stacktrace: null,
rowcount: 7,
colnames: ['product_line', '(Sales)'],
coltypes: [1, 0],
data: [
{
product_line: 'Classic Cars',
'(Sales)': 3919615.66,
},
],
applied_filters: [
{
column: '__time_range',
},
],
rejected_filters: [],
},
],
};
const EVENTS_ENDPOINT = 'glob:*/api/v1/async_event/*';
const CACHED_DATA_ENDPOINT = 'glob:*/api/v1/chart/data/*';
let featureEnabledStub: any;
beforeEach(async () => {
featureEnabledStub = sinon.stub(featureFlags, 'isFeatureEnabled');
featureEnabledStub.withArgs('GLOBAL_ASYNC_QUERIES').returns(true);
});
afterEach(() => {
fetchMock.reset();
featureEnabledStub.restore();
});
afterAll(fetchMock.reset);
describe('polling transport', () => {
const config = {
GLOBAL_ASYNC_QUERIES_TRANSPORT: 'polling',
GLOBAL_ASYNC_QUERIES_POLLING_DELAY: 50,
GLOBAL_ASYNC_QUERIES_WEBSOCKET_URL: '',
};
beforeEach(async () => {
fetchMock.get(EVENTS_ENDPOINT, {
status: 200,
body: { result: [asyncDoneEvent] },
});
fetchMock.get(CACHED_DATA_ENDPOINT, {
status: 200,
body: { result: chartData },
});
asyncEvent.init(config);
});
it('resolves with chart data on event done status', async () => {
await expect(
asyncEvent.waitForAsyncData(asyncPendingEvent),
).resolves.toEqual([chartData]);
expect(fetchMock.calls(EVENTS_ENDPOINT)).toHaveLength(1);
expect(fetchMock.calls(CACHED_DATA_ENDPOINT)).toHaveLength(1);
});
it('rejects on event error status', async () => {
fetchMock.reset();
fetchMock.get(EVENTS_ENDPOINT, {
status: 200,
body: { result: [asyncErrorEvent] },
});
const errorResponse = await parseErrorJson(asyncErrorEvent);
await expect(
asyncEvent.waitForAsyncData(asyncPendingEvent),
).rejects.toEqual(errorResponse);
expect(fetchMock.calls(EVENTS_ENDPOINT)).toHaveLength(1);
expect(fetchMock.calls(CACHED_DATA_ENDPOINT)).toHaveLength(0);
});
it('rejects on cached data fetch error', async () => {
fetchMock.reset();
fetchMock.get(EVENTS_ENDPOINT, {
status: 200,
body: { result: [asyncDoneEvent] },
});
fetchMock.get(CACHED_DATA_ENDPOINT, {
status: 400,
});
const errorResponse = [{ error: 'Bad Request' }];
await expect(
asyncEvent.waitForAsyncData(asyncPendingEvent),
).rejects.toEqual(errorResponse);
expect(fetchMock.calls(EVENTS_ENDPOINT)).toHaveLength(1);
expect(fetchMock.calls(CACHED_DATA_ENDPOINT)).toHaveLength(1);
});
});
describe('ws transport', () => {
let wsServer: WS;
const config = {
GLOBAL_ASYNC_QUERIES_TRANSPORT: 'ws',
GLOBAL_ASYNC_QUERIES_POLLING_DELAY: 50,
GLOBAL_ASYNC_QUERIES_WEBSOCKET_URL: 'ws://127.0.0.1:8080/',
};
beforeEach(async () => {
fetchMock.get(EVENTS_ENDPOINT, {
status: 200,
body: { result: [asyncDoneEvent] },
});
fetchMock.get(CACHED_DATA_ENDPOINT, {
status: 200,
body: { result: chartData },
});
wsServer = new WS(config.GLOBAL_ASYNC_QUERIES_WEBSOCKET_URL);
asyncEvent.init(config);
});
afterEach(() => {
WS.clean();
});
it('resolves with chart data on event done status', async () => {
await wsServer.connected;
const promise = asyncEvent.waitForAsyncData(asyncPendingEvent);
wsServer.send(JSON.stringify(asyncDoneEvent));
await expect(promise).resolves.toEqual([chartData]);
expect(fetchMock.calls(CACHED_DATA_ENDPOINT)).toHaveLength(1);
expect(fetchMock.calls(EVENTS_ENDPOINT)).toHaveLength(0);
});
it('rejects on event error status', async () => {
await wsServer.connected;
const promise = asyncEvent.waitForAsyncData(asyncPendingEvent);
wsServer.send(JSON.stringify(asyncErrorEvent));
const errorResponse = await parseErrorJson(asyncErrorEvent);
await expect(promise).rejects.toEqual(errorResponse);
expect(fetchMock.calls(CACHED_DATA_ENDPOINT)).toHaveLength(0);
expect(fetchMock.calls(EVENTS_ENDPOINT)).toHaveLength(0);
});
it('rejects on cached data fetch error', async () => {
fetchMock.reset();
fetchMock.get(CACHED_DATA_ENDPOINT, {
status: 400,
});
await wsServer.connected;
const promise = asyncEvent.waitForAsyncData(asyncPendingEvent);
wsServer.send(JSON.stringify(asyncDoneEvent));
const errorResponse = [{ error: 'Bad Request' }];
await expect(promise).rejects.toEqual(errorResponse);
expect(fetchMock.calls(CACHED_DATA_ENDPOINT)).toHaveLength(1);
expect(fetchMock.calls(EVENTS_ENDPOINT)).toHaveLength(0);
});
it('resolves when events are received before listener', async () => {
await wsServer.connected;
wsServer.send(JSON.stringify(asyncDoneEvent));
const promise = asyncEvent.waitForAsyncData(asyncPendingEvent);
await expect(promise).resolves.toEqual([chartData]);
expect(fetchMock.calls(CACHED_DATA_ENDPOINT)).toHaveLength(1);
expect(fetchMock.calls(EVENTS_ENDPOINT)).toHaveLength(0);
});
});
});
|
superset-frontend/src/middleware/asyncEvent.test.ts
| 0 |
https://github.com/apache/superset/commit/9646591d240516a7eb1515e70cfb8768352e4f30
|
[
0.00019614730263128877,
0.00017402278899680823,
0.00015961198369041085,
0.0001736219273880124,
0.000005821507329528686
] |
{
"id": 3,
"code_window": [
" linear_color_scheme: {\n",
" description: t(\n",
" 'When a secondary metric is provided, a linear color scale is used.',\n",
" ),\n",
" },\n",
" groupby: {\n",
" label: t('Hierarchy'),\n",
" description: t('This defines the level of the hierarchy'),\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" visibility: ({ controls }: ControlPanelsContainerProps) =>\n",
" Boolean(\n",
" controls?.secondary_metric?.value &&\n",
" controls?.secondary_metric?.value !== controls?.metric.value,\n",
" ),\n"
],
"file_path": "superset-frontend/plugins/legacy-plugin-chart-sunburst/src/controlPanel.ts",
"type": "add",
"edit_start_line_idx": 78
}
|
/*
* 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.
*/
/* eslint-disable no-magic-numbers */
import React from 'react';
import { SuperChart } from '@superset-ui/core';
import SunburstChartPlugin from '@superset-ui/legacy-plugin-chart-sunburst';
import ResizableChartDemo from '../../../shared/components/ResizableChartDemo';
import data from './data';
new SunburstChartPlugin().configure({ key: 'sunburst' }).register();
export default {
title: 'Legacy Chart Plugins/legacy-plugin-chart-sunburst',
};
export const basic = () => (
<SuperChart
chartType="sunburst"
width={400}
height={400}
queriesData={[{ data }]}
formData={{
colorScheme: 'd3Category10',
metric: 'sum__SP_POP_TOTL',
secondaryMetric: 'sum__SP_RUR_TOTL',
}}
/>
);
export const resizable = () => (
<ResizableChartDemo>
{({ width, height }) => (
<SuperChart
chartType="sunburst"
width={width}
height={height}
queriesData={[{ data }]}
formData={{
colorScheme: 'd3Category10',
metric: 'sum__SP_POP_TOTL',
secondaryMetric: 'sum__SP_RUR_TOTL',
}}
/>
)}
</ResizableChartDemo>
);
|
superset-frontend/packages/superset-ui-demo/storybook/stories/plugins/legacy-plugin-chart-sunburst/Stories.tsx
| 0 |
https://github.com/apache/superset/commit/9646591d240516a7eb1515e70cfb8768352e4f30
|
[
0.0007356850546784699,
0.00031674039200879633,
0.00016527932893950492,
0.00017408575513400137,
0.0002311855205334723
] |
{
"id": 3,
"code_window": [
" linear_color_scheme: {\n",
" description: t(\n",
" 'When a secondary metric is provided, a linear color scale is used.',\n",
" ),\n",
" },\n",
" groupby: {\n",
" label: t('Hierarchy'),\n",
" description: t('This defines the level of the hierarchy'),\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" visibility: ({ controls }: ControlPanelsContainerProps) =>\n",
" Boolean(\n",
" controls?.secondary_metric?.value &&\n",
" controls?.secondary_metric?.value !== controls?.metric.value,\n",
" ),\n"
],
"file_path": "superset-frontend/plugins/legacy-plugin-chart-sunburst/src/controlPanel.ts",
"type": "add",
"edit_start_line_idx": 78
}
|
<!--
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.
-->
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<circle cx="12" cy="12" r="4" fill="currentColor"/>
</svg>
|
superset-frontend/src/assets/images/icons/offline.svg
| 0 |
https://github.com/apache/superset/commit/9646591d240516a7eb1515e70cfb8768352e4f30
|
[
0.00017706766084302217,
0.00017542285786475986,
0.00017442704120185226,
0.0001747738424455747,
0.0000011716440440068254
] |
{
"id": 0,
"code_window": [
"import { DashboardRow } from './DashboardRow';\n",
"import { AddPanelPanel } from './AddPanelPanel';\n",
"import { importPluginModule } from 'app/features/plugins/plugin_loader';\n",
"import { PluginExports } from 'app/types/plugins';\n",
"import { PanelChrome } from './PanelChrome';\n",
"import { PanelEditor } from './PanelEditor';\n",
"\n",
"export interface Props {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { PluginExports, PanelPlugin } from 'app/types/plugins';\n"
],
"file_path": "public/app/features/dashboard/dashgrid/DashboardPanel.tsx",
"type": "replace",
"edit_start_line_idx": 8
}
|
import React from 'react';
import classNames from 'classnames';
import { PanelModel } from '../panel_model';
import { DashboardModel } from '../dashboard_model';
import { store } from 'app/stores/store';
import { observer } from 'mobx-react';
import { QueriesTab } from './QueriesTab';
import { PanelPlugin } from 'app/types/plugins';
import { VizTypePicker } from './VizTypePicker';
interface PanelEditorProps {
panel: PanelModel;
dashboard: DashboardModel;
}
interface PanelEditorTab {
id: string;
text: string;
icon: string;
}
@observer
export class PanelEditor extends React.Component<PanelEditorProps, any> {
tabs: PanelEditorTab[];
constructor(props) {
super(props);
this.tabs = [
{ id: 'queries', text: 'Queries', icon: 'fa fa-database' },
{ id: 'viz', text: 'Visualization', icon: 'fa fa-line-chart' },
];
}
renderQueriesTab() {
return <QueriesTab panel={this.props.panel} dashboard={this.props.dashboard} />;
}
renderVizTab() {
return (
<div className="viz-editor">
<div className="viz-editor-col1">
<VizTypePicker currentType={this.props.panel.type} onTypeChanged={this.onVizTypeChanged} />
</div>
<div className="viz-editor-col2">
<h5 className="page-heading">Options</h5>
</div>
</div>
);
}
onVizTypeChanged = (plugin: PanelPlugin) => {
console.log('changing type to ', plugin.id);
this.props.panel.changeType(plugin.id);
};
onChangeTab = (tab: PanelEditorTab) => {
store.view.updateQuery({ tab: tab.id }, false);
};
render() {
const activeTab: string = store.view.query.get('tab') || 'queries';
return (
<div className="tabbed-view tabbed-view--new">
<div className="tabbed-view-header">
<ul className="gf-tabs">
{this.tabs.map(tab => {
return <TabItem tab={tab} activeTab={activeTab} onClick={this.onChangeTab} key={tab.id} />;
})}
</ul>
<button className="tabbed-view-close-btn" ng-click="ctrl.exitFullscreen();">
<i className="fa fa-remove" />
</button>
</div>
<div className="tabbed-view-body">
{activeTab === 'queries' && this.renderQueriesTab()}
{activeTab === 'viz' && this.renderVizTab()}
</div>
</div>
);
}
}
interface TabItemParams {
tab: PanelEditorTab;
activeTab: string;
onClick: (tab: PanelEditorTab) => void;
}
function TabItem({ tab, activeTab, onClick }: TabItemParams) {
const tabClasses = classNames({
'gf-tabs-link': true,
active: activeTab === tab.id,
});
return (
<li className="gf-tabs-item" key={tab.id}>
<a className={tabClasses} onClick={() => onClick(tab)}>
<i className={tab.icon} />
{tab.text}
</a>
</li>
);
}
|
public/app/features/dashboard/dashgrid/PanelEditor.tsx
| 1 |
https://github.com/grafana/grafana/commit/dc3a81200b1cd366bdf237ada152ae3d79bdaf59
|
[
0.007433109916746616,
0.0016822990728542209,
0.0001662664581090212,
0.00021883111912757158,
0.0026645937468856573
] |
{
"id": 0,
"code_window": [
"import { DashboardRow } from './DashboardRow';\n",
"import { AddPanelPanel } from './AddPanelPanel';\n",
"import { importPluginModule } from 'app/features/plugins/plugin_loader';\n",
"import { PluginExports } from 'app/types/plugins';\n",
"import { PanelChrome } from './PanelChrome';\n",
"import { PanelEditor } from './PanelEditor';\n",
"\n",
"export interface Props {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { PluginExports, PanelPlugin } from 'app/types/plugins';\n"
],
"file_path": "public/app/features/dashboard/dashgrid/DashboardPanel.tsx",
"type": "replace",
"edit_start_line_idx": 8
}
|
// Copyright 2014 The Macaron Authors
//
// Licensed under the Apache License, Version 2.0 (the "License"): you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.
package macaron
import (
"crypto/sha256"
"encoding/hex"
"html/template"
"io"
"io/ioutil"
"mime/multipart"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
"reflect"
"strconv"
"strings"
"time"
"github.com/Unknwon/com"
"github.com/go-macaron/inject"
"golang.org/x/crypto/pbkdf2"
)
// Locale reprents a localization interface.
type Locale interface {
Language() string
Tr(string, ...interface{}) string
}
// RequestBody represents a request body.
type RequestBody struct {
reader io.ReadCloser
}
// Bytes reads and returns content of request body in bytes.
func (rb *RequestBody) Bytes() ([]byte, error) {
return ioutil.ReadAll(rb.reader)
}
// String reads and returns content of request body in string.
func (rb *RequestBody) String() (string, error) {
data, err := rb.Bytes()
return string(data), err
}
// ReadCloser returns a ReadCloser for request body.
func (rb *RequestBody) ReadCloser() io.ReadCloser {
return rb.reader
}
// Request represents an HTTP request received by a server or to be sent by a client.
type Request struct {
*http.Request
}
func (r *Request) Body() *RequestBody {
return &RequestBody{r.Request.Body}
}
// ContextInvoker is an inject.FastInvoker wrapper of func(ctx *Context).
type ContextInvoker func(ctx *Context)
func (invoke ContextInvoker) Invoke(params []interface{}) ([]reflect.Value, error) {
invoke(params[0].(*Context))
return nil, nil
}
// Context represents the runtime context of current request of Macaron instance.
// It is the integration of most frequently used middlewares and helper methods.
type Context struct {
inject.Injector
handlers []Handler
action Handler
index int
*Router
Req Request
Resp ResponseWriter
params Params
Render
Locale
Data map[string]interface{}
}
func (c *Context) handler() Handler {
if c.index < len(c.handlers) {
return c.handlers[c.index]
}
if c.index == len(c.handlers) {
return c.action
}
panic("invalid index for context handler")
}
func (c *Context) Next() {
c.index += 1
c.run()
}
func (c *Context) Written() bool {
return c.Resp.Written()
}
func (c *Context) run() {
for c.index <= len(c.handlers) {
vals, err := c.Invoke(c.handler())
if err != nil {
panic(err)
}
c.index += 1
// if the handler returned something, write it to the http response
if len(vals) > 0 {
ev := c.GetVal(reflect.TypeOf(ReturnHandler(nil)))
handleReturn := ev.Interface().(ReturnHandler)
handleReturn(c, vals)
}
if c.Written() {
return
}
}
}
// RemoteAddr returns more real IP address.
func (ctx *Context) RemoteAddr() string {
addr := ctx.Req.Header.Get("X-Real-IP")
if len(addr) == 0 {
addr = ctx.Req.Header.Get("X-Forwarded-For")
if addr == "" {
addr = ctx.Req.RemoteAddr
if i := strings.LastIndex(addr, ":"); i > -1 {
addr = addr[:i]
}
}
}
return addr
}
func (ctx *Context) renderHTML(status int, setName, tplName string, data ...interface{}) {
if len(data) <= 0 {
ctx.Render.HTMLSet(status, setName, tplName, ctx.Data)
} else if len(data) == 1 {
ctx.Render.HTMLSet(status, setName, tplName, data[0])
} else {
ctx.Render.HTMLSet(status, setName, tplName, data[0], data[1].(HTMLOptions))
}
}
// HTML calls Render.HTML but allows less arguments.
func (ctx *Context) HTML(status int, name string, data ...interface{}) {
ctx.renderHTML(status, DEFAULT_TPL_SET_NAME, name, data...)
}
// HTML calls Render.HTMLSet but allows less arguments.
func (ctx *Context) HTMLSet(status int, setName, tplName string, data ...interface{}) {
ctx.renderHTML(status, setName, tplName, data...)
}
func (ctx *Context) Redirect(location string, status ...int) {
code := http.StatusFound
if len(status) == 1 {
code = status[0]
}
http.Redirect(ctx.Resp, ctx.Req.Request, location, code)
}
// Maximum amount of memory to use when parsing a multipart form.
// Set this to whatever value you prefer; default is 10 MB.
var MaxMemory = int64(1024 * 1024 * 10)
func (ctx *Context) parseForm() {
if ctx.Req.Form != nil {
return
}
contentType := ctx.Req.Header.Get(_CONTENT_TYPE)
if (ctx.Req.Method == "POST" || ctx.Req.Method == "PUT") &&
len(contentType) > 0 && strings.Contains(contentType, "multipart/form-data") {
ctx.Req.ParseMultipartForm(MaxMemory)
} else {
ctx.Req.ParseForm()
}
}
// Query querys form parameter.
func (ctx *Context) Query(name string) string {
ctx.parseForm()
return ctx.Req.Form.Get(name)
}
// QueryTrim querys and trims spaces form parameter.
func (ctx *Context) QueryTrim(name string) string {
return strings.TrimSpace(ctx.Query(name))
}
// QueryStrings returns a list of results by given query name.
func (ctx *Context) QueryStrings(name string) []string {
ctx.parseForm()
vals, ok := ctx.Req.Form[name]
if !ok {
return []string{}
}
return vals
}
// QueryEscape returns escapred query result.
func (ctx *Context) QueryEscape(name string) string {
return template.HTMLEscapeString(ctx.Query(name))
}
// QueryBool returns query result in bool type.
func (ctx *Context) QueryBool(name string) bool {
v, _ := strconv.ParseBool(ctx.Query(name))
return v
}
// QueryInt returns query result in int type.
func (ctx *Context) QueryInt(name string) int {
return com.StrTo(ctx.Query(name)).MustInt()
}
// QueryInt64 returns query result in int64 type.
func (ctx *Context) QueryInt64(name string) int64 {
return com.StrTo(ctx.Query(name)).MustInt64()
}
// QueryFloat64 returns query result in float64 type.
func (ctx *Context) QueryFloat64(name string) float64 {
v, _ := strconv.ParseFloat(ctx.Query(name), 64)
return v
}
// Params returns value of given param name.
// e.g. ctx.Params(":uid") or ctx.Params("uid")
func (ctx *Context) Params(name string) string {
if len(name) == 0 {
return ""
}
if len(name) > 1 && name[0] != ':' {
name = ":" + name
}
return ctx.params[name]
}
// SetParams sets value of param with given name.
func (ctx *Context) SetParams(name, val string) {
if !strings.HasPrefix(name, ":") {
name = ":" + name
}
ctx.params[name] = val
}
// ReplaceAllParams replace all current params with given params
func (ctx *Context) ReplaceAllParams(params Params) {
ctx.params = params;
}
// ParamsEscape returns escapred params result.
// e.g. ctx.ParamsEscape(":uname")
func (ctx *Context) ParamsEscape(name string) string {
return template.HTMLEscapeString(ctx.Params(name))
}
// ParamsInt returns params result in int type.
// e.g. ctx.ParamsInt(":uid")
func (ctx *Context) ParamsInt(name string) int {
return com.StrTo(ctx.Params(name)).MustInt()
}
// ParamsInt64 returns params result in int64 type.
// e.g. ctx.ParamsInt64(":uid")
func (ctx *Context) ParamsInt64(name string) int64 {
return com.StrTo(ctx.Params(name)).MustInt64()
}
// ParamsFloat64 returns params result in int64 type.
// e.g. ctx.ParamsFloat64(":uid")
func (ctx *Context) ParamsFloat64(name string) float64 {
v, _ := strconv.ParseFloat(ctx.Params(name), 64)
return v
}
// GetFile returns information about user upload file by given form field name.
func (ctx *Context) GetFile(name string) (multipart.File, *multipart.FileHeader, error) {
return ctx.Req.FormFile(name)
}
// SaveToFile reads a file from request by field name and saves to given path.
func (ctx *Context) SaveToFile(name, savePath string) error {
fr, _, err := ctx.GetFile(name)
if err != nil {
return err
}
defer fr.Close()
fw, err := os.OpenFile(savePath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
if err != nil {
return err
}
defer fw.Close()
_, err = io.Copy(fw, fr)
return err
}
// SetCookie sets given cookie value to response header.
// FIXME: IE support? http://golanghome.com/post/620#reply2
func (ctx *Context) SetCookie(name string, value string, others ...interface{}) {
cookie := http.Cookie{}
cookie.Name = name
cookie.Value = url.QueryEscape(value)
if len(others) > 0 {
switch v := others[0].(type) {
case int:
cookie.MaxAge = v
case int64:
cookie.MaxAge = int(v)
case int32:
cookie.MaxAge = int(v)
}
}
cookie.Path = "/"
if len(others) > 1 {
if v, ok := others[1].(string); ok && len(v) > 0 {
cookie.Path = v
}
}
if len(others) > 2 {
if v, ok := others[2].(string); ok && len(v) > 0 {
cookie.Domain = v
}
}
if len(others) > 3 {
switch v := others[3].(type) {
case bool:
cookie.Secure = v
default:
if others[3] != nil {
cookie.Secure = true
}
}
}
if len(others) > 4 {
if v, ok := others[4].(bool); ok && v {
cookie.HttpOnly = true
}
}
if len(others) > 5 {
if v, ok := others[5].(time.Time); ok {
cookie.Expires = v
cookie.RawExpires = v.Format(time.UnixDate)
}
}
ctx.Resp.Header().Add("Set-Cookie", cookie.String())
}
// GetCookie returns given cookie value from request header.
func (ctx *Context) GetCookie(name string) string {
cookie, err := ctx.Req.Cookie(name)
if err != nil {
return ""
}
val, _ := url.QueryUnescape(cookie.Value)
return val
}
// GetCookieInt returns cookie result in int type.
func (ctx *Context) GetCookieInt(name string) int {
return com.StrTo(ctx.GetCookie(name)).MustInt()
}
// GetCookieInt64 returns cookie result in int64 type.
func (ctx *Context) GetCookieInt64(name string) int64 {
return com.StrTo(ctx.GetCookie(name)).MustInt64()
}
// GetCookieFloat64 returns cookie result in float64 type.
func (ctx *Context) GetCookieFloat64(name string) float64 {
v, _ := strconv.ParseFloat(ctx.GetCookie(name), 64)
return v
}
var defaultCookieSecret string
// SetDefaultCookieSecret sets global default secure cookie secret.
func (m *Macaron) SetDefaultCookieSecret(secret string) {
defaultCookieSecret = secret
}
// SetSecureCookie sets given cookie value to response header with default secret string.
func (ctx *Context) SetSecureCookie(name, value string, others ...interface{}) {
ctx.SetSuperSecureCookie(defaultCookieSecret, name, value, others...)
}
// GetSecureCookie returns given cookie value from request header with default secret string.
func (ctx *Context) GetSecureCookie(key string) (string, bool) {
return ctx.GetSuperSecureCookie(defaultCookieSecret, key)
}
// SetSuperSecureCookie sets given cookie value to response header with secret string.
func (ctx *Context) SetSuperSecureCookie(secret, name, value string, others ...interface{}) {
key := pbkdf2.Key([]byte(secret), []byte(secret), 1000, 16, sha256.New)
text, err := com.AESGCMEncrypt(key, []byte(value))
if err != nil {
panic("error encrypting cookie: " + err.Error())
}
ctx.SetCookie(name, hex.EncodeToString(text), others...)
}
// GetSuperSecureCookie returns given cookie value from request header with secret string.
func (ctx *Context) GetSuperSecureCookie(secret, name string) (string, bool) {
val := ctx.GetCookie(name)
if val == "" {
return "", false
}
text, err := hex.DecodeString(val)
if err != nil {
return "", false
}
key := pbkdf2.Key([]byte(secret), []byte(secret), 1000, 16, sha256.New)
text, err = com.AESGCMDecrypt(key, text)
return string(text), err == nil
}
func (ctx *Context) setRawContentHeader() {
ctx.Resp.Header().Set("Content-Description", "Raw content")
ctx.Resp.Header().Set("Content-Type", "text/plain")
ctx.Resp.Header().Set("Expires", "0")
ctx.Resp.Header().Set("Cache-Control", "must-revalidate")
ctx.Resp.Header().Set("Pragma", "public")
}
// ServeContent serves given content to response.
func (ctx *Context) ServeContent(name string, r io.ReadSeeker, params ...interface{}) {
modtime := time.Now()
for _, p := range params {
switch v := p.(type) {
case time.Time:
modtime = v
}
}
ctx.setRawContentHeader()
http.ServeContent(ctx.Resp, ctx.Req.Request, name, modtime, r)
}
// ServeFileContent serves given file as content to response.
func (ctx *Context) ServeFileContent(file string, names ...string) {
var name string
if len(names) > 0 {
name = names[0]
} else {
name = path.Base(file)
}
f, err := os.Open(file)
if err != nil {
if Env == PROD {
http.Error(ctx.Resp, "Internal Server Error", 500)
} else {
http.Error(ctx.Resp, err.Error(), 500)
}
return
}
defer f.Close()
ctx.setRawContentHeader()
http.ServeContent(ctx.Resp, ctx.Req.Request, name, time.Now(), f)
}
// ServeFile serves given file to response.
func (ctx *Context) ServeFile(file string, names ...string) {
var name string
if len(names) > 0 {
name = names[0]
} else {
name = path.Base(file)
}
ctx.Resp.Header().Set("Content-Description", "File Transfer")
ctx.Resp.Header().Set("Content-Type", "application/octet-stream")
ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+name)
ctx.Resp.Header().Set("Content-Transfer-Encoding", "binary")
ctx.Resp.Header().Set("Expires", "0")
ctx.Resp.Header().Set("Cache-Control", "must-revalidate")
ctx.Resp.Header().Set("Pragma", "public")
http.ServeFile(ctx.Resp, ctx.Req.Request, file)
}
// ChangeStaticPath changes static path from old to new one.
func (ctx *Context) ChangeStaticPath(oldPath, newPath string) {
if !filepath.IsAbs(oldPath) {
oldPath = filepath.Join(Root, oldPath)
}
dir := statics.Get(oldPath)
if dir != nil {
statics.Delete(oldPath)
if !filepath.IsAbs(newPath) {
newPath = filepath.Join(Root, newPath)
}
*dir = http.Dir(newPath)
statics.Set(dir)
}
}
|
vendor/gopkg.in/macaron.v1/context.go
| 0 |
https://github.com/grafana/grafana/commit/dc3a81200b1cd366bdf237ada152ae3d79bdaf59
|
[
0.00025624671252444386,
0.00017507656593807042,
0.000162957061547786,
0.0001745291956467554,
0.000011958653885812964
] |
{
"id": 0,
"code_window": [
"import { DashboardRow } from './DashboardRow';\n",
"import { AddPanelPanel } from './AddPanelPanel';\n",
"import { importPluginModule } from 'app/features/plugins/plugin_loader';\n",
"import { PluginExports } from 'app/types/plugins';\n",
"import { PanelChrome } from './PanelChrome';\n",
"import { PanelEditor } from './PanelEditor';\n",
"\n",
"export interface Props {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { PluginExports, PanelPlugin } from 'app/types/plugins';\n"
],
"file_path": "public/app/features/dashboard/dashgrid/DashboardPanel.tsx",
"type": "replace",
"edit_start_line_idx": 8
}
|
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build amd64,darwin
package unix
import (
"syscall"
"unsafe"
)
func setTimespec(sec, nsec int64) Timespec {
return Timespec{Sec: sec, Nsec: nsec}
}
func setTimeval(sec, usec int64) Timeval {
return Timeval{Sec: sec, Usec: int32(usec)}
}
//sysnb gettimeofday(tp *Timeval) (sec int64, usec int32, err error)
func Gettimeofday(tv *Timeval) (err error) {
// The tv passed to gettimeofday must be non-nil
// but is otherwise unused. The answers come back
// in the two registers.
sec, usec, err := gettimeofday(tv)
tv.Sec = sec
tv.Usec = usec
return err
}
func SetKevent(k *Kevent_t, fd, mode, flags int) {
k.Ident = uint64(fd)
k.Filter = int16(mode)
k.Flags = uint16(flags)
}
func (iov *Iovec) SetLen(length int) {
iov.Len = uint64(length)
}
func (msghdr *Msghdr) SetControllen(length int) {
msghdr.Controllen = uint32(length)
}
func (cmsg *Cmsghdr) SetLen(length int) {
cmsg.Len = uint32(length)
}
func sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) {
var length = uint64(count)
_, _, e1 := Syscall6(SYS_SENDFILE, uintptr(infd), uintptr(outfd), uintptr(*offset), uintptr(unsafe.Pointer(&length)), 0, 0)
written = int(length)
if e1 != 0 {
err = e1
}
return
}
func Syscall9(num, a1, a2, a3, a4, a5, a6, a7, a8, a9 uintptr) (r1, r2 uintptr, err syscall.Errno)
// SYS___SYSCTL is used by syscall_bsd.go for all BSDs, but in modern versions
// of darwin/amd64 the syscall is called sysctl instead of __sysctl.
const SYS___SYSCTL = SYS_SYSCTL
|
vendor/golang.org/x/sys/unix/syscall_darwin_amd64.go
| 0 |
https://github.com/grafana/grafana/commit/dc3a81200b1cd366bdf237ada152ae3d79bdaf59
|
[
0.00018131485558114946,
0.00017672199464868754,
0.0001678232365520671,
0.00017812145233619958,
0.000004241995611664606
] |
{
"id": 0,
"code_window": [
"import { DashboardRow } from './DashboardRow';\n",
"import { AddPanelPanel } from './AddPanelPanel';\n",
"import { importPluginModule } from 'app/features/plugins/plugin_loader';\n",
"import { PluginExports } from 'app/types/plugins';\n",
"import { PanelChrome } from './PanelChrome';\n",
"import { PanelEditor } from './PanelEditor';\n",
"\n",
"export interface Props {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { PluginExports, PanelPlugin } from 'app/types/plugins';\n"
],
"file_path": "public/app/features/dashboard/dashgrid/DashboardPanel.tsx",
"type": "replace",
"edit_start_line_idx": 8
}
|
FROM centos:centos7
LABEL maintainer="Przemyslaw Ozgo <[email protected]>"
RUN \
yum update -y && \
yum install -y net-snmp net-snmp-utils && \
yum clean all
COPY bootstrap.sh /tmp/bootstrap.sh
EXPOSE 161
ENTRYPOINT ["/tmp/bootstrap.sh"]
|
docker/blocks/smtp/Dockerfile
| 0 |
https://github.com/grafana/grafana/commit/dc3a81200b1cd366bdf237ada152ae3d79bdaf59
|
[
0.00017463837866671383,
0.00017192261293530464,
0.00016920684720389545,
0.00017192261293530464,
0.000002715765731409192
] |
{
"id": 1,
"code_window": [
" pluginInfo: any;\n",
" specialPanels = {};\n",
"\n",
" constructor(props) {\n",
" super(props);\n",
" this.state = { pluginExports: null };\n",
"\n",
" this.specialPanels['row'] = this.renderRow.bind(this);\n",
" this.specialPanels['add-panel'] = this.renderAddPanel.bind(this);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
" this.state = {\n",
" pluginExports: null,\n",
" };\n"
],
"file_path": "public/app/features/dashboard/dashgrid/DashboardPanel.tsx",
"type": "replace",
"edit_start_line_idx": 29
}
|
import React from 'react';
import config from 'app/core/config';
import { PanelModel } from '../panel_model';
import { DashboardModel } from '../dashboard_model';
import { getAngularLoader, AngularComponent } from 'app/core/services/angular_loader';
import { DashboardRow } from './DashboardRow';
import { AddPanelPanel } from './AddPanelPanel';
import { importPluginModule } from 'app/features/plugins/plugin_loader';
import { PluginExports } from 'app/types/plugins';
import { PanelChrome } from './PanelChrome';
import { PanelEditor } from './PanelEditor';
export interface Props {
panel: PanelModel;
dashboard: DashboardModel;
}
export interface State {
pluginExports: PluginExports;
}
export class DashboardPanel extends React.Component<Props, State> {
element: any;
angularPanel: AngularComponent;
pluginInfo: any;
specialPanels = {};
constructor(props) {
super(props);
this.state = { pluginExports: null };
this.specialPanels['row'] = this.renderRow.bind(this);
this.specialPanels['add-panel'] = this.renderAddPanel.bind(this);
this.props.panel.events.on('panel-size-changed', this.triggerForceUpdate.bind(this));
}
triggerForceUpdate() {
this.forceUpdate();
}
isSpecial() {
return this.specialPanels[this.props.panel.type];
}
renderRow() {
return <DashboardRow panel={this.props.panel} dashboard={this.props.dashboard} />;
}
renderAddPanel() {
return <AddPanelPanel panel={this.props.panel} dashboard={this.props.dashboard} />;
}
loadPlugin() {
if (this.isSpecial()) {
return;
}
// handle plugin loading & changing of plugin type
if (!this.pluginInfo || this.pluginInfo.id !== this.props.panel.type) {
this.pluginInfo = config.panels[this.props.panel.type];
if (this.pluginInfo.exports) {
this.setState({ pluginExports: this.pluginInfo.exports });
} else {
importPluginModule(this.pluginInfo.module).then(pluginExports => {
this.setState({ pluginExports: pluginExports });
});
}
}
}
componentDidMount() {
this.loadPlugin();
}
componentDidUpdate() {
this.loadPlugin();
// handle angular plugin loading
if (!this.element || this.angularPanel) {
return;
}
let loader = getAngularLoader();
var template = '<plugin-component type="panel" class="panel-height-helper"></plugin-component>';
let scopeProps = { panel: this.props.panel, dashboard: this.props.dashboard };
this.angularPanel = loader.load(this.element, scopeProps, template);
}
componentWillUnmount() {
if (this.angularPanel) {
this.angularPanel.destroy();
}
}
renderReactPanel() {
const { pluginExports } = this.state;
const containerClass = this.props.panel.isEditing ? 'panel-editor-container' : 'panel-height-helper';
const panelWrapperClass = this.props.panel.isEditing ? 'panel-editor-container__panel' : 'panel-height-helper';
// this might look strange with these classes that change when edit, but
// I want to try to keep markup (parents) for panel the same in edit mode to avoide unmount / new mount of panel
// plugin component
return (
<div className={containerClass}>
<div className={panelWrapperClass}>
<PanelChrome
component={pluginExports.PanelComponent}
panel={this.props.panel}
dashboard={this.props.dashboard}
/>
</div>
{this.props.panel.isEditing && (
<div className="panel-editor-container__editor">
<PanelEditor panel={this.props.panel} dashboard={this.props.dashboard} />
</div>
)}
</div>
);
}
render() {
if (this.isSpecial()) {
return this.specialPanels[this.props.panel.type]();
}
if (!this.state.pluginExports) {
return null;
}
if (this.state.pluginExports.PanelComponent) {
return this.renderReactPanel();
}
// legacy angular rendering
return <div ref={element => (this.element = element)} className="panel-height-helper" />;
}
}
|
public/app/features/dashboard/dashgrid/DashboardPanel.tsx
| 1 |
https://github.com/grafana/grafana/commit/dc3a81200b1cd366bdf237ada152ae3d79bdaf59
|
[
0.9977626800537109,
0.1945669949054718,
0.00019690170302055776,
0.00190864282194525,
0.3724001944065094
] |
{
"id": 1,
"code_window": [
" pluginInfo: any;\n",
" specialPanels = {};\n",
"\n",
" constructor(props) {\n",
" super(props);\n",
" this.state = { pluginExports: null };\n",
"\n",
" this.specialPanels['row'] = this.renderRow.bind(this);\n",
" this.specialPanels['add-panel'] = this.renderAddPanel.bind(this);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
" this.state = {\n",
" pluginExports: null,\n",
" };\n"
],
"file_path": "public/app/features/dashboard/dashgrid/DashboardPanel.tsx",
"type": "replace",
"edit_start_line_idx": 29
}
|
package plugin
import (
"syscall"
)
const (
// Weird name but matches the MSDN docs
exit_STILL_ACTIVE = 259
processDesiredAccess = syscall.STANDARD_RIGHTS_READ |
syscall.PROCESS_QUERY_INFORMATION |
syscall.SYNCHRONIZE
)
// _pidAlive tests whether a process is alive or not
func _pidAlive(pid int) bool {
h, err := syscall.OpenProcess(processDesiredAccess, false, uint32(pid))
if err != nil {
return false
}
var ec uint32
if e := syscall.GetExitCodeProcess(h, &ec); e != nil {
return false
}
return ec == exit_STILL_ACTIVE
}
|
vendor/github.com/hashicorp/go-plugin/process_windows.go
| 0 |
https://github.com/grafana/grafana/commit/dc3a81200b1cd366bdf237ada152ae3d79bdaf59
|
[
0.000177560665179044,
0.0001728950737742707,
0.00016662910638842732,
0.00017449542065151036,
0.0000046040272536629345
] |
{
"id": 1,
"code_window": [
" pluginInfo: any;\n",
" specialPanels = {};\n",
"\n",
" constructor(props) {\n",
" super(props);\n",
" this.state = { pluginExports: null };\n",
"\n",
" this.specialPanels['row'] = this.renderRow.bind(this);\n",
" this.specialPanels['add-panel'] = this.renderAddPanel.bind(this);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
" this.state = {\n",
" pluginExports: null,\n",
" };\n"
],
"file_path": "public/app/features/dashboard/dashgrid/DashboardPanel.tsx",
"type": "replace",
"edit_start_line_idx": 29
}
|
#start SQL Server and run setup script
/usr/setup/setup.sh & /opt/mssql/bin/sqlservr
|
docker/blocks/mssql/build/entrypoint.sh
| 0 |
https://github.com/grafana/grafana/commit/dc3a81200b1cd366bdf237ada152ae3d79bdaf59
|
[
0.00017189446953125298,
0.00017189446953125298,
0.00017189446953125298,
0.00017189446953125298,
0
] |
{
"id": 1,
"code_window": [
" pluginInfo: any;\n",
" specialPanels = {};\n",
"\n",
" constructor(props) {\n",
" super(props);\n",
" this.state = { pluginExports: null };\n",
"\n",
" this.specialPanels['row'] = this.renderRow.bind(this);\n",
" this.specialPanels['add-panel'] = this.renderAddPanel.bind(this);\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
"\n",
" this.state = {\n",
" pluginExports: null,\n",
" };\n"
],
"file_path": "public/app/features/dashboard/dashgrid/DashboardPanel.tsx",
"type": "replace",
"edit_start_line_idx": 29
}
|
<?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 19.1.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
<svg version="1.1" baseProfile="tiny" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"
x="0px" y="0px" width="70px" height="70px" viewBox="15 -15 70 70" xml:space="preserve">
<g>
<path fill="#F79520" d="M41.39,43.607l1.908-1.91l3.677,3.678l-1.91,1.91L41.39,43.607z M21.635,23.795l1.91-1.91l3.677,3.678
l-1.91,1.91L21.635,23.795z M47.8-4.9l1.9-1.9c-1.3-1.2-2.8-2.2-4.3-3l-2,2C45-7,46.4-6.1,47.8-4.9z M35.7-9.5c2,0,4,0.3,5.8,1
l2.1-2.1c-1.9-0.8-3.8-1.3-5.9-1.5l-2.6,2.6H35.7z M17.7,8.6V8l-2.6,2.6c0.2,2,0.7,4,1.5,5.9l2.1-2.1C18,12.6,17.7,10.6,17.7,8.6z
M23-4.2c2.6-2.6,5.8-4.3,9.4-5l3-3c-3.7,0.1-7.2,1.1-10.3,3L18-2.1C16.1,1,15.1,4.5,15,8.2l3-3C18.7,1.7,20.4-1.6,23-4.2z
M19.4,16.2l-2,2c0.8,1.5,1.8,3,3,4.3l1.9-1.9C21.1,19.3,20.1,17.8,19.4,16.2z M36.433,38.6l1.91-1.908l3.676,3.677l-1.91,1.908
L36.433,38.6z M82.4,8.6c0,0.5,0,0.9-0.1,1.4L85,7.3c-0.1-2.1-0.6-4.1-1.3-6l-2.1,2.1C82.1,5,82.4,6.8,82.4,8.6z M85,9.8L81.8,13
c-0.8,3.1-2.4,6-4.7,8.3L50,48.4l-1.8-1.8l-1.9,1.9l3.7,3.7l29.9-29.9C83,18.8,84.7,14.4,85,9.8z M26.59,28.8l1.91-1.908
l3.677,3.677l-1.91,1.908L26.59,28.8z M31.477,33.737l1.91-1.91l3.676,3.677l-1.91,1.91L31.477,33.737z M70.9-8.2l2-2
c-1.8-0.8-3.7-1.4-5.7-1.7l-2.5,2.5C66.9-9.4,69-9,70.9-8.2z M50-2.7l1.5-1.5c2.9-2.9,6.6-4.7,10.6-5.2l2.8-2.8h-0.6
c-3,0-5.8,0.6-8.5,1.8l-6.7,6.7L50-2.7z M76.9-4.4l1.9-1.9c-1.3-1.2-2.7-2.3-4.2-3.2l-2,2C74.2-6.6,75.6-5.6,76.9-4.4z M80.9,1.5
l2-2c-0.8-1.6-1.7-3.1-2.9-4.4L78.1-3C79.3-1.7,80.2-0.1,80.9,1.5z M26.8-0.4c-2.4,2.4-3.7,5.6-3.7,9c0,0.5,0,0.9,0.1,1.3l14-14
c-0.4,0-0.9-0.1-1.3-0.1C32.4-4.1,29.2-2.8,26.8-0.4z M23.5,12c0.5,1.7,1.4,3.4,2.6,4.8L44-1.1c-1.4-1.2-3-2.1-4.8-2.6L23.5,12z
M73.3,17.6c2.4-2.4,3.7-5.6,3.7-9V8L47.1,37.9l2.9,2.9C50,40.8,73.3,17.6,73.3,17.6z M37.2,28l3.7,3.7L73.1-0.5
c-1.3-1.3-2.9-2.2-4.5-2.8L37.2,28z M57.4-2L32.3,23.1l3.7,3.7L66.6-3.8C65.9-3.9,65.1-4,64.3-4C61.8-4.1,59.4-3.4,57.4-2z
M42.1,32.9l3.7,3.7L76.6,5.8c-0.4-1.8-1.2-3.5-2.4-5L42.1,32.9z M46.2,1.1l-0.9-0.9l-18,17.9l3.7,3.7l17.9-18L48.1,3"/>
</g>
</svg>
|
public/img/warn.svg
| 0 |
https://github.com/grafana/grafana/commit/dc3a81200b1cd366bdf237ada152ae3d79bdaf59
|
[
0.0002472180058248341,
0.0001996340579353273,
0.0001749459042912349,
0.0001767382345860824,
0.000033654894650680944
] |
{
"id": 2,
"code_window": [
"\n",
" this.specialPanels['row'] = this.renderRow.bind(this);\n",
" this.specialPanels['add-panel'] = this.renderAddPanel.bind(this);\n",
" this.props.panel.events.on('panel-size-changed', this.triggerForceUpdate.bind(this));\n",
" }\n",
"\n",
" triggerForceUpdate() {\n",
" this.forceUpdate();\n",
" }\n",
"\n",
" isSpecial() {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "public/app/features/dashboard/dashgrid/DashboardPanel.tsx",
"type": "replace",
"edit_start_line_idx": 33
}
|
import React from 'react';
import config from 'app/core/config';
import { PanelModel } from '../panel_model';
import { DashboardModel } from '../dashboard_model';
import { getAngularLoader, AngularComponent } from 'app/core/services/angular_loader';
import { DashboardRow } from './DashboardRow';
import { AddPanelPanel } from './AddPanelPanel';
import { importPluginModule } from 'app/features/plugins/plugin_loader';
import { PluginExports } from 'app/types/plugins';
import { PanelChrome } from './PanelChrome';
import { PanelEditor } from './PanelEditor';
export interface Props {
panel: PanelModel;
dashboard: DashboardModel;
}
export interface State {
pluginExports: PluginExports;
}
export class DashboardPanel extends React.Component<Props, State> {
element: any;
angularPanel: AngularComponent;
pluginInfo: any;
specialPanels = {};
constructor(props) {
super(props);
this.state = { pluginExports: null };
this.specialPanels['row'] = this.renderRow.bind(this);
this.specialPanels['add-panel'] = this.renderAddPanel.bind(this);
this.props.panel.events.on('panel-size-changed', this.triggerForceUpdate.bind(this));
}
triggerForceUpdate() {
this.forceUpdate();
}
isSpecial() {
return this.specialPanels[this.props.panel.type];
}
renderRow() {
return <DashboardRow panel={this.props.panel} dashboard={this.props.dashboard} />;
}
renderAddPanel() {
return <AddPanelPanel panel={this.props.panel} dashboard={this.props.dashboard} />;
}
loadPlugin() {
if (this.isSpecial()) {
return;
}
// handle plugin loading & changing of plugin type
if (!this.pluginInfo || this.pluginInfo.id !== this.props.panel.type) {
this.pluginInfo = config.panels[this.props.panel.type];
if (this.pluginInfo.exports) {
this.setState({ pluginExports: this.pluginInfo.exports });
} else {
importPluginModule(this.pluginInfo.module).then(pluginExports => {
this.setState({ pluginExports: pluginExports });
});
}
}
}
componentDidMount() {
this.loadPlugin();
}
componentDidUpdate() {
this.loadPlugin();
// handle angular plugin loading
if (!this.element || this.angularPanel) {
return;
}
let loader = getAngularLoader();
var template = '<plugin-component type="panel" class="panel-height-helper"></plugin-component>';
let scopeProps = { panel: this.props.panel, dashboard: this.props.dashboard };
this.angularPanel = loader.load(this.element, scopeProps, template);
}
componentWillUnmount() {
if (this.angularPanel) {
this.angularPanel.destroy();
}
}
renderReactPanel() {
const { pluginExports } = this.state;
const containerClass = this.props.panel.isEditing ? 'panel-editor-container' : 'panel-height-helper';
const panelWrapperClass = this.props.panel.isEditing ? 'panel-editor-container__panel' : 'panel-height-helper';
// this might look strange with these classes that change when edit, but
// I want to try to keep markup (parents) for panel the same in edit mode to avoide unmount / new mount of panel
// plugin component
return (
<div className={containerClass}>
<div className={panelWrapperClass}>
<PanelChrome
component={pluginExports.PanelComponent}
panel={this.props.panel}
dashboard={this.props.dashboard}
/>
</div>
{this.props.panel.isEditing && (
<div className="panel-editor-container__editor">
<PanelEditor panel={this.props.panel} dashboard={this.props.dashboard} />
</div>
)}
</div>
);
}
render() {
if (this.isSpecial()) {
return this.specialPanels[this.props.panel.type]();
}
if (!this.state.pluginExports) {
return null;
}
if (this.state.pluginExports.PanelComponent) {
return this.renderReactPanel();
}
// legacy angular rendering
return <div ref={element => (this.element = element)} className="panel-height-helper" />;
}
}
|
public/app/features/dashboard/dashgrid/DashboardPanel.tsx
| 1 |
https://github.com/grafana/grafana/commit/dc3a81200b1cd366bdf237ada152ae3d79bdaf59
|
[
0.9981202483177185,
0.0728418305516243,
0.00016444695938844234,
0.0009312295005656779,
0.25663289427757263
] |
{
"id": 2,
"code_window": [
"\n",
" this.specialPanels['row'] = this.renderRow.bind(this);\n",
" this.specialPanels['add-panel'] = this.renderAddPanel.bind(this);\n",
" this.props.panel.events.on('panel-size-changed', this.triggerForceUpdate.bind(this));\n",
" }\n",
"\n",
" triggerForceUpdate() {\n",
" this.forceUpdate();\n",
" }\n",
"\n",
" isSpecial() {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "public/app/features/dashboard/dashgrid/DashboardPanel.tsx",
"type": "replace",
"edit_start_line_idx": 33
}
|
package api
import (
"context"
"crypto/rand"
"crypto/tls"
"crypto/x509"
"encoding/base64"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"golang.org/x/oauth2"
"github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/log"
"github.com/grafana/grafana/pkg/login"
"github.com/grafana/grafana/pkg/metrics"
m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/session"
"github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/social"
)
var oauthLogger = log.New("oauth")
func GenStateString() string {
rnd := make([]byte, 32)
rand.Read(rnd)
return base64.URLEncoding.EncodeToString(rnd)
}
func OAuthLogin(ctx *m.ReqContext) {
if setting.OAuthService == nil {
ctx.Handle(404, "OAuth not enabled", nil)
return
}
name := ctx.Params(":name")
connect, ok := social.SocialMap[name]
if !ok {
ctx.Handle(404, fmt.Sprintf("No OAuth with name %s configured", name), nil)
return
}
errorParam := ctx.Query("error")
if errorParam != "" {
errorDesc := ctx.Query("error_description")
oauthLogger.Error("failed to login ", "error", errorParam, "errorDesc", errorDesc)
redirectWithError(ctx, login.ErrProviderDeniedRequest, "error", errorParam, "errorDesc", errorDesc)
return
}
code := ctx.Query("code")
if code == "" {
state := GenStateString()
ctx.Session.Set(session.SESS_KEY_OAUTH_STATE, state)
if setting.OAuthService.OAuthInfos[name].HostedDomain == "" {
ctx.Redirect(connect.AuthCodeURL(state, oauth2.AccessTypeOnline))
} else {
ctx.Redirect(connect.AuthCodeURL(state, oauth2.SetAuthURLParam("hd", setting.OAuthService.OAuthInfos[name].HostedDomain), oauth2.AccessTypeOnline))
}
return
}
savedState, ok := ctx.Session.Get(session.SESS_KEY_OAUTH_STATE).(string)
if !ok {
ctx.Handle(500, "login.OAuthLogin(missing saved state)", nil)
return
}
queryState := ctx.Query("state")
if savedState != queryState {
ctx.Handle(500, "login.OAuthLogin(state mismatch)", nil)
return
}
// handle call back
tr := &http.Transport{
Proxy: http.ProxyFromEnvironment,
TLSClientConfig: &tls.Config{
InsecureSkipVerify: setting.OAuthService.OAuthInfos[name].TlsSkipVerify,
},
}
oauthClient := &http.Client{
Transport: tr,
}
if setting.OAuthService.OAuthInfos[name].TlsClientCert != "" || setting.OAuthService.OAuthInfos[name].TlsClientKey != "" {
cert, err := tls.LoadX509KeyPair(setting.OAuthService.OAuthInfos[name].TlsClientCert, setting.OAuthService.OAuthInfos[name].TlsClientKey)
if err != nil {
ctx.Logger.Error("Failed to setup TlsClientCert", "oauth", name, "error", err)
ctx.Handle(500, "login.OAuthLogin(Failed to setup TlsClientCert)", nil)
return
}
tr.TLSClientConfig.Certificates = append(tr.TLSClientConfig.Certificates, cert)
}
if setting.OAuthService.OAuthInfos[name].TlsClientCa != "" {
caCert, err := ioutil.ReadFile(setting.OAuthService.OAuthInfos[name].TlsClientCa)
if err != nil {
ctx.Logger.Error("Failed to setup TlsClientCa", "oauth", name, "error", err)
ctx.Handle(500, "login.OAuthLogin(Failed to setup TlsClientCa)", nil)
return
}
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM(caCert)
tr.TLSClientConfig.RootCAs = caCertPool
}
oauthCtx := context.WithValue(context.Background(), oauth2.HTTPClient, oauthClient)
// get token from provider
token, err := connect.Exchange(oauthCtx, code)
if err != nil {
ctx.Handle(500, "login.OAuthLogin(NewTransportWithCode)", err)
return
}
// token.TokenType was defaulting to "bearer", which is out of spec, so we explicitly set to "Bearer"
token.TokenType = "Bearer"
oauthLogger.Debug("OAuthLogin Got token", "token", token)
// set up oauth2 client
client := connect.Client(oauthCtx, token)
// get user info
userInfo, err := connect.UserInfo(client, token)
if err != nil {
if sErr, ok := err.(*social.Error); ok {
redirectWithError(ctx, sErr)
} else {
ctx.Handle(500, fmt.Sprintf("login.OAuthLogin(get info from %s)", name), err)
}
return
}
oauthLogger.Debug("OAuthLogin got user info", "userInfo", userInfo)
// validate that we got at least an email address
if userInfo.Email == "" {
redirectWithError(ctx, login.ErrNoEmail)
return
}
// validate that the email is allowed to login to grafana
if !connect.IsEmailAllowed(userInfo.Email) {
redirectWithError(ctx, login.ErrEmailNotAllowed)
return
}
extUser := &m.ExternalUserInfo{
AuthModule: "oauth_" + name,
AuthId: userInfo.Id,
Name: userInfo.Name,
Login: userInfo.Login,
Email: userInfo.Email,
OrgRoles: map[int64]m.RoleType{},
}
if userInfo.Role != "" {
extUser.OrgRoles[1] = m.RoleType(userInfo.Role)
}
// add/update user in grafana
cmd := &m.UpsertUserCommand{
ReqContext: ctx,
ExternalUser: extUser,
SignupAllowed: connect.IsSignupAllowed(),
}
err = bus.Dispatch(cmd)
if err != nil {
redirectWithError(ctx, err)
return
}
// login
loginUserWithUser(cmd.Result, ctx)
metrics.M_Api_Login_OAuth.Inc()
if redirectTo, _ := url.QueryUnescape(ctx.GetCookie("redirect_to")); len(redirectTo) > 0 {
ctx.SetCookie("redirect_to", "", -1, setting.AppSubUrl+"/")
ctx.Redirect(redirectTo)
return
}
ctx.Redirect(setting.AppSubUrl + "/")
}
func redirectWithError(ctx *m.ReqContext, err error, v ...interface{}) {
ctx.Logger.Error(err.Error(), v...)
ctx.Session.Set("loginError", err.Error())
ctx.Redirect(setting.AppSubUrl + "/login")
}
|
pkg/api/login_oauth.go
| 0 |
https://github.com/grafana/grafana/commit/dc3a81200b1cd366bdf237ada152ae3d79bdaf59
|
[
0.00017715276044327766,
0.0001737772108754143,
0.00016982703527901322,
0.00017366331303492188,
0.0000017686893443169538
] |
{
"id": 2,
"code_window": [
"\n",
" this.specialPanels['row'] = this.renderRow.bind(this);\n",
" this.specialPanels['add-panel'] = this.renderAddPanel.bind(this);\n",
" this.props.panel.events.on('panel-size-changed', this.triggerForceUpdate.bind(this));\n",
" }\n",
"\n",
" triggerForceUpdate() {\n",
" this.forceUpdate();\n",
" }\n",
"\n",
" isSpecial() {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "public/app/features/dashboard/dashgrid/DashboardPanel.tsx",
"type": "replace",
"edit_start_line_idx": 33
}
|
+++
title = "Administration"
description = "Administration"
type = "docs"
[menu.docs]
name = "Administration"
identifier = "admin"
weight = 2
+++
|
docs/sources/administration/index.md
| 0 |
https://github.com/grafana/grafana/commit/dc3a81200b1cd366bdf237ada152ae3d79bdaf59
|
[
0.00017778987239580601,
0.0001726220070850104,
0.0001674541417742148,
0.0001726220070850104,
0.000005167865310795605
] |
{
"id": 2,
"code_window": [
"\n",
" this.specialPanels['row'] = this.renderRow.bind(this);\n",
" this.specialPanels['add-panel'] = this.renderAddPanel.bind(this);\n",
" this.props.panel.events.on('panel-size-changed', this.triggerForceUpdate.bind(this));\n",
" }\n",
"\n",
" triggerForceUpdate() {\n",
" this.forceUpdate();\n",
" }\n",
"\n",
" isSpecial() {\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "public/app/features/dashboard/dashgrid/DashboardPanel.tsx",
"type": "replace",
"edit_start_line_idx": 33
}
|
// Copyright 2011 Aaron Jacobs. All Rights Reserved.
// Author: [email protected] (Aaron Jacobs)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package oglematchers provides a set of matchers useful in a testing or
// mocking framework. These matchers are inspired by and mostly compatible with
// Google Test for C++ and Google JS Test.
//
// This package is used by github.com/smartystreets/assertions/internal/ogletest and
// github.com/smartystreets/assertions/internal/oglemock, which may be more directly useful if you're not
// writing your own testing package or defining your own matchers.
package oglematchers
// A Matcher is some predicate implicitly defining a set of values that it
// matches. For example, GreaterThan(17) matches all numeric values greater
// than 17, and HasSubstr("taco") matches all strings with the substring
// "taco".
//
// Matchers are typically exposed to tests via constructor functions like
// HasSubstr. In order to implement such a function you can either define your
// own matcher type or use NewMatcher.
type Matcher interface {
// Check whether the supplied value belongs to the the set defined by the
// matcher. Return a non-nil error if and only if it does not.
//
// The error describes why the value doesn't match. The error text is a
// relative clause that is suitable for being placed after the value. For
// example, a predicate that matches strings with a particular substring may,
// when presented with a numerical value, return the following error text:
//
// "which is not a string"
//
// Then the failure message may look like:
//
// Expected: has substring "taco"
// Actual: 17, which is not a string
//
// If the error is self-apparent based on the description of the matcher, the
// error text may be empty (but the error still non-nil). For example:
//
// Expected: 17
// Actual: 19
//
// If you are implementing a new matcher, see also the documentation on
// FatalError.
Matches(candidate interface{}) error
// Description returns a string describing the property that values matching
// this matcher have, as a verb phrase where the subject is the value. For
// example, "is greather than 17" or "has substring "taco"".
Description() string
}
// FatalError is an implementation of the error interface that may be returned
// from matchers, indicating the error should be propagated. Returning a
// *FatalError indicates that the matcher doesn't process values of the
// supplied type, or otherwise doesn't know how to handle the value.
//
// For example, if GreaterThan(17) returned false for the value "taco" without
// a fatal error, then Not(GreaterThan(17)) would return true. This is
// technically correct, but is surprising and may mask failures where the wrong
// sort of matcher is accidentally used. Instead, GreaterThan(17) can return a
// fatal error, which will be propagated by Not().
type FatalError struct {
errorText string
}
// NewFatalError creates a FatalError struct with the supplied error text.
func NewFatalError(s string) *FatalError {
return &FatalError{s}
}
func (e *FatalError) Error() string {
return e.errorText
}
|
vendor/github.com/smartystreets/assertions/internal/oglematchers/matcher.go
| 0 |
https://github.com/grafana/grafana/commit/dc3a81200b1cd366bdf237ada152ae3d79bdaf59
|
[
0.0003655347682069987,
0.0001955551269929856,
0.00016557476192247123,
0.00017745810328051448,
0.000060246933571761474
] |
{
"id": 3,
"code_window": [
" return <AddPanelPanel panel={this.props.panel} dashboard={this.props.dashboard} />;\n",
" }\n",
"\n",
" loadPlugin() {\n",
" if (this.isSpecial()) {\n",
" return;\n",
" }\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" onPluginTypeChanged = (plugin: PanelPlugin) => {\n",
" this.props.panel.changeType(plugin.id);\n",
" this.loadPlugin();\n",
" };\n",
"\n"
],
"file_path": "public/app/features/dashboard/dashgrid/DashboardPanel.tsx",
"type": "add",
"edit_start_line_idx": 52
}
|
import React from 'react';
import config from 'app/core/config';
import { PanelModel } from '../panel_model';
import { DashboardModel } from '../dashboard_model';
import { getAngularLoader, AngularComponent } from 'app/core/services/angular_loader';
import { DashboardRow } from './DashboardRow';
import { AddPanelPanel } from './AddPanelPanel';
import { importPluginModule } from 'app/features/plugins/plugin_loader';
import { PluginExports } from 'app/types/plugins';
import { PanelChrome } from './PanelChrome';
import { PanelEditor } from './PanelEditor';
export interface Props {
panel: PanelModel;
dashboard: DashboardModel;
}
export interface State {
pluginExports: PluginExports;
}
export class DashboardPanel extends React.Component<Props, State> {
element: any;
angularPanel: AngularComponent;
pluginInfo: any;
specialPanels = {};
constructor(props) {
super(props);
this.state = { pluginExports: null };
this.specialPanels['row'] = this.renderRow.bind(this);
this.specialPanels['add-panel'] = this.renderAddPanel.bind(this);
this.props.panel.events.on('panel-size-changed', this.triggerForceUpdate.bind(this));
}
triggerForceUpdate() {
this.forceUpdate();
}
isSpecial() {
return this.specialPanels[this.props.panel.type];
}
renderRow() {
return <DashboardRow panel={this.props.panel} dashboard={this.props.dashboard} />;
}
renderAddPanel() {
return <AddPanelPanel panel={this.props.panel} dashboard={this.props.dashboard} />;
}
loadPlugin() {
if (this.isSpecial()) {
return;
}
// handle plugin loading & changing of plugin type
if (!this.pluginInfo || this.pluginInfo.id !== this.props.panel.type) {
this.pluginInfo = config.panels[this.props.panel.type];
if (this.pluginInfo.exports) {
this.setState({ pluginExports: this.pluginInfo.exports });
} else {
importPluginModule(this.pluginInfo.module).then(pluginExports => {
this.setState({ pluginExports: pluginExports });
});
}
}
}
componentDidMount() {
this.loadPlugin();
}
componentDidUpdate() {
this.loadPlugin();
// handle angular plugin loading
if (!this.element || this.angularPanel) {
return;
}
let loader = getAngularLoader();
var template = '<plugin-component type="panel" class="panel-height-helper"></plugin-component>';
let scopeProps = { panel: this.props.panel, dashboard: this.props.dashboard };
this.angularPanel = loader.load(this.element, scopeProps, template);
}
componentWillUnmount() {
if (this.angularPanel) {
this.angularPanel.destroy();
}
}
renderReactPanel() {
const { pluginExports } = this.state;
const containerClass = this.props.panel.isEditing ? 'panel-editor-container' : 'panel-height-helper';
const panelWrapperClass = this.props.panel.isEditing ? 'panel-editor-container__panel' : 'panel-height-helper';
// this might look strange with these classes that change when edit, but
// I want to try to keep markup (parents) for panel the same in edit mode to avoide unmount / new mount of panel
// plugin component
return (
<div className={containerClass}>
<div className={panelWrapperClass}>
<PanelChrome
component={pluginExports.PanelComponent}
panel={this.props.panel}
dashboard={this.props.dashboard}
/>
</div>
{this.props.panel.isEditing && (
<div className="panel-editor-container__editor">
<PanelEditor panel={this.props.panel} dashboard={this.props.dashboard} />
</div>
)}
</div>
);
}
render() {
if (this.isSpecial()) {
return this.specialPanels[this.props.panel.type]();
}
if (!this.state.pluginExports) {
return null;
}
if (this.state.pluginExports.PanelComponent) {
return this.renderReactPanel();
}
// legacy angular rendering
return <div ref={element => (this.element = element)} className="panel-height-helper" />;
}
}
|
public/app/features/dashboard/dashgrid/DashboardPanel.tsx
| 1 |
https://github.com/grafana/grafana/commit/dc3a81200b1cd366bdf237ada152ae3d79bdaf59
|
[
0.9987719655036926,
0.1619071215391159,
0.00016923896328080446,
0.012583150528371334,
0.34234821796417236
] |
{
"id": 3,
"code_window": [
" return <AddPanelPanel panel={this.props.panel} dashboard={this.props.dashboard} />;\n",
" }\n",
"\n",
" loadPlugin() {\n",
" if (this.isSpecial()) {\n",
" return;\n",
" }\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" onPluginTypeChanged = (plugin: PanelPlugin) => {\n",
" this.props.panel.changeType(plugin.id);\n",
" this.loadPlugin();\n",
" };\n",
"\n"
],
"file_path": "public/app/features/dashboard/dashgrid/DashboardPanel.tsx",
"type": "add",
"edit_start_line_idx": 52
}
|
// cgo -godefs -- -Wall -Werror -static -I/tmp/include linux/types.go | go run mkpost.go
// Code generated by the command above; see README.md. DO NOT EDIT.
// +build mipsle,linux
package unix
const (
sizeofPtr = 0x4
sizeofShort = 0x2
sizeofInt = 0x4
sizeofLong = 0x4
sizeofLongLong = 0x8
PathMax = 0x1000
)
type (
_C_short int16
_C_int int32
_C_long int32
_C_long_long int64
)
type Timespec struct {
Sec int32
Nsec int32
}
type Timeval struct {
Sec int32
Usec int32
}
type Timex struct {
Modes uint32
Offset int32
Freq int32
Maxerror int32
Esterror int32
Status int32
Constant int32
Precision int32
Tolerance int32
Time Timeval
Tick int32
Ppsfreq int32
Jitter int32
Shift int32
Stabil int32
Jitcnt int32
Calcnt int32
Errcnt int32
Stbcnt int32
Tai int32
_ [44]byte
}
type Time_t int32
type Tms struct {
Utime int32
Stime int32
Cutime int32
Cstime int32
}
type Utimbuf struct {
Actime int32
Modtime int32
}
type Rusage struct {
Utime Timeval
Stime Timeval
Maxrss int32
Ixrss int32
Idrss int32
Isrss int32
Minflt int32
Majflt int32
Nswap int32
Inblock int32
Oublock int32
Msgsnd int32
Msgrcv int32
Nsignals int32
Nvcsw int32
Nivcsw int32
}
type Rlimit struct {
Cur uint64
Max uint64
}
type _Gid_t uint32
type Stat_t struct {
Dev uint32
Pad1 [3]int32
Ino uint64
Mode uint32
Nlink uint32
Uid uint32
Gid uint32
Rdev uint32
Pad2 [3]int32
Size int64
Atim Timespec
Mtim Timespec
Ctim Timespec
Blksize int32
Pad4 int32
Blocks int64
Pad5 [14]int32
}
type StatxTimestamp struct {
Sec int64
Nsec uint32
_ int32
}
type Statx_t struct {
Mask uint32
Blksize uint32
Attributes uint64
Nlink uint32
Uid uint32
Gid uint32
Mode uint16
_ [1]uint16
Ino uint64
Size uint64
Blocks uint64
Attributes_mask uint64
Atime StatxTimestamp
Btime StatxTimestamp
Ctime StatxTimestamp
Mtime StatxTimestamp
Rdev_major uint32
Rdev_minor uint32
Dev_major uint32
Dev_minor uint32
_ [14]uint64
}
type Dirent struct {
Ino uint64
Off int64
Reclen uint16
Type uint8
Name [256]int8
_ [5]byte
}
type Fsid struct {
Val [2]int32
}
type Flock_t struct {
Type int16
Whence int16
_ [4]byte
Start int64
Len int64
Pid int32
_ [4]byte
}
type FscryptPolicy struct {
Version uint8
Contents_encryption_mode uint8
Filenames_encryption_mode uint8
Flags uint8
Master_key_descriptor [8]uint8
}
type FscryptKey struct {
Mode uint32
Raw [64]uint8
Size uint32
}
type KeyctlDHParams struct {
Private int32
Prime int32
Base int32
}
const (
FADV_NORMAL = 0x0
FADV_RANDOM = 0x1
FADV_SEQUENTIAL = 0x2
FADV_WILLNEED = 0x3
FADV_DONTNEED = 0x4
FADV_NOREUSE = 0x5
)
type RawSockaddrInet4 struct {
Family uint16
Port uint16
Addr [4]byte /* in_addr */
Zero [8]uint8
}
type RawSockaddrInet6 struct {
Family uint16
Port uint16
Flowinfo uint32
Addr [16]byte /* in6_addr */
Scope_id uint32
}
type RawSockaddrUnix struct {
Family uint16
Path [108]int8
}
type RawSockaddrLinklayer struct {
Family uint16
Protocol uint16
Ifindex int32
Hatype uint16
Pkttype uint8
Halen uint8
Addr [8]uint8
}
type RawSockaddrNetlink struct {
Family uint16
Pad uint16
Pid uint32
Groups uint32
}
type RawSockaddrHCI struct {
Family uint16
Dev uint16
Channel uint16
}
type RawSockaddrL2 struct {
Family uint16
Psm uint16
Bdaddr [6]uint8
Cid uint16
Bdaddr_type uint8
_ [1]byte
}
type RawSockaddrCAN struct {
Family uint16
_ [2]byte
Ifindex int32
Addr [8]byte
}
type RawSockaddrALG struct {
Family uint16
Type [14]uint8
Feat uint32
Mask uint32
Name [64]uint8
}
type RawSockaddrVM struct {
Family uint16
Reserved1 uint16
Port uint32
Cid uint32
Zero [4]uint8
}
type RawSockaddr struct {
Family uint16
Data [14]int8
}
type RawSockaddrAny struct {
Addr RawSockaddr
Pad [96]int8
}
type _Socklen uint32
type Linger struct {
Onoff int32
Linger int32
}
type Iovec struct {
Base *byte
Len uint32
}
type IPMreq struct {
Multiaddr [4]byte /* in_addr */
Interface [4]byte /* in_addr */
}
type IPMreqn struct {
Multiaddr [4]byte /* in_addr */
Address [4]byte /* in_addr */
Ifindex int32
}
type IPv6Mreq struct {
Multiaddr [16]byte /* in6_addr */
Interface uint32
}
type PacketMreq struct {
Ifindex int32
Type uint16
Alen uint16
Address [8]uint8
}
type Msghdr struct {
Name *byte
Namelen uint32
Iov *Iovec
Iovlen uint32
Control *byte
Controllen uint32
Flags int32
}
type Cmsghdr struct {
Len uint32
Level int32
Type int32
}
type Inet4Pktinfo struct {
Ifindex int32
Spec_dst [4]byte /* in_addr */
Addr [4]byte /* in_addr */
}
type Inet6Pktinfo struct {
Addr [16]byte /* in6_addr */
Ifindex uint32
}
type IPv6MTUInfo struct {
Addr RawSockaddrInet6
Mtu uint32
}
type ICMPv6Filter struct {
Data [8]uint32
}
type Ucred struct {
Pid int32
Uid uint32
Gid uint32
}
type TCPInfo struct {
State uint8
Ca_state uint8
Retransmits uint8
Probes uint8
Backoff uint8
Options uint8
_ [2]byte
Rto uint32
Ato uint32
Snd_mss uint32
Rcv_mss uint32
Unacked uint32
Sacked uint32
Lost uint32
Retrans uint32
Fackets uint32
Last_data_sent uint32
Last_ack_sent uint32
Last_data_recv uint32
Last_ack_recv uint32
Pmtu uint32
Rcv_ssthresh uint32
Rtt uint32
Rttvar uint32
Snd_ssthresh uint32
Snd_cwnd uint32
Advmss uint32
Reordering uint32
Rcv_rtt uint32
Rcv_space uint32
Total_retrans uint32
}
const (
SizeofSockaddrInet4 = 0x10
SizeofSockaddrInet6 = 0x1c
SizeofSockaddrAny = 0x70
SizeofSockaddrUnix = 0x6e
SizeofSockaddrLinklayer = 0x14
SizeofSockaddrNetlink = 0xc
SizeofSockaddrHCI = 0x6
SizeofSockaddrL2 = 0xe
SizeofSockaddrCAN = 0x10
SizeofSockaddrALG = 0x58
SizeofSockaddrVM = 0x10
SizeofLinger = 0x8
SizeofIovec = 0x8
SizeofIPMreq = 0x8
SizeofIPMreqn = 0xc
SizeofIPv6Mreq = 0x14
SizeofPacketMreq = 0x10
SizeofMsghdr = 0x1c
SizeofCmsghdr = 0xc
SizeofInet4Pktinfo = 0xc
SizeofInet6Pktinfo = 0x14
SizeofIPv6MTUInfo = 0x20
SizeofICMPv6Filter = 0x20
SizeofUcred = 0xc
SizeofTCPInfo = 0x68
)
const (
IFA_UNSPEC = 0x0
IFA_ADDRESS = 0x1
IFA_LOCAL = 0x2
IFA_LABEL = 0x3
IFA_BROADCAST = 0x4
IFA_ANYCAST = 0x5
IFA_CACHEINFO = 0x6
IFA_MULTICAST = 0x7
IFLA_UNSPEC = 0x0
IFLA_ADDRESS = 0x1
IFLA_BROADCAST = 0x2
IFLA_IFNAME = 0x3
IFLA_MTU = 0x4
IFLA_LINK = 0x5
IFLA_QDISC = 0x6
IFLA_STATS = 0x7
IFLA_COST = 0x8
IFLA_PRIORITY = 0x9
IFLA_MASTER = 0xa
IFLA_WIRELESS = 0xb
IFLA_PROTINFO = 0xc
IFLA_TXQLEN = 0xd
IFLA_MAP = 0xe
IFLA_WEIGHT = 0xf
IFLA_OPERSTATE = 0x10
IFLA_LINKMODE = 0x11
IFLA_LINKINFO = 0x12
IFLA_NET_NS_PID = 0x13
IFLA_IFALIAS = 0x14
IFLA_NUM_VF = 0x15
IFLA_VFINFO_LIST = 0x16
IFLA_STATS64 = 0x17
IFLA_VF_PORTS = 0x18
IFLA_PORT_SELF = 0x19
IFLA_AF_SPEC = 0x1a
IFLA_GROUP = 0x1b
IFLA_NET_NS_FD = 0x1c
IFLA_EXT_MASK = 0x1d
IFLA_PROMISCUITY = 0x1e
IFLA_NUM_TX_QUEUES = 0x1f
IFLA_NUM_RX_QUEUES = 0x20
IFLA_CARRIER = 0x21
IFLA_PHYS_PORT_ID = 0x22
IFLA_CARRIER_CHANGES = 0x23
IFLA_PHYS_SWITCH_ID = 0x24
IFLA_LINK_NETNSID = 0x25
IFLA_PHYS_PORT_NAME = 0x26
IFLA_PROTO_DOWN = 0x27
IFLA_GSO_MAX_SEGS = 0x28
IFLA_GSO_MAX_SIZE = 0x29
IFLA_PAD = 0x2a
IFLA_XDP = 0x2b
IFLA_EVENT = 0x2c
IFLA_NEW_NETNSID = 0x2d
IFLA_IF_NETNSID = 0x2e
IFLA_MAX = 0x31
RT_SCOPE_UNIVERSE = 0x0
RT_SCOPE_SITE = 0xc8
RT_SCOPE_LINK = 0xfd
RT_SCOPE_HOST = 0xfe
RT_SCOPE_NOWHERE = 0xff
RT_TABLE_UNSPEC = 0x0
RT_TABLE_COMPAT = 0xfc
RT_TABLE_DEFAULT = 0xfd
RT_TABLE_MAIN = 0xfe
RT_TABLE_LOCAL = 0xff
RT_TABLE_MAX = 0xffffffff
RTA_UNSPEC = 0x0
RTA_DST = 0x1
RTA_SRC = 0x2
RTA_IIF = 0x3
RTA_OIF = 0x4
RTA_GATEWAY = 0x5
RTA_PRIORITY = 0x6
RTA_PREFSRC = 0x7
RTA_METRICS = 0x8
RTA_MULTIPATH = 0x9
RTA_FLOW = 0xb
RTA_CACHEINFO = 0xc
RTA_TABLE = 0xf
RTN_UNSPEC = 0x0
RTN_UNICAST = 0x1
RTN_LOCAL = 0x2
RTN_BROADCAST = 0x3
RTN_ANYCAST = 0x4
RTN_MULTICAST = 0x5
RTN_BLACKHOLE = 0x6
RTN_UNREACHABLE = 0x7
RTN_PROHIBIT = 0x8
RTN_THROW = 0x9
RTN_NAT = 0xa
RTN_XRESOLVE = 0xb
RTNLGRP_NONE = 0x0
RTNLGRP_LINK = 0x1
RTNLGRP_NOTIFY = 0x2
RTNLGRP_NEIGH = 0x3
RTNLGRP_TC = 0x4
RTNLGRP_IPV4_IFADDR = 0x5
RTNLGRP_IPV4_MROUTE = 0x6
RTNLGRP_IPV4_ROUTE = 0x7
RTNLGRP_IPV4_RULE = 0x8
RTNLGRP_IPV6_IFADDR = 0x9
RTNLGRP_IPV6_MROUTE = 0xa
RTNLGRP_IPV6_ROUTE = 0xb
RTNLGRP_IPV6_IFINFO = 0xc
RTNLGRP_IPV6_PREFIX = 0x12
RTNLGRP_IPV6_RULE = 0x13
RTNLGRP_ND_USEROPT = 0x14
SizeofNlMsghdr = 0x10
SizeofNlMsgerr = 0x14
SizeofRtGenmsg = 0x1
SizeofNlAttr = 0x4
SizeofRtAttr = 0x4
SizeofIfInfomsg = 0x10
SizeofIfAddrmsg = 0x8
SizeofRtMsg = 0xc
SizeofRtNexthop = 0x8
)
type NlMsghdr struct {
Len uint32
Type uint16
Flags uint16
Seq uint32
Pid uint32
}
type NlMsgerr struct {
Error int32
Msg NlMsghdr
}
type RtGenmsg struct {
Family uint8
}
type NlAttr struct {
Len uint16
Type uint16
}
type RtAttr struct {
Len uint16
Type uint16
}
type IfInfomsg struct {
Family uint8
_ uint8
Type uint16
Index int32
Flags uint32
Change uint32
}
type IfAddrmsg struct {
Family uint8
Prefixlen uint8
Flags uint8
Scope uint8
Index uint32
}
type RtMsg struct {
Family uint8
Dst_len uint8
Src_len uint8
Tos uint8
Table uint8
Protocol uint8
Scope uint8
Type uint8
Flags uint32
}
type RtNexthop struct {
Len uint16
Flags uint8
Hops uint8
Ifindex int32
}
const (
SizeofSockFilter = 0x8
SizeofSockFprog = 0x8
)
type SockFilter struct {
Code uint16
Jt uint8
Jf uint8
K uint32
}
type SockFprog struct {
Len uint16
_ [2]byte
Filter *SockFilter
}
type InotifyEvent struct {
Wd int32
Mask uint32
Cookie uint32
Len uint32
}
const SizeofInotifyEvent = 0x10
type PtraceRegs struct {
Regs [32]uint64
Lo uint64
Hi uint64
Epc uint64
Badvaddr uint64
Status uint64
Cause uint64
}
type FdSet struct {
Bits [32]int32
}
type Sysinfo_t struct {
Uptime int32
Loads [3]uint32
Totalram uint32
Freeram uint32
Sharedram uint32
Bufferram uint32
Totalswap uint32
Freeswap uint32
Procs uint16
Pad uint16
Totalhigh uint32
Freehigh uint32
Unit uint32
_ [8]int8
}
type Utsname struct {
Sysname [65]byte
Nodename [65]byte
Release [65]byte
Version [65]byte
Machine [65]byte
Domainname [65]byte
}
type Ustat_t struct {
Tfree int32
Tinode uint32
Fname [6]int8
Fpack [6]int8
}
type EpollEvent struct {
Events uint32
PadFd int32
Fd int32
Pad int32
}
const (
AT_EMPTY_PATH = 0x1000
AT_FDCWD = -0x64
AT_NO_AUTOMOUNT = 0x800
AT_REMOVEDIR = 0x200
AT_STATX_SYNC_AS_STAT = 0x0
AT_STATX_FORCE_SYNC = 0x2000
AT_STATX_DONT_SYNC = 0x4000
AT_SYMLINK_FOLLOW = 0x400
AT_SYMLINK_NOFOLLOW = 0x100
)
type PollFd struct {
Fd int32
Events int16
Revents int16
}
const (
POLLIN = 0x1
POLLPRI = 0x2
POLLOUT = 0x4
POLLRDHUP = 0x2000
POLLERR = 0x8
POLLHUP = 0x10
POLLNVAL = 0x20
)
type Sigset_t struct {
Val [32]uint32
}
const RNDGETENTCNT = 0x40045200
const PERF_IOC_FLAG_GROUP = 0x1
type Termios struct {
Iflag uint32
Oflag uint32
Cflag uint32
Lflag uint32
Line uint8
Cc [23]uint8
Ispeed uint32
Ospeed uint32
}
type Winsize struct {
Row uint16
Col uint16
Xpixel uint16
Ypixel uint16
}
type Taskstats struct {
Version uint16
_ [2]byte
Ac_exitcode uint32
Ac_flag uint8
Ac_nice uint8
_ [6]byte
Cpu_count uint64
Cpu_delay_total uint64
Blkio_count uint64
Blkio_delay_total uint64
Swapin_count uint64
Swapin_delay_total uint64
Cpu_run_real_total uint64
Cpu_run_virtual_total uint64
Ac_comm [32]int8
Ac_sched uint8
Ac_pad [3]uint8
_ [4]byte
Ac_uid uint32
Ac_gid uint32
Ac_pid uint32
Ac_ppid uint32
Ac_btime uint32
_ [4]byte
Ac_etime uint64
Ac_utime uint64
Ac_stime uint64
Ac_minflt uint64
Ac_majflt uint64
Coremem uint64
Virtmem uint64
Hiwater_rss uint64
Hiwater_vm uint64
Read_char uint64
Write_char uint64
Read_syscalls uint64
Write_syscalls uint64
Read_bytes uint64
Write_bytes uint64
Cancelled_write_bytes uint64
Nvcsw uint64
Nivcsw uint64
Ac_utimescaled uint64
Ac_stimescaled uint64
Cpu_scaled_run_real_total uint64
Freepages_count uint64
Freepages_delay_total uint64
}
const (
TASKSTATS_CMD_UNSPEC = 0x0
TASKSTATS_CMD_GET = 0x1
TASKSTATS_CMD_NEW = 0x2
TASKSTATS_TYPE_UNSPEC = 0x0
TASKSTATS_TYPE_PID = 0x1
TASKSTATS_TYPE_TGID = 0x2
TASKSTATS_TYPE_STATS = 0x3
TASKSTATS_TYPE_AGGR_PID = 0x4
TASKSTATS_TYPE_AGGR_TGID = 0x5
TASKSTATS_TYPE_NULL = 0x6
TASKSTATS_CMD_ATTR_UNSPEC = 0x0
TASKSTATS_CMD_ATTR_PID = 0x1
TASKSTATS_CMD_ATTR_TGID = 0x2
TASKSTATS_CMD_ATTR_REGISTER_CPUMASK = 0x3
TASKSTATS_CMD_ATTR_DEREGISTER_CPUMASK = 0x4
)
type CGroupStats struct {
Sleeping uint64
Running uint64
Stopped uint64
Uninterruptible uint64
Io_wait uint64
}
const (
CGROUPSTATS_CMD_UNSPEC = 0x3
CGROUPSTATS_CMD_GET = 0x4
CGROUPSTATS_CMD_NEW = 0x5
CGROUPSTATS_TYPE_UNSPEC = 0x0
CGROUPSTATS_TYPE_CGROUP_STATS = 0x1
CGROUPSTATS_CMD_ATTR_UNSPEC = 0x0
CGROUPSTATS_CMD_ATTR_FD = 0x1
)
type Genlmsghdr struct {
Cmd uint8
Version uint8
Reserved uint16
}
const (
CTRL_CMD_UNSPEC = 0x0
CTRL_CMD_NEWFAMILY = 0x1
CTRL_CMD_DELFAMILY = 0x2
CTRL_CMD_GETFAMILY = 0x3
CTRL_CMD_NEWOPS = 0x4
CTRL_CMD_DELOPS = 0x5
CTRL_CMD_GETOPS = 0x6
CTRL_CMD_NEWMCAST_GRP = 0x7
CTRL_CMD_DELMCAST_GRP = 0x8
CTRL_CMD_GETMCAST_GRP = 0x9
CTRL_ATTR_UNSPEC = 0x0
CTRL_ATTR_FAMILY_ID = 0x1
CTRL_ATTR_FAMILY_NAME = 0x2
CTRL_ATTR_VERSION = 0x3
CTRL_ATTR_HDRSIZE = 0x4
CTRL_ATTR_MAXATTR = 0x5
CTRL_ATTR_OPS = 0x6
CTRL_ATTR_MCAST_GROUPS = 0x7
CTRL_ATTR_OP_UNSPEC = 0x0
CTRL_ATTR_OP_ID = 0x1
CTRL_ATTR_OP_FLAGS = 0x2
CTRL_ATTR_MCAST_GRP_UNSPEC = 0x0
CTRL_ATTR_MCAST_GRP_NAME = 0x1
CTRL_ATTR_MCAST_GRP_ID = 0x2
)
type cpuMask uint32
const (
_CPU_SETSIZE = 0x400
_NCPUBITS = 0x20
)
const (
BDADDR_BREDR = 0x0
BDADDR_LE_PUBLIC = 0x1
BDADDR_LE_RANDOM = 0x2
)
type PerfEventAttr struct {
Type uint32
Size uint32
Config uint64
Sample uint64
Sample_type uint64
Read_format uint64
Bits uint64
Wakeup uint32
Bp_type uint32
Ext1 uint64
Ext2 uint64
Branch_sample_type uint64
Sample_regs_user uint64
Sample_stack_user uint32
Clockid int32
Sample_regs_intr uint64
Aux_watermark uint32
_ uint32
}
type PerfEventMmapPage struct {
Version uint32
Compat_version uint32
Lock uint32
Index uint32
Offset int64
Time_enabled uint64
Time_running uint64
Capabilities uint64
Pmc_width uint16
Time_shift uint16
Time_mult uint32
Time_offset uint64
Time_zero uint64
Size uint32
_ [948]uint8
Data_head uint64
Data_tail uint64
Data_offset uint64
Data_size uint64
Aux_head uint64
Aux_tail uint64
Aux_offset uint64
Aux_size uint64
}
const (
PerfBitDisabled uint64 = CBitFieldMaskBit0
PerfBitInherit = CBitFieldMaskBit1
PerfBitPinned = CBitFieldMaskBit2
PerfBitExclusive = CBitFieldMaskBit3
PerfBitExcludeUser = CBitFieldMaskBit4
PerfBitExcludeKernel = CBitFieldMaskBit5
PerfBitExcludeHv = CBitFieldMaskBit6
PerfBitExcludeIdle = CBitFieldMaskBit7
PerfBitMmap = CBitFieldMaskBit8
PerfBitComm = CBitFieldMaskBit9
PerfBitFreq = CBitFieldMaskBit10
PerfBitInheritStat = CBitFieldMaskBit11
PerfBitEnableOnExec = CBitFieldMaskBit12
PerfBitTask = CBitFieldMaskBit13
PerfBitWatermark = CBitFieldMaskBit14
PerfBitPreciseIPBit1 = CBitFieldMaskBit15
PerfBitPreciseIPBit2 = CBitFieldMaskBit16
PerfBitMmapData = CBitFieldMaskBit17
PerfBitSampleIDAll = CBitFieldMaskBit18
PerfBitExcludeHost = CBitFieldMaskBit19
PerfBitExcludeGuest = CBitFieldMaskBit20
PerfBitExcludeCallchainKernel = CBitFieldMaskBit21
PerfBitExcludeCallchainUser = CBitFieldMaskBit22
PerfBitMmap2 = CBitFieldMaskBit23
PerfBitCommExec = CBitFieldMaskBit24
PerfBitUseClockID = CBitFieldMaskBit25
PerfBitContextSwitch = CBitFieldMaskBit26
)
const (
PERF_TYPE_HARDWARE = 0x0
PERF_TYPE_SOFTWARE = 0x1
PERF_TYPE_TRACEPOINT = 0x2
PERF_TYPE_HW_CACHE = 0x3
PERF_TYPE_RAW = 0x4
PERF_TYPE_BREAKPOINT = 0x5
PERF_COUNT_HW_CPU_CYCLES = 0x0
PERF_COUNT_HW_INSTRUCTIONS = 0x1
PERF_COUNT_HW_CACHE_REFERENCES = 0x2
PERF_COUNT_HW_CACHE_MISSES = 0x3
PERF_COUNT_HW_BRANCH_INSTRUCTIONS = 0x4
PERF_COUNT_HW_BRANCH_MISSES = 0x5
PERF_COUNT_HW_BUS_CYCLES = 0x6
PERF_COUNT_HW_STALLED_CYCLES_FRONTEND = 0x7
PERF_COUNT_HW_STALLED_CYCLES_BACKEND = 0x8
PERF_COUNT_HW_REF_CPU_CYCLES = 0x9
PERF_COUNT_HW_CACHE_L1D = 0x0
PERF_COUNT_HW_CACHE_L1I = 0x1
PERF_COUNT_HW_CACHE_LL = 0x2
PERF_COUNT_HW_CACHE_DTLB = 0x3
PERF_COUNT_HW_CACHE_ITLB = 0x4
PERF_COUNT_HW_CACHE_BPU = 0x5
PERF_COUNT_HW_CACHE_NODE = 0x6
PERF_COUNT_HW_CACHE_OP_READ = 0x0
PERF_COUNT_HW_CACHE_OP_WRITE = 0x1
PERF_COUNT_HW_CACHE_OP_PREFETCH = 0x2
PERF_COUNT_HW_CACHE_RESULT_ACCESS = 0x0
PERF_COUNT_HW_CACHE_RESULT_MISS = 0x1
PERF_COUNT_SW_CPU_CLOCK = 0x0
PERF_COUNT_SW_TASK_CLOCK = 0x1
PERF_COUNT_SW_PAGE_FAULTS = 0x2
PERF_COUNT_SW_CONTEXT_SWITCHES = 0x3
PERF_COUNT_SW_CPU_MIGRATIONS = 0x4
PERF_COUNT_SW_PAGE_FAULTS_MIN = 0x5
PERF_COUNT_SW_PAGE_FAULTS_MAJ = 0x6
PERF_COUNT_SW_ALIGNMENT_FAULTS = 0x7
PERF_COUNT_SW_EMULATION_FAULTS = 0x8
PERF_COUNT_SW_DUMMY = 0x9
PERF_SAMPLE_IP = 0x1
PERF_SAMPLE_TID = 0x2
PERF_SAMPLE_TIME = 0x4
PERF_SAMPLE_ADDR = 0x8
PERF_SAMPLE_READ = 0x10
PERF_SAMPLE_CALLCHAIN = 0x20
PERF_SAMPLE_ID = 0x40
PERF_SAMPLE_CPU = 0x80
PERF_SAMPLE_PERIOD = 0x100
PERF_SAMPLE_STREAM_ID = 0x200
PERF_SAMPLE_RAW = 0x400
PERF_SAMPLE_BRANCH_STACK = 0x800
PERF_SAMPLE_BRANCH_USER = 0x1
PERF_SAMPLE_BRANCH_KERNEL = 0x2
PERF_SAMPLE_BRANCH_HV = 0x4
PERF_SAMPLE_BRANCH_ANY = 0x8
PERF_SAMPLE_BRANCH_ANY_CALL = 0x10
PERF_SAMPLE_BRANCH_ANY_RETURN = 0x20
PERF_SAMPLE_BRANCH_IND_CALL = 0x40
PERF_FORMAT_TOTAL_TIME_ENABLED = 0x1
PERF_FORMAT_TOTAL_TIME_RUNNING = 0x2
PERF_FORMAT_ID = 0x4
PERF_FORMAT_GROUP = 0x8
PERF_RECORD_MMAP = 0x1
PERF_RECORD_LOST = 0x2
PERF_RECORD_COMM = 0x3
PERF_RECORD_EXIT = 0x4
PERF_RECORD_THROTTLE = 0x5
PERF_RECORD_UNTHROTTLE = 0x6
PERF_RECORD_FORK = 0x7
PERF_RECORD_READ = 0x8
PERF_RECORD_SAMPLE = 0x9
PERF_CONTEXT_HV = -0x20
PERF_CONTEXT_KERNEL = -0x80
PERF_CONTEXT_USER = -0x200
PERF_CONTEXT_GUEST = -0x800
PERF_CONTEXT_GUEST_KERNEL = -0x880
PERF_CONTEXT_GUEST_USER = -0xa00
PERF_FLAG_FD_NO_GROUP = 0x1
PERF_FLAG_FD_OUTPUT = 0x2
PERF_FLAG_PID_CGROUP = 0x4
)
const (
CBitFieldMaskBit0 = 0x1
CBitFieldMaskBit1 = 0x2
CBitFieldMaskBit2 = 0x4
CBitFieldMaskBit3 = 0x8
CBitFieldMaskBit4 = 0x10
CBitFieldMaskBit5 = 0x20
CBitFieldMaskBit6 = 0x40
CBitFieldMaskBit7 = 0x80
CBitFieldMaskBit8 = 0x100
CBitFieldMaskBit9 = 0x200
CBitFieldMaskBit10 = 0x400
CBitFieldMaskBit11 = 0x800
CBitFieldMaskBit12 = 0x1000
CBitFieldMaskBit13 = 0x2000
CBitFieldMaskBit14 = 0x4000
CBitFieldMaskBit15 = 0x8000
CBitFieldMaskBit16 = 0x10000
CBitFieldMaskBit17 = 0x20000
CBitFieldMaskBit18 = 0x40000
CBitFieldMaskBit19 = 0x80000
CBitFieldMaskBit20 = 0x100000
CBitFieldMaskBit21 = 0x200000
CBitFieldMaskBit22 = 0x400000
CBitFieldMaskBit23 = 0x800000
CBitFieldMaskBit24 = 0x1000000
CBitFieldMaskBit25 = 0x2000000
CBitFieldMaskBit26 = 0x4000000
CBitFieldMaskBit27 = 0x8000000
CBitFieldMaskBit28 = 0x10000000
CBitFieldMaskBit29 = 0x20000000
CBitFieldMaskBit30 = 0x40000000
CBitFieldMaskBit31 = 0x80000000
CBitFieldMaskBit32 = 0x100000000
CBitFieldMaskBit33 = 0x200000000
CBitFieldMaskBit34 = 0x400000000
CBitFieldMaskBit35 = 0x800000000
CBitFieldMaskBit36 = 0x1000000000
CBitFieldMaskBit37 = 0x2000000000
CBitFieldMaskBit38 = 0x4000000000
CBitFieldMaskBit39 = 0x8000000000
CBitFieldMaskBit40 = 0x10000000000
CBitFieldMaskBit41 = 0x20000000000
CBitFieldMaskBit42 = 0x40000000000
CBitFieldMaskBit43 = 0x80000000000
CBitFieldMaskBit44 = 0x100000000000
CBitFieldMaskBit45 = 0x200000000000
CBitFieldMaskBit46 = 0x400000000000
CBitFieldMaskBit47 = 0x800000000000
CBitFieldMaskBit48 = 0x1000000000000
CBitFieldMaskBit49 = 0x2000000000000
CBitFieldMaskBit50 = 0x4000000000000
CBitFieldMaskBit51 = 0x8000000000000
CBitFieldMaskBit52 = 0x10000000000000
CBitFieldMaskBit53 = 0x20000000000000
CBitFieldMaskBit54 = 0x40000000000000
CBitFieldMaskBit55 = 0x80000000000000
CBitFieldMaskBit56 = 0x100000000000000
CBitFieldMaskBit57 = 0x200000000000000
CBitFieldMaskBit58 = 0x400000000000000
CBitFieldMaskBit59 = 0x800000000000000
CBitFieldMaskBit60 = 0x1000000000000000
CBitFieldMaskBit61 = 0x2000000000000000
CBitFieldMaskBit62 = 0x4000000000000000
CBitFieldMaskBit63 = 0x8000000000000000
)
type SockaddrStorage struct {
Family uint16
_ [122]int8
_ uint32
}
type TCPMD5Sig struct {
Addr SockaddrStorage
Flags uint8
Prefixlen uint8
Keylen uint16
_ uint32
Key [80]uint8
}
type HDDriveCmdHdr struct {
Command uint8
Number uint8
Feature uint8
Count uint8
}
type HDGeometry struct {
Heads uint8
Sectors uint8
Cylinders uint16
Start uint32
}
type HDDriveID struct {
Config uint16
Cyls uint16
Reserved2 uint16
Heads uint16
Track_bytes uint16
Sector_bytes uint16
Sectors uint16
Vendor0 uint16
Vendor1 uint16
Vendor2 uint16
Serial_no [20]uint8
Buf_type uint16
Buf_size uint16
Ecc_bytes uint16
Fw_rev [8]uint8
Model [40]uint8
Max_multsect uint8
Vendor3 uint8
Dword_io uint16
Vendor4 uint8
Capability uint8
Reserved50 uint16
Vendor5 uint8
TPIO uint8
Vendor6 uint8
TDMA uint8
Field_valid uint16
Cur_cyls uint16
Cur_heads uint16
Cur_sectors uint16
Cur_capacity0 uint16
Cur_capacity1 uint16
Multsect uint8
Multsect_valid uint8
Lba_capacity uint32
Dma_1word uint16
Dma_mword uint16
Eide_pio_modes uint16
Eide_dma_min uint16
Eide_dma_time uint16
Eide_pio uint16
Eide_pio_iordy uint16
Words69_70 [2]uint16
Words71_74 [4]uint16
Queue_depth uint16
Words76_79 [4]uint16
Major_rev_num uint16
Minor_rev_num uint16
Command_set_1 uint16
Command_set_2 uint16
Cfsse uint16
Cfs_enable_1 uint16
Cfs_enable_2 uint16
Csf_default uint16
Dma_ultra uint16
Trseuc uint16
TrsEuc uint16
CurAPMvalues uint16
Mprc uint16
Hw_config uint16
Acoustic uint16
Msrqs uint16
Sxfert uint16
Sal uint16
Spg uint32
Lba_capacity_2 uint64
Words104_125 [22]uint16
Last_lun uint16
Word127 uint16
Dlf uint16
Csfo uint16
Words130_155 [26]uint16
Word156 uint16
Words157_159 [3]uint16
Cfa_power uint16
Words161_175 [15]uint16
Words176_205 [30]uint16
Words206_254 [49]uint16
Integrity_word uint16
}
type Statfs_t struct {
Type int32
Bsize int32
Frsize int32
_ [4]byte
Blocks uint64
Bfree uint64
Files uint64
Ffree uint64
Bavail uint64
Fsid Fsid
Namelen int32
Flags int32
Spare [5]int32
_ [4]byte
}
const (
ST_MANDLOCK = 0x40
ST_NOATIME = 0x400
ST_NODEV = 0x4
ST_NODIRATIME = 0x800
ST_NOEXEC = 0x8
ST_NOSUID = 0x2
ST_RDONLY = 0x1
ST_RELATIME = 0x1000
ST_SYNCHRONOUS = 0x10
)
type TpacketHdr struct {
Status uint32
Len uint32
Snaplen uint32
Mac uint16
Net uint16
Sec uint32
Usec uint32
}
type Tpacket2Hdr struct {
Status uint32
Len uint32
Snaplen uint32
Mac uint16
Net uint16
Sec uint32
Nsec uint32
Vlan_tci uint16
Vlan_tpid uint16
_ [4]uint8
}
type Tpacket3Hdr struct {
Next_offset uint32
Sec uint32
Nsec uint32
Snaplen uint32
Len uint32
Status uint32
Mac uint16
Net uint16
Hv1 TpacketHdrVariant1
_ [8]uint8
}
type TpacketHdrVariant1 struct {
Rxhash uint32
Vlan_tci uint32
Vlan_tpid uint16
_ uint16
}
type TpacketBlockDesc struct {
Version uint32
To_priv uint32
Hdr [40]byte
}
type TpacketReq struct {
Block_size uint32
Block_nr uint32
Frame_size uint32
Frame_nr uint32
}
type TpacketReq3 struct {
Block_size uint32
Block_nr uint32
Frame_size uint32
Frame_nr uint32
Retire_blk_tov uint32
Sizeof_priv uint32
Feature_req_word uint32
}
type TpacketStats struct {
Packets uint32
Drops uint32
}
type TpacketStatsV3 struct {
Packets uint32
Drops uint32
Freeze_q_cnt uint32
}
type TpacketAuxdata struct {
Status uint32
Len uint32
Snaplen uint32
Mac uint16
Net uint16
Vlan_tci uint16
Vlan_tpid uint16
}
const (
TPACKET_V1 = 0x0
TPACKET_V2 = 0x1
TPACKET_V3 = 0x2
)
const (
SizeofTpacketHdr = 0x18
SizeofTpacket2Hdr = 0x20
SizeofTpacket3Hdr = 0x30
)
|
vendor/golang.org/x/sys/unix/ztypes_linux_mipsle.go
| 0 |
https://github.com/grafana/grafana/commit/dc3a81200b1cd366bdf237ada152ae3d79bdaf59
|
[
0.0004209968028590083,
0.0001752379903336987,
0.00016188689914997667,
0.00016906116798054427,
0.000028868707886431366
] |
{
"id": 3,
"code_window": [
" return <AddPanelPanel panel={this.props.panel} dashboard={this.props.dashboard} />;\n",
" }\n",
"\n",
" loadPlugin() {\n",
" if (this.isSpecial()) {\n",
" return;\n",
" }\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" onPluginTypeChanged = (plugin: PanelPlugin) => {\n",
" this.props.panel.changeType(plugin.id);\n",
" this.loadPlugin();\n",
" };\n",
"\n"
],
"file_path": "public/app/features/dashboard/dashgrid/DashboardPanel.tsx",
"type": "add",
"edit_start_line_idx": 52
}
|
apiVersion: 1
datasources:
- name: name
type: type
access: proxy
orgId: 2
url: url
password: password
user: user
database: database
basicAuth: true
basicAuthUser: basic_auth_user
basicAuthPassword: basic_auth_password
withCredentials: true
isDefault: true
jsonData:
graphiteVersion: "1.1"
tlsAuth: true
tlsAuthWithCACert: true
secureJsonData:
tlsCACert: "MjNOcW9RdkbUDHZmpco2HCYzVq9dE+i6Yi+gmUJotq5CDA=="
tlsClientCert: "ckN0dGlyMXN503YNfjTcf9CV+GGQneN+xmAclQ=="
tlsClientKey: "ZkN4aG1aNkja/gKAB1wlnKFIsy2SRDq4slrM0A=="
editable: true
version: 10
deleteDatasources:
- name: old-graphite3
orgId: 2
|
pkg/services/provisioning/datasources/testdata/all-properties/all-properties.yaml
| 0 |
https://github.com/grafana/grafana/commit/dc3a81200b1cd366bdf237ada152ae3d79bdaf59
|
[
0.0001774826378095895,
0.0001736590056680143,
0.000167100690305233,
0.00017502637638244778,
0.0000039499668673670385
] |
{
"id": 3,
"code_window": [
" return <AddPanelPanel panel={this.props.panel} dashboard={this.props.dashboard} />;\n",
" }\n",
"\n",
" loadPlugin() {\n",
" if (this.isSpecial()) {\n",
" return;\n",
" }\n",
"\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" onPluginTypeChanged = (plugin: PanelPlugin) => {\n",
" this.props.panel.changeType(plugin.id);\n",
" this.loadPlugin();\n",
" };\n",
"\n"
],
"file_path": "public/app/features/dashboard/dashgrid/DashboardPanel.tsx",
"type": "add",
"edit_start_line_idx": 52
}
|
---
title: Reference Index
description: Grafana docs reference
type: docs
---
# Documentation
|
docs/sources/reference/index.md
| 0 |
https://github.com/grafana/grafana/commit/dc3a81200b1cd366bdf237ada152ae3d79bdaf59
|
[
0.0001778945152182132,
0.0001778945152182132,
0.0001778945152182132,
0.0001778945152182132,
0
] |
{
"id": 4,
"code_window": [
" if (this.pluginInfo.exports) {\n",
" this.setState({ pluginExports: this.pluginInfo.exports });\n",
" } else {\n",
" importPluginModule(this.pluginInfo.module).then(pluginExports => {\n",
" this.setState({ pluginExports: pluginExports });\n",
" });\n",
" }\n",
" }\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" // cache plugin exports (saves a promise async cycle next time)\n",
" this.pluginInfo.exports = pluginExports;\n",
" // update panel state\n"
],
"file_path": "public/app/features/dashboard/dashgrid/DashboardPanel.tsx",
"type": "add",
"edit_start_line_idx": 65
}
|
import React, { ComponentClass } from 'react';
import $ from 'jquery';
import { PanelModel } from '../panel_model';
import { DashboardModel } from '../dashboard_model';
import { PanelHeader } from './PanelHeader';
import { DataPanel, PanelProps, DataPanelWrapper } from './DataPanel';
export interface Props {
panel: PanelModel;
dashboard: DashboardModel;
component: ComponentClass<PanelProps>;
}
interface State {}
export class PanelChrome extends React.Component<Props, State> {
panelComponent: DataPanel;
constructor(props) {
super(props);
this.panelComponent = DataPanelWrapper(this.props.component);
}
componentDidMount() {
console.log('panel chrome mounted');
}
render() {
let PanelComponent = this.panelComponent;
return (
<div className="panel-container">
<PanelHeader panel={this.props.panel} dashboard={this.props.dashboard} />
<div className="panel-content">{<PanelComponent type={'test'} queries={[]} isVisible={true} />}</div>
</div>
);
}
}
|
public/app/features/dashboard/dashgrid/PanelChrome.tsx
| 1 |
https://github.com/grafana/grafana/commit/dc3a81200b1cd366bdf237ada152ae3d79bdaf59
|
[
0.00017458811635151505,
0.00017068744637072086,
0.00016503050574101508,
0.0001715655525913462,
0.0000035091743484372273
] |
{
"id": 4,
"code_window": [
" if (this.pluginInfo.exports) {\n",
" this.setState({ pluginExports: this.pluginInfo.exports });\n",
" } else {\n",
" importPluginModule(this.pluginInfo.module).then(pluginExports => {\n",
" this.setState({ pluginExports: pluginExports });\n",
" });\n",
" }\n",
" }\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" // cache plugin exports (saves a promise async cycle next time)\n",
" this.pluginInfo.exports = pluginExports;\n",
" // update panel state\n"
],
"file_path": "public/app/features/dashboard/dashgrid/DashboardPanel.tsx",
"type": "add",
"edit_start_line_idx": 65
}
|
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build !gccgo
#include "textflag.h"
//
// System call support for AMD64, FreeBSD
//
// Just jump to package syscall's implementation for all these functions.
// The runtime may know about them.
TEXT ·Syscall(SB),NOSPLIT,$0-56
JMP syscall·Syscall(SB)
TEXT ·Syscall6(SB),NOSPLIT,$0-80
JMP syscall·Syscall6(SB)
TEXT ·Syscall9(SB),NOSPLIT,$0-104
JMP syscall·Syscall9(SB)
TEXT ·RawSyscall(SB),NOSPLIT,$0-56
JMP syscall·RawSyscall(SB)
TEXT ·RawSyscall6(SB),NOSPLIT,$0-80
JMP syscall·RawSyscall6(SB)
|
vendor/golang.org/x/sys/unix/asm_freebsd_amd64.s
| 0 |
https://github.com/grafana/grafana/commit/dc3a81200b1cd366bdf237ada152ae3d79bdaf59
|
[
0.00017786771059036255,
0.00017516240768600255,
0.00017330271657556295,
0.00017431681044399738,
0.0000019572216842789203
] |
{
"id": 4,
"code_window": [
" if (this.pluginInfo.exports) {\n",
" this.setState({ pluginExports: this.pluginInfo.exports });\n",
" } else {\n",
" importPluginModule(this.pluginInfo.module).then(pluginExports => {\n",
" this.setState({ pluginExports: pluginExports });\n",
" });\n",
" }\n",
" }\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" // cache plugin exports (saves a promise async cycle next time)\n",
" this.pluginInfo.exports = pluginExports;\n",
" // update panel state\n"
],
"file_path": "public/app/features/dashboard/dashgrid/DashboardPanel.tsx",
"type": "add",
"edit_start_line_idx": 65
}
|
package jmespath
import (
"errors"
"reflect"
"unicode"
"unicode/utf8"
)
/* This is a tree based interpreter. It walks the AST and directly
interprets the AST to search through a JSON document.
*/
type treeInterpreter struct {
fCall *functionCaller
}
func newInterpreter() *treeInterpreter {
interpreter := treeInterpreter{}
interpreter.fCall = newFunctionCaller()
return &interpreter
}
type expRef struct {
ref ASTNode
}
// Execute takes an ASTNode and input data and interprets the AST directly.
// It will produce the result of applying the JMESPath expression associated
// with the ASTNode to the input data "value".
func (intr *treeInterpreter) Execute(node ASTNode, value interface{}) (interface{}, error) {
switch node.nodeType {
case ASTComparator:
left, err := intr.Execute(node.children[0], value)
if err != nil {
return nil, err
}
right, err := intr.Execute(node.children[1], value)
if err != nil {
return nil, err
}
switch node.value {
case tEQ:
return objsEqual(left, right), nil
case tNE:
return !objsEqual(left, right), nil
}
leftNum, ok := left.(float64)
if !ok {
return nil, nil
}
rightNum, ok := right.(float64)
if !ok {
return nil, nil
}
switch node.value {
case tGT:
return leftNum > rightNum, nil
case tGTE:
return leftNum >= rightNum, nil
case tLT:
return leftNum < rightNum, nil
case tLTE:
return leftNum <= rightNum, nil
}
case ASTExpRef:
return expRef{ref: node.children[0]}, nil
case ASTFunctionExpression:
resolvedArgs := []interface{}{}
for _, arg := range node.children {
current, err := intr.Execute(arg, value)
if err != nil {
return nil, err
}
resolvedArgs = append(resolvedArgs, current)
}
return intr.fCall.CallFunction(node.value.(string), resolvedArgs, intr)
case ASTField:
if m, ok := value.(map[string]interface{}); ok {
key := node.value.(string)
return m[key], nil
}
return intr.fieldFromStruct(node.value.(string), value)
case ASTFilterProjection:
left, err := intr.Execute(node.children[0], value)
if err != nil {
return nil, nil
}
sliceType, ok := left.([]interface{})
if !ok {
if isSliceType(left) {
return intr.filterProjectionWithReflection(node, left)
}
return nil, nil
}
compareNode := node.children[2]
collected := []interface{}{}
for _, element := range sliceType {
result, err := intr.Execute(compareNode, element)
if err != nil {
return nil, err
}
if !isFalse(result) {
current, err := intr.Execute(node.children[1], element)
if err != nil {
return nil, err
}
if current != nil {
collected = append(collected, current)
}
}
}
return collected, nil
case ASTFlatten:
left, err := intr.Execute(node.children[0], value)
if err != nil {
return nil, nil
}
sliceType, ok := left.([]interface{})
if !ok {
// If we can't type convert to []interface{}, there's
// a chance this could still work via reflection if we're
// dealing with user provided types.
if isSliceType(left) {
return intr.flattenWithReflection(left)
}
return nil, nil
}
flattened := []interface{}{}
for _, element := range sliceType {
if elementSlice, ok := element.([]interface{}); ok {
flattened = append(flattened, elementSlice...)
} else if isSliceType(element) {
reflectFlat := []interface{}{}
v := reflect.ValueOf(element)
for i := 0; i < v.Len(); i++ {
reflectFlat = append(reflectFlat, v.Index(i).Interface())
}
flattened = append(flattened, reflectFlat...)
} else {
flattened = append(flattened, element)
}
}
return flattened, nil
case ASTIdentity, ASTCurrentNode:
return value, nil
case ASTIndex:
if sliceType, ok := value.([]interface{}); ok {
index := node.value.(int)
if index < 0 {
index += len(sliceType)
}
if index < len(sliceType) && index >= 0 {
return sliceType[index], nil
}
return nil, nil
}
// Otherwise try via reflection.
rv := reflect.ValueOf(value)
if rv.Kind() == reflect.Slice {
index := node.value.(int)
if index < 0 {
index += rv.Len()
}
if index < rv.Len() && index >= 0 {
v := rv.Index(index)
return v.Interface(), nil
}
}
return nil, nil
case ASTKeyValPair:
return intr.Execute(node.children[0], value)
case ASTLiteral:
return node.value, nil
case ASTMultiSelectHash:
if value == nil {
return nil, nil
}
collected := make(map[string]interface{})
for _, child := range node.children {
current, err := intr.Execute(child, value)
if err != nil {
return nil, err
}
key := child.value.(string)
collected[key] = current
}
return collected, nil
case ASTMultiSelectList:
if value == nil {
return nil, nil
}
collected := []interface{}{}
for _, child := range node.children {
current, err := intr.Execute(child, value)
if err != nil {
return nil, err
}
collected = append(collected, current)
}
return collected, nil
case ASTOrExpression:
matched, err := intr.Execute(node.children[0], value)
if err != nil {
return nil, err
}
if isFalse(matched) {
matched, err = intr.Execute(node.children[1], value)
if err != nil {
return nil, err
}
}
return matched, nil
case ASTAndExpression:
matched, err := intr.Execute(node.children[0], value)
if err != nil {
return nil, err
}
if isFalse(matched) {
return matched, nil
}
return intr.Execute(node.children[1], value)
case ASTNotExpression:
matched, err := intr.Execute(node.children[0], value)
if err != nil {
return nil, err
}
if isFalse(matched) {
return true, nil
}
return false, nil
case ASTPipe:
result := value
var err error
for _, child := range node.children {
result, err = intr.Execute(child, result)
if err != nil {
return nil, err
}
}
return result, nil
case ASTProjection:
left, err := intr.Execute(node.children[0], value)
if err != nil {
return nil, err
}
sliceType, ok := left.([]interface{})
if !ok {
if isSliceType(left) {
return intr.projectWithReflection(node, left)
}
return nil, nil
}
collected := []interface{}{}
var current interface{}
for _, element := range sliceType {
current, err = intr.Execute(node.children[1], element)
if err != nil {
return nil, err
}
if current != nil {
collected = append(collected, current)
}
}
return collected, nil
case ASTSubexpression, ASTIndexExpression:
left, err := intr.Execute(node.children[0], value)
if err != nil {
return nil, err
}
return intr.Execute(node.children[1], left)
case ASTSlice:
sliceType, ok := value.([]interface{})
if !ok {
if isSliceType(value) {
return intr.sliceWithReflection(node, value)
}
return nil, nil
}
parts := node.value.([]*int)
sliceParams := make([]sliceParam, 3)
for i, part := range parts {
if part != nil {
sliceParams[i].Specified = true
sliceParams[i].N = *part
}
}
return slice(sliceType, sliceParams)
case ASTValueProjection:
left, err := intr.Execute(node.children[0], value)
if err != nil {
return nil, nil
}
mapType, ok := left.(map[string]interface{})
if !ok {
return nil, nil
}
values := make([]interface{}, len(mapType))
for _, value := range mapType {
values = append(values, value)
}
collected := []interface{}{}
for _, element := range values {
current, err := intr.Execute(node.children[1], element)
if err != nil {
return nil, err
}
if current != nil {
collected = append(collected, current)
}
}
return collected, nil
}
return nil, errors.New("Unknown AST node: " + node.nodeType.String())
}
func (intr *treeInterpreter) fieldFromStruct(key string, value interface{}) (interface{}, error) {
rv := reflect.ValueOf(value)
first, n := utf8.DecodeRuneInString(key)
fieldName := string(unicode.ToUpper(first)) + key[n:]
if rv.Kind() == reflect.Struct {
v := rv.FieldByName(fieldName)
if !v.IsValid() {
return nil, nil
}
return v.Interface(), nil
} else if rv.Kind() == reflect.Ptr {
// Handle multiple levels of indirection?
if rv.IsNil() {
return nil, nil
}
rv = rv.Elem()
v := rv.FieldByName(fieldName)
if !v.IsValid() {
return nil, nil
}
return v.Interface(), nil
}
return nil, nil
}
func (intr *treeInterpreter) flattenWithReflection(value interface{}) (interface{}, error) {
v := reflect.ValueOf(value)
flattened := []interface{}{}
for i := 0; i < v.Len(); i++ {
element := v.Index(i).Interface()
if reflect.TypeOf(element).Kind() == reflect.Slice {
// Then insert the contents of the element
// slice into the flattened slice,
// i.e flattened = append(flattened, mySlice...)
elementV := reflect.ValueOf(element)
for j := 0; j < elementV.Len(); j++ {
flattened = append(
flattened, elementV.Index(j).Interface())
}
} else {
flattened = append(flattened, element)
}
}
return flattened, nil
}
func (intr *treeInterpreter) sliceWithReflection(node ASTNode, value interface{}) (interface{}, error) {
v := reflect.ValueOf(value)
parts := node.value.([]*int)
sliceParams := make([]sliceParam, 3)
for i, part := range parts {
if part != nil {
sliceParams[i].Specified = true
sliceParams[i].N = *part
}
}
final := []interface{}{}
for i := 0; i < v.Len(); i++ {
element := v.Index(i).Interface()
final = append(final, element)
}
return slice(final, sliceParams)
}
func (intr *treeInterpreter) filterProjectionWithReflection(node ASTNode, value interface{}) (interface{}, error) {
compareNode := node.children[2]
collected := []interface{}{}
v := reflect.ValueOf(value)
for i := 0; i < v.Len(); i++ {
element := v.Index(i).Interface()
result, err := intr.Execute(compareNode, element)
if err != nil {
return nil, err
}
if !isFalse(result) {
current, err := intr.Execute(node.children[1], element)
if err != nil {
return nil, err
}
if current != nil {
collected = append(collected, current)
}
}
}
return collected, nil
}
func (intr *treeInterpreter) projectWithReflection(node ASTNode, value interface{}) (interface{}, error) {
collected := []interface{}{}
v := reflect.ValueOf(value)
for i := 0; i < v.Len(); i++ {
element := v.Index(i).Interface()
result, err := intr.Execute(node.children[1], element)
if err != nil {
return nil, err
}
if result != nil {
collected = append(collected, result)
}
}
return collected, nil
}
|
vendor/github.com/jmespath/go-jmespath/interpreter.go
| 0 |
https://github.com/grafana/grafana/commit/dc3a81200b1cd366bdf237ada152ae3d79bdaf59
|
[
0.00017783990188036114,
0.00017388300329912454,
0.0001638762332731858,
0.000174279572092928,
0.0000027910969038202893
] |
{
"id": 4,
"code_window": [
" if (this.pluginInfo.exports) {\n",
" this.setState({ pluginExports: this.pluginInfo.exports });\n",
" } else {\n",
" importPluginModule(this.pluginInfo.module).then(pluginExports => {\n",
" this.setState({ pluginExports: pluginExports });\n",
" });\n",
" }\n",
" }\n",
" }\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" // cache plugin exports (saves a promise async cycle next time)\n",
" this.pluginInfo.exports = pluginExports;\n",
" // update panel state\n"
],
"file_path": "public/app/features/dashboard/dashgrid/DashboardPanel.tsx",
"type": "add",
"edit_start_line_idx": 65
}
|
// Copyright (c) 2017-2018 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.
package config
import (
"errors"
"fmt"
"io"
"strings"
"time"
"github.com/opentracing/opentracing-go"
"github.com/uber/jaeger-client-go"
"github.com/uber/jaeger-client-go/internal/baggage/remote"
throttler "github.com/uber/jaeger-client-go/internal/throttler/remote"
"github.com/uber/jaeger-client-go/rpcmetrics"
)
const defaultSamplingProbability = 0.001
// Configuration configures and creates Jaeger Tracer
type Configuration struct {
// ServiceName specifies the service name to use on the tracer.
// Can be provided via environment variable named JAEGER_SERVICE_NAME
ServiceName string `yaml:"serviceName"`
// Disabled can be provided via environment variable named JAEGER_DISABLED
Disabled bool `yaml:"disabled"`
// RPCMetrics can be provided via environment variable named JAEGER_RPC_METRICS
RPCMetrics bool `yaml:"rpc_metrics"`
// Tags can be provided via environment variable named JAEGER_TAGS
Tags []opentracing.Tag `yaml:"tags"`
Sampler *SamplerConfig `yaml:"sampler"`
Reporter *ReporterConfig `yaml:"reporter"`
Headers *jaeger.HeadersConfig `yaml:"headers"`
BaggageRestrictions *BaggageRestrictionsConfig `yaml:"baggage_restrictions"`
Throttler *ThrottlerConfig `yaml:"throttler"`
}
// SamplerConfig allows initializing a non-default sampler. All fields are optional.
type SamplerConfig struct {
// Type specifies the type of the sampler: const, probabilistic, rateLimiting, or remote
// Can be set by exporting an environment variable named JAEGER_SAMPLER_TYPE
Type string `yaml:"type"`
// Param is a value passed to the sampler.
// Valid values for Param field are:
// - for "const" sampler, 0 or 1 for always false/true respectively
// - for "probabilistic" sampler, a probability between 0 and 1
// - for "rateLimiting" sampler, the number of spans per second
// - for "remote" sampler, param is the same as for "probabilistic"
// and indicates the initial sampling rate before the actual one
// is received from the mothership.
// Can be set by exporting an environment variable named JAEGER_SAMPLER_PARAM
Param float64 `yaml:"param"`
// SamplingServerURL is the address of jaeger-agent's HTTP sampling server
// Can be set by exporting an environment variable named JAEGER_SAMPLER_MANAGER_HOST_PORT
SamplingServerURL string `yaml:"samplingServerURL"`
// MaxOperations is the maximum number of operations that the sampler
// will keep track of. If an operation is not tracked, a default probabilistic
// sampler will be used rather than the per operation specific sampler.
// Can be set by exporting an environment variable named JAEGER_SAMPLER_MAX_OPERATIONS
MaxOperations int `yaml:"maxOperations"`
// SamplingRefreshInterval controls how often the remotely controlled sampler will poll
// jaeger-agent for the appropriate sampling strategy.
// Can be set by exporting an environment variable named JAEGER_SAMPLER_REFRESH_INTERVAL
SamplingRefreshInterval time.Duration `yaml:"samplingRefreshInterval"`
}
// ReporterConfig configures the reporter. All fields are optional.
type ReporterConfig struct {
// QueueSize controls how many spans the reporter can keep in memory before it starts dropping
// new spans. The queue is continuously drained by a background go-routine, as fast as spans
// can be sent out of process.
// Can be set by exporting an environment variable named JAEGER_REPORTER_MAX_QUEUE_SIZE
QueueSize int `yaml:"queueSize"`
// BufferFlushInterval controls how often the buffer is force-flushed, even if it's not full.
// It is generally not useful, as it only matters for very low traffic services.
// Can be set by exporting an environment variable named JAEGER_REPORTER_FLUSH_INTERVAL
BufferFlushInterval time.Duration
// LogSpans, when true, enables LoggingReporter that runs in parallel with the main reporter
// and logs all submitted spans. Main Configuration.Logger must be initialized in the code
// for this option to have any effect.
// Can be set by exporting an environment variable named JAEGER_REPORTER_LOG_SPANS
LogSpans bool `yaml:"logSpans"`
// LocalAgentHostPort instructs reporter to send spans to jaeger-agent at this address
// Can be set by exporting an environment variable named JAEGER_AGENT_HOST / JAEGER_AGENT_PORT
LocalAgentHostPort string `yaml:"localAgentHostPort"`
}
// BaggageRestrictionsConfig configures the baggage restrictions manager which can be used to whitelist
// certain baggage keys. All fields are optional.
type BaggageRestrictionsConfig struct {
// DenyBaggageOnInitializationFailure controls the startup failure mode of the baggage restriction
// manager. If true, the manager will not allow any baggage to be written until baggage restrictions have
// been retrieved from jaeger-agent. If false, the manager wil allow any baggage to be written until baggage
// restrictions have been retrieved from jaeger-agent.
DenyBaggageOnInitializationFailure bool `yaml:"denyBaggageOnInitializationFailure"`
// HostPort is the hostPort of jaeger-agent's baggage restrictions server
HostPort string `yaml:"hostPort"`
// RefreshInterval controls how often the baggage restriction manager will poll
// jaeger-agent for the most recent baggage restrictions.
RefreshInterval time.Duration `yaml:"refreshInterval"`
}
// ThrottlerConfig configures the throttler which can be used to throttle the
// rate at which the client may send debug requests.
type ThrottlerConfig struct {
// HostPort of jaeger-agent's credit server.
HostPort string `yaml:"hostPort"`
// RefreshInterval controls how often the throttler will poll jaeger-agent
// for more throttling credits.
RefreshInterval time.Duration `yaml:"refreshInterval"`
// SynchronousInitialization determines whether or not the throttler should
// synchronously fetch credits from the agent when an operation is seen for
// the first time. This should be set to true if the client will be used by
// a short lived service that needs to ensure that credits are fetched
// upfront such that sampling or throttling occurs.
SynchronousInitialization bool `yaml:"synchronousInitialization"`
}
type nullCloser struct{}
func (*nullCloser) Close() error { return nil }
// New creates a new Jaeger Tracer, and a closer func that can be used to flush buffers
// before shutdown.
//
// Deprecated: use NewTracer() function
func (c Configuration) New(
serviceName string,
options ...Option,
) (opentracing.Tracer, io.Closer, error) {
if serviceName != "" {
c.ServiceName = serviceName
}
return c.NewTracer(options...)
}
// NewTracer returns a new tracer based on the current configuration, using the given options,
// and a closer func that can be used to flush buffers before shutdown.
func (c Configuration) NewTracer(options ...Option) (opentracing.Tracer, io.Closer, error) {
if c.ServiceName == "" {
return nil, nil, errors.New("no service name provided")
}
if c.Disabled {
return &opentracing.NoopTracer{}, &nullCloser{}, nil
}
opts := applyOptions(options...)
tracerMetrics := jaeger.NewMetrics(opts.metrics, nil)
if c.RPCMetrics {
Observer(
rpcmetrics.NewObserver(
opts.metrics.Namespace("jaeger-rpc", map[string]string{"component": "jaeger"}),
rpcmetrics.DefaultNameNormalizer,
),
)(&opts) // adds to c.observers
}
if c.Sampler == nil {
c.Sampler = &SamplerConfig{
Type: jaeger.SamplerTypeRemote,
Param: defaultSamplingProbability,
}
}
if c.Reporter == nil {
c.Reporter = &ReporterConfig{}
}
sampler := opts.sampler
if sampler == nil {
s, err := c.Sampler.NewSampler(c.ServiceName, tracerMetrics)
if err != nil {
return nil, nil, err
}
sampler = s
}
reporter := opts.reporter
if reporter == nil {
r, err := c.Reporter.NewReporter(c.ServiceName, tracerMetrics, opts.logger)
if err != nil {
return nil, nil, err
}
reporter = r
}
tracerOptions := []jaeger.TracerOption{
jaeger.TracerOptions.Metrics(tracerMetrics),
jaeger.TracerOptions.Logger(opts.logger),
jaeger.TracerOptions.CustomHeaderKeys(c.Headers),
jaeger.TracerOptions.Gen128Bit(opts.gen128Bit),
jaeger.TracerOptions.ZipkinSharedRPCSpan(opts.zipkinSharedRPCSpan),
}
for _, tag := range opts.tags {
tracerOptions = append(tracerOptions, jaeger.TracerOptions.Tag(tag.Key, tag.Value))
}
for _, tag := range c.Tags {
tracerOptions = append(tracerOptions, jaeger.TracerOptions.Tag(tag.Key, tag.Value))
}
for _, obs := range opts.observers {
tracerOptions = append(tracerOptions, jaeger.TracerOptions.Observer(obs))
}
for _, cobs := range opts.contribObservers {
tracerOptions = append(tracerOptions, jaeger.TracerOptions.ContribObserver(cobs))
}
for format, injector := range opts.injectors {
tracerOptions = append(tracerOptions, jaeger.TracerOptions.Injector(format, injector))
}
for format, extractor := range opts.extractors {
tracerOptions = append(tracerOptions, jaeger.TracerOptions.Extractor(format, extractor))
}
if c.BaggageRestrictions != nil {
mgr := remote.NewRestrictionManager(
c.ServiceName,
remote.Options.Metrics(tracerMetrics),
remote.Options.Logger(opts.logger),
remote.Options.HostPort(c.BaggageRestrictions.HostPort),
remote.Options.RefreshInterval(c.BaggageRestrictions.RefreshInterval),
remote.Options.DenyBaggageOnInitializationFailure(
c.BaggageRestrictions.DenyBaggageOnInitializationFailure,
),
)
tracerOptions = append(tracerOptions, jaeger.TracerOptions.BaggageRestrictionManager(mgr))
}
if c.Throttler != nil {
debugThrottler := throttler.NewThrottler(
c.ServiceName,
throttler.Options.Metrics(tracerMetrics),
throttler.Options.Logger(opts.logger),
throttler.Options.HostPort(c.Throttler.HostPort),
throttler.Options.RefreshInterval(c.Throttler.RefreshInterval),
throttler.Options.SynchronousInitialization(
c.Throttler.SynchronousInitialization,
),
)
tracerOptions = append(tracerOptions, jaeger.TracerOptions.DebugThrottler(debugThrottler))
}
tracer, closer := jaeger.NewTracer(
c.ServiceName,
sampler,
reporter,
tracerOptions...,
)
return tracer, closer, nil
}
// InitGlobalTracer creates a new Jaeger Tracer, and sets it as global OpenTracing Tracer.
// It returns a closer func that can be used to flush buffers before shutdown.
func (c Configuration) InitGlobalTracer(
serviceName string,
options ...Option,
) (io.Closer, error) {
if c.Disabled {
return &nullCloser{}, nil
}
tracer, closer, err := c.New(serviceName, options...)
if err != nil {
return nil, err
}
opentracing.SetGlobalTracer(tracer)
return closer, nil
}
// NewSampler creates a new sampler based on the configuration
func (sc *SamplerConfig) NewSampler(
serviceName string,
metrics *jaeger.Metrics,
) (jaeger.Sampler, error) {
samplerType := strings.ToLower(sc.Type)
if samplerType == jaeger.SamplerTypeConst {
return jaeger.NewConstSampler(sc.Param != 0), nil
}
if samplerType == jaeger.SamplerTypeProbabilistic {
if sc.Param >= 0 && sc.Param <= 1.0 {
return jaeger.NewProbabilisticSampler(sc.Param)
}
return nil, fmt.Errorf(
"Invalid Param for probabilistic sampler: %v. Expecting value between 0 and 1",
sc.Param,
)
}
if samplerType == jaeger.SamplerTypeRateLimiting {
return jaeger.NewRateLimitingSampler(sc.Param), nil
}
if samplerType == jaeger.SamplerTypeRemote || sc.Type == "" {
sc2 := *sc
sc2.Type = jaeger.SamplerTypeProbabilistic
initSampler, err := sc2.NewSampler(serviceName, nil)
if err != nil {
return nil, err
}
options := []jaeger.SamplerOption{
jaeger.SamplerOptions.Metrics(metrics),
jaeger.SamplerOptions.InitialSampler(initSampler),
jaeger.SamplerOptions.SamplingServerURL(sc.SamplingServerURL),
}
if sc.MaxOperations != 0 {
options = append(options, jaeger.SamplerOptions.MaxOperations(sc.MaxOperations))
}
if sc.SamplingRefreshInterval != 0 {
options = append(options, jaeger.SamplerOptions.SamplingRefreshInterval(sc.SamplingRefreshInterval))
}
return jaeger.NewRemotelyControlledSampler(serviceName, options...), nil
}
return nil, fmt.Errorf("Unknown sampler type %v", sc.Type)
}
// NewReporter instantiates a new reporter that submits spans to tcollector
func (rc *ReporterConfig) NewReporter(
serviceName string,
metrics *jaeger.Metrics,
logger jaeger.Logger,
) (jaeger.Reporter, error) {
sender, err := rc.newTransport()
if err != nil {
return nil, err
}
reporter := jaeger.NewRemoteReporter(
sender,
jaeger.ReporterOptions.QueueSize(rc.QueueSize),
jaeger.ReporterOptions.BufferFlushInterval(rc.BufferFlushInterval),
jaeger.ReporterOptions.Logger(logger),
jaeger.ReporterOptions.Metrics(metrics))
if rc.LogSpans && logger != nil {
logger.Infof("Initializing logging reporter\n")
reporter = jaeger.NewCompositeReporter(jaeger.NewLoggingReporter(logger), reporter)
}
return reporter, err
}
func (rc *ReporterConfig) newTransport() (jaeger.Transport, error) {
return jaeger.NewUDPTransport(rc.LocalAgentHostPort, 0)
}
|
vendor/github.com/uber/jaeger-client-go/config/config.go
| 0 |
https://github.com/grafana/grafana/commit/dc3a81200b1cd366bdf237ada152ae3d79bdaf59
|
[
0.00029543161508627236,
0.00017790135461837053,
0.00015982548939064145,
0.00017361456411890686,
0.000023214090106193908
] |
{
"id": 5,
"code_window": [
" }\n",
"\n",
" componentDidUpdate() {\n",
" this.loadPlugin();\n",
"\n",
" // handle angular plugin loading\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" console.log('componentDidUpdate');\n"
],
"file_path": "public/app/features/dashboard/dashgrid/DashboardPanel.tsx",
"type": "add",
"edit_start_line_idx": 76
}
|
import React, { ComponentClass } from 'react';
import $ from 'jquery';
import { PanelModel } from '../panel_model';
import { DashboardModel } from '../dashboard_model';
import { PanelHeader } from './PanelHeader';
import { DataPanel, PanelProps, DataPanelWrapper } from './DataPanel';
export interface Props {
panel: PanelModel;
dashboard: DashboardModel;
component: ComponentClass<PanelProps>;
}
interface State {}
export class PanelChrome extends React.Component<Props, State> {
panelComponent: DataPanel;
constructor(props) {
super(props);
this.panelComponent = DataPanelWrapper(this.props.component);
}
componentDidMount() {
console.log('panel chrome mounted');
}
render() {
let PanelComponent = this.panelComponent;
return (
<div className="panel-container">
<PanelHeader panel={this.props.panel} dashboard={this.props.dashboard} />
<div className="panel-content">{<PanelComponent type={'test'} queries={[]} isVisible={true} />}</div>
</div>
);
}
}
|
public/app/features/dashboard/dashgrid/PanelChrome.tsx
| 1 |
https://github.com/grafana/grafana/commit/dc3a81200b1cd366bdf237ada152ae3d79bdaf59
|
[
0.01868329755961895,
0.004797677509486675,
0.0001653400104260072,
0.000171036139363423,
0.008016866631805897
] |
{
"id": 5,
"code_window": [
" }\n",
"\n",
" componentDidUpdate() {\n",
" this.loadPlugin();\n",
"\n",
" // handle angular plugin loading\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" console.log('componentDidUpdate');\n"
],
"file_path": "public/app/features/dashboard/dashgrid/DashboardPanel.tsx",
"type": "add",
"edit_start_line_idx": 76
}
|
{
"rules": {
"no-string-throw": true,
"no-unused-expression": true,
"no-unused-variable": false,
"no-use-before-declare": false,
"no-duplicate-variable": true,
"curly": true,
"class-name": true,
"semicolon": [true, "always", "ignore-bound-class-methods"],
"triple-equals": [true, "allow-null-check"],
"comment-format": [false, "check-space"],
"eofline": true,
"forin": false,
"indent": [true, "spaces", 2],
"label-position": true,
"max-line-length": [true, 150],
"member-access": false,
"no-arg": true,
"no-bitwise": false,
"no-console": [true,
"debug",
"info",
"time",
"timeEnd",
"trace"
],
"no-construct": true,
"no-debugger": true,
"no-empty": false,
"no-eval": true,
"no-inferrable-types": true,
"no-shadowed-variable": false,
"no-string-literal": false,
"no-switch-case-fall-through": false,
"no-trailing-whitespace": true,
"no-var-keyword": false,
"object-literal-sort-keys": false,
"one-line": [true,
"check-open-brace",
"check-catch",
"check-else"
],
"radix": false,
"typedef-whitespace": [true, {
"call-signature": "nospace",
"index-signature": "nospace",
"parameter": "nospace",
"property-declaration": "nospace",
"variable-declaration": "nospace"
}],
"variable-name": [true, "ban-keywords"],
"whitespace": [true,
"check-branch",
"check-decl",
"check-type",
"check-preblock"
]
}
}
|
tslint.json
| 0 |
https://github.com/grafana/grafana/commit/dc3a81200b1cd366bdf237ada152ae3d79bdaf59
|
[
0.000179406808456406,
0.0001730969815980643,
0.0001714080135570839,
0.0001719961001072079,
0.0000026363838969700737
] |
{
"id": 5,
"code_window": [
" }\n",
"\n",
" componentDidUpdate() {\n",
" this.loadPlugin();\n",
"\n",
" // handle angular plugin loading\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" console.log('componentDidUpdate');\n"
],
"file_path": "public/app/features/dashboard/dashgrid/DashboardPanel.tsx",
"type": "add",
"edit_start_line_idx": 76
}
|
// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package cldr
import (
"encoding/xml"
"regexp"
"strconv"
)
// Elem is implemented by every XML element.
type Elem interface {
setEnclosing(Elem)
setName(string)
enclosing() Elem
GetCommon() *Common
}
type hidden struct {
CharData string `xml:",chardata"`
Alias *struct {
Common
Source string `xml:"source,attr"`
Path string `xml:"path,attr"`
} `xml:"alias"`
Def *struct {
Common
Choice string `xml:"choice,attr,omitempty"`
Type string `xml:"type,attr,omitempty"`
} `xml:"default"`
}
// Common holds several of the most common attributes and sub elements
// of an XML element.
type Common struct {
XMLName xml.Name
name string
enclElem Elem
Type string `xml:"type,attr,omitempty"`
Reference string `xml:"reference,attr,omitempty"`
Alt string `xml:"alt,attr,omitempty"`
ValidSubLocales string `xml:"validSubLocales,attr,omitempty"`
Draft string `xml:"draft,attr,omitempty"`
hidden
}
// Default returns the default type to select from the enclosed list
// or "" if no default value is specified.
func (e *Common) Default() string {
if e.Def == nil {
return ""
}
if e.Def.Choice != "" {
return e.Def.Choice
} else if e.Def.Type != "" {
// Type is still used by the default element in collation.
return e.Def.Type
}
return ""
}
// Element returns the XML element name.
func (e *Common) Element() string {
return e.name
}
// GetCommon returns e. It is provided such that Common implements Elem.
func (e *Common) GetCommon() *Common {
return e
}
// Data returns the character data accumulated for this element.
func (e *Common) Data() string {
e.CharData = charRe.ReplaceAllStringFunc(e.CharData, replaceUnicode)
return e.CharData
}
func (e *Common) setName(s string) {
e.name = s
}
func (e *Common) enclosing() Elem {
return e.enclElem
}
func (e *Common) setEnclosing(en Elem) {
e.enclElem = en
}
// Escape characters that can be escaped without further escaping the string.
var charRe = regexp.MustCompile(`&#x[0-9a-fA-F]*;|\\u[0-9a-fA-F]{4}|\\U[0-9a-fA-F]{8}|\\x[0-9a-fA-F]{2}|\\[0-7]{3}|\\[abtnvfr]`)
// replaceUnicode converts hexadecimal Unicode codepoint notations to a one-rune string.
// It assumes the input string is correctly formatted.
func replaceUnicode(s string) string {
if s[1] == '#' {
r, _ := strconv.ParseInt(s[3:len(s)-1], 16, 32)
return string(r)
}
r, _, _, _ := strconv.UnquoteChar(s, 0)
return string(r)
}
|
vendor/golang.org/x/text/unicode/cldr/base.go
| 0 |
https://github.com/grafana/grafana/commit/dc3a81200b1cd366bdf237ada152ae3d79bdaf59
|
[
0.00017649016808718443,
0.0001697854168014601,
0.00016426843649242073,
0.00016956702165771276,
0.0000033478786463092547
] |
{
"id": 5,
"code_window": [
" }\n",
"\n",
" componentDidUpdate() {\n",
" this.loadPlugin();\n",
"\n",
" // handle angular plugin loading\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" console.log('componentDidUpdate');\n"
],
"file_path": "public/app/features/dashboard/dashgrid/DashboardPanel.tsx",
"type": "add",
"edit_start_line_idx": 76
}
|
import './org_users_ctrl';
import './profile_ctrl';
import './org_users_ctrl';
import './select_org_ctrl';
import './change_password_ctrl';
import './new_org_ctrl';
import './user_invite_ctrl';
import './teams_ctrl';
import './team_details_ctrl';
import './create_team_ctrl';
import './org_api_keys_ctrl';
import './org_details_ctrl';
import './prefs_control';
|
public/app/features/org/all.ts
| 0 |
https://github.com/grafana/grafana/commit/dc3a81200b1cd366bdf237ada152ae3d79bdaf59
|
[
0.0001753299729898572,
0.0001739797298796475,
0.0001726294867694378,
0.0001739797298796475,
0.0000013502431102097034
] |
{
"id": 6,
"code_window": [
" />\n",
" </div>\n",
" {this.props.panel.isEditing && (\n",
" <div className=\"panel-editor-container__editor\">\n",
" <PanelEditor panel={this.props.panel} dashboard={this.props.dashboard} />\n",
" </div>\n",
" )}\n",
" </div>\n",
" );\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <PanelEditor\n",
" panel={this.props.panel}\n",
" panelType={this.props.panel.type}\n",
" dashboard={this.props.dashboard}\n",
" onTypeChanged={this.onPluginTypeChanged}\n",
" />\n"
],
"file_path": "public/app/features/dashboard/dashgrid/DashboardPanel.tsx",
"type": "replace",
"edit_start_line_idx": 114
}
|
import React from 'react';
import config from 'app/core/config';
import { PanelModel } from '../panel_model';
import { DashboardModel } from '../dashboard_model';
import { getAngularLoader, AngularComponent } from 'app/core/services/angular_loader';
import { DashboardRow } from './DashboardRow';
import { AddPanelPanel } from './AddPanelPanel';
import { importPluginModule } from 'app/features/plugins/plugin_loader';
import { PluginExports } from 'app/types/plugins';
import { PanelChrome } from './PanelChrome';
import { PanelEditor } from './PanelEditor';
export interface Props {
panel: PanelModel;
dashboard: DashboardModel;
}
export interface State {
pluginExports: PluginExports;
}
export class DashboardPanel extends React.Component<Props, State> {
element: any;
angularPanel: AngularComponent;
pluginInfo: any;
specialPanels = {};
constructor(props) {
super(props);
this.state = { pluginExports: null };
this.specialPanels['row'] = this.renderRow.bind(this);
this.specialPanels['add-panel'] = this.renderAddPanel.bind(this);
this.props.panel.events.on('panel-size-changed', this.triggerForceUpdate.bind(this));
}
triggerForceUpdate() {
this.forceUpdate();
}
isSpecial() {
return this.specialPanels[this.props.panel.type];
}
renderRow() {
return <DashboardRow panel={this.props.panel} dashboard={this.props.dashboard} />;
}
renderAddPanel() {
return <AddPanelPanel panel={this.props.panel} dashboard={this.props.dashboard} />;
}
loadPlugin() {
if (this.isSpecial()) {
return;
}
// handle plugin loading & changing of plugin type
if (!this.pluginInfo || this.pluginInfo.id !== this.props.panel.type) {
this.pluginInfo = config.panels[this.props.panel.type];
if (this.pluginInfo.exports) {
this.setState({ pluginExports: this.pluginInfo.exports });
} else {
importPluginModule(this.pluginInfo.module).then(pluginExports => {
this.setState({ pluginExports: pluginExports });
});
}
}
}
componentDidMount() {
this.loadPlugin();
}
componentDidUpdate() {
this.loadPlugin();
// handle angular plugin loading
if (!this.element || this.angularPanel) {
return;
}
let loader = getAngularLoader();
var template = '<plugin-component type="panel" class="panel-height-helper"></plugin-component>';
let scopeProps = { panel: this.props.panel, dashboard: this.props.dashboard };
this.angularPanel = loader.load(this.element, scopeProps, template);
}
componentWillUnmount() {
if (this.angularPanel) {
this.angularPanel.destroy();
}
}
renderReactPanel() {
const { pluginExports } = this.state;
const containerClass = this.props.panel.isEditing ? 'panel-editor-container' : 'panel-height-helper';
const panelWrapperClass = this.props.panel.isEditing ? 'panel-editor-container__panel' : 'panel-height-helper';
// this might look strange with these classes that change when edit, but
// I want to try to keep markup (parents) for panel the same in edit mode to avoide unmount / new mount of panel
// plugin component
return (
<div className={containerClass}>
<div className={panelWrapperClass}>
<PanelChrome
component={pluginExports.PanelComponent}
panel={this.props.panel}
dashboard={this.props.dashboard}
/>
</div>
{this.props.panel.isEditing && (
<div className="panel-editor-container__editor">
<PanelEditor panel={this.props.panel} dashboard={this.props.dashboard} />
</div>
)}
</div>
);
}
render() {
if (this.isSpecial()) {
return this.specialPanels[this.props.panel.type]();
}
if (!this.state.pluginExports) {
return null;
}
if (this.state.pluginExports.PanelComponent) {
return this.renderReactPanel();
}
// legacy angular rendering
return <div ref={element => (this.element = element)} className="panel-height-helper" />;
}
}
|
public/app/features/dashboard/dashgrid/DashboardPanel.tsx
| 1 |
https://github.com/grafana/grafana/commit/dc3a81200b1cd366bdf237ada152ae3d79bdaf59
|
[
0.996105968952179,
0.07451553642749786,
0.00016454514116048813,
0.0017156085232272744,
0.255639910697937
] |
{
"id": 6,
"code_window": [
" />\n",
" </div>\n",
" {this.props.panel.isEditing && (\n",
" <div className=\"panel-editor-container__editor\">\n",
" <PanelEditor panel={this.props.panel} dashboard={this.props.dashboard} />\n",
" </div>\n",
" )}\n",
" </div>\n",
" );\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <PanelEditor\n",
" panel={this.props.panel}\n",
" panelType={this.props.panel.type}\n",
" dashboard={this.props.dashboard}\n",
" onTypeChanged={this.onPluginTypeChanged}\n",
" />\n"
],
"file_path": "public/app/features/dashboard/dashgrid/DashboardPanel.tsx",
"type": "replace",
"edit_start_line_idx": 114
}
|
import React, { Component } from 'react';
import PermissionsList from './PermissionsList';
import { observer } from 'mobx-react';
import { FolderInfo } from './FolderInfo';
export interface DashboardAcl {
id?: number;
dashboardId?: number;
userId?: number;
userLogin?: string;
userEmail?: string;
teamId?: number;
team?: string;
permission?: number;
permissionName?: string;
role?: string;
icon?: string;
name?: string;
inherited?: boolean;
sortRank?: number;
}
export interface IProps {
dashboardId: number;
folderInfo?: FolderInfo;
permissions?: any;
isFolder: boolean;
backendSrv: any;
}
@observer
class Permissions extends Component<IProps, any> {
constructor(props) {
super(props);
const { dashboardId, isFolder, folderInfo } = this.props;
this.permissionChanged = this.permissionChanged.bind(this);
this.typeChanged = this.typeChanged.bind(this);
this.removeItem = this.removeItem.bind(this);
this.loadStore(dashboardId, isFolder, folderInfo && folderInfo.id === 0);
}
loadStore(dashboardId, isFolder, isInRoot = false) {
return this.props.permissions.load(dashboardId, isFolder, isInRoot);
}
permissionChanged(index: number, permission: number, permissionName: string) {
const { permissions } = this.props;
permissions.updatePermissionOnIndex(index, permission, permissionName);
}
removeItem(index: number) {
const { permissions } = this.props;
permissions.removeStoreItem(index);
}
resetNewType() {
const { permissions } = this.props;
permissions.resetNewType();
}
typeChanged(evt) {
const { value } = evt.target;
const { permissions, dashboardId } = this.props;
if (value === 'Viewer' || value === 'Editor') {
permissions.addStoreItem({ permission: 1, role: value, dashboardId: dashboardId }, dashboardId);
this.resetNewType();
return;
}
permissions.setNewType(value);
}
render() {
const { permissions, folderInfo } = this.props;
return (
<div className="gf-form-group">
<PermissionsList
permissions={permissions.items}
removeItem={this.removeItem}
permissionChanged={this.permissionChanged}
fetching={permissions.fetching}
folderInfo={folderInfo}
/>
</div>
);
}
}
export default Permissions;
|
public/app/core/components/Permissions/Permissions.tsx
| 0 |
https://github.com/grafana/grafana/commit/dc3a81200b1cd366bdf237ada152ae3d79bdaf59
|
[
0.003595721907913685,
0.0005790786817669868,
0.00016883923672139645,
0.0002345941320527345,
0.0010087761329486966
] |
{
"id": 6,
"code_window": [
" />\n",
" </div>\n",
" {this.props.panel.isEditing && (\n",
" <div className=\"panel-editor-container__editor\">\n",
" <PanelEditor panel={this.props.panel} dashboard={this.props.dashboard} />\n",
" </div>\n",
" )}\n",
" </div>\n",
" );\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <PanelEditor\n",
" panel={this.props.panel}\n",
" panelType={this.props.panel.type}\n",
" dashboard={this.props.dashboard}\n",
" onTypeChanged={this.onPluginTypeChanged}\n",
" />\n"
],
"file_path": "public/app/features/dashboard/dashgrid/DashboardPanel.tsx",
"type": "replace",
"edit_start_line_idx": 114
}
|
import { types } from 'mobx-state-tree';
export const PermissionsStoreItem = types
.model('PermissionsStoreItem', {
dashboardId: types.optional(types.number, -1),
permission: types.number,
permissionName: types.maybe(types.string),
role: types.maybe(types.string),
team: types.optional(types.string, ''),
teamId: types.optional(types.number, 0),
userEmail: types.optional(types.string, ''),
userId: types.optional(types.number, 0),
userLogin: types.optional(types.string, ''),
inherited: types.maybe(types.boolean),
sortRank: types.maybe(types.number),
icon: types.maybe(types.string),
name: types.maybe(types.string),
teamAvatarUrl: types.maybe(types.string),
userAvatarUrl: types.maybe(types.string),
})
.actions(self => ({
updateRole: role => {
self.role = role;
},
updatePermission(permission: number, permissionName: string) {
self.permission = permission;
self.permissionName = permissionName;
},
}));
|
public/app/stores/PermissionsStore/PermissionsStoreItem.ts
| 0 |
https://github.com/grafana/grafana/commit/dc3a81200b1cd366bdf237ada152ae3d79bdaf59
|
[
0.00017520297842565924,
0.00017026346176862717,
0.0001662548747844994,
0.00016933257575146854,
0.0000037118793443369213
] |
{
"id": 6,
"code_window": [
" />\n",
" </div>\n",
" {this.props.panel.isEditing && (\n",
" <div className=\"panel-editor-container__editor\">\n",
" <PanelEditor panel={this.props.panel} dashboard={this.props.dashboard} />\n",
" </div>\n",
" )}\n",
" </div>\n",
" );\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <PanelEditor\n",
" panel={this.props.panel}\n",
" panelType={this.props.panel.type}\n",
" dashboard={this.props.dashboard}\n",
" onTypeChanged={this.onPluginTypeChanged}\n",
" />\n"
],
"file_path": "public/app/features/dashboard/dashgrid/DashboardPanel.tsx",
"type": "replace",
"edit_start_line_idx": 114
}
|
// Copyright 2016 The Xorm Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package xorm
import (
"errors"
"fmt"
"reflect"
"strconv"
"strings"
"github.com/go-xorm/core"
)
// Insert insert one or more beans
func (session *Session) Insert(beans ...interface{}) (int64, error) {
var affected int64
var err error
if session.isAutoClose {
defer session.Close()
}
for _, bean := range beans {
sliceValue := reflect.Indirect(reflect.ValueOf(bean))
if sliceValue.Kind() == reflect.Slice {
size := sliceValue.Len()
if size > 0 {
if session.engine.SupportInsertMany() {
cnt, err := session.innerInsertMulti(bean)
if err != nil {
return affected, err
}
affected += cnt
} else {
for i := 0; i < size; i++ {
cnt, err := session.innerInsert(sliceValue.Index(i).Interface())
if err != nil {
return affected, err
}
affected += cnt
}
}
}
} else {
cnt, err := session.innerInsert(bean)
if err != nil {
return affected, err
}
affected += cnt
}
}
return affected, err
}
func (session *Session) innerInsertMulti(rowsSlicePtr interface{}) (int64, error) {
sliceValue := reflect.Indirect(reflect.ValueOf(rowsSlicePtr))
if sliceValue.Kind() != reflect.Slice {
return 0, errors.New("needs a pointer to a slice")
}
if sliceValue.Len() <= 0 {
return 0, errors.New("could not insert a empty slice")
}
if err := session.statement.setRefValue(reflect.ValueOf(sliceValue.Index(0).Interface())); err != nil {
return 0, err
}
if len(session.statement.TableName()) <= 0 {
return 0, ErrTableNotFound
}
table := session.statement.RefTable
size := sliceValue.Len()
var colNames []string
var colMultiPlaces []string
var args []interface{}
var cols []*core.Column
for i := 0; i < size; i++ {
v := sliceValue.Index(i)
vv := reflect.Indirect(v)
elemValue := v.Interface()
var colPlaces []string
// handle BeforeInsertProcessor
// !nashtsai! does user expect it's same slice to passed closure when using Before()/After() when insert multi??
for _, closure := range session.beforeClosures {
closure(elemValue)
}
if processor, ok := interface{}(elemValue).(BeforeInsertProcessor); ok {
processor.BeforeInsert()
}
// --
if i == 0 {
for _, col := range table.Columns() {
ptrFieldValue, err := col.ValueOfV(&vv)
if err != nil {
return 0, err
}
fieldValue := *ptrFieldValue
if col.IsAutoIncrement && isZero(fieldValue.Interface()) {
continue
}
if col.MapType == core.ONLYFROMDB {
continue
}
if col.IsDeleted {
continue
}
if session.statement.ColumnStr != "" {
if _, ok := getFlagForColumn(session.statement.columnMap, col); !ok {
continue
}
}
if session.statement.OmitStr != "" {
if _, ok := getFlagForColumn(session.statement.columnMap, col); ok {
continue
}
}
if (col.IsCreated || col.IsUpdated) && session.statement.UseAutoTime {
val, t := session.engine.nowTime(col)
args = append(args, val)
var colName = col.Name
session.afterClosures = append(session.afterClosures, func(bean interface{}) {
col := table.GetColumn(colName)
setColumnTime(bean, col, t)
})
} else if col.IsVersion && session.statement.checkVersion {
args = append(args, 1)
var colName = col.Name
session.afterClosures = append(session.afterClosures, func(bean interface{}) {
col := table.GetColumn(colName)
setColumnInt(bean, col, 1)
})
} else {
arg, err := session.value2Interface(col, fieldValue)
if err != nil {
return 0, err
}
args = append(args, arg)
}
colNames = append(colNames, col.Name)
cols = append(cols, col)
colPlaces = append(colPlaces, "?")
}
} else {
for _, col := range cols {
ptrFieldValue, err := col.ValueOfV(&vv)
if err != nil {
return 0, err
}
fieldValue := *ptrFieldValue
if col.IsAutoIncrement && isZero(fieldValue.Interface()) {
continue
}
if col.MapType == core.ONLYFROMDB {
continue
}
if col.IsDeleted {
continue
}
if session.statement.ColumnStr != "" {
if _, ok := getFlagForColumn(session.statement.columnMap, col); !ok {
continue
}
}
if session.statement.OmitStr != "" {
if _, ok := getFlagForColumn(session.statement.columnMap, col); ok {
continue
}
}
if (col.IsCreated || col.IsUpdated) && session.statement.UseAutoTime {
val, t := session.engine.nowTime(col)
args = append(args, val)
var colName = col.Name
session.afterClosures = append(session.afterClosures, func(bean interface{}) {
col := table.GetColumn(colName)
setColumnTime(bean, col, t)
})
} else if col.IsVersion && session.statement.checkVersion {
args = append(args, 1)
var colName = col.Name
session.afterClosures = append(session.afterClosures, func(bean interface{}) {
col := table.GetColumn(colName)
setColumnInt(bean, col, 1)
})
} else {
arg, err := session.value2Interface(col, fieldValue)
if err != nil {
return 0, err
}
args = append(args, arg)
}
colPlaces = append(colPlaces, "?")
}
}
colMultiPlaces = append(colMultiPlaces, strings.Join(colPlaces, ", "))
}
cleanupProcessorsClosures(&session.beforeClosures)
var sql = "INSERT INTO %s (%v%v%v) VALUES (%v)"
var statement string
var tableName = session.statement.TableName()
if session.engine.dialect.DBType() == core.ORACLE {
sql = "INSERT ALL INTO %s (%v%v%v) VALUES (%v) SELECT 1 FROM DUAL"
temp := fmt.Sprintf(") INTO %s (%v%v%v) VALUES (",
session.engine.Quote(tableName),
session.engine.QuoteStr(),
strings.Join(colNames, session.engine.QuoteStr()+", "+session.engine.QuoteStr()),
session.engine.QuoteStr())
statement = fmt.Sprintf(sql,
session.engine.Quote(tableName),
session.engine.QuoteStr(),
strings.Join(colNames, session.engine.QuoteStr()+", "+session.engine.QuoteStr()),
session.engine.QuoteStr(),
strings.Join(colMultiPlaces, temp))
} else {
statement = fmt.Sprintf(sql,
session.engine.Quote(tableName),
session.engine.QuoteStr(),
strings.Join(colNames, session.engine.QuoteStr()+", "+session.engine.QuoteStr()),
session.engine.QuoteStr(),
strings.Join(colMultiPlaces, "),("))
}
res, err := session.exec(statement, args...)
if err != nil {
return 0, err
}
if cacher := session.engine.getCacher2(table); cacher != nil && session.statement.UseCache {
session.cacheInsert(table, tableName)
}
lenAfterClosures := len(session.afterClosures)
for i := 0; i < size; i++ {
elemValue := reflect.Indirect(sliceValue.Index(i)).Addr().Interface()
// handle AfterInsertProcessor
if session.isAutoCommit {
// !nashtsai! does user expect it's same slice to passed closure when using Before()/After() when insert multi??
for _, closure := range session.afterClosures {
closure(elemValue)
}
if processor, ok := interface{}(elemValue).(AfterInsertProcessor); ok {
processor.AfterInsert()
}
} else {
if lenAfterClosures > 0 {
if value, has := session.afterInsertBeans[elemValue]; has && value != nil {
*value = append(*value, session.afterClosures...)
} else {
afterClosures := make([]func(interface{}), lenAfterClosures)
copy(afterClosures, session.afterClosures)
session.afterInsertBeans[elemValue] = &afterClosures
}
} else {
if _, ok := interface{}(elemValue).(AfterInsertProcessor); ok {
session.afterInsertBeans[elemValue] = nil
}
}
}
}
cleanupProcessorsClosures(&session.afterClosures)
return res.RowsAffected()
}
// InsertMulti insert multiple records
func (session *Session) InsertMulti(rowsSlicePtr interface{}) (int64, error) {
if session.isAutoClose {
defer session.Close()
}
sliceValue := reflect.Indirect(reflect.ValueOf(rowsSlicePtr))
if sliceValue.Kind() != reflect.Slice {
return 0, ErrParamsType
}
if sliceValue.Len() <= 0 {
return 0, nil
}
return session.innerInsertMulti(rowsSlicePtr)
}
func (session *Session) innerInsert(bean interface{}) (int64, error) {
if err := session.statement.setRefValue(rValue(bean)); err != nil {
return 0, err
}
if len(session.statement.TableName()) <= 0 {
return 0, ErrTableNotFound
}
table := session.statement.RefTable
// handle BeforeInsertProcessor
for _, closure := range session.beforeClosures {
closure(bean)
}
cleanupProcessorsClosures(&session.beforeClosures) // cleanup after used
if processor, ok := interface{}(bean).(BeforeInsertProcessor); ok {
processor.BeforeInsert()
}
// --
colNames, args, err := genCols(session.statement.RefTable, session, bean, false, false)
if err != nil {
return 0, err
}
// insert expr columns, override if exists
exprColumns := session.statement.getExpr()
exprColVals := make([]string, 0, len(exprColumns))
for _, v := range exprColumns {
// remove the expr columns
for i, colName := range colNames {
if colName == v.colName {
colNames = append(colNames[:i], colNames[i+1:]...)
args = append(args[:i], args[i+1:]...)
}
}
// append expr column to the end
colNames = append(colNames, v.colName)
exprColVals = append(exprColVals, v.expr)
}
colPlaces := strings.Repeat("?, ", len(colNames)-len(exprColumns))
if len(exprColVals) > 0 {
colPlaces = colPlaces + strings.Join(exprColVals, ", ")
} else {
if len(colPlaces) > 0 {
colPlaces = colPlaces[0 : len(colPlaces)-2]
}
}
var sqlStr string
var tableName = session.statement.TableName()
if len(colPlaces) > 0 {
sqlStr = fmt.Sprintf("INSERT INTO %s (%v%v%v) VALUES (%v)",
session.engine.Quote(tableName),
session.engine.QuoteStr(),
strings.Join(colNames, session.engine.Quote(", ")),
session.engine.QuoteStr(),
colPlaces)
} else {
if session.engine.dialect.DBType() == core.MYSQL {
sqlStr = fmt.Sprintf("INSERT INTO %s VALUES ()", session.engine.Quote(tableName))
} else {
sqlStr = fmt.Sprintf("INSERT INTO %s DEFAULT VALUES", session.engine.Quote(tableName))
}
}
handleAfterInsertProcessorFunc := func(bean interface{}) {
if session.isAutoCommit {
for _, closure := range session.afterClosures {
closure(bean)
}
if processor, ok := interface{}(bean).(AfterInsertProcessor); ok {
processor.AfterInsert()
}
} else {
lenAfterClosures := len(session.afterClosures)
if lenAfterClosures > 0 {
if value, has := session.afterInsertBeans[bean]; has && value != nil {
*value = append(*value, session.afterClosures...)
} else {
afterClosures := make([]func(interface{}), lenAfterClosures)
copy(afterClosures, session.afterClosures)
session.afterInsertBeans[bean] = &afterClosures
}
} else {
if _, ok := interface{}(bean).(AfterInsertProcessor); ok {
session.afterInsertBeans[bean] = nil
}
}
}
cleanupProcessorsClosures(&session.afterClosures) // cleanup after used
}
// for postgres, many of them didn't implement lastInsertId, so we should
// implemented it ourself.
if session.engine.dialect.DBType() == core.ORACLE && len(table.AutoIncrement) > 0 {
res, err := session.queryBytes("select seq_atable.currval from dual", args...)
if err != nil {
return 0, err
}
defer handleAfterInsertProcessorFunc(bean)
if cacher := session.engine.getCacher2(table); cacher != nil && session.statement.UseCache {
session.cacheInsert(table, tableName)
}
if table.Version != "" && session.statement.checkVersion {
verValue, err := table.VersionColumn().ValueOf(bean)
if err != nil {
session.engine.logger.Error(err)
} else if verValue.IsValid() && verValue.CanSet() {
verValue.SetInt(1)
}
}
if len(res) < 1 {
return 0, errors.New("insert no error but not returned id")
}
idByte := res[0][table.AutoIncrement]
id, err := strconv.ParseInt(string(idByte), 10, 64)
if err != nil || id <= 0 {
return 1, err
}
aiValue, err := table.AutoIncrColumn().ValueOf(bean)
if err != nil {
session.engine.logger.Error(err)
}
if aiValue == nil || !aiValue.IsValid() || !aiValue.CanSet() {
return 1, nil
}
aiValue.Set(int64ToIntValue(id, aiValue.Type()))
return 1, nil
} else if session.engine.dialect.DBType() == core.POSTGRES && len(table.AutoIncrement) > 0 {
//assert table.AutoIncrement != ""
sqlStr = sqlStr + " RETURNING " + session.engine.Quote(table.AutoIncrement)
res, err := session.queryBytes(sqlStr, args...)
if err != nil {
return 0, err
}
defer handleAfterInsertProcessorFunc(bean)
if cacher := session.engine.getCacher2(table); cacher != nil && session.statement.UseCache {
session.cacheInsert(table, tableName)
}
if table.Version != "" && session.statement.checkVersion {
verValue, err := table.VersionColumn().ValueOf(bean)
if err != nil {
session.engine.logger.Error(err)
} else if verValue.IsValid() && verValue.CanSet() {
verValue.SetInt(1)
}
}
if len(res) < 1 {
return 0, errors.New("insert no error but not returned id")
}
idByte := res[0][table.AutoIncrement]
id, err := strconv.ParseInt(string(idByte), 10, 64)
if err != nil || id <= 0 {
return 1, err
}
aiValue, err := table.AutoIncrColumn().ValueOf(bean)
if err != nil {
session.engine.logger.Error(err)
}
if aiValue == nil || !aiValue.IsValid() || !aiValue.CanSet() {
return 1, nil
}
aiValue.Set(int64ToIntValue(id, aiValue.Type()))
return 1, nil
} else {
res, err := session.exec(sqlStr, args...)
if err != nil {
return 0, err
}
defer handleAfterInsertProcessorFunc(bean)
if cacher := session.engine.getCacher2(table); cacher != nil && session.statement.UseCache {
session.cacheInsert(table, tableName)
}
if table.Version != "" && session.statement.checkVersion {
verValue, err := table.VersionColumn().ValueOf(bean)
if err != nil {
session.engine.logger.Error(err)
} else if verValue.IsValid() && verValue.CanSet() {
verValue.SetInt(1)
}
}
if table.AutoIncrement == "" {
return res.RowsAffected()
}
var id int64
id, err = res.LastInsertId()
if err != nil || id <= 0 {
return res.RowsAffected()
}
aiValue, err := table.AutoIncrColumn().ValueOf(bean)
if err != nil {
session.engine.logger.Error(err)
}
if aiValue == nil || !aiValue.IsValid() || !aiValue.CanSet() {
return res.RowsAffected()
}
aiValue.Set(int64ToIntValue(id, aiValue.Type()))
return res.RowsAffected()
}
}
// InsertOne insert only one struct into database as a record.
// The in parameter bean must a struct or a point to struct. The return
// parameter is inserted and error
func (session *Session) InsertOne(bean interface{}) (int64, error) {
if session.isAutoClose {
defer session.Close()
}
return session.innerInsert(bean)
}
func (session *Session) cacheInsert(table *core.Table, tables ...string) error {
if table == nil {
return ErrCacheFailed
}
cacher := session.engine.getCacher2(table)
for _, t := range tables {
session.engine.logger.Debug("[cache] clear sql:", t)
cacher.ClearIds(t)
}
return nil
}
|
vendor/github.com/go-xorm/xorm/session_insert.go
| 0 |
https://github.com/grafana/grafana/commit/dc3a81200b1cd366bdf237ada152ae3d79bdaf59
|
[
0.00017691779066808522,
0.00016987787967082113,
0.00016112673620227724,
0.00017046387074515224,
0.0000030612677619501483
] |
{
"id": 7,
"code_window": [
"import React, { ComponentClass } from 'react';\n",
"import $ from 'jquery';\n",
"import { PanelModel } from '../panel_model';\n",
"import { DashboardModel } from '../dashboard_model';\n",
"import { PanelHeader } from './PanelHeader';\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "public/app/features/dashboard/dashgrid/PanelChrome.tsx",
"type": "replace",
"edit_start_line_idx": 1
}
|
import React from 'react';
import classNames from 'classnames';
import { PanelModel } from '../panel_model';
import { DashboardModel } from '../dashboard_model';
import { store } from 'app/stores/store';
import { observer } from 'mobx-react';
import { QueriesTab } from './QueriesTab';
import { PanelPlugin } from 'app/types/plugins';
import { VizTypePicker } from './VizTypePicker';
interface PanelEditorProps {
panel: PanelModel;
dashboard: DashboardModel;
}
interface PanelEditorTab {
id: string;
text: string;
icon: string;
}
@observer
export class PanelEditor extends React.Component<PanelEditorProps, any> {
tabs: PanelEditorTab[];
constructor(props) {
super(props);
this.tabs = [
{ id: 'queries', text: 'Queries', icon: 'fa fa-database' },
{ id: 'viz', text: 'Visualization', icon: 'fa fa-line-chart' },
];
}
renderQueriesTab() {
return <QueriesTab panel={this.props.panel} dashboard={this.props.dashboard} />;
}
renderVizTab() {
return (
<div className="viz-editor">
<div className="viz-editor-col1">
<VizTypePicker currentType={this.props.panel.type} onTypeChanged={this.onVizTypeChanged} />
</div>
<div className="viz-editor-col2">
<h5 className="page-heading">Options</h5>
</div>
</div>
);
}
onVizTypeChanged = (plugin: PanelPlugin) => {
console.log('changing type to ', plugin.id);
this.props.panel.changeType(plugin.id);
};
onChangeTab = (tab: PanelEditorTab) => {
store.view.updateQuery({ tab: tab.id }, false);
};
render() {
const activeTab: string = store.view.query.get('tab') || 'queries';
return (
<div className="tabbed-view tabbed-view--new">
<div className="tabbed-view-header">
<ul className="gf-tabs">
{this.tabs.map(tab => {
return <TabItem tab={tab} activeTab={activeTab} onClick={this.onChangeTab} key={tab.id} />;
})}
</ul>
<button className="tabbed-view-close-btn" ng-click="ctrl.exitFullscreen();">
<i className="fa fa-remove" />
</button>
</div>
<div className="tabbed-view-body">
{activeTab === 'queries' && this.renderQueriesTab()}
{activeTab === 'viz' && this.renderVizTab()}
</div>
</div>
);
}
}
interface TabItemParams {
tab: PanelEditorTab;
activeTab: string;
onClick: (tab: PanelEditorTab) => void;
}
function TabItem({ tab, activeTab, onClick }: TabItemParams) {
const tabClasses = classNames({
'gf-tabs-link': true,
active: activeTab === tab.id,
});
return (
<li className="gf-tabs-item" key={tab.id}>
<a className={tabClasses} onClick={() => onClick(tab)}>
<i className={tab.icon} />
{tab.text}
</a>
</li>
);
}
|
public/app/features/dashboard/dashgrid/PanelEditor.tsx
| 1 |
https://github.com/grafana/grafana/commit/dc3a81200b1cd366bdf237ada152ae3d79bdaf59
|
[
0.0031305074226111174,
0.0006063090986572206,
0.00016608518490102142,
0.00018918560817837715,
0.0008319158805534244
] |
{
"id": 7,
"code_window": [
"import React, { ComponentClass } from 'react';\n",
"import $ from 'jquery';\n",
"import { PanelModel } from '../panel_model';\n",
"import { DashboardModel } from '../dashboard_model';\n",
"import { PanelHeader } from './PanelHeader';\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "public/app/features/dashboard/dashgrid/PanelChrome.tsx",
"type": "replace",
"edit_start_line_idx": 1
}
|
package models
import "errors"
var ErrInvalidEmailCode = errors.New("Invalid or expired email code")
var ErrSmtpNotEnabled = errors.New("SMTP not configured, check your grafana.ini config file's [smtp] section.")
type SendEmailCommand struct {
To []string
Template string
Subject string
Data map[string]interface{}
Info string
EmbededFiles []string
}
type SendEmailCommandSync struct {
SendEmailCommand
}
type SendWebhookSync struct {
Url string
User string
Password string
Body string
HttpMethod string
HttpHeader map[string]string
ContentType string
}
type SendResetPasswordEmailCommand struct {
User *User
}
type ValidateResetPasswordCodeQuery struct {
Code string
Result *User
}
|
pkg/models/notifications.go
| 0 |
https://github.com/grafana/grafana/commit/dc3a81200b1cd366bdf237ada152ae3d79bdaf59
|
[
0.00016985360707622021,
0.00016879000759217888,
0.0001682519941823557,
0.0001685272145550698,
6.44723172626982e-7
] |
{
"id": 7,
"code_window": [
"import React, { ComponentClass } from 'react';\n",
"import $ from 'jquery';\n",
"import { PanelModel } from '../panel_model';\n",
"import { DashboardModel } from '../dashboard_model';\n",
"import { PanelHeader } from './PanelHeader';\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "public/app/features/dashboard/dashgrid/PanelChrome.tsx",
"type": "replace",
"edit_start_line_idx": 1
}
|
<svg xmlns="http://www.w3.org/2000/svg" width="800" height="500" viewBox="0 0 800 500">
<metadata><?xpacket begin="" id="W5M0MpCehiHzreSzNTczkc9d"?>
<x:xmpmeta xmlns:x="adobe:ns:meta/" x:xmptk="Adobe XMP Core 5.6-c138 79.159824, 2016/09/14-01:09:01 ">
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
<rdf:Description rdf:about=""/>
</rdf:RDF>
</x:xmpmeta>
<?xpacket end="w"?></metadata>
<defs>
<style>
.cls-1, .cls-2 {
fill: none;
}
.cls-1 {
stroke: #7d7d7d;
stroke-width: 1px;
opacity: 0.4;
}
.cls-1, .cls-2, .cls-3 {
fill-rule: evenodd;
}
.cls-2, .cls-3 {
stroke: #7eb26d;
}
.cls-2 {
stroke-width: 3px;
}
.cls-3 {
fill: #7eb26d;
stroke-width: 3.221px;
opacity: 0.2;
}
</style>
</defs>
<path id="Form_3" data-name="Form 3" class="cls-1" d="M0,2V500H800"/>
<path id="Form_4" data-name="Form 4" class="cls-1" d="M160,2V500"/>
<path id="Form_5" data-name="Form 5" class="cls-1" d="M320,1V500"/>
<path id="Form_6" data-name="Form 6" class="cls-1" d="M480,1V500"/>
<path id="Form_7" data-name="Form 7" class="cls-1" d="M640,2V500"/>
<path id="Form_8" data-name="Form 8" class="cls-1" d="M0,100H801"/>
<path id="Form_9" data-name="Form 9" class="cls-1" d="M0,200H801"/>
<path id="Form_10" data-name="Form 10" class="cls-1" d="M0,300H798"/>
<path id="Form_11" data-name="Form 11" class="cls-1" d="M0,400H800"/>
<path id="Form_12" data-name="Form 12" class="cls-2" d="M0,0C0,299.762,320.7,500,800,500"/>
<path id="Form_12_kopiera" data-name="Form 12 kopiera" class="cls-3" d="M800,500C320.7,500,0,299.762,0,0V500H800Z"/>
</svg>
|
public/img/graph404.svg
| 0 |
https://github.com/grafana/grafana/commit/dc3a81200b1cd366bdf237ada152ae3d79bdaf59
|
[
0.00017630834190640599,
0.00017195504915434867,
0.00016710419731680304,
0.0001718173298286274,
0.000002724836349443649
] |
{
"id": 7,
"code_window": [
"import React, { ComponentClass } from 'react';\n",
"import $ from 'jquery';\n",
"import { PanelModel } from '../panel_model';\n",
"import { DashboardModel } from '../dashboard_model';\n",
"import { PanelHeader } from './PanelHeader';\n"
],
"labels": [
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "public/app/features/dashboard/dashgrid/PanelChrome.tsx",
"type": "replace",
"edit_start_line_idx": 1
}
|
// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package build // import "golang.org/x/text/collate/build"
import (
"fmt"
"io"
"log"
"sort"
"strings"
"unicode/utf8"
"golang.org/x/text/internal/colltab"
"golang.org/x/text/language"
"golang.org/x/text/unicode/norm"
)
// TODO: optimizations:
// - expandElem is currently 20K. By putting unique colElems in a separate
// table and having a byte array of indexes into this table, we can reduce
// the total size to about 7K. By also factoring out the length bytes, we
// can reduce this to about 6K.
// - trie valueBlocks are currently 100K. There are a lot of sparse blocks
// and many consecutive values with the same stride. This can be further
// compacted.
// - Compress secondary weights into 8 bits.
// - Some LDML specs specify a context element. Currently we simply concatenate
// those. Context can be implemented using the contraction trie. If Builder
// could analyze and detect when using a context makes sense, there is no
// need to expose this construct in the API.
// A Builder builds a root collation table. The user must specify the
// collation elements for each entry. A common use will be to base the weights
// on those specified in the allkeys* file as provided by the UCA or CLDR.
type Builder struct {
index *trieBuilder
root ordering
locale []*Tailoring
t *table
err error
built bool
minNonVar int // lowest primary recorded for a variable
varTop int // highest primary recorded for a non-variable
// indexes used for reusing expansions and contractions
expIndex map[string]int // positions of expansions keyed by their string representation
ctHandle map[string]ctHandle // contraction handles keyed by a concatenation of the suffixes
ctElem map[string]int // contraction elements keyed by their string representation
}
// A Tailoring builds a collation table based on another collation table.
// The table is defined by specifying tailorings to the underlying table.
// See http://unicode.org/reports/tr35/ for an overview of tailoring
// collation tables. The CLDR contains pre-defined tailorings for a variety
// of languages (See http://www.unicode.org/Public/cldr/<version>/core.zip.)
type Tailoring struct {
id string
builder *Builder
index *ordering
anchor *entry
before bool
}
// NewBuilder returns a new Builder.
func NewBuilder() *Builder {
return &Builder{
index: newTrieBuilder(),
root: makeRootOrdering(),
expIndex: make(map[string]int),
ctHandle: make(map[string]ctHandle),
ctElem: make(map[string]int),
}
}
// Tailoring returns a Tailoring for the given locale. One should
// have completed all calls to Add before calling Tailoring.
func (b *Builder) Tailoring(loc language.Tag) *Tailoring {
t := &Tailoring{
id: loc.String(),
builder: b,
index: b.root.clone(),
}
t.index.id = t.id
b.locale = append(b.locale, t)
return t
}
// Add adds an entry to the collation element table, mapping
// a slice of runes to a sequence of collation elements.
// A collation element is specified as list of weights: []int{primary, secondary, ...}.
// The entries are typically obtained from a collation element table
// as defined in http://www.unicode.org/reports/tr10/#Data_Table_Format.
// Note that the collation elements specified by colelems are only used
// as a guide. The actual weights generated by Builder may differ.
// The argument variables is a list of indices into colelems that should contain
// a value for each colelem that is a variable. (See the reference above.)
func (b *Builder) Add(runes []rune, colelems [][]int, variables []int) error {
str := string(runes)
elems := make([]rawCE, len(colelems))
for i, ce := range colelems {
if len(ce) == 0 {
break
}
elems[i] = makeRawCE(ce, 0)
if len(ce) == 1 {
elems[i].w[1] = defaultSecondary
}
if len(ce) <= 2 {
elems[i].w[2] = defaultTertiary
}
if len(ce) <= 3 {
elems[i].w[3] = ce[0]
}
}
for i, ce := range elems {
p := ce.w[0]
isvar := false
for _, j := range variables {
if i == j {
isvar = true
}
}
if isvar {
if p >= b.minNonVar && b.minNonVar > 0 {
return fmt.Errorf("primary value %X of variable is larger than the smallest non-variable %X", p, b.minNonVar)
}
if p > b.varTop {
b.varTop = p
}
} else if p > 1 { // 1 is a special primary value reserved for FFFE
if p <= b.varTop {
return fmt.Errorf("primary value %X of non-variable is smaller than the highest variable %X", p, b.varTop)
}
if b.minNonVar == 0 || p < b.minNonVar {
b.minNonVar = p
}
}
}
elems, err := convertLargeWeights(elems)
if err != nil {
return err
}
cccs := []uint8{}
nfd := norm.NFD.String(str)
for i := range nfd {
cccs = append(cccs, norm.NFD.PropertiesString(nfd[i:]).CCC())
}
if len(cccs) < len(elems) {
if len(cccs) > 2 {
return fmt.Errorf("number of decomposed characters should be greater or equal to the number of collation elements for len(colelems) > 3 (%d < %d)", len(cccs), len(elems))
}
p := len(elems) - 1
for ; p > 0 && elems[p].w[0] == 0; p-- {
elems[p].ccc = cccs[len(cccs)-1]
}
for ; p >= 0; p-- {
elems[p].ccc = cccs[0]
}
} else {
for i := range elems {
elems[i].ccc = cccs[i]
}
}
// doNorm in collate.go assumes that the following conditions hold.
if len(elems) > 1 && len(cccs) > 1 && cccs[0] != 0 && cccs[0] != cccs[len(cccs)-1] {
return fmt.Errorf("incompatible CCC values for expansion %X (%d)", runes, cccs)
}
b.root.newEntry(str, elems)
return nil
}
func (t *Tailoring) setAnchor(anchor string) error {
anchor = norm.NFC.String(anchor)
a := t.index.find(anchor)
if a == nil {
a = t.index.newEntry(anchor, nil)
a.implicit = true
a.modified = true
for _, r := range []rune(anchor) {
e := t.index.find(string(r))
e.lock = true
}
}
t.anchor = a
return nil
}
// SetAnchor sets the point after which elements passed in subsequent calls to
// Insert will be inserted. It is equivalent to the reset directive in an LDML
// specification. See Insert for an example.
// SetAnchor supports the following logical reset positions:
// <first_tertiary_ignorable/>, <last_teriary_ignorable/>, <first_primary_ignorable/>,
// and <last_non_ignorable/>.
func (t *Tailoring) SetAnchor(anchor string) error {
if err := t.setAnchor(anchor); err != nil {
return err
}
t.before = false
return nil
}
// SetAnchorBefore is similar to SetAnchor, except that subsequent calls to
// Insert will insert entries before the anchor.
func (t *Tailoring) SetAnchorBefore(anchor string) error {
if err := t.setAnchor(anchor); err != nil {
return err
}
t.before = true
return nil
}
// Insert sets the ordering of str relative to the entry set by the previous
// call to SetAnchor or Insert. The argument extend corresponds
// to the extend elements as defined in LDML. A non-empty value for extend
// will cause the collation elements corresponding to extend to be appended
// to the collation elements generated for the entry added by Insert.
// This has the same net effect as sorting str after the string anchor+extend.
// See http://www.unicode.org/reports/tr10/#Tailoring_Example for details
// on parametric tailoring and http://unicode.org/reports/tr35/#Collation_Elements
// for full details on LDML.
//
// Examples: create a tailoring for Swedish, where "ä" is ordered after "z"
// at the primary sorting level:
// t := b.Tailoring("se")
// t.SetAnchor("z")
// t.Insert(colltab.Primary, "ä", "")
// Order "ü" after "ue" at the secondary sorting level:
// t.SetAnchor("ue")
// t.Insert(colltab.Secondary, "ü","")
// or
// t.SetAnchor("u")
// t.Insert(colltab.Secondary, "ü", "e")
// Order "q" afer "ab" at the secondary level and "Q" after "q"
// at the tertiary level:
// t.SetAnchor("ab")
// t.Insert(colltab.Secondary, "q", "")
// t.Insert(colltab.Tertiary, "Q", "")
// Order "b" before "a":
// t.SetAnchorBefore("a")
// t.Insert(colltab.Primary, "b", "")
// Order "0" after the last primary ignorable:
// t.SetAnchor("<last_primary_ignorable/>")
// t.Insert(colltab.Primary, "0", "")
func (t *Tailoring) Insert(level colltab.Level, str, extend string) error {
if t.anchor == nil {
return fmt.Errorf("%s:Insert: no anchor point set for tailoring of %s", t.id, str)
}
str = norm.NFC.String(str)
e := t.index.find(str)
if e == nil {
e = t.index.newEntry(str, nil)
} else if e.logical != noAnchor {
return fmt.Errorf("%s:Insert: cannot reinsert logical reset position %q", t.id, e.str)
}
if e.lock {
return fmt.Errorf("%s:Insert: cannot reinsert element %q", t.id, e.str)
}
a := t.anchor
// Find the first element after the anchor which differs at a level smaller or
// equal to the given level. Then insert at this position.
// See http://unicode.org/reports/tr35/#Collation_Elements, Section 5.14.5 for details.
e.before = t.before
if t.before {
t.before = false
if a.prev == nil {
a.insertBefore(e)
} else {
for a = a.prev; a.level > level; a = a.prev {
}
a.insertAfter(e)
}
e.level = level
} else {
for ; a.level > level; a = a.next {
}
e.level = a.level
if a != e {
a.insertAfter(e)
a.level = level
} else {
// We don't set a to prev itself. This has the effect of the entry
// getting new collation elements that are an increment of itself.
// This is intentional.
a.prev.level = level
}
}
e.extend = norm.NFD.String(extend)
e.exclude = false
e.modified = true
e.elems = nil
t.anchor = e
return nil
}
func (o *ordering) getWeight(e *entry) []rawCE {
if len(e.elems) == 0 && e.logical == noAnchor {
if e.implicit {
for _, r := range e.runes {
e.elems = append(e.elems, o.getWeight(o.find(string(r)))...)
}
} else if e.before {
count := [colltab.Identity + 1]int{}
a := e
for ; a.elems == nil && !a.implicit; a = a.next {
count[a.level]++
}
e.elems = []rawCE{makeRawCE(a.elems[0].w, a.elems[0].ccc)}
for i := colltab.Primary; i < colltab.Quaternary; i++ {
if count[i] != 0 {
e.elems[0].w[i] -= count[i]
break
}
}
if e.prev != nil {
o.verifyWeights(e.prev, e, e.prev.level)
}
} else {
prev := e.prev
e.elems = nextWeight(prev.level, o.getWeight(prev))
o.verifyWeights(e, e.next, e.level)
}
}
return e.elems
}
func (o *ordering) addExtension(e *entry) {
if ex := o.find(e.extend); ex != nil {
e.elems = append(e.elems, ex.elems...)
} else {
for _, r := range []rune(e.extend) {
e.elems = append(e.elems, o.find(string(r)).elems...)
}
}
e.extend = ""
}
func (o *ordering) verifyWeights(a, b *entry, level colltab.Level) error {
if level == colltab.Identity || b == nil || b.elems == nil || a.elems == nil {
return nil
}
for i := colltab.Primary; i < level; i++ {
if a.elems[0].w[i] < b.elems[0].w[i] {
return nil
}
}
if a.elems[0].w[level] >= b.elems[0].w[level] {
err := fmt.Errorf("%s:overflow: collation elements of %q (%X) overflows those of %q (%X) at level %d (%X >= %X)", o.id, a.str, a.runes, b.str, b.runes, level, a.elems, b.elems)
log.Println(err)
// TODO: return the error instead, or better, fix the conflicting entry by making room.
}
return nil
}
func (b *Builder) error(e error) {
if e != nil {
b.err = e
}
}
func (b *Builder) errorID(locale string, e error) {
if e != nil {
b.err = fmt.Errorf("%s:%v", locale, e)
}
}
// patchNorm ensures that NFC and NFD counterparts are consistent.
func (o *ordering) patchNorm() {
// Insert the NFD counterparts, if necessary.
for _, e := range o.ordered {
nfd := norm.NFD.String(e.str)
if nfd != e.str {
if e0 := o.find(nfd); e0 != nil && !e0.modified {
e0.elems = e.elems
} else if e.modified && !equalCEArrays(o.genColElems(nfd), e.elems) {
e := o.newEntry(nfd, e.elems)
e.modified = true
}
}
}
// Update unchanged composed forms if one of their parts changed.
for _, e := range o.ordered {
nfd := norm.NFD.String(e.str)
if e.modified || nfd == e.str {
continue
}
if e0 := o.find(nfd); e0 != nil {
e.elems = e0.elems
} else {
e.elems = o.genColElems(nfd)
if norm.NFD.LastBoundary([]byte(nfd)) == 0 {
r := []rune(nfd)
head := string(r[0])
tail := ""
for i := 1; i < len(r); i++ {
s := norm.NFC.String(head + string(r[i]))
if e0 := o.find(s); e0 != nil && e0.modified {
head = s
} else {
tail += string(r[i])
}
}
e.elems = append(o.genColElems(head), o.genColElems(tail)...)
}
}
}
// Exclude entries for which the individual runes generate the same collation elements.
for _, e := range o.ordered {
if len(e.runes) > 1 && equalCEArrays(o.genColElems(e.str), e.elems) {
e.exclude = true
}
}
}
func (b *Builder) buildOrdering(o *ordering) {
for _, e := range o.ordered {
o.getWeight(e)
}
for _, e := range o.ordered {
o.addExtension(e)
}
o.patchNorm()
o.sort()
simplify(o)
b.processExpansions(o) // requires simplify
b.processContractions(o) // requires simplify
t := newNode()
for e := o.front(); e != nil; e, _ = e.nextIndexed() {
if !e.skip() {
ce, err := e.encode()
b.errorID(o.id, err)
t.insert(e.runes[0], ce)
}
}
o.handle = b.index.addTrie(t)
}
func (b *Builder) build() (*table, error) {
if b.built {
return b.t, b.err
}
b.built = true
b.t = &table{
Table: colltab.Table{
MaxContractLen: utf8.UTFMax,
VariableTop: uint32(b.varTop),
},
}
b.buildOrdering(&b.root)
b.t.root = b.root.handle
for _, t := range b.locale {
b.buildOrdering(t.index)
if b.err != nil {
break
}
}
i, err := b.index.generate()
b.t.trie = *i
b.t.Index = colltab.Trie{
Index: i.index,
Values: i.values,
Index0: i.index[blockSize*b.t.root.lookupStart:],
Values0: i.values[blockSize*b.t.root.valueStart:],
}
b.error(err)
return b.t, b.err
}
// Build builds the root Collator.
func (b *Builder) Build() (colltab.Weighter, error) {
table, err := b.build()
if err != nil {
return nil, err
}
return table, nil
}
// Build builds a Collator for Tailoring t.
func (t *Tailoring) Build() (colltab.Weighter, error) {
// TODO: implement.
return nil, nil
}
// Print prints the tables for b and all its Tailorings as a Go file
// that can be included in the Collate package.
func (b *Builder) Print(w io.Writer) (n int, err error) {
p := func(nn int, e error) {
n += nn
if err == nil {
err = e
}
}
t, err := b.build()
if err != nil {
return 0, err
}
p(fmt.Fprintf(w, `var availableLocales = "und`))
for _, loc := range b.locale {
if loc.id != "und" {
p(fmt.Fprintf(w, ",%s", loc.id))
}
}
p(fmt.Fprint(w, "\"\n\n"))
p(fmt.Fprintf(w, "const varTop = 0x%x\n\n", b.varTop))
p(fmt.Fprintln(w, "var locales = [...]tableIndex{"))
for _, loc := range b.locale {
if loc.id == "und" {
p(t.fprintIndex(w, loc.index.handle, loc.id))
}
}
for _, loc := range b.locale {
if loc.id != "und" {
p(t.fprintIndex(w, loc.index.handle, loc.id))
}
}
p(fmt.Fprint(w, "}\n\n"))
n, _, err = t.fprint(w, "main")
return
}
// reproducibleFromNFKD checks whether the given expansion could be generated
// from an NFKD expansion.
func reproducibleFromNFKD(e *entry, exp, nfkd []rawCE) bool {
// Length must be equal.
if len(exp) != len(nfkd) {
return false
}
for i, ce := range exp {
// Primary and secondary values should be equal.
if ce.w[0] != nfkd[i].w[0] || ce.w[1] != nfkd[i].w[1] {
return false
}
// Tertiary values should be equal to maxTertiary for third element onwards.
// TODO: there seem to be a lot of cases in CLDR (e.g. ㏭ in zh.xml) that can
// simply be dropped. Try this out by dropping the following code.
if i >= 2 && ce.w[2] != maxTertiary {
return false
}
if _, err := makeCE(ce); err != nil {
// Simply return false. The error will be caught elsewhere.
return false
}
}
return true
}
func simplify(o *ordering) {
// Runes that are a starter of a contraction should not be removed.
// (To date, there is only Kannada character 0CCA.)
keep := make(map[rune]bool)
for e := o.front(); e != nil; e, _ = e.nextIndexed() {
if len(e.runes) > 1 {
keep[e.runes[0]] = true
}
}
// Tag entries for which the runes NFKD decompose to identical values.
for e := o.front(); e != nil; e, _ = e.nextIndexed() {
s := e.str
nfkd := norm.NFKD.String(s)
nfd := norm.NFD.String(s)
if e.decompose || len(e.runes) > 1 || len(e.elems) == 1 || keep[e.runes[0]] || nfkd == nfd {
continue
}
if reproducibleFromNFKD(e, e.elems, o.genColElems(nfkd)) {
e.decompose = true
}
}
}
// appendExpansion converts the given collation sequence to
// collation elements and adds them to the expansion table.
// It returns an index to the expansion table.
func (b *Builder) appendExpansion(e *entry) int {
t := b.t
i := len(t.ExpandElem)
ce := uint32(len(e.elems))
t.ExpandElem = append(t.ExpandElem, ce)
for _, w := range e.elems {
ce, err := makeCE(w)
if err != nil {
b.error(err)
return -1
}
t.ExpandElem = append(t.ExpandElem, ce)
}
return i
}
// processExpansions extracts data necessary to generate
// the extraction tables.
func (b *Builder) processExpansions(o *ordering) {
for e := o.front(); e != nil; e, _ = e.nextIndexed() {
if !e.expansion() {
continue
}
key := fmt.Sprintf("%v", e.elems)
i, ok := b.expIndex[key]
if !ok {
i = b.appendExpansion(e)
b.expIndex[key] = i
}
e.expansionIndex = i
}
}
func (b *Builder) processContractions(o *ordering) {
// Collate contractions per starter rune.
starters := []rune{}
cm := make(map[rune][]*entry)
for e := o.front(); e != nil; e, _ = e.nextIndexed() {
if e.contraction() {
if len(e.str) > b.t.MaxContractLen {
b.t.MaxContractLen = len(e.str)
}
r := e.runes[0]
if _, ok := cm[r]; !ok {
starters = append(starters, r)
}
cm[r] = append(cm[r], e)
}
}
// Add entries of single runes that are at a start of a contraction.
for e := o.front(); e != nil; e, _ = e.nextIndexed() {
if !e.contraction() {
r := e.runes[0]
if _, ok := cm[r]; ok {
cm[r] = append(cm[r], e)
}
}
}
// Build the tries for the contractions.
t := b.t
for _, r := range starters {
l := cm[r]
// Compute suffix strings. There are 31 different contraction suffix
// sets for 715 contractions and 82 contraction starter runes as of
// version 6.0.0.
sufx := []string{}
hasSingle := false
for _, e := range l {
if len(e.runes) > 1 {
sufx = append(sufx, string(e.runes[1:]))
} else {
hasSingle = true
}
}
if !hasSingle {
b.error(fmt.Errorf("no single entry for starter rune %U found", r))
continue
}
// Unique the suffix set.
sort.Strings(sufx)
key := strings.Join(sufx, "\n")
handle, ok := b.ctHandle[key]
if !ok {
var err error
handle, err = appendTrie(&t.ContractTries, sufx)
if err != nil {
b.error(err)
}
b.ctHandle[key] = handle
}
// Bucket sort entries in index order.
es := make([]*entry, len(l))
for _, e := range l {
var p, sn int
if len(e.runes) > 1 {
str := []byte(string(e.runes[1:]))
p, sn = lookup(&t.ContractTries, handle, str)
if sn != len(str) {
log.Fatalf("%s: processContractions: unexpected length for '%X'; len=%d; want %d", o.id, e.runes, sn, len(str))
}
}
if es[p] != nil {
log.Fatalf("%s: multiple contractions for position %d for rune %U", o.id, p, e.runes[0])
}
es[p] = e
}
// Create collation elements for contractions.
elems := []uint32{}
for _, e := range es {
ce, err := e.encodeBase()
b.errorID(o.id, err)
elems = append(elems, ce)
}
key = fmt.Sprintf("%v", elems)
i, ok := b.ctElem[key]
if !ok {
i = len(t.ContractElem)
b.ctElem[key] = i
t.ContractElem = append(t.ContractElem, elems...)
}
// Store info in entry for starter rune.
es[0].contractionIndex = i
es[0].contractionHandle = handle
}
}
|
vendor/golang.org/x/text/collate/build/builder.go
| 0 |
https://github.com/grafana/grafana/commit/dc3a81200b1cd366bdf237ada152ae3d79bdaf59
|
[
0.00017910992028191686,
0.00017349822155665606,
0.00016132659220602363,
0.00017435253539588302,
0.000003463050688878866
] |
{
"id": 8,
"code_window": [
"\n",
"interface State {}\n",
"\n",
"export class PanelChrome extends React.Component<Props, State> {\n",
" panelComponent: DataPanel;\n",
"\n",
" constructor(props) {\n",
" super(props);\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"// cache DataPanel wrapper components\n",
"const dataPanels: { [s: string]: DataPanel } = {};\n",
"\n"
],
"file_path": "public/app/features/dashboard/dashgrid/PanelChrome.tsx",
"type": "add",
"edit_start_line_idx": 15
}
|
import React, { ComponentClass } from 'react';
import $ from 'jquery';
import { PanelModel } from '../panel_model';
import { DashboardModel } from '../dashboard_model';
import { PanelHeader } from './PanelHeader';
import { DataPanel, PanelProps, DataPanelWrapper } from './DataPanel';
export interface Props {
panel: PanelModel;
dashboard: DashboardModel;
component: ComponentClass<PanelProps>;
}
interface State {}
export class PanelChrome extends React.Component<Props, State> {
panelComponent: DataPanel;
constructor(props) {
super(props);
this.panelComponent = DataPanelWrapper(this.props.component);
}
componentDidMount() {
console.log('panel chrome mounted');
}
render() {
let PanelComponent = this.panelComponent;
return (
<div className="panel-container">
<PanelHeader panel={this.props.panel} dashboard={this.props.dashboard} />
<div className="panel-content">{<PanelComponent type={'test'} queries={[]} isVisible={true} />}</div>
</div>
);
}
}
|
public/app/features/dashboard/dashgrid/PanelChrome.tsx
| 1 |
https://github.com/grafana/grafana/commit/dc3a81200b1cd366bdf237ada152ae3d79bdaf59
|
[
0.9979984164237976,
0.25270557403564453,
0.0004005912342108786,
0.006211709231138229,
0.4303058385848999
] |
{
"id": 8,
"code_window": [
"\n",
"interface State {}\n",
"\n",
"export class PanelChrome extends React.Component<Props, State> {\n",
" panelComponent: DataPanel;\n",
"\n",
" constructor(props) {\n",
" super(props);\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"// cache DataPanel wrapper components\n",
"const dataPanels: { [s: string]: DataPanel } = {};\n",
"\n"
],
"file_path": "public/app/features/dashboard/dashgrid/PanelChrome.tsx",
"type": "add",
"edit_start_line_idx": 15
}
|
import _ from 'lodash';
import kbn from 'app/core/utils/kbn';
import { Variable, assignModelProperties, variableTypes } from './variable';
export class IntervalVariable implements Variable {
name: string;
auto_count: number;
auto_min: number;
options: any;
auto: boolean;
query: string;
refresh: number;
current: any;
defaults = {
type: 'interval',
name: '',
hide: 0,
label: '',
refresh: 2,
options: [],
current: {},
query: '1m,10m,30m,1h,6h,12h,1d,7d,14d,30d',
auto: false,
auto_min: '10s',
auto_count: 30,
};
/** @ngInject **/
constructor(private model, private timeSrv, private templateSrv, private variableSrv) {
assignModelProperties(this, model, this.defaults);
this.refresh = 2;
}
getSaveModel() {
assignModelProperties(this.model, this, this.defaults);
return this.model;
}
setValue(option) {
this.updateAutoValue();
return this.variableSrv.setOptionAsCurrent(this, option);
}
updateAutoValue() {
if (!this.auto) {
return;
}
// add auto option if missing
if (this.options.length && this.options[0].text !== 'auto') {
this.options.unshift({
text: 'auto',
value: '$__auto_interval_' + this.name,
});
}
var res = kbn.calculateInterval(this.timeSrv.timeRange(), this.auto_count, this.auto_min);
this.templateSrv.setGrafanaVariable('$__auto_interval_' + this.name, res.interval);
// for backward compatibility, to be removed eventually
this.templateSrv.setGrafanaVariable('$__auto_interval', res.interval);
}
updateOptions() {
// extract options between quotes and/or comma
this.options = _.map(this.query.match(/(["'])(.*?)\1|\w+/g), function(text) {
text = text.replace(/["']+/g, '');
return { text: text.trim(), value: text.trim() };
});
this.updateAutoValue();
return this.variableSrv.validateVariableSelectionState(this);
}
dependsOn(variable) {
return false;
}
setValueFromUrl(urlValue) {
this.updateAutoValue();
return this.variableSrv.setOptionFromUrl(this, urlValue);
}
getValueForUrl() {
return this.current.value;
}
}
variableTypes['interval'] = {
name: 'Interval',
ctor: IntervalVariable,
description: 'Define a timespan interval (ex 1m, 1h, 1d)',
};
|
public/app/features/templating/interval_variable.ts
| 0 |
https://github.com/grafana/grafana/commit/dc3a81200b1cd366bdf237ada152ae3d79bdaf59
|
[
0.0008677568985149264,
0.00024209854018408805,
0.0001694432139629498,
0.00017279094026889652,
0.00020856251649092883
] |
{
"id": 8,
"code_window": [
"\n",
"interface State {}\n",
"\n",
"export class PanelChrome extends React.Component<Props, State> {\n",
" panelComponent: DataPanel;\n",
"\n",
" constructor(props) {\n",
" super(props);\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"// cache DataPanel wrapper components\n",
"const dataPanels: { [s: string]: DataPanel } = {};\n",
"\n"
],
"file_path": "public/app/features/dashboard/dashgrid/PanelChrome.tsx",
"type": "add",
"edit_start_line_idx": 15
}
|
package hclog
import (
"log"
"io/ioutil"
)
// NewNullLogger instantiates a Logger for which all calls
// will succeed without doing anything.
// Useful for testing purposes.
func NewNullLogger() Logger {
return &nullLogger{}
}
type nullLogger struct{}
func (l *nullLogger) Trace(msg string, args ...interface{}) {}
func (l *nullLogger) Debug(msg string, args ...interface{}) {}
func (l *nullLogger) Info(msg string, args ...interface{}) {}
func (l *nullLogger) Warn(msg string, args ...interface{}) {}
func (l *nullLogger) Error(msg string, args ...interface{}) {}
func (l *nullLogger) IsTrace() bool { return false }
func (l *nullLogger) IsDebug() bool { return false }
func (l *nullLogger) IsInfo() bool { return false }
func (l *nullLogger) IsWarn() bool { return false }
func (l *nullLogger) IsError() bool { return false }
func (l *nullLogger) With(args ...interface{}) Logger { return l }
func (l *nullLogger) Named(name string) Logger { return l }
func (l *nullLogger) ResetNamed(name string) Logger { return l }
func (l *nullLogger) StandardLogger(opts *StandardLoggerOptions) *log.Logger {
return log.New(ioutil.Discard, "", log.LstdFlags)
}
|
vendor/github.com/hashicorp/go-hclog/nulllogger.go
| 0 |
https://github.com/grafana/grafana/commit/dc3a81200b1cd366bdf237ada152ae3d79bdaf59
|
[
0.0001729108626022935,
0.0001705184840830043,
0.00016610798775218427,
0.0001709223142825067,
0.0000024798710001050495
] |
{
"id": 8,
"code_window": [
"\n",
"interface State {}\n",
"\n",
"export class PanelChrome extends React.Component<Props, State> {\n",
" panelComponent: DataPanel;\n",
"\n",
" constructor(props) {\n",
" super(props);\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"// cache DataPanel wrapper components\n",
"const dataPanels: { [s: string]: DataPanel } = {};\n",
"\n"
],
"file_path": "public/app/features/dashboard/dashgrid/PanelChrome.tsx",
"type": "add",
"edit_start_line_idx": 15
}
|
package middleware
import (
"testing"
"time"
"github.com/grafana/grafana/pkg/login"
m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/session"
"github.com/grafana/grafana/pkg/setting"
. "github.com/smartystreets/goconvey/convey"
"gopkg.in/macaron.v1"
)
func TestAuthProxyWithLdapEnabled(t *testing.T) {
Convey("When calling sync grafana user with ldap user", t, func() {
setting.LdapEnabled = true
setting.AuthProxyLdapSyncTtl = 60
servers := []*login.LdapServerConf{{Host: "127.0.0.1"}}
login.LdapCfg = login.LdapConfig{Servers: servers}
mockLdapAuther := mockLdapAuthenticator{}
login.NewLdapAuthenticator = func(server *login.LdapServerConf) login.ILdapAuther {
return &mockLdapAuther
}
Convey("When user logs in, call SyncUser", func() {
// arrange
sess := newMockSession()
ctx := m.ReqContext{Session: &sess}
So(sess.Get(session.SESS_KEY_LASTLDAPSYNC), ShouldBeNil)
// act
syncGrafanaUserWithLdapUser(&m.LoginUserQuery{
ReqContext: &ctx,
Username: "test",
})
// assert
So(mockLdapAuther.syncUserCalled, ShouldBeTrue)
So(sess.Get(session.SESS_KEY_LASTLDAPSYNC), ShouldBeGreaterThan, 0)
})
Convey("When session variable not expired, don't sync and don't change session var", func() {
// arrange
sess := newMockSession()
ctx := m.ReqContext{Session: &sess}
now := time.Now().Unix()
sess.Set(session.SESS_KEY_LASTLDAPSYNC, now)
sess.Set(AUTH_PROXY_SESSION_VAR, "test")
// act
syncGrafanaUserWithLdapUser(&m.LoginUserQuery{
ReqContext: &ctx,
Username: "test",
})
// assert
So(sess.Get(session.SESS_KEY_LASTLDAPSYNC), ShouldEqual, now)
So(mockLdapAuther.syncUserCalled, ShouldBeFalse)
})
Convey("When lastldapsync is expired, session variable should be updated", func() {
// arrange
sess := newMockSession()
ctx := m.ReqContext{Session: &sess}
expiredTime := time.Now().Add(time.Duration(-120) * time.Minute).Unix()
sess.Set(session.SESS_KEY_LASTLDAPSYNC, expiredTime)
sess.Set(AUTH_PROXY_SESSION_VAR, "test")
// act
syncGrafanaUserWithLdapUser(&m.LoginUserQuery{
ReqContext: &ctx,
Username: "test",
})
// assert
So(sess.Get(session.SESS_KEY_LASTLDAPSYNC), ShouldBeGreaterThan, expiredTime)
So(mockLdapAuther.syncUserCalled, ShouldBeTrue)
})
})
}
type mockSession struct {
value map[interface{}]interface{}
}
func newMockSession() mockSession {
session := mockSession{}
session.value = make(map[interface{}]interface{})
return session
}
func (s *mockSession) Start(c *macaron.Context) error {
return nil
}
func (s *mockSession) Set(k interface{}, v interface{}) error {
s.value[k] = v
return nil
}
func (s *mockSession) Get(k interface{}) interface{} {
return s.value[k]
}
func (s *mockSession) Delete(k interface{}) interface{} {
delete(s.value, k)
return nil
}
func (s *mockSession) ID() string {
return ""
}
func (s *mockSession) Release() error {
return nil
}
func (s *mockSession) Destory(c *macaron.Context) error {
return nil
}
func (s *mockSession) RegenerateId(c *macaron.Context) error {
return nil
}
type mockLdapAuthenticator struct {
syncUserCalled bool
}
func (a *mockLdapAuthenticator) Login(query *m.LoginUserQuery) error {
return nil
}
func (a *mockLdapAuthenticator) SyncUser(query *m.LoginUserQuery) error {
a.syncUserCalled = true
return nil
}
func (a *mockLdapAuthenticator) GetGrafanaUserFor(ctx *m.ReqContext, ldapUser *login.LdapUserInfo) (*m.User, error) {
return nil, nil
}
|
pkg/middleware/auth_proxy_test.go
| 0 |
https://github.com/grafana/grafana/commit/dc3a81200b1cd366bdf237ada152ae3d79bdaf59
|
[
0.00017461340758018196,
0.0001724755420582369,
0.0001690554345259443,
0.00017264299094676971,
0.0000012621569567272672
] |
{
"id": 9,
"code_window": [
" panelComponent: DataPanel;\n",
"\n",
" constructor(props) {\n",
" super(props);\n",
"\n",
" this.panelComponent = DataPanelWrapper(this.props.component);\n",
" }\n",
"\n",
" componentDidMount() {\n",
" console.log('panel chrome mounted');\n",
" }\n",
"\n",
" render() {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "public/app/features/dashboard/dashgrid/PanelChrome.tsx",
"type": "replace",
"edit_start_line_idx": 20
}
|
import React from 'react';
import config from 'app/core/config';
import { PanelModel } from '../panel_model';
import { DashboardModel } from '../dashboard_model';
import { getAngularLoader, AngularComponent } from 'app/core/services/angular_loader';
import { DashboardRow } from './DashboardRow';
import { AddPanelPanel } from './AddPanelPanel';
import { importPluginModule } from 'app/features/plugins/plugin_loader';
import { PluginExports } from 'app/types/plugins';
import { PanelChrome } from './PanelChrome';
import { PanelEditor } from './PanelEditor';
export interface Props {
panel: PanelModel;
dashboard: DashboardModel;
}
export interface State {
pluginExports: PluginExports;
}
export class DashboardPanel extends React.Component<Props, State> {
element: any;
angularPanel: AngularComponent;
pluginInfo: any;
specialPanels = {};
constructor(props) {
super(props);
this.state = { pluginExports: null };
this.specialPanels['row'] = this.renderRow.bind(this);
this.specialPanels['add-panel'] = this.renderAddPanel.bind(this);
this.props.panel.events.on('panel-size-changed', this.triggerForceUpdate.bind(this));
}
triggerForceUpdate() {
this.forceUpdate();
}
isSpecial() {
return this.specialPanels[this.props.panel.type];
}
renderRow() {
return <DashboardRow panel={this.props.panel} dashboard={this.props.dashboard} />;
}
renderAddPanel() {
return <AddPanelPanel panel={this.props.panel} dashboard={this.props.dashboard} />;
}
loadPlugin() {
if (this.isSpecial()) {
return;
}
// handle plugin loading & changing of plugin type
if (!this.pluginInfo || this.pluginInfo.id !== this.props.panel.type) {
this.pluginInfo = config.panels[this.props.panel.type];
if (this.pluginInfo.exports) {
this.setState({ pluginExports: this.pluginInfo.exports });
} else {
importPluginModule(this.pluginInfo.module).then(pluginExports => {
this.setState({ pluginExports: pluginExports });
});
}
}
}
componentDidMount() {
this.loadPlugin();
}
componentDidUpdate() {
this.loadPlugin();
// handle angular plugin loading
if (!this.element || this.angularPanel) {
return;
}
let loader = getAngularLoader();
var template = '<plugin-component type="panel" class="panel-height-helper"></plugin-component>';
let scopeProps = { panel: this.props.panel, dashboard: this.props.dashboard };
this.angularPanel = loader.load(this.element, scopeProps, template);
}
componentWillUnmount() {
if (this.angularPanel) {
this.angularPanel.destroy();
}
}
renderReactPanel() {
const { pluginExports } = this.state;
const containerClass = this.props.panel.isEditing ? 'panel-editor-container' : 'panel-height-helper';
const panelWrapperClass = this.props.panel.isEditing ? 'panel-editor-container__panel' : 'panel-height-helper';
// this might look strange with these classes that change when edit, but
// I want to try to keep markup (parents) for panel the same in edit mode to avoide unmount / new mount of panel
// plugin component
return (
<div className={containerClass}>
<div className={panelWrapperClass}>
<PanelChrome
component={pluginExports.PanelComponent}
panel={this.props.panel}
dashboard={this.props.dashboard}
/>
</div>
{this.props.panel.isEditing && (
<div className="panel-editor-container__editor">
<PanelEditor panel={this.props.panel} dashboard={this.props.dashboard} />
</div>
)}
</div>
);
}
render() {
if (this.isSpecial()) {
return this.specialPanels[this.props.panel.type]();
}
if (!this.state.pluginExports) {
return null;
}
if (this.state.pluginExports.PanelComponent) {
return this.renderReactPanel();
}
// legacy angular rendering
return <div ref={element => (this.element = element)} className="panel-height-helper" />;
}
}
|
public/app/features/dashboard/dashgrid/DashboardPanel.tsx
| 1 |
https://github.com/grafana/grafana/commit/dc3a81200b1cd366bdf237ada152ae3d79bdaf59
|
[
0.7515829205513,
0.057859890162944794,
0.00017331312119495124,
0.0031673209741711617,
0.19247224926948547
] |
{
"id": 9,
"code_window": [
" panelComponent: DataPanel;\n",
"\n",
" constructor(props) {\n",
" super(props);\n",
"\n",
" this.panelComponent = DataPanelWrapper(this.props.component);\n",
" }\n",
"\n",
" componentDidMount() {\n",
" console.log('panel chrome mounted');\n",
" }\n",
"\n",
" render() {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "public/app/features/dashboard/dashgrid/PanelChrome.tsx",
"type": "replace",
"edit_start_line_idx": 20
}
|
package tsdb
import (
"context"
"github.com/grafana/grafana/pkg/models"
)
type HandleRequestFunc func(ctx context.Context, dsInfo *models.DataSource, req *TsdbQuery) (*Response, error)
func HandleRequest(ctx context.Context, dsInfo *models.DataSource, req *TsdbQuery) (*Response, error) {
endpoint, err := getTsdbQueryEndpointFor(dsInfo)
if err != nil {
return nil, err
}
return endpoint.Query(ctx, dsInfo, req)
}
|
pkg/tsdb/request.go
| 0 |
https://github.com/grafana/grafana/commit/dc3a81200b1cd366bdf237ada152ae3d79bdaf59
|
[
0.0001652259088587016,
0.0001649636251386255,
0.0001647013268666342,
0.0001649636251386255,
2.622909960336983e-7
] |
{
"id": 9,
"code_window": [
" panelComponent: DataPanel;\n",
"\n",
" constructor(props) {\n",
" super(props);\n",
"\n",
" this.panelComponent = DataPanelWrapper(this.props.component);\n",
" }\n",
"\n",
" componentDidMount() {\n",
" console.log('panel chrome mounted');\n",
" }\n",
"\n",
" render() {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "public/app/features/dashboard/dashgrid/PanelChrome.tsx",
"type": "replace",
"edit_start_line_idx": 20
}
|
package influxdb
import "time"
type Query struct {
Measurement string
Policy string
ResultFormat string
Tags []*Tag
GroupBy []*QueryPart
Selects []*Select
RawQuery string
UseRawQuery bool
Alias string
Interval time.Duration
}
type Tag struct {
Key string
Operator string
Value string
Condition string
}
type Select []QueryPart
type InfluxDbSelect struct {
Type string
}
type Response struct {
Results []Result
Err error
}
type Result struct {
Series []Row
Messages []*Message
Err error
}
type Message struct {
Level string `json:"level,omitempty"`
Text string `json:"text,omitempty"`
}
type Row struct {
Name string `json:"name,omitempty"`
Tags map[string]string `json:"tags,omitempty"`
Columns []string `json:"columns,omitempty"`
Values [][]interface{} `json:"values,omitempty"`
}
|
pkg/tsdb/influxdb/models.go
| 0 |
https://github.com/grafana/grafana/commit/dc3a81200b1cd366bdf237ada152ae3d79bdaf59
|
[
0.00017521799600217491,
0.00017240701708942652,
0.00016836450959090143,
0.00017346575623378158,
0.000002693951273613493
] |
{
"id": 9,
"code_window": [
" panelComponent: DataPanel;\n",
"\n",
" constructor(props) {\n",
" super(props);\n",
"\n",
" this.panelComponent = DataPanelWrapper(this.props.component);\n",
" }\n",
"\n",
" componentDidMount() {\n",
" console.log('panel chrome mounted');\n",
" }\n",
"\n",
" render() {\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "public/app/features/dashboard/dashgrid/PanelChrome.tsx",
"type": "replace",
"edit_start_line_idx": 20
}
|
import config from 'app/core/config';
import coreModule from '../core_module';
import appEvents from 'app/core/app_events';
export class ErrorCtrl {
/** @ngInject */
constructor($scope, contextSrv, navModelSrv) {
$scope.navModel = navModelSrv.getNotFoundNav();
$scope.appSubUrl = config.appSubUrl;
if (!contextSrv.isSignedIn) {
appEvents.emit('toggle-sidemenu-hidden');
}
$scope.$on('destroy', () => {
if (!contextSrv.isSignedIn) {
appEvents.emit('toggle-sidemenu-hidden');
}
});
}
}
coreModule.controller('ErrorCtrl', ErrorCtrl);
|
public/app/core/controllers/error_ctrl.ts
| 0 |
https://github.com/grafana/grafana/commit/dc3a81200b1cd366bdf237ada152ae3d79bdaf59
|
[
0.0001945397089002654,
0.0001827269297791645,
0.00017581747670192271,
0.0001778236182872206,
0.000008392948984692339
] |
{
"id": 10,
"code_window": [
" }\n",
"\n",
" render() {\n",
" let PanelComponent = this.panelComponent;\n",
"\n",
" return (\n",
" <div className=\"panel-container\">\n",
" <PanelHeader panel={this.props.panel} dashboard={this.props.dashboard} />\n",
" <div className=\"panel-content\">{<PanelComponent type={'test'} queries={[]} isVisible={true} />}</div>\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const { type } = this.props.panel;\n",
"\n",
" let PanelComponent = dataPanels[type];\n",
"\n",
" if (!PanelComponent) {\n",
" PanelComponent = dataPanels[type] = DataPanelWrapper(this.props.component);\n",
" }\n",
"\n",
" console.log('PanelChrome render', PanelComponent);\n"
],
"file_path": "public/app/features/dashboard/dashgrid/PanelChrome.tsx",
"type": "replace",
"edit_start_line_idx": 29
}
|
import React from 'react';
import config from 'app/core/config';
import { PanelModel } from '../panel_model';
import { DashboardModel } from '../dashboard_model';
import { getAngularLoader, AngularComponent } from 'app/core/services/angular_loader';
import { DashboardRow } from './DashboardRow';
import { AddPanelPanel } from './AddPanelPanel';
import { importPluginModule } from 'app/features/plugins/plugin_loader';
import { PluginExports } from 'app/types/plugins';
import { PanelChrome } from './PanelChrome';
import { PanelEditor } from './PanelEditor';
export interface Props {
panel: PanelModel;
dashboard: DashboardModel;
}
export interface State {
pluginExports: PluginExports;
}
export class DashboardPanel extends React.Component<Props, State> {
element: any;
angularPanel: AngularComponent;
pluginInfo: any;
specialPanels = {};
constructor(props) {
super(props);
this.state = { pluginExports: null };
this.specialPanels['row'] = this.renderRow.bind(this);
this.specialPanels['add-panel'] = this.renderAddPanel.bind(this);
this.props.panel.events.on('panel-size-changed', this.triggerForceUpdate.bind(this));
}
triggerForceUpdate() {
this.forceUpdate();
}
isSpecial() {
return this.specialPanels[this.props.panel.type];
}
renderRow() {
return <DashboardRow panel={this.props.panel} dashboard={this.props.dashboard} />;
}
renderAddPanel() {
return <AddPanelPanel panel={this.props.panel} dashboard={this.props.dashboard} />;
}
loadPlugin() {
if (this.isSpecial()) {
return;
}
// handle plugin loading & changing of plugin type
if (!this.pluginInfo || this.pluginInfo.id !== this.props.panel.type) {
this.pluginInfo = config.panels[this.props.panel.type];
if (this.pluginInfo.exports) {
this.setState({ pluginExports: this.pluginInfo.exports });
} else {
importPluginModule(this.pluginInfo.module).then(pluginExports => {
this.setState({ pluginExports: pluginExports });
});
}
}
}
componentDidMount() {
this.loadPlugin();
}
componentDidUpdate() {
this.loadPlugin();
// handle angular plugin loading
if (!this.element || this.angularPanel) {
return;
}
let loader = getAngularLoader();
var template = '<plugin-component type="panel" class="panel-height-helper"></plugin-component>';
let scopeProps = { panel: this.props.panel, dashboard: this.props.dashboard };
this.angularPanel = loader.load(this.element, scopeProps, template);
}
componentWillUnmount() {
if (this.angularPanel) {
this.angularPanel.destroy();
}
}
renderReactPanel() {
const { pluginExports } = this.state;
const containerClass = this.props.panel.isEditing ? 'panel-editor-container' : 'panel-height-helper';
const panelWrapperClass = this.props.panel.isEditing ? 'panel-editor-container__panel' : 'panel-height-helper';
// this might look strange with these classes that change when edit, but
// I want to try to keep markup (parents) for panel the same in edit mode to avoide unmount / new mount of panel
// plugin component
return (
<div className={containerClass}>
<div className={panelWrapperClass}>
<PanelChrome
component={pluginExports.PanelComponent}
panel={this.props.panel}
dashboard={this.props.dashboard}
/>
</div>
{this.props.panel.isEditing && (
<div className="panel-editor-container__editor">
<PanelEditor panel={this.props.panel} dashboard={this.props.dashboard} />
</div>
)}
</div>
);
}
render() {
if (this.isSpecial()) {
return this.specialPanels[this.props.panel.type]();
}
if (!this.state.pluginExports) {
return null;
}
if (this.state.pluginExports.PanelComponent) {
return this.renderReactPanel();
}
// legacy angular rendering
return <div ref={element => (this.element = element)} className="panel-height-helper" />;
}
}
|
public/app/features/dashboard/dashgrid/DashboardPanel.tsx
| 1 |
https://github.com/grafana/grafana/commit/dc3a81200b1cd366bdf237ada152ae3d79bdaf59
|
[
0.18424460291862488,
0.03470166400074959,
0.00016744503227528185,
0.007664015516638756,
0.060734886676073074
] |
{
"id": 10,
"code_window": [
" }\n",
"\n",
" render() {\n",
" let PanelComponent = this.panelComponent;\n",
"\n",
" return (\n",
" <div className=\"panel-container\">\n",
" <PanelHeader panel={this.props.panel} dashboard={this.props.dashboard} />\n",
" <div className=\"panel-content\">{<PanelComponent type={'test'} queries={[]} isVisible={true} />}</div>\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const { type } = this.props.panel;\n",
"\n",
" let PanelComponent = dataPanels[type];\n",
"\n",
" if (!PanelComponent) {\n",
" PanelComponent = dataPanels[type] = DataPanelWrapper(this.props.component);\n",
" }\n",
"\n",
" console.log('PanelChrome render', PanelComponent);\n"
],
"file_path": "public/app/features/dashboard/dashgrid/PanelChrome.tsx",
"type": "replace",
"edit_start_line_idx": 29
}
|
import _ from 'lodash';
import { QueryPartDef, QueryPart, functionRenderer, suffixRenderer } from 'app/core/components/query_part/query_part';
var index = [];
var categories = {
Aggregations: [],
Selectors: [],
Transformations: [],
Predictors: [],
Math: [],
Aliasing: [],
Fields: [],
};
function createPart(part): any {
var def = index[part.type];
if (!def) {
throw { message: 'Could not find query part ' + part.type };
}
return new QueryPart(part, def);
}
function register(options: any) {
index[options.type] = new QueryPartDef(options);
options.category.push(index[options.type]);
}
var groupByTimeFunctions = [];
function aliasRenderer(part, innerExpr) {
return innerExpr + ' AS ' + '"' + part.params[0] + '"';
}
function fieldRenderer(part, innerExpr) {
if (part.params[0] === '*') {
return '*';
}
return '"' + part.params[0] + '"';
}
function replaceAggregationAddStrategy(selectParts, partModel) {
// look for existing aggregation
for (var i = 0; i < selectParts.length; i++) {
var part = selectParts[i];
if (part.def.category === categories.Aggregations) {
if (part.def.type === partModel.def.type) {
return;
}
// count distinct is allowed
if (part.def.type === 'count' && partModel.def.type === 'distinct') {
break;
}
// remove next aggregation if distinct was replaced
if (part.def.type === 'distinct') {
var morePartsAvailable = selectParts.length >= i + 2;
if (partModel.def.type !== 'count' && morePartsAvailable) {
var nextPart = selectParts[i + 1];
if (nextPart.def.category === categories.Aggregations) {
selectParts.splice(i + 1, 1);
}
} else if (partModel.def.type === 'count') {
if (!morePartsAvailable || selectParts[i + 1].def.type !== 'count') {
selectParts.splice(i + 1, 0, partModel);
}
return;
}
}
selectParts[i] = partModel;
return;
}
if (part.def.category === categories.Selectors) {
selectParts[i] = partModel;
return;
}
}
selectParts.splice(1, 0, partModel);
}
function addTransformationStrategy(selectParts, partModel) {
var i;
// look for index to add transformation
for (i = 0; i < selectParts.length; i++) {
var part = selectParts[i];
if (part.def.category === categories.Math || part.def.category === categories.Aliasing) {
break;
}
}
selectParts.splice(i, 0, partModel);
}
function addMathStrategy(selectParts, partModel) {
var partCount = selectParts.length;
if (partCount > 0) {
// if last is math, replace it
if (selectParts[partCount - 1].def.type === 'math') {
selectParts[partCount - 1] = partModel;
return;
}
// if next to last is math, replace it
if (partCount > 1 && selectParts[partCount - 2].def.type === 'math') {
selectParts[partCount - 2] = partModel;
return;
} else if (selectParts[partCount - 1].def.type === 'alias') {
// if last is alias add it before
selectParts.splice(partCount - 1, 0, partModel);
return;
}
}
selectParts.push(partModel);
}
function addAliasStrategy(selectParts, partModel) {
var partCount = selectParts.length;
if (partCount > 0) {
// if last is alias, replace it
if (selectParts[partCount - 1].def.type === 'alias') {
selectParts[partCount - 1] = partModel;
return;
}
}
selectParts.push(partModel);
}
function addFieldStrategy(selectParts, partModel, query) {
// copy all parts
var parts = _.map(selectParts, function(part: any) {
return createPart({ type: part.def.type, params: _.clone(part.params) });
});
query.selectModels.push(parts);
}
register({
type: 'field',
addStrategy: addFieldStrategy,
category: categories.Fields,
params: [{ type: 'field', dynamicLookup: true }],
defaultParams: ['value'],
renderer: fieldRenderer,
});
// Aggregations
register({
type: 'count',
addStrategy: replaceAggregationAddStrategy,
category: categories.Aggregations,
params: [],
defaultParams: [],
renderer: functionRenderer,
});
register({
type: 'distinct',
addStrategy: replaceAggregationAddStrategy,
category: categories.Aggregations,
params: [],
defaultParams: [],
renderer: functionRenderer,
});
register({
type: 'integral',
addStrategy: replaceAggregationAddStrategy,
category: categories.Aggregations,
params: [],
defaultParams: [],
renderer: functionRenderer,
});
register({
type: 'mean',
addStrategy: replaceAggregationAddStrategy,
category: categories.Aggregations,
params: [],
defaultParams: [],
renderer: functionRenderer,
});
register({
type: 'median',
addStrategy: replaceAggregationAddStrategy,
category: categories.Aggregations,
params: [],
defaultParams: [],
renderer: functionRenderer,
});
register({
type: 'mode',
addStrategy: replaceAggregationAddStrategy,
category: categories.Aggregations,
params: [],
defaultParams: [],
renderer: functionRenderer,
});
register({
type: 'sum',
addStrategy: replaceAggregationAddStrategy,
category: categories.Aggregations,
params: [],
defaultParams: [],
renderer: functionRenderer,
});
// transformations
register({
type: 'derivative',
addStrategy: addTransformationStrategy,
category: categories.Transformations,
params: [
{
name: 'duration',
type: 'interval',
options: ['1s', '10s', '1m', '5m', '10m', '15m', '1h'],
},
],
defaultParams: ['10s'],
renderer: functionRenderer,
});
register({
type: 'spread',
addStrategy: addTransformationStrategy,
category: categories.Transformations,
params: [],
defaultParams: [],
renderer: functionRenderer,
});
register({
type: 'non_negative_derivative',
addStrategy: addTransformationStrategy,
category: categories.Transformations,
params: [
{
name: 'duration',
type: 'interval',
options: ['1s', '10s', '1m', '5m', '10m', '15m', '1h'],
},
],
defaultParams: ['10s'],
renderer: functionRenderer,
});
register({
type: 'difference',
addStrategy: addTransformationStrategy,
category: categories.Transformations,
params: [],
defaultParams: [],
renderer: functionRenderer,
});
register({
type: 'non_negative_difference',
addStrategy: addTransformationStrategy,
category: categories.Transformations,
params: [],
defaultParams: [],
renderer: functionRenderer,
});
register({
type: 'moving_average',
addStrategy: addTransformationStrategy,
category: categories.Transformations,
params: [{ name: 'window', type: 'int', options: [5, 10, 20, 30, 40] }],
defaultParams: [10],
renderer: functionRenderer,
});
register({
type: 'cumulative_sum',
addStrategy: addTransformationStrategy,
category: categories.Transformations,
params: [],
defaultParams: [],
renderer: functionRenderer,
});
register({
type: 'stddev',
addStrategy: addTransformationStrategy,
category: categories.Transformations,
params: [],
defaultParams: [],
renderer: functionRenderer,
});
register({
type: 'time',
category: groupByTimeFunctions,
params: [
{
name: 'interval',
type: 'time',
options: ['$__interval', '1s', '10s', '1m', '5m', '10m', '15m', '1h'],
},
],
defaultParams: ['$__interval'],
renderer: functionRenderer,
});
register({
type: 'fill',
category: groupByTimeFunctions,
params: [
{
name: 'fill',
type: 'string',
options: ['none', 'null', '0', 'previous', 'linear'],
},
],
defaultParams: ['null'],
renderer: functionRenderer,
});
register({
type: 'elapsed',
addStrategy: addTransformationStrategy,
category: categories.Transformations,
params: [
{
name: 'duration',
type: 'interval',
options: ['1s', '10s', '1m', '5m', '10m', '15m', '1h'],
},
],
defaultParams: ['10s'],
renderer: functionRenderer,
});
// predictions
register({
type: 'holt_winters',
addStrategy: addTransformationStrategy,
category: categories.Predictors,
params: [
{ name: 'number', type: 'int', options: [5, 10, 20, 30, 40] },
{ name: 'season', type: 'int', options: [0, 1, 2, 5, 10] },
],
defaultParams: [10, 2],
renderer: functionRenderer,
});
register({
type: 'holt_winters_with_fit',
addStrategy: addTransformationStrategy,
category: categories.Predictors,
params: [
{ name: 'number', type: 'int', options: [5, 10, 20, 30, 40] },
{ name: 'season', type: 'int', options: [0, 1, 2, 5, 10] },
],
defaultParams: [10, 2],
renderer: functionRenderer,
});
// Selectors
register({
type: 'bottom',
addStrategy: replaceAggregationAddStrategy,
category: categories.Selectors,
params: [{ name: 'count', type: 'int' }],
defaultParams: [3],
renderer: functionRenderer,
});
register({
type: 'first',
addStrategy: replaceAggregationAddStrategy,
category: categories.Selectors,
params: [],
defaultParams: [],
renderer: functionRenderer,
});
register({
type: 'last',
addStrategy: replaceAggregationAddStrategy,
category: categories.Selectors,
params: [],
defaultParams: [],
renderer: functionRenderer,
});
register({
type: 'max',
addStrategy: replaceAggregationAddStrategy,
category: categories.Selectors,
params: [],
defaultParams: [],
renderer: functionRenderer,
});
register({
type: 'min',
addStrategy: replaceAggregationAddStrategy,
category: categories.Selectors,
params: [],
defaultParams: [],
renderer: functionRenderer,
});
register({
type: 'percentile',
addStrategy: replaceAggregationAddStrategy,
category: categories.Selectors,
params: [{ name: 'nth', type: 'int' }],
defaultParams: [95],
renderer: functionRenderer,
});
register({
type: 'top',
addStrategy: replaceAggregationAddStrategy,
category: categories.Selectors,
params: [{ name: 'count', type: 'int' }],
defaultParams: [3],
renderer: functionRenderer,
});
register({
type: 'tag',
category: groupByTimeFunctions,
params: [{ name: 'tag', type: 'string', dynamicLookup: true }],
defaultParams: ['tag'],
renderer: fieldRenderer,
});
register({
type: 'math',
addStrategy: addMathStrategy,
category: categories.Math,
params: [{ name: 'expr', type: 'string' }],
defaultParams: [' / 100'],
renderer: suffixRenderer,
});
register({
type: 'alias',
addStrategy: addAliasStrategy,
category: categories.Aliasing,
params: [{ name: 'name', type: 'string', quote: 'double' }],
defaultParams: ['alias'],
renderMode: 'suffix',
renderer: aliasRenderer,
});
export default {
create: createPart,
getCategories: function() {
return categories;
},
replaceAggregationAdd: replaceAggregationAddStrategy,
};
|
public/app/plugins/datasource/influxdb/query_part.ts
| 0 |
https://github.com/grafana/grafana/commit/dc3a81200b1cd366bdf237ada152ae3d79bdaf59
|
[
0.00017824189853854477,
0.0001752144453348592,
0.00016952208534348756,
0.00017549139738548547,
0.0000019756976143980864
] |
{
"id": 10,
"code_window": [
" }\n",
"\n",
" render() {\n",
" let PanelComponent = this.panelComponent;\n",
"\n",
" return (\n",
" <div className=\"panel-container\">\n",
" <PanelHeader panel={this.props.panel} dashboard={this.props.dashboard} />\n",
" <div className=\"panel-content\">{<PanelComponent type={'test'} queries={[]} isVisible={true} />}</div>\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const { type } = this.props.panel;\n",
"\n",
" let PanelComponent = dataPanels[type];\n",
"\n",
" if (!PanelComponent) {\n",
" PanelComponent = dataPanels[type] = DataPanelWrapper(this.props.component);\n",
" }\n",
"\n",
" console.log('PanelChrome render', PanelComponent);\n"
],
"file_path": "public/app/features/dashboard/dashgrid/PanelChrome.tsx",
"type": "replace",
"edit_start_line_idx": 29
}
|
<?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 20.1.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
width="100px" height="100px" viewBox="0 0 100 100" enable-background="new 0 0 100 100" xml:space="preserve">
<g>
<path fill="#1F1F1F" d="M18.2,4.2c-1.5,0-2.9,0.6-3.9,1.6l-0.5,0.5l-0.5-0.5c-1-1.1-2.4-1.6-3.9-1.6S6.6,4.8,5.5,5.8
c-1,1-1.6,2.4-1.6,3.9s0.6,2.9,1.6,3.9l8.3,8.3l8.3-8.3c1-1,1.6-2.4,1.6-3.9s-0.6-2.9-1.6-3.9C21.1,4.8,19.7,4.2,18.2,4.2z
M21,12.5l-7.2,7.2l-7.1-7.1c-0.7-0.7-1.1-1.7-1.1-2.8c0-1,0.4-2,1.1-2.8c0.7-0.7,1.7-1.1,2.8-1.1c1,0,2,0.4,2.8,1.1l0.5,0.5
l0.6,0.6l0.6,0.6l0.6-0.6L15,7.5L15.5,7c0.7-0.7,1.7-1.1,2.8-1.1c1,0,2,0.4,2.8,1.1c0.7,0.7,1.1,1.7,1.1,2.8
C22.1,10.8,21.7,11.8,21,12.5z"/>
<path fill="#1F1F1F" d="M18.2,77.3c-1.5,0-2.9,0.6-3.9,1.6l-0.5,0.5L13.4,79c-1-1.1-2.4-1.6-3.9-1.6S6.6,77.9,5.5,79
c-1,1-1.6,2.4-1.6,3.9s0.6,2.9,1.6,3.9l8.3,8.3l8.3-8.3c1-1,1.6-2.4,1.6-3.9S23.2,80,22.1,79C21.1,77.9,19.7,77.3,18.2,77.3z
M21,85.6l-7.2,7.2l-7.1-7.1c-0.7-0.7-1.1-1.7-1.1-2.8c0-1,0.4-2,1.1-2.8C7.4,79.4,8.4,79,9.4,79c1,0,2,0.4,2.8,1.1l0.5,0.5
l0.6,0.6l0.6,0.6l0.6-0.6l0.6-0.6l0.5-0.5c0.7-0.7,1.7-1.1,2.8-1.1c1,0,2,0.4,2.8,1.1c0.7,0.7,1.1,1.7,1.1,2.8
C22.1,83.9,21.7,84.9,21,85.6z"/>
<path fill="#1F1F1F" d="M0,0v100h100V0H0z M22.7,87.4l-8.9,8.9l-8.9-8.9C3.7,86.2,3,84.6,3,82.9s0.7-3.3,1.9-4.5
c1.2-1.2,2.8-1.9,4.5-1.9c1.6,0,3.2,0.6,4.4,1.7c1.2-1.1,2.7-1.7,4.4-1.7c1.7,0,3.3,0.7,4.5,1.9c1.2,1.2,1.9,2.8,1.9,4.5
S23.9,86.2,22.7,87.4z M22.7,63l-8.9,8.9L4.9,63C3.7,61.8,3,60.2,3,58.5c0-1.7,0.7-3.3,1.9-4.5c1.2-1.2,2.8-1.9,4.5-1.9
c1.1,0,2.1,0.3,3,0.7l0,0.1l0,0l-1.3,6.6l0,0l0,0.1l2.3-0.1l-0.6,6.1l0-0.1l0,0l3.4-8.3l-2,0.3l1.2-3.7l0-0.1l0,0l0.3-1.1
c0.8-0.3,1.6-0.5,2.4-0.5c1.7,0,3.3,0.7,4.5,1.9c1.2,1.2,1.9,2.8,1.9,4.5C24.6,60.2,23.9,61.8,22.7,63z M22.7,38.7l-8.9,8.9
l-8.9-8.9C3.7,37.5,3,35.9,3,34.1s0.7-3.3,1.9-4.5c1.2-1.2,2.8-1.9,4.5-1.9c1.1,0,2.1,0.3,3,0.7l0,0.1l0,0l-1.3,6.6l0,0l0,0.1
l2.3-0.1l-0.6,6.1l0-0.1l0,0l3.4-8.3l-2,0.3l1.2-3.7l0-0.1l0,0l0.3-1.1c0.8-0.3,1.6-0.5,2.4-0.5c1.7,0,3.3,0.7,4.5,1.9
c1.2,1.2,1.9,2.8,1.9,4.5S23.9,37.5,22.7,38.7z M22.7,14.3l-8.9,8.9l-8.9-8.9C3.7,13.1,3,11.5,3,9.8s0.7-3.3,1.9-4.5
c1.2-1.2,2.8-1.9,4.5-1.9c1.6,0,3.2,0.6,4.4,1.7C15,4,16.6,3.4,18.2,3.4c1.7,0,3.3,0.7,4.5,1.9c1.2,1.2,1.9,2.8,1.9,4.5
S23.9,13.1,22.7,14.3z M96.6,94.4c0,1-0.8,1.8-1.8,1.8H33.4c-1,0-1.8-0.8-1.8-1.8V78.6c0-1,0.8-1.8,1.8-1.8h61.4
c1,0,1.8,0.8,1.8,1.8V94.4z M96.6,69.9c0,1-0.8,1.8-1.8,1.8H33.4c-1,0-1.8-0.8-1.8-1.8V54.1c0-1,0.8-1.8,1.8-1.8h61.4
c1,0,1.8,0.8,1.8,1.8V69.9z M96.6,45.4c0,1-0.8,1.8-1.8,1.8H33.4c-1,0-1.8-0.8-1.8-1.8V29.6c0-1,0.8-1.8,1.8-1.8h61.4
c1,0,1.8,0.8,1.8,1.8V45.4z M96.6,20.9c0,1-0.8,1.8-1.8,1.8H33.4c-1,0-1.8-0.8-1.8-1.8V5.1c0-1,0.8-1.8,1.8-1.8h61.4
c1,0,1.8,0.8,1.8,1.8V20.9z"/>
<path fill="#1F1F1F" d="M18.2,53c-0.5,0-1,0.1-1.4,0.2l-0.7,2.1c0.6-0.4,1.3-0.6,2.1-0.6c1,0,2,0.4,2.8,1.1
c0.7,0.7,1.1,1.7,1.1,2.8c0,1-0.4,2-1.1,2.8l-7.2,7.2l-7.1-7.1c-0.7-0.7-1.1-1.7-1.1-2.8c0-1,0.4-2,1.1-2.8
c0.7-0.7,1.7-1.1,2.8-1.1c0.5,0,1,0.1,1.5,0.3l0.3-1.6c-0.6-0.2-1.2-0.3-1.8-0.3c-1.5,0-2.9,0.6-3.9,1.6c-1,1-1.6,2.4-1.6,3.9
c0,1.5,0.6,2.9,1.6,3.9l8.3,8.3l8.3-8.3c1-1,1.6-2.4,1.6-3.9c0-1.5-0.6-2.9-1.6-3.9C21.1,53.5,19.7,53,18.2,53z"/>
<path fill="#1F1F1F" d="M18.2,28.6c-0.5,0-1,0.1-1.4,0.2l-0.7,2.1c0.6-0.4,1.3-0.6,2.1-0.6c1,0,2,0.4,2.8,1.1
c0.7,0.7,1.1,1.7,1.1,2.8c0,1-0.4,2-1.1,2.8l-7.2,7.2l-7.1-7.1c-0.7-0.7-1.1-1.7-1.1-2.8c0-1,0.4-2,1.1-2.8
c0.7-0.7,1.7-1.1,2.8-1.1c0.5,0,1,0.1,1.5,0.3l0.3-1.6c-0.6-0.2-1.2-0.3-1.8-0.3c-1.5,0-2.9,0.6-3.9,1.6c-1,1-1.6,2.4-1.6,3.9
s0.6,2.9,1.6,3.9l8.3,8.3l8.3-8.3c1-1,1.6-2.4,1.6-3.9s-0.6-2.9-1.6-3.9C21.1,29.2,19.7,28.6,18.2,28.6z"/>
<path fill="#898989" d="M94.7,3.3H33.4c-1,0-1.8,0.8-1.8,1.8v15.8c0,1,0.8,1.8,1.8,1.8h61.4c1,0,1.8-0.8,1.8-1.8V5.1
C96.6,4.1,95.7,3.3,94.7,3.3z"/>
<path fill="#898989" d="M94.7,27.8H33.4c-1,0-1.8,0.8-1.8,1.8v15.8c0,1,0.8,1.8,1.8,1.8h61.4c1,0,1.8-0.8,1.8-1.8V29.6
C96.6,28.6,95.7,27.8,94.7,27.8z"/>
<path fill="#898989" d="M94.7,52.3H33.4c-1,0-1.8,0.8-1.8,1.8v15.8c0,1,0.8,1.8,1.8,1.8h61.4c1,0,1.8-0.8,1.8-1.8V54.1
C96.6,53.1,95.7,52.3,94.7,52.3z"/>
<path fill="#898989" d="M94.7,76.8H33.4c-1,0-1.8,0.8-1.8,1.8v15.8c0,1,0.8,1.8,1.8,1.8h61.4c1,0,1.8-0.8,1.8-1.8V78.6
C96.6,77.6,95.7,76.8,94.7,76.8z"/>
<path fill="#04A64D" d="M18.2,3.4c-1.6,0-3.2,0.6-4.4,1.7C12.6,4,11.1,3.4,9.4,3.4c-1.7,0-3.3,0.7-4.5,1.9C3.7,6.5,3,8.1,3,9.8
s0.7,3.3,1.9,4.5l8.9,8.9l8.9-8.9c1.2-1.2,1.9-2.8,1.9-4.5s-0.7-3.3-1.9-4.5C21.5,4.1,19.9,3.4,18.2,3.4z M22.1,13.7L13.8,22
l-8.3-8.3c-1-1-1.6-2.4-1.6-3.9s0.6-2.9,1.6-3.9c1-1,2.4-1.6,3.9-1.6s2.9,0.6,3.9,1.6l0.5,0.5l0.5-0.5c1-1,2.4-1.6,3.9-1.6
c1.5,0,2.9,0.6,3.9,1.6c1,1,1.6,2.4,1.6,3.9S23.2,12.7,22.1,13.7z"/>
<path fill="#04A64D" d="M18.2,5.9c-1,0-2,0.4-2.8,1.1L15,7.5l-0.6,0.6l-0.6,0.6l-0.6-0.6l-0.6-0.6L12.2,7c-0.7-0.7-1.7-1.1-2.8-1.1
c-1,0-2,0.4-2.8,1.1C5.9,7.8,5.5,8.7,5.5,9.8c0,1,0.4,2,1.1,2.8l7.1,7.1l7.2-7.2c0.7-0.7,1.1-1.7,1.1-2.8c0-1-0.4-2-1.1-2.8
C20.2,6.3,19.3,5.9,18.2,5.9z"/>
<path fill="#04A64D" d="M18.2,76.5c-1.6,0-3.2,0.6-4.4,1.7c-1.2-1.1-2.7-1.7-4.4-1.7c-1.7,0-3.3,0.7-4.5,1.9
C3.7,79.6,3,81.2,3,82.9s0.7,3.3,1.9,4.5l8.9,8.9l8.9-8.9c1.2-1.2,1.9-2.8,1.9-4.5s-0.7-3.3-1.9-4.5C21.5,77.2,19.9,76.5,18.2,76.5
z M22.1,86.8l-8.3,8.3l-8.3-8.3c-1-1-1.6-2.4-1.6-3.9S4.5,80,5.5,79c1-1,2.4-1.6,3.9-1.6s2.9,0.6,3.9,1.6l0.5,0.5l0.5-0.5
c1-1,2.4-1.6,3.9-1.6c1.5,0,2.9,0.6,3.9,1.6c1,1,1.6,2.4,1.6,3.9S23.2,85.8,22.1,86.8z"/>
<path fill="#04A64D" d="M18.2,79c-1,0-2,0.4-2.8,1.1L15,80.6l-0.6,0.6l-0.6,0.6l-0.6-0.6l-0.6-0.6l-0.5-0.5
c-0.7-0.7-1.7-1.1-2.8-1.1c-1,0-2,0.4-2.8,1.1c-0.7,0.7-1.1,1.7-1.1,2.8c0,1,0.4,2,1.1,2.8l7.1,7.1l7.2-7.2
c0.7-0.7,1.1-1.7,1.1-2.8c0-1-0.4-2-1.1-2.8C20.2,79.4,19.3,79,18.2,79z"/>
<path fill="#EB242A" d="M18.2,27.8c-0.8,0-1.7,0.2-2.4,0.5l-0.3,1.1l0,0l0,0.1l-1.2,3.7l2-0.3l-3.4,8.3l0,0l0,0.1l0.6-6.1l-2.3,0.1
l0-0.1l0,0l1.3-6.6l0,0l0-0.1c-0.9-0.5-1.9-0.7-3-0.7c-1.7,0-3.3,0.7-4.5,1.9C3.7,30.8,3,32.4,3,34.1s0.7,3.3,1.9,4.5l8.9,8.9
l8.9-8.9c1.2-1.2,1.9-2.8,1.9-4.5s-0.7-3.3-1.9-4.5C21.5,28.4,19.9,27.8,18.2,27.8z M22.1,38.1l-8.3,8.3l-8.3-8.3
c-1-1-1.6-2.4-1.6-3.9s0.6-2.9,1.6-3.9c1-1,2.4-1.6,3.9-1.6c0.6,0,1.2,0.1,1.8,0.3l-0.3,1.6c-0.5-0.2-1-0.3-1.5-0.3
c-1,0-2,0.4-2.8,1.1c-0.7,0.7-1.1,1.7-1.1,2.8c0,1,0.4,2,1.1,2.8l7.1,7.1l7.2-7.2c0.7-0.7,1.1-1.7,1.1-2.8c0-1-0.4-2-1.1-2.8
c-0.7-0.7-1.7-1.1-2.8-1.1c-0.8,0-1.5,0.2-2.1,0.6l0.7-2.1c0.5-0.1,0.9-0.2,1.4-0.2c1.5,0,2.9,0.6,3.9,1.6c1,1,1.6,2.4,1.6,3.9
S23.2,37,22.1,38.1z"/>
<path fill="#EB242A" d="M18.2,52.1c-0.8,0-1.7,0.2-2.4,0.5l-0.3,1.1l0,0l0,0.1l-1.2,3.7l2-0.3l-3.4,8.3l0,0l0,0.1l0.6-6.1l-2.3,0.1
l0-0.1l0,0l1.3-6.6l0,0l0-0.1c-0.9-0.5-1.9-0.7-3-0.7c-1.7,0-3.3,0.7-4.5,1.9C3.7,55.2,3,56.8,3,58.5c0,1.7,0.7,3.3,1.9,4.5
l8.9,8.9l8.9-8.9c1.2-1.2,1.9-2.8,1.9-4.5c0-1.7-0.7-3.3-1.9-4.5C21.5,52.8,19.9,52.1,18.2,52.1z M22.1,62.4l-8.3,8.3l-8.3-8.3
c-1-1-1.6-2.4-1.6-3.9c0-1.5,0.6-2.9,1.6-3.9c1-1,2.4-1.6,3.9-1.6c0.6,0,1.2,0.1,1.8,0.3l-0.3,1.6c-0.5-0.2-1-0.3-1.5-0.3
c-1,0-2,0.4-2.8,1.1c-0.7,0.7-1.1,1.7-1.1,2.8c0,1,0.4,2,1.1,2.8l7.1,7.1l7.2-7.2c0.7-0.7,1.1-1.7,1.1-2.8c0-1-0.4-2-1.1-2.8
c-0.7-0.7-1.7-1.1-2.8-1.1c-0.8,0-1.5,0.2-2.1,0.6l0.7-2.1c0.5-0.1,0.9-0.2,1.4-0.2c1.5,0,2.9,0.6,3.9,1.6c1,1,1.6,2.4,1.6,3.9
C23.8,60,23.2,61.4,22.1,62.4z"/>
</g>
</svg>
|
public/app/plugins/panel/alertlist/img/icn-singlestat-panel.svg
| 0 |
https://github.com/grafana/grafana/commit/dc3a81200b1cd366bdf237ada152ae3d79bdaf59
|
[
0.00024644352379254997,
0.00018943831673823297,
0.00016349166980944574,
0.00016774304094724357,
0.00003358027970534749
] |
{
"id": 10,
"code_window": [
" }\n",
"\n",
" render() {\n",
" let PanelComponent = this.panelComponent;\n",
"\n",
" return (\n",
" <div className=\"panel-container\">\n",
" <PanelHeader panel={this.props.panel} dashboard={this.props.dashboard} />\n",
" <div className=\"panel-content\">{<PanelComponent type={'test'} queries={[]} isVisible={true} />}</div>\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" const { type } = this.props.panel;\n",
"\n",
" let PanelComponent = dataPanels[type];\n",
"\n",
" if (!PanelComponent) {\n",
" PanelComponent = dataPanels[type] = DataPanelWrapper(this.props.component);\n",
" }\n",
"\n",
" console.log('PanelChrome render', PanelComponent);\n"
],
"file_path": "public/app/features/dashboard/dashgrid/PanelChrome.tsx",
"type": "replace",
"edit_start_line_idx": 29
}
|
import { Lexer } from '../lexer';
describe('when lexing graphite expression', function() {
it('should tokenize metric expression', function() {
var lexer = new Lexer('metric.test.*.asd.count');
var tokens = lexer.tokenize();
expect(tokens[0].value).toBe('metric');
expect(tokens[1].value).toBe('.');
expect(tokens[2].type).toBe('identifier');
expect(tokens[4].type).toBe('identifier');
expect(tokens[4].pos).toBe(13);
});
it('should tokenize metric expression with dash', function() {
var lexer = new Lexer('metric.test.se1-server-*.asd.count');
var tokens = lexer.tokenize();
expect(tokens[4].type).toBe('identifier');
expect(tokens[4].value).toBe('se1-server-*');
});
it('should tokenize metric expression with dash2', function() {
var lexer = new Lexer('net.192-168-1-1.192-168-1-9.ping_value.*');
var tokens = lexer.tokenize();
expect(tokens[0].value).toBe('net');
expect(tokens[2].value).toBe('192-168-1-1');
});
it('should tokenize metric expression with equal sign', function() {
var lexer = new Lexer('apps=test');
var tokens = lexer.tokenize();
expect(tokens[0].value).toBe('apps=test');
});
it('simple function2', function() {
var lexer = new Lexer('offset(test.metric, -100)');
var tokens = lexer.tokenize();
expect(tokens[2].type).toBe('identifier');
expect(tokens[4].type).toBe('identifier');
expect(tokens[6].type).toBe('number');
});
it('should tokenize metric expression with curly braces', function() {
var lexer = new Lexer('metric.se1-{first, second}.count');
var tokens = lexer.tokenize();
expect(tokens.length).toBe(10);
expect(tokens[3].type).toBe('{');
expect(tokens[4].value).toBe('first');
expect(tokens[5].value).toBe(',');
expect(tokens[6].value).toBe('second');
});
it('should tokenize metric expression with number segments', function() {
var lexer = new Lexer('metric.10.12_10.test');
var tokens = lexer.tokenize();
expect(tokens[0].type).toBe('identifier');
expect(tokens[2].type).toBe('identifier');
expect(tokens[2].value).toBe('10');
expect(tokens[4].value).toBe('12_10');
expect(tokens[4].type).toBe('identifier');
});
it('should tokenize metric expression with segment that start with number', function() {
var lexer = new Lexer('metric.001-server');
var tokens = lexer.tokenize();
expect(tokens[0].type).toBe('identifier');
expect(tokens[2].type).toBe('identifier');
expect(tokens.length).toBe(3);
});
it('should tokenize func call with numbered metric and number arg', function() {
var lexer = new Lexer('scale(metric.10, 15)');
var tokens = lexer.tokenize();
expect(tokens[0].type).toBe('identifier');
expect(tokens[2].type).toBe('identifier');
expect(tokens[2].value).toBe('metric');
expect(tokens[4].value).toBe('10');
expect(tokens[4].type).toBe('number');
expect(tokens[6].type).toBe('number');
});
it('should tokenize metric with template parameter', function() {
var lexer = new Lexer('metric.[[server]].test');
var tokens = lexer.tokenize();
expect(tokens[2].type).toBe('identifier');
expect(tokens[2].value).toBe('[[server]]');
expect(tokens[4].type).toBe('identifier');
});
it('should tokenize metric with question mark', function() {
var lexer = new Lexer('metric.server_??.test');
var tokens = lexer.tokenize();
expect(tokens[2].type).toBe('identifier');
expect(tokens[2].value).toBe('server_??');
expect(tokens[4].type).toBe('identifier');
});
it('should handle error with unterminated string', function() {
var lexer = new Lexer("alias(metric, 'asd)");
var tokens = lexer.tokenize();
expect(tokens[0].value).toBe('alias');
expect(tokens[1].value).toBe('(');
expect(tokens[2].value).toBe('metric');
expect(tokens[3].value).toBe(',');
expect(tokens[4].type).toBe('string');
expect(tokens[4].isUnclosed).toBe(true);
expect(tokens[4].pos).toBe(20);
});
it('should handle float parameters', function() {
var lexer = new Lexer('alias(metric, 0.002)');
var tokens = lexer.tokenize();
expect(tokens[4].type).toBe('number');
expect(tokens[4].value).toBe('0.002');
});
it('should handle bool parameters', function() {
var lexer = new Lexer('alias(metric, true, false)');
var tokens = lexer.tokenize();
expect(tokens[4].type).toBe('bool');
expect(tokens[4].value).toBe('true');
expect(tokens[6].type).toBe('bool');
});
});
|
public/app/plugins/datasource/graphite/specs/lexer.jest.ts
| 0 |
https://github.com/grafana/grafana/commit/dc3a81200b1cd366bdf237ada152ae3d79bdaf59
|
[
0.00017977994866669178,
0.00017650885274633765,
0.00017271329124923795,
0.00017731399566400796,
0.000002015011887124274
] |
{
"id": 11,
"code_window": [
"import { VizTypePicker } from './VizTypePicker';\n",
"\n",
"interface PanelEditorProps {\n",
" panel: PanelModel;\n",
" dashboard: DashboardModel;\n",
"}\n",
"\n",
"interface PanelEditorTab {\n",
" id: string;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" panelType: string;\n",
" onTypeChanged: (newType: PanelPlugin) => void;\n"
],
"file_path": "public/app/features/dashboard/dashgrid/PanelEditor.tsx",
"type": "add",
"edit_start_line_idx": 13
}
|
import React from 'react';
import config from 'app/core/config';
import { PanelModel } from '../panel_model';
import { DashboardModel } from '../dashboard_model';
import { getAngularLoader, AngularComponent } from 'app/core/services/angular_loader';
import { DashboardRow } from './DashboardRow';
import { AddPanelPanel } from './AddPanelPanel';
import { importPluginModule } from 'app/features/plugins/plugin_loader';
import { PluginExports } from 'app/types/plugins';
import { PanelChrome } from './PanelChrome';
import { PanelEditor } from './PanelEditor';
export interface Props {
panel: PanelModel;
dashboard: DashboardModel;
}
export interface State {
pluginExports: PluginExports;
}
export class DashboardPanel extends React.Component<Props, State> {
element: any;
angularPanel: AngularComponent;
pluginInfo: any;
specialPanels = {};
constructor(props) {
super(props);
this.state = { pluginExports: null };
this.specialPanels['row'] = this.renderRow.bind(this);
this.specialPanels['add-panel'] = this.renderAddPanel.bind(this);
this.props.panel.events.on('panel-size-changed', this.triggerForceUpdate.bind(this));
}
triggerForceUpdate() {
this.forceUpdate();
}
isSpecial() {
return this.specialPanels[this.props.panel.type];
}
renderRow() {
return <DashboardRow panel={this.props.panel} dashboard={this.props.dashboard} />;
}
renderAddPanel() {
return <AddPanelPanel panel={this.props.panel} dashboard={this.props.dashboard} />;
}
loadPlugin() {
if (this.isSpecial()) {
return;
}
// handle plugin loading & changing of plugin type
if (!this.pluginInfo || this.pluginInfo.id !== this.props.panel.type) {
this.pluginInfo = config.panels[this.props.panel.type];
if (this.pluginInfo.exports) {
this.setState({ pluginExports: this.pluginInfo.exports });
} else {
importPluginModule(this.pluginInfo.module).then(pluginExports => {
this.setState({ pluginExports: pluginExports });
});
}
}
}
componentDidMount() {
this.loadPlugin();
}
componentDidUpdate() {
this.loadPlugin();
// handle angular plugin loading
if (!this.element || this.angularPanel) {
return;
}
let loader = getAngularLoader();
var template = '<plugin-component type="panel" class="panel-height-helper"></plugin-component>';
let scopeProps = { panel: this.props.panel, dashboard: this.props.dashboard };
this.angularPanel = loader.load(this.element, scopeProps, template);
}
componentWillUnmount() {
if (this.angularPanel) {
this.angularPanel.destroy();
}
}
renderReactPanel() {
const { pluginExports } = this.state;
const containerClass = this.props.panel.isEditing ? 'panel-editor-container' : 'panel-height-helper';
const panelWrapperClass = this.props.panel.isEditing ? 'panel-editor-container__panel' : 'panel-height-helper';
// this might look strange with these classes that change when edit, but
// I want to try to keep markup (parents) for panel the same in edit mode to avoide unmount / new mount of panel
// plugin component
return (
<div className={containerClass}>
<div className={panelWrapperClass}>
<PanelChrome
component={pluginExports.PanelComponent}
panel={this.props.panel}
dashboard={this.props.dashboard}
/>
</div>
{this.props.panel.isEditing && (
<div className="panel-editor-container__editor">
<PanelEditor panel={this.props.panel} dashboard={this.props.dashboard} />
</div>
)}
</div>
);
}
render() {
if (this.isSpecial()) {
return this.specialPanels[this.props.panel.type]();
}
if (!this.state.pluginExports) {
return null;
}
if (this.state.pluginExports.PanelComponent) {
return this.renderReactPanel();
}
// legacy angular rendering
return <div ref={element => (this.element = element)} className="panel-height-helper" />;
}
}
|
public/app/features/dashboard/dashgrid/DashboardPanel.tsx
| 1 |
https://github.com/grafana/grafana/commit/dc3a81200b1cd366bdf237ada152ae3d79bdaf59
|
[
0.12389518320560455,
0.013845768757164478,
0.00016806759231258184,
0.0018873104127123952,
0.031892310827970505
] |
{
"id": 11,
"code_window": [
"import { VizTypePicker } from './VizTypePicker';\n",
"\n",
"interface PanelEditorProps {\n",
" panel: PanelModel;\n",
" dashboard: DashboardModel;\n",
"}\n",
"\n",
"interface PanelEditorTab {\n",
" id: string;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" panelType: string;\n",
" onTypeChanged: (newType: PanelPlugin) => void;\n"
],
"file_path": "public/app/features/dashboard/dashgrid/PanelEditor.tsx",
"type": "add",
"edit_start_line_idx": 13
}
|
package mssql
import (
"bytes"
"encoding/binary"
"fmt"
"io"
"math"
"reflect"
"strconv"
"time"
"github.com/denisenkom/go-mssqldb/internal/cp"
)
// fixed-length data types
// http://msdn.microsoft.com/en-us/library/dd341171.aspx
const (
typeNull = 0x1f
typeInt1 = 0x30
typeBit = 0x32
typeInt2 = 0x34
typeInt4 = 0x38
typeDateTim4 = 0x3a
typeFlt4 = 0x3b
typeMoney = 0x3c
typeDateTime = 0x3d
typeFlt8 = 0x3e
typeMoney4 = 0x7a
typeInt8 = 0x7f
)
// variable-length data types
// http://msdn.microsoft.com/en-us/library/dd358341.aspx
const (
// byte len types
typeGuid = 0x24
typeIntN = 0x26
typeDecimal = 0x37 // legacy
typeNumeric = 0x3f // legacy
typeBitN = 0x68
typeDecimalN = 0x6a
typeNumericN = 0x6c
typeFltN = 0x6d
typeMoneyN = 0x6e
typeDateTimeN = 0x6f
typeDateN = 0x28
typeTimeN = 0x29
typeDateTime2N = 0x2a
typeDateTimeOffsetN = 0x2b
typeChar = 0x2f // legacy
typeVarChar = 0x27 // legacy
typeBinary = 0x2d // legacy
typeVarBinary = 0x25 // legacy
// short length types
typeBigVarBin = 0xa5
typeBigVarChar = 0xa7
typeBigBinary = 0xad
typeBigChar = 0xaf
typeNVarChar = 0xe7
typeNChar = 0xef
typeXml = 0xf1
typeUdt = 0xf0
// long length types
typeText = 0x23
typeImage = 0x22
typeNText = 0x63
typeVariant = 0x62
)
const PLP_NULL = 0xFFFFFFFFFFFFFFFF
const UNKNOWN_PLP_LEN = 0xFFFFFFFFFFFFFFFE
const PLP_TERMINATOR = 0x00000000
// TYPE_INFO rule
// http://msdn.microsoft.com/en-us/library/dd358284.aspx
type typeInfo struct {
TypeId uint8
Size int
Scale uint8
Prec uint8
Buffer []byte
Collation cp.Collation
UdtInfo udtInfo
XmlInfo xmlInfo
Reader func(ti *typeInfo, r *tdsBuffer) (res interface{})
Writer func(w io.Writer, ti typeInfo, buf []byte) (err error)
}
// Common Language Runtime (CLR) Instances
// http://msdn.microsoft.com/en-us/library/dd357962.aspx
type udtInfo struct {
//MaxByteSize uint32
DBName string
SchemaName string
TypeName string
AssemblyQualifiedName string
}
// XML Values
// http://msdn.microsoft.com/en-us/library/dd304764.aspx
type xmlInfo struct {
SchemaPresent uint8
DBName string
OwningSchema string
XmlSchemaCollection string
}
func readTypeInfo(r *tdsBuffer) (res typeInfo) {
res.TypeId = r.byte()
switch res.TypeId {
case typeNull, typeInt1, typeBit, typeInt2, typeInt4, typeDateTim4,
typeFlt4, typeMoney, typeDateTime, typeFlt8, typeMoney4, typeInt8:
// those are fixed length types
switch res.TypeId {
case typeNull:
res.Size = 0
case typeInt1, typeBit:
res.Size = 1
case typeInt2:
res.Size = 2
case typeInt4, typeDateTim4, typeFlt4, typeMoney4:
res.Size = 4
case typeMoney, typeDateTime, typeFlt8, typeInt8:
res.Size = 8
}
res.Reader = readFixedType
res.Buffer = make([]byte, res.Size)
default: // all others are VARLENTYPE
readVarLen(&res, r)
}
return
}
func writeTypeInfo(w io.Writer, ti *typeInfo) (err error) {
err = binary.Write(w, binary.LittleEndian, ti.TypeId)
if err != nil {
return
}
switch ti.TypeId {
case typeNull, typeInt1, typeBit, typeInt2, typeInt4, typeDateTim4,
typeFlt4, typeMoney, typeDateTime, typeFlt8, typeMoney4, typeInt8:
// those are fixed length
ti.Writer = writeFixedType
default: // all others are VARLENTYPE
err = writeVarLen(w, ti)
if err != nil {
return
}
}
return
}
func writeFixedType(w io.Writer, ti typeInfo, buf []byte) (err error) {
_, err = w.Write(buf)
return
}
func writeVarLen(w io.Writer, ti *typeInfo) (err error) {
switch ti.TypeId {
case typeDateN:
ti.Writer = writeByteLenType
case typeTimeN, typeDateTime2N, typeDateTimeOffsetN:
if err = binary.Write(w, binary.LittleEndian, ti.Scale); err != nil {
return
}
ti.Writer = writeByteLenType
case typeIntN, typeDecimal, typeNumeric,
typeBitN, typeDecimalN, typeNumericN, typeFltN,
typeMoneyN, typeDateTimeN, typeChar,
typeVarChar, typeBinary, typeVarBinary:
// byle len types
if ti.Size > 0xff {
panic("Invalid size for BYLELEN_TYPE")
}
if err = binary.Write(w, binary.LittleEndian, uint8(ti.Size)); err != nil {
return
}
switch ti.TypeId {
case typeDecimal, typeNumeric, typeDecimalN, typeNumericN:
err = binary.Write(w, binary.LittleEndian, ti.Prec)
if err != nil {
return
}
err = binary.Write(w, binary.LittleEndian, ti.Scale)
if err != nil {
return
}
}
ti.Writer = writeByteLenType
case typeGuid:
if !(ti.Size == 0x10 || ti.Size == 0x00) {
panic("Invalid size for BYLELEN_TYPE")
}
if err = binary.Write(w, binary.LittleEndian, uint8(ti.Size)); err != nil {
return
}
ti.Writer = writeByteLenType
case typeBigVarBin, typeBigVarChar, typeBigBinary, typeBigChar,
typeNVarChar, typeNChar, typeXml, typeUdt:
// short len types
if ti.Size > 8000 || ti.Size == 0 {
if err = binary.Write(w, binary.LittleEndian, uint16(0xffff)); err != nil {
return
}
ti.Writer = writePLPType
} else {
if err = binary.Write(w, binary.LittleEndian, uint16(ti.Size)); err != nil {
return
}
ti.Writer = writeShortLenType
}
switch ti.TypeId {
case typeBigVarChar, typeBigChar, typeNVarChar, typeNChar:
if err = writeCollation(w, ti.Collation); err != nil {
return
}
case typeXml:
if err = binary.Write(w, binary.LittleEndian, ti.XmlInfo.SchemaPresent); err != nil {
return
}
}
case typeText, typeImage, typeNText, typeVariant:
// LONGLEN_TYPE
if err = binary.Write(w, binary.LittleEndian, uint32(ti.Size)); err != nil {
return
}
if err = writeCollation(w, ti.Collation); err != nil {
return
}
ti.Writer = writeLongLenType
default:
panic("Invalid type")
}
return
}
// http://msdn.microsoft.com/en-us/library/ee780895.aspx
func decodeDateTim4(buf []byte) time.Time {
days := binary.LittleEndian.Uint16(buf)
mins := binary.LittleEndian.Uint16(buf[2:])
return time.Date(1900, 1, 1+int(days),
0, int(mins), 0, 0, time.UTC)
}
func decodeDateTime(buf []byte) time.Time {
days := int32(binary.LittleEndian.Uint32(buf))
tm := binary.LittleEndian.Uint32(buf[4:])
ns := int(math.Trunc(float64(tm%300)/0.3+0.5)) * 1000000
secs := int(tm / 300)
return time.Date(1900, 1, 1+int(days),
0, 0, secs, ns, time.UTC)
}
func readFixedType(ti *typeInfo, r *tdsBuffer) interface{} {
r.ReadFull(ti.Buffer)
buf := ti.Buffer
switch ti.TypeId {
case typeNull:
return nil
case typeInt1:
return int64(buf[0])
case typeBit:
return buf[0] != 0
case typeInt2:
return int64(int16(binary.LittleEndian.Uint16(buf)))
case typeInt4:
return int64(int32(binary.LittleEndian.Uint32(buf)))
case typeDateTim4:
return decodeDateTim4(buf)
case typeFlt4:
return math.Float32frombits(binary.LittleEndian.Uint32(buf))
case typeMoney4:
return decodeMoney4(buf)
case typeMoney:
return decodeMoney(buf)
case typeDateTime:
return decodeDateTime(buf)
case typeFlt8:
return math.Float64frombits(binary.LittleEndian.Uint64(buf))
case typeInt8:
return int64(binary.LittleEndian.Uint64(buf))
default:
badStreamPanicf("Invalid typeid")
}
panic("shoulnd't get here")
}
func readByteLenType(ti *typeInfo, r *tdsBuffer) interface{} {
size := r.byte()
if size == 0 {
return nil
}
r.ReadFull(ti.Buffer[:size])
buf := ti.Buffer[:size]
switch ti.TypeId {
case typeDateN:
if len(buf) != 3 {
badStreamPanicf("Invalid size for DATENTYPE")
}
return decodeDate(buf)
case typeTimeN:
return decodeTime(ti.Scale, buf)
case typeDateTime2N:
return decodeDateTime2(ti.Scale, buf)
case typeDateTimeOffsetN:
return decodeDateTimeOffset(ti.Scale, buf)
case typeGuid:
return decodeGuid(buf)
case typeIntN:
switch len(buf) {
case 1:
return int64(buf[0])
case 2:
return int64(int16((binary.LittleEndian.Uint16(buf))))
case 4:
return int64(int32(binary.LittleEndian.Uint32(buf)))
case 8:
return int64(binary.LittleEndian.Uint64(buf))
default:
badStreamPanicf("Invalid size for INTNTYPE")
}
case typeDecimal, typeNumeric, typeDecimalN, typeNumericN:
return decodeDecimal(ti.Prec, ti.Scale, buf)
case typeBitN:
if len(buf) != 1 {
badStreamPanicf("Invalid size for BITNTYPE")
}
return buf[0] != 0
case typeFltN:
switch len(buf) {
case 4:
return float64(math.Float32frombits(binary.LittleEndian.Uint32(buf)))
case 8:
return math.Float64frombits(binary.LittleEndian.Uint64(buf))
default:
badStreamPanicf("Invalid size for FLTNTYPE")
}
case typeMoneyN:
switch len(buf) {
case 4:
return decodeMoney4(buf)
case 8:
return decodeMoney(buf)
default:
badStreamPanicf("Invalid size for MONEYNTYPE")
}
case typeDateTim4:
return decodeDateTim4(buf)
case typeDateTime:
return decodeDateTime(buf)
case typeDateTimeN:
switch len(buf) {
case 4:
return decodeDateTim4(buf)
case 8:
return decodeDateTime(buf)
default:
badStreamPanicf("Invalid size for DATETIMENTYPE")
}
case typeChar, typeVarChar:
return decodeChar(ti.Collation, buf)
case typeBinary, typeVarBinary:
// a copy, because the backing array for ti.Buffer is reused
// and can be overwritten by the next row while this row waits
// in a buffered chan
cpy := make([]byte, len(buf))
copy(cpy, buf)
return cpy
default:
badStreamPanicf("Invalid typeid")
}
panic("shoulnd't get here")
}
func writeByteLenType(w io.Writer, ti typeInfo, buf []byte) (err error) {
if ti.Size > 0xff {
panic("Invalid size for BYTELEN_TYPE")
}
err = binary.Write(w, binary.LittleEndian, uint8(ti.Size))
if err != nil {
return
}
_, err = w.Write(buf)
return
}
func readShortLenType(ti *typeInfo, r *tdsBuffer) interface{} {
size := r.uint16()
if size == 0xffff {
return nil
}
r.ReadFull(ti.Buffer[:size])
buf := ti.Buffer[:size]
switch ti.TypeId {
case typeBigVarChar, typeBigChar:
return decodeChar(ti.Collation, buf)
case typeBigVarBin, typeBigBinary:
// a copy, because the backing array for ti.Buffer is reused
// and can be overwritten by the next row while this row waits
// in a buffered chan
cpy := make([]byte, len(buf))
copy(cpy, buf)
return cpy
case typeNVarChar, typeNChar:
return decodeNChar(buf)
case typeUdt:
return decodeUdt(*ti, buf)
default:
badStreamPanicf("Invalid typeid")
}
panic("shoulnd't get here")
}
func writeShortLenType(w io.Writer, ti typeInfo, buf []byte) (err error) {
if buf == nil {
err = binary.Write(w, binary.LittleEndian, uint16(0xffff))
return
}
if ti.Size > 0xfffe {
panic("Invalid size for USHORTLEN_TYPE")
}
err = binary.Write(w, binary.LittleEndian, uint16(ti.Size))
if err != nil {
return
}
_, err = w.Write(buf)
return
}
func readLongLenType(ti *typeInfo, r *tdsBuffer) interface{} {
// information about this format can be found here:
// http://msdn.microsoft.com/en-us/library/dd304783.aspx
// and here:
// http://msdn.microsoft.com/en-us/library/dd357254.aspx
textptrsize := int(r.byte())
if textptrsize == 0 {
return nil
}
textptr := make([]byte, textptrsize)
r.ReadFull(textptr)
timestamp := r.uint64()
_ = timestamp // ignore timestamp
size := r.int32()
if size == -1 {
return nil
}
buf := make([]byte, size)
r.ReadFull(buf)
switch ti.TypeId {
case typeText:
return decodeChar(ti.Collation, buf)
case typeImage:
return buf
case typeNText:
return decodeNChar(buf)
default:
badStreamPanicf("Invalid typeid")
}
panic("shoulnd't get here")
}
func writeLongLenType(w io.Writer, ti typeInfo, buf []byte) (err error) {
//textptr
err = binary.Write(w, binary.LittleEndian, byte(0x10))
if err != nil {
return
}
err = binary.Write(w, binary.LittleEndian, uint64(0xFFFFFFFFFFFFFFFF))
if err != nil {
return
}
err = binary.Write(w, binary.LittleEndian, uint64(0xFFFFFFFFFFFFFFFF))
if err != nil {
return
}
//timestamp?
err = binary.Write(w, binary.LittleEndian, uint64(0xFFFFFFFFFFFFFFFF))
if err != nil {
return
}
err = binary.Write(w, binary.LittleEndian, uint32(ti.Size))
if err != nil {
return
}
_, err = w.Write(buf)
return
}
func readCollation(r *tdsBuffer) (res cp.Collation) {
res.LcidAndFlags = r.uint32()
res.SortId = r.byte()
return
}
func writeCollation(w io.Writer, col cp.Collation) (err error) {
if err = binary.Write(w, binary.LittleEndian, col.LcidAndFlags); err != nil {
return
}
err = binary.Write(w, binary.LittleEndian, col.SortId)
return
}
// reads variant value
// http://msdn.microsoft.com/en-us/library/dd303302.aspx
func readVariantType(ti *typeInfo, r *tdsBuffer) interface{} {
size := r.int32()
if size == 0 {
return nil
}
vartype := r.byte()
propbytes := int32(r.byte())
switch vartype {
case typeGuid:
buf := make([]byte, size-2-propbytes)
r.ReadFull(buf)
return buf
case typeBit:
return r.byte() != 0
case typeInt1:
return int64(r.byte())
case typeInt2:
return int64(int16(r.uint16()))
case typeInt4:
return int64(r.int32())
case typeInt8:
return int64(r.uint64())
case typeDateTime:
buf := make([]byte, size-2-propbytes)
r.ReadFull(buf)
return decodeDateTime(buf)
case typeDateTim4:
buf := make([]byte, size-2-propbytes)
r.ReadFull(buf)
return decodeDateTim4(buf)
case typeFlt4:
return float64(math.Float32frombits(r.uint32()))
case typeFlt8:
return math.Float64frombits(r.uint64())
case typeMoney4:
buf := make([]byte, size-2-propbytes)
r.ReadFull(buf)
return decodeMoney4(buf)
case typeMoney:
buf := make([]byte, size-2-propbytes)
r.ReadFull(buf)
return decodeMoney(buf)
case typeDateN:
buf := make([]byte, size-2-propbytes)
r.ReadFull(buf)
return decodeDate(buf)
case typeTimeN:
scale := r.byte()
buf := make([]byte, size-2-propbytes)
r.ReadFull(buf)
return decodeTime(scale, buf)
case typeDateTime2N:
scale := r.byte()
buf := make([]byte, size-2-propbytes)
r.ReadFull(buf)
return decodeDateTime2(scale, buf)
case typeDateTimeOffsetN:
scale := r.byte()
buf := make([]byte, size-2-propbytes)
r.ReadFull(buf)
return decodeDateTimeOffset(scale, buf)
case typeBigVarBin, typeBigBinary:
r.uint16() // max length, ignoring
buf := make([]byte, size-2-propbytes)
r.ReadFull(buf)
return buf
case typeDecimalN, typeNumericN:
prec := r.byte()
scale := r.byte()
buf := make([]byte, size-2-propbytes)
r.ReadFull(buf)
return decodeDecimal(prec, scale, buf)
case typeBigVarChar, typeBigChar:
col := readCollation(r)
r.uint16() // max length, ignoring
buf := make([]byte, size-2-propbytes)
r.ReadFull(buf)
return decodeChar(col, buf)
case typeNVarChar, typeNChar:
_ = readCollation(r)
r.uint16() // max length, ignoring
buf := make([]byte, size-2-propbytes)
r.ReadFull(buf)
return decodeNChar(buf)
default:
badStreamPanicf("Invalid variant typeid")
}
panic("shoulnd't get here")
}
// partially length prefixed stream
// http://msdn.microsoft.com/en-us/library/dd340469.aspx
func readPLPType(ti *typeInfo, r *tdsBuffer) interface{} {
size := r.uint64()
var buf *bytes.Buffer
switch size {
case PLP_NULL:
// null
return nil
case UNKNOWN_PLP_LEN:
// size unknown
buf = bytes.NewBuffer(make([]byte, 0, 1000))
default:
buf = bytes.NewBuffer(make([]byte, 0, size))
}
for true {
chunksize := r.uint32()
if chunksize == 0 {
break
}
if _, err := io.CopyN(buf, r, int64(chunksize)); err != nil {
badStreamPanicf("Reading PLP type failed: %s", err.Error())
}
}
switch ti.TypeId {
case typeXml:
return decodeXml(*ti, buf.Bytes())
case typeBigVarChar, typeBigChar, typeText:
return decodeChar(ti.Collation, buf.Bytes())
case typeBigVarBin, typeBigBinary, typeImage:
return buf.Bytes()
case typeNVarChar, typeNChar, typeNText:
return decodeNChar(buf.Bytes())
case typeUdt:
return decodeUdt(*ti, buf.Bytes())
}
panic("shoulnd't get here")
}
func writePLPType(w io.Writer, ti typeInfo, buf []byte) (err error) {
if err = binary.Write(w, binary.LittleEndian, uint64(UNKNOWN_PLP_LEN)); err != nil {
return
}
for {
chunksize := uint32(len(buf))
if chunksize == 0 {
err = binary.Write(w, binary.LittleEndian, uint32(PLP_TERMINATOR))
return
}
if err = binary.Write(w, binary.LittleEndian, chunksize); err != nil {
return
}
if _, err = w.Write(buf[:chunksize]); err != nil {
return
}
buf = buf[chunksize:]
}
}
func readVarLen(ti *typeInfo, r *tdsBuffer) {
switch ti.TypeId {
case typeDateN:
ti.Size = 3
ti.Reader = readByteLenType
ti.Buffer = make([]byte, ti.Size)
case typeTimeN, typeDateTime2N, typeDateTimeOffsetN:
ti.Scale = r.byte()
switch ti.Scale {
case 0, 1, 2:
ti.Size = 3
case 3, 4:
ti.Size = 4
case 5, 6, 7:
ti.Size = 5
default:
badStreamPanicf("Invalid scale for TIME/DATETIME2/DATETIMEOFFSET type")
}
switch ti.TypeId {
case typeDateTime2N:
ti.Size += 3
case typeDateTimeOffsetN:
ti.Size += 5
}
ti.Reader = readByteLenType
ti.Buffer = make([]byte, ti.Size)
case typeGuid, typeIntN, typeDecimal, typeNumeric,
typeBitN, typeDecimalN, typeNumericN, typeFltN,
typeMoneyN, typeDateTimeN, typeChar,
typeVarChar, typeBinary, typeVarBinary:
// byle len types
ti.Size = int(r.byte())
ti.Buffer = make([]byte, ti.Size)
switch ti.TypeId {
case typeDecimal, typeNumeric, typeDecimalN, typeNumericN:
ti.Prec = r.byte()
ti.Scale = r.byte()
}
ti.Reader = readByteLenType
case typeXml:
ti.XmlInfo.SchemaPresent = r.byte()
if ti.XmlInfo.SchemaPresent != 0 {
// dbname
ti.XmlInfo.DBName = r.BVarChar()
// owning schema
ti.XmlInfo.OwningSchema = r.BVarChar()
// xml schema collection
ti.XmlInfo.XmlSchemaCollection = r.UsVarChar()
}
ti.Reader = readPLPType
case typeUdt:
ti.Size = int(r.uint16())
ti.UdtInfo.DBName = r.BVarChar()
ti.UdtInfo.SchemaName = r.BVarChar()
ti.UdtInfo.TypeName = r.BVarChar()
ti.UdtInfo.AssemblyQualifiedName = r.UsVarChar()
ti.Buffer = make([]byte, ti.Size)
ti.Reader = readPLPType
case typeBigVarBin, typeBigVarChar, typeBigBinary, typeBigChar,
typeNVarChar, typeNChar:
// short len types
ti.Size = int(r.uint16())
switch ti.TypeId {
case typeBigVarChar, typeBigChar, typeNVarChar, typeNChar:
ti.Collation = readCollation(r)
}
if ti.Size == 0xffff {
ti.Reader = readPLPType
} else {
ti.Buffer = make([]byte, ti.Size)
ti.Reader = readShortLenType
}
case typeText, typeImage, typeNText, typeVariant:
// LONGLEN_TYPE
ti.Size = int(r.int32())
switch ti.TypeId {
case typeText, typeNText:
ti.Collation = readCollation(r)
// ignore tablenames
numparts := int(r.byte())
for i := 0; i < numparts; i++ {
r.UsVarChar()
}
ti.Reader = readLongLenType
case typeImage:
// ignore tablenames
numparts := int(r.byte())
for i := 0; i < numparts; i++ {
r.UsVarChar()
}
ti.Reader = readLongLenType
case typeVariant:
ti.Reader = readVariantType
}
default:
badStreamPanicf("Invalid type %d", ti.TypeId)
}
return
}
func decodeMoney(buf []byte) []byte {
money := int64(uint64(buf[4]) |
uint64(buf[5])<<8 |
uint64(buf[6])<<16 |
uint64(buf[7])<<24 |
uint64(buf[0])<<32 |
uint64(buf[1])<<40 |
uint64(buf[2])<<48 |
uint64(buf[3])<<56)
return scaleBytes(strconv.FormatInt(money, 10), 4)
}
func decodeMoney4(buf []byte) []byte {
money := int32(binary.LittleEndian.Uint32(buf[0:4]))
return scaleBytes(strconv.FormatInt(int64(money), 10), 4)
}
func decodeGuid(buf []byte) []byte {
res := make([]byte, 16)
copy(res, buf)
return res
}
func decodeDecimal(prec uint8, scale uint8, buf []byte) []byte {
var sign uint8
sign = buf[0]
dec := Decimal{
positive: sign != 0,
prec: prec,
scale: scale,
}
buf = buf[1:]
l := len(buf) / 4
for i := 0; i < l; i++ {
dec.integer[i] = binary.LittleEndian.Uint32(buf[0:4])
buf = buf[4:]
}
return dec.Bytes()
}
// http://msdn.microsoft.com/en-us/library/ee780895.aspx
func decodeDateInt(buf []byte) (days int) {
days = int(buf[0]) + int(buf[1])*256 + int(buf[2])*256*256
return
}
func decodeDate(buf []byte) time.Time {
return time.Date(1, 1, 1+decodeDateInt(buf), 0, 0, 0, 0, time.UTC)
}
func decodeTimeInt(scale uint8, buf []byte) (sec int, ns int) {
var acc uint64 = 0
for i := len(buf) - 1; i >= 0; i-- {
acc <<= 8
acc |= uint64(buf[i])
}
for i := 0; i < 7-int(scale); i++ {
acc *= 10
}
nsbig := acc * 100
sec = int(nsbig / 1000000000)
ns = int(nsbig % 1000000000)
return
}
func decodeTime(scale uint8, buf []byte) time.Time {
sec, ns := decodeTimeInt(scale, buf)
return time.Date(1, 1, 1, 0, 0, sec, ns, time.UTC)
}
func decodeDateTime2(scale uint8, buf []byte) time.Time {
timesize := len(buf) - 3
sec, ns := decodeTimeInt(scale, buf[:timesize])
days := decodeDateInt(buf[timesize:])
return time.Date(1, 1, 1+days, 0, 0, sec, ns, time.UTC)
}
func decodeDateTimeOffset(scale uint8, buf []byte) time.Time {
timesize := len(buf) - 3 - 2
sec, ns := decodeTimeInt(scale, buf[:timesize])
buf = buf[timesize:]
days := decodeDateInt(buf[:3])
buf = buf[3:]
offset := int(int16(binary.LittleEndian.Uint16(buf))) // in mins
return time.Date(1, 1, 1+days, 0, 0, sec+offset*60, ns,
time.FixedZone("", offset*60))
}
func divFloor(x int64, y int64) int64 {
q := x / y
r := x % y
if r != 0 && ((r < 0) != (y < 0)) {
q--
}
return q
}
func dateTime2(t time.Time) (days int32, ns int64) {
// number of days since Jan 1 1970 UTC
days64 := divFloor(t.Unix(), 24*60*60)
// number of days since Jan 1 1 UTC
days = int32(days64) + 1969*365 + 1969/4 - 1969/100 + 1969/400
// number of seconds within day
secs := t.Unix() - days64*24*60*60
// number of nanoseconds within day
ns = secs*1e9 + int64(t.Nanosecond())
return
}
func decodeChar(col cp.Collation, buf []byte) string {
return cp.CharsetToUTF8(col, buf)
}
func decodeUcs2(buf []byte) string {
res, err := ucs22str(buf)
if err != nil {
badStreamPanicf("Invalid UCS2 encoding: %s", err.Error())
}
return res
}
func decodeNChar(buf []byte) string {
return decodeUcs2(buf)
}
func decodeXml(ti typeInfo, buf []byte) string {
return decodeUcs2(buf)
}
func decodeUdt(ti typeInfo, buf []byte) []byte {
return buf
}
// makes go/sql type instance as described below
// It should return
// the value type that can be used to scan types into. For example, the database
// column type "bigint" this should return "reflect.TypeOf(int64(0))".
func makeGoLangScanType(ti typeInfo) reflect.Type {
switch ti.TypeId {
case typeInt1:
return reflect.TypeOf(int64(0))
case typeInt2:
return reflect.TypeOf(int64(0))
case typeInt4:
return reflect.TypeOf(int64(0))
case typeInt8:
return reflect.TypeOf(int64(0))
case typeFlt4:
return reflect.TypeOf(float64(0))
case typeIntN:
switch ti.Size {
case 1:
return reflect.TypeOf(int64(0))
case 2:
return reflect.TypeOf(int64(0))
case 4:
return reflect.TypeOf(int64(0))
case 8:
return reflect.TypeOf(int64(0))
default:
panic("invalid size of INTNTYPE")
}
case typeFlt8:
return reflect.TypeOf(float64(0))
case typeFltN:
switch ti.Size {
case 4:
return reflect.TypeOf(float64(0))
case 8:
return reflect.TypeOf(float64(0))
default:
panic("invalid size of FLNNTYPE")
}
case typeBigVarBin:
return reflect.TypeOf([]byte{})
case typeVarChar:
return reflect.TypeOf("")
case typeNVarChar:
return reflect.TypeOf("")
case typeBit, typeBitN:
return reflect.TypeOf(true)
case typeDecimalN, typeNumericN:
return reflect.TypeOf([]byte{})
case typeMoney, typeMoney4, typeMoneyN:
switch ti.Size {
case 4:
return reflect.TypeOf([]byte{})
case 8:
return reflect.TypeOf([]byte{})
default:
panic("invalid size of MONEYN")
}
case typeDateTim4:
return reflect.TypeOf(time.Time{})
case typeDateTime:
return reflect.TypeOf(time.Time{})
case typeDateTimeN:
switch ti.Size {
case 4:
return reflect.TypeOf(time.Time{})
case 8:
return reflect.TypeOf(time.Time{})
default:
panic("invalid size of DATETIMEN")
}
case typeDateTime2N:
return reflect.TypeOf(time.Time{})
case typeDateN:
return reflect.TypeOf(time.Time{})
case typeTimeN:
return reflect.TypeOf(time.Time{})
case typeDateTimeOffsetN:
return reflect.TypeOf(time.Time{})
case typeBigVarChar:
return reflect.TypeOf("")
case typeBigChar:
return reflect.TypeOf("")
case typeNChar:
return reflect.TypeOf("")
case typeGuid:
return reflect.TypeOf([]byte{})
case typeXml:
return reflect.TypeOf("")
case typeText:
return reflect.TypeOf("")
case typeNText:
return reflect.TypeOf("")
case typeImage:
return reflect.TypeOf([]byte{})
case typeBigBinary:
return reflect.TypeOf([]byte{})
case typeVariant:
return reflect.TypeOf(nil)
default:
panic(fmt.Sprintf("not implemented makeDecl for type %d", ti.TypeId))
}
}
func makeDecl(ti typeInfo) string {
switch ti.TypeId {
case typeNull:
// maybe we should use something else here
// this is tested in TestNull
return "nvarchar(1)"
case typeInt1:
return "tinyint"
case typeInt2:
return "smallint"
case typeInt4:
return "int"
case typeInt8:
return "bigint"
case typeFlt4:
return "real"
case typeIntN:
switch ti.Size {
case 1:
return "tinyint"
case 2:
return "smallint"
case 4:
return "int"
case 8:
return "bigint"
default:
panic("invalid size of INTNTYPE")
}
case typeFlt8:
return "float"
case typeFltN:
switch ti.Size {
case 4:
return "real"
case 8:
return "float"
default:
panic("invalid size of FLNNTYPE")
}
case typeDecimal, typeDecimalN:
return fmt.Sprintf("decimal(%d, %d)", ti.Prec, ti.Scale)
case typeNumeric, typeNumericN:
return fmt.Sprintf("numeric(%d, %d)", ti.Prec, ti.Scale)
case typeMoney4:
return "smallmoney"
case typeMoney:
return "money"
case typeMoneyN:
switch ti.Size {
case 4:
return "smallmoney"
case 8:
return "money"
default:
panic("invalid size of MONEYNTYPE")
}
case typeBigVarBin:
if ti.Size > 8000 || ti.Size == 0 {
return "varbinary(max)"
} else {
return fmt.Sprintf("varbinary(%d)", ti.Size)
}
case typeNChar:
return fmt.Sprintf("nchar(%d)", ti.Size/2)
case typeBigChar, typeChar:
return fmt.Sprintf("char(%d)", ti.Size)
case typeBigVarChar, typeVarChar:
if ti.Size > 4000 || ti.Size == 0 {
return fmt.Sprintf("varchar(max)")
} else {
return fmt.Sprintf("varchar(%d)", ti.Size)
}
case typeNVarChar:
if ti.Size > 8000 || ti.Size == 0 {
return "nvarchar(max)"
} else {
return fmt.Sprintf("nvarchar(%d)", ti.Size/2)
}
case typeBit, typeBitN:
return "bit"
case typeDateN:
return "date"
case typeDateTim4:
return "smalldatetime"
case typeDateTime:
return "datetime"
case typeDateTimeN:
switch ti.Size {
case 4:
return "smalldatetime"
case 8:
return "datetime"
default:
panic("invalid size of DATETIMNTYPE")
}
case typeDateTime2N:
return fmt.Sprintf("datetime2(%d)", ti.Scale)
case typeDateTimeOffsetN:
return fmt.Sprintf("datetimeoffset(%d)", ti.Scale)
case typeText:
return "text"
case typeNText:
return "ntext"
case typeUdt:
return ti.UdtInfo.TypeName
case typeGuid:
return "uniqueidentifier"
default:
panic(fmt.Sprintf("not implemented makeDecl for type %#x", ti.TypeId))
}
}
// makes go/sql type name as described below
// RowsColumnTypeDatabaseTypeName may be implemented by Rows. It should return the
// database system type name without the length. Type names should be uppercase.
// Examples of returned types: "VARCHAR", "NVARCHAR", "VARCHAR2", "CHAR", "TEXT",
// "DECIMAL", "SMALLINT", "INT", "BIGINT", "BOOL", "[]BIGINT", "JSONB", "XML",
// "TIMESTAMP".
func makeGoLangTypeName(ti typeInfo) string {
switch ti.TypeId {
case typeInt1:
return "TINYINT"
case typeInt2:
return "SMALLINT"
case typeInt4:
return "INT"
case typeInt8:
return "BIGINT"
case typeFlt4:
return "REAL"
case typeIntN:
switch ti.Size {
case 1:
return "TINYINT"
case 2:
return "SMALLINT"
case 4:
return "INT"
case 8:
return "BIGINT"
default:
panic("invalid size of INTNTYPE")
}
case typeFlt8:
return "FLOAT"
case typeFltN:
switch ti.Size {
case 4:
return "REAL"
case 8:
return "FLOAT"
default:
panic("invalid size of FLNNTYPE")
}
case typeBigVarBin:
return "VARBINARY"
case typeVarChar:
return "VARCHAR"
case typeNVarChar:
return "NVARCHAR"
case typeBit, typeBitN:
return "BIT"
case typeDecimalN, typeNumericN:
return "DECIMAL"
case typeMoney, typeMoney4, typeMoneyN:
switch ti.Size {
case 4:
return "SMALLMONEY"
case 8:
return "MONEY"
default:
panic("invalid size of MONEYN")
}
case typeDateTim4:
return "SMALLDATETIME"
case typeDateTime:
return "DATETIME"
case typeDateTimeN:
switch ti.Size {
case 4:
return "SMALLDATETIME"
case 8:
return "DATETIME"
default:
panic("invalid size of DATETIMEN")
}
case typeDateTime2N:
return "DATETIME2"
case typeDateN:
return "DATE"
case typeTimeN:
return "TIME"
case typeDateTimeOffsetN:
return "DATETIMEOFFSET"
case typeBigVarChar:
return "VARCHAR"
case typeBigChar:
return "CHAR"
case typeNChar:
return "NCHAR"
case typeGuid:
return "UNIQUEIDENTIFIER"
case typeXml:
return "XML"
case typeText:
return "TEXT"
case typeNText:
return "NTEXT"
case typeImage:
return "IMAGE"
case typeVariant:
return "SQL_VARIANT"
case typeBigBinary:
return "BINARY"
default:
panic(fmt.Sprintf("not implemented makeDecl for type %d", ti.TypeId))
}
}
// makes go/sql type length as described below
// It should return the length
// of the column type if the column is a variable length type. If the column is
// not a variable length type ok should return false.
// If length is not limited other than system limits, it should return math.MaxInt64.
// The following are examples of returned values for various types:
// TEXT (math.MaxInt64, true)
// varchar(10) (10, true)
// nvarchar(10) (10, true)
// decimal (0, false)
// int (0, false)
// bytea(30) (30, true)
func makeGoLangTypeLength(ti typeInfo) (int64, bool) {
switch ti.TypeId {
case typeInt1:
return 0, false
case typeInt2:
return 0, false
case typeInt4:
return 0, false
case typeInt8:
return 0, false
case typeFlt4:
return 0, false
case typeIntN:
switch ti.Size {
case 1:
return 0, false
case 2:
return 0, false
case 4:
return 0, false
case 8:
return 0, false
default:
panic("invalid size of INTNTYPE")
}
case typeFlt8:
return 0, false
case typeFltN:
switch ti.Size {
case 4:
return 0, false
case 8:
return 0, false
default:
panic("invalid size of FLNNTYPE")
}
case typeBit, typeBitN:
return 0, false
case typeDecimalN, typeNumericN:
return 0, false
case typeMoney, typeMoney4, typeMoneyN:
switch ti.Size {
case 4:
return 0, false
case 8:
return 0, false
default:
panic("invalid size of MONEYN")
}
case typeDateTim4, typeDateTime:
return 0, false
case typeDateTimeN:
switch ti.Size {
case 4:
return 0, false
case 8:
return 0, false
default:
panic("invalid size of DATETIMEN")
}
case typeDateTime2N:
return 0, false
case typeDateN:
return 0, false
case typeTimeN:
return 0, false
case typeDateTimeOffsetN:
return 0, false
case typeBigVarBin:
if ti.Size == 0xffff {
return 2147483645, true
} else {
return int64(ti.Size), true
}
case typeVarChar:
return int64(ti.Size), true
case typeBigVarChar:
if ti.Size == 0xffff {
return 2147483645, true
} else {
return int64(ti.Size), true
}
case typeBigChar:
return int64(ti.Size), true
case typeNVarChar:
if ti.Size == 0xffff {
return 2147483645 / 2, true
} else {
return int64(ti.Size) / 2, true
}
case typeNChar:
return int64(ti.Size) / 2, true
case typeGuid:
return 0, false
case typeXml:
return 1073741822, true
case typeText:
return 2147483647, true
case typeNText:
return 1073741823, true
case typeImage:
return 2147483647, true
case typeVariant:
return 0, false
case typeBigBinary:
return 0, false
default:
panic(fmt.Sprintf("not implemented makeDecl for type %d", ti.TypeId))
}
}
// makes go/sql type precision and scale as described below
// It should return the length
// of the column type if the column is a variable length type. If the column is
// not a variable length type ok should return false.
// If length is not limited other than system limits, it should return math.MaxInt64.
// The following are examples of returned values for various types:
// TEXT (math.MaxInt64, true)
// varchar(10) (10, true)
// nvarchar(10) (10, true)
// decimal (0, false)
// int (0, false)
// bytea(30) (30, true)
func makeGoLangTypePrecisionScale(ti typeInfo) (int64, int64, bool) {
switch ti.TypeId {
case typeInt1:
return 0, 0, false
case typeInt2:
return 0, 0, false
case typeInt4:
return 0, 0, false
case typeInt8:
return 0, 0, false
case typeFlt4:
return 0, 0, false
case typeIntN:
switch ti.Size {
case 1:
return 0, 0, false
case 2:
return 0, 0, false
case 4:
return 0, 0, false
case 8:
return 0, 0, false
default:
panic("invalid size of INTNTYPE")
}
case typeFlt8:
return 0, 0, false
case typeFltN:
switch ti.Size {
case 4:
return 0, 0, false
case 8:
return 0, 0, false
default:
panic("invalid size of FLNNTYPE")
}
case typeBit, typeBitN:
return 0, 0, false
case typeDecimalN, typeNumericN:
return int64(ti.Prec), int64(ti.Scale), true
case typeMoney, typeMoney4, typeMoneyN:
switch ti.Size {
case 4:
return 0, 0, false
case 8:
return 0, 0, false
default:
panic("invalid size of MONEYN")
}
case typeDateTim4, typeDateTime:
return 0, 0, false
case typeDateTimeN:
switch ti.Size {
case 4:
return 0, 0, false
case 8:
return 0, 0, false
default:
panic("invalid size of DATETIMEN")
}
case typeDateTime2N:
return 0, 0, false
case typeDateN:
return 0, 0, false
case typeTimeN:
return 0, 0, false
case typeDateTimeOffsetN:
return 0, 0, false
case typeBigVarBin:
return 0, 0, false
case typeVarChar:
return 0, 0, false
case typeBigVarChar:
return 0, 0, false
case typeBigChar:
return 0, 0, false
case typeNVarChar:
return 0, 0, false
case typeNChar:
return 0, 0, false
case typeGuid:
return 0, 0, false
case typeXml:
return 0, 0, false
case typeText:
return 0, 0, false
case typeNText:
return 0, 0, false
case typeImage:
return 0, 0, false
case typeVariant:
return 0, 0, false
case typeBigBinary:
return 0, 0, false
default:
panic(fmt.Sprintf("not implemented makeDecl for type %d", ti.TypeId))
}
}
|
vendor/github.com/denisenkom/go-mssqldb/types.go
| 0 |
https://github.com/grafana/grafana/commit/dc3a81200b1cd366bdf237ada152ae3d79bdaf59
|
[
0.0001789564557839185,
0.00017517450032755733,
0.00016384873015340418,
0.0001761142921168357,
0.0000029504446956707397
] |
{
"id": 11,
"code_window": [
"import { VizTypePicker } from './VizTypePicker';\n",
"\n",
"interface PanelEditorProps {\n",
" panel: PanelModel;\n",
" dashboard: DashboardModel;\n",
"}\n",
"\n",
"interface PanelEditorTab {\n",
" id: string;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" panelType: string;\n",
" onTypeChanged: (newType: PanelPlugin) => void;\n"
],
"file_path": "public/app/features/dashboard/dashgrid/PanelEditor.tsx",
"type": "add",
"edit_start_line_idx": 13
}
|
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2004 Sam Hocevar <[email protected]>
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
|
vendor/github.com/BurntSushi/toml/cmd/tomlv/COPYING
| 0 |
https://github.com/grafana/grafana/commit/dc3a81200b1cd366bdf237ada152ae3d79bdaf59
|
[
0.0001700119028100744,
0.00016883615171536803,
0.00016766040062066168,
0.00016883615171536803,
0.0000011757510947063565
] |
{
"id": 11,
"code_window": [
"import { VizTypePicker } from './VizTypePicker';\n",
"\n",
"interface PanelEditorProps {\n",
" panel: PanelModel;\n",
" dashboard: DashboardModel;\n",
"}\n",
"\n",
"interface PanelEditorTab {\n",
" id: string;\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" panelType: string;\n",
" onTypeChanged: (newType: PanelPlugin) => void;\n"
],
"file_path": "public/app/features/dashboard/dashgrid/PanelEditor.tsx",
"type": "add",
"edit_start_line_idx": 13
}
|
package login
import (
"github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/log"
m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/quota"
)
func init() {
bus.AddHandler("auth", UpsertUser)
}
func UpsertUser(cmd *m.UpsertUserCommand) error {
extUser := cmd.ExternalUser
userQuery := &m.GetUserByAuthInfoQuery{
AuthModule: extUser.AuthModule,
AuthId: extUser.AuthId,
UserId: extUser.UserId,
Email: extUser.Email,
Login: extUser.Login,
}
err := bus.Dispatch(userQuery)
if err != m.ErrUserNotFound && err != nil {
return err
}
if err != nil {
if !cmd.SignupAllowed {
log.Warn("Not allowing %s login, user not found in internal user database and allow signup = false", extUser.AuthModule)
return ErrInvalidCredentials
}
limitReached, err := quota.QuotaReached(cmd.ReqContext, "user")
if err != nil {
log.Warn("Error getting user quota", "err", err)
return ErrGettingUserQuota
}
if limitReached {
return ErrUsersQuotaReached
}
cmd.Result, err = createUser(extUser)
if err != nil {
return err
}
if extUser.AuthModule != "" && extUser.AuthId != "" {
cmd2 := &m.SetAuthInfoCommand{
UserId: cmd.Result.Id,
AuthModule: extUser.AuthModule,
AuthId: extUser.AuthId,
}
if err := bus.Dispatch(cmd2); err != nil {
return err
}
}
} else {
cmd.Result = userQuery.Result
err = updateUser(cmd.Result, extUser)
if err != nil {
return err
}
}
err = syncOrgRoles(cmd.Result, extUser)
if err != nil {
return err
}
err = bus.Dispatch(&m.SyncTeamsCommand{
User: cmd.Result,
ExternalUser: extUser,
})
if err == bus.ErrHandlerNotFound {
return nil
}
return err
}
func createUser(extUser *m.ExternalUserInfo) (*m.User, error) {
cmd := &m.CreateUserCommand{
Login: extUser.Login,
Email: extUser.Email,
Name: extUser.Name,
SkipOrgSetup: len(extUser.OrgRoles) > 0,
}
if err := bus.Dispatch(cmd); err != nil {
return nil, err
}
return &cmd.Result, nil
}
func updateUser(user *m.User, extUser *m.ExternalUserInfo) error {
// sync user info
updateCmd := &m.UpdateUserCommand{
UserId: user.Id,
}
needsUpdate := false
if extUser.Login != "" && extUser.Login != user.Login {
updateCmd.Login = extUser.Login
user.Login = extUser.Login
needsUpdate = true
}
if extUser.Email != "" && extUser.Email != user.Email {
updateCmd.Email = extUser.Email
user.Email = extUser.Email
needsUpdate = true
}
if extUser.Name != "" && extUser.Name != user.Name {
updateCmd.Name = extUser.Name
user.Name = extUser.Name
needsUpdate = true
}
if !needsUpdate {
return nil
}
log.Debug("Syncing user info", "id", user.Id, "update", updateCmd)
return bus.Dispatch(updateCmd)
}
func syncOrgRoles(user *m.User, extUser *m.ExternalUserInfo) error {
// don't sync org roles if none are specified
if len(extUser.OrgRoles) == 0 {
return nil
}
orgsQuery := &m.GetUserOrgListQuery{UserId: user.Id}
if err := bus.Dispatch(orgsQuery); err != nil {
return err
}
handledOrgIds := map[int64]bool{}
deleteOrgIds := []int64{}
// update existing org roles
for _, org := range orgsQuery.Result {
handledOrgIds[org.OrgId] = true
if extUser.OrgRoles[org.OrgId] == "" {
deleteOrgIds = append(deleteOrgIds, org.OrgId)
} else if extUser.OrgRoles[org.OrgId] != org.Role {
// update role
cmd := &m.UpdateOrgUserCommand{OrgId: org.OrgId, UserId: user.Id, Role: extUser.OrgRoles[org.OrgId]}
if err := bus.Dispatch(cmd); err != nil {
return err
}
}
}
// add any new org roles
for orgId, orgRole := range extUser.OrgRoles {
if _, exists := handledOrgIds[orgId]; exists {
continue
}
// add role
cmd := &m.AddOrgUserCommand{UserId: user.Id, Role: orgRole, OrgId: orgId}
err := bus.Dispatch(cmd)
if err != nil && err != m.ErrOrgNotFound {
return err
}
}
// delete any removed org roles
for _, orgId := range deleteOrgIds {
cmd := &m.RemoveOrgUserCommand{OrgId: orgId, UserId: user.Id}
if err := bus.Dispatch(cmd); err != nil {
return err
}
}
// update user's default org if needed
if _, ok := extUser.OrgRoles[user.OrgId]; !ok {
for orgId := range extUser.OrgRoles {
user.OrgId = orgId
break
}
return bus.Dispatch(&m.SetUsingOrgCommand{
UserId: user.Id,
OrgId: user.OrgId,
})
}
return nil
}
|
pkg/login/ext_user.go
| 0 |
https://github.com/grafana/grafana/commit/dc3a81200b1cd366bdf237ada152ae3d79bdaf59
|
[
0.00018093973631039262,
0.0001746979251038283,
0.00016992472228594124,
0.00017427708371542394,
0.00000244847115027369
] |
{
"id": 12,
"code_window": [
" renderVizTab() {\n",
" return (\n",
" <div className=\"viz-editor\">\n",
" <div className=\"viz-editor-col1\">\n",
" <VizTypePicker currentType={this.props.panel.type} onTypeChanged={this.onVizTypeChanged} />\n",
" </div>\n",
" <div className=\"viz-editor-col2\">\n",
" <h5 className=\"page-heading\">Options</h5>\n",
" </div>\n",
" </div>\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <VizTypePicker currentType={this.props.panel.type} onTypeChanged={this.props.onTypeChanged} />\n"
],
"file_path": "public/app/features/dashboard/dashgrid/PanelEditor.tsx",
"type": "replace",
"edit_start_line_idx": 42
}
|
import React from 'react';
import classNames from 'classnames';
import { PanelModel } from '../panel_model';
import { DashboardModel } from '../dashboard_model';
import { store } from 'app/stores/store';
import { observer } from 'mobx-react';
import { QueriesTab } from './QueriesTab';
import { PanelPlugin } from 'app/types/plugins';
import { VizTypePicker } from './VizTypePicker';
interface PanelEditorProps {
panel: PanelModel;
dashboard: DashboardModel;
}
interface PanelEditorTab {
id: string;
text: string;
icon: string;
}
@observer
export class PanelEditor extends React.Component<PanelEditorProps, any> {
tabs: PanelEditorTab[];
constructor(props) {
super(props);
this.tabs = [
{ id: 'queries', text: 'Queries', icon: 'fa fa-database' },
{ id: 'viz', text: 'Visualization', icon: 'fa fa-line-chart' },
];
}
renderQueriesTab() {
return <QueriesTab panel={this.props.panel} dashboard={this.props.dashboard} />;
}
renderVizTab() {
return (
<div className="viz-editor">
<div className="viz-editor-col1">
<VizTypePicker currentType={this.props.panel.type} onTypeChanged={this.onVizTypeChanged} />
</div>
<div className="viz-editor-col2">
<h5 className="page-heading">Options</h5>
</div>
</div>
);
}
onVizTypeChanged = (plugin: PanelPlugin) => {
console.log('changing type to ', plugin.id);
this.props.panel.changeType(plugin.id);
};
onChangeTab = (tab: PanelEditorTab) => {
store.view.updateQuery({ tab: tab.id }, false);
};
render() {
const activeTab: string = store.view.query.get('tab') || 'queries';
return (
<div className="tabbed-view tabbed-view--new">
<div className="tabbed-view-header">
<ul className="gf-tabs">
{this.tabs.map(tab => {
return <TabItem tab={tab} activeTab={activeTab} onClick={this.onChangeTab} key={tab.id} />;
})}
</ul>
<button className="tabbed-view-close-btn" ng-click="ctrl.exitFullscreen();">
<i className="fa fa-remove" />
</button>
</div>
<div className="tabbed-view-body">
{activeTab === 'queries' && this.renderQueriesTab()}
{activeTab === 'viz' && this.renderVizTab()}
</div>
</div>
);
}
}
interface TabItemParams {
tab: PanelEditorTab;
activeTab: string;
onClick: (tab: PanelEditorTab) => void;
}
function TabItem({ tab, activeTab, onClick }: TabItemParams) {
const tabClasses = classNames({
'gf-tabs-link': true,
active: activeTab === tab.id,
});
return (
<li className="gf-tabs-item" key={tab.id}>
<a className={tabClasses} onClick={() => onClick(tab)}>
<i className={tab.icon} />
{tab.text}
</a>
</li>
);
}
|
public/app/features/dashboard/dashgrid/PanelEditor.tsx
| 1 |
https://github.com/grafana/grafana/commit/dc3a81200b1cd366bdf237ada152ae3d79bdaf59
|
[
0.9989062547683716,
0.26919734477996826,
0.0001702360896160826,
0.002562762936577201,
0.43669769167900085
] |
{
"id": 12,
"code_window": [
" renderVizTab() {\n",
" return (\n",
" <div className=\"viz-editor\">\n",
" <div className=\"viz-editor-col1\">\n",
" <VizTypePicker currentType={this.props.panel.type} onTypeChanged={this.onVizTypeChanged} />\n",
" </div>\n",
" <div className=\"viz-editor-col2\">\n",
" <h5 className=\"page-heading\">Options</h5>\n",
" </div>\n",
" </div>\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <VizTypePicker currentType={this.props.panel.type} onTypeChanged={this.props.onTypeChanged} />\n"
],
"file_path": "public/app/features/dashboard/dashgrid/PanelEditor.tsx",
"type": "replace",
"edit_start_line_idx": 42
}
|
declare var OpenTsDatasource: any;
export default OpenTsDatasource;
|
public/app/plugins/datasource/opentsdb/datasource.d.ts
| 0 |
https://github.com/grafana/grafana/commit/dc3a81200b1cd366bdf237ada152ae3d79bdaf59
|
[
0.00017263063637074083,
0.00017263063637074083,
0.00017263063637074083,
0.00017263063637074083,
0
] |
{
"id": 12,
"code_window": [
" renderVizTab() {\n",
" return (\n",
" <div className=\"viz-editor\">\n",
" <div className=\"viz-editor-col1\">\n",
" <VizTypePicker currentType={this.props.panel.type} onTypeChanged={this.onVizTypeChanged} />\n",
" </div>\n",
" <div className=\"viz-editor-col2\">\n",
" <h5 className=\"page-heading\">Options</h5>\n",
" </div>\n",
" </div>\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <VizTypePicker currentType={this.props.panel.type} onTypeChanged={this.props.onTypeChanged} />\n"
],
"file_path": "public/app/features/dashboard/dashgrid/PanelEditor.tsx",
"type": "replace",
"edit_start_line_idx": 42
}
|
<page-header model="ctrl.navModel"></page-header>
<div class="page-container page-body">
<div class="page-action-bar">
<div class="page-action-bar__spacer"></div>
<a class="btn btn-success pull-right" href="playlists/create">
<i class="fa fa-plus"></i>
New Playlist
</a>
</div>
<table class="filter-table">
<thead>
<th><strong>Name</strong></th>
<th><strong>Start url</strong></th>
<th style="width: 78px"></th>
<th style="width: 78px"></th>
<th style="width: 25px"></th>
</thead>
<tr ng-repeat="playlist in ctrl.playlists">
<td>
<a href="playlists/edit/{{playlist.id}}">{{playlist.name}}</a>
</td>
<td >
<a href="playlists/play/{{playlist.id}}">playlists/play/{{playlist.id}}</a>
</td>
<td class="text-center">
<a href="playlists/play/{{playlist.id}}" class="btn btn-inverse btn-small">
<i class="fa fa-play"></i>
Play
</a>
</td>
<td class="text-right">
<a href="playlists/edit/{{playlist.id}}" class="btn btn-inverse btn-small">
<i class="fa fa-edit"></i>
Edit
</a>
</td>
<td class="text-right">
<a ng-click="ctrl.removePlaylist(playlist)" class="btn btn-danger btn-small">
<i class="fa fa-remove"></i>
</a>
</td>
</tr>
</table>
</div>
|
public/app/features/playlist/partials/playlists.html
| 0 |
https://github.com/grafana/grafana/commit/dc3a81200b1cd366bdf237ada152ae3d79bdaf59
|
[
0.00017328685498796403,
0.00016987245180644095,
0.00016462344501633197,
0.00017142322030849755,
0.0000030555797820852604
] |
{
"id": 12,
"code_window": [
" renderVizTab() {\n",
" return (\n",
" <div className=\"viz-editor\">\n",
" <div className=\"viz-editor-col1\">\n",
" <VizTypePicker currentType={this.props.panel.type} onTypeChanged={this.onVizTypeChanged} />\n",
" </div>\n",
" <div className=\"viz-editor-col2\">\n",
" <h5 className=\"page-heading\">Options</h5>\n",
" </div>\n",
" </div>\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <VizTypePicker currentType={this.props.panel.type} onTypeChanged={this.props.onTypeChanged} />\n"
],
"file_path": "public/app/features/dashboard/dashgrid/PanelEditor.tsx",
"type": "replace",
"edit_start_line_idx": 42
}
|
package api
import (
"fmt"
"github.com/grafana/grafana/pkg/api/dtos"
"github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/events"
"github.com/grafana/grafana/pkg/metrics"
m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/util"
)
func GetPendingOrgInvites(c *m.ReqContext) Response {
query := m.GetTempUsersQuery{OrgId: c.OrgId, Status: m.TmpUserInvitePending}
if err := bus.Dispatch(&query); err != nil {
return Error(500, "Failed to get invites from db", err)
}
for _, invite := range query.Result {
invite.Url = setting.ToAbsUrl("invite/" + invite.Code)
}
return JSON(200, query.Result)
}
func AddOrgInvite(c *m.ReqContext, inviteDto dtos.AddInviteForm) Response {
if !inviteDto.Role.IsValid() {
return Error(400, "Invalid role specified", nil)
}
// first try get existing user
userQuery := m.GetUserByLoginQuery{LoginOrEmail: inviteDto.LoginOrEmail}
if err := bus.Dispatch(&userQuery); err != nil {
if err != m.ErrUserNotFound {
return Error(500, "Failed to query db for existing user check", err)
}
if setting.DisableLoginForm {
return Error(401, "User could not be found", nil)
}
} else {
return inviteExistingUserToOrg(c, userQuery.Result, &inviteDto)
}
cmd := m.CreateTempUserCommand{}
cmd.OrgId = c.OrgId
cmd.Email = inviteDto.LoginOrEmail
cmd.Name = inviteDto.Name
cmd.Status = m.TmpUserInvitePending
cmd.InvitedByUserId = c.UserId
cmd.Code = util.GetRandomString(30)
cmd.Role = inviteDto.Role
cmd.RemoteAddr = c.Req.RemoteAddr
if err := bus.Dispatch(&cmd); err != nil {
return Error(500, "Failed to save invite to database", err)
}
// send invite email
if inviteDto.SendEmail && util.IsEmail(inviteDto.LoginOrEmail) {
emailCmd := m.SendEmailCommand{
To: []string{inviteDto.LoginOrEmail},
Template: "new_user_invite.html",
Data: map[string]interface{}{
"Name": util.StringsFallback2(cmd.Name, cmd.Email),
"OrgName": c.OrgName,
"Email": c.Email,
"LinkUrl": setting.ToAbsUrl("invite/" + cmd.Code),
"InvitedBy": util.StringsFallback3(c.Name, c.Email, c.Login),
},
}
if err := bus.Dispatch(&emailCmd); err != nil {
if err == m.ErrSmtpNotEnabled {
return Error(412, err.Error(), err)
}
return Error(500, "Failed to send email invite", err)
}
emailSentCmd := m.UpdateTempUserWithEmailSentCommand{Code: cmd.Result.Code}
if err := bus.Dispatch(&emailSentCmd); err != nil {
return Error(500, "Failed to update invite with email sent info", err)
}
return Success(fmt.Sprintf("Sent invite to %s", inviteDto.LoginOrEmail))
}
return Success(fmt.Sprintf("Created invite for %s", inviteDto.LoginOrEmail))
}
func inviteExistingUserToOrg(c *m.ReqContext, user *m.User, inviteDto *dtos.AddInviteForm) Response {
// user exists, add org role
createOrgUserCmd := m.AddOrgUserCommand{OrgId: c.OrgId, UserId: user.Id, Role: inviteDto.Role}
if err := bus.Dispatch(&createOrgUserCmd); err != nil {
if err == m.ErrOrgUserAlreadyAdded {
return Error(412, fmt.Sprintf("User %s is already added to organization", inviteDto.LoginOrEmail), err)
}
return Error(500, "Error while trying to create org user", err)
}
if inviteDto.SendEmail && util.IsEmail(user.Email) {
emailCmd := m.SendEmailCommand{
To: []string{user.Email},
Template: "invited_to_org.html",
Data: map[string]interface{}{
"Name": user.NameOrFallback(),
"OrgName": c.OrgName,
"InvitedBy": util.StringsFallback3(c.Name, c.Email, c.Login),
},
}
if err := bus.Dispatch(&emailCmd); err != nil {
return Error(500, "Failed to send email invited_to_org", err)
}
}
return Success(fmt.Sprintf("Existing Grafana user %s added to org %s", user.NameOrFallback(), c.OrgName))
}
func RevokeInvite(c *m.ReqContext) Response {
if ok, rsp := updateTempUserStatus(c.Params(":code"), m.TmpUserRevoked); !ok {
return rsp
}
return Success("Invite revoked")
}
func GetInviteInfoByCode(c *m.ReqContext) Response {
query := m.GetTempUserByCodeQuery{Code: c.Params(":code")}
if err := bus.Dispatch(&query); err != nil {
if err == m.ErrTempUserNotFound {
return Error(404, "Invite not found", nil)
}
return Error(500, "Failed to get invite", err)
}
invite := query.Result
return JSON(200, dtos.InviteInfo{
Email: invite.Email,
Name: invite.Name,
Username: invite.Email,
InvitedBy: util.StringsFallback3(invite.InvitedByName, invite.InvitedByLogin, invite.InvitedByEmail),
})
}
func CompleteInvite(c *m.ReqContext, completeInvite dtos.CompleteInviteForm) Response {
query := m.GetTempUserByCodeQuery{Code: completeInvite.InviteCode}
if err := bus.Dispatch(&query); err != nil {
if err == m.ErrTempUserNotFound {
return Error(404, "Invite not found", nil)
}
return Error(500, "Failed to get invite", err)
}
invite := query.Result
if invite.Status != m.TmpUserInvitePending {
return Error(412, fmt.Sprintf("Invite cannot be used in status %s", invite.Status), nil)
}
cmd := m.CreateUserCommand{
Email: completeInvite.Email,
Name: completeInvite.Name,
Login: completeInvite.Username,
Password: completeInvite.Password,
SkipOrgSetup: true,
}
if err := bus.Dispatch(&cmd); err != nil {
return Error(500, "failed to create user", err)
}
user := &cmd.Result
bus.Publish(&events.SignUpCompleted{
Name: user.NameOrFallback(),
Email: user.Email,
})
if ok, rsp := applyUserInvite(user, invite, true); !ok {
return rsp
}
loginUserWithUser(user, c)
metrics.M_Api_User_SignUpCompleted.Inc()
metrics.M_Api_User_SignUpInvite.Inc()
return Success("User created and logged in")
}
func updateTempUserStatus(code string, status m.TempUserStatus) (bool, Response) {
// update temp user status
updateTmpUserCmd := m.UpdateTempUserStatusCommand{Code: code, Status: status}
if err := bus.Dispatch(&updateTmpUserCmd); err != nil {
return false, Error(500, "Failed to update invite status", err)
}
return true, nil
}
func applyUserInvite(user *m.User, invite *m.TempUserDTO, setActive bool) (bool, Response) {
// add to org
addOrgUserCmd := m.AddOrgUserCommand{OrgId: invite.OrgId, UserId: user.Id, Role: invite.Role}
if err := bus.Dispatch(&addOrgUserCmd); err != nil {
if err != m.ErrOrgUserAlreadyAdded {
return false, Error(500, "Error while trying to create org user", err)
}
}
// update temp user status
if ok, rsp := updateTempUserStatus(invite.Code, m.TmpUserCompleted); !ok {
return false, rsp
}
if setActive {
// set org to active
if err := bus.Dispatch(&m.SetUsingOrgCommand{OrgId: invite.OrgId, UserId: user.Id}); err != nil {
return false, Error(500, "Failed to set org as active", err)
}
}
return true, nil
}
|
pkg/api/org_invite.go
| 0 |
https://github.com/grafana/grafana/commit/dc3a81200b1cd366bdf237ada152ae3d79bdaf59
|
[
0.00017710683459881693,
0.00017309091344941407,
0.00016563745157327503,
0.0001731150841806084,
0.0000022810781956650317
] |
{
"id": 13,
"code_window": [
" );\n",
" }\n",
"\n",
" onVizTypeChanged = (plugin: PanelPlugin) => {\n",
" console.log('changing type to ', plugin.id);\n",
" this.props.panel.changeType(plugin.id);\n",
" };\n",
"\n",
" onChangeTab = (tab: PanelEditorTab) => {\n",
" store.view.updateQuery({ tab: tab.id }, false);\n",
" };\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "public/app/features/dashboard/dashgrid/PanelEditor.tsx",
"type": "replace",
"edit_start_line_idx": 51
}
|
import React from 'react';
import config from 'app/core/config';
import { PanelModel } from '../panel_model';
import { DashboardModel } from '../dashboard_model';
import { getAngularLoader, AngularComponent } from 'app/core/services/angular_loader';
import { DashboardRow } from './DashboardRow';
import { AddPanelPanel } from './AddPanelPanel';
import { importPluginModule } from 'app/features/plugins/plugin_loader';
import { PluginExports } from 'app/types/plugins';
import { PanelChrome } from './PanelChrome';
import { PanelEditor } from './PanelEditor';
export interface Props {
panel: PanelModel;
dashboard: DashboardModel;
}
export interface State {
pluginExports: PluginExports;
}
export class DashboardPanel extends React.Component<Props, State> {
element: any;
angularPanel: AngularComponent;
pluginInfo: any;
specialPanels = {};
constructor(props) {
super(props);
this.state = { pluginExports: null };
this.specialPanels['row'] = this.renderRow.bind(this);
this.specialPanels['add-panel'] = this.renderAddPanel.bind(this);
this.props.panel.events.on('panel-size-changed', this.triggerForceUpdate.bind(this));
}
triggerForceUpdate() {
this.forceUpdate();
}
isSpecial() {
return this.specialPanels[this.props.panel.type];
}
renderRow() {
return <DashboardRow panel={this.props.panel} dashboard={this.props.dashboard} />;
}
renderAddPanel() {
return <AddPanelPanel panel={this.props.panel} dashboard={this.props.dashboard} />;
}
loadPlugin() {
if (this.isSpecial()) {
return;
}
// handle plugin loading & changing of plugin type
if (!this.pluginInfo || this.pluginInfo.id !== this.props.panel.type) {
this.pluginInfo = config.panels[this.props.panel.type];
if (this.pluginInfo.exports) {
this.setState({ pluginExports: this.pluginInfo.exports });
} else {
importPluginModule(this.pluginInfo.module).then(pluginExports => {
this.setState({ pluginExports: pluginExports });
});
}
}
}
componentDidMount() {
this.loadPlugin();
}
componentDidUpdate() {
this.loadPlugin();
// handle angular plugin loading
if (!this.element || this.angularPanel) {
return;
}
let loader = getAngularLoader();
var template = '<plugin-component type="panel" class="panel-height-helper"></plugin-component>';
let scopeProps = { panel: this.props.panel, dashboard: this.props.dashboard };
this.angularPanel = loader.load(this.element, scopeProps, template);
}
componentWillUnmount() {
if (this.angularPanel) {
this.angularPanel.destroy();
}
}
renderReactPanel() {
const { pluginExports } = this.state;
const containerClass = this.props.panel.isEditing ? 'panel-editor-container' : 'panel-height-helper';
const panelWrapperClass = this.props.panel.isEditing ? 'panel-editor-container__panel' : 'panel-height-helper';
// this might look strange with these classes that change when edit, but
// I want to try to keep markup (parents) for panel the same in edit mode to avoide unmount / new mount of panel
// plugin component
return (
<div className={containerClass}>
<div className={panelWrapperClass}>
<PanelChrome
component={pluginExports.PanelComponent}
panel={this.props.panel}
dashboard={this.props.dashboard}
/>
</div>
{this.props.panel.isEditing && (
<div className="panel-editor-container__editor">
<PanelEditor panel={this.props.panel} dashboard={this.props.dashboard} />
</div>
)}
</div>
);
}
render() {
if (this.isSpecial()) {
return this.specialPanels[this.props.panel.type]();
}
if (!this.state.pluginExports) {
return null;
}
if (this.state.pluginExports.PanelComponent) {
return this.renderReactPanel();
}
// legacy angular rendering
return <div ref={element => (this.element = element)} className="panel-height-helper" />;
}
}
|
public/app/features/dashboard/dashgrid/DashboardPanel.tsx
| 1 |
https://github.com/grafana/grafana/commit/dc3a81200b1cd366bdf237ada152ae3d79bdaf59
|
[
0.003201524494215846,
0.0006701340316794813,
0.0001662865688558668,
0.00025845496566034853,
0.0008849319419823587
] |
{
"id": 13,
"code_window": [
" );\n",
" }\n",
"\n",
" onVizTypeChanged = (plugin: PanelPlugin) => {\n",
" console.log('changing type to ', plugin.id);\n",
" this.props.panel.changeType(plugin.id);\n",
" };\n",
"\n",
" onChangeTab = (tab: PanelEditorTab) => {\n",
" store.view.updateQuery({ tab: tab.id }, false);\n",
" };\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "public/app/features/dashboard/dashgrid/PanelEditor.tsx",
"type": "replace",
"edit_start_line_idx": 51
}
|
// 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.
package jaeger
import (
"fmt"
"sync"
"sync/atomic"
"time"
"github.com/opentracing/opentracing-go"
"github.com/uber/jaeger-client-go/log"
)
// Reporter is called by the tracer when a span is completed to report the span to the tracing collector.
type Reporter interface {
// Report submits a new span to collectors, possibly asynchronously and/or with buffering.
Report(span *Span)
// Close does a clean shutdown of the reporter, flushing any traces that may be buffered in memory.
Close()
}
// ------------------------------
type nullReporter struct{}
// NewNullReporter creates a no-op reporter that ignores all reported spans.
func NewNullReporter() Reporter {
return &nullReporter{}
}
// Report implements Report() method of Reporter by doing nothing.
func (r *nullReporter) Report(span *Span) {
// no-op
}
// Close implements Close() method of Reporter by doing nothing.
func (r *nullReporter) Close() {
// no-op
}
// ------------------------------
type loggingReporter struct {
logger Logger
}
// NewLoggingReporter creates a reporter that logs all reported spans to provided logger.
func NewLoggingReporter(logger Logger) Reporter {
return &loggingReporter{logger}
}
// Report implements Report() method of Reporter by logging the span to the logger.
func (r *loggingReporter) Report(span *Span) {
r.logger.Infof("Reporting span %+v", span)
}
// Close implements Close() method of Reporter by doing nothing.
func (r *loggingReporter) Close() {
// no-op
}
// ------------------------------
// InMemoryReporter is used for testing, and simply collects spans in memory.
type InMemoryReporter struct {
spans []opentracing.Span
lock sync.Mutex
}
// NewInMemoryReporter creates a reporter that stores spans in memory.
// NOTE: the Tracer should be created with options.PoolSpans = false.
func NewInMemoryReporter() *InMemoryReporter {
return &InMemoryReporter{
spans: make([]opentracing.Span, 0, 10),
}
}
// Report implements Report() method of Reporter by storing the span in the buffer.
func (r *InMemoryReporter) Report(span *Span) {
r.lock.Lock()
r.spans = append(r.spans, span)
r.lock.Unlock()
}
// Close implements Close() method of Reporter by doing nothing.
func (r *InMemoryReporter) Close() {
// no-op
}
// SpansSubmitted returns the number of spans accumulated in the buffer.
func (r *InMemoryReporter) SpansSubmitted() int {
r.lock.Lock()
defer r.lock.Unlock()
return len(r.spans)
}
// GetSpans returns accumulated spans as a copy of the buffer.
func (r *InMemoryReporter) GetSpans() []opentracing.Span {
r.lock.Lock()
defer r.lock.Unlock()
copied := make([]opentracing.Span, len(r.spans))
copy(copied, r.spans)
return copied
}
// Reset clears all accumulated spans.
func (r *InMemoryReporter) Reset() {
r.lock.Lock()
defer r.lock.Unlock()
r.spans = nil
}
// ------------------------------
type compositeReporter struct {
reporters []Reporter
}
// NewCompositeReporter creates a reporter that ignores all reported spans.
func NewCompositeReporter(reporters ...Reporter) Reporter {
return &compositeReporter{reporters: reporters}
}
// Report implements Report() method of Reporter by delegating to each underlying reporter.
func (r *compositeReporter) Report(span *Span) {
for _, reporter := range r.reporters {
reporter.Report(span)
}
}
// Close implements Close() method of Reporter by closing each underlying reporter.
func (r *compositeReporter) Close() {
for _, reporter := range r.reporters {
reporter.Close()
}
}
// ------------- REMOTE REPORTER -----------------
type reporterQueueItemType int
const (
defaultQueueSize = 100
defaultBufferFlushInterval = 1 * time.Second
reporterQueueItemSpan reporterQueueItemType = iota
reporterQueueItemClose
)
type reporterQueueItem struct {
itemType reporterQueueItemType
span *Span
close *sync.WaitGroup
}
type remoteReporter struct {
// These fields must be first in the struct because `sync/atomic` expects 64-bit alignment.
// Cf. https://github.com/uber/jaeger-client-go/issues/155, https://goo.gl/zW7dgq
queueLength int64
closed int64 // 0 - not closed, 1 - closed
reporterOptions
sender Transport
queue chan reporterQueueItem
}
// NewRemoteReporter creates a new reporter that sends spans out of process by means of Sender.
// Calls to Report(Span) return immediately (side effect: if internal buffer is full the span is dropped).
// Periodically the transport buffer is flushed even if it hasn't reached max packet size.
// Calls to Close() block until all spans reported prior to the call to Close are flushed.
func NewRemoteReporter(sender Transport, opts ...ReporterOption) Reporter {
options := reporterOptions{}
for _, option := range opts {
option(&options)
}
if options.bufferFlushInterval <= 0 {
options.bufferFlushInterval = defaultBufferFlushInterval
}
if options.logger == nil {
options.logger = log.NullLogger
}
if options.metrics == nil {
options.metrics = NewNullMetrics()
}
if options.queueSize <= 0 {
options.queueSize = defaultQueueSize
}
reporter := &remoteReporter{
reporterOptions: options,
sender: sender,
queue: make(chan reporterQueueItem, options.queueSize),
}
go reporter.processQueue()
return reporter
}
// Report implements Report() method of Reporter.
// It passes the span to a background go-routine for submission to Jaeger backend.
// If the internal queue is full, the span is dropped and metrics.ReporterDropped counter is incremented.
// If Report() is called after the reporter has been Close()-ed, the additional spans will not be
// sent to the backend, but the metrics.ReporterDropped counter may not reflect them correctly,
// because some of them may still be successfully added to the queue.
func (r *remoteReporter) Report(span *Span) {
select {
case r.queue <- reporterQueueItem{itemType: reporterQueueItemSpan, span: span}:
atomic.AddInt64(&r.queueLength, 1)
default:
r.metrics.ReporterDropped.Inc(1)
}
}
// Close implements Close() method of Reporter by waiting for the queue to be drained.
func (r *remoteReporter) Close() {
if swapped := atomic.CompareAndSwapInt64(&r.closed, 0, 1); !swapped {
r.logger.Error("Repeated attempt to close the reporter is ignored")
return
}
r.sendCloseEvent()
r.sender.Close()
}
func (r *remoteReporter) sendCloseEvent() {
wg := &sync.WaitGroup{}
wg.Add(1)
item := reporterQueueItem{itemType: reporterQueueItemClose, close: wg}
r.queue <- item // if the queue is full we will block until there is space
atomic.AddInt64(&r.queueLength, 1)
wg.Wait()
}
// processQueue reads spans from the queue, converts them to Thrift, and stores them in an internal buffer.
// When the buffer length reaches batchSize, it is flushed by submitting the accumulated spans to Jaeger.
// Buffer also gets flushed automatically every batchFlushInterval seconds, just in case the tracer stopped
// reporting new spans.
func (r *remoteReporter) processQueue() {
// flush causes the Sender to flush its accumulated spans and clear the buffer
flush := func() {
if flushed, err := r.sender.Flush(); err != nil {
r.metrics.ReporterFailure.Inc(int64(flushed))
r.logger.Error(fmt.Sprintf("error when flushing the buffer: %s", err.Error()))
} else if flushed > 0 {
r.metrics.ReporterSuccess.Inc(int64(flushed))
}
}
timer := time.NewTicker(r.bufferFlushInterval)
for {
select {
case <-timer.C:
flush()
case item := <-r.queue:
atomic.AddInt64(&r.queueLength, -1)
switch item.itemType {
case reporterQueueItemSpan:
span := item.span
if flushed, err := r.sender.Append(span); err != nil {
r.metrics.ReporterFailure.Inc(int64(flushed))
r.logger.Error(fmt.Sprintf("error reporting span %q: %s", span.OperationName(), err.Error()))
} else if flushed > 0 {
r.metrics.ReporterSuccess.Inc(int64(flushed))
// to reduce the number of gauge stats, we only emit queue length on flush
r.metrics.ReporterQueueLength.Update(atomic.LoadInt64(&r.queueLength))
}
case reporterQueueItemClose:
timer.Stop()
flush()
item.close.Done()
return
}
}
}
}
|
vendor/github.com/uber/jaeger-client-go/reporter.go
| 0 |
https://github.com/grafana/grafana/commit/dc3a81200b1cd366bdf237ada152ae3d79bdaf59
|
[
0.00018014098168350756,
0.00017236948770005256,
0.00016217488155234605,
0.0001731791562633589,
0.00000520986623087083
] |
{
"id": 13,
"code_window": [
" );\n",
" }\n",
"\n",
" onVizTypeChanged = (plugin: PanelPlugin) => {\n",
" console.log('changing type to ', plugin.id);\n",
" this.props.panel.changeType(plugin.id);\n",
" };\n",
"\n",
" onChangeTab = (tab: PanelEditorTab) => {\n",
" store.view.updateQuery({ tab: tab.id }, false);\n",
" };\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "public/app/features/dashboard/dashgrid/PanelEditor.tsx",
"type": "replace",
"edit_start_line_idx": 51
}
|
#!/usr/bin/expect -f
# wrapper to make rpm --sign be non-interactive
# passwd is 1st arg, file to sign is 2nd
#send_user «$argv0 [lrange $argv 0 2]\n"
#set files [lrange $argv 1 $argc ]
set password [lindex $argv 0]
set files [lindex $argv 1]
spawn rpm --addsign $files
expect "Enter pass phrase:"
send -- "$password\r"
expect eof
|
scripts/build/sign_expect
| 0 |
https://github.com/grafana/grafana/commit/dc3a81200b1cd366bdf237ada152ae3d79bdaf59
|
[
0.0001760810409905389,
0.00017576086975168437,
0.00017544069851282984,
0.00017576086975168437,
3.2017123885452747e-7
] |
{
"id": 13,
"code_window": [
" );\n",
" }\n",
"\n",
" onVizTypeChanged = (plugin: PanelPlugin) => {\n",
" console.log('changing type to ', plugin.id);\n",
" this.props.panel.changeType(plugin.id);\n",
" };\n",
"\n",
" onChangeTab = (tab: PanelEditorTab) => {\n",
" store.view.updateQuery({ tab: tab.id }, false);\n",
" };\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "public/app/features/dashboard/dashgrid/PanelEditor.tsx",
"type": "replace",
"edit_start_line_idx": 51
}
|
// Copyright 2017 The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package prometheus
// Observer is the interface that wraps the Observe method, which is used by
// Histogram and Summary to add observations.
type Observer interface {
Observe(float64)
}
// The ObserverFunc type is an adapter to allow the use of ordinary
// functions as Observers. If f is a function with the appropriate
// signature, ObserverFunc(f) is an Observer that calls f.
//
// This adapter is usually used in connection with the Timer type, and there are
// two general use cases:
//
// The most common one is to use a Gauge as the Observer for a Timer.
// See the "Gauge" Timer example.
//
// The more advanced use case is to create a function that dynamically decides
// which Observer to use for observing the duration. See the "Complex" Timer
// example.
type ObserverFunc func(float64)
// Observe calls f(value). It implements Observer.
func (f ObserverFunc) Observe(value float64) {
f(value)
}
// ObserverVec is an interface implemented by `HistogramVec` and `SummaryVec`.
type ObserverVec interface {
GetMetricWith(Labels) (Observer, error)
GetMetricWithLabelValues(lvs ...string) (Observer, error)
With(Labels) Observer
WithLabelValues(...string) Observer
Collector
}
|
vendor/github.com/prometheus/client_golang/prometheus/observer.go
| 0 |
https://github.com/grafana/grafana/commit/dc3a81200b1cd366bdf237ada152ae3d79bdaf59
|
[
0.00018007264588959515,
0.0001711659861030057,
0.00016066250100266188,
0.00017260501044802368,
0.000007012779860815499
] |
{
"id": 0,
"code_window": [
"import { transparentize } from 'polished';\n",
"import { includeConditionalArg } from '@storybook/csf';\n",
"import { once } from '@storybook/client-logger';\n",
"import { IconButton, ResetWrapper, Link } from '@storybook/components';\n",
"\n",
"import { UndoIcon } from '@storybook/icons';\n",
"import { ArgRow } from './ArgRow';\n",
"import { SectionRow } from './SectionRow';\n",
"import type { ArgType, ArgTypes, Args, Globals } from './types';\n",
"\n",
"import { EmptyBlock } from '..';\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { DocumentIcon, UndoIcon } from '@storybook/icons';\n"
],
"file_path": "code/ui/blocks/src/components/ArgsTable/ArgsTable.tsx",
"type": "replace",
"edit_start_line_idx": 9
}
|
import type { FC } from 'react';
import React, { useEffect, useState } from 'react';
import { styled } from '@storybook/theming';
import { Link } from '@storybook/components';
import { VideoIcon } from '@storybook/icons';
interface EmptyProps {
inAddonPanel?: boolean;
}
const Wrapper = styled.div<{ inAddonPanel?: boolean }>(({ inAddonPanel, theme }) => ({
height: inAddonPanel ? '100%' : 'auto',
display: 'flex',
border: inAddonPanel ? 'none' : `1px solid ${theme.appBorderColor}`,
borderRadius: inAddonPanel ? 0 : theme.appBorderRadius,
padding: inAddonPanel ? 0 : 40,
alignItems: 'center',
justifyContent: 'center',
flexDirection: 'column',
gap: 15,
background: theme.background.content,
boxShadow: 'rgba(0, 0, 0, 0.10) 0 1px 3px 0',
}));
const Content = styled.div({
display: 'flex',
flexDirection: 'column',
gap: 4,
maxWidth: 415,
});
const Title = styled.div(({ theme }) => ({
fontWeight: theme.typography.weight.bold,
fontSize: theme.typography.size.s2 - 1,
textAlign: 'center',
color: theme.textColor,
}));
const Description = styled.div(({ theme }) => ({
fontWeight: theme.typography.weight.regular,
fontSize: theme.typography.size.s2 - 1,
textAlign: 'center',
color: theme.textMutedColor,
}));
const Links = styled.div(({ theme }) => ({
display: 'flex',
fontSize: theme.typography.size.s2 - 1,
gap: 25,
}));
const Divider = styled.div(({ theme }) => ({
width: 1,
height: 16,
backgroundColor: theme.appBorderColor,
}));
export const Empty: FC<EmptyProps> = ({ inAddonPanel }) => {
const [isLoading, setIsLoading] = useState(true);
// We are adding a small delay to avoid flickering when the story is loading.
// It takes a bit of time for the controls to appear, so we don't want
// to show the empty state for a split second.
useEffect(() => {
const load = setTimeout(() => {
setIsLoading(false);
}, 100);
return () => clearTimeout(load);
}, []);
if (isLoading) return null;
return (
<Wrapper inAddonPanel={inAddonPanel}>
<Content>
<Title>
{inAddonPanel
? 'Interactive story playground'
: "Args table with interactive controls couldn't be auto-generated"}
</Title>
<Description>
Controls give you an easy to use interface to test your components. Set your story args
and you'll see controls appearing here automatically.
</Description>
</Content>
<Links>
{inAddonPanel && (
<>
<Link href="https://youtu.be/0gOfS6K0x0E" target="_blank" withArrow>
<VideoIcon /> Watch 5m video
</Link>
<Divider />
<Link
href="https://storybook.js.org/docs/react/essentials/controls"
target="_blank"
withArrow
>
Read docs
</Link>
</>
)}
{!inAddonPanel && (
<Link
href="https://storybook.js.org/docs/react/essentials/controls"
target="_blank"
withArrow
>
Learn how to set that up
</Link>
)}
</Links>
</Wrapper>
);
};
|
code/ui/blocks/src/components/ArgsTable/Empty.tsx
| 1 |
https://github.com/storybookjs/storybook/commit/39e6fd82c4a39766bdfc66f4b67021b57339a58f
|
[
0.0003309361345600337,
0.00018961005844175816,
0.0001624279102543369,
0.00017362373182550073,
0.00004476057438296266
] |
{
"id": 0,
"code_window": [
"import { transparentize } from 'polished';\n",
"import { includeConditionalArg } from '@storybook/csf';\n",
"import { once } from '@storybook/client-logger';\n",
"import { IconButton, ResetWrapper, Link } from '@storybook/components';\n",
"\n",
"import { UndoIcon } from '@storybook/icons';\n",
"import { ArgRow } from './ArgRow';\n",
"import { SectionRow } from './SectionRow';\n",
"import type { ArgType, ArgTypes, Args, Globals } from './types';\n",
"\n",
"import { EmptyBlock } from '..';\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { DocumentIcon, UndoIcon } from '@storybook/icons';\n"
],
"file_path": "code/ui/blocks/src/components/ArgsTable/ArgsTable.tsx",
"type": "replace",
"edit_start_line_idx": 9
}
|
```ts
// Button.stories.ts
import type { Meta, StoryObj } from '@storybook/angular/';
import { Button } from './button.component';
const meta: Meta<Button> = {
component: Button,
};
export default meta;
type Story = StoryObj<Button>;
export const Primary: Story = {
args: {
primary: true,
label: 'Button',
},
};
```
|
docs/snippets/angular/button-story-with-args.ts.mdx
| 0 |
https://github.com/storybookjs/storybook/commit/39e6fd82c4a39766bdfc66f4b67021b57339a58f
|
[
0.0001886464742710814,
0.000179561015102081,
0.00017436551570426673,
0.00017567102622706443,
0.000006446467068599304
] |
{
"id": 0,
"code_window": [
"import { transparentize } from 'polished';\n",
"import { includeConditionalArg } from '@storybook/csf';\n",
"import { once } from '@storybook/client-logger';\n",
"import { IconButton, ResetWrapper, Link } from '@storybook/components';\n",
"\n",
"import { UndoIcon } from '@storybook/icons';\n",
"import { ArgRow } from './ArgRow';\n",
"import { SectionRow } from './SectionRow';\n",
"import type { ArgType, ArgTypes, Args, Globals } from './types';\n",
"\n",
"import { EmptyBlock } from '..';\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { DocumentIcon, UndoIcon } from '@storybook/icons';\n"
],
"file_path": "code/ui/blocks/src/components/ArgsTable/ArgsTable.tsx",
"type": "replace",
"edit_start_line_idx": 9
}
|
import type { PropDef, ExtractedProp } from '@storybook/docs-tools';
import { createDefaultValue, createDefaultValueFromRawDefaultProp } from '../lib/defaultValues';
export function enhanceTypeScriptProp(extractedProp: ExtractedProp, rawDefaultProp?: any): PropDef {
const { propDef } = extractedProp;
const { defaultValue } = extractedProp.docgenInfo;
if (defaultValue != null && defaultValue.value != null) {
const newDefaultValue = createDefaultValue(defaultValue.value);
if (newDefaultValue != null) {
propDef.defaultValue = newDefaultValue;
}
} else if (rawDefaultProp != null) {
const newDefaultValue = createDefaultValueFromRawDefaultProp(rawDefaultProp, propDef);
if (newDefaultValue != null) {
propDef.defaultValue = newDefaultValue;
}
}
return propDef;
}
export function enhanceTypeScriptProps(extractedProps: ExtractedProp[]): PropDef[] {
return extractedProps.map((prop) => enhanceTypeScriptProp(prop));
}
|
code/renderers/react/src/docs/typeScript/handleProp.ts
| 0 |
https://github.com/storybookjs/storybook/commit/39e6fd82c4a39766bdfc66f4b67021b57339a58f
|
[
0.00017669441876932979,
0.0001728438219288364,
0.00016718119150027633,
0.00017465588462073356,
0.000004089663889317308
] |
{
"id": 0,
"code_window": [
"import { transparentize } from 'polished';\n",
"import { includeConditionalArg } from '@storybook/csf';\n",
"import { once } from '@storybook/client-logger';\n",
"import { IconButton, ResetWrapper, Link } from '@storybook/components';\n",
"\n",
"import { UndoIcon } from '@storybook/icons';\n",
"import { ArgRow } from './ArgRow';\n",
"import { SectionRow } from './SectionRow';\n",
"import type { ArgType, ArgTypes, Args, Globals } from './types';\n",
"\n",
"import { EmptyBlock } from '..';\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { DocumentIcon, UndoIcon } from '@storybook/icons';\n"
],
"file_path": "code/ui/blocks/src/components/ArgsTable/ArgsTable.tsx",
"type": "replace",
"edit_start_line_idx": 9
}
|
# Releasing <!-- omit in toc -->
> **Note**
> This document is relevant only for maintainers that have permissions to release new versions of Storybook. Anyone can read it for interest or to suggest changes, but it's not required knowledge.
## Table of Contents <!-- omit in toc -->
- [Introduction](#introduction)
- [Branches](#branches)
- [Release Pull Requests](#release-pull-requests)
- [Patch Releases](#patch-releases)
- [Non-patch Releases](#non-patch-releases)
- [Publishing](#publishing)
- [👉 How to Release](#-how-to-release)
- [1. Find the Prepared Pull Request](#1-find-the-prepared-pull-request)
- [2. Freeze the Pull Request and run CI](#2-freeze-the-pull-request-and-run-ci)
- [3. QA Each Merged Pull Request](#3-qa-each-merged-pull-request)
- [4. Re-trigger the Workflow](#4-re-trigger-the-workflow)
- [5. Make Manual Changes](#5-make-manual-changes)
- [6. Merge](#6-merge)
- [7. See the "Publish" Workflow Finish](#7-see-the-publish-workflow-finish)
- [Releasing Locally in an Emergency 🚨](#releasing-locally-in-an-emergency-)
- [Canary Releases](#canary-releases)
- [With GitHub UI](#with-github-ui)
- [With the CLI](#with-the-cli)
- [Versioning Scenarios](#versioning-scenarios)
- [Prereleases - `7.1.0-alpha.12` -\> `7.1.0-alpha.13`](#prereleases---710-alpha12---710-alpha13)
- [Prerelease promotions - `7.1.0-alpha.13` -\> `7.1.0-beta.0`](#prerelease-promotions---710-alpha13---710-beta0)
- [Minor/major releases - `7.1.0-rc.2` -\> `7.1.0` or `8.0.0-rc.3` -\> `8.0.0`](#minormajor-releases---710-rc2---710-or-800-rc3---800)
- [First prerelease of new major/minor - `7.1.0` -\> `7.2.0-alpha.0` or `8.0.0-alpha.0`](#first-prerelease-of-new-majorminor---710---720-alpha0-or-800-alpha0)
- [Patch releases to stable - subset of `7.1.0-alpha.13` -\> `7.0.14`](#patch-releases-to-stable---subset-of-710-alpha13---7014)
- [Patch releases to earlier versions - subset of `7.1.0-alpha.13` -\> `6.5.14`](#patch-releases-to-earlier-versions---subset-of-710-alpha13---6514)
- [Prerelease of upcoming patch release - `7.0.20` -\> `7.0.21-alpha.0`](#prerelease-of-upcoming-patch-release---7020---7021-alpha0)
- [Merges to `main` without versioning](#merges-to-main-without-versioning)
- [FAQ](#faq)
- [When should I use the "patch:yes" label?](#when-should-i-use-the-patchyes-label)
- [How do I make changes to the release tooling/process?](#how-do-i-make-changes-to-the-release-toolingprocess)
- [Why do I need to re-trigger workflows to update the changelog?](#why-do-i-need-to-re-trigger-workflows-to-update-the-changelog)
- [Which combination of inputs creates the version bump I need?](#which-combination-of-inputs-creates-the-version-bump-i-need)
- [Which changes are considered "releasable", and what does it mean?](#which-changes-are-considered-releasable-and-what-does-it-mean)
- [Why are no release PRs being prepared?](#why-are-no-release-prs-being-prepared)
- [Why do we need separate release branches?](#why-do-we-need-separate-release-branches)
## Introduction
This document explains the release process for the Storybook monorepo. There are two types:
1. Non-patch releases - releasing any content that is on the `next` branch, either prereleases or stable releases
2. Patch releases - picking any content from `next` to `main`, that needs to be patched back to the current stable minor release
The release process is based on automatically created "Release Pull Requests", that when merged will trigger a new version to be released.
A designated Releaser -- which may rotate between core team members -- will go through the release process in the current Release PR. This process is implemented with NodeJS scripts in [`scripts/release`](../scripts/release/) and three GitHub Actions workflows:
- [Prepare `next` PR](../.github/workflows/prepare-non-patch-release.yml)
- [Prepare patch PR](../.github/workflows/prepare-patch-release.yml)
- [Publish](../.github/workflows/publish.yml)
> **Note**
> This document distinguishes between **patch** and **non-patch** releases. The distinction reflects the difference between patching an existing minor version on `main` or releasing a new minor/major/prerelease from `next`.
### Branches
To understand the release structure, it's important to know the branching strategy used. All development is done on the `next` branch, where new features and bug fixes are added. This branch contains content to be released in the next prerelease (eg. `v7.1.0-alpha.22`).
The `main` branch contains the content for the current stable release (eg. `v7.0.20`). When changes need to be made to both the next major/minor release and the current patch release (bug fixes or small improvements), they are made to `next`. If the change needs to be patched back to the current minor version (eg. from `7.1.0-alpha.20` to `7.0.18`), the PR containing the fix is labeled with the **"patch"** label, so the release workflow can pick it up. This ensures changes are tested in a prerelease before being released to stable.
The actual (pre)releases are not made from `next` nor `main`, but from `next-release` and `latest-release` respectively. This indirection is explained in [the "Why do we need separate release branches?" section](#why-do-we-need-separate-release-branches) below.
The branches in the monorepo can be summarized in this diagram (simplified):
```mermaid
%%{init: { 'gitGraph': { 'showCommitLabel': false } } }%%
gitGraph
commit
branch latest-release
branch next
commit
branch next-release
commit
commit tag: "7.1.0-alpha.18"
checkout next
merge next-release
commit id: "bugfix"
commit
checkout latest-release
cherry-pick id: "bugfix"
commit tag: "7.0.20"
checkout next-release
merge next
commit tag: "7.1.0-alpha.19"
checkout next
merge next-release
commit
checkout main
merge latest-release
```
## Release Pull Requests
Two GitHub Actions workflows automatically create release pull requests, one for each type of release. These pull requests act as the "interface" for the Releaser to create a new release. Although the behavior between the two is similar, some minor differences exist, as described in the subsections below.
The high-level flow is:
1. When a PR is merged to `next` (or a commit is pushed), both release pull requests are (re)generated.
2. They create a new branch - `version-(patch|non-patch)-from-<CURRENT-VERSION>`.
3. They calculate which version to bump to according to the version strategy.
4. They update `CHANGELOG(.prerelease).md` with all changes detected.
5. They commit everything.
6. They **force push**.
7. They open/edit a pull request towards `next-release` or `latest-release`.
A few key points to note in this flow:
- The PRs are regenerated on any changes to `next`, or can be manually triggered (see [the Re-trigger the Workflow section](#4-re-trigger-the-workflow)).
- The changes are force pushed to the branch, so any manual changes on the release branch before merging risk being overwritten if someone else merges a new change to `next`, triggering the workflow. To avoid this, apply the **"freeze"** label to the pull request.
- The changelogs are committed during the preparation, but the packages are not version bumped and not published until later.
- The release pull requests don't target their working branches (`next` and `main`), but rather `next-release` and `latest-release`.
### Patch Releases
> **Note**
> Workflow: [`prepare-patch-release.yml`](../.github/workflows/prepare-patch-release.yml)
Patch releases are created by [cherry-picking](https://www.atlassian.com/git/tutorials/cherry-pick) any merged, unreleased pull requests that have the "**patch:yes**" label applied to the `next` branch. The merge commit of said pull requests are cherry-picked.
Sometimes it is desired to pick pull requests back to `main` even if they are not considered "releasable". Unlike non-patch release preparation, patch releases will not be canceled if the content is not releasable. It might not make sense to create a new patch release if the changes are only for documentation and/or internal build systems. However, getting the changes back to `main` is the only way to deploy the documentation to the production docs site. You may also want to cherry-pick changes to internal CI to fix issues. These are valid scenarios where you want to cherry-pick the changes without being blocked on "releasable" content. In these cases, where all cherry picks are non-releasable, the preparation workflow creates a "merging" pull request instead of a "releasing" pull request. This pull request does not bump versions or update changelogs; it just cherry-picks the changes and allows you to merge them into `latest-release` -> `main`.
The preparation workflow sequentially cherry-picks each patch pull request to its branch. If this cherry-picking fails due to conflicts or other reasons, it is ignored and the next pull request is processed. All failing cherry-picks are listed in the release pull request's description, for the Releaser to manually cherry-pick during the release process. This problem occurs more often when `main` and `next` diverge, i.e. the longer it has been since a stable major/minor release.
Similar to the non-patch release flow, the preparation workflow for patches will create a new branch from `main` called `version-patch-from-<CURRENT-STABLE-VERSION>`, and open a pull request that targets `latest-release`. When the pull request is merged by the Releaser, the [publish workflow](#publishing) will eventually merge `latest-release` into `main`.
Here is an example of a workflow where a feature and two bug fixes have been merged to `next`. Only the bug fixes have the "**patch:yes**" label, so only those two go into the new `7.0.19` release. Note that it is the merge commits to `next` that are cherry-picked, not the commits on the bugfix branches.
```mermaid
gitGraph
commit
branch latest-release
branch next
checkout latest-release
commit tag: "v7.0.18"
checkout main
merge latest-release
checkout next
commit
branch some-patched-bugfix
commit
commit id: "patch1"
checkout next
merge some-patched-bugfix
branch new-feature
commit
checkout next
merge new-feature
branch other-patched-bugfix
commit id: "patch2"
checkout next
merge other-patched-bugfix
checkout main
branch version-patch-from-7.0.18
cherry-pick id: "patch1"
cherry-pick id: "patch2"
commit id: "write changelog"
checkout latest-release
merge version-patch-from-7.0.18
commit id: "bump versions" tag: "v7.0.19"
checkout main
merge latest-release
```
### Non-patch Releases
> **Note**
> Workflow: [`prepare-non-patch-release.yml`](../.github/workflows/prepare-non-patch-release.yml)
Non-patch releases are prepared with all content from the `next` branch. The changelog is generated by examining the git history, and looking up all the commits and pull requests between the current prerelease (on `next-release`) and `HEAD` of `next`.
The default versioning strategy is to increase the current prerelease number, as described in [Prereleases - `7.1.0-alpha.12` -> `7.1.0-alpha.13`](#prereleases---710-alpha12---710-alpha13). If there is no prerelease number (i.e., we just released a new stable minor/major version), it will add one to a patch bump, so it would go from `7.2.0` to `7.2.1-0` by default.
`next`-PRs are only created if there are actual changes to release. Content labeled with "build" or "documentation" is [not considered "releasable"](#which-changes-are-considered-releasable-and-what-does-it-mean) and is not user-facing, so it doesn't make sense to create a release. This is explained in more detail in [Why are no release PRs being prepared?](#why-are-no-release-prs-being-prepared).
The preparation workflow will create a new branch from `next`, called `version-non-patch-from-<CURRENT-NEXT-VERSION>`, and open a pull request targeting `next-release`. When the Releaser merges it, the [publish workflow](#publishing) will merge `next-release` into `next`.
Here's an example of a workflow where a feature and a bugfix have been created and then released to a new `7.1.0-alpha.29` version. All the commits highlighted with square dots are the ones that will be considered when generating the changelog.
```mermaid
%%{init: { 'gitGraph': { 'mainBranchName': 'next' } } }%%
gitGraph
commit
branch next-release
commit tag: "7.1.0-alpha.28"
checkout next
merge next-release
commit type: HIGHLIGHT id: "direct commit"
branch new-feature
commit
commit
checkout next
merge new-feature type: HIGHLIGHT
branch some-bugfix
commit
checkout next
merge some-bugfix type: HIGHLIGHT
branch version-non-patch-from-7.1.0-alpha.28
commit id: "write changelog"
checkout next-release
merge version-non-patch-from-7.1.0-alpha.28
commit id: "bump versions" tag: "7.1.0-alpha.29"
checkout next
merge next-release
```
### Publishing
> **Note**
> Workflow: [`publish.yml`](../.github/workflows/publish.yml)
When either a non-patch release or a patch release branch is merged into `latest-release` or `next-release`, the publishing workflow is triggered. This workflow performs the following tasks:
1. Bump versions of all packages according to the plan from the prepared PRs
2. Install dependencies and build all packages.
3. Publish packages to npm.
4. (If this is a patch release, add the "**patch:done**" label to all relevant pull requests.)
5. Create a new GitHub Release, including a version tag in the release branch (`latest-release` or `next-release`).
6. Merge the release branch into the core branch (`main` or `next`).
7. (If this is a patch release, copy the `CHANGELOG.md` changes from `main` to `next`.)
The publish workflow runs in the "release" GitHub environment, which has the npm token required to publish packages to the `@storybook` npm organization. For security reasons, this environment can only be accessed from the four "core" branches: `main`, `next`, `latest-release` and `next-release`.
## 👉 How to Release
This section explains what a Releaser should do when it's time to release. The steps are also outlined in the release pull requests, to provide guidance for inexperienced Releasers.
The high-level workflow for a Releaser is:
1. Find the prepared pull request
2. Freeze the pull request
3. Make changes to merged pull requests (revert, rename, relabel)
4. Re-trigger the workflow to get changes from step 3 in
5. Make any manual changes needed
6. Merge
7. Check that the "publish" workflow has finished successfully
### 1. Find the Prepared Pull Request
Look for the release pull request that has been prepared for the type of release you're about to release:
- "Release: Prerelease|Minor|Major `<NEXT-VERSION>`" for releases from `next`
- "Release: Patch `<NEXT-VERSION>`" for patch releases
- "Release: Merge patches to `main` (without version bump)" for patches without releases
For example: https://github.com/storybookjs/storybook/pull/23148
### 2. Freeze the Pull Request and run CI
Add the "**freeze**" label to the pull request. This will stop the preparation workflows from running when new changes to `next` are merged. This allows you to make changes without worrying about other people's work overriding yours.
The "**freeze**" label does not cancel the workflows when they are triggered manually, so you can still run the workflow.
You also need to add the "**ci:daily**" label to the pull request to trigger CI runs. This will start a full CI run and re-run on any changes. CI does not run by default to avoid unnecessary re-runs until a new release is being created.
### 3. QA Each Merged Pull Request
It is important to verify that the release includes the right content. Key elements to account for are:
1. Is the change suitable for the version bump?
For example, check if it's a breaking change that isn't allowed in a minor prerelease, or if it's a new feature in a patch release. If it's not suitable, revert the pull request and notify the author.
Sometimes when doing a patch release, a pull request can have the "patch:yes" label but you don't want that change to be part of this release. Maybe you're not confident in the change, or you require more input from maintainers before releasing it. In those situations you should remove the "patch:yes" label from the pull request and follow through with the release (make sure to re-trigger the workflow). When the release is done, add the "patch:yes" label back again, so it will be part of the next release.
2. Is the pull request title correct?
The title of pull requests is added to the user-facing changelogs, so it must be accurate and understandable. It should follow the pattern "[Area]: [Summary]", where [Area] is the part of the repo that has been changed, and the summary is what has changed.
It's easy to confuse [Area] with labels, but they are not the same. For example, the "**build**" label indicates that the changes are internal, but a "build" [Area] is _not_ correct. The area could be "Core" or "CI", but rarely is the area being changed actually the "build" area.
If a pull request changes multiple places, it can be hard to choose an area - this is often the case when upgrading dependencies - so use your best judgement. There's no hard rule, but a good guideline is that the more precise it is, the more useful it is to read later.
3. Is the pull request labeled correctly?
Some labels have specific meanings when it comes to releases. It's important that each pull request has labels that accurately describe the change, as labels can determine if a pull request is included in the changelog or not. This is explained further in the [Which changes are considered "releasable", and what does it mean?](#which-changes-are-considered-releasable-and-what-does-it-mean) section.
4. Patches: has it already been released in a prerelease?
If this is a patch release, make sure that all pull requests have already been released in a prerelease. If some haven't, create a new prerelease first.
This is not a technical requirement, but it's a good practice to ensure that a change doesn't break a prerelease before releasing it to stable.
### 4. Re-trigger the Workflow
Any changes made to pull requests' titles, labels or even reverts won't be reflected in the release pull request because it's hopefully frozen at this point. Even if it isn't, the workflow only triggers on pushes to `next`, not when pull request meta data is changed.
Therefore, if any changes were made in step 3, you need to re-trigger the workflow manually to regenerate the changelog and the version bump. If no changes were made, this step can be skipped.
It's important to remember that triggering the workflow will force push changes to the branch, so it must be done before committing any changes manually (the next step). Otherwise, these will be overwritten.
> **Warning**
> When re-triggering the workflow, any new content merged to `next` will also become part of the release pull request. You can't assume the same content with fixes will be seen, as new content may have been merged in since the pull request was frozen.
When triggering the workflows, always choose the `next` branch as the base, unless you know exactly what you are doing.
The workflows can be triggered here:
- [Prepare next PR](https://github.com/storybookjs/storybook/actions/workflows/prepare-non-patch-release.yml)
- [Prepare patch PR](https://github.com/storybookjs/storybook/actions/workflows/prepare-patch-release.yml)
Crucially for prereleases, this is also where you change the versioning strategy if you need something else than the default as described in [Preparing - Non-patch Releases](#non-patch-releases). When triggering the non-patch workflow manually, you can optionally add inputs:

See [Versioning Scenarios](#versioning-scenarios) for a description of each version bump scenario, how to activate it and what it does, and [Which combination of inputs creates the version bump I need?](#which-combination-of-inputs-creates-the-version-bump-i-need) for a detailed description of the workflow inputs.
### 5. Make Manual Changes
It's possible and valid to push manual changes directly on the release branch when needed. This could be to alter the changelog in a way that can't be done automatically, or another critical change is needed for the release to work. Any changes made will be merged to `next|main` once the release has been published.
It's recommended to use the automated process as much as possible to ensure that the information in GitHub is the single source of truth, and that pull requests and changelogs are in sync.
> **Warning**
> If you make manual changes to the changelog, you also need to make those changes in either [`./docs/versions/latest.json`](../docs/versions/latest.json) or [`./docs/versions/next.json`](../docs/versions/next.json). The `"plain"` property should match the changelog entry, **without the heading** and with all new lines replaces with `\n`.
> This is common for custom release notes when releasing majors and minors.
### 6. Merge
When the pull request was frozen, a CI run was triggered on the branch. If it's green, it's time to merge the pull request. If CI is failing for some reason, consult with the rest of the core team. These release pull requests are almost exact copies of `next|main` so CI should only fail if they fail too.
### 7. See the "Publish" Workflow Finish
Merging the pull request will trigger [the publish workflow](https://github.com/storybookjs/storybook/actions/workflows/publish.yml), which does the final version bumping and publishing. As a Releaser, you're responsible for this to finish successfully, so you should watch it until the end. If it fails, it will notify in Discord, so you can monitor that instead if you want to.
Done! 🚀
## Releasing Locally in an Emergency 🚨
Things can fail, code can break, and bugs can exist. When automation is broken, there may be a need for an emergency escape hatch to release new fixes. In such a situation, it's valid to run the whole release process locally instead of relying on pull requests and workflows. You don't need to create pull requests or split preparation and publishing; you can do it all at once, but make sure you still follow the correct branching strategy.
You can either prepare the release locally and use the automatic workflow for publishing it or you can do the whole release workflow locally. If you choose the latter approach, you need a token to the npm registry to publish (set as `YARN_NPM_AUTH_TOKEN`), which you can get from @shilman or @ndelangen.
You can inspect the workflows to see what they are running and copy that, but here is a general sequence of steps to mimic the automated workflow. Feel free to deviate from this as needed.
Before you start you should make sure that your working tree is clean and the repository is in a clean state by running `git clean -xdf`.
1. Create a new branch from either `next` or `main` (patches)
2. Get all tags: `git fetch --tags origin`
3. Install dependencies: `yarn task --task=install --start-from=install`
4. `cd scripts`
5. (If patch release) Cherry pick:
1. `yarn release:pick-patches`
2. Manually cherry pick any necessary patches based on the previous output
6. Bump versions:
1. If you plan on using automatic publishing (ie. stop at step 12), bump with deferred: `yarn release:version --verbose --deferred --release-type <RELEASE_TYPE> --pre-id <PRE_ID>`
2. If doing the whole release locally, **do not** defer the bump: `yarn release:version --verbose --release-type <RELEASE_TYPE> --pre-id <PRE_ID>`
7. To see a list of changes (for your own to-do list), run `yarn release:generate-pr-description --current-version <CURRENT_VERSION> --next-version <NEXT_VERSION_FROM_PREVIOUS_STEP> --verbose`
8. Write changelogs: `yarn release:write-changelog <NEXT_VERSION_FROM_PREVIOUS_STEP> --verbose`
9. `git add .`.
10. Commit changes: `git commit -m "Bump version from <CURRENT_VERSION> to <NEXT_VERSION_FROM_PREVIOUS_STEP> MANUALLY"`
11. Merge changes to the release branch:
1. `git checkout <"latest-release" | "next-release">`
2. `git pull`
3. `git merge <PREVIOUS_BRANCH>`
4. `git push origin`
12. (If automatic publishing is still working, it should kick in now and the rest of the steps can be skipped)
13. `cd ..`
14. Publish to the registry: `YARN_NPM_AUTH_TOKEN=<NPM_TOKEN> yarn release:publish --tag <"next" OR "latest"> --verbose`
15. (If patch release) `yarn release:label-patches`
16. Manually create a GitHub Release with a tag that is the new version and the target being `latest-release` or `next-release`.
17. Merge to core branch:
1. `git checkout <"next"|"main">`
2. `git pull`
3. `git merge <"next-release"|"latest-release">`
4. `git push origin`
18. (If patch release) Sync `CHANGELOG.md` to `next` with:
1. `git checkout next`
2. `git pull`
3. `git checkout origin/main ./CHANGELOG.md`
4. `git add ./CHANGELOG.md`
5. `git commit -m "Update CHANGELOG.md for v<NEXT_VERSION>"`
6. `git push origin`
19. (If non-patch release) Sync `versions/next.json` from `next` to `main`
1. `git checkout main`
2. `git pull`
3. `git checkout origin/next ./docs/versions/next.json`
4. `git add ./docs/versions/next.json`
5. `git commit -m "Update versions/next.json for v<NEXT_VERSION_FROM_PREVIOUS_STEP>"`
6. `git push origin main`
## Canary Releases
It's possible to release any pull request as a canary release multiple times during development. This is an effective way to try out changes in standalone projects without linking projects together via package managers.
To create a canary release, a core team member (or anyone else with administrator privileges) must manually trigger the canary release workflow.
**Before creating a canary release from contributors, the core team member must ensure that the code being released is not malicious.**
Creating a canary release can either be done via GitHub's UI or the [CLI](https://cli.github.com/):
### With GitHub UI
1. Open the workflow UI at https://github.com/storybookjs/storybook/actions/workflows/canary-release-pr.yml
2. On the top right corner, click "Run workflow"
3. For "branch", **always select `next`**, regardless of which branch your pull request is on
4. For the pull request number, input the number for the pull request **without a leading #**
### With the CLI
The following command will trigger a workflow run - replace `<PR_NUMBER>` with the actual pull request number:
```bash
gh workflow run --repo storybookjs/storybook canary-release-pr.yml --field pr=<PR_NUMBER>
```
When the release succeeds, it will update the "Canary release" section of the pull request with information about the release and how to use it (see example [here](https://github.com/storybookjs/storybook/pull/23508)). If it fails, it will create a comment on the pull request, tagging the triggering actor to let them know that it failed (see example [here](https://github.com/storybookjs/storybook/pull/23508#issuecomment-1642850467)).
The canary release will have the following version format: `0.0.0-pr-<PR_NUMBER>-sha-<COMMIT_SHA>`, e.g., `0.0.0-pr-23508-5ec8c1c3`. Using v0.0.0 ensures that no user will accidentally get the canary release when using a canary with prereleases, eg. `^7.2.0-alpha.0`
> ** Note **
> All canary releases are released under the same "canary" dist tag. This means you'll technically be able to install it with `npm install @storybook/cli@canary`. However, this doesn't make sense, as releases from subsequent pull requests will overwrite that tag quickly. Therefore you should always install the specific version string, e.g., `npm install @storybook/[email protected]`.
<details>
<summary>Isn't there a simpler/smarter way to do this?</summary>
The simple approach would be to release canaries for all pull requests automatically; however, this would be insecure as any contributor with Write privileges to the repository (200+ users) could create a malicious pull request that alters the release script to release a malicious release (e.g., release a patch version that adds a crypto miner).
To alleviate this, we only allow the "Release" GitHub environment that contains the npm token to be accessible from workflows running on the protected branches (`next`, `main`, etc.).
You could also be tempted to require approval from admins before running the workflows. However, this would spam the core team with GitHub notifications for workflow runs seeking approval - even when a core team member triggered the workflow. Therefore we are doing it the other way around, requiring contributors and maintainers to ask for a canary release to be created explicitly.
Instead of triggering the workflow manually, you could also do something smart, like trigger it when there's a specific label on the pull request or when someone writes a specific comment on the pull request. However, this would create a lot of unnecessary workflow runs because there isn't a way to filter workflow runs based on labels or comment content. The only way to achieve this would be to trigger the workflow on every comment/labeling, then cancel it if it didn't contain the expected content, which is inefficient.
</details>
## Versioning Scenarios
There are multiple types of releases that use the same principles, but are done somewhat differently.
### Prereleases - `7.1.0-alpha.12` -> `7.1.0-alpha.13`
This is the default strategy for Non-patch releases, there's nothing special needed to trigger this scenario.
### Prerelease promotions - `7.1.0-alpha.13` -> `7.1.0-beta.0`
To promote a prerelease to a new prerelease ID, during the [Re-trigger the Workflow](#4-re-trigger-the-workflow) step, choose:
- Release type: Prerelease
- Prerelease ID: The ID to promote to. For example, for alpha to beta, write "beta".
### Minor/major releases - `7.1.0-rc.2` -> `7.1.0` or `8.0.0-rc.3` -> `8.0.0`
To promote a prerelease to a stable reelase, during the [Re-trigger the Workflow](#4-re-trigger-the-workflow) step, choose:
- Release type: Patch, Minor or Major
- Prerelease ID: Leave empty
This scenario is special as it will target `latest-release` instead of `next-release`, and thus merge into `main` when done, and not `next`. So it goes `next` -> `version-non-patch-from-<CURRENT-VERSION-ON_NEXT>` -> `latest-release` -> `main`.
### First prerelease of new major/minor - `7.1.0` -> `7.2.0-alpha.0` or `8.0.0-alpha.0`
This is the first prerelease after a stable major/minor has been released. The default versioning strategy for prereleases won't work here, because it will do `7.1.0` -> `7.1.1-0`. You need to use the workflow inputs to bump the major/minor correctly:
- Release type: Premajor for `8.0.0-alpha.0` or Preminor for `7.2.0-alpha.0`
- Prerelease ID: "alpha"
### Patch releases to stable - subset of `7.1.0-alpha.13` -> `7.0.14`
This is the default patch release scenario, which cherry picks patches to `main`.
### Patch releases to earlier versions - subset of `7.1.0-alpha.13` -> `6.5.14`
This happens so rarely on a case by case basis, so this is a completely manual process. The Releaser will find the git tag that matches the patch to bump, eg. `v6.5.14`, check it out, make the necessary changes and follow [the manual release process](#releasing-locally-in-case-of-emergency-🚨).
### Prerelease of upcoming patch release - `7.0.20` -> `7.0.21-alpha.0`
In some cases, a patch change is so big and complex that it makes sense to first release it as a prerelease of the current patch stable version to see if it works, before releasing it to stable shortly thereafter.
No process is defined for this.
### Merges to `main` without versioning
As described in more details in [the Patch Releases section](#patch-releases), there are scenarios where you want to patch [unreleasable](#which-changes-are-considered-releasable-and-what-does-it-mean) content back to `main` without bumping versions or publishing a new release. This happens automatically as long as all the unpicked patch pull requests have unreleasable labels. In that case the prepared patch pull request will change form slightly, to just cherry-picking the patches without bumping the versions.
## FAQ
### When should I use the "patch:yes" label?
Not all pull requests need to be patched back to the stable release, which is why only those with the **"patch:yes"** label gets that treatment. But how do you decide whether or not a give pull requests should have that label?
First of all, patches are only for important and time-sensitive fixes, and not minor improvements or completely new features. A pull request that introduces a new feature shouldn't be patched back to the stable release.
Second, PRs that changes the code in a big architectural way should ideally not be patched back either, because that makes merge conflicts more likely in the future.
When in doubt ask the core team for their input.
### How do I make changes to the release tooling/process?
The whole process is based on [GitHub Action workflows](../.github/workflows/) and [scripts](../scripts/release/), so you can modify them if you know what you're doing.
The short answer to "how", is to make changes as a regular pull request that is also patched back to `main`.
<details>
<summary>There's a longer answer too, but it's pretty confusing</summary>
The scripts run from either `main` or `next`, so if you're changing a release script, you must patch it back to `main` for it to have an effect on patch releases. If you need the change to take effect immediately, you must manually cherry pick it to `main`.
For workflow file changes, they usually run from `next`, but patching them back is recommended for consistency. The "publish" workflow runs from `latest-release` and `next-release`, so you should always patch changes back for _that_. 🙃
</details>
### Why do I need to re-trigger workflows to update the changelog?
Changes to pull requests' titles, labels or even reverts won't be reflected in the release pull request. This is because the workflow only triggers on pushes to `next`, not when pull request meta data is changed.
Therefore, if you've made any changes to pull requests, you must re-trigger the workflow manually to regenerate the changelog and the version bump. You could also make the changes to the changelog manually, but it means that the pull requests and their title/labels are no longer the single source of truth.
### Which combination of inputs creates the version bump I need?
Each versioning scenario including how to trigger it with inputs is described in [Versioning Scenarios](#versioning-scenarios). You can also see [the tests for the versioning script](https://github.com/storybookjs/storybook/blob/next/scripts/release/__tests__/version.test.ts#L137-L161) to determine which inputs create which outputs.
### Which changes are considered "releasable", and what does it mean?
A specific set of labels define which kind of change a pull request is, and whether it is a "releasable" change or not. Releasable changes will appear in the changelog and will trigger version bumps, while unreleasable changes will not.
The exact list of labels and their type is written [here](https://github.com/storybookjs/storybook/blob/next/scripts/release/utils/get-changes.ts#L9-L21). Currently, releasable labels are:
- BREAKING CHANGE
- Feature request
- Bug
- Maintenance
- Dependencies
And unreleasable labels are:
- Documentation
- Build
If a pull request does not have any of the above labels at the time of release, it is considered an unreleasable change. Unreleasable changes are changes that do not affect the user through releases. Documentation-only changes are unreleasable, because they are not part of packages and do not change behavior. Similarly, "build" changes are only internal-facing and do not change behavior. This could be tests, CI, etc.
### Why are no release PRs being prepared?
This is most likely because `next` only contains [unreleasable changes](#which-changes-are-considered-releasable-and-what-does-it-mean), which causes the preparation workflow to cancel itself. That's because it doesn't make sense to prepare a new release if all the changes are unreleasable, as that wouldn't bump the version nor write a new changelog entry, so "releasing" it would just merge it back to `next` without any differences.
You can always see the workflows and if they have been cancelled [here for non-patch releases](https://github.com/storybookjs/storybook/actions/workflows/prepare-non-patch-release.yml) and [here for patch releases](https://github.com/storybookjs/storybook/actions/workflows/prepare-patch-release.yml).
### Why do we need separate release branches?
A simpler branching approach would be to merge the versioning branches back to `main` or `next` instead of `latest-release` or `next-release`, and then trigger the publishing directly on that branch. That is what tools like [Changesets](https://github.com/changesets/changesets) do.
The problem with that is you could end up publishing changes that were not part of the prepared pull request, and thus not part of QA nor the changelog.
For example, if the Releaser is creating a new release with the frozen branch and another team member merges a new pull request - "some-simultaneous-bugfix - to `next` _during_ the QA steps:
```mermaid
%%{init: { 'gitGraph': { 'mainBranchName': 'next' } } }%%
gitGraph
commit type: HIGHLIGHT
branch new-feature
commit
commit
checkout next
merge new-feature type: HIGHLIGHT
branch some-simultaneous-bugfix
commit
checkout next
branch version-non-patch-from-7.1.0-alpha.28
commit id
checkout next
merge some-simultaneous-bugfix type: HIGHLIGHT id: "whoops!"
merge version-non-patch-from-7.1.0-alpha.28 tag: "v7.1.0-alpha.29"
```
When publishing at the last commit with tag `v7.1.0-alpha.29`, it will publish whatever the content is at that point (all the square dots), which includes the "whoops!" commit from merging the bugfix. But the bugfix was never part of the release pull request because it got prepared before the bugfix was merged in.
If we instead publish from `next-release` and then merge to `next`, the bugfix won't be part of the current release, but the next one:
```mermaid
%%{init: { 'gitGraph': { 'mainBranchName': 'next' } } }%%
gitGraph
commit type: HIGHLIGHT
branch next-release
branch new-feature
commit
commit
checkout next
merge new-feature type: HIGHLIGHT
branch some-simultanous-bugfix
commit
checkout next
branch version-non-patch-from-7.1.0-alpha.28
commit id: "write changelog"
checkout next
merge some-simultanous-bugfix id: "whoops!"
checkout next-release
merge version-non-patch-from-7.1.0-alpha.28
commit id: "bump versions" tag: "v7.1.0-alpha.29"
checkout next
merge next-release
branch version-non-patch-from-7.1.0-alpha.29
commit id: "write changelog again"
checkout next-release
merge version-non-patch-from-7.1.0-alpha.29
commit id: "bump versions again" tag: "v7.1.0-alpha.30"
checkout next
merge next-release
```
This is because the way that "unreleased" changes are found is to list all the commits that are part of the current history of `HEAD`, _except_ for the commits that are part of the history of the latest version tag. And since the bugfix is not part of the history of the previous version, it will be included.
|
CONTRIBUTING/RELEASING.md
| 0 |
https://github.com/storybookjs/storybook/commit/39e6fd82c4a39766bdfc66f4b67021b57339a58f
|
[
0.00017826465773396194,
0.0001719307474559173,
0.00016030596452765167,
0.00017273948469664901,
0.000004077853191120084
] |
{
"id": 1,
"code_window": [
" <EmptyBlock>\n",
" {error} \n",
" <Link href=\"http://storybook.js.org/docs/\" target=\"_blank\" withArrow>\n",
" Read the docs\n",
" </Link>\n",
" </EmptyBlock>\n",
" );\n",
" }\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <DocumentIcon /> Read the docs\n"
],
"file_path": "code/ui/blocks/src/components/ArgsTable/ArgsTable.tsx",
"type": "replace",
"edit_start_line_idx": 325
}
|
import type { FC } from 'react';
import React from 'react';
import pickBy from 'lodash/pickBy.js';
import { styled } from '@storybook/theming';
import { transparentize } from 'polished';
import { includeConditionalArg } from '@storybook/csf';
import { once } from '@storybook/client-logger';
import { IconButton, ResetWrapper, Link } from '@storybook/components';
import { UndoIcon } from '@storybook/icons';
import { ArgRow } from './ArgRow';
import { SectionRow } from './SectionRow';
import type { ArgType, ArgTypes, Args, Globals } from './types';
import { EmptyBlock } from '..';
import { Skeleton } from './Skeleton';
import { Empty } from './Empty';
export const TableWrapper = styled.table<{
compact?: boolean;
inAddonPanel?: boolean;
isLoading?: boolean;
}>(({ theme, compact, inAddonPanel }) => ({
'&&': {
// Resets for cascading/system styles
borderSpacing: 0,
color: theme.color.defaultText,
'td, th': {
padding: 0,
border: 'none',
verticalAlign: 'top',
textOverflow: 'ellipsis',
},
// End Resets
fontSize: theme.typography.size.s2 - 1,
lineHeight: '20px',
textAlign: 'left',
width: '100%',
// Margin collapse
marginTop: inAddonPanel ? 0 : 25,
marginBottom: inAddonPanel ? 0 : 40,
'thead th:first-of-type, td:first-of-type': {
// intentionally specify thead here
width: '25%',
},
'th:first-of-type, td:first-of-type': {
paddingLeft: 20,
},
'th:nth-of-type(2), td:nth-of-type(2)': {
...(compact
? null
: {
// Description column
width: '35%',
}),
},
'td:nth-of-type(3)': {
...(compact
? null
: {
// Defaults column
width: '15%',
}),
},
'th:last-of-type, td:last-of-type': {
paddingRight: 20,
...(compact
? null
: {
// Controls column
width: '25%',
}),
},
th: {
color:
theme.base === 'light'
? transparentize(0.25, theme.color.defaultText)
: transparentize(0.45, theme.color.defaultText),
paddingTop: 10,
paddingBottom: 10,
paddingLeft: 15,
paddingRight: 15,
},
td: {
paddingTop: '10px',
paddingBottom: '10px',
'&:not(:first-of-type)': {
paddingLeft: 15,
paddingRight: 15,
},
'&:last-of-type': {
paddingRight: 20,
},
},
// Makes border alignment consistent w/other DocBlocks
marginLeft: inAddonPanel ? 0 : 1,
marginRight: inAddonPanel ? 0 : 1,
tbody: {
// Safari doesn't love shadows on tbody so we need to use a shadow filter. In order to do this,
// the table cells all need to be solid so they have a background color applied.
// I wasn't sure what kinds of content go in these tables so I was extra specific with selectors
// to avoid unexpected surprises.
...(inAddonPanel
? null
: {
filter:
theme.base === 'light'
? `drop-shadow(0px 1px 3px rgba(0, 0, 0, 0.10))`
: `drop-shadow(0px 1px 3px rgba(0, 0, 0, 0.20))`,
}),
'> tr > *': {
// For filter to work properly, the table cells all need to be opaque.
background: theme.background.content,
borderTop: `1px solid ${theme.appBorderColor}`,
},
...(inAddonPanel
? null
: {
// This works and I don't know why. :)
'> tr:first-of-type > *': {
borderBlockStart: `1px solid ${theme.appBorderColor}`,
},
'> tr:last-of-type > *': {
borderBlockEnd: `1px solid ${theme.appBorderColor}`,
},
'> tr > *:first-of-type': {
borderInlineStart: `1px solid ${theme.appBorderColor}`,
},
'> tr > *:last-of-type': {
borderInlineEnd: `1px solid ${theme.appBorderColor}`,
},
// Thank you, Safari, for making me write code like this.
'> tr:first-of-type > td:first-of-type': {
borderTopLeftRadius: theme.appBorderRadius,
},
'> tr:first-of-type > td:last-of-type': {
borderTopRightRadius: theme.appBorderRadius,
},
'> tr:last-of-type > td:first-of-type': {
borderBottomLeftRadius: theme.appBorderRadius,
},
'> tr:last-of-type > td:last-of-type': {
borderBottomRightRadius: theme.appBorderRadius,
},
}),
},
// End awesome table styling
},
}));
const StyledIconButton = styled(IconButton as any)(({ theme }) => ({
color: theme.barTextColor,
margin: '-4px -12px -4px 0',
}));
const ControlHeadingWrapper = styled.span({
display: 'flex',
justifyContent: 'space-between',
});
export enum ArgsTableError {
NO_COMPONENT = 'No component found.',
ARGS_UNSUPPORTED = 'Args unsupported. See Args documentation for your framework.',
}
export type SortType = 'alpha' | 'requiredFirst' | 'none';
type SortFn = (a: ArgType, b: ArgType) => number;
const sortFns: Record<SortType, SortFn | null> = {
alpha: (a: ArgType, b: ArgType) => a.name.localeCompare(b.name),
requiredFirst: (a: ArgType, b: ArgType) =>
Number(!!b.type?.required) - Number(!!a.type?.required) || a.name.localeCompare(b.name),
none: undefined,
};
export interface ArgsTableOptionProps {
children?: React.ReactNode;
updateArgs?: (args: Args) => void;
resetArgs?: (argNames?: string[]) => void;
compact?: boolean;
inAddonPanel?: boolean;
initialExpandedArgs?: boolean;
isLoading?: boolean;
sort?: SortType;
}
interface ArgsTableDataProps {
rows: ArgTypes;
args?: Args;
globals?: Globals;
}
interface ArgsTableErrorProps {
error: ArgsTableError;
}
export interface ArgsTableLoadingProps {
isLoading: boolean;
}
export type ArgsTableProps = ArgsTableOptionProps &
(ArgsTableDataProps | ArgsTableErrorProps | ArgsTableLoadingProps);
type Rows = ArgType[];
type Subsection = Rows;
type Section = {
ungrouped: Rows;
subsections: Record<string, Subsection>;
};
type Sections = {
ungrouped: Rows;
ungroupedSubsections: Record<string, Subsection>;
sections: Record<string, Section>;
};
const groupRows = (rows: ArgType, sort: SortType) => {
const sections: Sections = { ungrouped: [], ungroupedSubsections: {}, sections: {} };
if (!rows) return sections;
Object.entries(rows).forEach(([key, row]) => {
const { category, subcategory } = row?.table || {};
if (category) {
const section = sections.sections[category] || { ungrouped: [], subsections: {} };
if (!subcategory) {
section.ungrouped.push({ key, ...row });
} else {
const subsection = section.subsections[subcategory] || [];
subsection.push({ key, ...row });
section.subsections[subcategory] = subsection;
}
sections.sections[category] = section;
} else if (subcategory) {
const subsection = sections.ungroupedSubsections[subcategory] || [];
subsection.push({ key, ...row });
sections.ungroupedSubsections[subcategory] = subsection;
} else {
sections.ungrouped.push({ key, ...row });
}
});
// apply sort
const sortFn = sortFns[sort];
const sortSubsection = (record: Record<string, Subsection>) => {
if (!sortFn) return record;
return Object.keys(record).reduce<Record<string, Subsection>>(
(acc, cur) => ({
...acc,
[cur]: record[cur].sort(sortFn),
}),
{}
);
};
const sorted = {
ungrouped: sections.ungrouped.sort(sortFn),
ungroupedSubsections: sortSubsection(sections.ungroupedSubsections),
sections: Object.keys(sections.sections).reduce<Record<string, Section>>(
(acc, cur) => ({
...acc,
[cur]: {
ungrouped: sections.sections[cur].ungrouped.sort(sortFn),
subsections: sortSubsection(sections.sections[cur].subsections),
},
}),
{}
),
};
return sorted;
};
/**
* Wrap CSF's `includeConditionalArg` in a try catch so that invalid
* conditionals don't break the entire UI. We can safely swallow the
* error because `includeConditionalArg` is also called in the preview
* in `prepareStory`, and that exception will be bubbled up into the
* UI in a red screen. Nevertheless, we log the error here just in case.
*/
const safeIncludeConditionalArg = (row: ArgType, args: Args, globals: Globals) => {
try {
return includeConditionalArg(row, args, globals);
} catch (err) {
once.warn(err.message);
return false;
}
};
/**
* Display the props for a component as a props table. Each row is a collection of
* ArgDefs, usually derived from docgen info for the component.
*/
export const ArgsTable: FC<ArgsTableProps> = (props) => {
const {
updateArgs,
resetArgs,
compact,
inAddonPanel,
initialExpandedArgs,
sort = 'none',
isLoading,
} = props;
if ('error' in props) {
const { error } = props;
return (
<EmptyBlock>
{error}
<Link href="http://storybook.js.org/docs/" target="_blank" withArrow>
Read the docs
</Link>
</EmptyBlock>
);
}
// If the story is loading, show a skeleton
// This happen when you load the manager and the story is not yet loaded
if (isLoading) return <Skeleton />;
const { rows, args, globals } = 'rows' in props && props;
const groups = groupRows(
pickBy(
rows,
(row) => !row?.table?.disable && safeIncludeConditionalArg(row, args || {}, globals || {})
),
sort
);
// If there are no controls, show the empty state
const hasNoUngrouped = groups.ungrouped.length === 0;
const hasNoSections = Object.entries(groups.sections).length === 0;
const hasNoUngroupedSubsections = Object.entries(groups.ungroupedSubsections).length === 0;
if (hasNoUngrouped && hasNoSections && hasNoUngroupedSubsections)
return <Empty inAddonPanel={inAddonPanel} />;
let colSpan = 1;
if (updateArgs) colSpan += 1;
if (!compact) colSpan += 2;
const expandable = Object.keys(groups.sections).length > 0;
const common = { updateArgs, compact, inAddonPanel, initialExpandedArgs };
return (
<ResetWrapper>
<TableWrapper {...{ compact, inAddonPanel }} className="docblock-argstable sb-unstyled">
<thead className="docblock-argstable-head">
<tr>
<th>
<span>Name</span>
</th>
{compact ? null : (
<th>
<span>Description</span>
</th>
)}
{compact ? null : (
<th>
<span>Default</span>
</th>
)}
{updateArgs ? (
<th>
<ControlHeadingWrapper>
Control{' '}
{!isLoading && resetArgs && (
<StyledIconButton onClick={() => resetArgs()} title="Reset controls">
<UndoIcon aria-hidden />
</StyledIconButton>
)}
</ControlHeadingWrapper>
</th>
) : null}
</tr>
</thead>
<tbody className="docblock-argstable-body">
{groups.ungrouped.map((row) => (
<ArgRow key={row.key} row={row} arg={args && args[row.key]} {...common} />
))}
{Object.entries(groups.ungroupedSubsections).map(([subcategory, subsection]) => (
<SectionRow key={subcategory} label={subcategory} level="subsection" colSpan={colSpan}>
{subsection.map((row) => (
<ArgRow
key={row.key}
row={row}
arg={args && args[row.key]}
expandable={expandable}
{...common}
/>
))}
</SectionRow>
))}
{Object.entries(groups.sections).map(([category, section]) => (
<SectionRow key={category} label={category} level="section" colSpan={colSpan}>
{section.ungrouped.map((row) => (
<ArgRow key={row.key} row={row} arg={args && args[row.key]} {...common} />
))}
{Object.entries(section.subsections).map(([subcategory, subsection]) => (
<SectionRow
key={subcategory}
label={subcategory}
level="subsection"
colSpan={colSpan}
>
{subsection.map((row) => (
<ArgRow
key={row.key}
row={row}
arg={args && args[row.key]}
expandable={expandable}
{...common}
/>
))}
</SectionRow>
))}
</SectionRow>
))}
</tbody>
</TableWrapper>
</ResetWrapper>
);
};
|
code/ui/blocks/src/components/ArgsTable/ArgsTable.tsx
| 1 |
https://github.com/storybookjs/storybook/commit/39e6fd82c4a39766bdfc66f4b67021b57339a58f
|
[
0.9924659729003906,
0.022873854264616966,
0.00016388796211685985,
0.00017303411732427776,
0.1478639543056488
] |
{
"id": 1,
"code_window": [
" <EmptyBlock>\n",
" {error} \n",
" <Link href=\"http://storybook.js.org/docs/\" target=\"_blank\" withArrow>\n",
" Read the docs\n",
" </Link>\n",
" </EmptyBlock>\n",
" );\n",
" }\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <DocumentIcon /> Read the docs\n"
],
"file_path": "code/ui/blocks/src/components/ArgsTable/ArgsTable.tsx",
"type": "replace",
"edit_start_line_idx": 325
}
|
---
title: 'Compiler support'
---
Javascript compilers are essential in optimizing and transforming code, enhancing performance, and ensuring compatibility across different environments. Storybook provides support for the leading compilers, ensuring lightning-fast build time and execution with [SWC](https://swc.rs/) or leveraging [Babel](https://babeljs.io/) with its extensive ecosystem of plugins and presets to allow you to use the latest features of the ecosystem with minimal configuration required for your Webpack-based project.
## SWC
SWC is a fast, highly extensible tool for compiling and bundling modern JavaScript applications. Powered by [Rust](https://www.rust-lang.org/), it improves performance and reduces build times. Storybook includes a built-in integration with SWC, allowing zero-configuration setup and built-in types for APIs. If you've initialized Storybook in a Webpack-based project with any of the supported [frameworks](./frameworks.md), except Angular, it will automatically use SWC as its default, providing you with faster loading time. However, if you're upgrading from a previous version of Storybook, you may need to opt-in to use SWC by adjusting your Storybook configuration file (i.e., `.storybook/main.js|ts`) as follows:
<!-- prettier-ignore-start -->
<CodeSnippets
paths={[
'common/main-config-framework-options-builder-use-swc.js.mdx',
'common/main-config-framework-options-builder-use-swc.ts.mdx',
]}
/>
<!-- prettier-ignore-end -->
<Callout variant="info">
Support for the SWC builder is currently experimental for Next.js projects, and it's not enabled by default. It requires you to opt in to use it. For more information on configuring SWC with the supported frameworks, see the [SWC API](../api/main-config-swc.md) documentation.
</Callout>
## Babel
Babel is a widely adopted JavaScript compiler providing a modular architecture and extensive plugin system to support a wide range of use cases, enabling access to the cutting-edge features of the tooling ecosystem. Storybook provides a seamless integration with Babel, allowing you to share a standard setup between your project and Storybook without any additional configuration.
<Callout variant="info">
If you're not using Storybook 7, please reference the [previous documentation](../../../release-6-5/docs/configure/babel.md) for guidance on configuring your Babel setup.
</Callout>
### Configure
By default, Babel provides an opinionated [configuration](https://babeljs.io/docs/config-files) that works for most projects, relying on two distinct methods for configuring projects with the tool:
- **Project-wide configuration**: Babel will look for a `babel.config.js` or equivalent file in the root of your project and use it to configure your project's Babel setup.
- **File-relative configuration**: Babel will look for a `.babelrc.json` or equivalent file, introspecting the project structure until it finds a configuration file. This will allow you to configure Babel individually for multiple aspects of your project.
Storybook relies on an agnostic approach to configuring Babel, enabling you to provide the necessary configuration for your project, and it will use it. Based on the supported frameworks, builders, and addons, it may include minor adjustments to ensure compatibility with Storybook's features.
<Callout variant="info">
For custom project configurations such as monorepos, where you have multiple Storybook configurations, creating a `.babelrc.json` file in your project's current working directory may not be sufficient. In those cases, you can create a `babel.config.js` file to override Babel's configuration, and Storybook will automatically detect and use it. See the Babel [documentation](https://babeljs.io/docs/config-files) for more information.
</Callout>
### Working with Create React App
If you're working with a project that was initialized with [Create React App](https://create-react-app.dev/), Storybook will automatically detect and use the Babel configuration provided by the tool enabled via the `@storybook/preset-create-react-app` preset, allowing to use Storybook without any additional configuration.
## Troubleshooting
<IfRenderer renderer='react'>
### The SWC compiler doesn't work with React
If you have enabled the SWC builder option in a React-based project and you are not explicitly importing React in your `jsx|tsx` files, it can cause Storybook to fail to load. SWC does not automatically import the `jsx-runtime` module when using the SWC builder. To resolve this issue, you need to adjust your Storybook configuration file (i.e., `.storybook/main.js|ts`) and configure the `swc` option as follows:
<!-- prettier-ignore-start -->
<CodeSnippets
paths={[
'common/main-config-swc-jsx-transform.js.mdx',
'common/main-config-swc-jsx-transform.ts.mdx',
]}
/>
<!-- prettier-ignore-end -->
</IfRenderer>
### Babel configuration not working
Out of the box, Storybook can detect and apply any Babel configuration you provided in your project. However, if you're running into a situation where your configuration is not being used, you configure the [`BABEL_SHOW_CONFIG_FOR`](https://babeljs.io/docs/configuration#print-effective-configs) environment variable and set it to the file you want to inspect. For example:
```sh
BABEL_SHOW_CONFIG_FOR=.storybook/preview.js yarn storybook
```
When the command runs, it will output the Babel configuration applied to the file you specified despite showing a transpilation error in the console and preventing Storybook from loading. This is a known issue with Babel unrelated to Storybook, which you address by turning off the environment variable after inspecting the configuration and restarting Storybook.
|
docs/configure/compilers.md
| 0 |
https://github.com/storybookjs/storybook/commit/39e6fd82c4a39766bdfc66f4b67021b57339a58f
|
[
0.00017580893472768366,
0.0001663763978285715,
0.00016157969366759062,
0.00016347717610187829,
0.000004672592694987543
] |
{
"id": 1,
"code_window": [
" <EmptyBlock>\n",
" {error} \n",
" <Link href=\"http://storybook.js.org/docs/\" target=\"_blank\" withArrow>\n",
" Read the docs\n",
" </Link>\n",
" </EmptyBlock>\n",
" );\n",
" }\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <DocumentIcon /> Read the docs\n"
],
"file_path": "code/ui/blocks/src/components/ArgsTable/ArgsTable.tsx",
"type": "replace",
"edit_start_line_idx": 325
}
|
import { global as globalThis } from '@storybook/global';
import type { PartialStoryFn, StoryContext } from '@storybook/types';
export default {
component: globalThis.Components.Pre,
decorators: [
(storyFn: PartialStoryFn, context: StoryContext) =>
storyFn({ args: { object: { ...context.args } } }),
],
args: {
helloWorld: 1,
helloPlanet: 1,
byeWorld: 1,
},
};
export const IncludeList = {
parameters: {
controls: {
include: ['helloWorld'],
},
},
};
export const IncludeRegex = {
parameters: {
controls: {
include: /hello*/,
},
},
};
export const ExcludeList = {
parameters: {
controls: {
exclude: ['helloPlanet', 'helloWorld'],
},
},
};
export const ExcludeRegex = {
parameters: {
controls: {
exclude: /hello*/,
},
},
};
|
code/addons/controls/template/stories/filters.stories.ts
| 0 |
https://github.com/storybookjs/storybook/commit/39e6fd82c4a39766bdfc66f4b67021b57339a58f
|
[
0.00017558629042468965,
0.000173288892256096,
0.00016710054478608072,
0.00017466038116253912,
0.0000031492493235418806
] |
{
"id": 1,
"code_window": [
" <EmptyBlock>\n",
" {error} \n",
" <Link href=\"http://storybook.js.org/docs/\" target=\"_blank\" withArrow>\n",
" Read the docs\n",
" </Link>\n",
" </EmptyBlock>\n",
" );\n",
" }\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <DocumentIcon /> Read the docs\n"
],
"file_path": "code/ui/blocks/src/components/ArgsTable/ArgsTable.tsx",
"type": "replace",
"edit_start_line_idx": 325
}
|
---
title: 'Test coverage'
---
<YouTubeCallout id="wEa6W8uUGSA" title="These tests use NO CODE | component testing in Storybook" />
Test coverage is the practice of measuring whether existing tests fully cover your code. That means surfacing areas which aren't currently being tested, such as: conditions, logic branches, functions and variables.
Coverage tests examine the instrumented code against a set of industry-accepted best practices. They act as the last line of QA to improve the quality of your test suite.
<video autoPlay muted playsInline loop>
<source
src="component-test-coverage-whitebg.mp4"
type="video/mp4"
/>
</video>
## Code instrumentation with the coverage addon
Storybook provides an official [test coverage addon](https://storybook.js.org/addons/@storybook/addon-coverage). Powered by [Istanbul](https://istanbul.js.org/), which allows out-of-the-box code instrumentation for the most commonly used frameworks and builders in the JavaScript ecosystem.
### Set up the coverage addon
Engineered to work alongside modern testing tools (e.g., [Playwright](https://playwright.dev/)), the coverage addon automatically instruments your code and generates code coverage data. For an optimal experience, we recommend using the [test runner](./test-runner.md) alongside the coverage addon to run your tests.
Run the following command to install the addon.
<!-- prettier-ignore-start -->
<CodeSnippets
paths={[
'common/storybook-coverage-addon-install.yarn.js.mdx',
'common/storybook-coverage-addon-install.npm.js.mdx',
'common/storybook-coverage-addon-install.pnpm.js.mdx',
]}
/>
<!-- prettier-ignore-end -->
Update your Storybook configuration (in `.storybook/main.js|ts`) to include the coverage addon.
<!-- prettier-ignore-start -->
<CodeSnippets
paths={[
'common/storybook-coverage-addon-registration.js.mdx',
'common/storybook-coverage-addon-registration.ts.mdx',
]}
/>
<!-- prettier-ignore-end -->
Start your Storybook with:
<!-- prettier-ignore-start -->
<CodeSnippets
paths={[
'common/storybook-run-dev.yarn.js.mdx',
'common/storybook-run-dev.npm.js.mdx',
'common/storybook-run-dev.pnpm.js.mdx',
]}
/>
<!-- prettier-ignore-end -->
Finally, open a new terminal window and run the test-runner with:
<!-- prettier-ignore-start -->
<CodeSnippets
paths={[
'common/test-runner-coverage.yarn.js.mdx',
'common/test-runner-coverage.npm.js.mdx',
'common/test-runner-coverage.pnpm.js.mdx',
]}
/>
<!-- prettier-ignore-end -->

### Configure
By default, the [`@storybook/addon-coverage`](https://storybook.js.org/addons/@storybook/addon-coverage) offers zero-config support for Storybook and instruments your code via [`istanbul-lib-instrument`](https://www.npmjs.com/package/istanbul-lib-instrument) for [Webpack](https://webpack.js.org/), or [`vite-plugin-istanbul`](https://github.com/iFaxity/vite-plugin-istanbul) for [Vite](https://vitejs.dev/). However, you can extend your Storybook configuration file (i.e., `.storybook/main.js|ts`) and provide additional options to the addon. Listed below are the available options and examples of how to use them.
<!-- prettier-ignore-start -->
<CodeSnippets
paths={[
'common/storybook-coverage-addon-config-options.js.mdx',
'common/storybook-coverage-addon-config-options.ts.mdx',
]}
/>
<!-- prettier-ignore-end -->
**The available options if your project uses Webpack5 are as follows:**
| Option name | Description | Type | Default |
| ---------------------- | -------------------------------------------------------------------------------------------------------------- | --------------- | -------------------------------------------------------------------------------------------- |
| `cwd` | Set the working directory | `String` | `process.cwd()` |
| `nycrcPath` | Path to specific nyc config to use instead of automatically searching for a nycconfig. | `string` | - |
| `include` | Glob pattern to include files. It has precedence over the include definition from your nyc config | `Array<String>` | - |
| `exclude` | Glob pattern to exclude files. It has precedence over the exclude definition from your nyc config | `Array<String>` | `defaultExclude` in https://github.com/storybookjs/addon-coverage/blob/main/src/constants.ts |
| `extension` | List of supported extensions. It has precedence over the extension definition from your nyc config | `Array<String>` | `['.js', '.cjs', '.mjs', '.ts', '.tsx', '.jsx', '.vue', '.svelte]` |
| `coverageVariable` | The global variable name that Istanbul will use to store coverage results. | `string` | - |
| `preserveComments` | Indicates whether comments in the code should be preserved during the instrumentation process. | `boolean` | `true` |
| `compact` | Controls whether the output of instrumented code is compacted. Useful for debugging when set to `false`. | `boolean` | `false` |
| `esModules` | Determines whether the code to be instrumented uses ES Module syntax. | `boolean` | `true` |
| `autoWrap` | When set to `true`, wraps program code in a function to enable top-level return statements. | `boolean` | `true` |
| `produceSourceMap` | If `true`, instructs Istanbul to produce a source map for the instrumented code. | `boolean` | `true` |
| `sourceMapUrlCallback` | A callback function that gets invoked with the filename and the source map URL when a source map is generated. | `function` | - |
| `debug` | Enables the debug mode, providing additional logging information during the instrumentation process. | `boolean` | - |
> **Note:**
> If you're using TypeScript, you can import the type for the options like so:
>
> ```ts
> import type { AddonOptionsWebpack } from '@storybook/addon-coverage';
> ```
**The available options if your project uses Vite are as follows:**
| Option name | Description | Type | Default |
| ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------- | -------------------------------------------------------------------------------- |
| `cwd` | Set the working directory | `String` | `process.cwd()` |
| `include` | See [here](https://github.com/istanbuljs/nyc#selecting-files-for-coverage) for more info | `Array<String>` or `string` | `['**']` |
| `exclude` | See [here](https://github.com/istanbuljs/nyc#selecting-files-for-coverage) for more info | `Array<String>` or `string` | [list](https://github.com/storybookjs/addon-coverage/blob/main/src/constants.ts) |
| `extension` | List of extensions that nyc should attempt to handle in addition to `.js` | `Array<String>` or `string` | `['.js', '.cjs', '.mjs', '.ts', '.tsx', '.jsx', '.vue', '.svelte]` |
| `requireEnv ` | Optional boolean to require the environment variable (defaults to VITE_COVERAGE) to equal true in order to instrument the code. Otherwise it will instrument even if env variable is not set. However if requireEnv is not set the instrumentation will stop if the environment variable is equal to false. | `boolean` | `-` |
| `cypress ` | Optional boolean to change the environment variable to CYPRESS_COVERAGE instead of VITE_COVERAGE. For ease of use with `@cypress/code-coverage` coverage | `boolean` | `-` |
| `checkProd ` | Optional boolean to enforce the plugin to skip instrumentation for production environments. Looks at Vite's isProduction key from the ResolvedConfig. | `boolean` | `-` |
| `forceBuildInstrument ` | Optional boolean to enforce the plugin to add instrumentation in build mode. | `boolean` | `false` |
| `nycrcPath ` | Path to specific nyc config to use instead of automatically searching for a nycconfig. This parameter is just passed down to @istanbuljs/load-nyc-config. | `string` | `-` |
> **Note:**
> If you're using TypeScript, you can import the type for the options like so:
>
> ```ts
> import type { AddonOptionsVite } from '@storybook/addon-coverage';
> ```
## What about other coverage reporting tools?
Out of the box, code coverage tests work seamlessly with Storybook's test-runner and the [`@storybook/addon-coverage`](https://storybook.js.org/addons/@storybook/addon-coverage). However, that doesn't mean you can't use additional reporting tools (e.g., [Codecov](https://about.codecov.io/)). For instance, if you're working with [LCOV](https://wiki.documentfoundation.org/Development/Lcov), you can use the generated output (in `coverage/storybook/coverage-storybook.json`) and create your own report with:
<!-- prettier-ignore-start -->
<CodeSnippets
paths={[
'common/storybook-coverage-report-lcov.js.mdx',
]}
/>
<!-- prettier-ignore-end -->
---
## Troubleshooting
### Run test coverage in other frameworks
If you intend on running coverage tests in frameworks with special files like Vue or Svelte, you'll need to adjust your configuration and enable the required file extensions. For example, if you're using Vue, you'll need to add the following to your nyc configuration file (i.e., `.nycrc.json` or `nyc.config.js`):
<!-- prettier-ignore-start -->
<CodeSnippets
paths={[
'common/storybook-coverage-report-vue.json.mdx',
'common/storybook-coverage-report-vue.js.mdx',
]}
/>
<!-- prettier-ignore-end -->
### The coverage addon doesn't support optimized builds
If you generated a production build optimized for performance with the [`--test`](../sharing/publish-storybook.md#customizing-the-build-for-performance) flag, and you're using the coverage addon to run tests against your Storybook, you may run into a situation where the coverage addon doesn't instrument your code. This is due to how the flag works, as it removes addons that have an impact on performance (e.g., [`Docs`](../writing-docs/index.md), [coverage addon](https://storybook.js.org/addons/@storybook/addon-coverage)). To resolve this issue, you'll need to adjust your Storybook configuration file (i.e., `.storybook/main.js|ts`) and include the [`disabledAddons`](../api/main-config-build.md#testdisabledaddons) option to allow the addon to run tests at the expense of a slower build.
<!-- prettier-ignore-start -->
<CodeSnippets
paths={[
'common/storybook-coverage-addon-optimized-config.js.mdx',
'common/storybook-coverage-addon-optimized-config.ts.mdx',
]}
/>
<!-- prettier-ignore-end -->
### The coverage addon doesn't support instrumented code
As the [coverage addon](https://storybook.js.org/addons/@storybook/addon-coverage) is based on Webpack5 loaders and Vite plugins for code instrumentation, frameworks that don't rely upon these libraries (e.g., Angular configured with Webpack), will require additional configuration to enable code instrumentation. In that case, you can refer to the following [repository](https://github.com/yannbf/storybook-coverage-recipes) for more information.
#### Learn about other UI tests
- [Test runner](./test-runner.md) to automate test execution
- [Visual tests](./visual-testing.md) for appearance
- [Accessibility tests](./accessibility-testing.md) for accessibility
- [Interaction tests](./interaction-testing.md) for user behavior simulation
- Coverage tests for measuring code coverage
- [Snapshot tests](./snapshot-testing.md) for rendering errors and warnings
- [End-to-end tests](./stories-in-end-to-end-tests.md) for simulating real user scenarios
- [Unit tests](./stories-in-unit-tests.md) for functionality
|
docs/writing-tests/test-coverage.md
| 0 |
https://github.com/storybookjs/storybook/commit/39e6fd82c4a39766bdfc66f4b67021b57339a58f
|
[
0.00022181891836225986,
0.00017275528807658702,
0.0001619415415916592,
0.00016958400374278426,
0.000014151384675642475
] |
{
"id": 2,
"code_window": [
"import React, { useEffect, useState } from 'react';\n",
"import { styled } from '@storybook/theming';\n",
"import { Link } from '@storybook/components';\n",
"import { VideoIcon } from '@storybook/icons';\n",
"\n",
"interface EmptyProps {\n",
" inAddonPanel?: boolean;\n",
"}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { DocumentIcon, SupportIcon, VideoIcon } from '@storybook/icons';\n"
],
"file_path": "code/ui/blocks/src/components/ArgsTable/Empty.tsx",
"type": "replace",
"edit_start_line_idx": 4
}
|
import type { FC } from 'react';
import React, { useEffect, useState } from 'react';
import { styled } from '@storybook/theming';
import { Link } from '@storybook/components';
import { VideoIcon } from '@storybook/icons';
interface EmptyProps {
inAddonPanel?: boolean;
}
const Wrapper = styled.div<{ inAddonPanel?: boolean }>(({ inAddonPanel, theme }) => ({
height: inAddonPanel ? '100%' : 'auto',
display: 'flex',
border: inAddonPanel ? 'none' : `1px solid ${theme.appBorderColor}`,
borderRadius: inAddonPanel ? 0 : theme.appBorderRadius,
padding: inAddonPanel ? 0 : 40,
alignItems: 'center',
justifyContent: 'center',
flexDirection: 'column',
gap: 15,
background: theme.background.content,
boxShadow: 'rgba(0, 0, 0, 0.10) 0 1px 3px 0',
}));
const Content = styled.div({
display: 'flex',
flexDirection: 'column',
gap: 4,
maxWidth: 415,
});
const Title = styled.div(({ theme }) => ({
fontWeight: theme.typography.weight.bold,
fontSize: theme.typography.size.s2 - 1,
textAlign: 'center',
color: theme.textColor,
}));
const Description = styled.div(({ theme }) => ({
fontWeight: theme.typography.weight.regular,
fontSize: theme.typography.size.s2 - 1,
textAlign: 'center',
color: theme.textMutedColor,
}));
const Links = styled.div(({ theme }) => ({
display: 'flex',
fontSize: theme.typography.size.s2 - 1,
gap: 25,
}));
const Divider = styled.div(({ theme }) => ({
width: 1,
height: 16,
backgroundColor: theme.appBorderColor,
}));
export const Empty: FC<EmptyProps> = ({ inAddonPanel }) => {
const [isLoading, setIsLoading] = useState(true);
// We are adding a small delay to avoid flickering when the story is loading.
// It takes a bit of time for the controls to appear, so we don't want
// to show the empty state for a split second.
useEffect(() => {
const load = setTimeout(() => {
setIsLoading(false);
}, 100);
return () => clearTimeout(load);
}, []);
if (isLoading) return null;
return (
<Wrapper inAddonPanel={inAddonPanel}>
<Content>
<Title>
{inAddonPanel
? 'Interactive story playground'
: "Args table with interactive controls couldn't be auto-generated"}
</Title>
<Description>
Controls give you an easy to use interface to test your components. Set your story args
and you'll see controls appearing here automatically.
</Description>
</Content>
<Links>
{inAddonPanel && (
<>
<Link href="https://youtu.be/0gOfS6K0x0E" target="_blank" withArrow>
<VideoIcon /> Watch 5m video
</Link>
<Divider />
<Link
href="https://storybook.js.org/docs/react/essentials/controls"
target="_blank"
withArrow
>
Read docs
</Link>
</>
)}
{!inAddonPanel && (
<Link
href="https://storybook.js.org/docs/react/essentials/controls"
target="_blank"
withArrow
>
Learn how to set that up
</Link>
)}
</Links>
</Wrapper>
);
};
|
code/ui/blocks/src/components/ArgsTable/Empty.tsx
| 1 |
https://github.com/storybookjs/storybook/commit/39e6fd82c4a39766bdfc66f4b67021b57339a58f
|
[
0.9986750483512878,
0.2504827380180359,
0.00016799439617898315,
0.004061984829604626,
0.4273083209991455
] |
{
"id": 2,
"code_window": [
"import React, { useEffect, useState } from 'react';\n",
"import { styled } from '@storybook/theming';\n",
"import { Link } from '@storybook/components';\n",
"import { VideoIcon } from '@storybook/icons';\n",
"\n",
"interface EmptyProps {\n",
" inAddonPanel?: boolean;\n",
"}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { DocumentIcon, SupportIcon, VideoIcon } from '@storybook/icons';\n"
],
"file_path": "code/ui/blocks/src/components/ArgsTable/Empty.tsx",
"type": "replace",
"edit_start_line_idx": 4
}
|
```ts
// MyComponent.stories.ts
// Replace vue3 with vue if you are using Storybook for Vue 2
import type { Meta, StoryObj } from '@storybook/vue3';
import MyComponent from './MyComponent.vue';
const meta = {
component: MyComponent,
} satisfies Meta<typeof MyComponent>;
export default meta;
type Story = StoryObj<typeof meta>;
export const Basic: Story = {
render: () => ({
components: { MyComponent },
template: '<MyComponent />',
}),
};
export const WithProp: Story = {
render: () => ({
components: { MyComponent },
template: '<MyComponent prop="value"/>',
}),
};
```
|
docs/snippets/vue/my-component-story-basic-and-props.ts-4-9.mdx
| 0 |
https://github.com/storybookjs/storybook/commit/39e6fd82c4a39766bdfc66f4b67021b57339a58f
|
[
0.00017645955085754395,
0.00017462934192735702,
0.00017229699005838484,
0.00017513148486614227,
0.0000017360565607305034
] |
{
"id": 2,
"code_window": [
"import React, { useEffect, useState } from 'react';\n",
"import { styled } from '@storybook/theming';\n",
"import { Link } from '@storybook/components';\n",
"import { VideoIcon } from '@storybook/icons';\n",
"\n",
"interface EmptyProps {\n",
" inAddonPanel?: boolean;\n",
"}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { DocumentIcon, SupportIcon, VideoIcon } from '@storybook/icons';\n"
],
"file_path": "code/ui/blocks/src/components/ArgsTable/Empty.tsx",
"type": "replace",
"edit_start_line_idx": 4
}
|
```html
<!-- YourPage.vue -->
<template>
<div v-if="loading">Loading...</div>
<div v-else-if="error">There was an error fetching the data!</div>
<div v-if="!loading && data && result.subdocuments.length">
<PageLayout :user="data.user">
<DocumentHeader :document="result.document" />
<DocumentList :documents="result.subdocuments" />
</PageLayout>
</div>
</template>
<script lang="ts">
import PageLayout from './PageLayout';
import DocumentHeader from './DocumentHeader';
import DocumentList from './DocumentList';
import gql from 'graphql-tag';
import { useQuery } from '@vue/apollo-composable';
import { defineComponent } from 'vue';
export default defineComponent({
name: 'DocumentScreen',
setup() {
const { result, loading, error } = useQuery(gql`
query AllInfoQuery {
user {
userID
name
}
document {
id
userID
title
brief
status
}
subdocuments {
id
userID
title
content
status
}
}
`);
return {
result,
loading,
error,
};
},
});
</script>
```
|
docs/snippets/vue/document-screen-with-graphql.3.ts.mdx
| 0 |
https://github.com/storybookjs/storybook/commit/39e6fd82c4a39766bdfc66f4b67021b57339a58f
|
[
0.00017876560741569847,
0.00017641040903981775,
0.000175014793057926,
0.000176370216649957,
0.0000011832182735815877
] |
{
"id": 2,
"code_window": [
"import React, { useEffect, useState } from 'react';\n",
"import { styled } from '@storybook/theming';\n",
"import { Link } from '@storybook/components';\n",
"import { VideoIcon } from '@storybook/icons';\n",
"\n",
"interface EmptyProps {\n",
" inAddonPanel?: boolean;\n",
"}\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
"import { DocumentIcon, SupportIcon, VideoIcon } from '@storybook/icons';\n"
],
"file_path": "code/ui/blocks/src/components/ArgsTable/Empty.tsx",
"type": "replace",
"edit_start_line_idx": 4
}
|
```shell
yarn test-storybook --url https://the-storybook-url-here.com
```
|
docs/snippets/common/test-runner-execute-with-url.yarn.js.mdx
| 0 |
https://github.com/storybookjs/storybook/commit/39e6fd82c4a39766bdfc66f4b67021b57339a58f
|
[
0.00016407012299168855,
0.00016407012299168855,
0.00016407012299168855,
0.00016407012299168855,
0
] |
{
"id": 3,
"code_window": [
" <Link href=\"https://youtu.be/0gOfS6K0x0E\" target=\"_blank\" withArrow>\n",
" <VideoIcon /> Watch 5m video\n",
" </Link>\n",
" <Divider />\n",
" <Link\n",
" href=\"https://storybook.js.org/docs/react/essentials/controls\"\n",
" target=\"_blank\"\n",
" withArrow\n",
" >\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" href=\"https://storybook.js.org/docs/essentials/controls\"\n"
],
"file_path": "code/ui/blocks/src/components/ArgsTable/Empty.tsx",
"type": "replace",
"edit_start_line_idx": 94
}
|
import type { FC } from 'react';
import React from 'react';
import pickBy from 'lodash/pickBy.js';
import { styled } from '@storybook/theming';
import { transparentize } from 'polished';
import { includeConditionalArg } from '@storybook/csf';
import { once } from '@storybook/client-logger';
import { IconButton, ResetWrapper, Link } from '@storybook/components';
import { UndoIcon } from '@storybook/icons';
import { ArgRow } from './ArgRow';
import { SectionRow } from './SectionRow';
import type { ArgType, ArgTypes, Args, Globals } from './types';
import { EmptyBlock } from '..';
import { Skeleton } from './Skeleton';
import { Empty } from './Empty';
export const TableWrapper = styled.table<{
compact?: boolean;
inAddonPanel?: boolean;
isLoading?: boolean;
}>(({ theme, compact, inAddonPanel }) => ({
'&&': {
// Resets for cascading/system styles
borderSpacing: 0,
color: theme.color.defaultText,
'td, th': {
padding: 0,
border: 'none',
verticalAlign: 'top',
textOverflow: 'ellipsis',
},
// End Resets
fontSize: theme.typography.size.s2 - 1,
lineHeight: '20px',
textAlign: 'left',
width: '100%',
// Margin collapse
marginTop: inAddonPanel ? 0 : 25,
marginBottom: inAddonPanel ? 0 : 40,
'thead th:first-of-type, td:first-of-type': {
// intentionally specify thead here
width: '25%',
},
'th:first-of-type, td:first-of-type': {
paddingLeft: 20,
},
'th:nth-of-type(2), td:nth-of-type(2)': {
...(compact
? null
: {
// Description column
width: '35%',
}),
},
'td:nth-of-type(3)': {
...(compact
? null
: {
// Defaults column
width: '15%',
}),
},
'th:last-of-type, td:last-of-type': {
paddingRight: 20,
...(compact
? null
: {
// Controls column
width: '25%',
}),
},
th: {
color:
theme.base === 'light'
? transparentize(0.25, theme.color.defaultText)
: transparentize(0.45, theme.color.defaultText),
paddingTop: 10,
paddingBottom: 10,
paddingLeft: 15,
paddingRight: 15,
},
td: {
paddingTop: '10px',
paddingBottom: '10px',
'&:not(:first-of-type)': {
paddingLeft: 15,
paddingRight: 15,
},
'&:last-of-type': {
paddingRight: 20,
},
},
// Makes border alignment consistent w/other DocBlocks
marginLeft: inAddonPanel ? 0 : 1,
marginRight: inAddonPanel ? 0 : 1,
tbody: {
// Safari doesn't love shadows on tbody so we need to use a shadow filter. In order to do this,
// the table cells all need to be solid so they have a background color applied.
// I wasn't sure what kinds of content go in these tables so I was extra specific with selectors
// to avoid unexpected surprises.
...(inAddonPanel
? null
: {
filter:
theme.base === 'light'
? `drop-shadow(0px 1px 3px rgba(0, 0, 0, 0.10))`
: `drop-shadow(0px 1px 3px rgba(0, 0, 0, 0.20))`,
}),
'> tr > *': {
// For filter to work properly, the table cells all need to be opaque.
background: theme.background.content,
borderTop: `1px solid ${theme.appBorderColor}`,
},
...(inAddonPanel
? null
: {
// This works and I don't know why. :)
'> tr:first-of-type > *': {
borderBlockStart: `1px solid ${theme.appBorderColor}`,
},
'> tr:last-of-type > *': {
borderBlockEnd: `1px solid ${theme.appBorderColor}`,
},
'> tr > *:first-of-type': {
borderInlineStart: `1px solid ${theme.appBorderColor}`,
},
'> tr > *:last-of-type': {
borderInlineEnd: `1px solid ${theme.appBorderColor}`,
},
// Thank you, Safari, for making me write code like this.
'> tr:first-of-type > td:first-of-type': {
borderTopLeftRadius: theme.appBorderRadius,
},
'> tr:first-of-type > td:last-of-type': {
borderTopRightRadius: theme.appBorderRadius,
},
'> tr:last-of-type > td:first-of-type': {
borderBottomLeftRadius: theme.appBorderRadius,
},
'> tr:last-of-type > td:last-of-type': {
borderBottomRightRadius: theme.appBorderRadius,
},
}),
},
// End awesome table styling
},
}));
const StyledIconButton = styled(IconButton as any)(({ theme }) => ({
color: theme.barTextColor,
margin: '-4px -12px -4px 0',
}));
const ControlHeadingWrapper = styled.span({
display: 'flex',
justifyContent: 'space-between',
});
export enum ArgsTableError {
NO_COMPONENT = 'No component found.',
ARGS_UNSUPPORTED = 'Args unsupported. See Args documentation for your framework.',
}
export type SortType = 'alpha' | 'requiredFirst' | 'none';
type SortFn = (a: ArgType, b: ArgType) => number;
const sortFns: Record<SortType, SortFn | null> = {
alpha: (a: ArgType, b: ArgType) => a.name.localeCompare(b.name),
requiredFirst: (a: ArgType, b: ArgType) =>
Number(!!b.type?.required) - Number(!!a.type?.required) || a.name.localeCompare(b.name),
none: undefined,
};
export interface ArgsTableOptionProps {
children?: React.ReactNode;
updateArgs?: (args: Args) => void;
resetArgs?: (argNames?: string[]) => void;
compact?: boolean;
inAddonPanel?: boolean;
initialExpandedArgs?: boolean;
isLoading?: boolean;
sort?: SortType;
}
interface ArgsTableDataProps {
rows: ArgTypes;
args?: Args;
globals?: Globals;
}
interface ArgsTableErrorProps {
error: ArgsTableError;
}
export interface ArgsTableLoadingProps {
isLoading: boolean;
}
export type ArgsTableProps = ArgsTableOptionProps &
(ArgsTableDataProps | ArgsTableErrorProps | ArgsTableLoadingProps);
type Rows = ArgType[];
type Subsection = Rows;
type Section = {
ungrouped: Rows;
subsections: Record<string, Subsection>;
};
type Sections = {
ungrouped: Rows;
ungroupedSubsections: Record<string, Subsection>;
sections: Record<string, Section>;
};
const groupRows = (rows: ArgType, sort: SortType) => {
const sections: Sections = { ungrouped: [], ungroupedSubsections: {}, sections: {} };
if (!rows) return sections;
Object.entries(rows).forEach(([key, row]) => {
const { category, subcategory } = row?.table || {};
if (category) {
const section = sections.sections[category] || { ungrouped: [], subsections: {} };
if (!subcategory) {
section.ungrouped.push({ key, ...row });
} else {
const subsection = section.subsections[subcategory] || [];
subsection.push({ key, ...row });
section.subsections[subcategory] = subsection;
}
sections.sections[category] = section;
} else if (subcategory) {
const subsection = sections.ungroupedSubsections[subcategory] || [];
subsection.push({ key, ...row });
sections.ungroupedSubsections[subcategory] = subsection;
} else {
sections.ungrouped.push({ key, ...row });
}
});
// apply sort
const sortFn = sortFns[sort];
const sortSubsection = (record: Record<string, Subsection>) => {
if (!sortFn) return record;
return Object.keys(record).reduce<Record<string, Subsection>>(
(acc, cur) => ({
...acc,
[cur]: record[cur].sort(sortFn),
}),
{}
);
};
const sorted = {
ungrouped: sections.ungrouped.sort(sortFn),
ungroupedSubsections: sortSubsection(sections.ungroupedSubsections),
sections: Object.keys(sections.sections).reduce<Record<string, Section>>(
(acc, cur) => ({
...acc,
[cur]: {
ungrouped: sections.sections[cur].ungrouped.sort(sortFn),
subsections: sortSubsection(sections.sections[cur].subsections),
},
}),
{}
),
};
return sorted;
};
/**
* Wrap CSF's `includeConditionalArg` in a try catch so that invalid
* conditionals don't break the entire UI. We can safely swallow the
* error because `includeConditionalArg` is also called in the preview
* in `prepareStory`, and that exception will be bubbled up into the
* UI in a red screen. Nevertheless, we log the error here just in case.
*/
const safeIncludeConditionalArg = (row: ArgType, args: Args, globals: Globals) => {
try {
return includeConditionalArg(row, args, globals);
} catch (err) {
once.warn(err.message);
return false;
}
};
/**
* Display the props for a component as a props table. Each row is a collection of
* ArgDefs, usually derived from docgen info for the component.
*/
export const ArgsTable: FC<ArgsTableProps> = (props) => {
const {
updateArgs,
resetArgs,
compact,
inAddonPanel,
initialExpandedArgs,
sort = 'none',
isLoading,
} = props;
if ('error' in props) {
const { error } = props;
return (
<EmptyBlock>
{error}
<Link href="http://storybook.js.org/docs/" target="_blank" withArrow>
Read the docs
</Link>
</EmptyBlock>
);
}
// If the story is loading, show a skeleton
// This happen when you load the manager and the story is not yet loaded
if (isLoading) return <Skeleton />;
const { rows, args, globals } = 'rows' in props && props;
const groups = groupRows(
pickBy(
rows,
(row) => !row?.table?.disable && safeIncludeConditionalArg(row, args || {}, globals || {})
),
sort
);
// If there are no controls, show the empty state
const hasNoUngrouped = groups.ungrouped.length === 0;
const hasNoSections = Object.entries(groups.sections).length === 0;
const hasNoUngroupedSubsections = Object.entries(groups.ungroupedSubsections).length === 0;
if (hasNoUngrouped && hasNoSections && hasNoUngroupedSubsections)
return <Empty inAddonPanel={inAddonPanel} />;
let colSpan = 1;
if (updateArgs) colSpan += 1;
if (!compact) colSpan += 2;
const expandable = Object.keys(groups.sections).length > 0;
const common = { updateArgs, compact, inAddonPanel, initialExpandedArgs };
return (
<ResetWrapper>
<TableWrapper {...{ compact, inAddonPanel }} className="docblock-argstable sb-unstyled">
<thead className="docblock-argstable-head">
<tr>
<th>
<span>Name</span>
</th>
{compact ? null : (
<th>
<span>Description</span>
</th>
)}
{compact ? null : (
<th>
<span>Default</span>
</th>
)}
{updateArgs ? (
<th>
<ControlHeadingWrapper>
Control{' '}
{!isLoading && resetArgs && (
<StyledIconButton onClick={() => resetArgs()} title="Reset controls">
<UndoIcon aria-hidden />
</StyledIconButton>
)}
</ControlHeadingWrapper>
</th>
) : null}
</tr>
</thead>
<tbody className="docblock-argstable-body">
{groups.ungrouped.map((row) => (
<ArgRow key={row.key} row={row} arg={args && args[row.key]} {...common} />
))}
{Object.entries(groups.ungroupedSubsections).map(([subcategory, subsection]) => (
<SectionRow key={subcategory} label={subcategory} level="subsection" colSpan={colSpan}>
{subsection.map((row) => (
<ArgRow
key={row.key}
row={row}
arg={args && args[row.key]}
expandable={expandable}
{...common}
/>
))}
</SectionRow>
))}
{Object.entries(groups.sections).map(([category, section]) => (
<SectionRow key={category} label={category} level="section" colSpan={colSpan}>
{section.ungrouped.map((row) => (
<ArgRow key={row.key} row={row} arg={args && args[row.key]} {...common} />
))}
{Object.entries(section.subsections).map(([subcategory, subsection]) => (
<SectionRow
key={subcategory}
label={subcategory}
level="subsection"
colSpan={colSpan}
>
{subsection.map((row) => (
<ArgRow
key={row.key}
row={row}
arg={args && args[row.key]}
expandable={expandable}
{...common}
/>
))}
</SectionRow>
))}
</SectionRow>
))}
</tbody>
</TableWrapper>
</ResetWrapper>
);
};
|
code/ui/blocks/src/components/ArgsTable/ArgsTable.tsx
| 1 |
https://github.com/storybookjs/storybook/commit/39e6fd82c4a39766bdfc66f4b67021b57339a58f
|
[
0.0011266483925282955,
0.00019957659242209047,
0.00016298254195135087,
0.00017198406567331403,
0.00014923972776159644
] |
{
"id": 3,
"code_window": [
" <Link href=\"https://youtu.be/0gOfS6K0x0E\" target=\"_blank\" withArrow>\n",
" <VideoIcon /> Watch 5m video\n",
" </Link>\n",
" <Divider />\n",
" <Link\n",
" href=\"https://storybook.js.org/docs/react/essentials/controls\"\n",
" target=\"_blank\"\n",
" withArrow\n",
" >\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" href=\"https://storybook.js.org/docs/essentials/controls\"\n"
],
"file_path": "code/ui/blocks/src/components/ArgsTable/Empty.tsx",
"type": "replace",
"edit_start_line_idx": 94
}
|
```tsx
// CSF 2
import { ComponentStory, ComponentMeta } from 'storybook-solidjs';
import { Button } from './Button';
export default {
title: 'Button',
component: Button,
} as ComponentMeta<typeof Button>;
export const Primary: ComponentStory<typeof Button> = (args) => <Button {...args} />;
Primary.args = { primary: true };
```
|
docs/snippets/solid/csf-2-example-starter.ts.mdx
| 0 |
https://github.com/storybookjs/storybook/commit/39e6fd82c4a39766bdfc66f4b67021b57339a58f
|
[
0.0001723451423458755,
0.0001694047823548317,
0.00016646440781187266,
0.0001694047823548317,
0.0000029403672670014203
] |
{
"id": 3,
"code_window": [
" <Link href=\"https://youtu.be/0gOfS6K0x0E\" target=\"_blank\" withArrow>\n",
" <VideoIcon /> Watch 5m video\n",
" </Link>\n",
" <Divider />\n",
" <Link\n",
" href=\"https://storybook.js.org/docs/react/essentials/controls\"\n",
" target=\"_blank\"\n",
" withArrow\n",
" >\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" href=\"https://storybook.js.org/docs/essentials/controls\"\n"
],
"file_path": "code/ui/blocks/src/components/ArgsTable/Empty.tsx",
"type": "replace",
"edit_start_line_idx": 94
}
|
import { describe, it, expect } from 'vitest';
import { dedent } from 'ts-dedent';
import type { API } from 'jscodeshift';
import ansiRegex from 'ansi-regex';
import _transform from '../csf-2-to-3';
expect.addSnapshotSerializer({
serialize: (val: any) => (typeof val === 'string' ? val : val.toString()),
test: () => true,
});
const jsTransform = async (source: string) =>
(await _transform({ source, path: 'Component.stories.jsx' }, {} as API, {})).trim();
const tsTransform = async (source: string) =>
(
await _transform({ source, path: 'Component.stories.tsx' }, {} as API, {
parser: 'tsx',
})
).trim();
describe('csf-2-to-3', () => {
describe('javascript', () => {
it('should replace non-simple function exports with objects', async () => {
await expect(
jsTransform(dedent`
export default { title: 'Cat' };
export const A = () => <Cat />;
export const B = (args) => <Button {...args} />;
`)
).resolves.toMatchInlineSnapshot(`
export default { title: 'Cat' };
export const A = () => <Cat />;
export const B = {
render: (args) => <Button {...args} />,
};
`);
});
it('should move annotations into story objects', async () => {
await expect(
jsTransform(dedent`
export default { title: 'Cat' };
export const A = () => <Cat />;
A.storyName = 'foo';
A.parameters = { bar: 2 };
A.play = () => {};
`)
).resolves.toMatchInlineSnapshot(`
export default { title: 'Cat' };
export const A = {
render: () => <Cat />,
name: 'foo',
parameters: { bar: 2 },
play: () => {},
};
`);
});
it('should ignore non-story exports, statements', async () => {
await expect(
jsTransform(dedent`
export default { title: 'components/Fruit', includeStories: ['A'] };
export const A = (args) => <Apple {...args} />;
export const B = (args) => <Banana {...args} />;
const C = (args) => <Cherry {...args} />;
`)
).resolves.toMatchInlineSnapshot(`
export default { title: 'components/Fruit', includeStories: ['A'] };
export const A = {
render: (args) => <Apple {...args} />,
};
export const B = (args) => <Banana {...args} />;
const C = (args) => <Cherry {...args} />;
`);
});
it('should do nothing when there is no meta', async () => {
await expect(
jsTransform(dedent`
export const A = () => <Apple />;
export const B = (args) => <Banana {...args} />;
`)
).resolves.toMatchInlineSnapshot(`
export const A = () => <Apple />;
export const B = (args) => <Banana {...args} />;
`);
});
it('should remove implicit global render function (react)', async () => {
await expect(
jsTransform(dedent`
export default { title: 'Cat', component: Cat };
export const A = (args) => <Cat {...args} />;
export const B = (args) => <Banana {...args} />;
`)
).resolves.toMatchInlineSnapshot(`
export default { title: 'Cat', component: Cat };
export const A = {};
export const B = {
render: (args) => <Banana {...args} />,
};
`);
});
it('should ignore object exports', async () => {
await expect(
jsTransform(dedent`
export default { title: 'Cat', component: Cat };
export const A = {
render: (args) => <Cat {...args} />
};
`)
).resolves.toMatchInlineSnapshot(`
export default { title: 'Cat', component: Cat };
export const A = {
render: (args) => <Cat {...args} />,
};
`);
});
it('should hoist template.bind (if there is only one)', async () => {
await expect(
jsTransform(dedent`
export default { title: 'Cat' };
const Template = (args) => <Cat {...args} />;
export const A = Template.bind({});
A.args = { isPrimary: false };
`)
).resolves.toMatchInlineSnapshot(`
export default { title: 'Cat' };
const Template = (args) => <Cat {...args} />;
export const A = {
render: Template,
args: { isPrimary: false },
};
`);
});
it('should reuse the template when there are multiple Template.bind references but no component defined', async () => {
await expect(
jsTransform(dedent`
export default { title: 'Cat' };
const Template = (args) => <Cat {...args} />;
export const A = Template.bind({});
A.args = { isPrimary: false };
export const B = Template.bind({});
B.args = { isPrimary: true };
export const C = Template.bind({});
C.args = { bla: true };
export const D = Template.bind({});
D.args = { bla: false };
`)
).resolves.toMatchInlineSnapshot(`
export default { title: 'Cat' };
const Template = (args) => <Cat {...args} />;
export const A = {
render: Template,
args: { isPrimary: false },
};
export const B = {
render: Template,
args: { isPrimary: true },
};
export const C = {
render: Template,
args: { bla: true },
};
export const D = {
render: Template,
args: { bla: false },
};
`);
});
it('should remove implicit global render for template.bind', async () => {
await expect(
jsTransform(dedent`
export default { title: 'Cat', component: Cat };
const Template = (args) => <Cat {...args} />;
export const A = Template.bind({});
A.args = { isPrimary: false };
const Template2 = (args) => <Banana {...args} />;
export const B = Template2.bind({});
B.args = { isPrimary: true };
`)
).resolves.toMatchInlineSnapshot(`
export default { title: 'Cat', component: Cat };
export const A = {
args: { isPrimary: false },
};
const Template2 = (args) => <Banana {...args} />;
export const B = {
render: Template2,
args: { isPrimary: true },
};
`);
});
it('should ignore no-arg stories without annotations', async () => {
await expect(
jsTransform(dedent`
export default { title: 'Cat', component: Cat };
export const A = (args) => <Cat {...args} />;
export const B = () => <Cat name="frisky" />;
export const C = () => <Cat name="fluffy" />;
C.parameters = { foo: 2 };
`)
).resolves.toMatchInlineSnapshot(`
export default { title: 'Cat', component: Cat };
export const A = {};
export const B = () => <Cat name="frisky" />;
export const C = {
render: () => <Cat name="fluffy" />,
parameters: { foo: 2 },
};
`);
});
it('should work for v1-style annotations', async () => {
await expect(
jsTransform(dedent`
export default { title: 'Cat' };
export const A = (args) => <Cat {...args} />;
A.story = {
parameters: { foo: 2 }
};
`)
).resolves.toMatchInlineSnapshot(`
export default { title: 'Cat' };
export const A = {
render: (args) => <Cat {...args} />,
parameters: { foo: 2 },
};
`);
});
});
describe('typescript', () => {
it('should error with namespace imports', async () => {
await expect.addSnapshotSerializer({
serialize: (value) => {
const stringVal = typeof value === 'string' ? value : value.toString();
return stringVal.replace(ansiRegex(), '');
},
test: () => true,
});
await expect(() =>
tsTransform(dedent`
import * as SB from '@storybook/react';
import { CatProps } from './Cat';
const meta = { title: 'Cat', component: Cat } as Meta<CatProps>
export default meta;
export const A: SB.StoryFn<CatProps> = () => <Cat />;
`)
).rejects.toThrowErrorMatchingInlineSnapshot(dedent`
Error: This codemod does not support namespace imports for a @storybook/react package.
Replace the namespace import with named imports and try again.
`);
});
it('should keep local names', async () => {
await expect(
tsTransform(dedent`
import { Meta, StoryObj as CSF3, StoryFn as CSF2 } from '@storybook/react';
import { CatProps } from './Cat';
const meta = { title: 'Cat', component: Cat } satisfies Meta<CatProps>
export default meta;
export const A: CSF2<CatProps> = () => <Cat />;
export const B: CSF3<CatProps> = {
args: { name: "already csf3" }
};
export const C: CSF2<CatProps> = (args) => <Cat {...args} />;
C.args = {
name: "Fluffy"
};
`)
).resolves.toMatchInlineSnapshot(`
import { Meta, StoryObj as CSF3, StoryFn as CSF2 } from '@storybook/react';
import { CatProps } from './Cat';
const meta = { title: 'Cat', component: Cat } satisfies Meta<CatProps>;
export default meta;
export const A: CSF2<CatProps> = () => <Cat />;
export const B: CSF3<CatProps> = {
args: { name: 'already csf3' },
};
export const C: CSF3<CatProps> = {
args: {
name: 'Fluffy',
},
};
`);
});
it('should replace function exports with objects and update type', async () => {
await expect(
tsTransform(dedent`
import { Story, StoryFn, ComponentStory, ComponentStoryObj } from '@storybook/react';
// some extra whitespace to test
export default {
title: 'Cat',
component: Cat,
} as Meta<CatProps>;
export const A: Story<CatProps> = (args) => <Cat {...args} />;
A.args = { name: "Fluffy" };
export const B: any = (args) => <Button {...args} />;
export const C: Story<CatProps> = () => <Cat />;
export const D: StoryFn<CatProps> = (args) => <Cat {...args} />;
D.args = {
name: "Fluffy"
};
export const E: ComponentStory<Cat> = (args) => <Cat {...args} />;
E.args = { name: "Fluffy" };
export const F: Story = (args) => <Cat {...args} />;
F.args = {
name: "Fluffy"
};
export const G: ComponentStoryObj<typeof Cat> = {
args: {
name: 'Fluffy',
},
};
`)
).resolves.toMatchInlineSnapshot(`
import { StoryObj, StoryFn } from '@storybook/react';
// some extra whitespace to test
export default {
title: 'Cat',
component: Cat,
} as Meta<CatProps>;
export const A: StoryObj<CatProps> = {
args: { name: 'Fluffy' },
};
export const B: any = {
render: (args) => <Button {...args} />,
};
export const C: StoryFn<CatProps> = () => <Cat />;
export const D: StoryObj<CatProps> = {
args: {
name: 'Fluffy',
},
};
export const E: StoryObj<Cat> = {
args: { name: 'Fluffy' },
};
export const F: StoryObj = {
args: {
name: 'Fluffy',
},
};
export const G: StoryObj<typeof Cat> = {
args: {
name: 'Fluffy',
},
};
`);
});
it('migrate Story type to StoryFn when used in an not exported Template function', async () => {
await expect(
tsTransform(dedent`
import { Story, Meta } from '@storybook/react'
export default {
component: Cat,
} satisfies Meta
const Template: Story = () => <div>Hello World</div>;
export const Default = Template.bind({})
`)
).resolves.toMatchInlineSnapshot(`
import { StoryFn, Meta } from '@storybook/react';
export default {
component: Cat,
} satisfies Meta;
const Template: StoryFn = () => <div>Hello World</div>;
export const Default = {
render: Template,
};
`);
});
});
});
|
code/lib/codemod/src/transforms/__tests__/csf-2-to-3.test.ts
| 0 |
https://github.com/storybookjs/storybook/commit/39e6fd82c4a39766bdfc66f4b67021b57339a58f
|
[
0.00017895849305205047,
0.0001743509783409536,
0.00016301346477121115,
0.0001758840517140925,
0.000004026395345135825
] |
{
"id": 3,
"code_window": [
" <Link href=\"https://youtu.be/0gOfS6K0x0E\" target=\"_blank\" withArrow>\n",
" <VideoIcon /> Watch 5m video\n",
" </Link>\n",
" <Divider />\n",
" <Link\n",
" href=\"https://storybook.js.org/docs/react/essentials/controls\"\n",
" target=\"_blank\"\n",
" withArrow\n",
" >\n"
],
"labels": [
"keep",
"keep",
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [
" href=\"https://storybook.js.org/docs/essentials/controls\"\n"
],
"file_path": "code/ui/blocks/src/components/ArgsTable/Empty.tsx",
"type": "replace",
"edit_start_line_idx": 94
}
|
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`is not Nx project > angular builders > Angular < 15.0.0 > should throw an Error 1`] = `
[Error: ❌ Your project uses Angular < 15.0.0. Storybook 8.0 for Angular requires Angular 15.0.0 or higher.
Please upgrade your Angular version to at least version 15.0.0 to use Storybook 8.0 in your project.]
`;
|
code/lib/cli/src/automigrate/fixes/__snapshots__/angular-builders.test.ts.snap
| 0 |
https://github.com/storybookjs/storybook/commit/39e6fd82c4a39766bdfc66f4b67021b57339a58f
|
[
0.00016278561088256538,
0.00016278561088256538,
0.00016278561088256538,
0.00016278561088256538,
0
] |
{
"id": 4,
"code_window": [
" target=\"_blank\"\n",
" withArrow\n",
" >\n",
" Read docs\n",
" </Link>\n",
" </>\n",
" )}\n",
" {!inAddonPanel && (\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <DocumentIcon /> Read docs\n"
],
"file_path": "code/ui/blocks/src/components/ArgsTable/Empty.tsx",
"type": "replace",
"edit_start_line_idx": 98
}
|
import type { FC } from 'react';
import React, { useEffect, useState } from 'react';
import { styled } from '@storybook/theming';
import { Link } from '@storybook/components';
import { VideoIcon } from '@storybook/icons';
interface EmptyProps {
inAddonPanel?: boolean;
}
const Wrapper = styled.div<{ inAddonPanel?: boolean }>(({ inAddonPanel, theme }) => ({
height: inAddonPanel ? '100%' : 'auto',
display: 'flex',
border: inAddonPanel ? 'none' : `1px solid ${theme.appBorderColor}`,
borderRadius: inAddonPanel ? 0 : theme.appBorderRadius,
padding: inAddonPanel ? 0 : 40,
alignItems: 'center',
justifyContent: 'center',
flexDirection: 'column',
gap: 15,
background: theme.background.content,
boxShadow: 'rgba(0, 0, 0, 0.10) 0 1px 3px 0',
}));
const Content = styled.div({
display: 'flex',
flexDirection: 'column',
gap: 4,
maxWidth: 415,
});
const Title = styled.div(({ theme }) => ({
fontWeight: theme.typography.weight.bold,
fontSize: theme.typography.size.s2 - 1,
textAlign: 'center',
color: theme.textColor,
}));
const Description = styled.div(({ theme }) => ({
fontWeight: theme.typography.weight.regular,
fontSize: theme.typography.size.s2 - 1,
textAlign: 'center',
color: theme.textMutedColor,
}));
const Links = styled.div(({ theme }) => ({
display: 'flex',
fontSize: theme.typography.size.s2 - 1,
gap: 25,
}));
const Divider = styled.div(({ theme }) => ({
width: 1,
height: 16,
backgroundColor: theme.appBorderColor,
}));
export const Empty: FC<EmptyProps> = ({ inAddonPanel }) => {
const [isLoading, setIsLoading] = useState(true);
// We are adding a small delay to avoid flickering when the story is loading.
// It takes a bit of time for the controls to appear, so we don't want
// to show the empty state for a split second.
useEffect(() => {
const load = setTimeout(() => {
setIsLoading(false);
}, 100);
return () => clearTimeout(load);
}, []);
if (isLoading) return null;
return (
<Wrapper inAddonPanel={inAddonPanel}>
<Content>
<Title>
{inAddonPanel
? 'Interactive story playground'
: "Args table with interactive controls couldn't be auto-generated"}
</Title>
<Description>
Controls give you an easy to use interface to test your components. Set your story args
and you'll see controls appearing here automatically.
</Description>
</Content>
<Links>
{inAddonPanel && (
<>
<Link href="https://youtu.be/0gOfS6K0x0E" target="_blank" withArrow>
<VideoIcon /> Watch 5m video
</Link>
<Divider />
<Link
href="https://storybook.js.org/docs/react/essentials/controls"
target="_blank"
withArrow
>
Read docs
</Link>
</>
)}
{!inAddonPanel && (
<Link
href="https://storybook.js.org/docs/react/essentials/controls"
target="_blank"
withArrow
>
Learn how to set that up
</Link>
)}
</Links>
</Wrapper>
);
};
|
code/ui/blocks/src/components/ArgsTable/Empty.tsx
| 1 |
https://github.com/storybookjs/storybook/commit/39e6fd82c4a39766bdfc66f4b67021b57339a58f
|
[
0.92351895570755,
0.09213966876268387,
0.00016973557649180293,
0.0028704614378511906,
0.2527215778827667
] |
{
"id": 4,
"code_window": [
" target=\"_blank\"\n",
" withArrow\n",
" >\n",
" Read docs\n",
" </Link>\n",
" </>\n",
" )}\n",
" {!inAddonPanel && (\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <DocumentIcon /> Read docs\n"
],
"file_path": "code/ui/blocks/src/components/ArgsTable/Empty.tsx",
"type": "replace",
"edit_start_line_idx": 98
}
|
```ts
// Button.stories.ts
import type { Meta } from '@storybook/angular';
import { Button } from './button.component';
// To apply a set of backgrounds to all stories of Button:
const meta: Meta<Button> = {
component: Button,
parameters: {
backgrounds: {
default: 'twitter',
values: [
{ name: 'twitter', value: '#00aced' },
{ name: 'facebook', value: '#3b5998' },
],
},
},
};
export default meta;
```
|
docs/snippets/angular/storybook-addon-backgrounds-configure-backgrounds.ts.mdx
| 0 |
https://github.com/storybookjs/storybook/commit/39e6fd82c4a39766bdfc66f4b67021b57339a58f
|
[
0.00017314942670054734,
0.00017195379768963903,
0.0001704838068690151,
0.00017222815949935466,
0.0000011053922435166896
] |
{
"id": 4,
"code_window": [
" target=\"_blank\"\n",
" withArrow\n",
" >\n",
" Read docs\n",
" </Link>\n",
" </>\n",
" )}\n",
" {!inAddonPanel && (\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <DocumentIcon /> Read docs\n"
],
"file_path": "code/ui/blocks/src/components/ArgsTable/Empty.tsx",
"type": "replace",
"edit_start_line_idx": 98
}
|
{
"name": "@storybook/builder-webpack5",
"$schema": "../../node_modules/nx/schemas/project-schema.json",
"implicitDependencies": [],
"type": "library"
}
|
code/builders/builder-webpack5/project.json
| 0 |
https://github.com/storybookjs/storybook/commit/39e6fd82c4a39766bdfc66f4b67021b57339a58f
|
[
0.0001707654446363449,
0.0001707654446363449,
0.0001707654446363449,
0.0001707654446363449,
0
] |
{
"id": 4,
"code_window": [
" target=\"_blank\"\n",
" withArrow\n",
" >\n",
" Read docs\n",
" </Link>\n",
" </>\n",
" )}\n",
" {!inAddonPanel && (\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <DocumentIcon /> Read docs\n"
],
"file_path": "code/ui/blocks/src/components/ArgsTable/Empty.tsx",
"type": "replace",
"edit_start_line_idx": 98
}
|
import { logger } from '@storybook/node-logger';
import type { Preset, StorybookConfig } from '@storybook/core-webpack';
import { isReactScriptsInstalled } from './cra-config';
const checkForNewPreset = (presetsList: Preset[]) => {
const hasNewPreset = presetsList.some((preset: Preset) => {
const presetName = typeof preset === 'string' ? preset : preset.name;
return /@storybook(\/|\\)preset-create-react-app/.test(presetName);
});
if (!hasNewPreset) {
logger.warn('Storybook support for Create React App is now a separate preset.');
logger.warn(
'To use the new preset, install `@storybook/preset-create-react-app` and add it to the list of `addons` in your `.storybook/main.js` config file.'
);
logger.warn('The built-in preset has been disabled in Storybook 6.0.');
}
};
export const webpackFinal: StorybookConfig['webpack'] = (config, { presetsList }) => {
if (isReactScriptsInstalled()) {
if (presetsList) {
checkForNewPreset(presetsList);
}
}
config.module?.rules?.push(
...[
{
test: /\.m?js$/,
type: 'javascript/auto',
},
{
test: /\.m?js$/,
resolve: {
fullySpecified: false,
},
},
]
);
return config;
};
|
code/presets/react-webpack/src/framework-preset-cra.ts
| 0 |
https://github.com/storybookjs/storybook/commit/39e6fd82c4a39766bdfc66f4b67021b57339a58f
|
[
0.00017200855654664338,
0.00016978774510789663,
0.00016571927699260414,
0.00017169788770843297,
0.000002580429736553924
] |
{
"id": 5,
"code_window": [
" </>\n",
" )}\n",
" {!inAddonPanel && (\n",
" <Link\n",
" href=\"https://storybook.js.org/docs/react/essentials/controls\"\n",
" target=\"_blank\"\n",
" withArrow\n",
" >\n",
" Learn how to set that up\n",
" </Link>\n",
" )}\n",
" </Links>\n",
" </Wrapper>\n",
" );\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <Link href=\"https://storybook.js.org/docs/essentials/controls\" target=\"_blank\" withArrow>\n",
" <SupportIcon /> Learn how to set that up\n"
],
"file_path": "code/ui/blocks/src/components/ArgsTable/Empty.tsx",
"type": "replace",
"edit_start_line_idx": 103
}
|
import type { FC } from 'react';
import React from 'react';
import pickBy from 'lodash/pickBy.js';
import { styled } from '@storybook/theming';
import { transparentize } from 'polished';
import { includeConditionalArg } from '@storybook/csf';
import { once } from '@storybook/client-logger';
import { IconButton, ResetWrapper, Link } from '@storybook/components';
import { UndoIcon } from '@storybook/icons';
import { ArgRow } from './ArgRow';
import { SectionRow } from './SectionRow';
import type { ArgType, ArgTypes, Args, Globals } from './types';
import { EmptyBlock } from '..';
import { Skeleton } from './Skeleton';
import { Empty } from './Empty';
export const TableWrapper = styled.table<{
compact?: boolean;
inAddonPanel?: boolean;
isLoading?: boolean;
}>(({ theme, compact, inAddonPanel }) => ({
'&&': {
// Resets for cascading/system styles
borderSpacing: 0,
color: theme.color.defaultText,
'td, th': {
padding: 0,
border: 'none',
verticalAlign: 'top',
textOverflow: 'ellipsis',
},
// End Resets
fontSize: theme.typography.size.s2 - 1,
lineHeight: '20px',
textAlign: 'left',
width: '100%',
// Margin collapse
marginTop: inAddonPanel ? 0 : 25,
marginBottom: inAddonPanel ? 0 : 40,
'thead th:first-of-type, td:first-of-type': {
// intentionally specify thead here
width: '25%',
},
'th:first-of-type, td:first-of-type': {
paddingLeft: 20,
},
'th:nth-of-type(2), td:nth-of-type(2)': {
...(compact
? null
: {
// Description column
width: '35%',
}),
},
'td:nth-of-type(3)': {
...(compact
? null
: {
// Defaults column
width: '15%',
}),
},
'th:last-of-type, td:last-of-type': {
paddingRight: 20,
...(compact
? null
: {
// Controls column
width: '25%',
}),
},
th: {
color:
theme.base === 'light'
? transparentize(0.25, theme.color.defaultText)
: transparentize(0.45, theme.color.defaultText),
paddingTop: 10,
paddingBottom: 10,
paddingLeft: 15,
paddingRight: 15,
},
td: {
paddingTop: '10px',
paddingBottom: '10px',
'&:not(:first-of-type)': {
paddingLeft: 15,
paddingRight: 15,
},
'&:last-of-type': {
paddingRight: 20,
},
},
// Makes border alignment consistent w/other DocBlocks
marginLeft: inAddonPanel ? 0 : 1,
marginRight: inAddonPanel ? 0 : 1,
tbody: {
// Safari doesn't love shadows on tbody so we need to use a shadow filter. In order to do this,
// the table cells all need to be solid so they have a background color applied.
// I wasn't sure what kinds of content go in these tables so I was extra specific with selectors
// to avoid unexpected surprises.
...(inAddonPanel
? null
: {
filter:
theme.base === 'light'
? `drop-shadow(0px 1px 3px rgba(0, 0, 0, 0.10))`
: `drop-shadow(0px 1px 3px rgba(0, 0, 0, 0.20))`,
}),
'> tr > *': {
// For filter to work properly, the table cells all need to be opaque.
background: theme.background.content,
borderTop: `1px solid ${theme.appBorderColor}`,
},
...(inAddonPanel
? null
: {
// This works and I don't know why. :)
'> tr:first-of-type > *': {
borderBlockStart: `1px solid ${theme.appBorderColor}`,
},
'> tr:last-of-type > *': {
borderBlockEnd: `1px solid ${theme.appBorderColor}`,
},
'> tr > *:first-of-type': {
borderInlineStart: `1px solid ${theme.appBorderColor}`,
},
'> tr > *:last-of-type': {
borderInlineEnd: `1px solid ${theme.appBorderColor}`,
},
// Thank you, Safari, for making me write code like this.
'> tr:first-of-type > td:first-of-type': {
borderTopLeftRadius: theme.appBorderRadius,
},
'> tr:first-of-type > td:last-of-type': {
borderTopRightRadius: theme.appBorderRadius,
},
'> tr:last-of-type > td:first-of-type': {
borderBottomLeftRadius: theme.appBorderRadius,
},
'> tr:last-of-type > td:last-of-type': {
borderBottomRightRadius: theme.appBorderRadius,
},
}),
},
// End awesome table styling
},
}));
const StyledIconButton = styled(IconButton as any)(({ theme }) => ({
color: theme.barTextColor,
margin: '-4px -12px -4px 0',
}));
const ControlHeadingWrapper = styled.span({
display: 'flex',
justifyContent: 'space-between',
});
export enum ArgsTableError {
NO_COMPONENT = 'No component found.',
ARGS_UNSUPPORTED = 'Args unsupported. See Args documentation for your framework.',
}
export type SortType = 'alpha' | 'requiredFirst' | 'none';
type SortFn = (a: ArgType, b: ArgType) => number;
const sortFns: Record<SortType, SortFn | null> = {
alpha: (a: ArgType, b: ArgType) => a.name.localeCompare(b.name),
requiredFirst: (a: ArgType, b: ArgType) =>
Number(!!b.type?.required) - Number(!!a.type?.required) || a.name.localeCompare(b.name),
none: undefined,
};
export interface ArgsTableOptionProps {
children?: React.ReactNode;
updateArgs?: (args: Args) => void;
resetArgs?: (argNames?: string[]) => void;
compact?: boolean;
inAddonPanel?: boolean;
initialExpandedArgs?: boolean;
isLoading?: boolean;
sort?: SortType;
}
interface ArgsTableDataProps {
rows: ArgTypes;
args?: Args;
globals?: Globals;
}
interface ArgsTableErrorProps {
error: ArgsTableError;
}
export interface ArgsTableLoadingProps {
isLoading: boolean;
}
export type ArgsTableProps = ArgsTableOptionProps &
(ArgsTableDataProps | ArgsTableErrorProps | ArgsTableLoadingProps);
type Rows = ArgType[];
type Subsection = Rows;
type Section = {
ungrouped: Rows;
subsections: Record<string, Subsection>;
};
type Sections = {
ungrouped: Rows;
ungroupedSubsections: Record<string, Subsection>;
sections: Record<string, Section>;
};
const groupRows = (rows: ArgType, sort: SortType) => {
const sections: Sections = { ungrouped: [], ungroupedSubsections: {}, sections: {} };
if (!rows) return sections;
Object.entries(rows).forEach(([key, row]) => {
const { category, subcategory } = row?.table || {};
if (category) {
const section = sections.sections[category] || { ungrouped: [], subsections: {} };
if (!subcategory) {
section.ungrouped.push({ key, ...row });
} else {
const subsection = section.subsections[subcategory] || [];
subsection.push({ key, ...row });
section.subsections[subcategory] = subsection;
}
sections.sections[category] = section;
} else if (subcategory) {
const subsection = sections.ungroupedSubsections[subcategory] || [];
subsection.push({ key, ...row });
sections.ungroupedSubsections[subcategory] = subsection;
} else {
sections.ungrouped.push({ key, ...row });
}
});
// apply sort
const sortFn = sortFns[sort];
const sortSubsection = (record: Record<string, Subsection>) => {
if (!sortFn) return record;
return Object.keys(record).reduce<Record<string, Subsection>>(
(acc, cur) => ({
...acc,
[cur]: record[cur].sort(sortFn),
}),
{}
);
};
const sorted = {
ungrouped: sections.ungrouped.sort(sortFn),
ungroupedSubsections: sortSubsection(sections.ungroupedSubsections),
sections: Object.keys(sections.sections).reduce<Record<string, Section>>(
(acc, cur) => ({
...acc,
[cur]: {
ungrouped: sections.sections[cur].ungrouped.sort(sortFn),
subsections: sortSubsection(sections.sections[cur].subsections),
},
}),
{}
),
};
return sorted;
};
/**
* Wrap CSF's `includeConditionalArg` in a try catch so that invalid
* conditionals don't break the entire UI. We can safely swallow the
* error because `includeConditionalArg` is also called in the preview
* in `prepareStory`, and that exception will be bubbled up into the
* UI in a red screen. Nevertheless, we log the error here just in case.
*/
const safeIncludeConditionalArg = (row: ArgType, args: Args, globals: Globals) => {
try {
return includeConditionalArg(row, args, globals);
} catch (err) {
once.warn(err.message);
return false;
}
};
/**
* Display the props for a component as a props table. Each row is a collection of
* ArgDefs, usually derived from docgen info for the component.
*/
export const ArgsTable: FC<ArgsTableProps> = (props) => {
const {
updateArgs,
resetArgs,
compact,
inAddonPanel,
initialExpandedArgs,
sort = 'none',
isLoading,
} = props;
if ('error' in props) {
const { error } = props;
return (
<EmptyBlock>
{error}
<Link href="http://storybook.js.org/docs/" target="_blank" withArrow>
Read the docs
</Link>
</EmptyBlock>
);
}
// If the story is loading, show a skeleton
// This happen when you load the manager and the story is not yet loaded
if (isLoading) return <Skeleton />;
const { rows, args, globals } = 'rows' in props && props;
const groups = groupRows(
pickBy(
rows,
(row) => !row?.table?.disable && safeIncludeConditionalArg(row, args || {}, globals || {})
),
sort
);
// If there are no controls, show the empty state
const hasNoUngrouped = groups.ungrouped.length === 0;
const hasNoSections = Object.entries(groups.sections).length === 0;
const hasNoUngroupedSubsections = Object.entries(groups.ungroupedSubsections).length === 0;
if (hasNoUngrouped && hasNoSections && hasNoUngroupedSubsections)
return <Empty inAddonPanel={inAddonPanel} />;
let colSpan = 1;
if (updateArgs) colSpan += 1;
if (!compact) colSpan += 2;
const expandable = Object.keys(groups.sections).length > 0;
const common = { updateArgs, compact, inAddonPanel, initialExpandedArgs };
return (
<ResetWrapper>
<TableWrapper {...{ compact, inAddonPanel }} className="docblock-argstable sb-unstyled">
<thead className="docblock-argstable-head">
<tr>
<th>
<span>Name</span>
</th>
{compact ? null : (
<th>
<span>Description</span>
</th>
)}
{compact ? null : (
<th>
<span>Default</span>
</th>
)}
{updateArgs ? (
<th>
<ControlHeadingWrapper>
Control{' '}
{!isLoading && resetArgs && (
<StyledIconButton onClick={() => resetArgs()} title="Reset controls">
<UndoIcon aria-hidden />
</StyledIconButton>
)}
</ControlHeadingWrapper>
</th>
) : null}
</tr>
</thead>
<tbody className="docblock-argstable-body">
{groups.ungrouped.map((row) => (
<ArgRow key={row.key} row={row} arg={args && args[row.key]} {...common} />
))}
{Object.entries(groups.ungroupedSubsections).map(([subcategory, subsection]) => (
<SectionRow key={subcategory} label={subcategory} level="subsection" colSpan={colSpan}>
{subsection.map((row) => (
<ArgRow
key={row.key}
row={row}
arg={args && args[row.key]}
expandable={expandable}
{...common}
/>
))}
</SectionRow>
))}
{Object.entries(groups.sections).map(([category, section]) => (
<SectionRow key={category} label={category} level="section" colSpan={colSpan}>
{section.ungrouped.map((row) => (
<ArgRow key={row.key} row={row} arg={args && args[row.key]} {...common} />
))}
{Object.entries(section.subsections).map(([subcategory, subsection]) => (
<SectionRow
key={subcategory}
label={subcategory}
level="subsection"
colSpan={colSpan}
>
{subsection.map((row) => (
<ArgRow
key={row.key}
row={row}
arg={args && args[row.key]}
expandable={expandable}
{...common}
/>
))}
</SectionRow>
))}
</SectionRow>
))}
</tbody>
</TableWrapper>
</ResetWrapper>
);
};
|
code/ui/blocks/src/components/ArgsTable/ArgsTable.tsx
| 1 |
https://github.com/storybookjs/storybook/commit/39e6fd82c4a39766bdfc66f4b67021b57339a58f
|
[
0.008109897375106812,
0.000642359082121402,
0.0001628576428629458,
0.00017298768216278404,
0.0013102329103276134
] |
{
"id": 5,
"code_window": [
" </>\n",
" )}\n",
" {!inAddonPanel && (\n",
" <Link\n",
" href=\"https://storybook.js.org/docs/react/essentials/controls\"\n",
" target=\"_blank\"\n",
" withArrow\n",
" >\n",
" Learn how to set that up\n",
" </Link>\n",
" )}\n",
" </Links>\n",
" </Wrapper>\n",
" );\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <Link href=\"https://storybook.js.org/docs/essentials/controls\" target=\"_blank\" withArrow>\n",
" <SupportIcon /> Learn how to set that up\n"
],
"file_path": "code/ui/blocks/src/components/ArgsTable/Empty.tsx",
"type": "replace",
"edit_start_line_idx": 103
}
|
---
title: 'Source'
---
<YouTubeCallout id="uAA1JvLcl-w" title="Avoid Documentation Nightmares with Storybook's Source Doc Block" params='start=136' />
The `Source` block is used to render a snippet of source code directly.

<!-- prettier-ignore-start -->
```md
{/* ButtonDocs.mdx */}
import { Meta, Source } from '@storybook/blocks';
import * as ButtonStories from './Button.stories';
<Meta of={ButtonStories} />
<Source of={ButtonStories.Primary} />
```
<!-- prettier-ignore-end -->
## Source
```js
import { Source } from '@storybook/blocks';
```
<details>
<summary>Configuring with props <strong>and</strong> parameters</summary>
ℹ️ Like most blocks, the `Source` block is configured with props in MDX. Many of those props derive their default value from a corresponding [parameter](../writing-stories/parameters.md) in the block's namespace, `parameters.docs.source`.
The following `language` configurations are equivalent:
<!-- prettier-ignore-start -->
<CodeSnippets
paths={[
'angular/api-doc-block-source-parameter.ts.mdx',
'web-components/api-doc-block-source-parameter.js.mdx',
'web-components/api-doc-block-source-parameter.ts.mdx',
'common/api-doc-block-source-parameter.js.mdx',
'common/api-doc-block-source-parameter.ts.mdx',
]}
/>
<!-- prettier-ignore-end -->
<!-- prettier-ignore-start -->
```md
{/* ButtonDocs.mdx */}
<Source of={ButtonStories.Basic} language="tsx" />
```
<!-- prettier-ignore-end -->
The example above applied the parameter at the [story](../writing-stories/parameters.md#story-parameters) level, but it could also be applied at the [component](../writing-stories/parameters.md#component-parameters) (or meta) level or [project](../writing-stories/parameters.md#global-parameters) level.
</details>
### `code`
Type: `string`
Default: `parameters.docs.source.code`
Provides the source code to be rendered.
<!-- prettier-ignore-start -->
```md
{/* ButtonDocs.mdx */}
import { Meta, Source } from '@storybook/blocks';
import * as ButtonStories from './Button.stories';
<Meta of={ButtonStories} />
<Source code={`const thisIsCustomSource = true;
if (isSyntaxHighlighted) {
console.log('syntax highlighting is working');
}`} />
```
<!-- prettier-ignore-end -->
### `dark`
Type: `boolean`
Default: `parameters.docs.source.dark`
Determines if the snippet is rendered in dark mode.
<Callout variant="info" icon="💡">
Light mode is only supported when the `Source` block is rendered independently. When rendered as part of a [`Canvas` block](./doc-block-canvas.md)—like it is in [autodocs](../writing-docs/autodocs.md)—it will always use dark mode.
</Callout>
<IfRenderer renderer={['angular', 'react', 'html', 'web-components' ]}>
### `excludeDecorators`
Type: `boolean`
Default: `parameters.docs.source.excludeDecorators`
Determines if [decorators](../writing-stories/decorators.md) are rendered in the source code snippet.
</IfRenderer>
### `format`
Type: `boolean | 'dedent' | BuiltInParserName`
Default: `parameters.docs.source.format` or `true`
Specifies the formatting used on source code. Both `true` and `'dedent'` have the same effect of removing any extraneous indentation. Supports all valid [prettier parser names](https://prettier.io/docs/en/configuration.html#setting-the-parserdocsenoptionshtmlparser-option).
### `language`
Type:
<!-- prettier-ignore-start -->
```ts
'jsextra' | 'jsx' | 'json' | 'yml' | 'md' | 'bash' | 'css' | 'html' | 'tsx' | 'typescript' | 'graphql'
```
<!-- prettier-ignore-end -->
Default: `parameters.docs.source.language` or `'jsx'`
Specifies the language used for syntax highlighting.
### `of`
Type: Story export
Specifies which story's source is rendered.
### `transform`
Type: `(code: string, storyContext: StoryContext) => string`
Default: `parameters.docs.source.transform`
A function to dynamically transform the source before being rendered, based on the original source and any story context necessary. The returned string is displayed as-is.
If both [`code`](#code) and `transform` are specified, `transform` will be ignored.
### `type`
Type: `'auto' | 'code' | 'dynamic'`
Default: `parameters.docs.source.type` or `'auto'`
Specifies how the source code is rendered.
- **auto**: Same as **dynamic**, if the story's `render` function accepts args inputs and **dynamic** is supported by the framework in use; otherwise same as **code**
- **code**: Renders the value of [`code` prop](#code), otherwise renders static story source
- **dynamic**: Renders the story source with dynamically updated arg values
<Callout variant="info" icon="💡">
Note that dynamic snippets will only work if the story uses [`args`](../writing-stories/args.md) and the [`Story` block](./doc-block-story.md) for that story is rendered along with the `Source` block.
</Callout>
|
docs/api/doc-block-source.md
| 0 |
https://github.com/storybookjs/storybook/commit/39e6fd82c4a39766bdfc66f4b67021b57339a58f
|
[
0.00017973488138522953,
0.0001669462799327448,
0.000161066695000045,
0.00016724351735319942,
0.000004234447260387242
] |
{
"id": 5,
"code_window": [
" </>\n",
" )}\n",
" {!inAddonPanel && (\n",
" <Link\n",
" href=\"https://storybook.js.org/docs/react/essentials/controls\"\n",
" target=\"_blank\"\n",
" withArrow\n",
" >\n",
" Learn how to set that up\n",
" </Link>\n",
" )}\n",
" </Links>\n",
" </Wrapper>\n",
" );\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <Link href=\"https://storybook.js.org/docs/essentials/controls\" target=\"_blank\" withArrow>\n",
" <SupportIcon /> Learn how to set that up\n"
],
"file_path": "code/ui/blocks/src/components/ArgsTable/Empty.tsx",
"type": "replace",
"edit_start_line_idx": 103
}
|
module.exports = require('./dist/preset');
|
code/frameworks/preact-vite/preset.js
| 0 |
https://github.com/storybookjs/storybook/commit/39e6fd82c4a39766bdfc66f4b67021b57339a58f
|
[
0.00017024599947035313,
0.00017024599947035313,
0.00017024599947035313,
0.00017024599947035313,
0
] |
{
"id": 5,
"code_window": [
" </>\n",
" )}\n",
" {!inAddonPanel && (\n",
" <Link\n",
" href=\"https://storybook.js.org/docs/react/essentials/controls\"\n",
" target=\"_blank\"\n",
" withArrow\n",
" >\n",
" Learn how to set that up\n",
" </Link>\n",
" )}\n",
" </Links>\n",
" </Wrapper>\n",
" );\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"replace",
"replace",
"replace",
"replace",
"replace",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" <Link href=\"https://storybook.js.org/docs/essentials/controls\" target=\"_blank\" withArrow>\n",
" <SupportIcon /> Learn how to set that up\n"
],
"file_path": "code/ui/blocks/src/components/ArgsTable/Empty.tsx",
"type": "replace",
"edit_start_line_idx": 103
}
|
```html
<!-- ApolloWrapperClient.vue -->
<template>
<div><slot /></div>
</template>
<script>
import { defineComponent, provide } from 'vue';
import { DefaultApolloClient } from '@vue/apollo-composable';
import { ApolloClient, createHttpLink, InMemoryCache } from '@apollo/client/core';
// Apollo client wrapper component that can be used within your app and Storybook
export default defineComponent({
name: 'WrapperComponent',
setup() {
const httpLink = createHttpLink({
// You should use an absolute URL here
uri: 'https://your-graphql-endpoint',
});
const cache = new InMemoryCache();
const mockedClient = new ApolloClient({
link: httpLink,
cache,
defaultOptions: {
watchQuery: {
fetchPolicy: 'no-cache',
errorPolicy: 'all',
},
query: {
fetchPolicy: 'no-cache',
errorPolicy: 'all',
},
},
});
provide(DefaultApolloClient, mockedClient);
},
});
</script>
```
|
docs/snippets/vue/apollo-wrapper-component.with-mock-implementation.3.js.mdx
| 0 |
https://github.com/storybookjs/storybook/commit/39e6fd82c4a39766bdfc66f4b67021b57339a58f
|
[
0.0006178398034535348,
0.00026496656937524676,
0.0001682667643763125,
0.00017338039469905198,
0.00017672778631094843
] |
{
"id": 0,
"code_window": [
" label: PropTypes.string,\n",
" hasCustomLabel: PropTypes.bool,\n",
" }),\n",
" defaultLabel: PropTypes.string,\n",
" onChange: PropTypes.func.isRequired,\n",
"};\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "superset-frontend/src/explore/components/AdhocMetricEditPopoverTitle.jsx",
"type": "replace",
"edit_start_line_idx": 28
}
|
/**
* 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, { ReactNode } from 'react';
import Popover from 'src/common/components/Popover';
import AdhocMetricEditPopoverTitle from 'src/explore/components/AdhocMetricEditPopoverTitle';
import AdhocMetricEditPopover from './AdhocMetricEditPopover';
import AdhocMetric from '../AdhocMetric';
import { savedMetricType } from '../types';
export type AdhocMetricPopoverTriggerProps = {
adhocMetric: AdhocMetric;
onMetricEdit: () => void;
columns: { column_name: string; type: string }[];
savedMetrics: savedMetricType[];
savedMetric: savedMetricType;
datasourceType: string;
children: ReactNode;
createNew?: boolean;
};
export type AdhocMetricPopoverTriggerState = {
popoverVisible: boolean;
title: { label: string; hasCustomLabel: boolean };
};
class AdhocMetricPopoverTrigger extends React.PureComponent<
AdhocMetricPopoverTriggerProps,
AdhocMetricPopoverTriggerState
> {
constructor(props: AdhocMetricPopoverTriggerProps) {
super(props);
this.onPopoverResize = this.onPopoverResize.bind(this);
this.onLabelChange = this.onLabelChange.bind(this);
this.closePopover = this.closePopover.bind(this);
this.togglePopover = this.togglePopover.bind(this);
this.state = {
popoverVisible: false,
title: {
label: props.adhocMetric.label,
hasCustomLabel: props.adhocMetric.hasCustomLabel,
},
};
}
onLabelChange(e: any) {
const label = e.target.value;
this.setState({
title: {
label: label || this.props.adhocMetric.label,
hasCustomLabel: !!label,
},
});
}
onPopoverResize() {
this.forceUpdate();
}
closePopover() {
this.togglePopover(false);
}
togglePopover(visible: boolean) {
this.setState({
popoverVisible: visible,
});
}
render() {
const { adhocMetric } = this.props;
const overlayContent = (
<AdhocMetricEditPopover
adhocMetric={adhocMetric}
title={this.state.title}
columns={this.props.columns}
savedMetrics={this.props.savedMetrics}
savedMetric={this.props.savedMetric}
datasourceType={this.props.datasourceType}
onResize={this.onPopoverResize}
onClose={this.closePopover}
onChange={this.props.onMetricEdit}
/>
);
const popoverTitle = (
<AdhocMetricEditPopoverTitle
title={this.state.title}
defaultLabel={adhocMetric.label}
onChange={this.onLabelChange}
/>
);
return (
<Popover
placement="right"
trigger="click"
content={overlayContent}
defaultVisible={this.state.popoverVisible}
visible={this.state.popoverVisible}
onVisibleChange={this.togglePopover}
title={popoverTitle}
destroyTooltipOnHide={this.props.createNew}
>
{this.props.children}
</Popover>
);
}
}
export default AdhocMetricPopoverTrigger;
|
superset-frontend/src/explore/components/AdhocMetricPopoverTrigger.tsx
| 1 |
https://github.com/apache/superset/commit/14ccbe43b3219f7c2bdea953d84a94da4b3cc2ef
|
[
0.0005377300549298525,
0.00021778781956527382,
0.00016428927483502775,
0.00017195641703438014,
0.00010572854080237448
] |
{
"id": 0,
"code_window": [
" label: PropTypes.string,\n",
" hasCustomLabel: PropTypes.bool,\n",
" }),\n",
" defaultLabel: PropTypes.string,\n",
" onChange: PropTypes.func.isRequired,\n",
"};\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "superset-frontend/src/explore/components/AdhocMetricEditPopoverTitle.jsx",
"type": "replace",
"edit_start_line_idx": 28
}
|
# 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.
"""form strip leading and trailing whitespace
Revision ID: 258b5280a45e
Revises: 11c737c17cc6
Create Date: 2019-09-19 13:40:25.293907
"""
import re
from alembic import op
from sqlalchemy import Column, Integer, String, Text
from sqlalchemy.ext.declarative import declarative_base
from superset import db
from superset.utils.core import MediumText
Base = declarative_base()
class BaseColumnMixin:
id = Column(Integer, primary_key=True)
column_name = Column(String(255))
description = Column(Text)
type = Column(String(32))
verbose_name = Column(String(1024))
class BaseDatasourceMixin:
id = Column(Integer, primary_key=True)
description = Column(Text)
class BaseMetricMixin:
id = Column(Integer, primary_key=True)
d3format = Column(String(128))
description = Column(Text)
metric_name = Column(String(512))
metric_type = Column(String(32))
verbose_name = Column(String(1024))
warning_text = Column(Text)
class Annotation(Base):
__tablename__ = "annotation"
id = Column(Integer, primary_key=True)
long_descr = Column(Text)
json_metadata = Column(Text)
short_descr = Column(String(500))
class Dashboard(Base):
__tablename__ = "dashboards"
id = Column(Integer, primary_key=True)
css = Column(Text)
dashboard_title = Column(String(500))
description = Column(Text)
json_metadata = Column(Text)
position_json = Column(MediumText())
slug = Column(String(255))
class Database(Base):
__tablename__ = "dbs"
id = Column(Integer, primary_key=True)
database_name = Column(String(250))
extra = Column(Text)
force_ctas_schema = Column(String(250))
sqlalchemy_uri = Column(String(1024))
verbose_name = Column(String(250))
class DruidCluster(Base):
__tablename__ = "clusters"
id = Column(Integer, primary_key=True)
broker_host = Column(String(255))
broker_endpoint = Column(String(255))
cluster_name = Column(String(250))
verbose_name = Column(String(250))
class DruidColumn(BaseColumnMixin, Base):
__tablename__ = "columns"
dimension_spec_json = Column(Text)
class DruidDatasource(BaseDatasourceMixin, Base):
__tablename__ = "datasources"
datasource_name = Column(String(255))
default_endpoint = Column(Text)
fetch_values_from = Column(String(100))
class DruidMetric(BaseMetricMixin, Base):
__tablename__ = "metrics"
json = Column(Text)
class Slice(Base):
__tablename__ = "slices"
id = Column(Integer, primary_key=True)
description = Column(Text)
params = Column(Text)
slice_name = Column(String(250))
viz_type = Column(String(250))
class SqlaTable(BaseDatasourceMixin, Base):
__tablename__ = "tables"
default_endpoint = Column(MediumText())
fetch_values_predicate = Column(String(1000))
main_dttm_col = Column(String(250))
schema = Column(String(255))
sql = Column(Text)
table_name = Column(String(250))
template_params = Column(Text)
class SqlMetric(BaseMetricMixin, Base):
__tablename__ = "sql_metrics"
expression = Column(Text)
class TableColumn(BaseColumnMixin, Base):
__tablename__ = "table_columns"
expression = Column(Text)
python_date_format = Column(String(255))
# revision identifiers, used by Alembic.
revision = "258b5280a45e"
down_revision = "11c737c17cc6"
def upgrade():
bind = op.get_bind()
session = db.Session(bind=bind)
tables = [
Annotation,
Dashboard,
Database,
DruidCluster,
DruidColumn,
DruidDatasource,
DruidMetric,
Slice,
SqlaTable,
SqlMetric,
TableColumn,
]
for table in tables:
for record in session.query(table).all():
for col in record.__table__.columns.values():
if not col.primary_key:
value = getattr(record, col.name)
if value is not None and re.search(r"^\s+|\s+$", value):
setattr(record, col.name, value.strip())
session.commit()
session.close()
def downgrade():
pass
|
superset/migrations/versions/258b5280a45e_form_strip_leading_and_trailing_whitespace.py
| 0 |
https://github.com/apache/superset/commit/14ccbe43b3219f7c2bdea953d84a94da4b3cc2ef
|
[
0.0017901686951518059,
0.0003272963222116232,
0.00016369430522900075,
0.00017377827316522598,
0.00037443573819473386
] |
{
"id": 0,
"code_window": [
" label: PropTypes.string,\n",
" hasCustomLabel: PropTypes.bool,\n",
" }),\n",
" defaultLabel: PropTypes.string,\n",
" onChange: PropTypes.func.isRequired,\n",
"};\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "superset-frontend/src/explore/components/AdhocMetricEditPopoverTitle.jsx",
"type": "replace",
"edit_start_line_idx": 28
}
|
/**
* 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 PropTypes from 'prop-types';
import SyntaxHighlighter from 'react-syntax-highlighter/dist/cjs/light';
import sql from 'react-syntax-highlighter/dist/cjs/languages/hljs/sql';
import github from 'react-syntax-highlighter/dist/cjs/styles/hljs/github';
import { t } from '@superset-ui/core';
import ModalTrigger from '../../components/ModalTrigger';
SyntaxHighlighter.registerLanguage('sql', sql);
const defaultProps = {
maxWidth: 50,
maxLines: 5,
shrink: false,
};
const propTypes = {
sql: PropTypes.string.isRequired,
rawSql: PropTypes.string,
maxWidth: PropTypes.number,
maxLines: PropTypes.number,
shrink: PropTypes.bool,
};
class HighlightedSql extends React.Component {
constructor(props) {
super(props);
this.state = {
modalBody: null,
};
}
shrinkSql() {
const ssql = this.props.sql || '';
let lines = ssql.split('\n');
if (lines.length >= this.props.maxLines) {
lines = lines.slice(0, this.props.maxLines);
lines.push('{...}');
}
return lines
.map(line => {
if (line.length > this.props.maxWidth) {
return `${line.slice(0, this.props.maxWidth)}{...}`;
}
return line;
})
.join('\n');
}
triggerNode() {
const shownSql = this.props.shrink
? this.shrinkSql(this.props.sql)
: this.props.sql;
return (
<SyntaxHighlighter language="sql" style={github}>
{shownSql}
</SyntaxHighlighter>
);
}
generateModal() {
let rawSql;
if (this.props.rawSql && this.props.rawSql !== this.props.sql) {
rawSql = (
<div>
<h4>{t('Raw SQL')}</h4>
<SyntaxHighlighter language="sql" style={github}>
{this.props.rawSql}
</SyntaxHighlighter>
</div>
);
}
this.setState({
modalBody: (
<div>
<h4>{t('Source SQL')}</h4>
<SyntaxHighlighter language="sql" style={github}>
{this.props.sql}
</SyntaxHighlighter>
{rawSql}
</div>
),
});
}
render() {
return (
<ModalTrigger
modalTitle={t('SQL')}
triggerNode={this.triggerNode()}
modalBody={this.state.modalBody}
beforeOpen={this.generateModal.bind(this)}
/>
);
}
}
HighlightedSql.propTypes = propTypes;
HighlightedSql.defaultProps = defaultProps;
export default HighlightedSql;
|
superset-frontend/src/SqlLab/components/HighlightedSql.jsx
| 0 |
https://github.com/apache/superset/commit/14ccbe43b3219f7c2bdea953d84a94da4b3cc2ef
|
[
0.002164622535929084,
0.00035467694397084415,
0.00016745159518904984,
0.00017065770225599408,
0.0005474213976413012
] |
{
"id": 0,
"code_window": [
" label: PropTypes.string,\n",
" hasCustomLabel: PropTypes.bool,\n",
" }),\n",
" defaultLabel: PropTypes.string,\n",
" onChange: PropTypes.func.isRequired,\n",
"};\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"replace",
"keep",
"keep",
"keep"
],
"after_edit": [],
"file_path": "superset-frontend/src/explore/components/AdhocMetricEditPopoverTitle.jsx",
"type": "replace",
"edit_start_line_idx": 28
}
|
/**
* 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 { mount } from 'enzyme';
import sinon from 'sinon';
import DeleteComponentButton from 'src/dashboard/components/DeleteComponentButton';
import HoverMenu from 'src/dashboard/components/menu/HoverMenu';
import DragDroppable from 'src/dashboard/components/dnd/DragDroppable';
import Divider from 'src/dashboard/components/gridComponents/Divider';
import newComponentFactory from 'src/dashboard/util/newComponentFactory';
import {
DIVIDER_TYPE,
DASHBOARD_GRID_TYPE,
} from 'src/dashboard/util/componentTypes';
import WithDragDropContext from 'spec/helpers/WithDragDropContext';
describe('Divider', () => {
const props = {
id: 'id',
parentId: 'parentId',
component: newComponentFactory(DIVIDER_TYPE),
depth: 1,
parentComponent: newComponentFactory(DASHBOARD_GRID_TYPE),
index: 0,
editMode: false,
handleComponentDrop() {},
deleteComponent() {},
};
function setup(overrideProps) {
// We have to wrap provide DragDropContext for the underlying DragDroppable
// otherwise we cannot assert on DragDroppable children
const wrapper = mount(
<WithDragDropContext>
<Divider {...props} {...overrideProps} />
</WithDragDropContext>,
);
return wrapper;
}
it('should render a DragDroppable', () => {
const wrapper = setup();
expect(wrapper.find(DragDroppable)).toExist();
});
it('should render a div with class "dashboard-component-divider"', () => {
const wrapper = setup();
expect(wrapper.find('.dashboard-component-divider')).toExist();
});
it('should render a HoverMenu with DeleteComponentButton in editMode', () => {
let wrapper = setup();
expect(wrapper.find(HoverMenu)).not.toExist();
expect(wrapper.find(DeleteComponentButton)).not.toExist();
// we cannot set props on the Divider because of the WithDragDropContext wrapper
wrapper = setup({ editMode: true });
expect(wrapper.find(HoverMenu)).toExist();
expect(wrapper.find(DeleteComponentButton)).toExist();
});
it('should call deleteComponent when deleted', () => {
const deleteComponent = sinon.spy();
const wrapper = setup({ editMode: true, deleteComponent });
wrapper.find(DeleteComponentButton).simulate('click');
expect(deleteComponent.callCount).toBe(1);
});
});
|
superset-frontend/spec/javascripts/dashboard/components/gridComponents/Divider_spec.jsx
| 0 |
https://github.com/apache/superset/commit/14ccbe43b3219f7c2bdea953d84a94da4b3cc2ef
|
[
0.0001778812729753554,
0.0001736335107125342,
0.0001700591092230752,
0.000173669119249098,
0.0000023805439468560508
] |
{
"id": 1,
"code_window": [
"export type AdhocMetricPopoverTriggerState = {\n",
" popoverVisible: boolean;\n",
" title: { label: string; hasCustomLabel: boolean };\n",
"};\n",
"\n",
"class AdhocMetricPopoverTrigger extends React.PureComponent<\n",
" AdhocMetricPopoverTriggerProps,\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" labelModified: boolean;\n"
],
"file_path": "superset-frontend/src/explore/components/AdhocMetricPopoverTrigger.tsx",
"type": "add",
"edit_start_line_idx": 39
}
|
/**
* 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, { ReactNode } from 'react';
import Popover from 'src/common/components/Popover';
import AdhocMetricEditPopoverTitle from 'src/explore/components/AdhocMetricEditPopoverTitle';
import AdhocMetricEditPopover from './AdhocMetricEditPopover';
import AdhocMetric from '../AdhocMetric';
import { savedMetricType } from '../types';
export type AdhocMetricPopoverTriggerProps = {
adhocMetric: AdhocMetric;
onMetricEdit: () => void;
columns: { column_name: string; type: string }[];
savedMetrics: savedMetricType[];
savedMetric: savedMetricType;
datasourceType: string;
children: ReactNode;
createNew?: boolean;
};
export type AdhocMetricPopoverTriggerState = {
popoverVisible: boolean;
title: { label: string; hasCustomLabel: boolean };
};
class AdhocMetricPopoverTrigger extends React.PureComponent<
AdhocMetricPopoverTriggerProps,
AdhocMetricPopoverTriggerState
> {
constructor(props: AdhocMetricPopoverTriggerProps) {
super(props);
this.onPopoverResize = this.onPopoverResize.bind(this);
this.onLabelChange = this.onLabelChange.bind(this);
this.closePopover = this.closePopover.bind(this);
this.togglePopover = this.togglePopover.bind(this);
this.state = {
popoverVisible: false,
title: {
label: props.adhocMetric.label,
hasCustomLabel: props.adhocMetric.hasCustomLabel,
},
};
}
onLabelChange(e: any) {
const label = e.target.value;
this.setState({
title: {
label: label || this.props.adhocMetric.label,
hasCustomLabel: !!label,
},
});
}
onPopoverResize() {
this.forceUpdate();
}
closePopover() {
this.togglePopover(false);
}
togglePopover(visible: boolean) {
this.setState({
popoverVisible: visible,
});
}
render() {
const { adhocMetric } = this.props;
const overlayContent = (
<AdhocMetricEditPopover
adhocMetric={adhocMetric}
title={this.state.title}
columns={this.props.columns}
savedMetrics={this.props.savedMetrics}
savedMetric={this.props.savedMetric}
datasourceType={this.props.datasourceType}
onResize={this.onPopoverResize}
onClose={this.closePopover}
onChange={this.props.onMetricEdit}
/>
);
const popoverTitle = (
<AdhocMetricEditPopoverTitle
title={this.state.title}
defaultLabel={adhocMetric.label}
onChange={this.onLabelChange}
/>
);
return (
<Popover
placement="right"
trigger="click"
content={overlayContent}
defaultVisible={this.state.popoverVisible}
visible={this.state.popoverVisible}
onVisibleChange={this.togglePopover}
title={popoverTitle}
destroyTooltipOnHide={this.props.createNew}
>
{this.props.children}
</Popover>
);
}
}
export default AdhocMetricPopoverTrigger;
|
superset-frontend/src/explore/components/AdhocMetricPopoverTrigger.tsx
| 1 |
https://github.com/apache/superset/commit/14ccbe43b3219f7c2bdea953d84a94da4b3cc2ef
|
[
0.9989533424377441,
0.3819125294685364,
0.00016942979709710926,
0.018995817750692368,
0.4724620282649994
] |
{
"id": 1,
"code_window": [
"export type AdhocMetricPopoverTriggerState = {\n",
" popoverVisible: boolean;\n",
" title: { label: string; hasCustomLabel: boolean };\n",
"};\n",
"\n",
"class AdhocMetricPopoverTrigger extends React.PureComponent<\n",
" AdhocMetricPopoverTriggerProps,\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" labelModified: boolean;\n"
],
"file_path": "superset-frontend/src/explore/components/AdhocMetricPopoverTrigger.tsx",
"type": "add",
"edit_start_line_idx": 39
}
|
---
name: Extra Database Settings
menu: Connecting to Databases
route: /docs/databases/extra-settings
index: 40
version: 1
---
## Extra Database Settings
### Deeper SQLAlchemy Integration
It is possible to tweak the database connection information using the parameters exposed by
SQLAlchemy. In the **Database edit** view, you can edit the **Extra** field as a JSON blob.
This JSON string contains extra configuration elements. The `engine_params` object gets unpacked
into the `sqlalchemy.create_engine` call, while the `metadata_params` get unpacked into the
`sqlalchemy.MetaData` call. Refer to the SQLAlchemy docs for more information.
### Schemas
Databases like Postgres and Redshift use the **schema** as the logical entity on top of the
**database**. For Superset to connect to a specific schema, you can set the **schema** parameter in
the **Edit Tables** form (Sources > Tables > Edit record).
### External Password Store for SQLAlchemy Connections
Superset can be configured to use an external store for database passwords. This is useful if you a
running a custom secret distribution framework and do not wish to store secrets in Superset’s meta
database.
Example: Write a function that takes a single argument of type `sqla.engine.url` and returns the
password for the given connection string. Then set `SQLALCHEMY_CUSTOM_PASSWORD_STORE` in your config
file to point to that function.
```python
def example_lookup_password(url):
secret = <<get password from external framework>>
return 'secret'
SQLALCHEMY_CUSTOM_PASSWORD_STORE = example_lookup_password
```
A common pattern is to use environment variables to make secrets available.
`SQLALCHEMY_CUSTOM_PASSWORD_STORE` can also be used for that purpose.
```python
def example_password_as_env_var(url):
# assuming the uri looks like
# mysql://localhost?superset_user:{SUPERSET_PASSWORD}
return url.password.format(os.environ)
SQLALCHEMY_CUSTOM_PASSWORD_STORE = example_password_as_env_var
```
### SSL Access to Databases
You can use the `Extra` field in the **Edit Databases** form to configure SSL:
```JSON
{
"metadata_params": {},
"engine_params": {
"connect_args":{
"sslmode":"require",
"sslrootcert": "/path/to/my/pem"
}
}
}
```
|
docs/src/pages/docs/Connecting to Databases/extra-settings.mdx
| 0 |
https://github.com/apache/superset/commit/14ccbe43b3219f7c2bdea953d84a94da4b3cc2ef
|
[
0.0004268803750164807,
0.00021466998441610485,
0.0001654396764934063,
0.00017017048958223313,
0.0000854902173159644
] |
{
"id": 1,
"code_window": [
"export type AdhocMetricPopoverTriggerState = {\n",
" popoverVisible: boolean;\n",
" title: { label: string; hasCustomLabel: boolean };\n",
"};\n",
"\n",
"class AdhocMetricPopoverTrigger extends React.PureComponent<\n",
" AdhocMetricPopoverTriggerProps,\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" labelModified: boolean;\n"
],
"file_path": "superset-frontend/src/explore/components/AdhocMetricPopoverTrigger.tsx",
"type": "add",
"edit_start_line_idx": 39
}
|
# 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.
# pylint: disable=too-few-public-methods,invalid-name
from dataclasses import dataclass # pylint: disable=wrong-import-order
from enum import Enum
from typing import Any, Dict, Optional
from flask_babel import gettext as _
class SupersetErrorType(str, Enum):
"""
Types of errors that can exist within Superset.
Keep in sync with superset-frontend/src/components/ErrorMessage/types.ts
and docs/src/pages/docs/Miscellaneous/issue_codes.mdx
"""
# Frontend errors
FRONTEND_CSRF_ERROR = "FRONTEND_CSRF_ERROR"
FRONTEND_NETWORK_ERROR = "FRONTEND_NETWORK_ERROR"
FRONTEND_TIMEOUT_ERROR = "FRONTEND_TIMEOUT_ERROR"
# DB Engine errors
GENERIC_DB_ENGINE_ERROR = "GENERIC_DB_ENGINE_ERROR"
COLUMN_DOES_NOT_EXIST_ERROR = "COLUMN_DOES_NOT_EXIST_ERROR"
TABLE_DOES_NOT_EXIST_ERROR = "TABLE_DOES_NOT_EXIST_ERROR"
# Viz errors
VIZ_GET_DF_ERROR = "VIZ_GET_DF_ERROR"
UNKNOWN_DATASOURCE_TYPE_ERROR = "UNKNOWN_DATASOURCE_TYPE_ERROR"
FAILED_FETCHING_DATASOURCE_INFO_ERROR = "FAILED_FETCHING_DATASOURCE_INFO_ERROR"
# Security access errors
TABLE_SECURITY_ACCESS_ERROR = "TABLE_SECURITY_ACCESS_ERROR"
DATASOURCE_SECURITY_ACCESS_ERROR = "DATASOURCE_SECURITY_ACCESS_ERROR"
MISSING_OWNERSHIP_ERROR = "MISSING_OWNERSHIP_ERROR"
# Other errors
BACKEND_TIMEOUT_ERROR = "BACKEND_TIMEOUT_ERROR"
# Sql Lab errors
MISSING_TEMPLATE_PARAMS_ERROR = "MISSING_TEMPLATE_PARAMS_ERROR"
ERROR_TYPES_TO_ISSUE_CODES_MAPPING = {
SupersetErrorType.BACKEND_TIMEOUT_ERROR: [
{
"code": 1000,
"message": _("Issue 1000 - The datasource is too large to query."),
},
{
"code": 1001,
"message": _("Issue 1001 - The database is under an unusual load."),
},
],
SupersetErrorType.GENERIC_DB_ENGINE_ERROR: [
{
"code": 1002,
"message": _("Issue 1002 - The database returned an unexpected error."),
}
],
SupersetErrorType.COLUMN_DOES_NOT_EXIST_ERROR: [
{
"code": 1003,
"message": _(
"Issue 1003 - There is a syntax error in the SQL query. "
"Perhaps there was a misspelling or a typo."
),
},
{
"code": 1004,
"message": _(
"Issue 1004 - The column was deleted or renamed in the database."
),
},
],
SupersetErrorType.TABLE_DOES_NOT_EXIST_ERROR: [
{
"code": 1003,
"message": _(
"Issue 1003 - There is a syntax error in the SQL query. "
"Perhaps there was a misspelling or a typo."
),
},
{
"code": 1005,
"message": _(
"Issue 1005 - The table was deleted or renamed in the database."
),
},
],
SupersetErrorType.MISSING_TEMPLATE_PARAMS_ERROR: [
{
"code": 1006,
"message": _(
"Issue 1006 - One or more parameters specified in the query are "
"missing."
),
},
],
}
class ErrorLevel(str, Enum):
"""
Levels of errors that can exist within Superset.
Keep in sync with superset-frontend/src/components/ErrorMessage/types.ts
"""
INFO = "info"
WARNING = "warning"
ERROR = "error"
@dataclass
class SupersetError:
"""
An error that is returned to a client.
"""
message: str
error_type: SupersetErrorType
level: ErrorLevel
extra: Optional[Dict[str, Any]] = None
def __post_init__(self) -> None:
"""
Mutates the extra params with user facing error codes that map to backend
errors.
"""
issue_codes = ERROR_TYPES_TO_ISSUE_CODES_MAPPING.get(self.error_type)
if issue_codes:
self.extra = self.extra or {}
self.extra.update({"issue_codes": issue_codes})
|
superset/errors.py
| 0 |
https://github.com/apache/superset/commit/14ccbe43b3219f7c2bdea953d84a94da4b3cc2ef
|
[
0.0012713075848296285,
0.0002857256622519344,
0.0001626825687708333,
0.00017384439706802368,
0.0002761882496997714
] |
{
"id": 1,
"code_window": [
"export type AdhocMetricPopoverTriggerState = {\n",
" popoverVisible: boolean;\n",
" title: { label: string; hasCustomLabel: boolean };\n",
"};\n",
"\n",
"class AdhocMetricPopoverTrigger extends React.PureComponent<\n",
" AdhocMetricPopoverTriggerProps,\n"
],
"labels": [
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" labelModified: boolean;\n"
],
"file_path": "superset-frontend/src/explore/components/AdhocMetricPopoverTrigger.tsx",
"type": "add",
"edit_start_line_idx": 39
}
|
# 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 List, Optional
from flask_appbuilder.security.sqla.models import User
from superset.annotation_layers.annotations.commands.exceptions import (
AnnotationBulkDeleteFailedError,
AnnotationNotFoundError,
)
from superset.annotation_layers.annotations.dao import AnnotationDAO
from superset.commands.base import BaseCommand
from superset.dao.exceptions import DAODeleteFailedError
from superset.models.annotations import Annotation
logger = logging.getLogger(__name__)
class BulkDeleteAnnotationCommand(BaseCommand):
def __init__(self, user: User, model_ids: List[int]):
self._actor = user
self._model_ids = model_ids
self._models: Optional[List[Annotation]] = None
def run(self) -> None:
self.validate()
try:
AnnotationDAO.bulk_delete(self._models)
return None
except DAODeleteFailedError as ex:
logger.exception(ex.exception)
raise AnnotationBulkDeleteFailedError()
def validate(self) -> None:
# Validate/populate model exists
self._models = AnnotationDAO.find_by_ids(self._model_ids)
if not self._models or len(self._models) != len(self._model_ids):
raise AnnotationNotFoundError()
|
superset/annotation_layers/annotations/commands/bulk_delete.py
| 0 |
https://github.com/apache/superset/commit/14ccbe43b3219f7c2bdea953d84a94da4b3cc2ef
|
[
0.00017804469098336995,
0.000173615975654684,
0.00016559907817281783,
0.0001745265326462686,
0.000004250223810231546
] |
{
"id": 2,
"code_window": [
" title: {\n",
" label: props.adhocMetric.label,\n",
" hasCustomLabel: props.adhocMetric.hasCustomLabel,\n",
" },\n",
" };\n",
" }\n",
"\n",
" onLabelChange(e: any) {\n",
" const label = e.target.value;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" labelModified: false,\n"
],
"file_path": "superset-frontend/src/explore/components/AdhocMetricPopoverTrigger.tsx",
"type": "add",
"edit_start_line_idx": 57
}
|
/**
* 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, { ReactNode } from 'react';
import Popover from 'src/common/components/Popover';
import AdhocMetricEditPopoverTitle from 'src/explore/components/AdhocMetricEditPopoverTitle';
import AdhocMetricEditPopover from './AdhocMetricEditPopover';
import AdhocMetric from '../AdhocMetric';
import { savedMetricType } from '../types';
export type AdhocMetricPopoverTriggerProps = {
adhocMetric: AdhocMetric;
onMetricEdit: () => void;
columns: { column_name: string; type: string }[];
savedMetrics: savedMetricType[];
savedMetric: savedMetricType;
datasourceType: string;
children: ReactNode;
createNew?: boolean;
};
export type AdhocMetricPopoverTriggerState = {
popoverVisible: boolean;
title: { label: string; hasCustomLabel: boolean };
};
class AdhocMetricPopoverTrigger extends React.PureComponent<
AdhocMetricPopoverTriggerProps,
AdhocMetricPopoverTriggerState
> {
constructor(props: AdhocMetricPopoverTriggerProps) {
super(props);
this.onPopoverResize = this.onPopoverResize.bind(this);
this.onLabelChange = this.onLabelChange.bind(this);
this.closePopover = this.closePopover.bind(this);
this.togglePopover = this.togglePopover.bind(this);
this.state = {
popoverVisible: false,
title: {
label: props.adhocMetric.label,
hasCustomLabel: props.adhocMetric.hasCustomLabel,
},
};
}
onLabelChange(e: any) {
const label = e.target.value;
this.setState({
title: {
label: label || this.props.adhocMetric.label,
hasCustomLabel: !!label,
},
});
}
onPopoverResize() {
this.forceUpdate();
}
closePopover() {
this.togglePopover(false);
}
togglePopover(visible: boolean) {
this.setState({
popoverVisible: visible,
});
}
render() {
const { adhocMetric } = this.props;
const overlayContent = (
<AdhocMetricEditPopover
adhocMetric={adhocMetric}
title={this.state.title}
columns={this.props.columns}
savedMetrics={this.props.savedMetrics}
savedMetric={this.props.savedMetric}
datasourceType={this.props.datasourceType}
onResize={this.onPopoverResize}
onClose={this.closePopover}
onChange={this.props.onMetricEdit}
/>
);
const popoverTitle = (
<AdhocMetricEditPopoverTitle
title={this.state.title}
defaultLabel={adhocMetric.label}
onChange={this.onLabelChange}
/>
);
return (
<Popover
placement="right"
trigger="click"
content={overlayContent}
defaultVisible={this.state.popoverVisible}
visible={this.state.popoverVisible}
onVisibleChange={this.togglePopover}
title={popoverTitle}
destroyTooltipOnHide={this.props.createNew}
>
{this.props.children}
</Popover>
);
}
}
export default AdhocMetricPopoverTrigger;
|
superset-frontend/src/explore/components/AdhocMetricPopoverTrigger.tsx
| 1 |
https://github.com/apache/superset/commit/14ccbe43b3219f7c2bdea953d84a94da4b3cc2ef
|
[
0.9982342720031738,
0.2751408815383911,
0.0001669153425609693,
0.0019053320866078138,
0.42264020442962646
] |
{
"id": 2,
"code_window": [
" title: {\n",
" label: props.adhocMetric.label,\n",
" hasCustomLabel: props.adhocMetric.hasCustomLabel,\n",
" },\n",
" };\n",
" }\n",
"\n",
" onLabelChange(e: any) {\n",
" const label = e.target.value;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" labelModified: false,\n"
],
"file_path": "superset-frontend/src/explore/components/AdhocMetricPopoverTrigger.tsx",
"type": "add",
"edit_start_line_idx": 57
}
|
# SHA1:4cc294ed9d355a099d37603d7e209d3b85e4f421
#
# This file is autogenerated by pip-compile-multi
# To update, run:
#
# pip-compile-multi
#
-r development.txt
-e file:. # via -r requirements/base.in
# The following packages are considered to be unsafe in a requirements file:
# setuptools
|
requirements/local.txt
| 0 |
https://github.com/apache/superset/commit/14ccbe43b3219f7c2bdea953d84a94da4b3cc2ef
|
[
0.00016894328291527927,
0.00016868086822796613,
0.000168418453540653,
0.00016868086822796613,
2.6241468731313944e-7
] |
{
"id": 2,
"code_window": [
" title: {\n",
" label: props.adhocMetric.label,\n",
" hasCustomLabel: props.adhocMetric.hasCustomLabel,\n",
" },\n",
" };\n",
" }\n",
"\n",
" onLabelChange(e: any) {\n",
" const label = e.target.value;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" labelModified: false,\n"
],
"file_path": "superset-frontend/src/explore/components/AdhocMetricPopoverTrigger.tsx",
"type": "add",
"edit_start_line_idx": 57
}
|
#
# 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.
#
FROM python:3.7-buster
RUN useradd --user-group --create-home --no-log-init --shell /bin/bash superset
# Configure environment
ENV LANG=C.UTF-8 \
LC_ALL=C.UTF-8
RUN apt-get update -y
# Install dependencies to fix `curl https support error` and `elaying package configuration warning`
RUN apt-get install -y apt-transport-https apt-utils
# Install superset dependencies
# https://superset.apache.org/docs/installation/installing-superset-from-scratch
RUN apt-get install -y build-essential libssl-dev \
libffi-dev python3-dev libsasl2-dev libldap2-dev libxi-dev
# Install nodejs for custom build
# https://nodejs.org/en/download/package-manager/
RUN curl -sL https://deb.nodesource.com/setup_12.x | bash - \
&& apt-get install -y nodejs
RUN mkdir -p /home/superset
RUN chown superset /home/superset
WORKDIR /home/superset
ARG VERSION
# Can fetch source from svn or copy tarball from local mounted directory
RUN svn co https://dist.apache.org/repos/dist/dev/superset/$VERSION ./
RUN tar -xvf *.tar.gz
WORKDIR apache-superset-$VERSION
RUN cd superset-frontend \
&& npm ci \
&& npm run build \
&& rm -rf node_modules
WORKDIR /home/superset/apache-superset-$VERSION
RUN pip install --upgrade setuptools pip \
&& pip install -r requirements.txt \
&& pip install --no-cache-dir .
RUN flask fab babel-compile --target superset/translations
ENV PATH=/home/superset/superset/bin:$PATH \
PYTHONPATH=/home/superset/superset/:$PYTHONPATH
COPY from_tarball_entrypoint.sh /entrypoint.sh
ENTRYPOINT ["/entrypoint.sh"]
|
RELEASING/Dockerfile.from_svn_tarball
| 0 |
https://github.com/apache/superset/commit/14ccbe43b3219f7c2bdea953d84a94da4b3cc2ef
|
[
0.00017712675617076457,
0.00016986015543807298,
0.00016369788500014693,
0.00016873767890501767,
0.000004932763204124058
] |
{
"id": 2,
"code_window": [
" title: {\n",
" label: props.adhocMetric.label,\n",
" hasCustomLabel: props.adhocMetric.hasCustomLabel,\n",
" },\n",
" };\n",
" }\n",
"\n",
" onLabelChange(e: any) {\n",
" const label = e.target.value;\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep",
"keep",
"keep"
],
"after_edit": [
" labelModified: false,\n"
],
"file_path": "superset-frontend/src/explore/components/AdhocMetricPopoverTrigger.tsx",
"type": "add",
"edit_start_line_idx": 57
}
|
<!--
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.
-->
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" clip-rule="evenodd" d="M16.9997 9.17C16.6097 8.78228 15.9797 8.78228 15.5897 9.17L11.9997 12.71L8.4597 9.17C8.06967 8.78228 7.43974 8.78228 7.0497 9.17C6.86039 9.35777 6.75391 9.61337 6.75391 9.88C6.75391 10.1466 6.86039 10.4022 7.0497 10.59L11.2897 14.83C11.4775 15.0193 11.7331 15.1258 11.9997 15.1258C12.2663 15.1258 12.5219 15.0193 12.7097 14.83L16.9997 10.59C17.189 10.4022 17.2955 10.1466 17.2955 9.88C17.2955 9.61337 17.189 9.35777 16.9997 9.17Z" fill="currentColor"/>
</svg>
|
superset-frontend/images/icons/caret_down.svg
| 0 |
https://github.com/apache/superset/commit/14ccbe43b3219f7c2bdea953d84a94da4b3cc2ef
|
[
0.0001789967209333554,
0.00017724826466292143,
0.00017611680959817022,
0.00017663124890532345,
0.0000012540598390842206
] |
{
"id": 3,
"code_window": [
" title: {\n",
" label: label || this.props.adhocMetric.label,\n",
" hasCustomLabel: !!label,\n",
" },\n",
" });\n",
" }\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" labelModified: true,\n"
],
"file_path": "superset-frontend/src/explore/components/AdhocMetricPopoverTrigger.tsx",
"type": "add",
"edit_start_line_idx": 67
}
|
/**
* 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, { ReactNode } from 'react';
import Popover from 'src/common/components/Popover';
import AdhocMetricEditPopoverTitle from 'src/explore/components/AdhocMetricEditPopoverTitle';
import AdhocMetricEditPopover from './AdhocMetricEditPopover';
import AdhocMetric from '../AdhocMetric';
import { savedMetricType } from '../types';
export type AdhocMetricPopoverTriggerProps = {
adhocMetric: AdhocMetric;
onMetricEdit: () => void;
columns: { column_name: string; type: string }[];
savedMetrics: savedMetricType[];
savedMetric: savedMetricType;
datasourceType: string;
children: ReactNode;
createNew?: boolean;
};
export type AdhocMetricPopoverTriggerState = {
popoverVisible: boolean;
title: { label: string; hasCustomLabel: boolean };
};
class AdhocMetricPopoverTrigger extends React.PureComponent<
AdhocMetricPopoverTriggerProps,
AdhocMetricPopoverTriggerState
> {
constructor(props: AdhocMetricPopoverTriggerProps) {
super(props);
this.onPopoverResize = this.onPopoverResize.bind(this);
this.onLabelChange = this.onLabelChange.bind(this);
this.closePopover = this.closePopover.bind(this);
this.togglePopover = this.togglePopover.bind(this);
this.state = {
popoverVisible: false,
title: {
label: props.adhocMetric.label,
hasCustomLabel: props.adhocMetric.hasCustomLabel,
},
};
}
onLabelChange(e: any) {
const label = e.target.value;
this.setState({
title: {
label: label || this.props.adhocMetric.label,
hasCustomLabel: !!label,
},
});
}
onPopoverResize() {
this.forceUpdate();
}
closePopover() {
this.togglePopover(false);
}
togglePopover(visible: boolean) {
this.setState({
popoverVisible: visible,
});
}
render() {
const { adhocMetric } = this.props;
const overlayContent = (
<AdhocMetricEditPopover
adhocMetric={adhocMetric}
title={this.state.title}
columns={this.props.columns}
savedMetrics={this.props.savedMetrics}
savedMetric={this.props.savedMetric}
datasourceType={this.props.datasourceType}
onResize={this.onPopoverResize}
onClose={this.closePopover}
onChange={this.props.onMetricEdit}
/>
);
const popoverTitle = (
<AdhocMetricEditPopoverTitle
title={this.state.title}
defaultLabel={adhocMetric.label}
onChange={this.onLabelChange}
/>
);
return (
<Popover
placement="right"
trigger="click"
content={overlayContent}
defaultVisible={this.state.popoverVisible}
visible={this.state.popoverVisible}
onVisibleChange={this.togglePopover}
title={popoverTitle}
destroyTooltipOnHide={this.props.createNew}
>
{this.props.children}
</Popover>
);
}
}
export default AdhocMetricPopoverTrigger;
|
superset-frontend/src/explore/components/AdhocMetricPopoverTrigger.tsx
| 1 |
https://github.com/apache/superset/commit/14ccbe43b3219f7c2bdea953d84a94da4b3cc2ef
|
[
0.9674829244613647,
0.07943275570869446,
0.00016458264144603163,
0.0009603190701454878,
0.2566560208797455
] |
{
"id": 3,
"code_window": [
" title: {\n",
" label: label || this.props.adhocMetric.label,\n",
" hasCustomLabel: !!label,\n",
" },\n",
" });\n",
" }\n",
"\n"
],
"labels": [
"keep",
"keep",
"keep",
"add",
"keep",
"keep",
"keep"
],
"after_edit": [
" labelModified: true,\n"
],
"file_path": "superset-frontend/src/explore/components/AdhocMetricPopoverTrigger.tsx",
"type": "add",
"edit_start_line_idx": 67
}
|
/**
* 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.
*/
export { CommonFrame } from './CommonFrame';
export { CalendarFrame } from './CalendarFrame';
export { CustomFrame } from './CustomFrame';
export { AdvancedFrame } from './AdvancedFrame';
|
superset-frontend/src/explore/components/controls/DateFilterControl/frame/index.ts
| 0 |
https://github.com/apache/superset/commit/14ccbe43b3219f7c2bdea953d84a94da4b3cc2ef
|
[
0.00022777145204599947,
0.00019206875003874302,
0.00017410369764547795,
0.0001743310858728364,
0.000025245795768569224
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.