text stringlengths 9 39.2M | dir stringlengths 26 295 | lang stringclasses 185
values | created_date timestamp[us] | updated_date timestamp[us] | repo_name stringlengths 1 97 | repo_full_name stringlengths 7 106 | star int64 1k 183k | len_tokens int64 1 13.8M |
|---|---|---|---|---|---|---|---|---|
```xml
/* tslint:disable:no-unused-variable */
import { FeedLinkerComponent } from './feed-linker.component';
import { TestBed, async } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
describe('Component: FeedLinker', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
RouterTestingModule
],
declarations: [
FeedLinkerComponent
]
});
});
it('should create an instance', () => {
const fixture = TestBed.createComponent(FeedLinkerComponent);
const component = fixture.debugElement.componentInstance;
expect(component).toBeTruthy();
});
it('should call generateAllShards() when useAll is true', async(() => {
const fixture = TestBed.createComponent(FeedLinkerComponent);
const component = fixture.debugElement.componentInstance;
component.useAll = true;
component.text = 'loklak @fossasia #loklak path_to_url
component.ngOnInit();
expect(component.shardArray.length).toBe(4);
}));
it('should call generateShards() when useAll is false', async(() => {
const fixture = TestBed.createComponent(FeedLinkerComponent);
const component = fixture.debugElement.componentInstance;
component.useAll = false;
component.hashtags = [
'FOSSASIA',
'loklak'
];
component.mentions = [
'loklak'
];
component.links = [
'path_to_url
'path_to_url
];
component.text = 'loklak @fossasia #loklak path_to_url
component.ngOnInit();
expect(component.shardArray.length).toBe(4);
}));
});
``` | /content/code_sandbox/src/app/feed/feed-linker/feed-linker.component.spec.ts | xml | 2016-09-20T13:50:42 | 2024-08-06T13:58:18 | loklak_search | fossasia/loklak_search | 1,829 | 373 |
```xml
export * from './WebCamDialog';
export * from './WebCamDialog.types';
``` | /content/code_sandbox/samples/react-smart-profile-photo-editor/src/webparts/profilePhotoEditor/components/WebCamDialog/index.ts | xml | 2016-08-30T17:21:43 | 2024-08-16T18:41:32 | sp-dev-fx-webparts | pnp/sp-dev-fx-webparts | 2,027 | 18 |
```xml
import { clearLongTimeout, setLongTimeout } from "long-settimeout";
import React, { FunctionComponent, useEffect, useState } from "react";
interface Props {
ms?: number;
children: React.ReactNode;
}
const Delay: FunctionComponent<Props> = ({ ms = 500, children }) => {
const [render, setRender] = useState<boolean>(false);
useEffect(() => {
const timeout = setLongTimeout(() => {
setRender(true);
}, ms);
return () => {
clearLongTimeout(timeout);
};
}, [ms]);
if (!render) {
return null;
}
return <>{children}</>;
};
export default Delay;
``` | /content/code_sandbox/client/src/core/client/ui/components/v2/Delay/Delay.tsx | xml | 2016-10-31T16:14:05 | 2024-08-06T16:15:57 | talk | coralproject/talk | 1,881 | 145 |
```xml
<vector xmlns:android="path_to_url"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24.0"
android:viewportHeight="24.0">
<path
android:fillColor="#FF000000"
android:pathData="M12,8c1.1,0 2,-0.9 2,-2s-0.9,-2 -2,-2 -2,0.9 -2,2 0.9,2 2,2zM12,10c-1.1,0 -2,0.9 -2,2s0.9,2 2,2 2,-0.9 2,-2 -0.9,-2 -2,-2zM12,16c-1.1,0 -2,0.9 -2,2s0.9,2 2,2 2,-0.9 2,-2 -0.9,-2 -2,-2z" />
</vector>
``` | /content/code_sandbox/demo/src/main/res/drawable/ic_more.xml | xml | 2016-10-28T04:13:42 | 2024-08-02T07:46:08 | RxDownload | ssseasonnn/RxDownload | 4,135 | 224 |
```xml
<vector android:height="153.6dp" android:viewportHeight="400"
android:viewportWidth="625" android:width="240dp" xmlns:android="path_to_url">
<path android:fillColor="#032ea1" android:pathData="M0,0h625v400H0z"/>
<path android:fillColor="#e00025" android:pathData="M0,100h625v200H0z"/>
<path android:fillColor="#fff"
android:pathData="m256.163,188.526h113.8v43.788h-113.8z"
android:strokeColor="#000" android:strokeLineJoin="bevel" android:strokeWidth="1"/>
<path android:fillColor="#fff"
android:pathData="m364.093,212.706h3.586v16.495h-3.586zM256.163,204.556h113.8v5.09h-113.8zM256.163,197.656h113.8v4.49h-113.8z"
android:strokeColor="#000" android:strokeLineJoin="bevel" android:strokeWidth="1"/>
<path android:fillColor="#fff"
android:pathData="m256.163,190.766h113.8v4.354h-113.8z"
android:strokeColor="#000" android:strokeLineJoin="bevel" android:strokeWidth="1"/>
<path android:fillColor="#fff"
android:pathData="m286.123,212.706h3.586v16.495h-3.586zM335.113,212.706h3.586v16.495h-3.586zM257.063,212.706h3.586v16.495h-3.586zM264.093,212.706h3.586v16.495h-3.586zM271.593,212.706h3.586v16.495h-3.586zM279.093,212.706h3.586v16.495h-3.586zM341.913,212.706h3.586v16.495h-3.586zM349.413,212.706h3.586v16.495h-3.586zM356.913,212.706h3.586v16.495h-3.586z"
android:strokeColor="#000" android:strokeLineJoin="bevel" android:strokeWidth="1"/>
<path android:fillColor="#fff"
android:pathData="m211.653,234.616c1.76,-0.897 3.767,-2.984 4.424,-5.32h193.07c0.657,2.336 2.665,4.423 4.425,5.32z"
android:strokeColor="#000" android:strokeWidth="1"/>
<path android:fillColor="#fff"
android:pathData="m310.143,121.866c0,0 -0.144,-4.112 2.25,-4.157 2.396,0.044 2.25,4.157 2.25,4.157zM297.653,176.406v-5.536c-0.08,-2.768 -2.76,-2.968 -2.838,-4.986 0,0 -0.346,-3.027 0.452,-4.408 1.084,4.047 3.056,3.304 3.056,1.64 0,-1.453 -1.117,-2.804 -3.408,-6.33 -0.732,-1.128 -0.28,-4.66 0.747,-5.923 0.397,3.07 0.852,4.54 2.17,4.54 0.805,0 1.462,-0.524 1.462,-2.062 0,-1.957 -1.325,-2.945 -1.977,-4.725 -0.76,-2.078 -0.236,-4.196 1.026,-5.38 0.542,3.03 0.38,4.237 1.727,4.237 2.713,-0.858 0,-4.786 -0.58,-5.777 -0.666,-1.155 0.897,-3.46 0.897,-3.46 0.863,2.69 1.14,2.91 2.07,2.66 1.174,-0.315 1.023,-2.056 -0.41,-3.463 -0.904,-0.89 -0.808,-2.212 0.163,-3.274 0.975,1.905 2.223,1.79 2.343,0.658l-0.784,-4.392h17.255l-0.856,4.25c-0.245,1.215 1.396,1.48 2.416,-0.515 0.972,1.062 1.067,2.385 0.163,3.274 -1.432,1.407 -1.584,3.148 -0.41,3.463 0.93,0.25 1.208,0.03 2.07,-2.66 0,0 1.403,1.57 0.897,3.46 -0.58,0.99 -3.293,4.92 -0.58,5.777 1.346,0 1.185,-1.208 1.726,-4.237 1.263,1.184 1.786,3.302 1.026,5.38 -0.65,1.78 -1.976,2.768 -1.976,4.725 0,1.538 0.657,2.062 1.46,2.062 1.32,0 1.775,-1.47 2.173,-4.54 1.025,1.263 1.478,4.795 0.746,5.922 -2.29,3.526 -3.408,4.877 -3.408,6.33 0,1.664 1.97,2.407 3.056,-1.64 0.797,1.38 0.45,4.408 0.45,4.408 -0.078,2.018 -2.758,2.218 -2.837,4.986v5.536zM304.873,130.386 L304.476,127.261h15.838l-0.396,3.125zM305.933,127.196 L305.593,124.626h13.603l-0.34,2.57zM308.093,124.536 L307.866,121.966h9.058l-0.226,2.57zM341.113,234.616c-2.027,-0.78 -4.977,-2.92 -4.977,-5.07v-24.297l2.638,-3.358h-52.775l2.53,3.36v24.296c0,2.15 -2.027,4.29 -4.053,5.07z"
android:strokeColor="#000" android:strokeWidth="1"/>
<path android:fillColor="#fff"
android:pathData="m295.383,212.706h3.586v16.495h-3.586zM325.703,212.706h3.586v16.495h-3.586z"
android:strokeColor="#000" android:strokeLineJoin="bevel" android:strokeWidth="1"/>
<path android:fillColor="#fff"
android:pathData="m285.053,174.236v27.656h54.023v-5.957l0.078,-21.7c-2.208,0.868 -2.596,2.87 -2.596,2.87v11.778h-48.75v-11.777c0,0 -0.544,-2.002 -2.754,-2.87z"
android:strokeColor="#000" android:strokeWidth="1"/>
<path android:fillColor="#fff"
android:pathData="m331.743,234.616c-1.766,-0.78 -5.612,-2.92 -5.612,-5.07v-27.19c0.378,-1.518 2.436,-2.414 3.76,-3.358h-35.822c1.705,0.902 3.606,1.652 4.285,3.36v27.19c0,2.15 -3.04,4.29 -4.806,5.07z"
android:strokeColor="#000" android:strokeWidth="1"/>
<path android:fillColor="#fff"
android:pathData="m336.553,199.286v-19.587h-4.91v-1.91h-38.84v1.91h-4.91v19.587zM324.003,234.616c-1.73,-0.78 -4.25,-2.92 -4.25,-5.07v-23.214l1.422,-2.11h-17.69l1.42,2.11v23.215c0,2.152 -2.52,4.29 -4.25,5.07z"
android:strokeColor="#000" android:strokeWidth="1"/>
<path android:fillColor="#fff"
android:pathData="m307.853,204.226h8.966v30.377h-8.966z"
android:strokeColor="#000" android:strokeWidth="1"/>
<path android:fillColor="#fff"
android:pathData="m321.523,197.546c0.02,-2 5.838,-2.09 8.832,-3.795h-35.952c2.994,1.704 8.675,1.844 8.675,3.795l1.217,3.882 14.883,0.598z"
android:strokeColor="#000" android:strokeLineJoin="bevel" android:strokeWidth="1"/>
<path android:fillColor="#fff"
android:pathData="m328.553,176.406c0,-4.9 0.205,-6.786 1.71,-6.786v15.58c-3.69,1.34 -6.325,6.05 -6.325,6.05h-23.21c0,0 -2.635,-4.71 -6.326,-6.05v-15.58c1.855,0 1.867,1.972 1.867,6.786zM330.263,174.396c0,-5.618 4.85,-6.25 4.85,-6.25v5c-1.845,-0.08 -2.736,1.578 -2.736,4.044 0,2.466 1.487,2.506 1.487,2.506v14.19h-3.6z"
android:strokeColor="#000" android:strokeWidth="1"/>
<path android:fillColor="#fff"
android:pathData="m294.423,174.396c0,-5.618 -4.85,-6.25 -4.85,-6.25v5c1.845,-0.08 2.736,1.578 2.736,4.044 0,2.466 -1.487,2.506 -1.487,2.506v14.19h3.6z"
android:strokeColor="#000" android:strokeWidth="1"/>
<path android:pathData="m303.983,135.686h17.128m-19.158,5.35h20.92m-22.95,6.49h24.904m-27.024,7.93h29.536m-30.216,9.04h30.426"
android:strokeColor="#000" android:strokeWidth="1"/>
<path android:pathData="m287.893,193.986h48.66m-33.22,0.01h18.036v6.63h-18.036z"
android:strokeColor="#000" android:strokeWidth="1"/>
<path android:fillColor="#fff"
android:pathData="m301.073,179.306c2.99,3.59 2.713,9.68 2.68,13.27h17.342c-0.035,-3.59 -0.312,-9.68 2.678,-13.27zM310.823,138.176 L308.447,136.952v-3.497c0.97,0.29 2.062,0.41 2.168,1.958 0.338,-2.21 0.948,-2.102 1.907,-2.963 0.957,0.86 1.567,0.753 1.905,2.963 0.107,-1.548 1.197,-1.667 2.17,-1.96v3.498l-2.378,1.224z"
android:strokeColor="#000" android:strokeWidth="1"/>
<path android:fillColor="#fff"
android:pathData="m310.663,143.916 l-3.946,-2.713v-3.223c1.383,0.32 2.936,0.45 3.088,2.15 0.482,-2.424 1.35,-3.676 2.715,-4.62 1.365,0.944 2.233,2.196 2.715,4.62 0.152,-1.7 1.705,-1.83 3.09,-2.15v3.223l-3.948,2.713z"
android:strokeColor="#000" android:strokeWidth="1"/>
<path android:fillColor="#fff"
android:pathData="m310.383,152.866 l-4.538,-3.985v-4.736c1.59,0.47 3.377,0.662 3.552,3.156 0.553,-3.56 1.552,-5.4 3.12,-6.787 1.57,1.387 2.57,3.226 3.123,6.786 0.175,-2.494 1.96,-2.686 3.55,-3.157v4.735l-4.536,3.985zM318.753,158.156 L314.649,163.832h-4.646l-4.104,-5.676zM303.533,167.686c2.053,1.122 2.81,3.357 3.03,7.553h11.55c0.22,-4.196 0.977,-6.43 3.03,-7.553z"
android:strokeColor="#000" android:strokeWidth="1"/>
<path android:fillColor="#fff"
android:pathData="m321.313,158.156v-5.702c-1.95,0.537 -3.213,1.69 -3.776,3.258 0,-1.893 -2.49,-6.257 -5.207,-8.43 -2.724,2.432 -5.257,6.38 -5.206,8.43 -0.463,-1.492 -1.825,-2.72 -3.775,-3.258v5.702z"
android:strokeColor="#000" android:strokeLineJoin="bevel" android:strokeWidth="1"/>
<path android:fillColor="#fff"
android:pathData="m322.183,167.686v-5.702c-2.138,0.537 -3.522,1.69 -4.14,3.258 0,-1.893 -2.73,-6.258 -5.707,-8.43 -2.986,2.432 -5.763,6.38 -5.707,8.43 -0.508,-1.492 -2.002,-2.72 -4.14,-3.258v5.702z"
android:strokeColor="#000" android:strokeLineJoin="bevel" android:strokeWidth="1"/>
<path android:fillColor="#fff"
android:pathData="m324.583,179.386v-6.577c-2.66,0.687 -4.312,2.653 -5.15,3.8 0,-3.56 -4.02,-8.99 -7.1,-10.768 -3.16,1.825 -7.1,7.435 -7.1,10.768 -0.86,-1.14 -2.49,-3.113 -5.15,-3.8v6.577z"
android:strokeColor="#000" android:strokeLineJoin="bevel" android:strokeWidth="1"/>
<path android:fillColor="#fff"
android:pathData="m323.143,193.986v-6.762c-2.346,0.92 -3.048,3.18 -3.786,4.717 0.29,-6.86 -3.862,-14.23 -7.024,-16.1 -3.163,1.87 -7.393,9.4 -7.024,16.1 -0.758,-1.527 -1.44,-3.797 -3.786,-4.717v6.762z"
android:strokeColor="#000" android:strokeLineJoin="bevel" android:strokeWidth="1"/>
<path android:fillColor="#fff"
android:pathData="m321.503,204.226v-6.762c-2.458,0.585 -2.61,1.49 -3.392,3.006 0.29,-4.097 -2.61,-8.77 -5.773,-10.64 -3.163,1.87 -6.064,6.544 -5.774,10.64 -0.78,-1.515 -0.877,-2.42 -3.39,-3.006v6.762z"
android:strokeColor="#000" android:strokeWidth="1"/>
<path android:fillColor="#fff"
android:pathData="m216.078,229.296v-20.44c-0.67,-2.603 -2.88,-4.905 -4.54,-5.366v-17.994l3.74,2.024 4.272,18.81v22.966z"
android:strokeColor="#000" android:strokeWidth="1"/>
<path android:fillColor="#fff"
android:pathData="m216.078,229.376v-20.52c-0.67,-2.602 -2.88,-4.904 -4.54,-5.365v-19.243c2.51,0 3.74,3.273 3.74,3.273l4.272,18.81v22.887z"
android:strokeColor="#000" android:strokeWidth="1"/>
<path android:fillColor="#fff"
android:pathData="m213.418,234.616c1.73,-0.78 4.25,-2.92 4.25,-5.07v-25.547l-1.187,-2.108h43.523l-1.698,2.108v25.547c0,2.15 1.73,4.29 3.46,5.07z"
android:strokeColor="#000" android:strokeWidth="1"/>
<path android:fillColor="#fff"
android:pathData="m252.983,234.616c-1.73,-0.78 -4.25,-2.92 -4.25,-5.07v-24.297l3.62,-3.36 -29.588,0.002 3.62,3.358v24.297c0,2.15 -2.52,4.29 -4.25,5.07z"
android:strokeColor="#000" android:strokeWidth="1"/>
<path android:fillColor="#fff"
android:pathData="m248.833,234.616c-1.73,-0.78 -4.25,-2.92 -4.25,-5.07v-21.965l2.37,-3.36h-18.798l2.37,3.36v21.965c0,2.15 -2.52,4.29 -4.25,5.07z"
android:strokeColor="#000" android:strokeWidth="1"/>
<path android:fillColor="#fff"
android:pathData="m233.063,204.226h8.982v30.393h-8.982z"
android:strokeColor="#000" android:strokeWidth="1"/>
<path android:fillColor="#fff"
android:pathData="m220.843,212.706h3.586v16.495h-3.586zM251.593,212.706h3.586v16.495h-3.586zM217.783,184.886h4.32v16.91h-4.32zM217.783,181.706h4.295v3.14h-4.295z"
android:strokeColor="#000" android:strokeLineJoin="bevel" android:strokeWidth="1"/>
<path android:fillColor="#fff"
android:pathData="m253.313,188.526h6.16v13.054h-6.16z"
android:strokeColor="#000" android:strokeLineJoin="bevel" android:strokeWidth="1"/>
<path android:fillColor="#fff"
android:pathData="m222.033,201.666v-28.94c1.232,0 1.422,4.24 4.25,4.24 1.47,0 1.314,-1.756 0.488,-3.187 -0.732,-1.268 -1.637,-3.018 -0.407,-6.28 0.844,2.496 3.113,3.288 2.694,1.723 -0.72,-2.688 -2.795,-3.13 -1.24,-7.302 0.542,3.48 2.774,3.327 2.232,1.304 -0.61,-2.28 -1.873,-3.214 -0.316,-6.428 0.873,3.65 2.052,3.435 2.052,1.17 0,-3.346 -0.128,-6.956 4.203,-8.295 0,0 0.25,-3.068 1.812,-3.068 1.562,0 1.813,3.068 1.813,3.068 4.33,1.34 4.202,4.95 4.202,8.296 0,2.265 1.18,2.48 2.052,-1.17 1.558,3.214 0.295,4.148 -0.315,6.428 -0.544,2.023 1.69,2.177 2.23,-1.304 1.556,4.172 -0.518,4.614 -1.24,7.302 -0.418,1.565 1.85,0.773 2.694,-1.722 1.23,3.26 0.325,5.01 -0.407,6.28 -0.826,1.43 -0.983,3.187 0.49,3.187 2.826,0 3.016,-4.24 4.248,-4.24v28.94zM215.267,179.806v22.08h2.51L217.777,179.75c-0.904,-0.457 -1.754,-0.527 -2.51,0.056z"
android:strokeColor="#000" android:strokeWidth="1"/>
<path android:fillColor="#fff"
android:pathData="m215.346,194.096c3.112,1.59 6.195,3.433 6.975,7.793h-6.975zM258.513,187.486v14.407h2.035L260.548,187.45c-0.635,-0.298 -1.503,-0.345 -2.035,0.036z"
android:strokeColor="#000" android:strokeWidth="1"/>
<path android:fillColor="#fff"
android:pathData="m260.553,193.986c-3.112,1.59 -6.195,3.433 -6.975,7.793h6.975z"
android:strokeColor="#000" android:strokeWidth="1"/>
<path android:fillColor="#fff"
android:pathData="m239.973,160.336 l1.814,-1.525v-1.953c-0.664,0.065 -1.026,0.293 -1.516,0.936 -0.417,-1.295 -1.334,-2.305 -2.562,-2.933 -1.23,0.628 -2.146,1.593 -2.563,2.887 -0.49,-0.643 -0.852,-0.825 -1.516,-0.89v1.953l1.815,1.525z"
android:strokeColor="#000" android:strokeWidth="1"/>
<path android:fillColor="#fff"
android:pathData="m240.943,165.226 l0.843,-1.825v-2.54c-0.664,0.067 -1.026,0.298 -1.516,0.95 -0.417,-1.313 -1.334,-2.338 -2.562,-2.974 -1.23,0.637 -2.146,1.616 -2.563,2.928 -0.49,-0.65 -0.852,-0.836 -1.516,-0.902v2.54l0.844,1.824z"
android:strokeColor="#000" android:strokeWidth="1"/>
<path android:fillColor="#fff"
android:pathData="m241.073,171.856 l2.695,-3.287v-3.243c-0.986,0.11 -1.524,0.503 -2.252,1.606 -0.62,-2.222 -1.98,-2.708 -3.806,-3.786 -1.825,1.078 -3.187,1.485 -3.806,3.707 -0.728,-1.103 -1.266,-1.416 -2.25,-1.527v3.243l2.693,3.287z"
android:strokeColor="#000" android:strokeWidth="1"/>
<path android:fillColor="#fff"
android:pathData="m241.863,178.366c0,0 3.14,-2.74 3.327,-4.244v-3.467c-1.217,0.142 -2.368,0.458 -3.267,1.882 -0.765,-2.87 -1.96,-3.67 -4.212,-5.062 -2.253,1.392 -3.447,2.192 -4.212,5.062 -0.9,-1.425 -2.05,-1.74 -3.267,-1.883v3.466c0.396,1.504 3.326,4.244 3.326,4.244z"
android:strokeColor="#000" android:strokeWidth="1"/>
<path android:fillColor="#fff"
android:pathData="m243.203,190.386c0,0 4.3,-4.76 4.4,-6.616v-5.406c-1.61,0.223 -3.132,1.33 -4.32,3.55 -1.012,-4.474 -2.59,-7.594 -5.57,-9.764 -2.98,2.17 -4.56,5.29 -5.57,9.765 -1.19,-2.222 -2.713,-3.33 -4.322,-3.552v5.406c0.308,1.855 4.4,6.616 4.4,6.616z"
android:strokeColor="#000" android:strokeWidth="1"/>
<path android:fillColor="#fff"
android:pathData="m243.203,197.496c0,0 3.676,-3.742 4.4,-5.366v-5.406c-1.61,0.223 -3.132,1.33 -4.32,3.55 -1.012,-4.474 -2.59,-7.036 -5.57,-9.206 -2.98,2.17 -4.56,4.732 -5.57,9.207 -1.19,-2.223 -2.713,-3.33 -4.322,-3.552v5.406c0.933,1.624 4.4,5.366 4.4,5.366z"
android:strokeColor="#000" android:strokeWidth="1"/>
<path android:fillColor="#fff"
android:pathData="m244.683,201.626c-1.073,-4.668 -1.996,-8.13 -7.163,-11.64 -5.167,3.51 -6.09,6.972 -7.163,11.64z"
android:strokeColor="#000" android:strokeWidth="1"/>
<path android:fillColor="#fff"
android:pathData="m247.343,204.226v-6.762c-2.346,0.92 -4.467,2.28 -5.25,3.795 -0.872,-3.754 -2.556,-5.408 -4.652,-7.68 -2.097,2.272 -3.5,3.926 -4.375,7.68 -0.782,-1.515 -2.902,-2.875 -5.25,-3.795v6.762z"
android:strokeColor="#000" android:strokeWidth="1"/>
<path android:fillColor="#fff"
android:pathData="m408.948,229.296v-20.44c0.67,-2.603 2.88,-4.905 4.54,-5.366v-17.994l-3.74,2.024 -4.272,18.81v22.966z"
android:strokeColor="#000" android:strokeWidth="1"/>
<path android:fillColor="#fff"
android:pathData="m408.948,229.376v-20.52c0.67,-2.602 2.88,-4.904 4.54,-5.365v-19.243c-2.51,0 -3.74,3.273 -3.74,3.273l-4.272,18.81v22.887z"
android:strokeColor="#000" android:strokeWidth="1"/>
<path android:fillColor="#fff"
android:pathData="m411.608,234.616c-1.73,-0.78 -4.25,-2.92 -4.25,-5.07v-25.547l1.187,-2.108h-43.523l1.698,2.108v25.547c0,2.15 -1.73,4.29 -3.46,5.07z"
android:strokeColor="#000" android:strokeWidth="1"/>
<path android:fillColor="#fff"
android:pathData="m372.043,234.616c1.73,-0.78 4.25,-2.92 4.25,-5.07v-24.297l-3.62,-3.36 29.588,0.002 -3.62,3.358v24.297c0,2.15 2.52,4.29 4.25,5.07z"
android:strokeColor="#000" android:strokeWidth="1"/>
<path android:fillColor="#fff"
android:pathData="m376.193,234.616c1.73,-0.78 4.25,-2.92 4.25,-5.07v-21.965l-2.37,-3.36h18.798l-2.37,3.36v21.965c0,2.15 2.52,4.29 4.25,5.07z"
android:strokeColor="#000" android:strokeWidth="1"/>
<path android:fillColor="#fff"
android:pathData="m391.963,204.226h-8.982v30.393h8.982z"
android:strokeColor="#000" android:strokeWidth="1"/>
<path android:fillColor="#fff"
android:pathData="m404.183,212.706h-3.586v16.495h3.586zM373.433,212.706h-3.586v16.495h3.586zM407.243,184.886h-4.32v16.91h4.32zM407.243,181.706h-4.295v3.14h4.295z"
android:strokeColor="#000" android:strokeLineJoin="bevel" android:strokeWidth="1"/>
<path android:fillColor="#fff"
android:pathData="m371.713,188.526h-6.16v13.054h6.16z"
android:strokeColor="#000" android:strokeLineJoin="bevel" android:strokeWidth="1"/>
<path android:fillColor="#fff"
android:pathData="m402.993,201.666v-28.94c-1.232,0 -1.422,4.24 -4.25,4.24 -1.47,0 -1.314,-1.756 -0.488,-3.187 0.732,-1.268 1.637,-3.018 0.407,-6.28 -0.844,2.496 -3.113,3.288 -2.694,1.723 0.72,-2.688 2.795,-3.13 1.24,-7.302 -0.542,3.48 -2.774,3.327 -2.232,1.304 0.61,-2.28 1.873,-3.214 0.316,-6.428 -0.873,3.65 -2.052,3.435 -2.052,1.17 0,-3.346 0.128,-6.956 -4.203,-8.295 0,0 -0.25,-3.068 -1.812,-3.068 -1.562,0 -1.813,3.068 -1.813,3.068 -4.33,1.34 -4.202,4.95 -4.202,8.296 0,2.265 -1.18,2.48 -2.052,-1.17 -1.558,3.214 -0.295,4.148 0.315,6.428 0.544,2.023 -1.69,2.177 -2.23,-1.304 -1.556,4.172 0.518,4.614 1.24,7.302 0.418,1.565 -1.85,0.773 -2.694,-1.722 -1.23,3.26 -0.325,5.01 0.407,6.28 0.826,1.43 0.983,3.187 -0.49,3.187 -2.826,0 -3.016,-4.24 -4.248,-4.24v28.94zM409.759,179.806v22.08h-2.51L407.249,179.75c0.904,-0.457 1.754,-0.527 2.51,0.056z"
android:strokeColor="#000" android:strokeWidth="1"/>
<path android:fillColor="#fff"
android:pathData="m409.68,194.096c-3.112,1.59 -6.195,3.433 -6.975,7.793h6.975zM366.513,187.486v14.407h-2.035L364.478,187.45c0.635,-0.298 1.503,-0.345 2.035,0.036z"
android:strokeColor="#000" android:strokeWidth="1"/>
<path android:fillColor="#fff"
android:pathData="m364.473,193.986c3.112,1.59 6.195,3.433 6.975,7.793h-6.975z"
android:strokeColor="#000" android:strokeWidth="1"/>
<path android:fillColor="#fff"
android:pathData="m385.053,160.336 l-1.814,-1.525v-1.953c0.664,0.065 1.026,0.293 1.516,0.936 0.417,-1.295 1.334,-2.305 2.562,-2.933 1.23,0.628 2.146,1.593 2.563,2.887 0.49,-0.643 0.852,-0.825 1.516,-0.89v1.953l-1.815,1.525z"
android:strokeColor="#000" android:strokeWidth="1"/>
<path android:fillColor="#fff"
android:pathData="m384.083,165.226 l-0.843,-1.825v-2.54c0.664,0.067 1.026,0.298 1.516,0.95 0.417,-1.313 1.334,-2.338 2.562,-2.974 1.23,0.637 2.146,1.616 2.563,2.928 0.49,-0.65 0.852,-0.836 1.516,-0.902v2.54l-0.844,1.824z"
android:strokeColor="#000" android:strokeWidth="1"/>
<path android:fillColor="#fff"
android:pathData="m383.953,171.856 l-2.695,-3.287v-3.243c0.986,0.11 1.524,0.503 2.252,1.606 0.62,-2.222 1.98,-2.708 3.806,-3.786 1.825,1.078 3.187,1.485 3.806,3.707 0.728,-1.103 1.266,-1.416 2.25,-1.527v3.243l-2.693,3.287z"
android:strokeColor="#000" android:strokeWidth="1"/>
<path android:fillColor="#fff"
android:pathData="m383.163,178.366c0,0 -3.14,-2.74 -3.327,-4.244v-3.467c1.217,0.142 2.368,0.458 3.267,1.882 0.765,-2.87 1.96,-3.67 4.212,-5.062 2.253,1.392 3.447,2.192 4.212,5.062 0.9,-1.425 2.05,-1.74 3.267,-1.883v3.466c-0.396,1.504 -3.326,4.244 -3.326,4.244z"
android:strokeColor="#000" android:strokeWidth="1"/>
<path android:fillColor="#fff"
android:pathData="m381.823,190.386c0,0 -4.3,-4.76 -4.4,-6.616v-5.406c1.61,0.223 3.132,1.33 4.32,3.55 1.012,-4.474 2.59,-7.594 5.57,-9.764 2.98,2.17 4.56,5.29 5.57,9.765 1.19,-2.222 2.713,-3.33 4.322,-3.552v5.406c-0.308,1.855 -4.4,6.616 -4.4,6.616z"
android:strokeColor="#000" android:strokeWidth="1"/>
<path android:fillColor="#fff"
android:pathData="m381.823,197.496c0,0 -3.676,-3.742 -4.4,-5.366v-5.406c1.61,0.223 3.132,1.33 4.32,3.55 1.012,-4.474 2.59,-7.036 5.57,-9.206 2.98,2.17 4.56,4.732 5.57,9.207 1.19,-2.223 2.713,-3.33 4.322,-3.552v5.406c-0.933,1.624 -4.4,5.366 -4.4,5.366z"
android:strokeColor="#000" android:strokeWidth="1"/>
<path android:fillColor="#fff"
android:pathData="m380.343,201.626c1.073,-4.668 1.996,-8.13 7.163,-11.64 5.167,3.51 6.09,6.972 7.163,11.64z"
android:strokeColor="#000" android:strokeWidth="1"/>
<path android:fillColor="#fff"
android:pathData="m377.683,204.226v-6.762c2.346,0.92 4.467,2.28 5.25,3.795 0.872,-3.754 2.556,-5.408 4.652,-7.68 2.097,2.272 3.5,3.926 4.375,7.68 0.782,-1.515 2.902,-2.875 5.25,-3.795v6.762z"
android:strokeColor="#000" android:strokeWidth="1"/>
<path android:fillColor="#fff"
android:pathData="m206.555,234.346v6.173h211.89v-6.174zM202.719,240.576v8.05h219.56v-8.05zM422.279,248.626 L202.719,248.686 196.301,248.626v10.622h232.398v-10.62zM189.836,259.316 L189.838,271.826h245.33l-0.002,-12.51zM435.168,271.826v0.02h-245.33v-0.02h-6.467v12.51h258.26v-12.51z"
android:strokeColor="#000" android:strokeWidth="1"/>
<path android:fillColor="#fff"
android:pathData="m229.553,234.376h16.005v49.935h-16.005z"
android:strokeColor="#000" android:strokeWidth="1"/>
<path android:fillColor="#fff"
android:pathData="m233.093,234.376h8.917v49.936h-8.917z"
android:strokeColor="#000" android:strokeWidth="1"/>
<path android:fillColor="#fff"
android:pathData="m304.223,234.376h16.006v49.935h-16.006z"
android:strokeColor="#000" android:strokeWidth="1"/>
<path android:fillColor="#fff"
android:pathData="m307.873,234.376h8.917v49.936h-8.917z"
android:strokeColor="#000" android:strokeWidth="1"/>
<path android:fillColor="#fff"
android:pathData="m379.333,234.376h16.005v49.935h-16.005z"
android:strokeColor="#000" android:strokeWidth="1"/>
<path android:fillColor="#fff"
android:pathData="m382.873,234.376h8.917v49.936h-8.917z"
android:strokeColor="#000" android:strokeWidth="1"/>
<path android:pathData="m216.078,229.296h193.07m-176.215,48.74h9.244m-9.244,-6.25h9.244m-9.244,-6.25h9.244m-9.244,-6.25h9.244m-9.244,-6.25h9.244m-9.244,-6.25h9.244m-9.244,-6.25h9.244m65.736,37.51h8.607m-8.607,-6.253h8.607m-8.607,-6.254h8.607m-8.607,-6.253h8.607m-8.607,-6.253h8.607m-8.607,-6.253h8.607m-8.607,-6.254h8.607m66.193,37.51h9.244m-9.244,-6.25h9.244m-9.244,-6.25h9.244m-9.244,-6.25h9.244m-9.244,-6.25h9.244m-9.244,-6.25h9.244m-9.244,-6.25h9.244"
android:strokeColor="#000" android:strokeWidth="1"/>
</vector>
``` | /content/code_sandbox/app/src/main/res/drawable/ic_flag_kh.xml | xml | 2016-07-02T10:44:04 | 2024-08-16T18:55:54 | StreetComplete | streetcomplete/StreetComplete | 3,781 | 10,746 |
```xml
import { WebBlockStyles } from '@native-html/transient-render-engine';
import React from 'react';
import {
ImageErrorEventData,
ImageProps,
ImageStyle,
NativeSyntheticEvent
} from 'react-native';
import { act, render } from '@testing-library/react-native';
import IMGElement from '../IMGElement';
import HTMLImgElement from '../IMGElement';
describe('IMGElement', () => {
it('should render an error fallback component on error', async () => {
const source = { uri: 'error' };
const { findByTestId } = render(<HTMLImgElement source={source} />);
await findByTestId('image-error');
});
it('should render a GenericPressable when provided with onPress prop', async () => {
const onPress = jest.fn();
const source = { uri: 'path_to_url };
const { findByTestId } = render(
<HTMLImgElement onPress={onPress} source={source} />
);
await findByTestId('generic-pressable');
});
it('should call onError when encountering an error after success', async () => {
const source = { uri: 'path_to_url };
const { findByTestId } = render(<IMGElement source={source} />);
const imageSuccess = await findByTestId('image-success');
act(() =>
(imageSuccess.props.onError as Required<ImageProps>['onError']).call(
null,
{
nativeEvent: { error: new Error() }
} as NativeSyntheticEvent<ImageErrorEventData>
)
);
await findByTestId('image-error', { timeout: 50 });
});
describe('object-fit support', () => {
const defaultRM = 'cover' as const;
const specs: Record<
Required<WebBlockStyles>['objectFit'],
ImageStyle['resizeMode'] | null
> = {
contain: 'contain',
cover: 'cover',
unset: defaultRM,
fill: 'stretch',
'scale-down': 'contain',
'-moz-initial': defaultRM,
inherit: defaultRM,
initial: defaultRM,
none: defaultRM,
revert: defaultRM
};
for (const [objectFit, resizeMode] of Object.entries(specs)) {
it(`should map object-fit "${objectFit}" to resizeMode "${resizeMode}"`, async () => {
const source = { uri: 'path_to_url };
const style = {
width: 320,
height: 180
};
const { findByTestId } = render(
<HTMLImgElement
objectFit={objectFit as any}
style={style}
source={source}
/>
);
const image = await findByTestId('image-success');
expect(image).toHaveStyle({
resizeMode
});
});
}
});
describe('scaling logic', () => {
it('should use width and height from styles', async () => {
const source = { uri: 'path_to_url };
const style = {
width: 320,
height: 180
};
const { findByTestId } = render(
<HTMLImgElement style={style} source={source} />
);
const image = await findByTestId('image-success');
expect(image).toBeTruthy();
expect(image).toHaveStyle(style);
});
it('should use width and height from props', async () => {
const source = { uri: 'path_to_url };
const style = {
width: 320,
height: 180
};
const { findByTestId } = render(
<HTMLImgElement {...style} source={source} />
);
const image = await findByTestId('image-success');
expect(image).toBeTruthy();
expect(image).toHaveStyle(style);
});
it('should combine width with aspectRatio', async () => {
const source = { uri: 'path_to_url };
const dimensions = {
width: 320
};
const { findByTestId } = render(
<HTMLImgElement
{...dimensions}
style={{ aspectRatio: 2 }}
source={source}
/>
);
const image = await findByTestId('image-success');
expect(image).toBeTruthy();
expect(image).toHaveStyle({
width: 320,
height: 160
});
});
it('should combine height with aspectRatio', async () => {
const source = { uri: 'path_to_url };
const dimensions = {
height: 160
};
const { findByTestId } = render(
<HTMLImgElement
{...dimensions}
style={{ aspectRatio: 2 }}
source={source}
/>
);
const image = await findByTestId('image-success');
expect(image).toBeTruthy();
expect(image).toHaveStyle({
width: 320,
height: 160
});
});
it('should scale down required dimensions to contentWidth prop when appropriate', async () => {
const source = { uri: 'path_to_url };
const style = {
width: 320,
height: 180
};
const contentWidth = 160;
const { findByTestId } = render(
<HTMLImgElement
contentWidth={contentWidth}
{...style}
source={source}
/>
);
const image = await findByTestId('image-success');
expect(image).toBeTruthy();
expect(image).toHaveStyle({
width: contentWidth,
height: contentWidth / (style.width / style.height)
});
});
it('should scale the image to contentWidth prop when appropriate when only width or height is required', async () => {
const source = { uri: 'path_to_url };
const style = {
width: 320
};
const contentWidth = 160;
const { findByTestId } = render(
<HTMLImgElement
contentWidth={contentWidth}
{...style}
source={source}
/>
);
const image = await findByTestId('image-success');
expect(image).toBeTruthy();
expect(image).toHaveStyle({
width: contentWidth,
height: contentWidth / (640 / 360)
});
});
it('should scale the image down when only width or height is required', async () => {
const source = { uri: 'path_to_url };
const style = {
width: 320
};
const { findByTestId } = render(
<HTMLImgElement {...style} source={source} />
);
const image = await findByTestId('image-success');
expect(image).toBeTruthy();
expect(image).toHaveStyle({
width: 320,
height: 180
});
});
it('should use physical dimensions when no width or height requirements are provided', async () => {
const source = { uri: 'path_to_url };
const { findByTestId } = render(
<HTMLImgElement contentWidth={800} source={source} />
);
const image = await findByTestId('image-success');
expect(image).toBeTruthy();
expect(image).toHaveStyle({
width: 640,
height: 360
});
});
it('should handle 0-width and height requirements', async () => {
const source = { uri: 'path_to_url };
const style = {
width: 0,
height: 0
};
const { findByTestId } = render(
<HTMLImgElement {...style} source={source} />
);
const image = await findByTestId('image-success');
expect(image).toBeTruthy();
expect(image).toHaveStyle({
width: 0,
height: 0
});
});
it('should handle 0-width or height requirements', async () => {
const source = { uri: 'path_to_url };
const style = {
width: 0
};
const { findByTestId } = render(
<HTMLImgElement {...style} source={source} />
);
const image = await findByTestId('image-success');
expect(image).toBeTruthy();
expect(image).toHaveStyle({
width: 0,
height: 0
});
});
it('should handle maxWidth requirements', async () => {
const source = { uri: 'path_to_url };
const style = {
maxWidth: 320
};
const { findByTestId } = render(
<HTMLImgElement style={style} source={source} />
);
const image = await findByTestId('image-success');
expect(image).toBeTruthy();
expect(image).toHaveStyle({
width: 320,
height: 180
});
});
it('should handle maxHeight requirements', async () => {
const source = { uri: 'path_to_url };
const style = {
maxHeight: 180
};
const { findByTestId } = render(
<HTMLImgElement style={style} source={source} />
);
const image = await findByTestId('image-success');
expect(image).toBeTruthy();
expect(image).toHaveStyle({
width: 320,
height: 180
});
});
it('should handle minWidth requirements', async () => {
const source = { uri: 'path_to_url };
const style = {
minWidth: 30
};
const { findByTestId } = render(
<HTMLImgElement style={style} source={source} />
);
const image = await findByTestId('image-success');
expect(image).toBeTruthy();
expect(image).toHaveStyle({
width: 30,
height: 36
});
});
it('should handle minHeight requirements', async () => {
const source = { uri: 'path_to_url };
const style = {
minHeight: 36
};
const { findByTestId } = render(
<HTMLImgElement style={style} source={source} />
);
const image = await findByTestId('image-success');
expect(image).toBeTruthy();
expect(image).toHaveStyle({
width: 30,
height: 36
});
});
});
describe('special units', () => {
it('should ignore requirements in percentage when enableExperimentalPercentWidth or contentWidth props are not set', async () => {
const source = { uri: 'path_to_url };
const style = {
width: '50%'
};
const { findByTestId } = render(
<HTMLImgElement {...style} source={source} />
);
const image = await findByTestId('image-success');
expect(image).toBeTruthy();
expect(image).toHaveStyle({
width: 640,
height: 360
});
});
it('should support strings for width and height which can be parsed to numbers', async () => {
const source = { uri: 'path_to_url };
const style = {
width: '50'
};
const { findByTestId } = render(
<HTMLImgElement {...style} source={source} />
);
const image = await findByTestId('image-success');
expect(image).toBeTruthy();
expect(image).toHaveStyle({
width: 50
});
});
describe('when given enableExperimentalPercentWidth + contentWidth props', () => {
it('should support requirements in percentage', async () => {
const source = { uri: 'path_to_url };
const contentWidth = 250;
const style = {
width: '50%'
};
const { findByTestId } = render(
<HTMLImgElement
enableExperimentalPercentWidth
contentWidth={contentWidth}
{...style}
source={source}
/>
);
const image = await findByTestId('image-success');
expect(image).toBeTruthy();
expect(image).toHaveStyle({
width: contentWidth * 0.5
});
});
it('should constrain a percentage width with the value returned by computeMaxWidth', async () => {
const source = { uri: 'path_to_url };
const contentWidth = 250;
const style = {
width: '80%'
};
const { findByTestId } = render(
<HTMLImgElement
enableExperimentalPercentWidth
computeMaxWidth={(c) => c * 0.7}
contentWidth={250}
{...style}
source={source}
/>
);
const image = await findByTestId('image-success');
expect(image).toBeTruthy();
expect(image).toHaveStyle({
width: contentWidth * 0.7
});
});
it('should ignore percentage heights', async () => {
const source = { uri: 'path_to_url };
const contentWidth = 250;
const style = {
height: '10%'
};
const { findByTestId } = render(
<HTMLImgElement
enableExperimentalPercentWidth
contentWidth={250}
{...style}
source={source}
/>
);
const image = await findByTestId('image-success');
expect(image).toBeTruthy();
expect(image).toHaveStyle({
width: contentWidth,
height: (360 / 640) * contentWidth
});
});
});
});
describe('capabilities regarding spacing', () => {
it('should take into account horizontal margins when scaling down', async () => {
const source = { uri: 'path_to_url };
const style = {
margin: 25,
marginHorizontal: 30
};
const { findByTestId } = render(
<HTMLImgElement contentWidth={200} style={style} source={source} />
);
const image = await findByTestId('image-success');
expect(image).toBeTruthy();
expect(image).toHaveStyle({
width: 200 - 30 * 2
});
});
});
describe('when changing props', () => {
it('should update box width and height when requirements change', async () => {
const source = { uri: 'path_to_url };
const initialStyle = {
width: 640,
height: 360
};
const nextStyle = {
width: 320,
height: 180
};
const { findByTestId, update } = render(
<HTMLImgElement {...initialStyle} source={source} />
);
update(<HTMLImgElement {...nextStyle} source={source} />);
const image = await findByTestId('image-success');
expect(image).toBeTruthy();
expect(image).toHaveStyle(nextStyle);
});
it('should update uri and fetch new dimensions when source changes', async () => {
const initialSource = { uri: 'path_to_url };
const nextSource = { uri: 'path_to_url };
const { findByTestId, update } = render(
<HTMLImgElement source={initialSource} />
);
const image1 = await findByTestId('image-success');
expect(image1).toBeTruthy();
expect(image1).toHaveStyle({
width: 640,
height: 360
});
update(<HTMLImgElement source={nextSource} />);
await findByTestId('image-loading');
const image2 = await findByTestId('image-success');
expect(image2).toBeTruthy();
expect(image2).toHaveStyle({
width: 1920,
height: 1080
});
});
it('should retain inline style prior to attributes width and height to compute concrete dimensions', async () => {
const { findByTestId } = render(
<HTMLImgElement
width="1200"
height="800"
contentWidth={500}
enableExperimentalPercentWidth
style={{
width: '50%',
height: 100
}}
source={{ uri: 'path_to_url }}
/>
);
const image2 = await findByTestId('image-success');
expect(image2).toBeTruthy();
expect(image2).toHaveStyle({
width: 250,
height: 100
});
});
it('should retain border-related style', async () => {
const source = { uri: 'path_to_url };
const style = {
borderBottomLeftRadius: 10,
borderBottomRightRadius: 10,
borderTopLeftRadius: 10,
borderTopRightRadius: 10
};
const { findByTestId } = render(
<HTMLImgElement source={source} style={style} />
);
const image = await findByTestId('image-success');
expect(image).toBeTruthy();
expect(image).toHaveStyle({
borderBottomLeftRadius: 10,
borderBottomRightRadius: 10,
borderTopLeftRadius: 10,
borderTopRightRadius: 10
});
});
});
});
``` | /content/code_sandbox/packages/render-html/src/elements/__tests__/IMGElement.test.tsx | xml | 2016-11-29T10:50:53 | 2024-08-08T06:53:22 | react-native-render-html | meliorence/react-native-render-html | 3,445 | 3,539 |
```xml
// Type definitions for ag-grid v6.2.1
// Project: path_to_url
// Definitions by: Niall Crosby <path_to_url
// Definitions: path_to_url
import { GridOptions } from "./entities/gridOptions";
import { IFrameworkFactory } from "./interfaces/iFrameworkFactory";
export interface GridParams {
globalEventListener?: Function;
$scope?: any;
$compile?: any;
quickFilterOnScope?: any;
frameworkFactory?: IFrameworkFactory;
}
export declare class Grid {
private context;
private static enterpriseBeans;
private static RowModelClasses;
static setEnterpriseBeans(enterpriseBeans: any[], rowModelClasses: any): void;
constructor(eGridDiv: HTMLElement, gridOptions: GridOptions, params?: GridParams);
private getRowModelClass(gridOptions);
destroy(): void;
}
``` | /content/code_sandbox/services/dashboard/assets-dev/js/vendor/ag-grid/dist/lib/grid.d.ts | xml | 2016-06-21T19:39:58 | 2024-08-12T19:23:26 | mylg | mehrdadrad/mylg | 2,691 | 180 |
```xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
xmlns="path_to_url"
xmlns:xsi="path_to_url"
xsi:schemaLocation="path_to_url
path_to_url">
<display-name></display-name>
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>cn.hncu.servlets.LoginServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>ImgServlet</servlet-name>
<servlet-class>cn.hncu.servlets.ImgServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>SaveServlet</servlet-name>
<servlet-class>cn.hncu.servlets.SaveServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>DelServlet</servlet-name>
<servlet-class>cn.hncu.servlets.DelServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>AddUserServlet</servlet-name>
<servlet-class>cn.hncu.servlets.AddUserServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>QueryServlet</servlet-name>
<servlet-class>cn.hncu.servlets.QueryServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>ImgServlet</servlet-name>
<url-pattern>/ImgServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>SaveServlet</servlet-name>
<url-pattern>/SaveServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>DelServlet</servlet-name>
<url-pattern>/DelServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>AddUserServlet</servlet-name>
<url-pattern>/AddUserServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>QueryServlet</servlet-name>
<url-pattern>/QueryServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
``` | /content/code_sandbox/myMvcWeb/WebRoot/WEB-INF/web.xml | xml | 2016-04-25T16:39:57 | 2024-08-16T08:33:16 | Java | chenhaoxiang/Java | 1,250 | 576 |
```xml
<vector xmlns:android="path_to_url"
xmlns:tools="path_to_url"
android:width="448dp"
android:height="512dp"
android:viewportWidth="448.0"
android:viewportHeight="512.0"
tools:keep="@drawable/fa_windows">
<path
android:fillColor="#FFFFFFFF"
android:pathData="M0,93.7l183.6,-25.3v177.4L0,245.8L0,93.7zM0,418.3l183.6,25.3L183.6,268.4L0,268.4v149.9zM203.8,446.3L448,480L448,268.4L203.8,268.4v177.9zM203.8,65.7v180.1L448,245.8L448,32L203.8,65.7z"/>
</vector>
``` | /content/code_sandbox/mobile/src/main/res/drawable/fa_windows.xml | xml | 2016-10-24T13:23:25 | 2024-08-16T07:20:37 | freeotp-android | freeotp/freeotp-android | 1,387 | 208 |
```xml
import { CMakeCache, CacheEntryType, CacheEntry } from '@cmt/cache';
import { CMakeProject, ConfigureTrigger } from '@cmt/cmakeProject';
import paths from '@cmt/paths';
import { objectPairs, platformNormalizePath, makeHashString } from '@cmt/util';
import { clearExistingKitConfigurationFile, DefaultEnvironment, expect, getFirstSystemKit } from '@test/util';
import * as path from 'path';
suite('Variable Substitution', () => {
let cmakeProject: CMakeProject;
let testEnv: DefaultEnvironment;
setup(async function (this: Mocha.Context) {
this.timeout(100000);
testEnv = new DefaultEnvironment('test/extension-tests/successful-build/project-folder', 'build', 'output.txt');
cmakeProject = await CMakeProject.create(testEnv.wsContext, "${workspaceFolder}");
// This test will use all on the same kit.
// No rescan of the tools is needed
// No new kit selection is needed
await clearExistingKitConfigurationFile();
await cmakeProject.setKit(await getFirstSystemKit());
testEnv.projectFolder.buildDirectory.clear();
});
teardown(async function (this: Mocha.Context) {
this.timeout(30000);
await cmakeProject.asyncDispose();
testEnv.teardown();
});
test('Check variable substitution', async () => {
// Set new settings
testEnv.config.updatePartial({
configureSettings: {
workspaceRoot: '${workspaceRoot}',
workspaceFolder: '${workspaceFolder}',
sourceDir: '${sourceDir}',
workspaceHash: '${workspaceHash}',
buildType: '${buildType}',
buildKit: '${buildKit}',
workspaceRootFolderName: '${workspaceRootFolderName}',
workspaceFolderBasename: '${workspaceFolderBasename}',
generator: '${generator}',
userHome: '${userHome}',
test1: true,
test2: 123,
test3: ["1", "2", "3"],
test4: {"type": "PATH", "value": "/usr/bin"}
},
installPrefix: '${workspaceFolder}/build/dist'
});
// Configure
//expect(await cmt.configureInternal(ConfigureTrigger.runTests)).to.be.eq(0, '[workspaceRoot] configure failed');
await cmakeProject.configureInternal(ConfigureTrigger.runTests);
expect(testEnv.projectFolder.buildDirectory.isCMakeCachePresent).to.eql(true, 'expected cache not present');
const cache = await CMakeCache.fromPath(await cmakeProject.cachePath);
// Check substitution for "workspaceRoot"
let cacheEntry = cache.get('workspaceRoot') as CacheEntry;
expect(cacheEntry.type).to.eq(CacheEntryType.String, '[workspaceRoot] unexpected cache entry type');
expect(cacheEntry.key).to.eq('workspaceRoot', '[workspaceRoot] unexpected cache entry key name');
expect(platformNormalizePath(cacheEntry.as<string>()))
.to.eq(platformNormalizePath(testEnv.projectFolder.location), '[workspaceRoot] substitution incorrect');
expect(typeof cacheEntry.value).to.eq('string', '[workspaceRoot] unexpected cache entry value type');
// Check substitution for "workspaceFolder".
cacheEntry = cache.get('workspaceFolder') as CacheEntry;
expect(cacheEntry.type).to.eq(CacheEntryType.String, '[workspaceFolder] unexpected cache entry type');
expect(cacheEntry.key).to.eq('workspaceFolder', '[workspaceFolder] unexpected cache entry key name');
expect(platformNormalizePath(cacheEntry.as<string>()))
.to.eq(platformNormalizePath(testEnv.projectFolder.location), '[workspaceFolder] substitution incorrect');
expect(typeof cacheEntry.value).to.eq('string', '[workspaceFolder] unexpected cache entry value type');
// Check substitution for "workspaceHash".
cacheEntry = cache.get('workspaceHash') as CacheEntry;
expect(cacheEntry.type).to.eq(CacheEntryType.String, '[workspaceHash] unexpected cache entry type');
expect(cacheEntry.key).to.eq('workspaceHash', '[workspaceHash] unexpected cache entry key name');
expect(cacheEntry.as<string>()).to.eq(makeHashString(testEnv.projectFolder.location), '[workspaceHash] substitution incorrect');
expect(typeof cacheEntry.value).to.eq('string', '[workspaceHash] unexpected cache entry value type');
// Check substitution for "buildType".
cacheEntry = cache.get('buildType') as CacheEntry;
expect(cacheEntry.type).to.eq(CacheEntryType.String, '[buildType] unexpected cache entry type');
expect(cacheEntry.key).to.eq('buildType', '[buildType] unexpected cache entry key name');
expect(cacheEntry.as<string>()).to.eq('Debug', '[buildType] substitution incorrect');
expect(typeof cacheEntry.value).to.eq('string', '[buildType] unexpected cache entry value type');
// Check substitution for "buildKit".
cacheEntry = cache.get('buildKit') as CacheEntry;
expect(cacheEntry.type).to.eq(CacheEntryType.String, '[buildKit] unexpected cache entry type');
expect(cacheEntry.key).to.eq('buildKit', '[buildKit] unexpected cache entry key name');
const kit = cmakeProject.activeKit;
expect(cacheEntry.as<string>()).to.eq(kit!.name, '[buildKit] substitution incorrect');
expect(typeof cacheEntry.value).to.eq('string', '[buildKit] unexpected cache entry value type');
// Check substitution for "workspaceRootFolderName".
cacheEntry = cache.get('workspaceRootFolderName') as CacheEntry;
expect(cacheEntry.type).to.eq(CacheEntryType.String, '[workspaceRootFolderName] unexpected cache entry type');
expect(cacheEntry.key)
.to.eq('workspaceRootFolderName', '[workspaceRootFolderName] unexpected cache entry key name');
expect(cacheEntry.as<string>())
.to.eq(path.basename(testEnv.projectFolder.location), '[workspaceRootFolderName] substitution incorrect');
expect(typeof cacheEntry.value).to.eq('string', '[workspaceRootFolderName] unexpected cache entry value type');
// Check substitution for "workspaceFolderBasename".
cacheEntry = cache.get('workspaceFolderBasename') as CacheEntry;
expect(cacheEntry.type).to.eq(CacheEntryType.String, '[workspaceFolderBasename] unexpected cache entry type');
expect(cacheEntry.key)
.to.eq('workspaceFolderBasename', '[workspaceFolderBasename] unexpected cache entry key name');
expect(cacheEntry.as<string>())
.to.eq(path.basename(testEnv.projectFolder.location), '[workspaceFolderBasename] substitution incorrect');
expect(typeof cacheEntry.value).to.eq('string', '[workspaceFolderBasename] unexpected cache entry value type');
// Check substitution for "generator".
cacheEntry = cache.get('generator') as CacheEntry;
expect(cacheEntry.type).to.eq(CacheEntryType.String, '[generator] unexpected cache entry type');
expect(cacheEntry.key).to.eq('generator', '[generator] unexpected cache entry key name');
const generator = cache.get('CMAKE_GENERATOR') as CacheEntry;
expect(cacheEntry.as<string>()).to.eq(generator.as<string>(), '[generator] substitution incorrect');
expect(typeof cacheEntry.value).to.eq('string', '[generator] unexpected cache entry value type');
// Check substitution for "userHome".
cacheEntry = cache.get('userHome') as CacheEntry;
expect(cacheEntry.type).to.eq(CacheEntryType.String, '[userHome] unexpected cache entry type');
expect(cacheEntry.key).to.eq('userHome', '[userHome] unexpected cache entry key name');
expect(cacheEntry.as<string>()).to.eq(paths.userHome, '[userHome] substitution incorrect');
expect(typeof cacheEntry.value).to.eq('string', '[userHome] unexpected cache entry value type');
// Check substitution within "cmake.installPrefix".
cacheEntry = cache.get('CMAKE_INSTALL_PREFIX') as CacheEntry;
expect(cacheEntry.type).to.eq(CacheEntryType.String, '[cmakeInstallPrefix] unexpected cache entry type');
expect(cacheEntry.key).to.eq('CMAKE_INSTALL_PREFIX', '[cmakeInstallPrefix] unexpected cache entry key name');
expect(platformNormalizePath(cacheEntry.as<string>()))
.to.eq(platformNormalizePath(testEnv.projectFolder.buildDirectory.location.concat('/dist')),
'[cmakeInstallPrefix] substitution incorrect');
expect(typeof cacheEntry.value).to.eq('string', '[cmakeInstallPrefix] unexpected cache entry value type');
cacheEntry = cache.get('test1') as CacheEntry;
expect(cacheEntry.type).to.eq(CacheEntryType.Bool);
expect(cacheEntry.value).to.eq(true);
cacheEntry = cache.get('test2') as CacheEntry;
expect(cacheEntry.type).to.eq(CacheEntryType.String);
expect(cacheEntry.value).to.eq('123');
cacheEntry = cache.get('test3') as CacheEntry;
expect(cacheEntry.type).to.eq(CacheEntryType.String);
expect(cacheEntry.value).to.eq('1;2;3');
cacheEntry = cache.get('test4') as CacheEntry;
expect(cacheEntry.type).to.eq(CacheEntryType.Path);
expect(cacheEntry.value).to.eq('/usr/bin');
}).timeout(100000);
test('Check substitution for variant names', async () => {
// Define test keys and expected values
const testKeys = { buildType: 'debug-label', otherVariant: 'option1' };
// Update configure settings
const configSettings: { [key: string]: string } = {};
await Promise.all(Object.keys(testKeys).map(async key => configSettings[key] = `\${variant:${key}}`));
testEnv.config.updatePartial({ configureSettings: configSettings });
// Configure and retrieve generated cache
expect((await cmakeProject.configureInternal(ConfigureTrigger.runTests)).result).to.be.eq(0, '[variant] configure failed');
expect(testEnv.projectFolder.buildDirectory.isCMakeCachePresent).to.eql(true, '[variant] cache not found');
const cache = await CMakeCache.fromPath(await cmakeProject.cachePath);
// Helper function for checking test keys in a cmake cache
const checkTestKey = async (testKey: [string, string], testCache: CMakeCache) => {
const [key, expected] = testKey;
// Get cache entry for given test key
const cacheEntry = testCache.get(key) as CacheEntry;
// Check type and value of the retrieved cache entry
expect(cacheEntry.type).to.eq(CacheEntryType.String, `[variant:${key}] unexpected cache entry type`);
expect(cacheEntry.key).to.eql(key, `[variant:${key}] unexpected cache entry key name`);
expect(cacheEntry.as<string>()).to.eql(expected, `[variant:${key}] incorrect substitution`);
expect(typeof cacheEntry.value).to.eq('string', `[variant:${key}] unexpected cache entry value type`);
};
// Check test keys
await Promise.all(objectPairs(testKeys).map(async testKey => checkTestKey(testKey, cache)));
}).timeout(100000);
});
``` | /content/code_sandbox/test/extension-tests/successful-build/test/variable-substitution.test.ts | xml | 2016-04-16T21:00:29 | 2024-08-16T16:41:57 | vscode-cmake-tools | microsoft/vscode-cmake-tools | 1,450 | 2,322 |
```xml
import { useRef, useEffect } from 'react';
/**
* Hook keeping track of a given value from a previous execution of the component the Hook is used in.
*
* See [React Hooks FAQ](path_to_url#how-to-get-the-previous-props-or-state)
*/
export function usePrevious<T>(value: T): T | undefined {
const ref = useRef<T | undefined>();
useEffect(() => {
ref.current = value;
});
return ref.current;
}
``` | /content/code_sandbox/packages/react-hooks/src/usePrevious.ts | xml | 2016-06-06T15:03:44 | 2024-08-16T18:49:29 | fluentui | microsoft/fluentui | 18,221 | 99 |
```xml
import React, { MouseEventHandler } from 'react'
import NavigationBarButton from './NavigationBarButton'
import Icon from '../../../design/components/atoms/Icon'
import { mdiArrowLeft } from '@mdi/js'
interface NavigationBarBackButtonProps {
onClick: MouseEventHandler<HTMLButtonElement>
}
const NavigationBarBackButton = ({ onClick }: NavigationBarBackButtonProps) => {
return (
<NavigationBarButton onClick={onClick}>
<Icon size={20} path={mdiArrowLeft} /> Back
</NavigationBarButton>
)
}
export default NavigationBarBackButton
``` | /content/code_sandbox/src/mobile/components/atoms/NavigationBarBackButton.tsx | xml | 2016-11-19T14:30:34 | 2024-08-16T03:13:45 | BoostNote-App | BoostIO/BoostNote-App | 3,745 | 118 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<!--
~
~
~ path_to_url
~
~ Unless required by applicable law or agreed to in writing, software
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-->
<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<string name="material_timepicker_pm">PM</string>
<string name="material_timepicker_am">AM</string>
<string name="material_timepicker_select_time">Vyberte as</string>
<string name="material_timepicker_minute">Minta</string>
<string name="material_timepicker_hour">Hodina</string>
<string name="material_hour_suffix">%1$s</string>
<string name="material_hour_24h_suffix">%1$shodn</string>
<string name="material_minute_suffix">%1$smin</string>
<string name="material_hour_selection">Vybra hodinu</string>
<string name="material_minute_selection">Vyberte minty</string>
<string name="material_clock_toggle_content_description">Vyberte AM alebo PM</string>
<string name="mtrl_timepicker_confirm">OK</string>
<string name="mtrl_timepicker_cancel">Zrui</string>
<string name="material_timepicker_text_input_mode_description">Ak chcete zada as, prepnite na textov reim vstupu</string>
<string name="material_timepicker_clock_mode_description">Ak chcete zada as, prepnite na reim hodn.</string>
</resources>
``` | /content/code_sandbox/lib/java/com/google/android/material/timepicker/res/values-sk/strings.xml | xml | 2016-12-05T16:11:29 | 2024-08-16T17:51:42 | material-components-android | material-components/material-components-android | 16,176 | 363 |
```xml
import { normalizedAssetPrefix } from './normalized-asset-prefix'
describe('normalizedAssetPrefix', () => {
it('should return an empty string when assetPrefix is nullish', () => {
expect(normalizedAssetPrefix(undefined)).toBe('')
})
it('should return an empty string when assetPrefix is an empty string', () => {
expect(normalizedAssetPrefix('')).toBe('')
})
it('should return an empty string when assetPrefix is a single slash', () => {
expect(normalizedAssetPrefix('/')).toBe('')
})
// we expect an empty string because it could be an unnecessary trailing slash
it('should remove leading slash(es) when assetPrefix has more than one', () => {
expect(normalizedAssetPrefix('///path/to/asset')).toBe('/path/to/asset')
})
it('should not remove the leading slash when assetPrefix has only one', () => {
expect(normalizedAssetPrefix('/path/to/asset')).toBe('/path/to/asset')
})
it('should add a leading slash when assetPrefix is missing one', () => {
expect(normalizedAssetPrefix('path/to/asset')).toBe('/path/to/asset')
})
it('should remove all trailing slash(es) when assetPrefix has one', () => {
expect(normalizedAssetPrefix('/path/to/asset///')).toBe('/path/to/asset')
})
it('should return the URL when assetPrefix is a URL', () => {
expect(normalizedAssetPrefix('path_to_url
'path_to_url
)
})
it('should not leave a trailing slash when assetPrefix is a URL with no pathname', () => {
expect(normalizedAssetPrefix('path_to_url
'path_to_url
)
})
})
``` | /content/code_sandbox/packages/next/src/shared/lib/normalized-asset-prefix.test.ts | xml | 2016-10-05T23:32:51 | 2024-08-16T19:44:30 | next.js | vercel/next.js | 124,056 | 375 |
```xml
import { c } from 'ttag';
import type { WasmApiWalletAccount, WasmInviteNotificationType } from '@proton/andromeda';
import { Icon, useModalStateWithData } from '@proton/components/components';
import { useContactEmailsCache } from '@proton/components/containers/contacts/ContactEmailsProvider';
import useVerifyOutboundPublicKeys from '@proton/components/containers/keyTransparency/useVerifyOutboundPublicKeys';
import { useApi, useNotifications } from '@proton/components/hooks';
import type { PublicKeyReference } from '@proton/crypto/lib';
import { CryptoProxy } from '@proton/crypto/lib';
import useLoading from '@proton/hooks/useLoading';
import { getAndVerifyApiKeys } from '@proton/shared/lib/api/helpers/getAndVerifyApiKeys';
import { WALLET_APP_NAME } from '@proton/shared/lib/constants';
import { validateEmailAddress } from '@proton/shared/lib/helpers/email';
import type { ProcessedApiKey, Recipient } from '@proton/shared/lib/interfaces';
import { getKeyHasFlagsToVerify } from '@proton/shared/lib/keys';
import {
MAX_RECIPIENTS_PER_TRANSACTIONS,
useBitcoinNetwork,
useWalletApiClients,
verifySignedData,
} from '@proton/wallet';
import { Button } from '../../atoms';
import type { TxBuilderHelper } from '../../hooks/useTxBuilder';
import { isUndefined, isValidBitcoinAddress } from '../../utils';
import { EmailOrBitcoinAddressInput } from '../EmailOrBitcoinAddressInput';
import type { useEmailAndBtcAddressesMaps } from '../EmailOrBitcoinAddressInput/useEmailAndBtcAddressesMaps';
import { InvalidRecipientErrorCode } from '../EmailOrBitcoinAddressInput/useEmailAndBtcAddressesMaps';
import { InviteSentConfirmModal } from '../InviteSentConfirmModal';
import { RecipientDetailsModal } from '../RecipientDetailsModal';
import { WalletNotFoundError } from './WalletNotFoundError/WalletNotFoundErrorDropdown';
import { WalletNotFoundErrorModal } from './WalletNotFoundError/WalletNotFoundErrorModal';
interface Props {
apiAccount: WasmApiWalletAccount;
recipientHelpers: ReturnType<typeof useEmailAndBtcAddressesMaps>;
onRecipientsConfirm: () => void;
txBuilderHelpers: TxBuilderHelper;
}
interface WalletNotFoundModalData {
email: string;
textContent: string;
error: InvalidRecipientErrorCode;
type: WasmInviteNotificationType;
}
const getVerifiedAddressKey = async (
addressKeys: ProcessedApiKey[],
btcAddress: string,
btcAddressSignature: string
): Promise<PublicKeyReference | undefined> => {
const keys = await Promise.allSettled(
addressKeys
.filter((k) => {
return getKeyHasFlagsToVerify(k.flags);
})
.map(async (addressKey) => {
const pubkey = await CryptoProxy.importPublicKey({ armoredKey: addressKey.armoredKey });
const isVerified = await verifySignedData(btcAddress, btcAddressSignature, 'wallet.bitcoin-address', [
pubkey,
]);
return isVerified ? pubkey : null;
})
);
const [firstAddressKey] = keys
.map((result) => ('value' in result ? result.value : undefined))
.filter((key): key is PublicKeyReference => !!key);
return firstAddressKey;
};
export const RecipientsSelection = ({ apiAccount, recipientHelpers, txBuilderHelpers, onRecipientsConfirm }: Props) => {
const {
recipientEmailMap,
addValidRecipient,
addInvalidRecipient,
removeRecipient,
exists,
addRecipientWithSentInvite,
checkHasSentInvite,
} = recipientHelpers;
const { updateTxBuilder, txBuilder } = txBuilderHelpers;
const verifyOutboundPublicKeys = useVerifyOutboundPublicKeys();
const { contactEmails, contactEmailsMap } = useContactEmailsCache();
const [loadingBitcoinAddressLookup, withLoadingBitcoinAddressLookup] = useLoading();
const [walletNotFoundModal, setWalletNotFoundModal] = useModalStateWithData<WalletNotFoundModalData>();
const { createNotification } = useNotifications();
const [inviteSentConfirmModal, setInviteSentConfirmModal] = useModalStateWithData<{ email: string }>();
const [recipientDetailsModal, setRecipientDetailsModal] = useModalStateWithData<{
recipient: Recipient;
btcAddress: string;
index: number;
}>();
const [network] = useBitcoinNetwork();
const walletApi = useWalletApiClients();
const api = useApi();
const [loading, withLoading] = useLoading();
const safeAddRecipient = (
recipientOrBitcoinAddress: Recipient,
btcAddress: string,
addressKey?: PublicKeyReference
) => {
if (!exists(recipientOrBitcoinAddress)) {
addValidRecipient(recipientOrBitcoinAddress, btcAddress, addressKey);
updateTxBuilder((txBuilder) => txBuilder.addRecipient(btcAddress));
}
};
const handleSendEmailInvite = async (type: 'bve' | 'newcomer', email: string, inviterAddressID: string) => {
try {
await withLoading(
type === 'bve'
? walletApi.invite.sendEmailIntegrationInvite(email, inviterAddressID)
: walletApi.invite.sendNewcomerInvite(email, inviterAddressID)
);
walletNotFoundModal.onClose();
setInviteSentConfirmModal({ email });
addRecipientWithSentInvite(email);
createNotification({ text: c('Bitcoin send').t`Invitation sent to the recipient` });
} catch (error: any) {
createNotification({
text: error?.error ?? c('Bitcoin send').t`Could not send invitation to the recipient`,
});
}
};
const handleAddRecipients = async (recipientOrBitcoinAddresses: Recipient[]) => {
if (isUndefined(network)) {
return;
}
const remainingSlot = Math.max(MAX_RECIPIENTS_PER_TRANSACTIONS - Object.values(recipientEmailMap).length, 0);
for (const recipientOrBitcoinAddress of recipientOrBitcoinAddresses.slice(0, remainingSlot)) {
if (validateEmailAddress(recipientOrBitcoinAddress?.Address)) {
try {
const bitcoinAddress = await walletApi.email_integration.lookupBitcoinAddress(
recipientOrBitcoinAddress.Address
);
const btcAddress = bitcoinAddress.Data.BitcoinAddress;
const btcAddressSignature = bitcoinAddress.Data.BitcoinAddressSignature;
if (!btcAddress) {
addInvalidRecipient(
recipientOrBitcoinAddress,
InvalidRecipientErrorCode.NoAddressSetOnBitcoinAddress
);
continue;
}
if (!btcAddressSignature) {
addInvalidRecipient(
recipientOrBitcoinAddress,
InvalidRecipientErrorCode.NoSignatureSetOnBitcoinAddress
);
continue;
}
// Bitcoin address signature verification
const { addressKeys } = await getAndVerifyApiKeys({
api,
email: recipientOrBitcoinAddress.Address,
internalKeysOnly: true,
verifyOutboundPublicKeys,
});
const addressKey = await getVerifiedAddressKey(addressKeys, btcAddress, btcAddressSignature);
if (!addressKey) {
addInvalidRecipient(
recipientOrBitcoinAddress,
InvalidRecipientErrorCode.BitcoinAddressSignatureCouldNotBeVerified
);
} else {
safeAddRecipient(recipientOrBitcoinAddress, btcAddress, addressKey);
}
} catch (error: any) {
const code = error.code as number;
if (code === 2028) {
createNotification({ text: error.details, type: 'error' });
return;
}
if (code === 2000) {
return addInvalidRecipient(
recipientOrBitcoinAddress,
InvalidRecipientErrorCode.NoBitcoinAddressAvailable
);
}
const [errorCode, type, textContent] =
code === 2001
? ([
InvalidRecipientErrorCode.CouldNotFindProtonWallet,
'Newcomer',
c('Bitcoin send')
.t`This email is not using a ${WALLET_APP_NAME} yet. Invite them to create their own wallet for easier transactions.`,
] as const)
: ([
InvalidRecipientErrorCode.CouldNotFindBitcoinAddressLinkedToEmail,
'EmailIntegration',
c('Bitcoin send')
.t`This user may not have a ${WALLET_APP_NAME} integrated with their email yet. Send them an email to tell them you would like to send them bitcoin.`,
] as const);
setWalletNotFoundModal({
email: recipientOrBitcoinAddress.Address,
textContent,
error: errorCode,
type,
});
addInvalidRecipient(recipientOrBitcoinAddress, errorCode);
}
} else if (isValidBitcoinAddress(recipientOrBitcoinAddress.Address, network)) {
safeAddRecipient(recipientOrBitcoinAddress, recipientOrBitcoinAddress.Address);
} else {
addInvalidRecipient(recipientOrBitcoinAddress, InvalidRecipientErrorCode.InvalidAddress);
}
}
};
const handleRemoveRecipient = (recipient: Recipient) => {
const recipientToRemove = recipientEmailMap[recipient.Address];
const indexToRemove = txBuilder.getRecipients().findIndex((r) => r[1] === recipientToRemove?.btcAddress.value);
updateTxBuilder((txBuilder) => txBuilder.removeRecipient(indexToRemove));
removeRecipient(recipient);
};
if (isUndefined(network)) {
return null;
}
return (
<>
<div className="relative flex flex-column max-w-full justify-center">
<h2 className="text-center mb-8 text-semibold">{c('Wallet send')
.t`Who are you sending Bitcoin to?`}</h2>
<EmailOrBitcoinAddressInput
disabled={Object.values(loadingBitcoinAddressLookup).some((v) => Boolean(v))}
placeholder={'andy.yen@proton.ch / bc1...'}
contactEmails={contactEmails}
contactEmailsMap={contactEmailsMap}
recipientEmailMap={recipientEmailMap}
network={network}
loading={loadingBitcoinAddressLookup}
fetchedEmailListItemRightNode={({ email, error }) => {
if (error === InvalidRecipientErrorCode.CouldNotFindBitcoinAddressLinkedToEmail) {
const textContent = c('Bitcoin send')
.t`This user may not have a ${WALLET_APP_NAME} integrated with their email yet. Send them an email to tell them you would like to send them bitcoin.`;
return (
<WalletNotFoundError
hasSentInvite={checkHasSentInvite(email)}
email={email}
onSendInvite={() => {
setWalletNotFoundModal({
email,
textContent,
error,
type: 'EmailIntegration',
});
}}
/>
);
}
if (error === InvalidRecipientErrorCode.CouldNotFindProtonWallet) {
const textContent = c('Bitcoin send')
.t`This email is not using a ${WALLET_APP_NAME} yet. Invite them to create their own wallet for easier transactions.`;
return (
<WalletNotFoundError
hasSentInvite={checkHasSentInvite(email)}
email={email}
onSendInvite={() => {
setWalletNotFoundModal({
email,
textContent,
error,
type: 'Newcomer',
});
}}
/>
);
}
if (error === InvalidRecipientErrorCode.InvalidAddress) {
return (
<span className="block text-sm color-danger w-1/3">{c('Wallet send')
.t`Address is neither a valid bitcoin or email address`}</span>
);
}
if (error === InvalidRecipientErrorCode.NoBitcoinAddressAvailable) {
return (
<span className="block text-sm color-danger w-1/3">{c('Wallet send')
.t`Recipient has no bitcoin address available`}</span>
);
}
if (error) {
return (
<span className="block text-sm color-danger w-1/3">{c('Wallet send')
.t`Bitcoin address signature could not be verified`}</span>
);
}
return (
<span className="mr-1 color-weak shrink-0">
<Icon name="chevron-right" className="my-auto" />
</span>
);
}}
onClickRecipient={(recipient, btcAddress, index) => {
if (btcAddress.value) {
setRecipientDetailsModal({ recipient, btcAddress: btcAddress.value, index });
}
}}
onAddRecipients={(recipients: Recipient[]) => {
void withLoadingBitcoinAddressLookup(handleAddRecipients(recipients));
}}
onRemoveRecipient={(recipient: Recipient) => handleRemoveRecipient(recipient)}
/>
{txBuilder.getRecipients().length ? (
<div className="px-10 mt-6">
<Button
color="norm"
shape="solid"
size="large"
shadow
fullWidth
onClick={() => {
onRecipientsConfirm();
}}
>{c('Wallet send').t`Confirm`}</Button>
</div>
) : null}
</div>
{recipientDetailsModal.data && (
<RecipientDetailsModal {...recipientDetailsModal.data} {...recipientDetailsModal} />
)}
{walletNotFoundModal.data && (
<WalletNotFoundErrorModal
onSendInvite={(email, inviterAddressId) => {
const type =
walletNotFoundModal.data?.error === InvalidRecipientErrorCode.CouldNotFindProtonWallet
? 'newcomer'
: 'bve';
void handleSendEmailInvite(type, email, inviterAddressId);
}}
defaultInviterAddressID={apiAccount.Addresses?.[0]?.ID}
email={walletNotFoundModal.data.email}
textContent={walletNotFoundModal.data.textContent}
type={walletNotFoundModal.data.type}
loading={loading}
checkHasSentInvite={checkHasSentInvite}
{...walletNotFoundModal}
/>
)}
{inviteSentConfirmModal.data && (
<InviteSentConfirmModal email={inviteSentConfirmModal.data.email} {...inviteSentConfirmModal} />
)}
</>
);
};
``` | /content/code_sandbox/applications/wallet/src/app/components/BitcoinSendModal/RecipientsSelection.tsx | xml | 2016-06-08T11:16:51 | 2024-08-16T14:14:27 | WebClients | ProtonMail/WebClients | 4,300 | 3,009 |
```xml
import * as compose from "lodash.flowright";
import { ChildProps, graphql } from "@apollo/client/react/hoc";
import ButtonMutate from "@erxes/ui/src/components/ButtonMutate";
import { IButtonMutateProps } from "@erxes/ui/src/types";
import { BoardsQueryResponse as PurchasesBoardsQueryResponse } from "@erxes/ui-purchases/src/boards/types";
import React from "react";
import { BoardsQueryResponse as SalesBoardsQueryResponse } from "@erxes/ui-sales/src/boards/types";
import SelectBoards from "../components/SelectBoardPipeline";
import Spinner from "@erxes/ui/src/components/Spinner";
import { BoardsQueryResponse as TasksBoardsQueryResponse } from "@erxes/ui-tasks/src/boards/types";
import { BoardsQueryResponse as TicketsBoardsQueryResponse } from "@erxes/ui-tickets/src/boards/types";
import { gql } from "@apollo/client";
import { mutations as purchasesMutations } from "@erxes/ui-purchases/src/settings/boards/graphql";
import { queries as purchasesQueries } from "@erxes/ui-purchases/src/boards/graphql";
import { mutations as salesMutations } from "@erxes/ui-sales/src/settings/boards/graphql";
import { queries as salesQueries } from "@erxes/ui-sales/src/boards/graphql";
import { mutations as tasksMutations } from "@erxes/ui-tasks/src/settings/boards/graphql";
import { queries as tasksQueries } from "@erxes/ui-tasks/src/boards/graphql";
import { mutations as ticketsMutations } from "@erxes/ui-tickets/src/settings/boards/graphql";
import { queries as ticketsQueries } from "@erxes/ui-tickets/src/boards/graphql";
import { withProps } from "@erxes/ui/src/utils";
type Props = {
onChangeItems: (items: any) => any;
selectedItems: any[];
isRequired?: boolean;
description?: string;
type: string;
};
type FinalProps = {
salesBoardsQuery: SalesBoardsQueryResponse;
ticketsdBoardsQuery: TicketsBoardsQueryResponse;
tasksBoardsQuery: TasksBoardsQueryResponse;
purchasesBoardsQuery: PurchasesBoardsQueryResponse;
} & Props;
const SelectContainer = (props: ChildProps<FinalProps>) => {
const {
salesBoardsQuery,
ticketsdBoardsQuery,
tasksBoardsQuery,
purchasesBoardsQuery,
type,
} = props;
let boardsQuery:
| SalesBoardsQueryResponse
| TicketsBoardsQueryResponse
| TasksBoardsQueryResponse
| PurchasesBoardsQueryResponse
| undefined;
let mutations;
let queryResponse;
switch (type) {
case "deal":
boardsQuery = salesBoardsQuery;
mutations = salesMutations;
queryResponse = "salesBoards";
break;
case "ticket":
boardsQuery = ticketsdBoardsQuery;
mutations = ticketsMutations;
queryResponse = "ticketsBoards";
break;
case "task":
boardsQuery = tasksBoardsQuery;
mutations = tasksMutations;
queryResponse = "tasksBoards";
break;
case "purchase":
boardsQuery = purchasesBoardsQuery;
mutations = purchasesMutations;
queryResponse = "purchasesBoards";
break;
}
if (!boardsQuery) {
return null;
}
const boards = boardsQuery[queryResponse] || [];
if (boardsQuery.loading) {
return <Spinner objective={true} />;
}
const renderButton = ({
name,
values,
isSubmitted,
callback,
}: IButtonMutateProps) => {
const callBackResponse = () => {
boardsQuery && boardsQuery.refetch();
if (callback) {
callback();
}
};
return (
<ButtonMutate
mutation={mutations.boardAdd}
variables={values}
callback={callBackResponse}
isSubmitted={isSubmitted}
type="submit"
successMessage={`You successfully added a ${name}`}
/>
);
};
const updatedProps = {
...props,
boards,
items: [],
renderButton,
};
return <SelectBoards {...updatedProps} />;
};
const getRefetchQueries = () => {
return [
{
query: gql(salesQueries.boards),
variables: {},
},
];
};
export default withProps<Props>(
compose(
graphql<Props, SalesBoardsQueryResponse, { type: string }>(
gql(salesQueries.boards),
{
name: "salesBoardsQuery",
options: ({ type }) => ({
variables: {
type,
},
refetchQueries: getRefetchQueries,
}),
}
),
graphql<Props, TicketsBoardsQueryResponse, { type: string }>(
gql(ticketsQueries.boards),
{
name: "ticketsdBoardsQuery",
options: ({ type }) => ({
variables: {
type,
},
refetchQueries: getRefetchQueries,
}),
}
),
graphql<Props, TasksBoardsQueryResponse, { type: string }>(
gql(tasksQueries.boards),
{
name: "tasksBoardsQuery",
options: ({ type }) => ({
variables: {
type,
},
refetchQueries: getRefetchQueries,
}),
}
),
graphql<Props, PurchasesBoardsQueryResponse, { type: string }>(
gql(purchasesQueries.boards),
{
name: "purchasesBoardsQuery",
options: ({ type }) => ({
variables: {
type,
},
refetchQueries: getRefetchQueries,
}),
}
)
)(SelectContainer)
);
``` | /content/code_sandbox/packages/ui-forms/src/settings/properties/containers/SelectBoardPipeline.tsx | xml | 2016-11-11T06:54:50 | 2024-08-16T10:26:06 | erxes | erxes/erxes | 3,479 | 1,222 |
```xml
import {
ParseOptions,
RegexpToFunctionOptions,
TokensToFunctionOptions,
TokensToRegexpOptions,
} from 'path-to-regexp'
import {FunctionComponent} from 'react'
export declare type RouterProps = {
location: string|undefined|null,
options?: ParseOptions & TokensToRegexpOptions & RegexpToFunctionOptions,
}
export declare const Router: FunctionComponent<RouterProps>
export declare function genLocation(
path: string,
params?: object,
options?: ParseOptions & TokensToFunctionOptions,
): string
export declare function loc(
path: string,
params?: object,
options?: ParseOptions & TokensToFunctionOptions,
): string
export declare function isPath(
path: string,
location: string,
options?: TokensToRegexpOptions & ParseOptions,
): boolean
export declare type SearchResult = {
path: string,
params: object[],
}
export declare function findPath(
paths: string[],
location: string,
options?: ParseOptions & TokensToRegexpOptions & RegexpToFunctionOptions,
): SearchResult|void
export declare type SearchValueResult = {
path: string,
value: any,
params: object[],
}
export declare function findPathValue(
obj: object,
location: string,
options?: ParseOptions & TokensToRegexpOptions & RegexpToFunctionOptions,
): SearchValueResult|void
``` | /content/code_sandbox/index.d.ts | xml | 2016-06-15T13:57:44 | 2024-08-12T10:51:34 | react-enroute | tj/react-enroute | 1,490 | 300 |
```xml
import Link from 'next/link'
// We want to trace this fetch in runtime
export const dynamic = 'force-dynamic'
export default async function Page() {
await new Promise((resolve) => setTimeout(resolve, 5000))
return (
<>
<p>app/loading/page1</p>
<Link href="/app/loading/page2">Page2</Link>
</>
)
}
``` | /content/code_sandbox/test/e2e/opentelemetry/instrumentation/app/app/[param]/loading/page1/page.tsx | xml | 2016-10-05T23:32:51 | 2024-08-16T19:44:30 | next.js | vercel/next.js | 124,056 | 85 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="path_to_url">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>9.0.21022</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{C5AE4EF3-23FC-47D9-968D-41AA3E4A4B31}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>SqlDatabaseSample</RootNamespace>
<AssemblyName>SqlDatabaseSample</AssemblyName>
<TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<FileUpgradeFlags>
</FileUpgradeFlags>
<OldToolsVersion>4.0</OldToolsVersion>
<UpgradeBackupLocation>
</UpgradeBackupLocation>
<PublishUrl>publish\</PublishUrl>
<Install>true</Install>
<InstallFrom>Disk</InstallFrom>
<UpdateEnabled>false</UpdateEnabled>
<UpdateMode>Foreground</UpdateMode>
<UpdateInterval>7</UpdateInterval>
<UpdateIntervalUnits>Days</UpdateIntervalUnits>
<UpdatePeriodically>false</UpdatePeriodically>
<UpdateRequired>false</UpdateRequired>
<MapFileExtensions>true</MapFileExtensions>
<ApplicationRevision>0</ApplicationRevision>
<ApplicationVersion>1.0.0.%2a</ApplicationVersion>
<IsWebBootstrapper>false</IsWebBootstrapper>
<UseApplicationTrust>false</UseApplicationTrust>
<BootstrapperEnabled>true</BootstrapperEnabled>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\SqlDatabase\</OutputPath>
<IntermediateOutputPath>bin\SqlDatabase\obj\</IntermediateOutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\SqlDatabase\</OutputPath>
<IntermediateOutputPath>bin\SqlDatabase\obj\</IntermediateOutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml.Linq">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
<Reference Include="System.Data.DataSetExtensions">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\WixSharp\WixSharp.csproj">
<Project>{8860B29B-749F-4925-86C8-F9C4B93C9DA5}</Project>
<Name>WixSharp</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<BootstrapperPackage Include="Microsoft.Net.Client.3.5">
<Visible>False</Visible>
<ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName>
<Install>false</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">
<Visible>False</Visible>
<ProductName>.NET Framework 3.5 SP1</ProductName>
<Install>true</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Windows.Installer.3.1">
<Visible>False</Visible>
<ProductName>Windows Installer 3.1</ProductName>
<Install>true</Install>
</BootstrapperPackage>
</ItemGroup>
<ItemGroup>
<Compile Include="..\Wix# Samples\SqlDatabase\setup.cs">
<Link>setup.cs</Link>
</Compile>
</ItemGroup>
<ItemGroup>
<None Include="app.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
``` | /content/code_sandbox/Source/src/WixSharp.Samples/VSProjects/SqlDatabase.csproj | xml | 2016-01-16T05:51:01 | 2024-08-16T12:26:25 | wixsharp | oleg-shilo/wixsharp | 1,077 | 1,219 |
```xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<types>
<composite name="messageHeader" description="Message identifiers and length of message root">
<type name="blockLength" primitiveType="uint16"/>
<type name="templateId" primitiveType="uint16"/>
<type name="schemaId" primitiveType="uint16"/>
<type name="version" primitiveType="uint16"/>
</composite>
<composite name="varDataEncoding">
<type name="length" primitiveType="uint32" maxValue="2147483647"/>
<type name="varData" primitiveType="uint8" length="0" characterEncoding="UTF-8"/>
</composite>
<composite name="groupSizeEncoding" description="Repeating group dimensions">
<type name="blockLength" primitiveType="uint16"/>
<type name="numInGroup" primitiveType="uint8" semanticType="NumInGroup"/>
</composite>
<enum name="BooleanType" encodingType="uint8" semanticType="Boolean">
<validValue name="FALSE">0</validValue>
<validValue name="TRUE">1</validValue>
</enum>
</types>
``` | /content/code_sandbox/zeebe/protocol/src/main/resources/common-types.xml | xml | 2016-03-20T03:38:04 | 2024-08-16T19:59:58 | camunda | camunda/camunda | 3,172 | 265 |
```xml
import ExecutionEnvironment from '@docusaurus/ExecutionEnvironment';
import type { ClientModule } from '@docusaurus/types';
import versions from '../versions.json';
declare global {
const gtag: any;
}
export default (function (): ClientModule | undefined {
if (!ExecutionEnvironment.canUseDOM) {
return;
}
return {
onRouteUpdate({ location }) {
if (!location || !location.pathname) return;
const paths = location.pathname?.split('/').filter(Boolean);
if (paths[0] !== 'docs') return;
let version = '',
component = '';
if (paths[1] == 'next' || versions.includes(paths[1])) {
version = paths[1];
component = paths[3] || paths[2] || 'overview';
} else {
version = versions[0];
component = paths[2] || paths[1] || 'overview';
}
// @ts-ignore
if (!window.gtag) return;
if (version && component) {
gtag('event', 'doc_view', {
version,
component,
docID: `${version} - ${component}`,
});
}
// if (version) {
// version = version.replace(/\.|-/g, '_');
// gtag('event', `version_${version}`, {
// component,
// });
// }
},
};
})();
``` | /content/code_sandbox/website/plugins/gtag.ts | xml | 2016-09-08T14:21:41 | 2024-08-16T10:11:29 | react-native-elements | react-native-elements/react-native-elements | 24,875 | 305 |
```xml
import * as vscode from 'vscode';
import { macrosOf } from './macros';
import { Diagram } from '../diagram/diagram';
export async function MacroCompletionItems(target: vscode.TextDocument | Diagram, position: vscode.Position, token: vscode.CancellationToken): Promise<vscode.CompletionItem[]> {
if (!target) return [];
return new Promise<vscode.CompletionItem[]>((resolve, reject) => {
const results: vscode.CompletionItem[] = [];
const macros = macrosOf(target, position);
macros
.forEach(macro => {
const item = new vscode.CompletionItem(macro.name, vscode.CompletionItemKind.Method);
item.detail = macro.getDetailLabel();
item.insertText = new vscode.SnippetString(macro.name);
results.push(item);
});
return resolve(results);
});
}
``` | /content/code_sandbox/src/plantuml/intellisense/macroCompletion.ts | xml | 2016-11-18T14:14:05 | 2024-08-11T10:43:40 | vscode-plantuml | qjebbs/vscode-plantuml | 1,078 | 179 |
```xml
import { useCallback } from 'react';
import { c } from 'ttag';
import { useModalTwoStatic } from '@proton/components/components';
import { labelContactEmails, unLabelContactEmails } from '@proton/shared/lib/api/contacts';
import { hasReachedContactGroupMembersLimit } from '@proton/shared/lib/contacts/helpers/contactGroup';
import type { Contact, ContactEmail } from '@proton/shared/lib/interfaces/contacts';
import {
useApi,
useContactEmails,
useContactGroups,
useContacts,
useEventManager,
useMailSettings,
useNotifications,
} from '../../../hooks';
import ContactGroupLimitReachedModal from '../modals/ContactGroupLimitReachedModal';
import type { SelectEmailsProps } from '../modals/SelectEmailsModal';
/**
* Collect contacts having multiple emails
* Used for <SelectEmailsModal />
*/
export const collectContacts = (contactEmails: ContactEmail[] = [], contacts: Contact[]) => {
return contactEmails.reduce(
(acc, { ContactID }) => {
acc.duplicate[ContactID] = (acc.duplicate[ContactID] || 0) + 1;
if (acc.duplicate[ContactID] === 2) {
const contact = contacts.find(({ ID }: { ID: string }) => ID === ContactID);
if (contact) {
acc.contacts.push(contact);
}
}
return acc;
},
{
contacts: [] as Contact[],
duplicate: Object.create(null),
}
);
};
/**
* Returns a reusable action to apply or remove groups to a list of contact emails
*/
const useApplyGroups = (
onLock?: (lock: boolean) => void,
setLoading?: (loading: boolean) => void,
onSelectEmails?: (props: SelectEmailsProps) => Promise<ContactEmail[]>
) => {
const [mailSettings] = useMailSettings();
const { createNotification } = useNotifications();
const { call } = useEventManager();
const api = useApi();
const contacts = useContacts()[0] || [];
const userContactEmails = useContactEmails()[0] || [];
const [groups = []] = useContactGroups();
const [contactGroupLimitReachedModal, handleShowContactGroupLimitReachedModal] =
useModalTwoStatic(ContactGroupLimitReachedModal);
const applyGroups = useCallback(
async (contactEmails: ContactEmail[], changes: { [groupID: string]: boolean }, preventNotification = false) => {
const { contacts: collectedContacts } = collectContacts(contactEmails, contacts);
// contact emails in contacts with only one email (and then, skipping the modal)
const simpleEmails = contactEmails.filter(
(contactEmail) => !collectedContacts.find((contact) => contactEmail.ContactID === contact.ID)
);
// contact emails in contacts with multiple email (and then, passing through the modal)
let selectedEmails: ContactEmail[] = [];
if (collectedContacts.length) {
const groupIDs = Object.entries(changes)
.filter(([, isChecked]) => isChecked)
.map(([groupID]) => groupID);
if (groupIDs.length) {
setLoading?.(false);
selectedEmails = (await onSelectEmails?.({ groupIDs, contacts: collectedContacts, onLock })) || [];
setLoading?.(true);
}
}
// When removing a group, we remove it for all emails selected
const listForRemoving = [...contactEmails];
// When adding a group, we do it only for the selected ones
const listForAdding = [...simpleEmails, ...selectedEmails];
const groupEntries = Object.entries(changes);
const cannotAddContactInGroupIDs: string[] = [];
await Promise.all(
groupEntries.map(([groupID, isChecked]) => {
const contactGroup = groups.find((group) => group.ID === groupID);
const contactGroupName = contactGroup?.Name;
if (isChecked) {
const groupExistingMembers =
groupID &&
userContactEmails.filter(({ LabelIDs = [] }: { LabelIDs: string[] }) =>
LabelIDs.includes(groupID)
);
const toLabel = listForAdding
.filter(({ LabelIDs = [] }) => !LabelIDs.includes(groupID))
.map(({ ID }) => ID);
if (!toLabel.length) {
return Promise.resolve();
}
// Cannot add more than 100 contacts in a contact group
const canAddContact = hasReachedContactGroupMembersLimit(
groupExistingMembers.length + toLabel.length,
mailSettings,
false
);
if (!canAddContact) {
cannotAddContactInGroupIDs.push(groupID);
return Promise.resolve();
}
if (!preventNotification && contactGroupName) {
const notificationText = c('Info').t`Contact assigned to group ${contactGroupName}`;
createNotification({ text: notificationText });
}
return api(labelContactEmails({ LabelID: groupID, ContactEmailIDs: toLabel }));
}
const toUnlabel = listForRemoving
.filter(({ LabelIDs = [] }) => LabelIDs.includes(groupID))
.map(({ ID }) => ID);
if (!toUnlabel.length) {
return Promise.resolve();
}
if (!preventNotification && contactGroupName) {
const notificationText = c('Info').t`Contact unassigned to group ${contactGroupName}`;
createNotification({ text: notificationText });
}
return api(unLabelContactEmails({ LabelID: groupID, ContactEmailIDs: toUnlabel }));
})
);
if (cannotAddContactInGroupIDs.length > 0) {
void handleShowContactGroupLimitReachedModal({ groupIDs: cannotAddContactInGroupIDs });
}
await call();
},
[contacts, userContactEmails]
);
return { applyGroups, contactGroupLimitReachedModal };
};
export default useApplyGroups;
``` | /content/code_sandbox/packages/components/containers/contacts/hooks/useApplyGroups.tsx | xml | 2016-06-08T11:16:51 | 2024-08-16T14:14:27 | WebClients | ProtonMail/WebClients | 4,300 | 1,270 |
```xml
import { Emitter, Disposable } from 'event-kit'
import * as ipcRenderer from '../../lib/ipc-renderer'
/**
* Describes the interface of a UI activity monitor.
*
* We define a UI activity monitor as an object which can
* be used to be notified whenever the user interacts with the
* application.
*/
export interface IUiActivityMonitor {
/**
* Subscribe to get notified when the user interacts
* with the application. The first, and only argument
* to the event handler will be a value indicating the
* kind of action detected (mouse/pointer, keyboard etc).
*
* @returns A disposable object which, when disposed will
* terminate the subscription and prevent any
* further calls to the handler.
*/
onActivity(handler: (kind: UiActivityKind) => void): Disposable
}
/**
* A value indicating a user activity type (mouse/pointer, keyboard etc).
*/
export type UiActivityKind = 'pointer' | 'keyboard' | 'menu'
/**
* UI Activity monitor for user interactions within GitHub Desktop.
*/
export class UiActivityMonitor implements IUiActivityMonitor {
private readonly emitter = new Emitter()
private subscriberCount = 0
/**
* Subscribe to get notified when the user interacts
* with the application. The first, and only argument
* to the event handler will be a value indicating the
* kind of action detected (mouse/pointer, keyboard etc).
*
* @returns A disposable object which, when disposed will
* terminate the subscription and prevent any
* further calls to the handler.
*/
public onActivity(handler: (kind: UiActivityKind) => void): Disposable {
const emitterDisposable = this.emitter.on('activity', handler)
if (this.subscriberCount === 0) {
this.startTracking()
}
this.subscriberCount++
return new Disposable(() => {
this.subscriberCount--
if (this.subscriberCount === 0) {
this.stopTracking()
}
emitterDisposable.dispose()
})
}
private emit(kind: UiActivityKind) {
this.emitter.emit('activity', kind)
}
private startTracking() {
document.addEventListener('mousedown', this.onMouseDown)
document.addEventListener('keydown', this.onKeyDown)
ipcRenderer.on('menu-event', this.onMenuEvent)
}
private stopTracking() {
document.removeEventListener('mousedown', this.onMouseDown)
document.removeEventListener('keydown', this.onKeyDown)
ipcRenderer.removeListener('menu-event', this.onMenuEvent)
}
private onMouseDown = (e: MouseEvent) => {
if (e.target === null || !(e.target instanceof HTMLElement)) {
return
}
if (!isInteractionTarget(e.target)) {
return
}
this.emit('pointer')
}
private onKeyDown = (e: KeyboardEvent) => {
this.emit('keyboard')
}
private onMenuEvent = () => this.emit('menu')
}
const interactionTargets = new Set(
['button', 'a', 'input', 'textarea', 'label'].map(x => x.toUpperCase())
)
const interactionRoles = new Set([
'button',
'option',
'menuitem',
'tab',
'radio',
])
/**
* Determine if the target of a pointer event is contained within,
* or is itself, an "interaction target".
*
* We define an interaction target to be things like buttons, text
* inputs, links, etc. We don't consider divs, spans, etc to be
* interaction targets at the moment although they arguable would fit
* the description when a user selects text within a span.
*/
function isInteractionTarget(target: HTMLElement | null) {
while (target !== null) {
if (interactionTargets.has(target.nodeName)) {
return true
}
const role = target.getAttribute('role')
if (role !== null && interactionRoles.has(role)) {
return true
}
target = target instanceof HTMLElement ? target.parentElement : null
}
return false
}
``` | /content/code_sandbox/app/src/ui/lib/ui-activity-monitor.ts | xml | 2016-05-11T15:59:00 | 2024-08-16T17:00:41 | desktop | desktop/desktop | 19,544 | 865 |
```xml
export * from './confirmation.service';
export * from './nav-items.service';
export * from './page-alert.service';
export * from './toaster.service';
export * from './user-menu.service';
export * from './create-error-component.service';
export * from './abp-format-error-handler.service';
export * from './tenant-resolve-error-handler.service';
export * from './status-code-error-handler.service';
export * from './unknown-status-code-error-handler.service';
export * from './router-error-handler.service';
export * from './authentication-error-handler.service'
``` | /content/code_sandbox/npm/ng-packs/packages/theme-shared/src/lib/services/index.ts | xml | 2016-12-03T22:56:24 | 2024-08-16T16:24:05 | abp | abpframework/abp | 12,657 | 110 |
```xml
import * as path from 'path';
import postcss from 'postcss';
import * as atImport from 'postcss-import';
import { IStyleSheetProps } from '../../config/IStylesheetProps';
import { Context } from '../../core/context';
import { FuseBoxLogAdapter } from '../../fuseLog/FuseBoxLogAdapter';
import { IModule } from '../../moduleResolver/module';
import { readFile } from '../../utils/utils';
import { cssHandleResources } from '../cssHandleResources';
import { cssResolveModule } from '../cssResolveModule';
import { alignCSSSourceMap } from '../cssSourceMap';
import { IStyleSheetProcessor, IStylesheetModuleResponse } from '../interfaces';
interface IRenderModuleProps {
ctx: Context;
module: IModule;
options?: IStyleSheetProps;
}
async function callPostCSS(
plugins: Array<any>,
css: string,
options,
logger: FuseBoxLogAdapter,
): Promise<{ map: string; css: string }> {
return new Promise((resolve, reject) => {
postcss(plugins)
.process(css, options)
.then(resolve as any)
.catch(reject);
});
}
export async function renderModule(props: IRenderModuleProps): Promise<IStylesheetModuleResponse> {
function loader(url, opts) {
const data = cssHandleResources(
{ contents: readFile(url), path: url },
{
ctx: props.ctx,
fileRoot: path.dirname(url),
module: props.module,
options: props.options,
url: url,
},
);
return data.contents;
}
function resolver(url, root, importOptions) {
const userPaths = props.options.paths || [];
const paths = [root].concat(userPaths);
const resolved = cssResolveModule({
extensions: ['.css', '.scss', '.sass'],
options: props.options,
paths,
target: url,
tryUnderscore: true,
});
if (resolved.success) {
if (props.options.breakDependantsCache) {
props.module.breakDependantsCache = true;
}
props.module.ctx.setLinkedReference(resolved.path, props.module);
return resolved.path;
}
}
const requireSourceMap = props.module.isCSSSourceMapRequired;
// handle root resources
const processed = cssHandleResources(
{ contents: props.module.contents, path: props.module.absPath },
{ ctx: props.ctx, module: props.module, options: props.options },
);
let pluginList: Array<any> = [atImport({ load: loader, resolve: resolver })];
if (props.options.postCSS) {
if (props.options.postCSS.plugins) {
pluginList = pluginList.concat(props.options.postCSS.plugins);
}
}
const data = await callPostCSS(
pluginList,
processed.contents,
{
from: props.module.absPath,
to: props.module.absPath,
map: requireSourceMap && { inline: false },
},
props.ctx.log,
);
let sourceMap: string;
if (data.map) {
sourceMap = alignCSSSourceMap({ ctx: props.ctx, module: props.module, sourceMap: data.map });
}
return { css: data.css && data.css.toString(), map: sourceMap };
}
export interface IPostCSSHandlerProps {
ctx: Context;
module: IModule;
options: IStyleSheetProps;
}
export function postCSSHandler(props: IPostCSSHandlerProps): IStyleSheetProcessor {
const { ctx, module } = props;
return {
render: async () => renderModule({ ctx, module, options: props.options }),
};
}
``` | /content/code_sandbox/src/stylesheet/postcss/postcssHandler.ts | xml | 2016-10-28T10:37:16 | 2024-07-27T15:17:43 | fuse-box | fuse-box/fuse-box | 4,003 | 779 |
```xml
/**
* @license
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at path_to_url
*/
import {ElementRef, QueryList} from '@angular/core';
import {defer, fromEvent, Observable, Subject} from 'rxjs';
import {mapTo, mergeAll, mergeMap, startWith, takeUntil} from 'rxjs/operators';
/** Item to track for mouse focus events. */
export interface FocusableElement {
/** A reference to the element to be tracked. */
_elementRef: ElementRef<HTMLElement>;
}
/**
* PointerFocusTracker keeps track of the currently active item under mouse focus. It also has
* observables which emit when the users mouse enters and leaves a tracked element.
*/
export class PointerFocusTracker<T extends FocusableElement> {
/** Emits when an element is moused into. */
readonly entered: Observable<T> = this._getItemPointerEntries();
/** Emits when an element is moused out. */
readonly exited: Observable<T> = this._getItemPointerExits();
/** The element currently under mouse focus. */
activeElement?: T;
/** The element previously under mouse focus. */
previousElement?: T;
/** Emits when this is destroyed. */
private readonly _destroyed: Subject<void> = new Subject();
constructor(
/** The list of items being tracked. */
private readonly _items: QueryList<T>,
) {
this.entered.subscribe(element => (this.activeElement = element));
this.exited.subscribe(() => {
this.previousElement = this.activeElement;
this.activeElement = undefined;
});
}
/** Stop the managers listeners. */
destroy() {
this._destroyed.next();
this._destroyed.complete();
}
/**
* Gets a stream of pointer (mouse) entries into the given items.
* This should typically run outside the Angular zone.
*/
private _getItemPointerEntries(): Observable<T> {
return defer(() =>
this._items.changes.pipe(
startWith(this._items),
mergeMap((list: QueryList<T>) =>
list.map(element =>
fromEvent(element._elementRef.nativeElement, 'mouseenter').pipe(
mapTo(element),
takeUntil(this._items.changes),
),
),
),
mergeAll(),
),
);
}
/**
* Gets a stream of pointer (mouse) exits out of the given items.
* This should typically run outside the Angular zone.
*/
private _getItemPointerExits() {
return defer(() =>
this._items.changes.pipe(
startWith(this._items),
mergeMap((list: QueryList<T>) =>
list.map(element =>
fromEvent(element._elementRef.nativeElement, 'mouseout').pipe(
mapTo(element),
takeUntil(this._items.changes),
),
),
),
mergeAll(),
),
);
}
}
``` | /content/code_sandbox/src/cdk/menu/pointer-focus-tracker.ts | xml | 2016-01-04T18:50:02 | 2024-08-16T11:21:13 | components | angular/components | 24,263 | 624 |
```xml
export const ADDON_ID = 'storybook/outline';
export const PARAM_KEY = 'outline';
``` | /content/code_sandbox/code/addons/outline/src/constants.ts | xml | 2016-03-18T04:23:44 | 2024-08-16T19:22:08 | storybook | storybookjs/storybook | 83,755 | 20 |
```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "path_to_url">
<plist version="1.0">
<dict>
<key>BuildMachineOSBuild</key>
<string>15A284</string>
<key>CFBundleDevelopmentRegion</key>
<string>English</string>
<key>CFBundleExecutable</key>
<string>HackrNVMeFamily</string>
<key>CFBundleGetInfoString</key>
<key>CFBundleIdentifier</key>
<string>com.apple.hack.HackrNVMeFamily</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>HackrNVMeFamily</string>
<key>CFBundlePackageType</key>
<string>KEXT</string>
<key>CFBundleShortVersionString</key>
<string>1.2.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleSupportedPlatforms</key>
<array>
<string>MacOSX</string>
</array>
<key>CFBundleVersion</key>
<string>1.2.0</string>
<key>DTCompiler</key>
<string>com.apple.compilers.llvm.clang.1_0</string>
<key>DTPlatformBuild</key>
<string>7D129b</string>
<key>DTPlatformVersion</key>
<string>GM</string>
<key>DTSDKBuild</key>
<string>15G22</string>
<key>DTSDKName</key>
<string>macosx10.11internal</string>
<key>DTXcode</key>
<string>0730</string>
<key>DTXcodeBuild</key>
<string>7D129b</string>
<key>IOKitPersonalities</key>
<dict>
<key>GenericNVMeSSD</key>
<dict>
<key>CFBundleIdentifier</key>
<string>com.apple.hack.HackrNVMeFamily</string>
<key>Chipset Name</key>
<string>SSD Controller</string>
<key>IOClass</key>
<string>HackrNVMeController</string>
<key>IOPCIClassMatch</key>
<string>0x01080200&0xFFFFFF00</string>
<key>IOPCIPauseCompatible</key>
<true/>
<key>IOPCITunnelCompatible</key>
<true/>
<key>IOProviderClass</key>
<string>IOPCIDevice</string>
<key>IOUnitName</key>
<string>disk</string>
<key>Physical Interconnect</key>
<string>PCI-Express</string>
<key>Physical Interconnect Location</key>
<string>Internal</string>
<key>Vendor Name</key>
<string>Apple</string>
</dict>
</dict>
<key>OSBundleCompatibleVersion</key>
<string>1.2.0</string>
<key>OSBundleLibraries</key>
<dict>
<key>com.apple.driver.AppleEFINVRAM</key>
<string>2.0</string>
<key>com.apple.driver.AppleMobileFileIntegrity</key>
<string>1.0.1</string>
<key>com.apple.iokit.IOPCIFamily</key>
<string>1.0.0</string>
<key>com.apple.iokit.IOReportFamily</key>
<string>1.0</string>
<key>com.apple.iokit.IOStorageFamily</key>
<string>1.7.0</string>
<key>com.apple.kpi.bsd</key>
<string>9.0.0</string>
<key>com.apple.kpi.iokit</key>
<string>9.0.0</string>
<key>com.apple.kpi.libkern</key>
<string>9.0.0</string>
<key>com.apple.kpi.mach</key>
<string>9.0.0</string>
<key>com.apple.kpi.private</key>
<string>9.0.0</string>
<key>com.apple.kpi.unsupported</key>
<string>9.0.0</string>
</dict>
<key>OSBundleRequired</key>
<string>Local-Root</string>
</dict>
</plist>
``` | /content/code_sandbox/Clover-Configs/Dell/Dell XPS 13 9550/CLOVER/kexts/Other/HackrNVMeFamily-10_11_6.kext/Contents/Info.plist | xml | 2016-11-05T04:22:54 | 2024-08-12T19:25:53 | Hackintosh-Installer-University | huangyz0918/Hackintosh-Installer-University | 3,937 | 1,077 |
```xml
import * as React from 'react';
import type { Meta } from '@storybook/react';
import { createTheme, ThemeProvider, Theme as ThemeV8, DefaultPalette } from '@fluentui/react';
import {
Button,
makeStyles,
Textarea,
TextareaProps,
tokens,
Theme as ThemeV9,
webLightTheme,
FluentProvider,
} from '@fluentui/react-components';
import { createV9Theme } from '@fluentui/react-migration-v8-v9';
import descriptionMd from './Description.md';
import { ThemePreviewV8 } from '../ThemePreviewV8.stories';
import { ThemePreviewV9 } from '../ThemePreviewV9.stories';
const useStyles = makeStyles({
root: {
display: 'grid',
gridTemplateColumns: 'auto',
gridTemplateRows: 'auto',
gridRowGap: '10px',
justifyItems: 'start',
padding: '5px',
},
instructions: {
color: tokens.colorNeutralForeground2,
},
editor: {
width: '400px',
height: '300px',
},
actions: {
display: 'grid',
gridTemplateColumns: 'auto auto',
gridColumnGap: '10px',
justifyItems: 'start',
},
error: {
color: 'red',
},
result: {
display: 'grid',
gridTemplateColumns: 'auto auto',
gridTemplateRows: 'auto',
columnGap: '10px',
rowGap: '5px',
},
colorBlock: {
display: 'inline-block',
width: '10px',
height: '10px',
border: '1px solid black',
},
});
export const Playground = () => {
const styles = useStyles();
const defaultPaletteText = JSON.stringify(DefaultPalette, null, 4);
const [paletteText, setPaletteText] = React.useState(defaultPaletteText);
const defaultV8Theme = createTheme();
const defaultV8ThemeText = JSON.stringify(defaultV8Theme, null, 4);
const [v8ThemeText, setV8ThemeText] = React.useState(defaultV8ThemeText);
const [v8Theme, setV8Theme] = React.useState<ThemeV8>(defaultV8Theme);
const [createV8ThemeError, setCreateV8ThemeError] = React.useState('');
const [previewV8ThemeError, setPreviewV8ThemeError] = React.useState('');
const defaultV9Theme = webLightTheme;
const defaultV9ThemeText = JSON.stringify(defaultV9Theme, null, 4);
const [v9Theme, setV9Theme] = React.useState<ThemeV9>(defaultV9Theme);
const [v9ThemeText, setV9ThemeText] = React.useState(defaultV9ThemeText);
const [createV9ThemeError, setCreateV9ThemeError] = React.useState('');
const onPaletteTextChange: TextareaProps['onChange'] = (_, data) => {
setPaletteText(data.value);
};
const onV8ThemeTextChange: TextareaProps['onChange'] = (_, data) => {
setV8ThemeText(data.value);
};
const onResetPalette = () => {
setPaletteText(defaultPaletteText);
};
const onResetV8Theme = () => {
setV8Theme(defaultV8Theme);
setV8ThemeText(defaultV8ThemeText);
setCreateV8ThemeError('');
setPreviewV8ThemeError('');
};
const onCreateV8Theme = React.useCallback(() => {
try {
setCreateV8ThemeError('');
const palette = JSON.parse(paletteText);
const newPalette = { ...DefaultPalette, ...palette };
const newV8Theme = createTheme({ palette: newPalette });
setV8Theme(newV8Theme);
setV8ThemeText(JSON.stringify(newV8Theme, null, 4));
} catch (e) {
setCreateV8ThemeError((e as Error).message);
}
}, [paletteText]);
const onPreviewV8Theme = React.useCallback(() => {
try {
setPreviewV8ThemeError('');
const newV8Theme = JSON.parse(v8ThemeText);
setV8Theme(newV8Theme);
} catch (e) {
setPreviewV8ThemeError((e as Error).message);
}
}, [v8ThemeText]);
const onResetV9Theme = () => {
setV9Theme(defaultV9Theme);
setV9ThemeText(defaultV9ThemeText);
setCreateV9ThemeError('');
};
const onCreateV9Theme = React.useCallback(() => {
try {
setCreateV9ThemeError('');
const newV8Theme = JSON.parse(v8ThemeText);
setV8Theme(newV8Theme);
const newV9Theme = createV9Theme(newV8Theme);
setV9Theme(newV9Theme);
setV9ThemeText(JSON.stringify(newV9Theme, null, 4));
} catch (e) {
setCreateV9ThemeError((e as Error).message);
}
}, [v8ThemeText]);
return (
<div className={styles.root}>
<h2>1. Define a v8 Palette</h2>
<div className={styles.instructions}>
<p>Adjust the palette. You can reset to the default colors.</p>
<p>
If you want to generate an entirely different v8 palette, use the
<a href="path_to_url">v8 Theme Designer</a>.
</p>
</div>
<div className={styles.actions}>
<Button onClick={onResetPalette}>Reset</Button>
</div>
<Textarea
resize="both"
textarea={{ className: styles.editor }}
value={paletteText}
onChange={onPaletteTextChange}
/>
<h2>2. Create a v8 Theme</h2>
<div className={styles.instructions}>
<p>Create a v8 theme from the palette.</p>
<p>You can adjust the theme and click preview to see the result.</p>
</div>
<div className={styles.actions}>
<Button onClick={onResetV8Theme}>Reset</Button>
<Button onClick={onCreateV8Theme}>Create</Button>
</div>
<div className={styles.error}>{createV8ThemeError}</div>
<Textarea
resize="both"
textarea={{ className: styles.editor }}
value={v8ThemeText}
onChange={onV8ThemeTextChange}
/>
<h3>v8 Theme</h3>
<div className={styles.actions}>
<Button onClick={onPreviewV8Theme}>Preview</Button>
</div>
<div className={styles.error}>{previewV8ThemeError}</div>
<div>
<ThemeProvider theme={v8Theme}>
<ThemePreviewV8
backgroundColor={v8Theme?.semanticColors.bodyBackground || 'white'}
textColor={v8Theme?.semanticColors.bodyText || 'black'}
/>
</ThemeProvider>
</div>
<h2>2. Create a v9 Theme</h2>
<p className={styles.instructions}>
Create a v9 theme from the v8 theme. You can copy the result to use it in your application.
</p>
<div className={styles.actions}>
<Button onClick={onResetV9Theme}>Reset</Button>
<Button onClick={onCreateV9Theme}>Create</Button>
</div>
<div className={styles.error}>{createV9ThemeError}</div>
<FluentProvider theme={v9Theme}>
<ThemePreviewV9 />
</FluentProvider>
<h3>v9 Theme</h3>
<Textarea resize="both" textarea={{ className: styles.editor }} value={v9ThemeText} readOnly />
</div>
);
};
export default {
title: 'Migration Shims/V8/Theme/createV9Theme',
component: React.Fragment,
parameters: {
docs: {
description: {
component: [descriptionMd].join('\n'),
},
},
},
} as Meta;
``` | /content/code_sandbox/packages/react-components/react-migration-v8-v9/stories/src/ThemeShim/createV9Theme/index.stories.tsx | xml | 2016-06-06T15:03:44 | 2024-08-16T18:49:29 | fluentui | microsoft/fluentui | 18,221 | 1,786 |
```xml
<manifest package="com.aurelhubert.ahbottomnavigation"
xmlns:android="path_to_url">
<application
/>
</manifest>
``` | /content/code_sandbox/ahbottomnavigation/src/main/AndroidManifest.xml | xml | 2016-03-17T12:17:56 | 2024-08-16T05:12:20 | ahbottomnavigation | aurelhubert/ahbottomnavigation | 3,836 | 34 |
```xml
import { Modules, StateMachine } from 'lisk-sdk';
import { MessageStore, MessageStoreData } from './stores/message';
export class HelloMethod extends Modules.BaseMethod {
public async getHello(
methodContext: StateMachine.ImmutableMethodContext,
address: Buffer,
): Promise<MessageStoreData> {
const messageSubStore = this.stores.get(MessageStore);
const helloMessage = await messageSubStore.get(methodContext, address);
return helloMessage;
}
}
``` | /content/code_sandbox/examples/interop/pos-sidechain-example-one/src/app/modules/hello/method.ts | xml | 2016-02-01T21:45:35 | 2024-08-15T19:16:48 | lisk-sdk | LiskArchive/lisk-sdk | 2,721 | 101 |
```xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="path_to_url"
xmlns:xsi="path_to_url"
xsi:schemaLocation="path_to_url path_to_url">
<parent>
<artifactId>whatsmars-spring-boot-samples</artifactId>
<groupId>org.hongxi</groupId>
<version>2021.4.1</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>whatsmars-boot-sample-session</artifactId>
<name>${project.artifactId}</name>
<packaging>jar</packaging>
<description>Spring Boot Session Sample</description>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
</dependency>
</dependencies>
</project>
``` | /content/code_sandbox/whatsmars-spring-boot-samples/whatsmars-boot-sample-session/pom.xml | xml | 2016-04-01T10:33:04 | 2024-08-14T23:44:08 | whatsmars | javahongxi/whatsmars | 1,952 | 292 |
```xml
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="12121" systemVersion="16F73" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" colorMatched="NO">
<dependencies>
<deployment identifier="iOS"/>
<development version="7000" identifier="xcode"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="12089"/>
</dependencies>
<objects>
<placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner" customClass="FTRTableViewController">
<connections>
<outlet property="insetsValue" destination="C9l-0A-zww" id="neP-aJ-dlY"/>
<outlet property="mainTableView" destination="YKc-6C-Ui5" id="LOv-FF-4BV"/>
<outlet property="view" destination="1" id="3"/>
</connections>
</placeholder>
<placeholder placeholderIdentifier="IBFirstResponder" id="-2" customClass="UIResponder"/>
<view contentMode="scaleToFill" id="1">
<rect key="frame" x="0.0" y="0.0" width="320" height="480"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<tableView clipsSubviews="YES" contentMode="scaleToFill" misplaced="YES" alwaysBounceVertical="YES" style="plain" separatorStyle="default" rowHeight="44" sectionHeaderHeight="22" sectionFooterHeight="22" translatesAutoresizingMaskIntoConstraints="NO" id="YKc-6C-Ui5">
<rect key="frame" x="0.0" y="0.0" width="375" height="620"/>
<color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="calibratedRGB"/>
</tableView>
<switch opaque="NO" contentMode="scaleToFill" horizontalHuggingPriority="750" verticalHuggingPriority="750" misplaced="YES" contentHorizontalAlignment="center" contentVerticalAlignment="center" translatesAutoresizingMaskIntoConstraints="NO" id="W7j-SG-pbJ">
<rect key="frame" x="8" y="628" width="51" height="31"/>
<userDefinedRuntimeAttributes>
<userDefinedRuntimeAttribute type="string" keyPath="accessibilityIdentifier" value="insets toggle"/>
</userDefinedRuntimeAttributes>
<connections>
<action selector="insetsToggled:" destination="-1" eventType="valueChanged" id="pRu-Jq-oJB"/>
</connections>
</switch>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" misplaced="YES" text="Insets" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="8uT-c9-coK">
<rect key="frame" x="65" y="633" width="46" height="21"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<color key="textColor" cocoaTouchSystemColor="darkTextColor"/>
<nil key="highlightedColor"/>
</label>
<textField opaque="NO" clipsSubviews="YES" contentMode="scaleToFill" misplaced="YES" contentHorizontalAlignment="left" contentVerticalAlignment="center" text="{0,0,0,0}" borderStyle="roundedRect" clearsOnBeginEditing="YES" minimumFontSize="17" translatesAutoresizingMaskIntoConstraints="NO" id="C9l-0A-zww">
<rect key="frame" x="119" y="629" width="248" height="30"/>
<fontDescription key="fontDescription" type="system" pointSize="14"/>
<textInputTraits key="textInputTraits"/>
<userDefinedRuntimeAttributes>
<userDefinedRuntimeAttribute type="string" keyPath="accessibilityIdentifier" value="insets value"/>
</userDefinedRuntimeAttributes>
</textField>
</subviews>
<color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="calibratedRGB"/>
<constraints>
<constraint firstItem="8uT-c9-coK" firstAttribute="leading" secondItem="W7j-SG-pbJ" secondAttribute="trailing" constant="8" id="EoZ-te-zo4"/>
<constraint firstItem="C9l-0A-zww" firstAttribute="top" secondItem="YKc-6C-Ui5" secondAttribute="bottom" constant="9" id="KvJ-Au-zSF"/>
<constraint firstItem="YKc-6C-Ui5" firstAttribute="leading" secondItem="1" secondAttribute="leading" id="MDR-oZ-2fv"/>
<constraint firstItem="C9l-0A-zww" firstAttribute="leading" secondItem="8uT-c9-coK" secondAttribute="trailing" constant="8" id="NU4-3n-pTb"/>
<constraint firstAttribute="bottom" secondItem="8uT-c9-coK" secondAttribute="bottom" constant="13" id="OoF-bl-Wec"/>
<constraint firstAttribute="trailing" secondItem="YKc-6C-Ui5" secondAttribute="trailing" id="P8Z-Qq-mjZ"/>
<constraint firstItem="W7j-SG-pbJ" firstAttribute="leading" secondItem="1" secondAttribute="leading" constant="8" id="Tn8-mG-Frq"/>
<constraint firstAttribute="trailing" secondItem="C9l-0A-zww" secondAttribute="trailing" constant="8" id="XA1-dF-wOx"/>
<constraint firstAttribute="bottom" secondItem="W7j-SG-pbJ" secondAttribute="bottom" constant="8" id="d3K-fF-0ht"/>
<constraint firstItem="W7j-SG-pbJ" firstAttribute="top" secondItem="YKc-6C-Ui5" secondAttribute="bottom" constant="8" id="oCd-Mj-PO4"/>
<constraint firstItem="YKc-6C-Ui5" firstAttribute="top" secondItem="1" secondAttribute="top" id="wzq-j8-vRb"/>
</constraints>
</view>
</objects>
<simulatedMetricsContainer key="defaultSimulatedMetrics">
<simulatedStatusBarMetrics key="statusBar"/>
<simulatedOrientationMetrics key="orientation"/>
<simulatedScreenMetrics key="destination"/>
</simulatedMetricsContainer>
</document>
``` | /content/code_sandbox/Tests/FunctionalTests/TestRig/Sources/FTRTableViewController.xib | xml | 2016-02-04T17:55:29 | 2024-08-08T03:33:02 | EarlGrey | google/EarlGrey | 5,612 | 1,530 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="path_to_url" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="it" original="../LocalizableStrings.resx">
<body>
<trans-unit id="AppFullName">
<source>.NET SDK Check Command</source>
<target state="translated">Comando per controllo disponibilit .NET SDK</target>
<note />
</trans-unit>
<trans-unit id="AppDescription">
<source>Check for SDK updates.</source>
<target state="translated">Controlla la disponibilit di aggiornamenti dell'SDK.</target>
<note />
</trans-unit>
<trans-unit id="BundleUpToDateMessage">
<source>Up to date.</source>
<target state="translated">Aggiornato.</target>
<note />
</trans-unit>
<trans-unit id="CommandFooter">
<source>The latest versions of .NET can be installed from path_to_url For more information about .NET lifecycles, see path_to_url
<target state="translated"> possibile installare le versioni pi recenti di .NET da path_to_url Per altre informazioni sui cicli di vita di .NET, vedere path_to_url
<note />
</trans-unit>
<trans-unit id="HostFxrCouldNotBeLoaded">
<source>Could not load hostfxr from '{0}'.</source>
<target state="translated">Non stato possibile caricare hostfxr da '{0}'.</target>
<note />
</trans-unit>
<trans-unit id="MaintenanceMessage">
<source>.NET {0} is going out of support soon.</source>
<target state="translated">A breve il supporto per .NET {0} verr dismesso.</target>
<note />
</trans-unit>
<trans-unit id="NameColumnHeader">
<source>Name</source>
<target state="translated">Nome</target>
<note />
</trans-unit>
<trans-unit id="NewFeatureBandMessage">
<source>Try out the newest .NET SDK features with .NET {0}.</source>
<target state="translated">Per provare le funzionalit pi recenti di .NET SDK, usare .NET {0}.</target>
<note />
</trans-unit>
<trans-unit id="NewPatchAvailableMessage">
<source>Patch {0} is available.</source>
<target state="translated"> disponibile la patch {0}.</target>
<note />
</trans-unit>
<trans-unit id="OutOfSupportMessage">
<source>.NET {0} is out of support.</source>
<target state="translated">Il supporto per .NET {0} non pi disponibile.</target>
<note />
</trans-unit>
<trans-unit id="VersionCheckFailure">
<source>No version found to check if this is up to date. Please check for updates manually.</source>
<target state="translated">Nessuna versione trovata per verificarne laggiornamento. Controllare manualmente la disponibilit di aggiornamenti.</target>
<note />
</trans-unit>
<trans-unit id="ReleasesLibraryFailed">
<source>Unable to get releases information: {0}</source>
<target state="translated">Non possibile ottenere informazioni sulle versioni: {0}</target>
<note />
</trans-unit>
<trans-unit id="RuntimePropertyNotFound">
<source>Runtime property 'HOSTFXR_PATH' was not set or empty.</source>
<target state="translated">La propriet di runtime ' HOSTFXR_PATH ' non stata impostata o vuota.</target>
<note />
</trans-unit>
<trans-unit id="RuntimeSectionHeader">
<source>.NET Runtimes:</source>
<target state="translated">Runtime di .NET:</target>
<note />
</trans-unit>
<trans-unit id="SdkSectionHeader">
<source>.NET SDKs:</source>
<target state="translated">.NET SDK:</target>
<note />
</trans-unit>
<trans-unit id="StatusColumnHeader">
<source>Status</source>
<target state="translated">Stato</target>
<note />
</trans-unit>
<trans-unit id="VersionColumnHeader">
<source>Version</source>
<target state="translated">Versione</target>
<note />
</trans-unit>
</body>
</file>
</xliff>
``` | /content/code_sandbox/src/Cli/dotnet/commands/dotnet-sdk/check/xlf/LocalizableStrings.it.xlf | xml | 2016-07-22T21:26:02 | 2024-08-16T17:23:58 | sdk | dotnet/sdk | 2,627 | 1,071 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="path_to_url"
xmlns:app="path_to_url"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?android:attr/selectableItemBackground"
android:clickable="true"
android:focusable="true"
android:paddingBottom="10dp"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="10dp">
<TextView
android:id="@+id/item_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toEndOf="@+id/item_enabled"
android:ellipsize="end"
android:maxLines="1"
android:textAppearance="?android:attr/textAppearanceListItem"/>
<TextView
android:id="@+id/item_subtitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/item_title"
android:layout_toEndOf="@+id/item_enabled"
android:ellipsize="end"
android:maxLines="1"
android:textAppearance="?android:attr/textAppearanceListItemSecondary"
android:textColor="?android:attr/textColorSecondary"/>
<ImageView
android:id="@+id/item_enabled"
android:layout_width="38dp"
android:layout_height="38dp"
android:layout_alignParentStart="true"
android:layout_centerVertical="true"
android:layout_marginEnd="10dp"
android:clickable="true"
android:focusable="true"
app:tint="?android:attr/textColorPrimary"
app:srcCompat="@drawable/ic_state_ignore"/>
</RelativeLayout>
``` | /content/code_sandbox/app/src/main/res/layout/view_item.xml | xml | 2016-10-15T15:27:17 | 2024-08-16T06:53:53 | dns66 | julian-klode/dns66 | 2,104 | 392 |
```xml
import { TextProps } from '../primitives/Text';
import { ViewProps } from '../primitives/View';
export type QuoteProps = React.PropsWithChildren<TextProps & { cite?: string }>;
export type BlockQuoteProps = React.PropsWithChildren<ViewProps & { cite?: string }>;
export type TimeProps = React.PropsWithChildren<TextProps & { dateTime?: string }>;
export type LinkProps = React.PropsWithChildren<
TextProps & {
/** @platform web */
href?: string;
/** @platform web */
target?: string;
/** @platform web */
rel?: string;
/** @platform web */
download?: boolean | string;
}
>;
``` | /content/code_sandbox/packages/html-elements/src/elements/Text.types.ts | xml | 2016-08-15T17:14:25 | 2024-08-16T19:54:44 | expo | expo/expo | 32,004 | 148 |
```xml
///
///
///
/// path_to_url
///
/// Unless required by applicable law or agreed to in writing, software
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
///
import { ComponentFactory, Inject, Injectable, Optional, Type } from '@angular/core';
import { DynamicComponentFactoryService } from '@core/services/dynamic-component-factory.service';
import { WidgetService } from '@core/http/widget.service';
import { forkJoin, from, Observable, of, ReplaySubject, Subject, throwError } from 'rxjs';
import {
ErrorWidgetType,
MissingWidgetType,
toWidgetInfo,
toWidgetType,
WidgetInfo,
WidgetTypeInstance
} from '@home/models/widget-component.models';
import cssjs from '@core/css/css';
import { UtilsService } from '@core/services/utils.service';
import { ModulesWithFactories, ResourcesService } from '@core/services/resources.service';
import {
IWidgetSettingsComponent,
Widget,
widgetActionSources,
WidgetControllerDescriptor,
WidgetType
} from '@shared/models/widget.models';
import { catchError, map, mergeMap, switchMap, tap } from 'rxjs/operators';
import { isFunction, isUndefined } from '@core/utils';
import { TranslateService } from '@ngx-translate/core';
import { DynamicWidgetComponent } from '@home/components/widget/dynamic-widget.component';
import { WidgetComponentsModule } from '@home/components/widget/widget-components.module';
import { WINDOW } from '@core/services/window.service';
import { NULL_UUID } from '@shared/models/id/has-uuid';
import { WidgetTypeId } from '@app/shared/models/id/widget-type-id';
import { TenantId } from '@app/shared/models/id/tenant-id';
import { SharedModule } from '@shared/shared.module';
import { MODULES_MAP } from '@shared/public-api';
import tinycolor from 'tinycolor2';
import moment from 'moment';
import { IModulesMap } from '@modules/common/modules-map.models';
import { HOME_COMPONENTS_MODULE_TOKEN } from '@home/components/tokens';
import { widgetSettingsComponentsMap } from '@home/components/widget/lib/settings/widget-settings.module';
import { basicWidgetConfigComponentsMap } from '@home/components/widget/config/basic/basic-widget-config.module';
import { IBasicWidgetConfigComponent } from '@home/components/widget/config/widget-config.component.models';
import { TbTimeSeriesChart } from '@home/components/widget/lib/chart/time-series-chart';
@Injectable()
export class WidgetComponentService {
private cssParser = new cssjs();
private widgetsInfoFetchQueue = new Map<string, Array<Subject<WidgetInfo>>>();
private init$: Observable<any>;
private missingWidgetType: WidgetInfo;
private errorWidgetType: WidgetInfo;
private editingWidgetType: WidgetType;
constructor(@Inject(WINDOW) private window: Window,
@Optional() @Inject(MODULES_MAP) private modulesMap: IModulesMap,
@Inject(HOME_COMPONENTS_MODULE_TOKEN) private homeComponentsModule: Type<any>,
private dynamicComponentFactoryService: DynamicComponentFactoryService,
private widgetService: WidgetService,
private utils: UtilsService,
private resources: ResourcesService,
private translate: TranslateService) {
this.cssParser.testMode = false;
this.init();
}
private init(): Observable<any> {
if (this.init$) {
return this.init$;
} else {
this.missingWidgetType = {...MissingWidgetType};
this.errorWidgetType = {...ErrorWidgetType};
if (this.utils.widgetEditMode) {
this.editingWidgetType = toWidgetType(
{
widgetName: this.utils.editWidgetInfo.widgetName,
fullFqn: 'system.customWidget',
deprecated: false,
scada: false,
type: this.utils.editWidgetInfo.type,
sizeX: this.utils.editWidgetInfo.sizeX,
sizeY: this.utils.editWidgetInfo.sizeY,
resources: this.utils.editWidgetInfo.resources,
templateHtml: this.utils.editWidgetInfo.templateHtml,
templateCss: this.utils.editWidgetInfo.templateCss,
controllerScript: this.utils.editWidgetInfo.controllerScript,
settingsSchema: this.utils.editWidgetInfo.settingsSchema,
dataKeySettingsSchema: this.utils.editWidgetInfo.dataKeySettingsSchema,
latestDataKeySettingsSchema: this.utils.editWidgetInfo.latestDataKeySettingsSchema,
settingsDirective: this.utils.editWidgetInfo.settingsDirective,
dataKeySettingsDirective: this.utils.editWidgetInfo.dataKeySettingsDirective,
latestDataKeySettingsDirective: this.utils.editWidgetInfo.latestDataKeySettingsDirective,
hasBasicMode: this.utils.editWidgetInfo.hasBasicMode,
basicModeDirective: this.utils.editWidgetInfo.basicModeDirective,
defaultConfig: this.utils.editWidgetInfo.defaultConfig
}, new WidgetTypeId('1'), new TenantId( NULL_UUID ), undefined, undefined
);
}
const initSubject = new ReplaySubject<void>();
this.init$ = initSubject.asObservable();
const w = (this.window as any);
w.tinycolor = tinycolor;
w.cssjs = cssjs;
w.moment = moment;
w.$ = $;
w.jQuery = $;
const widgetModulesTasks: Observable<any>[] = [];
widgetModulesTasks.push(from(import('jquery.terminal')));
widgetModulesTasks.push(from(import('flot/src/jquery.flot.js')).pipe(
mergeMap(() => {
const flotJsPluginsTasks: Observable<any>[] = [];
flotJsPluginsTasks.push(from(import('flot/lib/jquery.colorhelpers.js')));
flotJsPluginsTasks.push(from(import('flot/src/plugins/jquery.flot.time.js')));
flotJsPluginsTasks.push(from(import('flot/src/plugins/jquery.flot.selection.js')));
flotJsPluginsTasks.push(from(import('flot/src/plugins/jquery.flot.pie.js')));
flotJsPluginsTasks.push(from(import('flot/src/plugins/jquery.flot.crosshair.js')));
flotJsPluginsTasks.push(from(import('flot/src/plugins/jquery.flot.stack.js')));
flotJsPluginsTasks.push(from(import('flot/src/plugins/jquery.flot.symbol.js')));
flotJsPluginsTasks.push(from(import('flot.curvedlines/curvedLines.js')));
return forkJoin(flotJsPluginsTasks);
})
));
widgetModulesTasks.push(from(import('@home/components/widget/lib/flot-widget')).pipe(
tap((mod) => {
(window as any).TbFlot = mod.TbFlot;
}))
);
widgetModulesTasks.push(from(import('@home/components/widget/lib/chart/time-series-chart')).pipe(
tap((mod) => {
(window as any).TbTimeSeriesChart = mod.TbTimeSeriesChart;
}))
);
widgetModulesTasks.push(from(import('@home/components/widget/lib/analogue-compass')).pipe(
tap((mod) => {
(window as any).TbAnalogueCompass = mod.TbAnalogueCompass;
}))
);
widgetModulesTasks.push(from(import('@home/components/widget/lib/analogue-radial-gauge')).pipe(
tap((mod) => {
(window as any).TbAnalogueRadialGauge = mod.TbAnalogueRadialGauge;
}))
);
widgetModulesTasks.push(from(import('@home/components/widget/lib/analogue-linear-gauge')).pipe(
tap((mod) => {
(window as any).TbAnalogueLinearGauge = mod.TbAnalogueLinearGauge;
}))
);
widgetModulesTasks.push(from(import('@home/components/widget/lib/digital-gauge')).pipe(
tap((mod) => {
(window as any).TbCanvasDigitalGauge = mod.TbCanvasDigitalGauge;
}))
);
widgetModulesTasks.push(from(import('@home/components/widget/lib/maps/map-widget2')).pipe(
tap((mod) => {
(window as any).TbMapWidgetV2 = mod.TbMapWidgetV2;
}))
);
widgetModulesTasks.push(from(import('@home/components/widget/lib/trip-animation/trip-animation.component')).pipe(
tap((mod) => {
(window as any).TbTripAnimationWidget = mod.TbTripAnimationWidget;
}))
);
forkJoin(widgetModulesTasks).subscribe(
() => {
const loadDefaultWidgetInfoTasks = [
this.loadWidgetResources(this.missingWidgetType, 'global-widget-missing-type',
[SharedModule, WidgetComponentsModule, this.homeComponentsModule]),
this.loadWidgetResources(this.errorWidgetType, 'global-widget-error-type',
[SharedModule, WidgetComponentsModule, this.homeComponentsModule]),
];
forkJoin(loadDefaultWidgetInfoTasks).subscribe(
() => {
initSubject.next();
},
(e) => {
let errorMessages = ['Failed to load default widget types!'];
if (e && e.length) {
errorMessages = errorMessages.concat(e);
}
console.error('Failed to load default widget types!');
initSubject.error({
widgetInfo: this.errorWidgetType,
errorMessages
});
}
);
},
(e) => {
let errorMessages = ['Failed to load widget modules!'];
if (e && e.length) {
errorMessages = errorMessages.concat(e);
}
console.error('Failed to load widget modules!');
initSubject.error({
widgetInfo: this.errorWidgetType,
errorMessages
});
}
);
return this.init$;
}
}
public getInstantWidgetInfo(widget: Widget): WidgetInfo {
const widgetInfo = this.widgetService.getWidgetInfoFromCache(widget.typeFullFqn);
if (widgetInfo) {
return widgetInfo;
} else {
return {} as WidgetInfo;
}
}
public getWidgetInfo(fullFqn: string): Observable<WidgetInfo> {
return this.init().pipe(
mergeMap(() => this.getWidgetInfoInternal(fullFqn))
);
}
public clearWidgetInfo(widgetInfo: WidgetInfo): void {
this.dynamicComponentFactoryService.destroyDynamicComponent(widgetInfo.componentType);
this.widgetService.deleteWidgetInfoFromCache(widgetInfo.fullFqn);
}
private getWidgetInfoInternal(fullFqn: string): Observable<WidgetInfo> {
const widgetInfoSubject = new ReplaySubject<WidgetInfo>();
const widgetInfo = this.widgetService.getWidgetInfoFromCache(fullFqn);
if (widgetInfo) {
widgetInfoSubject.next(widgetInfo);
widgetInfoSubject.complete();
} else {
if (this.utils.widgetEditMode) {
this.loadWidget(this.editingWidgetType, widgetInfoSubject);
} else {
let fetchQueue = this.widgetsInfoFetchQueue.get(fullFqn);
if (fetchQueue) {
fetchQueue.push(widgetInfoSubject);
} else {
fetchQueue = new Array<Subject<WidgetInfo>>();
this.widgetsInfoFetchQueue.set(fullFqn, fetchQueue);
this.widgetService.getWidgetType(fullFqn, {ignoreErrors: true}).subscribe(
(widgetType) => {
this.loadWidget(widgetType, widgetInfoSubject);
},
() => {
widgetInfoSubject.next(this.missingWidgetType);
widgetInfoSubject.complete();
this.resolveWidgetsInfoFetchQueue(fullFqn, this.missingWidgetType);
}
);
}
}
}
return widgetInfoSubject.asObservable();
}
private loadWidget(widgetType: WidgetType, widgetInfoSubject: Subject<WidgetInfo>) {
const widgetInfo = toWidgetInfo(widgetType);
let widgetControllerDescriptor: WidgetControllerDescriptor = null;
try {
widgetControllerDescriptor = this.createWidgetControllerDescriptor(widgetInfo);
} catch (e) {
const details = this.utils.parseException(e);
const errorMessage = `Failed to compile widget script. \n Error: ${details.message}`;
this.processWidgetLoadError([errorMessage], widgetInfo.fullFqn, widgetInfoSubject);
}
if (widgetControllerDescriptor) {
const widgetNamespace = `widget-type-${widgetInfo.fullFqn.replace(/\./g, '-')}`;
this.loadWidgetResources(widgetInfo, widgetNamespace, [SharedModule, WidgetComponentsModule, this.homeComponentsModule]).subscribe(
() => {
if (widgetControllerDescriptor.settingsSchema) {
widgetInfo.typeSettingsSchema = widgetControllerDescriptor.settingsSchema;
}
if (widgetControllerDescriptor.dataKeySettingsSchema) {
widgetInfo.typeDataKeySettingsSchema = widgetControllerDescriptor.dataKeySettingsSchema;
}
if (widgetControllerDescriptor.latestDataKeySettingsSchema) {
widgetInfo.typeLatestDataKeySettingsSchema = widgetControllerDescriptor.latestDataKeySettingsSchema;
}
widgetInfo.typeParameters = widgetControllerDescriptor.typeParameters;
widgetInfo.actionSources = widgetControllerDescriptor.actionSources;
widgetInfo.widgetTypeFunction = widgetControllerDescriptor.widgetTypeFunction;
this.widgetService.putWidgetInfoToCache(widgetInfo);
if (widgetInfoSubject) {
widgetInfoSubject.next(widgetInfo);
widgetInfoSubject.complete();
}
this.resolveWidgetsInfoFetchQueue(widgetInfo.fullFqn, widgetInfo);
},
(errorMessages: string[]) => {
this.processWidgetLoadError(errorMessages, widgetInfo.fullFqn, widgetInfoSubject);
}
);
}
}
private loadWidgetResources(widgetInfo: WidgetInfo, widgetNamespace: string, modules?: Type<any>[]): Observable<any> {
this.cssParser.cssPreviewNamespace = widgetNamespace;
this.cssParser.createStyleElement(widgetNamespace, widgetInfo.templateCss);
const resourceTasks: Observable<string>[] = [];
const modulesTasks: Observable<ModulesWithFactories | string>[] = [];
if (widgetInfo.resources.length > 0) {
widgetInfo.resources.filter(r => r.isModule).forEach(
(resource) => {
modulesTasks.push(
this.resources.loadFactories(resource.url, this.modulesMap).pipe(
catchError((e: Error) => of(e?.message ? e.message : `Failed to load widget resource module: '${resource.url}'`))
)
);
}
);
}
widgetInfo.resources.filter(r => !r.isModule).forEach(
(resource) => {
resourceTasks.push(
this.resources.loadResource(resource.url).pipe(
catchError(() => of(`Failed to load widget resource: '${resource.url}'`))
)
);
}
);
let modulesObservable: Observable<string | ModulesWithFactories>;
if (modulesTasks.length) {
modulesObservable = forkJoin(modulesTasks).pipe(
map(res => {
const msg = res.find(r => typeof r === 'string');
if (msg) {
return msg as string;
} else {
const modulesWithFactoriesList = res as ModulesWithFactories[];
const resModulesWithFactories: ModulesWithFactories = {
modules: modulesWithFactoriesList.map(mf => mf.modules).flat(),
factories: modulesWithFactoriesList.map(mf => mf.factories).flat()
};
if (modules && modules.length) {
resModulesWithFactories.modules = resModulesWithFactories.modules.concat(modules);
}
return resModulesWithFactories;
}
})
);
} else {
modulesObservable = modules && modules.length ? of({modules, factories: []}) : of({modules: [], factories: []});
}
resourceTasks.push(
modulesObservable.pipe(
mergeMap((resolvedModules) => {
if (typeof resolvedModules === 'string') {
return of(resolvedModules);
} else {
this.registerWidgetSettingsForms(widgetInfo, resolvedModules.factories);
return this.dynamicComponentFactoryService.createDynamicComponent(
class DynamicWidgetComponentInstance extends DynamicWidgetComponent {},
widgetInfo.templateHtml,
resolvedModules.modules
).pipe(
map((componentData) => {
widgetInfo.componentType = componentData.componentType;
widgetInfo.componentModuleRef = componentData.componentModuleRef;
return null;
}),
catchError(e => {
const details = this.utils.parseException(e);
const errorMessage = `Failed to compile widget html. \n Error: ${details.message}`;
return of(errorMessage);
})
);
}
}))
);
return forkJoin(resourceTasks).pipe(
switchMap(msgs => {
let errors: string[];
if (msgs && msgs.length) {
errors = msgs.filter(msg => msg && msg.length > 0);
}
if (errors && errors.length) {
return throwError(errors);
} else {
return of(null);
}
}
));
}
private registerWidgetSettingsForms(widgetInfo: WidgetInfo, factories: ComponentFactory<any>[]) {
const directives: string[] = [];
const basicDirectives: string[] = [];
if (widgetInfo.settingsDirective && widgetInfo.settingsDirective.length) {
directives.push(widgetInfo.settingsDirective);
}
if (widgetInfo.dataKeySettingsDirective && widgetInfo.dataKeySettingsDirective.length) {
directives.push(widgetInfo.dataKeySettingsDirective);
}
if (widgetInfo.latestDataKeySettingsDirective && widgetInfo.latestDataKeySettingsDirective.length) {
directives.push(widgetInfo.latestDataKeySettingsDirective);
}
if (widgetInfo.basicModeDirective && widgetInfo.basicModeDirective.length) {
basicDirectives.push(widgetInfo.basicModeDirective);
}
this.expandSettingComponentMap(widgetSettingsComponentsMap, directives, factories);
this.expandSettingComponentMap(basicWidgetConfigComponentsMap, basicDirectives, factories);
}
private expandSettingComponentMap(settingsComponentsMap: {[key: string]: Type<IWidgetSettingsComponent | IBasicWidgetConfigComponent>},
directives: string[], factories: ComponentFactory<any>[]): void {
if (directives.length) {
factories.filter((factory) => directives.includes(factory.selector))
.forEach((foundFactory) => {
settingsComponentsMap[foundFactory.selector] = foundFactory.componentType;
});
}
}
private createWidgetControllerDescriptor(widgetInfo: WidgetInfo): WidgetControllerDescriptor {
let widgetTypeFunctionBody = `return function _${widgetInfo.fullFqn.replace(/\./g, '_')} (ctx) {\n` +
' var self = this;\n' +
' self.ctx = ctx;\n\n'; /*+
' self.onInit = function() {\n\n' +
' }\n\n' +
' self.onDataUpdated = function() {\n\n' +
' }\n\n' +
' self.useCustomDatasources = function() {\n\n' +
' }\n\n' +
' self.typeParameters = function() {\n\n' +
return {
useCustomDatasources: false,
maxDatasources: -1, //unlimited
maxDataKeys: -1, //unlimited
dataKeysOptional: false,
stateData: false
};
' }\n\n' +
' self.actionSources = function() {\n\n' +
return {
'headerButton': {
name: 'Header button',
multiple: true
}
};
}\n\n' +
' self.onResize = function() {\n\n' +
' }\n\n' +
' self.onEditModeChanged = function() {\n\n' +
' }\n\n' +
' self.onMobileModeChanged = function() {\n\n' +
' }\n\n' +
' self.getSettingsSchema = function() {\n\n' +
' }\n\n' +
' self.getDataKeySettingsSchema = function() {\n\n' +
' }\n\n' +
' self.onDestroy = function() {\n\n' +
' }\n\n' +
'}';*/
widgetTypeFunctionBody += widgetInfo.controllerScript;
widgetTypeFunctionBody += '\n};\n';
try {
const widgetTypeFunction = new Function(widgetTypeFunctionBody);
const widgetType = widgetTypeFunction.apply(this);
const widgetTypeInstance: WidgetTypeInstance = new widgetType();
const result: WidgetControllerDescriptor = {
widgetTypeFunction: widgetType
};
if (isFunction(widgetTypeInstance.getSettingsSchema)) {
result.settingsSchema = widgetTypeInstance.getSettingsSchema();
}
if (isFunction(widgetTypeInstance.getDataKeySettingsSchema)) {
result.dataKeySettingsSchema = widgetTypeInstance.getDataKeySettingsSchema();
}
if (isFunction(widgetTypeInstance.getLatestDataKeySettingsSchema)) {
result.latestDataKeySettingsSchema = widgetTypeInstance.getLatestDataKeySettingsSchema();
}
if (isFunction(widgetTypeInstance.typeParameters)) {
result.typeParameters = widgetTypeInstance.typeParameters();
} else {
result.typeParameters = {};
}
if (isFunction(widgetTypeInstance.useCustomDatasources)) {
result.typeParameters.useCustomDatasources = widgetTypeInstance.useCustomDatasources();
} else {
result.typeParameters.useCustomDatasources = false;
}
if (isUndefined(result.typeParameters.hasDataPageLink)) {
result.typeParameters.hasDataPageLink = false;
}
if (isUndefined(result.typeParameters.maxDatasources)) {
result.typeParameters.maxDatasources = -1;
}
if (isUndefined(result.typeParameters.maxDataKeys)) {
result.typeParameters.maxDataKeys = -1;
}
if (isUndefined(result.typeParameters.singleEntity)) {
result.typeParameters.singleEntity = false;
}
if (isUndefined(result.typeParameters.hasAdditionalLatestDataKeys)) {
result.typeParameters.hasAdditionalLatestDataKeys = false;
}
if (isUndefined(result.typeParameters.warnOnPageDataOverflow)) {
result.typeParameters.warnOnPageDataOverflow = true;
}
if (isUndefined(result.typeParameters.ignoreDataUpdateOnIntervalTick)) {
result.typeParameters.ignoreDataUpdateOnIntervalTick = false;
}
if (isUndefined(result.typeParameters.dataKeysOptional)) {
result.typeParameters.dataKeysOptional = false;
}
if (isUndefined(result.typeParameters.datasourcesOptional)) {
result.typeParameters.datasourcesOptional = false;
}
if (isUndefined(result.typeParameters.stateData)) {
result.typeParameters.stateData = false;
}
if (isUndefined(result.typeParameters.processNoDataByWidget)) {
result.typeParameters.processNoDataByWidget = false;
}
if (isUndefined(result.typeParameters.previewWidth)) {
result.typeParameters.previewWidth = '100%';
}
if (isUndefined(result.typeParameters.previewHeight)) {
result.typeParameters.previewHeight = '70%';
}
if (isUndefined(result.typeParameters.embedTitlePanel)) {
result.typeParameters.embedTitlePanel = false;
}
if (isUndefined(result.typeParameters.overflowVisible)) {
result.typeParameters.overflowVisible = false;
}
if (isUndefined(result.typeParameters.hideDataSettings)) {
result.typeParameters.hideDataSettings = false;
}
if (!isFunction(result.typeParameters.defaultDataKeysFunction)) {
result.typeParameters.defaultDataKeysFunction = null;
}
if (!isFunction(result.typeParameters.defaultLatestDataKeysFunction)) {
result.typeParameters.defaultLatestDataKeysFunction = null;
}
if (!isFunction(result.typeParameters.dataKeySettingsFunction)) {
result.typeParameters.dataKeySettingsFunction = null;
}
if (isUndefined(result.typeParameters.displayRpcMessageToast)) {
result.typeParameters.displayRpcMessageToast = true;
}
if (isUndefined(result.typeParameters.targetDeviceOptional)) {
result.typeParameters.targetDeviceOptional = false;
}
if (isFunction(widgetTypeInstance.actionSources)) {
result.actionSources = widgetTypeInstance.actionSources();
} else {
result.actionSources = {};
}
for (const actionSourceId of Object.keys(widgetActionSources)) {
result.actionSources[actionSourceId] = {...widgetActionSources[actionSourceId]};
result.actionSources[actionSourceId].name = this.translate.instant(result.actionSources[actionSourceId].name);
}
return result;
} catch (e) {
this.utils.processWidgetException(e);
throw e;
}
}
private processWidgetLoadError(errorMessages: string[], fullFqn: string, widgetInfoSubject: Subject<WidgetInfo>) {
if (widgetInfoSubject) {
widgetInfoSubject.error({
widgetInfo: this.errorWidgetType,
errorMessages
});
}
this.resolveWidgetsInfoFetchQueue(fullFqn, this.errorWidgetType, errorMessages);
}
private resolveWidgetsInfoFetchQueue(fullFqn: string, widgetInfo: WidgetInfo, errorMessages?: string[]) {
const fetchQueue = this.widgetsInfoFetchQueue.get(fullFqn);
if (fetchQueue) {
fetchQueue.forEach(subject => {
if (!errorMessages) {
subject.next(widgetInfo);
subject.complete();
} else {
subject.error({
widgetInfo,
errorMessages
});
}
});
this.widgetsInfoFetchQueue.delete(fullFqn);
}
}
}
``` | /content/code_sandbox/ui-ngx/src/app/modules/home/components/widget/widget-component.service.ts | xml | 2016-12-01T09:33:30 | 2024-08-16T19:58:25 | thingsboard | thingsboard/thingsboard | 16,820 | 5,280 |
```xml
import "reflect-metadata"
import { DataSource } from "../../../../../src"
import { Post } from "./entity/Post"
import {
closeTestingConnections,
createTestingConnections,
reloadTestingDatabases,
} from "../../../../utils/test-utils"
import { PostWithoutTypes } from "./entity/PostWithoutTypes"
import { PostWithOptions } from "./entity/PostWithOptions"
describe("database schema > column types > spanner", () => {
let connections: DataSource[]
before(async () => {
connections = await createTestingConnections({
entities: [__dirname + "/entity/*{.js,.ts}"],
enabledDrivers: ["spanner"],
})
})
beforeEach(() => reloadTestingDatabases(connections))
after(() => closeTestingConnections(connections))
it("all types should work correctly - persist and hydrate", () =>
Promise.all(
connections.map(async (connection) => {
const postRepository = connection.getRepository(Post)
const queryRunner = connection.createQueryRunner()
const table = await queryRunner.getTable("post")
await queryRunner.release()
const post = new Post()
post.id = 1
post.name = "Post"
post.int64 = 2147483647
post.string = "This is string"
post.bytes = Buffer.from("This is bytes")
post.float64 = 10.53
post.numeric = "10"
post.bool = true
post.date = "2022-03-16"
post.timestamp = new Date()
post.json = { param: "VALUE" }
post.array = ["A", "B", "C"]
await postRepository.save(post)
const loadedPost = (await postRepository.findOneBy({ id: 1 }))!
loadedPost.id.should.be.equal(post.id)
loadedPost.name.should.be.equal(post.name)
loadedPost.int64.should.be.equal(post.int64)
loadedPost.string.should.be.equal(post.string)
loadedPost.bytes
.toString()
.should.be.equal(post.bytes.toString())
loadedPost.float64.should.be.equal(post.float64)
loadedPost.numeric.should.be.equal(post.numeric)
loadedPost.bool.should.be.equal(post.bool)
loadedPost.date.should.be.equal(post.date)
loadedPost.timestamp
.valueOf()
.should.be.equal(post.timestamp.valueOf())
loadedPost.json.should.be.eql(post.json)
loadedPost.array[0].should.be.equal(post.array[0])
loadedPost.array[1].should.be.equal(post.array[1])
loadedPost.array[2].should.be.equal(post.array[2])
table!.findColumnByName("id")!.type.should.be.equal("int64")
table!.findColumnByName("name")!.type.should.be.equal("string")
table!.findColumnByName("int64")!.type.should.be.equal("int64")
table!
.findColumnByName("string")!
.type.should.be.equal("string")
table!.findColumnByName("bytes")!.type.should.be.equal("bytes")
table!
.findColumnByName("float64")!
.type.should.be.equal("float64")
table!
.findColumnByName("numeric")!
.type.should.be.equal("numeric")
table!.findColumnByName("date")!.type.should.be.equal("date")
table!.findColumnByName("bool")!.type.should.be.equal("bool")
table!.findColumnByName("date")!.type.should.be.equal("date")
table!
.findColumnByName("timestamp")!
.type.should.be.equal("timestamp")
table!.findColumnByName("json")!.type.should.be.equal("json")
table!.findColumnByName("array")!.type.should.be.equal("string")
table!.findColumnByName("array")!.isArray.should.be.true
}),
))
it("all types should work correctly - persist and hydrate when options are specified on columns", () =>
Promise.all(
connections.map(async (connection) => {
const postRepository = connection.getRepository(PostWithOptions)
const queryRunner = connection.createQueryRunner()
const table = await queryRunner.getTable("post_with_options")
await queryRunner.release()
const post = new PostWithOptions()
post.id = 1
post.string = "This is string"
post.bytes = Buffer.from("This is bytes")
await postRepository.save(post)
const loadedPost = (await postRepository.findOneBy({ id: 1 }))!
loadedPost.id.should.be.equal(post.id)
loadedPost.string.should.be.equal(post.string)
loadedPost.bytes
.toString()
.should.be.equal(post.bytes.toString())
table!.findColumnByName("id")!.type.should.be.equal("int64")
table!
.findColumnByName("string")!
.type.should.be.equal("string")
table!.findColumnByName("string")!.length!.should.be.equal("50")
table!.findColumnByName("bytes")!.type.should.be.equal("bytes")
table!.findColumnByName("bytes")!.length!.should.be.equal("50")
}),
))
it("all types should work correctly - persist and hydrate when types are not specified on columns", () =>
Promise.all(
connections.map(async (connection) => {
const postRepository =
connection.getRepository(PostWithoutTypes)
const queryRunner = connection.createQueryRunner()
const table = await queryRunner.getTable("post_without_types")
await queryRunner.release()
const post = new PostWithoutTypes()
post.id = 1
post.name = "Post"
post.bool = true
post.bytes = Buffer.from("A")
post.timestamp = new Date()
post.timestamp.setMilliseconds(0)
await postRepository.save(post)
const loadedPost = (await postRepository.findOneBy({ id: 1 }))!
loadedPost.id.should.be.equal(post.id)
loadedPost.name.should.be.equal(post.name)
loadedPost.bool.should.be.equal(post.bool)
loadedPost.bytes
.toString()
.should.be.equal(post.bytes.toString())
loadedPost.timestamp
.valueOf()
.should.be.equal(post.timestamp.valueOf())
table!.findColumnByName("id")!.type.should.be.equal("int64")
table!.findColumnByName("name")!.type.should.be.equal("string")
table!.findColumnByName("bool")!.type.should.be.equal("bool")
table!.findColumnByName("bytes")!.type.should.be.equal("bytes")
table!
.findColumnByName("timestamp")!
.type.should.be.equal("timestamp")
}),
))
})
``` | /content/code_sandbox/test/functional/database-schema/column-types/spanner/column-types-spanner.ts | xml | 2016-02-29T07:41:14 | 2024-08-16T18:28:52 | typeorm | typeorm/typeorm | 33,875 | 1,391 |
```xml
import { getBasename, getLocalIDFromPathname } from '../../lib/authentication/pathnameHelper';
describe('basename helper', () => {
[
{ name: 'should get basename for 0', input: 0, output: '/u/0' },
{ name: 'should get basename for 1', input: 1, output: '/u/1' },
].forEach(({ name, input, output }) => {
it(name, () => {
expect(getBasename(input)).toEqual(output);
});
});
});
describe('local id pathname helper', () => {
[
{ name: 'should get simple id 0', input: '/u/0', output: 0 },
{
name: 'should get simple id 1',
input: '/u/1',
output: 1,
},
{
name: 'should get id with or without starting slash',
input: 'u/1',
output: 1,
},
{
name: 'should get from pathname',
input: '/u/1/my-complicated/path/',
output: 1,
},
{
name: 'should get id with or without starting slash',
input: 'u/1',
output: 1,
},
{
name: 'should get id with or without starting slash',
input: 'u/123/my-complicated/path',
output: 123,
},
{
name: 'should not get id if it does not starts with /foo',
input: '/foo/u/2/my-complicated/path',
output: undefined,
},
{
name: 'should not get id if it starts with foo',
input: 'foo/u/2/my-complicated/path',
output: undefined,
},
{
name: 'should not get id if it starts with a whitespace',
input: ' /u/2/my-complicated/path',
output: undefined,
},
].forEach(({ name, input, output }) => {
it(name, () => {
expect(getLocalIDFromPathname(input)).toEqual(output);
});
});
});
``` | /content/code_sandbox/packages/shared/test/authentication/pathnameHelper.spec.ts | xml | 2016-06-08T11:16:51 | 2024-08-16T14:14:27 | WebClients | ProtonMail/WebClients | 4,300 | 458 |
```xml
/**
*/
import { translate as t } from '@nextcloud/l10n'
import { type Node, FileType, FileAction, DefaultType } from '@nextcloud/files'
/**
* TODO: Move away from a redirect and handle
* navigation straight out of the recent view
*/
export const action = new FileAction({
id: 'open-in-files-recent',
displayName: () => t('files', 'Open in Files'),
iconSvgInline: () => '',
enabled: (nodes, view) => view.id === 'recent',
async exec(node: Node) {
let dir = node.dirname
if (node.type === FileType.Folder) {
dir = dir + '/' + node.basename
}
window.OCP.Files.Router.goToRoute(
null, // use default route
{ view: 'files', fileid: String(node.fileid) },
{ dir, openfile: 'true' },
)
return null
},
// Before openFolderAction
order: -1000,
default: DefaultType.HIDDEN,
})
``` | /content/code_sandbox/apps/files/src/actions/openInFilesAction.ts | xml | 2016-06-02T07:44:14 | 2024-08-16T18:23:54 | server | nextcloud/server | 26,415 | 227 |
```xml
import { Component, OnInit } from "@angular/core";
import {
debounceTime,
switchMap,
tap,
finalize,
} from "rxjs/operators";
import { empty} from "rxjs";
import { Router } from "@angular/router";
import { UntypedFormGroup, UntypedFormBuilder } from "@angular/forms";
@Component({
selector: "app-nav-search",
templateUrl: "./nav-search.component.html",
styleUrls: ["./nav-search.component.scss"],
})
export class NavSearchComponent implements OnInit {
public searchForm: UntypedFormGroup;
constructor(
private router: Router,
private fb: UntypedFormBuilder
) {}
public async ngOnInit() {
this.searchForm = this.fb.group({
input: null,
});
this.searchForm
.get("input")
.valueChanges.pipe(
debounceTime(1300),
switchMap((value: string) => {
if (value) {
this.router.navigate([`discover`, value]);
}
return empty();;
})
)
.subscribe();
}
}
``` | /content/code_sandbox/src/Ombi/ClientApp/src/app/my-nav/nav-search.component.ts | xml | 2016-02-25T12:14:54 | 2024-08-14T22:56:44 | Ombi | Ombi-app/Ombi | 3,674 | 225 |
```xml
import { useTranslation } from 'react-i18next';
export default function InfoText() {
const { t } = useTranslation();
return (
<div className="prose dark:prose-invert prose-p:my-1 prose-p:leading-snug prose-a:no-underline hover:prose-a:underline">
<p className="mb-4">{t('info.text')}</p>
<p
dangerouslySetInnerHTML={{
__html: t('info.open-source-text', {
link: 'path_to_url
}),
}}
/>
</div>
);
}
``` | /content/code_sandbox/web/src/features/modals/InfoText.tsx | xml | 2016-05-21T16:36:17 | 2024-08-16T17:56:07 | electricitymaps-contrib | electricitymaps/electricitymaps-contrib | 3,437 | 128 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="path_to_url"
xmlns:tools="path_to_url"
android:layout_width="match_parent"
android:layout_height="match_parent">
<org.maplibre.android.maps.MapView
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<RelativeLayout
android:id="@+id/attributionContainer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:padding="8dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/openstreetmapLink"
android:textColor="@color/attribution_text"
android:textSize="12sp"
android:shadowColor="@color/background"
android:shadowRadius="6"
android:text="@string/map_attribution_osm"
android:layout_alignParentLeft="true"
tools:ignore="RtlHardcoded" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/mapTileProviderLink"
android:textColor="@color/attribution_text"
android:textSize="12sp"
android:shadowColor="@color/background"
android:shadowRadius="6"
android:text=" JawgMaps"
android:paddingLeft="8dp"
android:layout_toRightOf="@id/openstreetmapLink"
tools:ignore="RtlHardcoded,RtlSymmetry" />
</RelativeLayout>
</RelativeLayout>
``` | /content/code_sandbox/app/src/main/res/layout/fragment_map.xml | xml | 2016-07-02T10:44:04 | 2024-08-16T18:55:54 | StreetComplete | streetcomplete/StreetComplete | 3,781 | 360 |
```xml
import { Component } from '@angular/core';
import { FieldBaseComponent } from '../field-base';
@Component({
selector: 'app-form-select',
styleUrls: ['form-select.component.scss'],
templateUrl: 'form-select.component.html',
})
export class FormSelectComponent extends FieldBaseComponent {
onChange($event) {
if (this.config.onSelectChange) {
this.config.onSelectChange($event.target.value);
}
}
}
``` | /content/code_sandbox/src/Presentation/Web/ClientApp/src/app/shared/components/forms/components/form-select/form-select.component.ts | xml | 2016-06-03T17:49:56 | 2024-08-14T02:53:24 | AspNetCoreSpa | fullstackproltd/AspNetCoreSpa | 1,472 | 92 |
```xml
import { get } from "lodash";
import sinon from "sinon";
import { pureMerge } from "coral-common/common/lib/utils";
import { act, wait, waitForElement, within } from "coral-framework/testHelpers";
import create from "./create";
import { settings } from "./fixtures";
async function createTestRenderer(
customResolver: any = {},
options: { muteNetworkErrors?: boolean; logNetwork?: boolean } = {}
) {
const resolvers = {
...customResolver,
Query: {
...customResolver.Query,
settings: sinon
.stub()
.returns(pureMerge(settings, get(customResolver, "Query.settings"))),
},
};
const { testRenderer, context } = create({
// Set this to true, to see graphql responses.
logNetwork: options.logNetwork,
muteNetworkErrors: options.muteNetworkErrors,
resolvers,
initLocalState: (localRecord) => {
localRecord.setValue("CREATE_USERNAME", "view");
},
});
const container = await waitForElement(() =>
within(testRenderer.root).getByTestID("createUsername-container")
);
const main = within(testRenderer.root).getByTestID(/.*-main/);
const form = within(main).getByType("form");
const usernameField = within(form).getByLabelText("Username");
return {
context,
testRenderer,
form,
main,
root: testRenderer.root,
usernameField,
container,
};
}
it("renders createUsername view", async () => {
const { root } = await createTestRenderer();
expect(await within(root).axe()).toHaveNoViolations();
});
it("shows server error", async () => {
const username = "hans";
const setUsername = sinon.stub().callsFake((_: any, data: any) => {
throw new Error("server error");
});
const { form, usernameField, submitButton } = await act(async () => {
const { form: f, usernameField: u } = await createTestRenderer(
{
Mutation: {
setUsername,
},
},
{ muteNetworkErrors: true }
);
const s = f.find((i) => i.type === "button" && i.props.type === "submit");
return {
form: f,
usernameField: u,
submitButton: s,
};
});
act(() => usernameField.props.onChange({ target: { value: username } }));
act(() => {
form.props.onSubmit();
});
expect(usernameField.props.disabled).toBe(true);
expect(submitButton.props.disabled).toBe(true);
await act(async () => {
await wait(() => expect(submitButton.props.disabled).toBe(false));
});
});
it("successfully sets username", async () => {
const username = "hans";
const setUsername = sinon.stub().callsFake((_: any, data: any) => {
expectAndFail(data.input).toEqual({
username,
clientMutationId: data.input.clientMutationId,
});
return {
user: {
id: "me",
username,
},
clientMutationId: data.input.clientMutationId,
};
});
const { form, usernameField, submitButton } = await act(async () => {
const { form: f, usernameField: u } = await createTestRenderer(
{
Mutation: {
setUsername,
},
},
{ muteNetworkErrors: true }
);
const s = f.find((i) => i.type === "button" && i.props.type === "submit");
return {
form: f,
usernameField: u,
submitButton: s,
};
});
act(() => usernameField.props.onChange({ target: { value: username } }));
act(() => {
form.props.onSubmit();
});
expect(usernameField.props.disabled).toBe(true);
expect(submitButton.props.disabled).toBe(true);
await act(async () => {
await wait(() => expect(submitButton.props.disabled).toBe(false));
});
expect(setUsername.called).toBe(true);
});
``` | /content/code_sandbox/client/src/core/client/auth/test/createUsername.spec.tsx | xml | 2016-10-31T16:14:05 | 2024-08-06T16:15:57 | talk | coralproject/talk | 1,881 | 874 |
```xml
import { Pipe, PipeTransform } from "@angular/core";
import { FormatPipe } from 'ngx-date-fns';
@Pipe({
name: "ombiDate",
})
export class OmbiDatePipe implements PipeTransform {
constructor(
private FormatPipe: FormatPipe,
) {}
public transform(value: string, format: string ) {
const date = new Date(value);
return this.FormatPipe.transform(date, format);
}
}
``` | /content/code_sandbox/src/Ombi/ClientApp/src/app/pipes/OmbiDatePipe.ts | xml | 2016-02-25T12:14:54 | 2024-08-14T22:56:44 | Ombi | Ombi-app/Ombi | 3,674 | 96 |
```xml
/**
* AVA: path_to_url
* g2-extension-ava: path_to_url
*/
import { Chart } from '@antv/g2';
import { Auto } from '@antv/g2-extension-ava';
const chart = new Chart({
container: 'container',
});
chart.mark(Auto).data([
{ price: 100, type: 'A' },
{ price: 120, type: 'B' },
{ price: 150, type: 'C' },
]);
chart.render();
``` | /content/code_sandbox/site/examples/intelligent/auto/demo/auto-interval.ts | xml | 2016-05-26T09:21:04 | 2024-08-15T16:11:17 | G2 | antvis/G2 | 12,060 | 110 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<!--
path_to_url
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-->
<resources>
<!-- Base application theme. -->
<style name="Theme.Demo" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/primary</item>
<item name="colorPrimaryDark">@color/primaryDark</item>
<item name="colorAccent">@color/accent</item>
<item name="android:textColorPrimary">@color/primaryText</item>
<item name="android:textColorSecondary">@color/secondaryText</item>
</style>
</resources>
``` | /content/code_sandbox/demo/src/main/res/values/styles.xml | xml | 2016-08-04T05:22:14 | 2024-08-08T07:34:11 | cameraview | google/cameraview | 4,736 | 171 |
```xml
import React from 'react';
import { observable, runInAction } from 'mobx';
import { storiesOf } from '@storybook/react';
import { action } from '@storybook/addon-actions';
import { withKnobs, select } from '@storybook/addon-knobs';
import BigNumber from 'bignumber.js';
import {
DEVELOPMENT,
TESTNET,
STAGING,
} from '../../../source/common/types/environment.types';
import StoryDecorator from '../_support/StoryDecorator';
import StoryProvider from '../_support/StoryProvider';
import { isShelleyTestnetTheme } from '../_support/utils';
import Sidebar from '../../../source/renderer/app/components/sidebar/Sidebar';
import {
CATEGORIES_WITH_DELEGATION_COUNTDOWN,
CATEGORIES_WITHOUT_DELEGATION_COUNTDOWN,
} from '../../../source/renderer/app/config/sidebarConfig';
const sidebarMenus = observable({
wallets: {
items: [
{
id: '1',
title: 'First',
amount: new BigNumber(100),
isNotResponding: false,
isConnected: true,
isLegacy: false,
hasNotification: false,
},
{
id: '2',
title: 'Second',
amount: new BigNumber(200),
isNotResponding: false,
isConnected: true,
isLegacy: false,
hasNotification: false,
},
{
id: '3',
title: 'Third',
amount: new BigNumber(300),
isNotResponding: false,
isConnected: true,
isLegacy: false,
hasNotification: false,
},
],
activeWalletId: '1',
actions: {
onAddWallet: action('toggleAddWallet'),
onWalletItemClick: (walletId: string) => {
runInAction(() => {
sidebarMenus.wallets.activeWalletId = walletId;
});
},
},
},
hardwareWallets: null,
});
const sidebarMenusHardware = observable({
wallets: null,
hardwareWallets: {
items: [
{
id: '1',
title: 'BTC wallet',
info: '2.41824 BTC',
isNotResponding: false,
isConnected: false,
isLegacy: false,
hasNotification: false,
},
{
id: '2',
title: 'ETC wallet',
info: '12M ETC',
isNotResponding: false,
isConnected: false,
isLegacy: false,
hasNotification: false,
},
{
id: '3',
title: 'ADA wallet',
info: '9,800 ADA',
isNotResponding: false,
isConnected: true,
isLegacy: false,
hasNotification: false,
},
],
activeWalletId: '3',
actions: {
onAddWallet: action('toggleAddWallet'),
onHardwareWalletItemClick: (walletId: string) => {
runInAction(() => {
sidebarMenusHardware.hardwareWallets.activeWalletId = walletId;
});
},
},
},
});
let emptyMenus;
storiesOf('Navigation / Sidebar', module)
.addDecorator((story) => (
<StoryProvider>
<StoryDecorator>{story()}</StoryDecorator>
</StoryProvider>
))
.addDecorator(withKnobs) // ====== Stories ======
// @ts-ignore ts-migrate(2345) FIXME: Argument of type '(props: { currentTheme: strin... Remove this comment to see the full error message
.add('No Category', (_, props: { currentTheme: string }) => (
<Sidebar
menus={emptyMenus}
categories={CATEGORIES_WITH_DELEGATION_COUNTDOWN}
activeSidebarCategory=""
onActivateCategory={action('onActivateCategory')}
// @ts-ignore ts-migrate(2322) FIXME: Type '{ menus: any; categories: { name: string; ic... Remove this comment to see the full error message
isDialogOpen={() => false}
onAddWallet={action('onAddWallet')}
onOpenDialog={action('openDialog')}
onSubmitSupportRequest={() => {}}
pathname="/"
currentTheme={props.currentTheme}
network="testnet"
isShelleyActivated={isShelleyTestnetTheme(props.currentTheme)}
/>
))
// @ts-ignore ts-migrate(2345) FIXME: Argument of type '(props: { currentTheme: strin... Remove this comment to see the full error message
.add('Wallets Category', (_, props: { currentTheme: string }) => (
<Sidebar
menus={emptyMenus}
categories={CATEGORIES_WITH_DELEGATION_COUNTDOWN}
activeSidebarCategory={CATEGORIES_WITH_DELEGATION_COUNTDOWN[0].route}
onActivateCategory={action('onActivateCategory')}
// @ts-ignore ts-migrate(2322) FIXME: Type '{ menus: any; categories: { name: string; ic... Remove this comment to see the full error message
isDialogOpen={() => false}
onAddWallet={action('onAddWallet')}
onOpenDialog={action('openDialog')}
onSubmitSupportRequest={() => {}}
pathname="/"
currentTheme={props.currentTheme}
network="testnet"
isShelleyActivated={isShelleyTestnetTheme(props.currentTheme)}
/>
))
// @ts-ignore ts-migrate(2345) FIXME: Argument of type '(props: { currentTheme: strin... Remove this comment to see the full error message
.add('Wallet Selected', (_, props: { currentTheme: string }) => (
<Sidebar
categories={CATEGORIES_WITH_DELEGATION_COUNTDOWN}
activeSidebarCategory={CATEGORIES_WITH_DELEGATION_COUNTDOWN[0].route}
// @ts-ignore ts-migrate(2322) FIXME: Type '{ wallets: { items: { id: string; title: str... Remove this comment to see the full error message
menus={sidebarMenus}
onActivateCategory={action('onActivateCategory')}
isShowingSubMenus
// @ts-ignore ts-migrate(2322) FIXME: Type '{ categories: { name: string; icon: any; rou... Remove this comment to see the full error message
isDialogOpen={() => false}
onAddWallet={action('onAddWallet')}
onOpenDialog={action('openDialog')}
onSubmitSupportRequest={() => {}}
pathname="/"
currentTheme={props.currentTheme}
network="testnet"
isShelleyActivated={isShelleyTestnetTheme(props.currentTheme)}
/>
))
// @ts-ignore ts-migrate(2345) FIXME: Argument of type '(props: { currentTheme: strin... Remove this comment to see the full error message
.add('Hardware Wallet Selected', (_, props: { currentTheme: string }) => (
<Sidebar
categories={CATEGORIES_WITH_DELEGATION_COUNTDOWN}
activeSidebarCategory={CATEGORIES_WITH_DELEGATION_COUNTDOWN[1].route}
menus={sidebarMenusHardware}
onActivateCategory={action('onActivateCategory')}
isShowingSubMenus
// @ts-ignore ts-migrate(2322) FIXME: Type '{ categories: { name: string; icon: any; rou... Remove this comment to see the full error message
isDialogOpen={() => false}
onAddWallet={action('onAddWallet')}
onOpenDialog={action('openDialog')}
onSubmitSupportRequest={() => {}}
pathname="/"
currentTheme={props.currentTheme}
network="testnet"
isShelleyActivated={isShelleyTestnetTheme(props.currentTheme)}
/>
))
// @ts-ignore ts-migrate(2345) FIXME: Argument of type '(props: { currentTheme: strin... Remove this comment to see the full error message
.add('Delegation Category', (_, props: { currentTheme: string }) => (
<Sidebar
menus={emptyMenus}
categories={CATEGORIES_WITH_DELEGATION_COUNTDOWN}
activeSidebarCategory={CATEGORIES_WITH_DELEGATION_COUNTDOWN[2].route}
onActivateCategory={action('onActivateCategory')}
// @ts-ignore ts-migrate(2322) FIXME: Type '{ menus: any; categories: { name: string; ic... Remove this comment to see the full error message
isDialogOpen={() => false}
onAddWallet={action('onAddWallet')}
onOpenDialog={action('openDialog')}
onSubmitSupportRequest={() => {}}
pathname="/"
currentTheme={props.currentTheme}
network="testnet"
isShelleyActivated={isShelleyTestnetTheme(props.currentTheme)}
/>
))
.add(
'Decentralization Progress Category',
// @ts-ignore ts-migrate(2345) FIXME: Argument of type '(props: { currentTheme: strin... Remove this comment to see the full error message
(_, props: { currentTheme: string }) => (
<Sidebar
menus={emptyMenus}
categories={CATEGORIES_WITHOUT_DELEGATION_COUNTDOWN}
activeSidebarCategory={CATEGORIES_WITHOUT_DELEGATION_COUNTDOWN[1].route}
onActivateCategory={action('onActivateCategory')}
// @ts-ignore ts-migrate(2322) FIXME: Type '{ menus: any; categories: { name: string; ic... Remove this comment to see the full error message
isDialogOpen={() => false}
onAddWallet={action('onAddWallet')}
onOpenDialog={action('openDialog')}
onSubmitSupportRequest={() => {}}
pathname="/"
currentTheme={props.currentTheme}
network="testnet"
isShelleyActivated={isShelleyTestnetTheme(props.currentTheme)}
/>
)
)
// @ts-ignore ts-migrate(2345) FIXME: Argument of type '(props: { currentTheme: strin... Remove this comment to see the full error message
.add('Network label', (_, props: { currentTheme: string }) => (
<Sidebar
menus={emptyMenus}
categories={CATEGORIES_WITH_DELEGATION_COUNTDOWN}
activeSidebarCategory=""
onActivateCategory={action('onActivateCategory')}
// @ts-ignore ts-migrate(2322) FIXME: Type '{ menus: any; categories: { name: string; ic... Remove this comment to see the full error message
isDialogOpen={() => false}
onAddWallet={action('onAddWallet')}
onOpenDialog={action('openDialog')}
onSubmitSupportRequest={() => {}}
pathname="/"
currentTheme={props.currentTheme}
network={select(
'Netork badge',
{
Development: DEVELOPMENT,
Test: TESTNET,
Staging: STAGING,
},
TESTNET
)}
isShelleyActivated={isShelleyTestnetTheme(props.currentTheme)}
/>
));
``` | /content/code_sandbox/storybook/stories/navigation/Sidebar.stories.tsx | xml | 2016-10-05T13:48:54 | 2024-08-13T22:03:19 | daedalus | input-output-hk/daedalus | 1,230 | 2,345 |
```xml
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { localized, FocusedPerspectiveStore, Thread } from 'mailspring-exports';
import { RetinaImg, MailLabel } from 'mailspring-component-kit';
import { PLUGIN_ID } from './snooze-constants';
import { snoozedUntilMessage } from './snooze-utils';
export class SnoozeMailLabel extends Component<{ thread: Thread }> {
static displayName = 'SnoozeMailLabel';
static propTypes = {
thread: PropTypes.object,
};
static containerRequired = false;
render() {
const current = FocusedPerspectiveStore.current();
const isSnoozedPerspective =
current.categories().length > 0 && current.categories()[0].role === 'snoozed';
if (!isSnoozedPerspective) {
return false;
}
const { thread } = this.props;
if (!thread.categories.find(c => c.role === 'snoozed')) {
return false;
}
const metadata = thread.metadataForPluginId(PLUGIN_ID);
if (!metadata || !metadata.expiration) {
return false;
}
const content = (
<span className="snooze-mail-label">
<RetinaImg name="icon-snoozed.png" mode={RetinaImg.Mode.ContentIsMask} />
<span className="date-message">
{snoozedUntilMessage(metadata.expiration)
.replace('Snoozed', '')
.replace(localized('Snoozed'), '')}
</span>
</span>
);
const label = {
displayName: content,
isLockedCategory: () => true,
hue: () => 259,
};
return <MailLabel label={label} key={`snooze-message-${thread.id}`} />;
}
}
``` | /content/code_sandbox/app/internal_packages/thread-snooze/lib/snooze-mail-label.tsx | xml | 2016-10-13T06:45:50 | 2024-08-16T18:14:37 | Mailspring | Foundry376/Mailspring | 15,331 | 400 |
```xml
<resources>
<string name="app_name">FragmentBestPractice</string>
</resources>
``` | /content/code_sandbox/chapter4/FragmentBestPractice/app/src/main/res/values/strings.xml | xml | 2016-10-04T02:55:57 | 2024-08-16T11:00:26 | booksource | guolindev/booksource | 3,105 | 21 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="path_to_url"
xmlns:tools="path_to_url"
android:id="@+id/md_colorChooserCustomFrame"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:paddingBottom="@dimen/md_title_frame_margin_bottom"
android:paddingTop="@dimen/md_title_frame_margin_bottom">
<View
android:id="@+id/md_colorIndicator"
android:layout_width="match_parent"
android:layout_height="120dp"
tools:background="@color/md_material_blue_600"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="@dimen/md_title_frame_margin_bottom"
android:gravity="center">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="2dp"
android:layout_marginRight="2dp"
android:digits="0123456789abcdefABCDEF"
android:text="#"
android:textColor="?android:textColorPrimary"
android:textColorHint="?android:textColorSecondary"
android:textSize="@dimen/md_title_textsize"
tools:ignore="HardcodedText,TextViewEdits"/>
<EditText
android:id="@+id/md_hexInput"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:digits="0123456789abcdefABCDEF"
android:hint="FF0099CC"
android:textSize="@dimen/md_title_textsize"
tools:ignore="HardcodedText"/>
</LinearLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/md_title_frame_margin_bottom"
android:paddingLeft="@dimen/md_dialog_frame_margin"
android:paddingRight="@dimen/md_dialog_frame_margin">
<!-- Alpha -->
<TextView
android:id="@+id/md_colorALabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/md_colorA"
android:layout_alignTop="@+id/md_colorA"
android:layout_marginEnd="4dp"
android:layout_marginRight="4dp"
android:text="A"
android:textColor="?android:textColorPrimary"
android:textSize="@dimen/md_content_textsize"
tools:ignore="HardcodedText"/>
<SeekBar
android:id="@+id/md_colorA"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/md_title_frame_margin_bottom"
android:layout_toEndOf="@+id/md_colorALabel"
android:layout_toLeftOf="@+id/md_colorAValue"
android:layout_toRightOf="@+id/md_colorALabel"
android:layout_toStartOf="@+id/md_colorAValue"
android:max="255"/>
<TextView
android:id="@+id/md_colorAValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/md_colorA"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_alignTop="@+id/md_colorA"
android:layout_marginLeft="4dp"
android:layout_marginStart="4dp"
android:gravity="center"
android:minWidth="24dp"
android:text="0"
android:textColor="?android:textColorPrimary"
android:textSize="@dimen/md_content_textsize"
tools:ignore="HardcodedText"/>
<!-- Red -->
<TextView
android:id="@+id/md_colorRLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/md_colorR"
android:layout_alignTop="@+id/md_colorR"
android:layout_marginEnd="4dp"
android:layout_marginRight="4dp"
android:text="R"
android:textColor="?android:textColorPrimary"
android:textSize="@dimen/md_content_textsize"
tools:ignore="HardcodedText"/>
<SeekBar
android:id="@+id/md_colorR"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/md_colorA"
android:layout_marginTop="@dimen/md_title_frame_margin_bottom"
android:layout_toEndOf="@+id/md_colorRLabel"
android:layout_toLeftOf="@+id/md_colorRValue"
android:layout_toRightOf="@+id/md_colorRLabel"
android:layout_toStartOf="@+id/md_colorRValue"
android:max="255"/>
<TextView
android:id="@+id/md_colorRValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/md_colorR"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_alignTop="@+id/md_colorR"
android:layout_marginLeft="4dp"
android:layout_marginStart="4dp"
android:gravity="center"
android:minWidth="24dp"
android:text="0"
android:textColor="?android:textColorPrimary"
android:textSize="@dimen/md_content_textsize"
tools:ignore="HardcodedText"/>
<!-- Green -->
<TextView
android:id="@+id/md_colorGLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/md_colorG"
android:layout_alignTop="@+id/md_colorG"
android:layout_marginEnd="4dp"
android:layout_marginRight="4dp"
android:text="G"
android:textColor="?android:textColorPrimary"
android:textSize="@dimen/md_content_textsize"
tools:ignore="HardcodedText"/>
<SeekBar
android:id="@+id/md_colorG"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/md_colorR"
android:layout_marginTop="@dimen/md_title_frame_margin_bottom"
android:layout_toEndOf="@+id/md_colorGLabel"
android:layout_toLeftOf="@+id/md_colorGValue"
android:layout_toRightOf="@+id/md_colorGLabel"
android:layout_toStartOf="@+id/md_colorGValue"
android:max="255"/>
<TextView
android:id="@+id/md_colorGValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/md_colorG"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_alignTop="@+id/md_colorG"
android:layout_marginLeft="4dp"
android:layout_marginStart="4dp"
android:gravity="center"
android:minWidth="24dp"
android:text="0"
android:textColor="?android:textColorPrimary"
android:textSize="@dimen/md_content_textsize"
tools:ignore="HardcodedText"/>
<!-- Blue -->
<TextView
android:id="@+id/md_colorBLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/md_colorB"
android:layout_alignTop="@+id/md_colorB"
android:layout_marginEnd="4dp"
android:layout_marginRight="4dp"
android:text="B"
android:textColor="?android:textColorPrimary"
android:textSize="@dimen/md_content_textsize"
tools:ignore="HardcodedText"/>
<SeekBar
android:id="@+id/md_colorB"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/md_colorG"
android:layout_marginTop="@dimen/md_title_frame_margin_bottom"
android:layout_toEndOf="@+id/md_colorBLabel"
android:layout_toLeftOf="@+id/md_colorBValue"
android:layout_toRightOf="@+id/md_colorBLabel"
android:layout_toStartOf="@+id/md_colorBValue"
android:max="255"/>
<TextView
android:id="@+id/md_colorBValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/md_colorB"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_alignTop="@+id/md_colorB"
android:layout_marginLeft="4dp"
android:layout_marginStart="4dp"
android:gravity="center"
android:minWidth="24dp"
android:text="0"
android:textColor="?android:textColorPrimary"
android:textSize="@dimen/md_content_textsize"
tools:ignore="HardcodedText"/>
</RelativeLayout>
</LinearLayout>
``` | /content/code_sandbox/app/src/main/res/layout/md_stub_colorchooser_custom.xml | xml | 2016-01-14T13:38:47 | 2024-08-16T13:03:46 | APlayer | rRemix/APlayer | 1,308 | 2,027 |
```xml
import {
ILegacyTxObject,
ILegacyTxReceipt,
ITxObject,
ITxReceipt,
ITxType2Object,
ITxType2Receipt
} from '@types';
export const isTypedTx = (tx: Partial<ITxObject>): tx is Partial<ITxType2Object> => {
return 'type' in tx && tx.type !== null && tx.type !== undefined && tx.type !== 0;
};
export const isType2Tx = (tx: Partial<ITxObject>): tx is Partial<ITxType2Object> => {
return isTypedTx(tx) && tx.type === 2;
};
export const isLegacyTx = (tx: ITxObject): tx is ILegacyTxObject => {
return !isTypedTx(tx);
};
export const isTypedReceipt = (tx: ITxReceipt): tx is ITxType2Receipt => {
return 'type' in tx && tx.type !== null && tx.type !== undefined && tx.type !== 0;
};
export const isType2Receipt = (tx: ITxReceipt): tx is ITxType2Receipt => {
return isTypedReceipt(tx) && tx.type === 2;
};
export const isLegacyReceipt = (tx: ITxReceipt): tx is ILegacyTxReceipt => {
return !isTypedReceipt(tx);
};
``` | /content/code_sandbox/src/utils/typedTx.ts | xml | 2016-12-04T01:35:27 | 2024-08-14T21:41:58 | MyCrypto | MyCryptoHQ/MyCrypto | 1,347 | 288 |
```xml
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>$(BasicTargetFrameworks);$(WindowsDesktopTargetFrameworks)</TargetFrameworks>
<RootNamespace>SkiaSharp.Views.Desktop</RootNamespace>
<AssemblyName>SkiaSharp.Views.Desktop.Common</AssemblyName>
<PackagingGroup>SkiaSharp.Views.Desktop.Common</PackagingGroup>
<DefineConstants>$(DefineConstants);__DESKTOP__</DefineConstants>
<Title>SkiaSharp Views & Layers for Desktop</Title>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\binding\SkiaSharp\SkiaSharp.csproj" />
</ItemGroup>
<ItemGroup>
<Compile Include="..\SkiaSharp.Views.Shared\**\*.cs" Link="%(RecursiveDir)%(Filename)%(Extension)" />
</ItemGroup>
</Project>
``` | /content/code_sandbox/source/SkiaSharp.Views/SkiaSharp.Views.Desktop.Common/SkiaSharp.Views.Desktop.Common.csproj | xml | 2016-02-22T17:54:43 | 2024-08-16T17:53:42 | SkiaSharp | mono/SkiaSharp | 4,347 | 196 |
```xml
/**
* @license Apache-2.0
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
import { HttpClientTestingModule, HttpTestingController } from "@angular/common/http/testing";
import { TestBed } from "@angular/core/testing";
import { type ResponseServer } from "trafficops-types";
import { ServerService } from "./server.service";
describe("ServerService", () => {
let service: ServerService;
let httpTestingController: HttpTestingController;
const server: ResponseServer = {
cachegroup: "cachegroup",
cachegroupId: 1,
cdnId: 1,
cdnName: "cdnName",
domainName: "quest",
guid: null,
hostName: "test",
httpsPort: null,
id: 1,
iloIpAddress: null,
iloIpGateway: null,
iloIpNetmask: null,
iloPassword: null,
iloUsername: null,
interfaces: [],
lastUpdated: new Date(),
mgmtIpAddress: null,
mgmtIpGateway: null,
mgmtIpNetmask: null,
offlineReason: null,
physLocation: "physicalLocation",
physLocationId: 1,
profileNames: ["profile"],
rack: null,
revalPending: false,
routerHostName: null,
routerPortName: null,
status: "ONLINE",
statusId: 1,
statusLastUpdated: null,
tcpPort: null,
type: "EDGE",
typeId: 1,
updPending: false,
xmppId: "xmppId",
};
const status = {
description: "description",
id: 1,
lastUpdated: new Date(),
name: "testquest",
};
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [
ServerService,
]
});
service = TestBed.inject(ServerService);
httpTestingController = TestBed.inject(HttpTestingController);
});
it("should be created", () => {
expect(service).toBeTruthy();
});
describe("server methods", () => {
it("sends requests for multiple servers", async () => {
const responseP = service.getServers();
const req = httpTestingController.expectOne(`/api/${service.apiVersion}/servers`);
expect(req.request.method).toBe("GET");
req.flush({response: [server]});
await expectAsync(responseP).toBeResolvedTo([server]);
});
it("sends requests for a single server by ID", async () => {
const responseP = service.getServers(server.id);
const req = httpTestingController.expectOne(r => r.url === `/api/${service.apiVersion}/servers`);
expect(req.request.params.keys().length).toBe(1);
expect(req.request.params.get("id")).toBe(String(server.id));
expect(req.request.method).toBe("GET");
req.flush({response: [server]});
await expectAsync(responseP).toBeResolvedTo(server);
});
it("sends requests for a single server by hostName", async () => {
const responseP = service.getServers(server.hostName);
const req = httpTestingController.expectOne(r => r.url === `/api/${service.apiVersion}/servers`);
expect(req.request.params.keys().length).toBe(1);
expect(req.request.params.get("hostName")).toBe(server.hostName);
expect(req.request.method).toBe("GET");
req.flush({response: [server]});
await expectAsync(responseP).toBeResolvedTo(server);
});
it("returns a single server when TO presents it with multiple matches by hostName", async () => {
const responseP = service.getServers(server.hostName);
const req = httpTestingController.expectOne(r => r.url === `/api/${service.apiVersion}/servers`);
expect(req.request.params.keys().length).toBe(1);
expect(req.request.params.get("hostName")).toBe(server.hostName);
expect(req.request.method).toBe("GET");
req.flush({response: [server, {...server, id: server.id + 1}]});
await expectAsync(responseP).toBeResolvedTo(server);
});
it("throws an error when fetching a non-existent server", async () => {
const responseP = service.getServers(server.id);
const req = httpTestingController.expectOne(r => r.url === `/api/${service.apiVersion}/servers`);
expect(req.request.params.keys().length).toBe(1);
expect(req.request.params.get("id")).toBe(String(server.id));
expect(req.request.method).toBe("GET");
req.flush({response: []});
await expectAsync(responseP).toBeRejected();
});
it("sends requests for creating a new server", async () => {
const responseP = service.createServer(server);
const req = httpTestingController.expectOne(`/api/${service.apiVersion}/servers`);
expect(req.request.method).toBe("POST");
expect(req.request.body).toEqual(server);
req.flush({response: server});
await expectAsync(responseP).toBeResolvedTo(server);
});
it("updates a server by ID", async () => {
const resp = service.updateServer(server.id, server);
const req = httpTestingController.expectOne(`/api/${service.apiVersion}/servers/${server.id}`);
expect(req.request.method).toBe("PUT");
expect(req.request.body).toEqual(server);
req.flush({response: server});
await expectAsync(resp).toBeResolvedTo(server);
});
it("updates a server", async () => {
const resp = service.updateServer(server);
const req = httpTestingController.expectOne(`/api/${service.apiVersion}/servers/${server.id}`);
expect(req.request.method).toBe("PUT");
expect(req.request.body).toEqual(server);
req.flush({response: server});
await expectAsync(resp).toBeResolvedTo(server);
});
it("delete a server", async () => {
const resp = service.deleteServer(server);
const req = httpTestingController.expectOne(`/api/${service.apiVersion}/servers/${server.id}`);
expect(req.request.method).toBe("DELETE");
expect(req.request.body).toBeNull();
req.flush({response: server});
await expectAsync(resp).toBeResolvedTo(server);
});
it("delete a server by ID", async () => {
const resp = service.deleteServer(server.id);
const req = httpTestingController.expectOne(`/api/${service.apiVersion}/servers/${server.id}`);
expect(req.request.method).toBe("DELETE");
expect(req.request.body).toBeNull();
req.flush({response: server});
await expectAsync(resp).toBeResolvedTo(server);
});
});
describe("Status-related methods", () => {
it("sends requests for multiple statuses", async () => {
const responseP = service.getStatuses();
const req = httpTestingController.expectOne(`/api/${service.apiVersion}/statuses`);
expect(req.request.method).toBe("GET");
req.flush({response: [status]});
await expectAsync(responseP).toBeResolvedTo([status]);
});
it("sends requests for a single status by ID", async () => {
const responseP = service.getStatuses(status.id);
const req = httpTestingController.expectOne(r => r.url === `/api/${service.apiVersion}/statuses`);
expect(req.request.params.keys().length).toBe(1);
expect(req.request.params.get("id")).toBe(String(status.id));
expect(req.request.method).toBe("GET");
req.flush({response: [status]});
await expectAsync(responseP).toBeResolvedTo(status);
});
it("sends requests for a single status by name", async () => {
const responseP = service.getStatuses(status.name);
const req = httpTestingController.expectOne(r => r.url === `/api/${service.apiVersion}/statuses`);
expect(req.request.params.keys().length).toBe(1);
expect(req.request.params.get("name")).toBe(status.name);
expect(req.request.method).toBe("GET");
req.flush({response: [status]});
await expectAsync(responseP).toBeResolvedTo(status);
});
it("throws an error when fetching a non-existent status", async () => {
const responseP = service.getStatuses(status.id);
const req = httpTestingController.expectOne(r => r.url === `/api/${service.apiVersion}/statuses`);
expect(req.request.params.keys().length).toBe(1);
expect(req.request.params.get("id")).toBe(String(status.id));
expect(req.request.method).toBe("GET");
req.flush({response: []});
await expectAsync(responseP).toBeRejected();
});
it("updates a server's status", async () => {
const responseP = service.updateStatus(server, status);
const req = httpTestingController.expectOne(`/api/${service.apiVersion}/servers/${server.id}/status`);
expect(req.request.method).toBe("PUT");
// We specifically don't care whether the offline reason truly isn't
// specified or has the value `undefined`. Actually, `null` would
// also work for the API, but typings forbid that.
expect([{offlineReason: undefined, status: status.name}, {status: status.name}]).toContain(req.request.body);
req.flush({});
await expectAsync(responseP).toBeResolved();
});
it("updates a server's status with an offlineReason", async () => {
const offlineReason = "because I told you to";
const responseP = service.updateStatus(server.id, status.name, offlineReason);
const req = httpTestingController.expectOne(`/api/${service.apiVersion}/servers/${server.id}/status`);
expect(req.request.method).toBe("PUT");
expect(req.request.body).toEqual({offlineReason, status: status.name});
req.flush({});
await expectAsync(responseP).toBeResolved();
});
it("creates a new status", async () => {
const responseP = service.createStatus(status);
const req = httpTestingController.expectOne(`/api/${service.apiVersion}/statuses`);
expect(req.request.method).toBe("POST");
expect(req.request.body).toEqual(status);
req.flush({response: status});
await expectAsync(responseP).toBeResolvedTo(status);
});
it("updates an existing status", async () => {
const responseP = service.updateStatusDetail(status);
const req = httpTestingController.expectOne(`/api/${service.apiVersion}/statuses/${status.id}`);
expect(req.request.method).toBe("PUT");
expect(req.request.body).toEqual(status);
req.flush({response: status});
await expectAsync(responseP).toBeResolvedTo(status);
});
it("deletes statuses", async () => {
const responseP = service.deleteStatus(status);
const req = httpTestingController.expectOne(`/api/${service.apiVersion}/statuses/${status.id}`);
expect(req.request.method).toBe("DELETE");
expect(req.request.body).toBeNull();
req.flush({response: status});
await expectAsync(responseP).toBeResolvedTo(status);
});
it("deletes statuses by ID", async () => {
const responseP = service.deleteStatus(status.id);
const req = httpTestingController.expectOne(`/api/${service.apiVersion}/statuses/${status.id}`);
expect(req.request.method).toBe("DELETE");
expect(req.request.body).toBeNull();
req.flush({response: status});
await expectAsync(responseP).toBeResolvedTo(status);
});
});
describe("other methods", () => {
const serverCheck = {
adminState: "ONLINE",
cacheGroup: "cacheGroup",
hostName: "hostName",
id: 1,
profile: "profile",
revalPending: false,
type: "EDGE",
updPending: false,
};
it("queues updates on a server", async () => {
const responseP = service.queueUpdates(server);
const req = httpTestingController.expectOne(`/api/${service.apiVersion}/servers/${server.id}/queue_update`);
expect(req.request.method).toBe("POST");
expect(req.request.body).toEqual({action: "queue"});
const response = {action: "queue" as const, serverId: server.id};
req.flush({response});
await expectAsync(responseP).toBeResolvedTo(response);
});
it("queues updates on a server by ID", async () => {
const responseP = service.queueUpdates(server.id);
const req = httpTestingController.expectOne(`/api/${service.apiVersion}/servers/${server.id}/queue_update`);
expect(req.request.method).toBe("POST");
expect(req.request.body).toEqual({action: "queue"});
const response = {action: "queue" as const, serverId: server.id};
req.flush({response});
await expectAsync(responseP).toBeResolvedTo(response);
});
it("de-queues updates on a server", async () => {
const responseP = service.clearUpdates(server);
const req = httpTestingController.expectOne(`/api/${service.apiVersion}/servers/${server.id}/queue_update`);
expect(req.request.method).toBe("POST");
expect(req.request.body).toEqual({action: "dequeue"});
const response = {action: "dequeue" as const, serverId: server.id};
req.flush({response});
await expectAsync(responseP).toBeResolvedTo(response);
});
it("de-queues updates on a server by ID", async () => {
const responseP = service.clearUpdates(server.id);
const req = httpTestingController.expectOne(`/api/${service.apiVersion}/servers/${server.id}/queue_update`);
expect(req.request.method).toBe("POST");
expect(req.request.body).toEqual({action: "dequeue"});
const response = {action: "dequeue" as const, serverId: server.id};
req.flush({response});
await expectAsync(responseP).toBeResolvedTo(response);
});
it("sends a request for multiple Serverchecks", async () => {
const responseP = service.getServerChecks();
const req = httpTestingController.expectOne(`/api/${service.apiVersion}/servercheck`);
expect(req.request.method).toBe("GET");
const response = [serverCheck];
req.flush({response});
await expectAsync(responseP).toBeResolvedTo(response);
});
it("gets Serverchecks for a single server by ID", async () => {
const responseP = service.getServerChecks(server.id);
const req = httpTestingController.expectOne(`/api/${service.apiVersion}/servercheck`);
expect(req.request.method).toBe("GET");
const response = [{...serverCheck, id: 2}, serverCheck];
req.flush({response});
await expectAsync(responseP).toBeResolvedTo(response[1]);
});
it("throws an error if the checks for the requested server cannot be found", async () => {
const responseP = service.getServerChecks(server.id);
const req = httpTestingController.expectOne(`/api/${service.apiVersion}/servercheck`);
expect(req.request.method).toBe("GET");
const response = [{...serverCheck, id: server.id+1}];
req.flush({response});
await expectAsync(responseP).toBeRejected(response[1]);
});
});
describe("static methods", () => {
it("finds a service address", () => {
const infs = [
{
ipAddresses: [
{
address: "",
gateway: "",
serviceAddress: false
}
],
maxBandwidth: null,
monitor: false,
mtu: null,
name: "eth0"
},
{
ipAddresses: [
{
address: "",
gateway: "",
serviceAddress: false
},
{
address: "",
gateway: "",
serviceAddress: false
}
],
maxBandwidth: null,
monitor: false,
mtu: null,
name: "eth1"
},
{
ipAddresses: [
{
address: "",
gateway: "",
serviceAddress: false
},
{
address: "",
gateway: "",
serviceAddress: true
},
],
maxBandwidth: null,
monitor: false,
mtu: null,
name: "eth2"
}
];
const serviceInf = ServerService.getServiceInterface(infs);
expect(serviceInf).toBe(infs[2]);
});
it("throws an error when a server has no service addresses", () => {
expect(()=>ServerService.getServiceInterface({
cachegroupId: -1,
cdnId: -1,
domainName: "",
hostName: "",
interfaces: [{
ipAddresses: [
{
address: "",
gateway: "",
serviceAddress: false
},
{
address: "",
gateway: "",
serviceAddress: false
}
],
maxBandwidth: null,
monitor: false,
mtu: null,
name: "eth0"
}],
physLocationId: -1,
profileNames: [],
statusId: -1,
typeId: -1,
})).toThrow();
});
it("extracts netmasks", () => {
const [addr, netmask] = ServerService.extractNetmask("192.168.0.1/16");
expect(addr).toBe("192.168.0.1");
expect(netmask).toBe("255.255.0.0");
});
it("doesn't break when a plain address (no CIDR suffix) is passed", () => {
const raw = "192.168.0.1";
const [addr, netmask] = ServerService.extractNetmask(raw);
expect(addr).toBe(raw);
expect(netmask).toBeUndefined();
});
});
afterEach(() => {
httpTestingController.verify();
});
});
``` | /content/code_sandbox/experimental/traffic-portal/src/app/api/server.service.spec.ts | xml | 2016-09-02T07:00:06 | 2024-08-16T03:50:21 | trafficcontrol | apache/trafficcontrol | 1,043 | 3,911 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="path_to_url"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="1">
<TextView
android:text="Client:"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="10dp"
android:paddingTop="20dp"
/>
<Spinner
android:id="@+id/spinner_arpreplay_stations"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="20dp"
android:paddingBottom="20dp" />
<Button
android:id="@+id/btn_start_arpreplay"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Start"
android:paddingTop="20dp"
android:paddingBottom="20dp" />
</LinearLayout>
``` | /content/code_sandbox/app/app/src/main/res/layout/fragment_arp_replay_dialog.xml | xml | 2016-10-27T09:31:28 | 2024-08-16T19:00:35 | nexmon | seemoo-lab/nexmon | 2,381 | 224 |
```xml
import { RequestsImport } from '../base/request_import';
import { Record } from '../../models/record';
import * as _ from 'lodash';
import { StringUtil } from '../../utils/string_util';
import { RecordCategory } from '../../common/enum/record_category';
import { RecordService } from '../record_service';
import { ParameterType } from '../../common/enum/parameter_type';
import { DtoHeader } from '../../common/interfaces/dto_header';
import { HeaderService } from '../header_service';
import { Header } from '../../models/header';
import { User } from '../../models/user';
import { CollectionService } from '../collection_service';
import { ProjectService } from '../project_service';
import { DtoCollection } from '../../common/interfaces/dto_collection';
import { DtoBodyFormData } from '../../common/interfaces/dto_variable';
import { DataMode } from '../../common/enum/data_mode';
import { Environment } from '../../models/environment';
import { VariableService } from '../variable_service';
import { EnvironmentService } from '../environment_service';
export class SwaggerImport implements RequestsImport {
baseUrl: string;
async import(swaggerData: any, projectId: string, user: User): Promise<void> {
const env = this.createEnv(projectId, `${swaggerData.host}${swaggerData.basePath}`);
this.baseUrl = '{{host}}';
let sort = await RecordService.getMaxSort();
const dtoCollection: DtoCollection = {
name: swaggerData.info.title,
commonPreScript: '',
commonSetting: { prescript: '', test: '', headers: [] },
projectId: projectId,
id: StringUtil.generateUID(),
description: swaggerData.info.description
};
const collection = CollectionService.fromDto(dtoCollection);
collection.owner = user;
collection.project = ProjectService.create(projectId);
collection.records = this.createRecords(swaggerData, collection.id, sort);
await CollectionService.save(collection);
await Promise.all(collection.records.map(r => RecordService.saveRecordHistory(RecordService.createRecordHistory(r, user))));
await EnvironmentService.save(env);
}
private createEnv(projectId: string, host: string): Environment {
const env = new Environment();
env.name = 'swagger env';
env.id = StringUtil.generateUID();
env.variables = [];
env.project = ProjectService.create(projectId);
const variable = VariableService.fromDto({
id: StringUtil.generateUID(),
key: 'host',
value: host,
isActive: true,
sort: 0
});
variable.environment = env;
env.variables.push(variable);
return env;
}
private createRecords(swaggerData: any, collectionId: string, sort: number): Record[] {
const folders: _.Dictionary<Record> = {};
const records: Record[] = [];
_.keys(swaggerData.paths).forEach(path => {
let pathName = path.substr(1);
if (pathName.includes('/')) {
pathName = pathName.substr(0, pathName.indexOf('/'));
}
if (!folders[pathName]) {
folders[pathName] = this.createFolder(pathName, collectionId, ++sort);
records.push(folders[pathName]);
}
const folderRecords = this.createRecordsForFolder(path, swaggerData.paths[path], swaggerData.schemes, folders[pathName].id, collectionId, sort);
sort += folderRecords.length + 1;
records.push(...folderRecords);
});
return records;
}
private createFolder(name: string, collectionId: string, sort: number): Record {
return RecordService.fromDto({
id: StringUtil.generateUID(),
name,
collectionId,
category: RecordCategory.folder,
parameterType: ParameterType.ManyToMany,
sort
});
}
private createRecordsForFolder(path: string, methodDatas: any, schemes: any, folderId: string, collectionId: string, sort: number): Record[] {
return _.keys(methodDatas).map(method => {
const methodData = methodDatas[method];
const formData = this.parseFormData(methodData);
return RecordService.fromDto({
id: StringUtil.generateUID(),
name: methodData.summary || methodData.operationId || '',
collectionId,
pid: folderId,
category: RecordCategory.record,
parameterType: ParameterType.ManyToMany,
url: this.parseUrl(path, methodData, schemes),
method: method.toUpperCase(),
headers: this.parseHeaders(methodData),
formDatas: formData,
dataMode: formData.length > 0 ? DataMode.urlencoded : DataMode.raw,
sort: ++sort
});
});
}
private parseUrl(path: string, methodData: any, schemes: any): string {
path = path.replace('{', ':').replace('}', '');
let url = `${(schemes || []).length > 0 ? schemes[0] : 'http'}://${this.baseUrl}${path}`;
if (methodData.parameters) {
methodData.parameters.filter(p => p.in === 'query').forEach(p => {
url = `${url}${url.includes('?') ? '&' : '?'}${p.name}={{${p.name}}}`;
});
}
return url;
}
private parseFormData(methodData: any): DtoBodyFormData[] {
let formDatas: DtoBodyFormData[] = [];
if (methodData.parameters) {
methodData.parameters.filter(p => p.in === 'formData').forEach((p, i) => {
formDatas.push({ id: undefined, key: p.name, value: `{{${p.name}}`, description: p.description, isActive: true, sort: i });
});
}
return formDatas;
}
private parseHeaders(methodData: any): Header[] {
const headers: DtoHeader[] = [];
let sort = 0;
if (methodData.consumes) {
headers.push({ key: 'Content-Type', value: methodData.consumes[0], isActive: true, sort: ++sort });
}
if (methodData.produces) {
headers.push({ key: 'Accept', value: methodData.produces.join(', '), isActive: true, sort: ++sort });
}
if (methodData.parameters) {
methodData.parameters.filter(p => p.in === 'header').forEach((h, i) => {
headers.push({ key: h.name, value: `{{${h.name}}}`, description: h.description, isActive: true, sort: i + sort + 1 });
});
}
return headers.map(h => HeaderService.fromDto(h));
}
}
``` | /content/code_sandbox/api/src/services/importer/swagger_import.ts | xml | 2016-09-26T02:47:43 | 2024-07-24T09:32:20 | Hitchhiker | brookshi/Hitchhiker | 2,193 | 1,385 |
```xml
import { Box, IntegrationItem, Ribbon, Type } from "./styles";
import { INTEGRATION_KINDS } from "@erxes/ui/src/constants/integrations";
import Icon from "@erxes/ui/src/components/Icon";
import IntegrationForm from "../../containers/common/IntegrationForm";
import LineForm from "../../containers/line/Form";
import { Link } from "react-router-dom";
import ModalTrigger from "@erxes/ui/src/components/ModalTrigger";
import NylasForm from "../../containers/mail/Form";
import React from "react";
import TelnyxForm from "../../containers/telnyx/TelnyxForm";
import Twitter from "../../containers/twitter/Twitter";
import { __ } from "coreui/utils";
import { formatText } from "@erxes/ui-log/src/activityLogs/utils";
type TotalCount = {
messenger: number;
form: number;
facebook: number;
instagram: number;
callpro: number;
chatfuel: number;
gmail: number;
imap: number;
office365: number;
outlook: number;
yahoo: number;
line: number;
telegram: number;
viber: number;
twilio: number;
whatsapp: number;
exchange: number;
telnyx: number;
};
type Props = {
integration: any;
getClassName: (selectedKind: string) => string;
toggleBox: (kind: string) => void;
customLink?: (kind: string, addLink: string) => void;
queryParams: any;
totalCount: TotalCount;
};
function getCount(kind: string, totalCount: TotalCount) {
const countByKind = totalCount[kind];
if (typeof countByKind === "undefined") {
return null;
}
return <span>({countByKind})</span>;
}
function renderType(type: string) {
if (!type) {
return null;
}
return (
<Type>
<Icon icon="comment-alt-lines" /> {__("Works with messenger")}
</Type>
);
}
function renderCreate(createUrl, kind, isAvailable) {
if ((!createUrl && !kind) || !isAvailable) {
return null;
}
const trigger = <button>+ {__("Add")}</button>;
if (kind === INTEGRATION_KINDS.FACEBOOK_MESSENGER) {
return (
<Link to={`${createUrl}?kind=${INTEGRATION_KINDS.FACEBOOK_MESSENGER}`}>
+ {__("Add")}
</Link>
);
}
if (kind === INTEGRATION_KINDS.INSTAGRAM_MESSENGER) {
return (
<Link to={`${createUrl}?kind=${INTEGRATION_KINDS.INSTAGRAM_MESSENGER}`}>
+ {__("Add")}
</Link>
);
}
if (kind === INTEGRATION_KINDS.FACEBOOK_POST) {
return (
<Link to={`${createUrl}?kind=${INTEGRATION_KINDS.FACEBOOK_POST}`}>
+ {__("Add")}
</Link>
);
}
if (kind === INTEGRATION_KINDS.INSTAGRAM_MESSENGER) {
return (
<Link to={`${createUrl}?kind=${INTEGRATION_KINDS.INSTAGRAM_MESSENGER}`}>
+ {__("Add")}
</Link>
);
}
if (kind === INTEGRATION_KINDS.MESSENGER) {
return <Link to={createUrl}>+ {__("Add")}</Link>;
}
if (
kind === INTEGRATION_KINDS.NYLAS_OFFICE365 ||
kind === INTEGRATION_KINDS.NYLAS_GMAIL
) {
const content = (props) => <NylasForm kind={kind} {...props} />;
return (
<ModalTrigger
title={`Add ${formatText(kind)}`}
content={content}
autoOpenKey={`show${formatText(kind, true)}Modal`}
/>
);
}
if (
kind === INTEGRATION_KINDS.NYLAS_IMAP ||
kind === INTEGRATION_KINDS.NYLAS_EXCHANGE ||
kind === INTEGRATION_KINDS.NYLAS_OUTLOOK ||
kind === INTEGRATION_KINDS.NYLAS_YAHOO
) {
const content = (props) => <NylasForm kind={kind} {...props} />;
return (
<ModalTrigger
title={`Add ${formatText(kind)}`}
trigger={trigger}
content={content}
autoOpenKey={`show${formatText(kind)}Modal`}
/>
);
}
if (kind === INTEGRATION_KINDS.GMAIL) {
return <Link to={createUrl}>+ {__("Add")}</Link>;
}
if (kind === "twitter") {
const content = (props) => <Twitter {...props} />;
return (
<ModalTrigger title="Add twitter" trigger={trigger} content={content} />
);
}
if (kind === INTEGRATION_KINDS.SMOOCH_LINE) {
const content = (props) => <LineForm {...props} />;
return (
<ModalTrigger title="Add Line" trigger={trigger} content={content} />
);
}
if (kind === INTEGRATION_KINDS.TELNYX) {
const content = (props) => <TelnyxForm {...props} />;
return (
<ModalTrigger title="Add telnyx" trigger={trigger} content={content} />
);
}
const formContent = (props) => <IntegrationForm {...props} type={kind} />;
return (
<ModalTrigger
title={`Add ${formatText(kind)}`}
trigger={trigger}
content={formContent}
/>
);
}
function Entry({
integration,
getClassName,
toggleBox,
totalCount,
customLink,
}: Props) {
const { kind, isAvailable, createUrl } = integration;
const handleLink = () => {
return customLink && customLink(kind, createUrl);
};
function renderCustomLink(isAvailable) {
if (
![
INTEGRATION_KINDS.NYLAS_GMAIL,
INTEGRATION_KINDS.NYLAS_OFFICE365,
].includes(kind) ||
!isAvailable
) {
return null;
}
return <button onClick={handleLink}>+{__("Add")}</button>;
}
return (
<IntegrationItem key={integration.name} className={getClassName(kind)}>
<Box
onClick={() => toggleBox(kind)}
$isInMessenger={integration.inMessenger}
>
<img alt="logo" src={integration.logo} />
<h5>
{integration.name} {getCount(kind, totalCount)}
</h5>
<p>
{__(integration.description)}
{renderType(integration.inMessenger)}
</p>
{!isAvailable && (
<Ribbon>
<span>{__("Coming soon")}</span>
</Ribbon>
)}
</Box>
{renderCustomLink(isAvailable)}
{renderCreate(createUrl, kind, isAvailable)}
</IntegrationItem>
);
}
export default Entry;
``` | /content/code_sandbox/packages/ui-inbox/src/settings/integrations/components/store/Entry.tsx | xml | 2016-11-11T06:54:50 | 2024-08-16T10:26:06 | erxes | erxes/erxes | 3,479 | 1,541 |
```xml
export * from './dateGrid.types';
export * from './findAvailableDate';
export * from './getBoundedDateRange';
export * from './getDayGrid';
export * from './isRestrictedDate';
``` | /content/code_sandbox/packages/react-components/react-calendar-compat/library/src/utils/dateGrid/index.ts | xml | 2016-06-06T15:03:44 | 2024-08-16T18:49:29 | fluentui | microsoft/fluentui | 18,221 | 43 |
```xml
import { useState, useCallback, useEffect } from 'react'
import { createStoreContext } from '../../utils/context'
import { usePage } from '../pageStore'
import { localLiteStorage } from 'ltstrg'
import { teamPreferenceskey } from '../../localStorageKeys'
import {
TeamPreferencesContext,
LocallyStoredTeamPreferences,
TeamPreferencesContent,
TeamPreferencesType,
} from './types'
function useTeamPreferencesStore(): TeamPreferencesContext {
const { team } = usePage()
const [currentTeamPreferences, setCurrentTeamPreferences] =
useState<TeamPreferencesContent>({})
const setToLocalStorage = useCallback(
(teamId: string, content: TeamPreferencesContent) => {
let baseData = localLiteStorage.getItem(teamPreferenceskey)
if (baseData == null) {
baseData = '{}'
}
const data = JSON.parse(baseData)
data[teamId] = content
localLiteStorage.setItem(teamPreferenceskey, JSON.stringify(data))
},
[]
)
const toggleItem = useCallback((type: TeamPreferencesType) => {
setCurrentTeamPreferences((prev) => {
const newState = Object.assign({}, prev)
if (newState[type] != null) {
delete newState[type]
} else {
newState[type] = true
}
return newState
})
}, [])
// LOAD FROM LOCAL STORAGE
useEffect(() => {
if (team == null) {
return
}
try {
const stringifiedData = localLiteStorage.getItem(teamPreferenceskey)
if (stringifiedData == null) {
return
}
const locallyStoredDatas = JSON.parse(
stringifiedData
) as LocallyStoredTeamPreferences
setCurrentTeamPreferences(locallyStoredDatas[team.id] || {})
} catch (error) {
// eslint-disable-next-line no-console
console.warn(error.message)
}
}, [team])
// SAVE CHANGES TO LOCALSTORAGE
useEffect(() => {
if (team == null) {
return
}
let baseData = localLiteStorage.getItem(teamPreferenceskey)
if (baseData == null) {
baseData = '{}'
}
const data = JSON.parse(baseData)
data[team!.id] = currentTeamPreferences
localLiteStorage.setItem(teamPreferenceskey, JSON.stringify(data))
}, [currentTeamPreferences, team])
return {
teamPreferences: currentTeamPreferences,
setToLocalStorage,
toggleItem,
}
}
export const {
StoreProvider: TeamPreferencesProvider,
useStore: useTeamPreferences,
} = createStoreContext(useTeamPreferencesStore, 'teamPreferences')
``` | /content/code_sandbox/src/cloud/lib/stores/teamPreferences/store.tsx | xml | 2016-11-19T14:30:34 | 2024-08-16T03:13:45 | BoostNote-App | BoostIO/BoostNote-App | 3,745 | 565 |
```xml
import React from 'react';
type IconProps = React.SVGProps<SVGSVGElement>;
export declare const IcPassVault: (props: IconProps) => React.JSX.Element;
export {};
``` | /content/code_sandbox/packages/icons/lib/icPassVault.d.ts | xml | 2016-06-08T11:16:51 | 2024-08-16T14:14:27 | WebClients | ProtonMail/WebClients | 4,300 | 43 |
```xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="path_to_url"
xmlns:xsi="path_to_url"
xsi:schemaLocation="path_to_url path_to_url">
<bean id="processEngineConfiguration" class="org.flowable.engine.impl.cfg.StandaloneInMemProcessEngineConfiguration">
<!-- Database configurations -->
<property name="history" value="full" />
<property name="databaseSchemaUpdate" value="true" />
<property name="flowable5CompatibilityEnabled" value="true" />
<property name="jpaPersistenceUnitName" value="flowable5-jpa-pu" />
<property name="jpaHandleTransaction" value="true" />
<property name="jpaCloseEntityManager" value="true" />
<!-- job executor configurations -->
<property name="asyncExecutorActivate" value="false" />
</bean>
</beans>
``` | /content/code_sandbox/modules/flowable5-test/src/test/resources/org/activiti/standalone/history/fullhistory.flowable.cfg.xml | xml | 2016-10-13T07:21:43 | 2024-08-16T15:23:14 | flowable-engine | flowable/flowable-engine | 7,715 | 204 |
```xml
<!--
***********************************************************************************************
Xamarin.Android.AvailableItems.targets
This file is imported by every project type to setup @(AvailableItemName).
This item group populates the Build Action drop-down in IDEs.
***********************************************************************************************
-->
<Project>
<!-- Not legacy binding projects -->
<ItemGroup Condition=" '$(_AndroidIsBindingProject)' != 'true' ">
<AvailableItemName Include="AndroidAotProfile" />
<AvailableItemName Include="AndroidAsset" />
<AvailableItemName Include="AndroidEnvironment" />
<AvailableItemName Include="AndroidExternalJavaLibrary" />
<AvailableItemName Include="AndroidInterfaceDescription" />
<AvailableItemName Include="AndroidJavaSource" />
<AvailableItemName Include="AndroidLibrary" />
<AvailableItemName Include="AndroidLintConfig" />
<AvailableItemName Include="AndroidResourceAnalysisConfig" />
<AvailableItemName Include="AndroidNativeLibrary" />
<AvailableItemName Include="AndroidResource" />
<AvailableItemName Include="AndroidBoundLayout" />
<AvailableItemName Include="LinkDescription" />
<AvailableItemName Include="MultiDexMainDexList" />
<AvailableItemName Include="ProguardConfiguration" />
<AvailableItemName Include="ProjectReference" />
<AvailableItemName Include="AndroidManifestOverlay" />
</ItemGroup>
<!-- All project types -->
<ItemGroup>
<AvailableItemName Include="TransformFile" />
<AvailableItemName Include="LibraryProjectProperties" />
<AvailableItemName Include="JavaDocIndex" />
<AvailableItemName Include="JavaDocJar" />
<AvailableItemName Include="JavaSourceJar" />
</ItemGroup>
<!-- Default item metadata -->
<ItemDefinitionGroup>
<AndroidResource>
<SubType>Designer</SubType>
<Generator>MSBuild:UpdateGeneratedFiles</Generator>
</AndroidResource>
<AndroidLibrary>
<Bind>true</Bind>
<Pack>true</Pack>
</AndroidLibrary>
<LibraryProjectZip>
<Pack>true</Pack>
</LibraryProjectZip>
<AndroidJavaSource>
<Bind>true</Bind>
</AndroidJavaSource>
<AndroidAarLibrary>
<!-- NOTE: .aar items should skip %(AndroidSkipResourceProcessing) by default -->
<AndroidSkipResourceProcessing>true</AndroidSkipResourceProcessing>
</AndroidAarLibrary>
</ItemDefinitionGroup>
<!-- Convert @(AndroidLibrary) to the legacy item group names -->
<Target Name="_CategorizeAndroidLibraries">
<!-- Applications -->
<ItemGroup Condition=" '$(AndroidApplication)' == 'true' ">
<AndroidAarLibrary Include="@(AndroidLibrary)" Condition=" '%(AndroidLibrary.Extension)' == '.aar' " />
<AndroidJavaLibrary Include="@(AndroidLibrary)" Condition=" '%(AndroidLibrary.Extension)' == '.jar' " />
<InputJar Include="@(AndroidLibrary)" Condition=" '%(AndroidLibrary.Extension)' == '.jar' and '%(AndroidLibrary.Bind)' == 'true' " />
</ItemGroup>
<!-- Class libraries, not an application -->
<ItemGroup Condition=" '$(AndroidApplication)' != 'true' ">
<EmbeddedNativeLibrary Include="@(AndroidNativeLibrary)" />
<AndroidAarLibrary Include="@(AndroidLibrary)" Condition=" '%(AndroidLibrary.Extension)' == '.aar' and '%(AndroidLibrary.Bind)' != 'true' " />
<AndroidJavaLibrary Include="@(AndroidLibrary)" Condition=" '%(AndroidLibrary.Extension)' == '.jar' and '%(AndroidLibrary.Bind)' != 'true' " />
<EmbeddedJar Include="@(AndroidLibrary)" Condition=" '%(AndroidLibrary.Extension)' == '.jar' and '%(AndroidLibrary.Bind)' == 'true' " />
<!-- .aar files should be copied to $(OutputPath) in .NET 6+ -->
<None Include="@(AndroidLibrary)" Condition=" '%(AndroidLibrary.Extension)' == '.aar' " TfmSpecificPackageFile="%(AndroidLibrary.Pack)" Pack="false" CopyToOutputDirectory="PreserveNewest" Link="%(Filename)%(Extension)" />
<!-- @(LibraryProjectZip) items that are not in @(AndroidLibrary) -->
<None Include="@(LibraryProjectZip)" Exclude="@(AndroidLibrary)" TfmSpecificPackageFile="%(LibraryProjectZip.Pack)" Pack="false" CopyToOutputDirectory="PreserveNewest" Link="%(Filename)%(Extension)" />
</ItemGroup>
<!-- All projects -->
<ItemGroup>
<LibraryProjectZip Include="@(AndroidLibrary)" Condition=" '%(AndroidLibrary.Extension)' == '.aar' and '%(AndroidLibrary.Bind)' == 'true' " />
</ItemGroup>
</Target>
</Project>
``` | /content/code_sandbox/src/Xamarin.Android.Build.Tasks/MSBuild/Xamarin/Android/Xamarin.Android.AvailableItems.targets | xml | 2016-03-30T15:37:14 | 2024-08-16T19:22:13 | android | dotnet/android | 1,905 | 1,012 |
```xml
/* eslint-env jest */
import cheerio from 'cheerio'
import validateHTML from 'html-validator'
import {
assertHasRedbox,
assertNoRedbox,
check,
fetchViaHTTP,
findPort,
getRedboxHeader,
killApp,
launchApp,
nextBuild,
nextStart,
renderViaHTTP,
waitFor,
} from 'next-test-utils'
import webdriver from 'next-webdriver'
import { join } from 'path'
import { existsSync } from 'fs'
const appDir = join(__dirname, '../')
let appPort
let app
async function hasImageMatchingUrl(browser, url) {
const links = await browser.elementsByCss('img')
let foundMatch = false
for (const link of links) {
const src = await link.getAttribute('src')
if (new URL(src, `path_to_url{appPort}`).toString() === url) {
foundMatch = true
break
}
}
return foundMatch
}
async function getComputed(browser, id, prop) {
const val = await browser.eval(`document.getElementById('${id}').${prop}`)
if (typeof val === 'number') {
return val
}
if (typeof val === 'string') {
const v = parseInt(val, 10)
if (isNaN(v)) {
return val
}
return v
}
return null
}
async function getComputedStyle(browser, id, prop) {
return browser.eval(
`window.getComputedStyle(document.getElementById('${id}')).getPropertyValue('${prop}')`
)
}
async function getSrc(browser, id) {
const src = await browser.elementById(id).getAttribute('src')
if (src) {
const url = new URL(src, `path_to_url{appPort}`)
return url.href.slice(url.origin.length)
}
}
function getRatio(width, height) {
return height / width
}
function runTests(mode) {
it('should load the images', async () => {
let browser
try {
browser = await webdriver(appPort, '/')
await check(async () => {
const result = await browser.eval(
`document.getElementById('basic-image').naturalWidth`
)
if (result === 0) {
throw new Error('Incorrectly loaded image')
}
return 'result-correct'
}, /result-correct/)
expect(
await hasImageMatchingUrl(
browser,
`path_to_url{appPort}/_next/image?url=%2Ftest.jpg&w=828&q=75`
)
).toBe(true)
} finally {
if (browser) {
await browser.close()
}
}
})
it('should preload priority images', async () => {
let browser
try {
browser = await webdriver(appPort, '/priority')
await check(async () => {
const result = await browser.eval(
`document.getElementById('basic-image').naturalWidth`
)
if (result === 0) {
throw new Error('Incorrectly loaded image')
}
return 'result-correct'
}, /result-correct/)
const links = await browser.elementsByCss('link[rel=preload][as=image]')
const entries = []
for (const link of links) {
const imagesrcset = await link.getAttribute('imagesrcset')
const imagesizes = await link.getAttribute('imagesizes')
entries.push({ imagesrcset, imagesizes })
}
expect(entries).toEqual([
{
imagesizes: '',
imagesrcset:
'/_next/image?url=%2Ftest.jpg&w=640&q=75 1x, /_next/image?url=%2Ftest.jpg&w=828&q=75 2x',
},
{
imagesizes: '',
imagesrcset:
'/_next/image?url=%2Ftest.gif&w=640&q=75 1x, /_next/image?url=%2Ftest.gif&w=828&q=75 2x',
},
{
imagesizes: '',
imagesrcset:
'/_next/image?url=%2Ftest.png&w=640&q=75 1x, /_next/image?url=%2Ftest.png&w=828&q=75 2x',
},
{
imagesizes: '100vw',
imagesrcset:
'/_next/image?url=%2Fwide.png&w=640&q=75 640w, /_next/image?url=%2Fwide.png&w=750&q=75 750w, /_next/image?url=%2Fwide.png&w=828&q=75 828w, /_next/image?url=%2Fwide.png&w=1080&q=75 1080w, /_next/image?url=%2Fwide.png&w=1200&q=75 1200w, /_next/image?url=%2Fwide.png&w=1920&q=75 1920w, /_next/image?url=%2Fwide.png&w=2048&q=75 2048w, /_next/image?url=%2Fwide.png&w=3840&q=75 3840w',
},
{
imagesizes: '',
imagesrcset:
'/_next/image?url=%2Ftest.tiff&w=640&q=75 1x, /_next/image?url=%2Ftest.tiff&w=828&q=75 2x',
},
])
// When priority={true}, we should _not_ set loading="lazy"
expect(
await browser.elementById('basic-image').getAttribute('loading')
).toBe(null)
expect(
await browser
.elementById('basic-image-with-crossorigin')
.getAttribute('loading')
).toBe(null)
expect(
await browser
.elementById('basic-image-with-referrerpolicy')
.getAttribute('loading')
).toBe(null)
expect(
await browser.elementById('load-eager').getAttribute('loading')
).toBe(null)
expect(
await browser.elementById('responsive1').getAttribute('loading')
).toBe(null)
expect(
await browser.elementById('responsive2').getAttribute('loading')
).toBe(null)
expect(
await browser.elementById('belowthefold').getAttribute('loading')
).toBe(null)
const warnings = (await browser.log())
.map((log) => log.message)
.join('\n')
expect(warnings).not.toMatch(
/was detected as the Largest Contentful Paint/gm
)
// should preload with crossorigin
expect(
await browser.elementsByCss(
'link[rel=preload][as=image][crossorigin=use-credentials][imagesrcset*="test.gif"]'
)
).toHaveLength(1)
// should preload with referrerpolicy
expect(
await browser.elementsByCss(
'link[rel=preload][as=image][referrerpolicy="no-referrer"][imagesrcset*="test.png"]'
)
).toHaveLength(1)
} finally {
if (browser) {
await browser.close()
}
}
})
it('should not pass through user-provided srcset (causing a flash)', async () => {
const html = await renderViaHTTP(appPort, '/drop-srcset')
const $html = cheerio.load(html)
const els = [].slice.apply($html('img'))
expect(els.length).toBe(2)
const [el, noscriptEl] = els
expect(noscriptEl.attribs.src).toBeDefined()
expect(noscriptEl.attribs.srcset).toBeDefined()
expect(el.attribs.src).toBeDefined()
expect(el.attribs.srcset).toBeUndefined()
expect(el.attribs.srcSet).toBeUndefined()
})
it('should update the image on src change', async () => {
let browser
try {
browser = await webdriver(appPort, '/update')
await check(
() => browser.eval(`document.getElementById("update-image").src`),
/test\.jpg/
)
await browser.eval(`document.getElementById("toggle").click()`)
await check(
() => browser.eval(`document.getElementById("update-image").src`),
/test\.png/
)
} finally {
if (browser) {
await browser.close()
}
}
})
it('should callback onLoadingComplete when image is fully loaded', async () => {
let browser
try {
browser = await webdriver(appPort, '/on-loading-complete')
await browser.eval(
`document.getElementById("footer").scrollIntoView({behavior: "smooth"})`
)
await check(
() => browser.eval(`document.getElementById("img1").currentSrc`),
/test(.*)jpg/
)
await check(
() => browser.eval(`document.getElementById("img2").currentSrc`),
/test(.*).png/
)
await check(
() => browser.eval(`document.getElementById("img3").currentSrc`),
/test\.svg/
)
await check(
() => browser.eval(`document.getElementById("img4").currentSrc`),
/test(.*)ico/
)
await check(
() => browser.eval(`document.getElementById("msg1").textContent`),
'loaded 1 img1 with dimensions 128x128'
)
await check(
() => browser.eval(`document.getElementById("msg2").textContent`),
'loaded 1 img2 with dimensions 400x400'
)
await check(
() => browser.eval(`document.getElementById("msg3").textContent`),
'loaded 1 img3 with dimensions 266x266'
)
await check(
() => browser.eval(`document.getElementById("msg4").textContent`),
'loaded 1 img4 with dimensions 21x21'
)
await check(
() => browser.eval(`document.getElementById("msg5").textContent`),
'loaded 1 img5 with dimensions 3x5'
)
await check(
() => browser.eval(`document.getElementById("msg6").textContent`),
'loaded 1 img6 with dimensions 3x5'
)
await check(
() => browser.eval(`document.getElementById("msg7").textContent`),
'loaded 1 img7 with dimensions 400x400'
)
await check(
() => browser.eval(`document.getElementById("msg8").textContent`),
'loaded 1 img8 with dimensions 640x373'
)
await check(
() =>
browser.eval(
`document.getElementById("img8").getAttribute("data-nimg")`
),
'intrinsic'
)
await check(
() => browser.eval(`document.getElementById("img8").currentSrc`),
/wide.png/
)
await browser.eval('document.getElementById("toggle").click()')
await check(
() => browser.eval(`document.getElementById("msg8").textContent`),
'loaded 2 img8 with dimensions 400x300'
)
await check(
() =>
browser.eval(
`document.getElementById("img8").getAttribute("data-nimg")`
),
'fixed'
)
await check(
() => browser.eval(`document.getElementById("img8").currentSrc`),
/test-rect.jpg/
)
} finally {
if (browser) {
await browser.close()
}
}
})
it('should callback native onLoad in most cases', async () => {
let browser = await webdriver(appPort, '/on-load')
await browser.eval(
`document.getElementById("footer").scrollIntoView({behavior: "smooth"})`
)
await check(
() => browser.eval(`document.getElementById("img1").currentSrc`),
/test(.*)jpg/
)
await check(
() => browser.eval(`document.getElementById("img2").currentSrc`),
/test(.*).png/
)
await check(
() => browser.eval(`document.getElementById("img3").currentSrc`),
/test\.svg/
)
await check(
() => browser.eval(`document.getElementById("img4").currentSrc`),
/test(.*)ico/
)
await check(
() => browser.eval(`document.getElementById("msg1").textContent`),
'loaded 1 img1 with native onLoad'
)
await check(
() => browser.eval(`document.getElementById("msg2").textContent`),
'loaded 1 img2 with native onLoad'
)
await check(
() => browser.eval(`document.getElementById("msg3").textContent`),
'loaded 1 img3 with native onLoad'
)
await check(
() => browser.eval(`document.getElementById("msg4").textContent`),
'loaded 1 img4 with native onLoad'
)
await check(
() => browser.eval(`document.getElementById("msg8").textContent`),
'loaded 1 img8 with native onLoad'
)
await check(
() =>
browser.eval(
`document.getElementById("img8").getAttribute("data-nimg")`
),
'intrinsic'
)
await check(
() => browser.eval(`document.getElementById("img8").currentSrc`),
/wide.png/
)
await browser.eval('document.getElementById("toggle").click()')
// The normal `onLoad()` is triggered by lazy placeholder image
// so ideally this would be "2" instead of "3" count
await check(
() => browser.eval(`document.getElementById("msg8").textContent`),
'loaded 3 img8 with native onLoad'
)
await check(
() =>
browser.eval(
`document.getElementById("img8").getAttribute("data-nimg")`
),
'fixed'
)
await check(
() => browser.eval(`document.getElementById("img8").currentSrc`),
/test-rect.jpg/
)
})
it('should callback native onError when error occurred while loading image', async () => {
let browser = await webdriver(appPort, '/on-error')
await check(
() => browser.eval(`document.getElementById("img1").currentSrc`),
/test\.png/
)
await check(
() => browser.eval(`document.getElementById("img2").currentSrc`),
//This is an empty data url
/nonexistent-img\.png/
)
await check(
() => browser.eval(`document.getElementById("msg1").textContent`),
'no error occurred'
)
await check(
() => browser.eval(`document.getElementById("msg2").textContent`),
'error occurred while loading img2'
)
})
it('should work with image with blob src', async () => {
let browser
try {
browser = await webdriver(appPort, '/blob')
await check(
() => browser.eval(`document.getElementById("blob-image").src`),
/^blob:/
)
await check(
() => browser.eval(`document.getElementById("blob-image").srcset`),
''
)
} finally {
if (browser) {
await browser.close()
}
}
})
it('should work when using flexbox', async () => {
let browser
try {
browser = await webdriver(appPort, '/flex')
await check(async () => {
const result = await browser.eval(
`document.getElementById('basic-image').width`
)
if (result === 0) {
throw new Error('Incorrectly loaded image')
}
return 'result-correct'
}, /result-correct/)
} finally {
if (browser) {
await browser.close()
}
}
})
it('should work with layout-fixed so resizing window does not resize image', async () => {
let browser
try {
browser = await webdriver(appPort, '/layout-fixed')
const width = 1200
const height = 700
const delta = 250
const id = 'fixed1'
await check(async () => {
expect(await getSrc(browser, id)).toBe(
'/_next/image?url=%2Fwide.png&w=3840&q=75'
)
return 'success'
}, 'success')
expect(await browser.elementById(id).getAttribute('srcset')).toBe(
'/_next/image?url=%2Fwide.png&w=1200&q=75 1x, /_next/image?url=%2Fwide.png&w=3840&q=75 2x'
)
expect(await browser.elementById(id).getAttribute('sizes')).toBeFalsy()
await browser.setDimensions({
width: width + delta,
height: height + delta,
})
expect(await getComputed(browser, id, 'width')).toBe(width)
expect(await getComputed(browser, id, 'height')).toBe(height)
await browser.setDimensions({
width: width - delta,
height: height - delta,
})
expect(await getComputed(browser, id, 'width')).toBe(width)
expect(await getComputed(browser, id, 'height')).toBe(height)
} finally {
if (browser) {
await browser.close()
}
}
})
it('should work with layout-intrinsic so resizing window maintains image aspect ratio', async () => {
let browser
try {
browser = await webdriver(appPort, '/layout-intrinsic')
const width = 1200
const height = 700
const delta = 250
const id = 'intrinsic1'
await check(async () => {
expect(await getSrc(browser, id)).toBe(
'/_next/image?url=%2Fwide.png&w=3840&q=75'
)
return 'success'
}, 'success')
expect(await browser.elementById(id).getAttribute('srcset')).toBe(
'/_next/image?url=%2Fwide.png&w=1200&q=75 1x, /_next/image?url=%2Fwide.png&w=3840&q=75 2x'
)
expect(await browser.elementById(id).getAttribute('sizes')).toBeFalsy()
await browser.setDimensions({
width: width + delta,
height: height + delta,
})
expect(await getComputed(browser, id, 'width')).toBe(width)
expect(await getComputed(browser, id, 'height')).toBe(height)
await browser.setDimensions({
width: width - delta,
height: height - delta,
})
const newWidth = await getComputed(browser, id, 'width')
const newHeight = await getComputed(browser, id, 'height')
expect(newWidth).toBeLessThan(width)
expect(newHeight).toBeLessThan(height)
expect(getRatio(newWidth, newHeight)).toBeCloseTo(
getRatio(width, height),
1
)
} finally {
if (browser) {
await browser.close()
}
}
})
it('should work with layout-responsive so resizing window maintains image aspect ratio', async () => {
let browser
try {
browser = await webdriver(appPort, '/layout-responsive')
const width = 1200
const height = 700
const delta = 250
const id = 'responsive1'
await check(async () => {
expect(await getSrc(browser, id)).toBe(
'/_next/image?url=%2Fwide.png&w=3840&q=75'
)
return 'success'
}, 'success')
expect(await browser.elementById(id).getAttribute('srcset')).toBe(
'/_next/image?url=%2Fwide.png&w=640&q=75 640w, /_next/image?url=%2Fwide.png&w=750&q=75 750w, /_next/image?url=%2Fwide.png&w=828&q=75 828w, /_next/image?url=%2Fwide.png&w=1080&q=75 1080w, /_next/image?url=%2Fwide.png&w=1200&q=75 1200w, /_next/image?url=%2Fwide.png&w=1920&q=75 1920w, /_next/image?url=%2Fwide.png&w=2048&q=75 2048w, /_next/image?url=%2Fwide.png&w=3840&q=75 3840w'
)
expect(await browser.elementById(id).getAttribute('sizes')).toBe('100vw')
await browser.setDimensions({
width: width + delta,
height: height + delta,
})
expect(await getComputed(browser, id, 'width')).toBeGreaterThan(width)
expect(await getComputed(browser, id, 'height')).toBeGreaterThan(height)
await browser.setDimensions({
width: width - delta,
height: height - delta,
})
const newWidth = await getComputed(browser, id, 'width')
const newHeight = await getComputed(browser, id, 'height')
expect(newWidth).toBeLessThan(width)
expect(newHeight).toBeLessThan(height)
expect(getRatio(newWidth, newHeight)).toBeCloseTo(
getRatio(width, height),
1
)
} finally {
if (browser) {
await browser.close()
}
}
})
it('should work with layout-fill to fill the parent but NOT stretch with viewport', async () => {
let browser
try {
browser = await webdriver(appPort, '/layout-fill')
const width = 600
const height = 350
const delta = 150
const id = 'fill1'
await check(async () => {
expect(await getSrc(browser, id)).toBe(
'/_next/image?url=%2Fwide.png&w=3840&q=75'
)
return 'success'
}, 'success')
expect(await browser.elementById(id).getAttribute('srcset')).toBe(
'/_next/image?url=%2Fwide.png&w=640&q=75 640w, /_next/image?url=%2Fwide.png&w=750&q=75 750w, /_next/image?url=%2Fwide.png&w=828&q=75 828w, /_next/image?url=%2Fwide.png&w=1080&q=75 1080w, /_next/image?url=%2Fwide.png&w=1200&q=75 1200w, /_next/image?url=%2Fwide.png&w=1920&q=75 1920w, /_next/image?url=%2Fwide.png&w=2048&q=75 2048w, /_next/image?url=%2Fwide.png&w=3840&q=75 3840w'
)
expect(await browser.elementById(id).getAttribute('sizes')).toBe('100vw')
await browser.setDimensions({
width: width + delta,
height: height + delta,
})
expect(await getComputed(browser, id, 'width')).toBe(width)
expect(await getComputed(browser, id, 'height')).toBe(height)
await browser.setDimensions({
width: width - delta,
height: height - delta,
})
const newWidth = await getComputed(browser, id, 'width')
const newHeight = await getComputed(browser, id, 'height')
expect(newWidth).toBe(width)
expect(newHeight).toBe(height)
expect(getRatio(newWidth, newHeight)).toBeCloseTo(
getRatio(width, height),
1
)
} finally {
if (browser) {
await browser.close()
}
}
})
it('should work with layout-fill to fill the parent and stretch with viewport', async () => {
let browser
try {
browser = await webdriver(appPort, '/layout-fill')
const id = 'fill2'
const width = await getComputed(browser, id, 'width')
const height = await getComputed(browser, id, 'height')
await browser.eval(`document.getElementById("${id}").scrollIntoView()`)
await check(async () => {
expect(await getSrc(browser, id)).toBe(
'/_next/image?url=%2Fwide.png&w=3840&q=75'
)
return 'success'
}, 'success')
await check(() => {
return browser.eval(
`document.querySelector('#${id}').getAttribute('srcset')`
)
}, '/_next/image?url=%2Fwide.png&w=640&q=75 640w, /_next/image?url=%2Fwide.png&w=750&q=75 750w, /_next/image?url=%2Fwide.png&w=828&q=75 828w, /_next/image?url=%2Fwide.png&w=1080&q=75 1080w, /_next/image?url=%2Fwide.png&w=1200&q=75 1200w, /_next/image?url=%2Fwide.png&w=1920&q=75 1920w, /_next/image?url=%2Fwide.png&w=2048&q=75 2048w, /_next/image?url=%2Fwide.png&w=3840&q=75 3840w')
expect(await browser.elementById(id).getAttribute('sizes')).toBe('100vw')
expect(await getComputed(browser, id, 'width')).toBe(width)
expect(await getComputed(browser, id, 'height')).toBe(height)
const delta = 150
const largeWidth = Number(width) + delta
const largeHeight = Number(height) + delta
await browser.setDimensions({
width: largeWidth,
height: largeHeight,
})
expect(await getComputed(browser, id, 'width')).toBe(largeWidth)
expect(await getComputed(browser, id, 'height')).toBe(largeHeight)
const smallWidth = Number(width) - delta
const smallHeight = Number(height) - delta
await browser.setDimensions({
width: smallWidth,
height: smallHeight,
})
expect(await getComputed(browser, id, 'width')).toBe(smallWidth)
expect(await getComputed(browser, id, 'height')).toBe(smallHeight)
const objectFit = await browser.eval(
`document.getElementById("${id}").style.objectFit`
)
const objectPosition = await browser.eval(
`document.getElementById("${id}").style.objectPosition`
)
expect(objectFit).toBe('cover')
expect(objectPosition).toBe('left center')
await browser.eval(`document.getElementById("fill3").scrollIntoView()`)
await check(() => {
return browser.eval(
`document.querySelector('#fill3').getAttribute('srcset')`
)
}, '/_next/image?url=%2Fwide.png&w=256&q=75 256w, /_next/image?url=%2Fwide.png&w=384&q=75 384w, /_next/image?url=%2Fwide.png&w=640&q=75 640w, /_next/image?url=%2Fwide.png&w=750&q=75 750w, /_next/image?url=%2Fwide.png&w=828&q=75 828w, /_next/image?url=%2Fwide.png&w=1080&q=75 1080w, /_next/image?url=%2Fwide.png&w=1200&q=75 1200w, /_next/image?url=%2Fwide.png&w=1920&q=75 1920w, /_next/image?url=%2Fwide.png&w=2048&q=75 2048w, /_next/image?url=%2Fwide.png&w=3840&q=75 3840w')
await browser.eval(`document.getElementById("fill4").scrollIntoView()`)
await check(() => {
return browser.eval(
`document.querySelector('#fill4').getAttribute('srcset')`
)
}, '/_next/image?url=%2Fwide.png&w=16&q=75 16w, /_next/image?url=%2Fwide.png&w=32&q=75 32w, /_next/image?url=%2Fwide.png&w=48&q=75 48w, /_next/image?url=%2Fwide.png&w=64&q=75 64w, /_next/image?url=%2Fwide.png&w=96&q=75 96w, /_next/image?url=%2Fwide.png&w=128&q=75 128w, /_next/image?url=%2Fwide.png&w=256&q=75 256w, /_next/image?url=%2Fwide.png&w=384&q=75 384w, /_next/image?url=%2Fwide.png&w=640&q=75 640w, /_next/image?url=%2Fwide.png&w=750&q=75 750w, /_next/image?url=%2Fwide.png&w=828&q=75 828w, /_next/image?url=%2Fwide.png&w=1080&q=75 1080w, /_next/image?url=%2Fwide.png&w=1200&q=75 1200w, /_next/image?url=%2Fwide.png&w=1920&q=75 1920w, /_next/image?url=%2Fwide.png&w=2048&q=75 2048w, /_next/image?url=%2Fwide.png&w=3840&q=75 3840w')
} finally {
if (browser) {
await browser.close()
}
}
})
it('should work with sizes and automatically use layout-responsive', async () => {
let browser
try {
browser = await webdriver(appPort, '/sizes')
const width = 1200
const height = 700
const delta = 250
const id = 'sizes1'
await check(async () => {
expect(await getSrc(browser, id)).toBe(
'/_next/image?url=%2Fwide.png&w=3840&q=75'
)
return 'success'
}, 'success')
expect(await browser.elementById(id).getAttribute('srcset')).toBe(
'/_next/image?url=%2Fwide.png&w=16&q=75 16w, /_next/image?url=%2Fwide.png&w=32&q=75 32w, /_next/image?url=%2Fwide.png&w=48&q=75 48w, /_next/image?url=%2Fwide.png&w=64&q=75 64w, /_next/image?url=%2Fwide.png&w=96&q=75 96w, /_next/image?url=%2Fwide.png&w=128&q=75 128w, /_next/image?url=%2Fwide.png&w=256&q=75 256w, /_next/image?url=%2Fwide.png&w=384&q=75 384w, /_next/image?url=%2Fwide.png&w=640&q=75 640w, /_next/image?url=%2Fwide.png&w=750&q=75 750w, /_next/image?url=%2Fwide.png&w=828&q=75 828w, /_next/image?url=%2Fwide.png&w=1080&q=75 1080w, /_next/image?url=%2Fwide.png&w=1200&q=75 1200w, /_next/image?url=%2Fwide.png&w=1920&q=75 1920w, /_next/image?url=%2Fwide.png&w=2048&q=75 2048w, /_next/image?url=%2Fwide.png&w=3840&q=75 3840w'
)
expect(await browser.elementById(id).getAttribute('sizes')).toBe(
'(max-width: 2048px) 1200px, 3840px'
)
await browser.setDimensions({
width: width + delta,
height: height + delta,
})
expect(await getComputed(browser, id, 'width')).toBeGreaterThan(width)
expect(await getComputed(browser, id, 'height')).toBeGreaterThan(height)
await browser.setDimensions({
width: width - delta,
height: height - delta,
})
const newWidth = await getComputed(browser, id, 'width')
const newHeight = await getComputed(browser, id, 'height')
expect(newWidth).toBeLessThan(width)
expect(newHeight).toBeLessThan(height)
expect(getRatio(newWidth, newHeight)).toBeCloseTo(
getRatio(width, height),
1
)
} finally {
if (browser) {
await browser.close()
}
}
})
it('should handle the styles prop appropriately', async () => {
let browser
try {
browser = await webdriver(appPort, '/style-prop')
expect(
await browser.elementById('with-styles').getAttribute('style')
).toBe(
'border-radius:10px;padding:0;position:absolute;top:0;left:0;bottom:0;right:0;box-sizing:border-box;border:none;margin:auto;display:block;width:0;height:0;min-width:100%;max-width:100%;min-height:100%;max-height:100%'
)
expect(
await browser
.elementById('with-overlapping-styles-intrinsic')
.getAttribute('style')
).toBe(
'width:0;border-radius:10px;margin:auto;position:absolute;top:0;left:0;bottom:0;right:0;box-sizing:border-box;padding:0;border:none;display:block;height:0;min-width:100%;max-width:100%;min-height:100%;max-height:100%'
)
expect(
await browser
.elementById('without-styles-responsive')
.getAttribute('style')
).toBe(
'position:absolute;top:0;left:0;bottom:0;right:0;box-sizing:border-box;padding:0;border:none;margin:auto;display:block;width:0;height:0;min-width:100%;max-width:100%;min-height:100%;max-height:100%'
)
if (mode === 'dev') {
await waitFor(1000)
const warnings = (await browser.log())
.map((log) => log.message)
.join('\n')
expect(warnings).toMatch(
/Image with src \/test.png is assigned the following styles, which are overwritten by automatically-generated styles: padding/gm
)
expect(warnings).toMatch(
/Image with src \/test.jpg is assigned the following styles, which are overwritten by automatically-generated styles: width, margin/gm
)
expect(warnings).not.toMatch(
/Image with src \/test.webp is assigned the following styles/gm
)
}
} finally {
if (browser) {
await browser.close()
}
}
})
if (mode === 'dev') {
it('should show missing src error', async () => {
const browser = await webdriver(appPort, '/missing-src')
await assertNoRedbox(browser)
await check(async () => {
return (await browser.log()).map((log) => log.message).join('\n')
}, /Image is missing required "src" property/gm)
})
it('should show invalid src error', async () => {
const browser = await webdriver(appPort, '/invalid-src')
await assertHasRedbox(browser)
expect(await getRedboxHeader(browser)).toContain(
'Invalid src prop (path_to_url on `next/image`, hostname "google.com" is not configured under images in your `next.config.js`'
)
})
it('should show invalid src error when protocol-relative', async () => {
const browser = await webdriver(appPort, '/invalid-src-proto-relative')
await assertHasRedbox(browser)
expect(await getRedboxHeader(browser)).toContain(
'Failed to parse src "//assets.example.com/img.jpg" on `next/image`, protocol-relative URL (//) must be changed to an absolute URL (http:// or path_to_url
)
})
it('should show error when string src and placeholder=blur and blurDataURL is missing', async () => {
const browser = await webdriver(appPort, '/invalid-placeholder-blur')
await assertHasRedbox(browser)
expect(await getRedboxHeader(browser)).toContain(
`Image with src "/test.png" has "placeholder='blur'" property but is missing the "blurDataURL" property.`
)
})
it('should show error when not numeric string width or height', async () => {
const browser = await webdriver(appPort, '/invalid-width-or-height')
await assertHasRedbox(browser)
expect(await getRedboxHeader(browser)).toContain(
`Image with src "/test.jpg" has invalid "width" or "height" property. These should be numeric values.`
)
})
it('should show error when static import and placeholder=blur and blurDataUrl is missing', async () => {
const browser = await webdriver(
appPort,
'/invalid-placeholder-blur-static'
)
await assertHasRedbox(browser)
expect(await getRedboxHeader(browser)).toMatch(
/Image with src "(.*)bmp" has "placeholder='blur'" property but is missing the "blurDataURL" property/
)
})
it('should warn when img with layout=responsive is inside flex container', async () => {
const browser = await webdriver(appPort, '/layout-responsive-inside-flex')
await browser.eval(`document.getElementById("img").scrollIntoView()`)
await check(async () => {
return (await browser.log()).map((log) => log.message).join('\n')
}, /Image with src (.*)jpg(.*) may not render properly as a child of a flex container. Consider wrapping the image with a div to configure the width/gm)
await assertNoRedbox(browser)
})
it('should warn when img with layout=fill is inside a container without position relative', async () => {
const browser = await webdriver(
appPort,
'/layout-fill-inside-nonrelative'
)
await browser.eval(`document.querySelector("footer").scrollIntoView()`)
await waitFor(1000)
const warnings = (await browser.log())
.map((log) => log.message)
.join('\n')
expect(warnings).toMatch(
/Image with src (.*)jpg(.*) may not render properly with a parent using position:"static". Consider changing the parent style to position:"relative"/gm
)
expect(warnings).not.toMatch(
/Image with src (.*)png(.*) may not render properly/gm
)
expect(warnings).not.toMatch(
/Image with src (.*)avif(.*) may not render properly/gm
)
expect(warnings).not.toMatch(
/Image with src (.*)webp(.*) may not render properly/gm
)
await assertNoRedbox(browser)
})
it('should warn when using a very small image with placeholder=blur', async () => {
const browser = await webdriver(appPort, '/small-img-import')
const warnings = (await browser.log())
.map((log) => log.message)
.join('\n')
await assertNoRedbox(browser)
expect(warnings).toMatch(
/Image with src (.*)jpg(.*) is smaller than 40x40. Consider removing(.*)/gm
)
})
it('should not warn when Image is child of p', async () => {
const browser = await webdriver(appPort, '/inside-paragraph')
const warnings = (await browser.log())
.map((log) => log.message)
.join('\n')
await assertNoRedbox(browser)
expect(warnings).not.toMatch(
/Expected server HTML to contain a matching/gm
)
expect(warnings).not.toMatch(/cannot appear as a descendant/gm)
})
it('should warn when priority prop is missing on LCP image', async () => {
let browser = await webdriver(appPort, '/priority-missing-warning')
try {
// Wait for image to load:
await check(async () => {
const result = await browser.eval(
`document.getElementById('responsive').naturalWidth`
)
if (result < 1) {
throw new Error('Image not ready')
}
return 'done'
}, 'done')
await waitFor(1000)
const warnings = (await browser.log())
.map((log) => log.message)
.join('\n')
await assertNoRedbox(browser)
expect(warnings).toMatch(
/Image with src (.*)test(.*) was detected as the Largest Contentful Paint/gm
)
} finally {
await browser.close()
}
})
it('should warn when loader is missing width', async () => {
const browser = await webdriver(appPort, '/invalid-loader')
await browser.eval(`document.querySelector("footer").scrollIntoView()`)
const warnings = (await browser.log())
.map((log) => log.message)
.join('\n')
await assertNoRedbox(browser)
expect(warnings).toMatch(
/Image with src (.*)png(.*) has a "loader" property that does not implement width/gm
)
expect(warnings).not.toMatch(
/Image with src (.*)jpg(.*) has a "loader" property that does not implement width/gm
)
expect(warnings).not.toMatch(
/Image with src (.*)webp(.*) has a "loader" property that does not implement width/gm
)
expect(warnings).not.toMatch(
/Image with src (.*)gif(.*) has a "loader" property that does not implement width/gm
)
expect(warnings).not.toMatch(
/Image with src (.*)tiff(.*) has a "loader" property that does not implement width/gm
)
})
it('should warn when using sizes with incorrect layout', async () => {
const browser = await webdriver(appPort, '/invalid-sizes')
await browser.eval(`document.querySelector("footer").scrollIntoView()`)
const warnings = (await browser.log())
.map((log) => log.message)
.join('\n')
await assertNoRedbox(browser)
expect(warnings).toMatch(
/Image with src (.*)png(.*) has "sizes" property but it will be ignored/gm
)
expect(warnings).toMatch(
/Image with src (.*)jpg(.*) has "sizes" property but it will be ignored/gm
)
expect(warnings).not.toMatch(
/Image with src (.*)webp(.*) has "sizes" property but it will be ignored/gm
)
expect(warnings).not.toMatch(
/Image with src (.*)gif(.*) has "sizes" property but it will be ignored/gm
)
})
it('should not warn when svg, even if with loader prop or without', async () => {
const browser = await webdriver(appPort, '/loader-svg')
await browser.eval(`document.querySelector("footer").scrollIntoView()`)
const warnings = (await browser.log())
.map((log) => log.message)
.join('\n')
await assertNoRedbox(browser)
expect(warnings).not.toMatch(
/Image with src (.*) has a "loader" property that does not implement width/gm
)
expect(await browser.elementById('with-loader').getAttribute('src')).toBe(
'/test.svg?size=256'
)
expect(
await browser.elementById('with-loader').getAttribute('srcset')
).toBe('/test.svg?size=128 1x, /test.svg?size=256 2x')
expect(
await browser.elementById('without-loader').getAttribute('src')
).toBe('/test.svg')
expect(
await browser.elementById('without-loader').getAttribute('srcset')
).toBe('/test.svg 1x, /test.svg 2x')
})
it('should warn at most once even after state change', async () => {
const browser = await webdriver(appPort, '/warning-once')
await browser.eval(`document.querySelector("footer").scrollIntoView()`)
await browser.eval(`document.querySelector("button").click()`)
await browser.eval(`document.querySelector("button").click()`)
const count = await browser.eval(
`document.querySelector("button").textContent`
)
expect(count).toBe('Count: 2')
await check(async () => {
const result = await browser.eval(
'document.getElementById("w").naturalWidth'
)
if (result < 1) {
throw new Error('Image not loaded')
}
return 'done'
}, 'done')
await waitFor(1000)
const warnings = (await browser.log())
.map((log) => log.message)
.filter((log) => log.startsWith('Image with src'))
expect(warnings[0]).toMatch(
'Image with src "/test.png" has "sizes" property but it will be ignored.'
)
expect(warnings[1]).toMatch(
'Image with src "/test.png" was detected as the Largest Contentful Paint (LCP).'
)
expect(warnings.length).toBe(2)
})
} else {
//server-only tests
it('should not create an image folder in server/chunks', async () => {
expect(
existsSync(join(appDir, '.next/server/chunks/static/media'))
).toBeFalsy()
})
}
it('should correctly ignore prose styles', async () => {
let browser
try {
browser = await webdriver(appPort, '/prose')
const id = 'prose-image'
// Wait for image to load:
await check(async () => {
const result = await browser.eval(
`document.getElementById(${JSON.stringify(id)}).naturalWidth`
)
if (result < 1) {
throw new Error('Image not ready')
}
return 'result-correct'
}, /result-correct/)
await waitFor(1000)
const computedWidth = await getComputed(browser, id, 'width')
const computedHeight = await getComputed(browser, id, 'height')
expect(getRatio(computedWidth, computedHeight)).toBeCloseTo(1, 1)
} finally {
if (browser) {
await browser.close()
}
}
})
it('should apply style inheritance for img elements but not wrapper elements', async () => {
let browser
try {
browser = await webdriver(appPort, '/style-inheritance')
await browser.eval(
`document.querySelector("footer").scrollIntoView({behavior: "smooth"})`
)
const imagesWithIds = await browser.eval(`
function foo() {
const imgs = document.querySelectorAll("img[id]");
for (let img of imgs) {
const br = window.getComputedStyle(img).getPropertyValue("border-radius");
if (!br) return 'no-border-radius';
if (br !== '139px') return br;
}
return true;
}()
`)
expect(imagesWithIds).toBe(true)
const allSpans = await browser.eval(`
function foo() {
const spans = document.querySelectorAll("span");
for (let span of spans) {
const m = window.getComputedStyle(span).getPropertyValue("margin");
if (m && m !== '0px') return m;
}
return false;
}()
`)
expect(allSpans).toBe(false)
} finally {
if (browser) {
await browser.close()
}
}
})
it('should apply filter style after image loads', async () => {
const browser = await webdriver(appPort, '/style-filter')
await check(() => getSrc(browser, 'img-plain'), /^\/_next\/image/)
await check(() => getSrc(browser, 'img-blur'), /^\/_next\/image/)
await waitFor(1000)
expect(await getComputedStyle(browser, 'img-plain', 'filter')).toBe(
'opacity(0.5)'
)
expect(
await getComputedStyle(browser, 'img-plain', 'background-size')
).toBe('30%')
expect(
await getComputedStyle(browser, 'img-plain', 'background-image')
).toMatch('iVBORw0KGgo=')
expect(
await getComputedStyle(browser, 'img-plain', 'background-position')
).toBe('1px 2px')
expect(await getComputedStyle(browser, 'img-blur', 'filter')).toBe(
'opacity(0.5)'
)
expect(await getComputedStyle(browser, 'img-blur', 'background-size')).toBe(
'30%'
)
expect(
await getComputedStyle(browser, 'img-blur', 'background-image')
).toMatch('iVBORw0KGgo=')
expect(
await getComputedStyle(browser, 'img-blur', 'background-position')
).toBe('1px 2px')
})
it('should emit image for next/dynamic with non ssr case', async () => {
let browser = await webdriver(appPort, '/dynamic-static-img')
const img = await browser.elementById('dynamic-loaded-static-jpg')
const src = await img.getAttribute('src')
const { status } = await fetchViaHTTP(appPort, src)
expect(status).toBe(200)
})
// Tests that use the `unsized` attribute:
if (mode !== 'dev') {
it('should correctly rotate image', async () => {
let browser
try {
browser = await webdriver(appPort, '/rotated')
const id = 'exif-rotation-image'
// Wait for image to load:
await check(async () => {
const result = await browser.eval(
`document.getElementById(${JSON.stringify(id)}).naturalWidth`
)
if (result < 1) {
throw new Error('Image not ready')
}
return 'result-correct'
}, /result-correct/)
await waitFor(1000)
const computedWidth = await getComputed(browser, id, 'width')
const computedHeight = await getComputed(browser, id, 'height')
expect(getRatio(computedWidth, computedHeight)).toBeCloseTo(0.5625, 1)
} finally {
if (browser) {
await browser.close()
}
}
})
}
it('should have blurry placeholder when enabled', async () => {
const html = await renderViaHTTP(appPort, '/blurry-placeholder')
const $html = cheerio.load(html)
$html('noscript > img').attr('id', 'unused')
expect($html('#blurry-placeholder')[0].attribs.style).toContain(
`background-image:url("data:image/svg+xml,%3Csvg xmlns='path_to_url width='400' height='400' viewBox='0 0 400 400'%3E%3Cfilter id='blur' filterUnits='userSpaceOnUse' color-interpolation-filters='sRGB'%3E%3CfeGaussianBlur stdDeviation='20' edgeMode='duplicate' /%3E%3CfeComponentTransfer%3E%3CfeFuncA type='discrete' tableValues='1 1' /%3E%3C/feComponentTransfer%3E%3C/filter%3E%3Cimage filter='url(%23blur)' href='data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/your_sha256_hashFRMTFRsfGhkaHyYiIiYwLTA+PlT/wAALCAAKAAoBAREA/your_sha256_hashyEVMlH/2gAIAQEAAD8Az1bLPaxhiuk0QdeCOLDtHixN2dmd2bsc5FPX7VTREX//2Q==' x='0' y='0' height='100%25' width='100%25'/%3E%3C/svg%3E")`
)
expect($html('#blurry-placeholder')[0].attribs.style).toContain(
`background-position:0% 0%`
)
expect(
$html('#blurry-placeholder-tall-centered')[0].attribs.style
).toContain(`background-position:center`)
expect($html('#blurry-placeholder-with-lazy')[0].attribs.style).toContain(
`background-image:url("data:image/svg+xml,%3Csvg xmlns='path_to_url width='400' height='400' viewBox='0 0 400 400'%3E%3Cfilter id='blur' filterUnits='userSpaceOnUse' color-interpolation-filters='sRGB'%3E%3CfeGaussianBlur stdDeviation='20' edgeMode='duplicate' /%3E%3CfeComponentTransfer%3E%3CfeFuncA type='discrete' tableValues='1 1' /%3E%3C/feComponentTransfer%3E%3C/filter%3E%3Cimage filter='url(%23blur)' href='data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/your_sha256_hashFRMTFRsfGhkaHyYiIiYwLTA+PlT/wAALCAAKAAoBAREA/your_sha256_hashyEVMlH/2gAIAQEAAD8Az1bLPaxhiuk0QdeCOLDtHixN2dmd2bsc5FPX7VTREX//2Q==' x='0' y='0' height='100%25' width='100%25'/%3E%3C/svg%3E")`
)
})
it('should not use blurry placeholder for <noscript> image', async () => {
const html = await renderViaHTTP(appPort, '/blurry-placeholder')
const $html = cheerio.load(html)
const style = $html('noscript > img')[0].attribs.style
expect(style).not.toContain(`background-position`)
expect(style).not.toContain(`background-size`)
expect(style).not.toContain(
`background-image:url("data:image/svg+xml,%3Csvg xmlns='path_to_url width='400' height='400' viewBox='0 0 400 400'%3E%3Cfilter id='blur' filterUnits='userSpaceOnUse' color-interpolation-filters='sRGB'%3E%3CfeGaussianBlur stdDeviation='20' edgeMode='duplicate' /%3E%3CfeComponentTransfer%3E%3CfeFuncA type='discrete' tableValues='1 1' /%3E%3C/feComponentTransfer%3E%3C/filter%3E%3Cimage filter='url(%23blur)' href='data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/your_sha256_hashFRMTFRsfGhkaHyYiIiYwLTA+PlT/wAALCAAKAAoBAREA/your_sha256_hashyEVMlH/2gAIAQEAAD8Az1bLPaxhiuk0QdeCOLDtHixN2dmd2bsc5FPX7VTREX//2Q==' x='0' y='0' height='100%25' width='100%25'/%3E%3C/svg%3E")`
)
})
it('should remove blurry placeholder after image loads', async () => {
let browser
try {
browser = await webdriver(appPort, '/blurry-placeholder')
await check(
async () =>
await getComputedStyle(
browser,
'blurry-placeholder',
'background-image'
),
'none'
)
expect(
await getComputedStyle(
browser,
'blurry-placeholder-with-lazy',
'background-image'
)
).toBe(
`url("data:image/svg+xml,%3Csvg xmlns='path_to_url width='400' height='400' viewBox='0 0 400 400'%3E%3Cfilter id='blur' filterUnits='userSpaceOnUse' color-interpolation-filters='sRGB'%3E%3CfeGaussianBlur stdDeviation='20' edgeMode='duplicate' /%3E%3CfeComponentTransfer%3E%3CfeFuncA type='discrete' tableValues='1 1' /%3E%3C/feComponentTransfer%3E%3C/filter%3E%3Cimage filter='url(%23blur)' href='data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/your_sha256_hashFRMTFRsfGhkaHyYiIiYwLTA+PlT/wAALCAAKAAoBAREA/your_sha256_hashyEVMlH/2gAIAQEAAD8Az1bLPaxhiuk0QdeCOLDtHixN2dmd2bsc5FPX7VTREX//2Q==' x='0' y='0' height='100%25' width='100%25'/%3E%3C/svg%3E")`
)
await browser.eval('document.getElementById("spacer").remove()')
await check(
async () =>
await getComputedStyle(
browser,
'blurry-placeholder-with-lazy',
'background-image'
),
'none'
)
} finally {
if (browser) {
await browser.close()
}
}
})
it('should re-lazyload images after src changes', async () => {
let browser
try {
browser = await webdriver(appPort, '/lazy-src-change')
// image should not be loaded as it is out of viewport
await check(async () => {
const result = await browser.eval(
`document.getElementById('basic-image').naturalWidth`
)
if (result >= 400) {
throw new Error('Incorrectly loaded image')
}
return 'result-correct'
}, /result-correct/)
// Move image into viewport
await browser.eval(
'document.getElementById("spacer").style.display = "none"'
)
// image should be loaded by now
await check(async () => {
const result = await browser.eval(
`document.getElementById('basic-image').naturalWidth`
)
if (result < 400) {
throw new Error('Incorrectly loaded image')
}
return 'result-correct'
}, /result-correct/)
await check(
() => browser.eval(`document.getElementById("basic-image").currentSrc`),
/test\.jpg/
)
// Make image out of viewport again
await browser.eval(
'document.getElementById("spacer").style.display = "block"'
)
// Toggle image's src
await browser.eval(
'document.getElementById("button-change-image-src").click()'
)
// "new" image should be lazy loaded
await check(async () => {
const result = await browser.eval(
`document.getElementById('basic-image').naturalWidth`
)
if (result >= 400) {
throw new Error('Incorrectly loaded image')
}
return 'result-correct'
}, /result-correct/)
// Move image into viewport again
await browser.eval(
'document.getElementById("spacer").style.display = "none"'
)
// "new" image should be loaded by now
await check(async () => {
const result = await browser.eval(
`document.getElementById('basic-image').naturalWidth`
)
if (result < 400) {
throw new Error('Incorrectly loaded image')
}
return 'result-correct'
}, /result-correct/)
await check(
() => browser.eval(`document.getElementById("basic-image").currentSrc`),
/test\.png/
)
} finally {
if (browser) {
await browser.close()
}
}
})
it('should initially load only two of four images using lazyroot', async () => {
let browser
try {
browser = await webdriver(appPort, '/lazy-withref')
await check(async () => {
const result = await browser.eval(
`document.getElementById('myImage1').naturalWidth`
)
if (result >= 400) {
throw new Error('Incorrectly loaded image')
}
return 'result-correct'
}, /result-correct/)
await check(async () => {
const result = await browser.eval(
`document.getElementById('myImage4').naturalWidth`
)
if (result >= 400) {
throw new Error('Incorrectly loaded image')
}
return 'result-correct'
}, /result-correct/)
await check(async () => {
const result = await browser.eval(
`document.getElementById('myImage2').naturalWidth`
)
if (result < 400) {
throw new Error('Incorrectly loaded image')
}
return 'result-correct'
}, /result-correct/)
await check(async () => {
const result = await browser.eval(
`document.getElementById('myImage3').naturalWidth`
)
if (result < 400) {
throw new Error('Incorrectly loaded image')
}
return 'result-correct'
}, /result-correct/)
expect(
await hasImageMatchingUrl(
browser,
`path_to_url{appPort}/_next/image?url=%2Ftest.jpg&w=828&q=75`
)
).toBe(false)
expect(
await hasImageMatchingUrl(
browser,
`path_to_url{appPort}/_next/image?url=%2Ftest.png&w=828&q=75`
)
).toBe(true)
expect(
await hasImageMatchingUrl(
browser,
`path_to_url{appPort}/test.svg`
)
).toBe(true)
expect(
await hasImageMatchingUrl(
browser,
`path_to_url{appPort}/_next/image?url=%2Ftest.webp&w=828&q=75`
)
).toBe(false)
} finally {
if (browser) {
await browser.close()
}
}
})
it('should be valid HTML', async () => {
let browser
try {
browser = await webdriver(appPort, '/valid-html-w3c')
await waitFor(1000)
expect(await browser.hasElementByCssSelector('img')).toBeTruthy()
const url = await browser.url()
const result = (await validateHTML({
url,
format: 'json',
isLocal: true,
validator: 'whatwg',
})) as any
expect(result.isValid).toBe(true)
expect(result.errors).toEqual([])
} finally {
if (browser) {
await browser.close()
}
}
})
}
describe('Image Component Tests', () => {
;(process.env.TURBOPACK_BUILD ? describe.skip : describe)(
'development mode',
() => {
beforeAll(async () => {
appPort = await findPort()
app = await launchApp(appDir, appPort)
})
afterAll(async () => {
await killApp(app)
})
runTests('dev')
}
)
;(process.env.TURBOPACK_DEV ? describe.skip : describe)(
'production mode',
() => {
beforeAll(async () => {
await nextBuild(appDir)
appPort = await findPort()
app = await nextStart(appDir, appPort)
})
afterAll(async () => {
await killApp(app)
})
runTests('server')
}
)
})
``` | /content/code_sandbox/test/integration/next-image-legacy/default/test/index.test.ts | xml | 2016-10-05T23:32:51 | 2024-08-16T19:44:30 | next.js | vercel/next.js | 124,056 | 13,659 |
```xml
import type createIntervalTree from '@protontech/interval-tree';
import type { CALENDAR_SIGNED_FIELDS, SHARED_SIGNED_FIELDS } from '@proton/shared/lib/calendar/constants';
import type { OccurrenceIterationCache } from '@proton/shared/lib/calendar/recurrence/recurring';
import type { RequireSome } from '@proton/shared/lib/interfaces';
import type {
CalendarEvent,
CalendarEventSharedData,
DecryptedVeventResult,
} from '@proton/shared/lib/interfaces/calendar';
import type { VcalVeventComponent } from '@proton/shared/lib/interfaces/calendar/VcalModel';
import type { EventInternalProperties } from '../../../interfaces/EventInternalProperties';
export type IntervalTree = ReturnType<typeof createIntervalTree>;
export interface RecurringCache {
parentEventID?: string;
cache?: Partial<OccurrenceIterationCache>;
recurrenceInstances?: { [key: number]: string };
}
export type DecryptedEventTupleResult = [
DecryptedVeventResult,
Pick<EventInternalProperties, 'Permissions' | 'IsProtonProtonInvite'>,
];
export type EventReadResult = {
result?: DecryptedEventTupleResult;
error?: Error;
};
export type SharedVcalVeventComponent = Pick<VcalVeventComponent, (typeof SHARED_SIGNED_FIELDS)[number] | 'component'>;
export type CalendarVcalVeventComponent = Pick<
VcalVeventComponent,
(typeof CALENDAR_SIGNED_FIELDS)[number] | 'component'
>;
export type MetadataVcalVeventComponent = Pick<
VcalVeventComponent,
'uid' | 'dtstamp' | 'component' | 'dtstart' | 'dtend' | 'recurrence-id' | 'exdate' | 'rrule'
>;
export interface CalendarEventStoreRecord {
utcStart: Date;
utcEnd: Date;
isAllDay: boolean;
isAllPartDay: boolean;
eventData?: CalendarEvent | CalendarEventSharedData;
eventComponent: SharedVcalVeventComponent | MetadataVcalVeventComponent;
eventReadResult?: EventReadResult;
eventPromise?: Promise<EventReadResult | undefined>;
eventReadRetry?: () => Promise<EventReadResult | undefined>;
}
export const getEventStoreRecordHasEventData = (
record: CalendarEventStoreRecord
): record is RequireSome<CalendarEventStoreRecord, 'eventData'> => {
return !!record.eventData;
};
export type RecurringEventsCache = Map<string, RecurringCache>;
export type EventsCache = Map<string, CalendarEventStoreRecord>;
export type FetchCache = Map<string, { promise?: Promise<void>; dateRange: [Date, Date] }>;
export type FetchUidCache = Map<string, { promise?: Promise<void> }>;
export interface CalendarEventsCache {
events: EventsCache;
recurringEvents: RecurringEventsCache;
tree: IntervalTree;
fetchTree: IntervalTree;
fetchCache: FetchCache;
fetchUidCache: FetchUidCache;
}
export interface CalendarsEventsCache {
ref: number;
isUnmounted: boolean;
calendars: {
[key: string]: CalendarEventsCache | undefined;
};
getCachedEvent: (calendarID: string, eventID: string) => CalendarEvent | undefined;
getCachedRecurringEvent: (calendarID: string, uid: string) => RecurringCache | undefined;
retryReadEvent: (calendarID: string, eventID: string) => Promise<EventReadResult | undefined>;
rerender?: () => void;
}
export type GetDecryptedEventCb = (Event: CalendarEvent) => Promise<DecryptedEventTupleResult>;
``` | /content/code_sandbox/applications/calendar/src/app/containers/calendar/eventStore/interface.ts | xml | 2016-06-08T11:16:51 | 2024-08-16T14:14:27 | WebClients | ProtonMail/WebClients | 4,300 | 768 |
```xml
import { newE2EPage } from '@stencil/core/testing';
describe('my-component', () => {
it('renders', async () => {
const page = await newE2EPage();
await page.setContent('<my-component></my-component>');
const element = await page.find('my-component');
expect(element).toHaveClass('hydrated');
});
it('renders changes to the name data', async () => {
const page = await newE2EPage();
await page.setContent('<my-component></my-component>');
const component = await page.find('my-component');
const element = await page.find('my-component >>> div');
expect(element.textContent).toEqual(`Hello, World! I'm `);
component.setProperty('first', 'James');
await page.waitForChanges();
expect(element.textContent).toEqual(`Hello, World! I'm James`);
component.setProperty('last', 'Quincy');
await page.waitForChanges();
expect(element.textContent).toEqual(`Hello, World! I'm James Quincy`);
component.setProperty('middle', 'Earl');
await page.waitForChanges();
expect(element.textContent).toEqual(`Hello, World! I'm James Earl Quincy`);
});
});
``` | /content/code_sandbox/packages/static-build/test/fixtures/stencil-v4/src/components/my-component/my-component.e2e.ts | xml | 2016-09-09T01:12:08 | 2024-08-16T17:39:45 | vercel | vercel/vercel | 12,545 | 251 |
```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "path_to_url">
<mapper namespace="com.zheng.ucenter.dao.mapper.UcenterUserDetailsMapper">
<resultMap id="BaseResultMap" type="com.zheng.ucenter.dao.model.UcenterUserDetails">
<id column="user_id" jdbcType="INTEGER" property="userId" />
<result column="signature" jdbcType="VARCHAR" property="signature" />
<result column="real_name" jdbcType="VARCHAR" property="realName" />
<result column="birthday" jdbcType="TIMESTAMP" property="birthday" />
<result column="question" jdbcType="VARCHAR" property="question" />
<result column="answer" jdbcType="VARCHAR" property="answer" />
</resultMap>
<sql id="Example_Where_Clause">
<where>
<foreach collection="oredCriteria" item="criteria" separator="or">
<if test="criteria.valid">
<trim prefix="(" prefixOverrides="and" suffix=")">
<foreach collection="criteria.criteria" item="criterion">
<choose>
<when test="criterion.noValue">
and ${criterion.condition}
</when>
<when test="criterion.singleValue">
and ${criterion.condition} #{criterion.value}
</when>
<when test="criterion.betweenValue">
and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
</when>
<when test="criterion.listValue">
and ${criterion.condition}
<foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">
#{listItem}
</foreach>
</when>
</choose>
</foreach>
</trim>
</if>
</foreach>
</where>
</sql>
<sql id="Update_By_Example_Where_Clause">
<where>
<foreach collection="example.oredCriteria" item="criteria" separator="or">
<if test="criteria.valid">
<trim prefix="(" prefixOverrides="and" suffix=")">
<foreach collection="criteria.criteria" item="criterion">
<choose>
<when test="criterion.noValue">
and ${criterion.condition}
</when>
<when test="criterion.singleValue">
and ${criterion.condition} #{criterion.value}
</when>
<when test="criterion.betweenValue">
and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
</when>
<when test="criterion.listValue">
and ${criterion.condition}
<foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">
#{listItem}
</foreach>
</when>
</choose>
</foreach>
</trim>
</if>
</foreach>
</where>
</sql>
<sql id="Base_Column_List">
user_id, signature, real_name, birthday, question, answer
</sql>
<select id="selectByExample" parameterType="com.zheng.ucenter.dao.model.UcenterUserDetailsExample" resultMap="BaseResultMap">
select
<if test="distinct">
distinct
</if>
<include refid="Base_Column_List" />
from ucenter_user_details
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
<if test="orderByClause != null">
order by ${orderByClause}
</if>
</select>
<select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from ucenter_user_details
where user_id = #{userId,jdbcType=INTEGER}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
delete from ucenter_user_details
where user_id = #{userId,jdbcType=INTEGER}
</delete>
<delete id="deleteByExample" parameterType="com.zheng.ucenter.dao.model.UcenterUserDetailsExample">
delete from ucenter_user_details
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
</delete>
<insert id="insert" parameterType="com.zheng.ucenter.dao.model.UcenterUserDetails">
insert into ucenter_user_details (user_id, signature, real_name,
birthday, question, answer
)
values (#{userId,jdbcType=INTEGER}, #{signature,jdbcType=VARCHAR}, #{realName,jdbcType=VARCHAR},
#{birthday,jdbcType=TIMESTAMP}, #{question,jdbcType=VARCHAR}, #{answer,jdbcType=VARCHAR}
)
</insert>
<insert id="insertSelective" parameterType="com.zheng.ucenter.dao.model.UcenterUserDetails">
insert into ucenter_user_details
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="userId != null">
user_id,
</if>
<if test="signature != null">
signature,
</if>
<if test="realName != null">
real_name,
</if>
<if test="birthday != null">
birthday,
</if>
<if test="question != null">
question,
</if>
<if test="answer != null">
answer,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="userId != null">
#{userId,jdbcType=INTEGER},
</if>
<if test="signature != null">
#{signature,jdbcType=VARCHAR},
</if>
<if test="realName != null">
#{realName,jdbcType=VARCHAR},
</if>
<if test="birthday != null">
#{birthday,jdbcType=TIMESTAMP},
</if>
<if test="question != null">
#{question,jdbcType=VARCHAR},
</if>
<if test="answer != null">
#{answer,jdbcType=VARCHAR},
</if>
</trim>
</insert>
<select id="countByExample" parameterType="com.zheng.ucenter.dao.model.UcenterUserDetailsExample" resultType="java.lang.Long">
select count(*) from ucenter_user_details
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
</select>
<update id="updateByExampleSelective" parameterType="map">
update ucenter_user_details
<set>
<if test="record.userId != null">
user_id = #{record.userId,jdbcType=INTEGER},
</if>
<if test="record.signature != null">
signature = #{record.signature,jdbcType=VARCHAR},
</if>
<if test="record.realName != null">
real_name = #{record.realName,jdbcType=VARCHAR},
</if>
<if test="record.birthday != null">
birthday = #{record.birthday,jdbcType=TIMESTAMP},
</if>
<if test="record.question != null">
question = #{record.question,jdbcType=VARCHAR},
</if>
<if test="record.answer != null">
answer = #{record.answer,jdbcType=VARCHAR},
</if>
</set>
<if test="_parameter != null">
<include refid="Update_By_Example_Where_Clause" />
</if>
</update>
<update id="updateByExample" parameterType="map">
update ucenter_user_details
set user_id = #{record.userId,jdbcType=INTEGER},
signature = #{record.signature,jdbcType=VARCHAR},
real_name = #{record.realName,jdbcType=VARCHAR},
birthday = #{record.birthday,jdbcType=TIMESTAMP},
question = #{record.question,jdbcType=VARCHAR},
answer = #{record.answer,jdbcType=VARCHAR}
<if test="_parameter != null">
<include refid="Update_By_Example_Where_Clause" />
</if>
</update>
<update id="updateByPrimaryKeySelective" parameterType="com.zheng.ucenter.dao.model.UcenterUserDetails">
update ucenter_user_details
<set>
<if test="signature != null">
signature = #{signature,jdbcType=VARCHAR},
</if>
<if test="realName != null">
real_name = #{realName,jdbcType=VARCHAR},
</if>
<if test="birthday != null">
birthday = #{birthday,jdbcType=TIMESTAMP},
</if>
<if test="question != null">
question = #{question,jdbcType=VARCHAR},
</if>
<if test="answer != null">
answer = #{answer,jdbcType=VARCHAR},
</if>
</set>
where user_id = #{userId,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey" parameterType="com.zheng.ucenter.dao.model.UcenterUserDetails">
update ucenter_user_details
set signature = #{signature,jdbcType=VARCHAR},
real_name = #{realName,jdbcType=VARCHAR},
birthday = #{birthday,jdbcType=TIMESTAMP},
question = #{question,jdbcType=VARCHAR},
answer = #{answer,jdbcType=VARCHAR}
where user_id = #{userId,jdbcType=INTEGER}
</update>
<cache type="org.mybatis.caches.ehcache.LoggingEhcache" />
</mapper>
``` | /content/code_sandbox/zheng-ucenter/zheng-ucenter-rpc-service/src/main/java/com/zheng/ucenter/dao/mapper/UcenterUserDetailsMapper.xml | xml | 2016-10-04T10:07:06 | 2024-08-16T07:00:44 | zheng | shuzheng/zheng | 16,660 | 2,109 |
```xml
/* eslint-disable */
// Disable ESLint to prevent failing linting inside the Next.js repo.
// If you're using ESLint on your project, we recommend installing the ESLint Cypress plugin instead:
// path_to_url
describe("Navigation", () => {
it("should navigate to the about page", () => {
// Start from the index page
cy.visit("path_to_url");
// Find a link with an href attribute containing "about" and click it
cy.get('a[href*="about"]').click();
// The new url should include "/home/about"
cy.url().should("include", "/home/about");
// The new page should contain an h1 with "About"
cy.get("h1").contains("About");
});
});
``` | /content/code_sandbox/examples/with-cypress/cypress/e2e/pages.cy.ts | xml | 2016-10-05T23:32:51 | 2024-08-16T19:44:30 | next.js | vercel/next.js | 124,056 | 162 |
```xml
/*
* one or more contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright ownership.
*/
const mockComplexProcess = `<?xml version="1.0" encoding="UTF-8"?>
<bpmn:definitions xmlns:bpmn="path_to_url" xmlns:bpmndi="path_to_url" xmlns:di="path_to_url" xmlns:dc="path_to_url" xmlns:zeebe="path_to_url" xmlns:xsi="path_to_url" id="Definitions_0hir062" targetNamespace="path_to_url" exporter="Zeebe Modeler" exporterVersion="0.8.0">
<bpmn:process id="complexProcess" isExecutable="true">
<bpmn:startEvent id="startEvent">
<bpmn:outgoing>SequenceFlow_1gvaaro</bpmn:outgoing>
</bpmn:startEvent>
<bpmn:serviceTask id="upperTask" name="Upper task">
<bpmn:extensionElements>
<zeebe:taskDefinition type="upperTask" />
<zeebe:ioMapping>
<zeebe:input source="=orderId" target="taskOrderId" />
</zeebe:ioMapping>
</bpmn:extensionElements>
<bpmn:incoming>SequenceFlow_0oxsuty</bpmn:incoming>
<bpmn:outgoing>SequenceFlow_1kpkmd0</bpmn:outgoing>
</bpmn:serviceTask>
<bpmn:serviceTask id="alwaysFailingTask" name="Always failing task">
<bpmn:extensionElements>
<zeebe:taskDefinition type="alwaysFailingTask" />
</bpmn:extensionElements>
<bpmn:incoming>SequenceFlow_1ti40d3</bpmn:incoming>
<bpmn:outgoing>SequenceFlow_0avs127</bpmn:outgoing>
</bpmn:serviceTask>
<bpmn:sequenceFlow id="SequenceFlow_1gvaaro" sourceRef="startEvent" targetRef="inclGatewayFork" />
<bpmn:sequenceFlow id="SequenceFlow_0oxsuty" sourceRef="inclGatewayFork" targetRef="upperTask" />
<bpmn:sequenceFlow id="SequenceFlow_1ti40d3" sourceRef="inclGatewayFork" targetRef="alwaysFailingTask" />
<bpmn:parallelGateway id="inclGatewayFork" name="Start 4 threads">
<bpmn:incoming>SequenceFlow_1gvaaro</bpmn:incoming>
<bpmn:outgoing>SequenceFlow_0oxsuty</bpmn:outgoing>
<bpmn:outgoing>SequenceFlow_1ti40d3</bpmn:outgoing>
<bpmn:outgoing>SequenceFlow_1j24jks</bpmn:outgoing>
<bpmn:outgoing>SequenceFlow_12gxvr0</bpmn:outgoing>
</bpmn:parallelGateway>
<bpmn:intermediateCatchEvent id="messageCatchEvent" name="message">
<bpmn:incoming>SequenceFlow_1j24jks</bpmn:incoming>
<bpmn:outgoing>SequenceFlow_10d2jhh</bpmn:outgoing>
<bpmn:messageEventDefinition messageRef="Message_0hh3rtz" />
</bpmn:intermediateCatchEvent>
<bpmn:sequenceFlow id="SequenceFlow_1j24jks" sourceRef="inclGatewayFork" targetRef="messageCatchEvent" />
<bpmn:exclusiveGateway id="exclusiveGateway" name="Where to go?">
<bpmn:incoming>SequenceFlow_12gxvr0</bpmn:incoming>
<bpmn:outgoing>SequenceFlow_1pzygua</bpmn:outgoing>
<bpmn:outgoing>SequenceFlow_1goon4z</bpmn:outgoing>
</bpmn:exclusiveGateway>
<bpmn:sequenceFlow id="SequenceFlow_12gxvr0" sourceRef="inclGatewayFork" targetRef="exclusiveGateway" />
<bpmn:endEvent id="EndEvent_0bkqw71">
<bpmn:incoming>SequenceFlow_10d2jhh</bpmn:incoming>
</bpmn:endEvent>
<bpmn:endEvent id="EndEvent_1w1u88d" name="endUp">
<bpmn:incoming>SequenceFlow_1pzygua</bpmn:incoming>
</bpmn:endEvent>
<bpmn:sequenceFlow id="SequenceFlow_1pzygua" name="goUp > 5" sourceRef="exclusiveGateway" targetRef="EndEvent_1w1u88d">
<bpmn:conditionExpression xsi:type="bpmn:tFormalExpression">=goUp > 5</bpmn:conditionExpression>
</bpmn:sequenceFlow>
<bpmn:endEvent id="EndEvent_0tfsfo0" name="endDown">
<bpmn:incoming>SequenceFlow_1goon4z</bpmn:incoming>
</bpmn:endEvent>
<bpmn:sequenceFlow id="SequenceFlow_1goon4z" name="goUp < 0" sourceRef="exclusiveGateway" targetRef="EndEvent_0tfsfo0">
<bpmn:conditionExpression xsi:type="bpmn:tFormalExpression">=goUp < 0</bpmn:conditionExpression>
</bpmn:sequenceFlow>
<bpmn:sequenceFlow id="SequenceFlow_10d2jhh" sourceRef="messageCatchEvent" targetRef="EndEvent_0bkqw71" />
<bpmn:endEvent id="endEvent">
<bpmn:incoming>SequenceFlow_1kpkmd0</bpmn:incoming>
</bpmn:endEvent>
<bpmn:sequenceFlow id="SequenceFlow_1kpkmd0" sourceRef="upperTask" targetRef="endEvent" />
<bpmn:endEvent id="EndEvent_03hsdez">
<bpmn:incoming>SequenceFlow_0avs127</bpmn:incoming>
</bpmn:endEvent>
<bpmn:sequenceFlow id="SequenceFlow_0avs127" sourceRef="alwaysFailingTask" targetRef="EndEvent_03hsdez" />
</bpmn:process>
<bpmn:message id="Message_0hh3rtz" name="clientMessage">
<bpmn:extensionElements>
<zeebe:subscription correlationKey="=clientId" />
</bpmn:extensionElements>
</bpmn:message>
<bpmn:message id="Message_1agndym" name="dataReceived">
<bpmn:extensionElements>
<zeebe:subscription correlationKey="=clientId" />
</bpmn:extensionElements>
</bpmn:message>
<bpmndi:BPMNDiagram id="BPMNDiagram_1">
<bpmndi:BPMNPlane id="BPMNPlane_1" bpmnElement="complexProcess">
<bpmndi:BPMNShape id="_BPMNShape_StartEvent_2" bpmnElement="startEvent">
<dc:Bounds x="157" y="177" width="36" height="36" />
</bpmndi:BPMNShape>
<bpmndi:BPMNShape id="ServiceTask_132jrbt_di" bpmnElement="upperTask">
<dc:Bounds x="386" y="90" width="100" height="80" />
</bpmndi:BPMNShape>
<bpmndi:BPMNShape id="ServiceTask_1meo1hw_di" bpmnElement="alwaysFailingTask">
<dc:Bounds x="386" y="242" width="100" height="80" />
</bpmndi:BPMNShape>
<bpmndi:BPMNEdge id="SequenceFlow_1gvaaro_di" bpmnElement="SequenceFlow_1gvaaro">
<di:waypoint x="193" y="195" />
<di:waypoint x="262" y="195" />
</bpmndi:BPMNEdge>
<bpmndi:BPMNEdge id="SequenceFlow_0oxsuty_di" bpmnElement="SequenceFlow_0oxsuty">
<di:waypoint x="287" y="170" />
<di:waypoint x="287" y="130" />
<di:waypoint x="386" y="130" />
</bpmndi:BPMNEdge>
<bpmndi:BPMNEdge id="SequenceFlow_1ti40d3_di" bpmnElement="SequenceFlow_1ti40d3">
<di:waypoint x="287" y="220" />
<di:waypoint x="287" y="282" />
<di:waypoint x="386" y="282" />
</bpmndi:BPMNEdge>
<bpmndi:BPMNShape id="ParallelGateway_0n4dl17_di" bpmnElement="inclGatewayFork">
<dc:Bounds x="262" y="170" width="50" height="50" />
<bpmndi:BPMNLabel>
<dc:Bounds x="322" y="188" width="73" height="14" />
</bpmndi:BPMNLabel>
</bpmndi:BPMNShape>
<bpmndi:BPMNShape id="IntermediateCatchEvent_0opz4tk_di" bpmnElement="messageCatchEvent">
<dc:Bounds x="418" y="410" width="36" height="36" />
<bpmndi:BPMNLabel>
<dc:Bounds x="414" y="453" width="45" height="14" />
</bpmndi:BPMNLabel>
</bpmndi:BPMNShape>
<bpmndi:BPMNEdge id="SequenceFlow_1j24jks_di" bpmnElement="SequenceFlow_1j24jks">
<di:waypoint x="287" y="220" />
<di:waypoint x="287" y="428" />
<di:waypoint x="418" y="428" />
</bpmndi:BPMNEdge>
<bpmndi:BPMNShape id="ExclusiveGateway_01pou5h_di" bpmnElement="exclusiveGateway" isMarkerVisible="true">
<dc:Bounds x="398" y="558" width="50" height="50" />
<bpmndi:BPMNLabel>
<dc:Bounds x="348" y="550" width="66" height="14" />
</bpmndi:BPMNLabel>
</bpmndi:BPMNShape>
<bpmndi:BPMNEdge id="SequenceFlow_12gxvr0_di" bpmnElement="SequenceFlow_12gxvr0">
<di:waypoint x="287" y="220" />
<di:waypoint x="287" y="583" />
<di:waypoint x="398" y="583" />
</bpmndi:BPMNEdge>
<bpmndi:BPMNShape id="EndEvent_0bkqw71_di" bpmnElement="EndEvent_0bkqw71">
<dc:Bounds x="552" y="410" width="36" height="36" />
</bpmndi:BPMNShape>
<bpmndi:BPMNShape id="EndEvent_1w1u88d_di" bpmnElement="EndEvent_1w1u88d">
<dc:Bounds x="540" y="516" width="36" height="36" />
<bpmndi:BPMNLabel>
<dc:Bounds x="542" y="559" width="34" height="14" />
</bpmndi:BPMNLabel>
</bpmndi:BPMNShape>
<bpmndi:BPMNEdge id="SequenceFlow_1pzygua_di" bpmnElement="SequenceFlow_1pzygua">
<di:waypoint x="423" y="558" />
<di:waypoint x="423" y="534" />
<di:waypoint x="540" y="534" />
<bpmndi:BPMNLabel>
<dc:Bounds x="440" y="516" width="45" height="14" />
</bpmndi:BPMNLabel>
</bpmndi:BPMNEdge>
<bpmndi:BPMNShape id="EndEvent_0tfsfo0_di" bpmnElement="EndEvent_0tfsfo0">
<dc:Bounds x="540" y="623" width="36" height="36" />
<bpmndi:BPMNLabel>
<dc:Bounds x="535" y="666" width="47" height="14" />
</bpmndi:BPMNLabel>
</bpmndi:BPMNShape>
<bpmndi:BPMNEdge id="SequenceFlow_1goon4z_di" bpmnElement="SequenceFlow_1goon4z">
<di:waypoint x="423" y="608" />
<di:waypoint x="423" y="641" />
<di:waypoint x="540" y="641" />
<bpmndi:BPMNLabel>
<dc:Bounds x="443" y="647" width="45" height="14" />
</bpmndi:BPMNLabel>
</bpmndi:BPMNEdge>
<bpmndi:BPMNEdge id="SequenceFlow_10d2jhh_di" bpmnElement="SequenceFlow_10d2jhh">
<di:waypoint x="454" y="428" />
<di:waypoint x="552" y="428" />
</bpmndi:BPMNEdge>
<bpmndi:BPMNShape id="endEvent" bpmnElement="endEvent">
<dc:Bounds x="552" y="112" width="36" height="36" />
</bpmndi:BPMNShape>
<bpmndi:BPMNEdge id="SequenceFlow_1kpkmd0_di" bpmnElement="SequenceFlow_1kpkmd0">
<di:waypoint x="486" y="130" />
<di:waypoint x="552" y="130" />
</bpmndi:BPMNEdge>
<bpmndi:BPMNShape id="EndEvent_03hsdez_di" bpmnElement="EndEvent_03hsdez">
<dc:Bounds x="552" y="264" width="36" height="36" />
</bpmndi:BPMNShape>
<bpmndi:BPMNEdge id="SequenceFlow_0avs127_di" bpmnElement="SequenceFlow_0avs127">
<di:waypoint x="486" y="282" />
<di:waypoint x="552" y="282" />
</bpmndi:BPMNEdge>
</bpmndi:BPMNPlane>
</bpmndi:BPMNDiagram>
</bpmn:definitions>
`;
export {mockComplexProcess};
``` | /content/code_sandbox/operate/client/src/modules/mocks/mockComplexProcess.ts | xml | 2016-03-20T03:38:04 | 2024-08-16T19:59:58 | camunda | camunda/camunda | 3,172 | 3,557 |
```xml
/*
* Wire
*
* This program is free software: you can redistribute it and/or modify
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* along with this program. If not, see path_to_url
*
*/
import type {FileAsset} from './FileAsset';
import type {Location as LocationAsset} from './Location';
import type {MediumImage as MediumImageAsset} from './MediumImage';
import type {Text as TextAsset} from './Text';
import {AssetType} from '../../assets/AssetType';
export interface AssetPayload {
id: string;
key: string;
size: string;
type: string;
}
export class Asset {
public file_type?: string;
public file_name?: string;
public id?: string;
public key: string;
public size: string;
public type: string;
public text: string;
constructor(id?: string) {
this.id = id;
this.key = '';
this.type = '';
this.text = '';
}
isDownloadable(): boolean {
return this.isAudio() || this.isFile() || this.isVideo() || this.isImage();
}
isImage(): this is MediumImageAsset {
return this.type === AssetType.IMAGE;
}
isText(): this is TextAsset {
return this.type === AssetType.TEXT;
}
isFile(): this is FileAsset {
return this.type === AssetType.FILE && !this.isVideo() && !this.isAudio();
}
isLocation(): this is LocationAsset {
return this.type === AssetType.LOCATION;
}
isVideo(): boolean {
const is_video_asset = this.type === AssetType.FILE && this.file_type?.startsWith('video');
if (is_video_asset) {
const can_play = document.createElement('video').canPlayType(this.file_type);
if (can_play !== '') {
return true;
}
}
return false;
}
isAudio(): boolean {
const is_audio_asset = this.type === AssetType.FILE && this.file_type?.startsWith('audio');
if (is_audio_asset) {
const can_play = document.createElement('audio').canPlayType(this.file_type);
if (can_play !== '') {
return true;
}
}
return false;
}
isButton(): boolean {
return this.type === AssetType.BUTTON;
}
}
``` | /content/code_sandbox/src/script/entity/message/Asset.ts | xml | 2016-07-21T15:34:05 | 2024-08-16T11:40:13 | wire-webapp | wireapp/wire-webapp | 1,125 | 542 |
```xml
import type { PassCoreMethod, PassCoreParams, PassCoreResult, PassCoreService } from '@proton/pass/lib/core/types';
import { type MessageWithSenderFactory, sendMessage } from '@proton/pass/lib/extension/message';
import { WorkerMessageType } from '@proton/pass/types';
export const createCoreServiceBridge = (messageFactory: MessageWithSenderFactory): PassCoreService => ({
exec: async <T extends PassCoreMethod>(method: T, ...args: PassCoreParams<T>) => {
const res = await sendMessage(
messageFactory({
type: WorkerMessageType.PASS_CORE_RPC,
payload: { method, args },
})
);
if (res.type === 'error') throw new Error(res.error);
return res.result as PassCoreResult<T>;
},
});
``` | /content/code_sandbox/applications/pass-extension/src/lib/services/core.bridge.ts | xml | 2016-06-08T11:16:51 | 2024-08-16T14:14:27 | WebClients | ProtonMail/WebClients | 4,300 | 168 |
```xml
export function distanceAB(a, b) {
return distance(a.x, a.y, b.x, b.y);
}
export function distance(x1, y1, x2, y2) {
const dx = x1 - x2;
const dy = y1 - y2;
return Math.sqrt(dx * dx + dy * dy);
}
export function distanceAB3(a, b) {
return distance3(a.x, a.y, a.z, b.x, b.y, b.z);
}
export function distance3(x1, y1, z1, x2, y2, z2) {
return Math.sqrt(distanceSquared3(x1, y1, z1, x2, y2, z2));
}
export function distanceSquaredAB3(a, b) {
return distanceSquared3(a.x, a.y, a.z, b.x, b.y, b.z);
}
export function distanceSquaredANegB3(a, b) {
return distanceSquared3(a.x, a.y, a.z, -b.x, -b.y, -b.z);
}
export function distanceSquared3(x1, y1, z1, x2, y2, z2) {
const dx = x1 - x2;
const dy = y1 - y2;
const dz = z1 - z2;
return dx * dx + dy * dy + dz * dz;
}
export function distanceSquared(x1, y1, x2, y2) {
const dx = x1 - x2;
const dy = y1 - y2;
return dx * dx + dy * dy;
}
``` | /content/code_sandbox/modules/math/distance.ts | xml | 2016-08-26T21:55:19 | 2024-08-15T01:02:53 | jsketcher | xibyte/jsketcher | 1,461 | 349 |
```xml
/*
* Squidex Headless CMS
*
* @license
*/
import { TestBed } from '@angular/core/testing';
import { Router } from '@angular/router';
import { firstValueFrom, of } from 'rxjs';
import { IMock, It, Mock, Times } from 'typemoq';
import { ContentDto, ContentsState } from '@app/shared/internal';
import { contentMustExistGuard } from './content-must-exist.guard';
describe('ContentMustExistGuard', () => {
let router: IMock<Router>;
let contentsState: IMock<ContentsState>;
beforeEach(() => {
router = Mock.ofType<Router>();
contentsState = Mock.ofType<ContentsState>();
TestBed.configureTestingModule({
providers: [
{
provide: ContentsState,
useValue: contentsState.object,
},
{
provide: Router,
useValue: router.object,
},
],
});
});
bit('should load content and return true if found', async () => {
contentsState.setup(x => x.select('123'))
.returns(() => of(<ContentDto>{}));
const route: any = {
params: {
contentId: '123',
},
};
const result = await firstValueFrom(contentMustExistGuard(route));
expect(result).toBeTruthy();
router.verify(x => x.navigate(It.isAny()), Times.never());
});
bit('should load content and return false if not found', async () => {
contentsState.setup(x => x.select('123'))
.returns(() => of(null));
const route: any = {
params: {
contentId: '123',
},
};
const result = await firstValueFrom(contentMustExistGuard(route));
expect(result).toBeFalsy();
router.verify(x => x.navigate(['/404']), Times.once());
});
bit('should unset content if content id is undefined', async () => {
contentsState.setup(x => x.select(null))
.returns(() => of(null));
const route: any = {
params: {
contentId: undefined,
},
};
const result = await firstValueFrom(contentMustExistGuard(route));
expect(result!).toBeTruthy();
contentsState.verify(x => x.select(null), Times.once());
});
bit('should unset content if content id is <new>', async () => {
contentsState.setup(x => x.select(null))
.returns(() => of(null));
const route: any = {
params: {
contentId: 'new',
},
};
const result = await firstValueFrom(contentMustExistGuard(route));
expect(result!).toBeTruthy();
contentsState.verify(x => x.select(null), Times.once());
});
});
function bit(name: string, assertion: (() => PromiseLike<any>) | (() => void)) {
it(name, () => {
return TestBed.runInInjectionContext(() => assertion());
});
}
``` | /content/code_sandbox/frontend/src/app/shared/guards/content-must-exist.guard.spec.ts | xml | 2016-08-29T05:53:40 | 2024-08-16T17:39:38 | squidex | Squidex/squidex | 2,222 | 612 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="path_to_url"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="16dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="@string/update_found_new_version"
android:textColor="#030303"
android:textSize="20sp" />
<TextView
android:id="@+id/common_update_dialog_msg"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="14dp"
android:textColor="#030303"
android:textSize="16sp" />
</LinearLayout>
``` | /content/code_sandbox/playground/android/playground/src/main/res/layout/common_update_notify_dialog.xml | xml | 2016-03-11T10:18:11 | 2024-08-16T06:43:02 | weex | alibaba/weex | 18,250 | 177 |
```xml
/* tslint:disable:no-unused-variable */
// Subject imported before Observable to bypass circular dependency issue since
// Subject extends Observable and Observable references Subject in it's
// definition
export {Subject, AnonymousSubject} from './Subject';
/* tslint:enable:no-unused-variable */
export {Observable} from './Observable';
export { config } from './config';
// statics
/* tslint:disable:no-use-before-declare */
import 'rxjs-compat/add/observable/bindCallback';
import 'rxjs-compat/add/observable/bindNodeCallback';
import 'rxjs-compat/add/observable/combineLatest';
import 'rxjs-compat/add/observable/concat';
import 'rxjs-compat/add/observable/defer';
import 'rxjs-compat/add/observable/empty';
import 'rxjs-compat/add/observable/forkJoin';
import 'rxjs-compat/add/observable/from';
import 'rxjs-compat/add/observable/fromEvent';
import 'rxjs-compat/add/observable/fromEventPattern';
import 'rxjs-compat/add/observable/fromPromise';
import 'rxjs-compat/add/observable/generate';
import 'rxjs-compat/add/observable/if';
import 'rxjs-compat/add/observable/interval';
import 'rxjs-compat/add/observable/merge';
import 'rxjs-compat/add/observable/race';
import 'rxjs-compat/add/observable/never';
import 'rxjs-compat/add/observable/of';
import 'rxjs-compat/add/observable/onErrorResumeNext';
import 'rxjs-compat/add/observable/pairs';
import 'rxjs-compat/add/observable/range';
import 'rxjs-compat/add/observable/using';
import 'rxjs-compat/add/observable/throw';
import 'rxjs-compat/add/observable/timer';
import 'rxjs-compat/add/observable/zip';
//dom
import 'rxjs-compat/add/observable/dom/ajax';
import 'rxjs-compat/add/observable/dom/webSocket';
//internal/operators
import 'rxjs-compat/add/operator/buffer';
import 'rxjs-compat/add/operator/bufferCount';
import 'rxjs-compat/add/operator/bufferTime';
import 'rxjs-compat/add/operator/bufferToggle';
import 'rxjs-compat/add/operator/bufferWhen';
import 'rxjs-compat/add/operator/catch';
import 'rxjs-compat/add/operator/combineAll';
import 'rxjs-compat/add/operator/combineLatest';
import 'rxjs-compat/add/operator/concat';
import 'rxjs-compat/add/operator/concatAll';
import 'rxjs-compat/add/operator/concatMap';
import 'rxjs-compat/add/operator/concatMapTo';
import 'rxjs-compat/add/operator/count';
import 'rxjs-compat/add/operator/dematerialize';
import 'rxjs-compat/add/operator/debounce';
import 'rxjs-compat/add/operator/debounceTime';
import 'rxjs-compat/add/operator/defaultIfEmpty';
import 'rxjs-compat/add/operator/delay';
import 'rxjs-compat/add/operator/delayWhen';
import 'rxjs-compat/add/operator/distinct';
import 'rxjs-compat/add/operator/distinctUntilChanged';
import 'rxjs-compat/add/operator/distinctUntilKeyChanged';
import 'rxjs-compat/add/operator/do';
import 'rxjs-compat/add/operator/exhaust';
import 'rxjs-compat/add/operator/exhaustMap';
import 'rxjs-compat/add/operator/expand';
import 'rxjs-compat/add/operator/elementAt';
import 'rxjs-compat/add/operator/filter';
import 'rxjs-compat/add/operator/finally';
import 'rxjs-compat/add/operator/find';
import 'rxjs-compat/add/operator/findIndex';
import 'rxjs-compat/add/operator/first';
import 'rxjs-compat/add/operator/groupBy';
import 'rxjs-compat/add/operator/ignoreElements';
import 'rxjs-compat/add/operator/isEmpty';
import 'rxjs-compat/add/operator/audit';
import 'rxjs-compat/add/operator/auditTime';
import 'rxjs-compat/add/operator/last';
import 'rxjs-compat/add/operator/let';
import 'rxjs-compat/add/operator/every';
import 'rxjs-compat/add/operator/map';
import 'rxjs-compat/add/operator/mapTo';
import 'rxjs-compat/add/operator/materialize';
import 'rxjs-compat/add/operator/max';
import 'rxjs-compat/add/operator/merge';
import 'rxjs-compat/add/operator/mergeAll';
import 'rxjs-compat/add/operator/mergeMap';
import 'rxjs-compat/add/operator/mergeMapTo';
import 'rxjs-compat/add/operator/mergeScan';
import 'rxjs-compat/add/operator/min';
import 'rxjs-compat/add/operator/multicast';
import 'rxjs-compat/add/operator/observeOn';
import 'rxjs-compat/add/operator/onErrorResumeNext';
import 'rxjs-compat/add/operator/pairwise';
import 'rxjs-compat/add/operator/partition';
import 'rxjs-compat/add/operator/pluck';
import 'rxjs-compat/add/operator/publish';
import 'rxjs-compat/add/operator/publishBehavior';
import 'rxjs-compat/add/operator/publishReplay';
import 'rxjs-compat/add/operator/publishLast';
import 'rxjs-compat/add/operator/race';
import 'rxjs-compat/add/operator/reduce';
import 'rxjs-compat/add/operator/repeat';
import 'rxjs-compat/add/operator/repeatWhen';
import 'rxjs-compat/add/operator/retry';
import 'rxjs-compat/add/operator/retryWhen';
import 'rxjs-compat/add/operator/sample';
import 'rxjs-compat/add/operator/sampleTime';
import 'rxjs-compat/add/operator/scan';
import 'rxjs-compat/add/operator/sequenceEqual';
import 'rxjs-compat/add/operator/share';
import 'rxjs-compat/add/operator/shareReplay';
import 'rxjs-compat/add/operator/single';
import 'rxjs-compat/add/operator/skip';
import 'rxjs-compat/add/operator/skipLast';
import 'rxjs-compat/add/operator/skipUntil';
import 'rxjs-compat/add/operator/skipWhile';
import 'rxjs-compat/add/operator/startWith';
import 'rxjs-compat/add/operator/subscribeOn';
import 'rxjs-compat/add/operator/switch';
import 'rxjs-compat/add/operator/switchMap';
import 'rxjs-compat/add/operator/switchMapTo';
import 'rxjs-compat/add/operator/take';
import 'rxjs-compat/add/operator/takeLast';
import 'rxjs-compat/add/operator/takeUntil';
import 'rxjs-compat/add/operator/takeWhile';
import 'rxjs-compat/add/operator/throttle';
import 'rxjs-compat/add/operator/throttleTime';
import 'rxjs-compat/add/operator/timeInterval';
import 'rxjs-compat/add/operator/timeout';
import 'rxjs-compat/add/operator/timeoutWith';
import 'rxjs-compat/add/operator/timestamp';
import 'rxjs-compat/add/operator/toArray';
import 'rxjs-compat/add/operator/toPromise';
import 'rxjs-compat/add/operator/window';
import 'rxjs-compat/add/operator/windowCount';
import 'rxjs-compat/add/operator/windowTime';
import 'rxjs-compat/add/operator/windowToggle';
import 'rxjs-compat/add/operator/windowWhen';
import 'rxjs-compat/add/operator/withLatestFrom';
import 'rxjs-compat/add/operator/zip';
import 'rxjs-compat/add/operator/zipAll';
/* tslint:disable:no-unused-variable */
export {Operator} from './Operator';
export {Observer} from './types';
export {Subscription} from './Subscription';
export {Subscriber} from './Subscriber';
export {AsyncSubject} from './AsyncSubject';
export {ReplaySubject} from './ReplaySubject';
export {BehaviorSubject} from './BehaviorSubject';
export {ConnectableObservable} from './observable/ConnectableObservable';
export {Notification} from './Notification';
export {EmptyError} from './util/EmptyError';
export {ArgumentOutOfRangeError} from './util/ArgumentOutOfRangeError';
export {ObjectUnsubscribedError} from './util/ObjectUnsubscribedError';
export {TimeoutError} from './util/TimeoutError';
export {UnsubscriptionError} from './util/UnsubscriptionError';
export {TimeInterval} from './operators/timeInterval';
export {Timestamp} from './operators/timestamp';
export {TestScheduler} from './testing/TestScheduler';
export {VirtualTimeScheduler} from './scheduler/VirtualTimeScheduler';
export {AjaxRequest, AjaxResponse, AjaxError, AjaxTimeoutError} from './observable/dom/AjaxObservable';
export { pipe } from './util/pipe';
import { asap } from './scheduler/asap';
import { async } from './scheduler/async';
import { queue } from './scheduler/queue';
import { animationFrame } from './scheduler/animationFrame';
import { AsapScheduler } from './scheduler/AsapScheduler';
import { AsyncScheduler } from './scheduler/AsyncScheduler';
import { QueueScheduler } from './scheduler/QueueScheduler';
import { AnimationFrameScheduler } from './scheduler/AnimationFrameScheduler';
import { rxSubscriber } from './symbol/rxSubscriber';
import { iterator } from './symbol/iterator';
import { observable } from './symbol/observable';
import * as _operators from './operators/index';
export const operators = _operators;
/* tslint:enable:no-unused-variable */
/**
* @typedef {Object} Rx.Scheduler
* @property {SchedulerLike} asap Schedules on the micro task queue, which is the same
* queue used for promises. Basically after the current job, but before the next job.
* Use this for asynchronous conversions.
* @property {SchedulerLike} queue Schedules on a queue in the current event frame
* (trampoline scheduler). Use this for iteration operations.
* @property {SchedulerLike} animationFrame Schedules work with `requestAnimationFrame`.
* Use this for synchronizing with the platform's painting.
* @property {SchedulerLike} async Schedules work with `setInterval`. Use this for
* time-based operations.
*/
let Scheduler = {
asap,
queue,
animationFrame,
async
};
/**
* @typedef {Object} Rx.Symbol
* @property {Symbol|string} rxSubscriber A symbol to use as a property name to
* retrieve an "Rx safe" Observer from an object. "Rx safety" can be defined as
* an object that has all of the traits of an Rx Subscriber, including the
* ability to add and remove subscriptions to the subscription chain and
* guarantees involving event triggering (can't "next" after unsubscription,
* etc).
* @property {Symbol|string} observable A symbol to use as a property name to
* retrieve an Observable as defined by the [ECMAScript "Observable" spec](path_to_url
* @property {Symbol|string} iterator The ES6 symbol to use as a property name
* to retrieve an iterator from an object.
*/
let Symbol = {
rxSubscriber,
observable,
iterator
};
export {
Scheduler,
Symbol
};
``` | /content/code_sandbox/deps/node-10.15.3/tools/node_modules/eslint/node_modules/rxjs/src/internal/Rx.ts | xml | 2016-09-05T10:18:44 | 2024-08-11T13:21:40 | LiquidCore | LiquidPlayer/LiquidCore | 1,010 | 2,200 |
```xml
export const TERM_GROUP_REQUEST = 'TERM_GROUP_REQUEST';
export const TERM_GROUP_EXIT = 'TERM_GROUP_EXIT';
export const TERM_GROUP_RESIZE = 'TERM_GROUP_RESIZE';
export const TERM_GROUP_EXIT_ACTIVE = 'TERM_GROUP_EXIT_ACTIVE';
export enum DIRECTION {
HORIZONTAL = 'HORIZONTAL',
VERTICAL = 'VERTICAL'
}
export interface TermGroupRequestAction {
type: typeof TERM_GROUP_REQUEST;
}
export interface TermGroupExitAction {
type: typeof TERM_GROUP_EXIT;
uid: string;
}
export interface TermGroupResizeAction {
type: typeof TERM_GROUP_RESIZE;
uid: string;
sizes: number[];
}
export interface TermGroupExitActiveAction {
type: typeof TERM_GROUP_EXIT_ACTIVE;
}
export type TermGroupActions =
| TermGroupRequestAction
| TermGroupExitAction
| TermGroupResizeAction
| TermGroupExitActiveAction;
``` | /content/code_sandbox/typings/constants/term-groups.d.ts | xml | 2016-07-01T06:01:21 | 2024-08-16T16:05:22 | hyper | vercel/hyper | 43,095 | 188 |
```xml
export * from './CarouselButton';
export * from './CarouselButton.types';
export * from './renderCarouselButton';
export * from './useCarouselButton';
export * from './useCarouselButtonStyles.styles';
``` | /content/code_sandbox/packages/react-components/react-carousel-preview/library/src/components/CarouselButton/index.ts | xml | 2016-06-06T15:03:44 | 2024-08-16T18:49:29 | fluentui | microsoft/fluentui | 18,221 | 42 |
```xml
import type { IDropdownStyleProps, IDropdownStyles, IStyleFunctionOrObject } from '@fluentui/react';
import { FontWeights } from '@fluentui/react';
export function getDropdownStyles(
props: IDropdownStyleProps,
): IStyleFunctionOrObject<IDropdownStyleProps, IDropdownStyles> {
const { theme } = props;
return {
dropdown: {
selectors: {
'&:focus:after': {
borderRadius: theme?.effects.roundedCorner4,
},
},
},
title: { borderRadius: theme?.effects.roundedCorner4 },
caretDown: { color: theme?.palette.neutralQuaternary },
label: { fontWeight: FontWeights.regular },
};
}
``` | /content/code_sandbox/packages/fluent2-theme/src/componentStyles/HoverCard.styles.ts | xml | 2016-06-06T15:03:44 | 2024-08-16T18:49:29 | fluentui | microsoft/fluentui | 18,221 | 156 |
```xml
<!-- drawable/weather-cloudy.xml -->
<vector xmlns:android="path_to_url"
xmlns:tools="path_to_url"
android:height="24dp"
android:width="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path android:fillColor="#5f6267" android:pathData="M6,19A5,5 0 0,1 1,14A5,5 0 0,1 6,9C7,6.65 9.3,5 12,5C15.43,5 18.24,7.66 18.5,11.03L19,11A4,4 0 0,1 23,15A4,4 0 0,1 19,19H6M19,13H17V12A5,5 0 0,0 12,7C9.5,7 7.45,8.82 7.06,11.19C6.73,11.07 6.37,11 6,11A3,3 0 0,0 3,14A3,3 0 0,0 6,17H19A2,2 0 0,0 21,15A2,2 0 0,0 19,13Z"
tools:ignore="VectorRaster" />
</vector>
``` | /content/code_sandbox/app/src/main/res/drawable/ic_weather.xml | xml | 2016-02-21T04:39:19 | 2024-08-16T13:35:51 | GeometricWeather | WangDaYeeeeee/GeometricWeather | 2,420 | 313 |
```xml
export * from '../build/providers/Facebook';
``` | /content/code_sandbox/packages/expo-auth-session/providers/facebook.d.ts | xml | 2016-08-15T17:14:25 | 2024-08-16T19:54:44 | expo | expo/expo | 32,004 | 10 |
```xml
import type { ComponentType, ReactNode } from 'react';
import type { SortableContainerProps } from 'react-sortable-hoc';
import { SortableContainer } from 'react-sortable-hoc';
interface Props extends SortableContainerProps {
children: ReactNode;
}
const OrderableContainer = SortableContainer(({ children }: Props) => children) as ComponentType<Props>;
export default OrderableContainer;
``` | /content/code_sandbox/packages/components/components/orderable/OrderableContainer.tsx | xml | 2016-06-08T11:16:51 | 2024-08-16T14:14:27 | WebClients | ProtonMail/WebClients | 4,300 | 86 |
```xml
export const GOOGLE_MAP_LINKS = [
{
zh: '',
en: `My Foodie Map`,
url: 'path_to_url
},
{
zh: '',
en: 'My map reviews',
url: 'path_to_url
},
{
zh: '',
en: `Places I've been to`,
url: 'path_to_url
},
{
zh: '',
en: `Places I want to go`,
url: 'path_to_url
}
]
``` | /content/code_sandbox/src/pages/about/footprint/google-map.ts | xml | 2016-09-23T02:02:33 | 2024-08-16T03:13:52 | surmon.me | surmon-china/surmon.me | 2,092 | 111 |
```xml
import {
createResolver as _createResolver,
type ResolveFunction,
type ResolverFactoryOptions,
} from '@pnpm/default-resolver'
import { type AgentOptions, createFetchFromRegistry } from '@pnpm/fetch'
import { type SslConfig } from '@pnpm/types'
import { type FetchFromRegistry, type GetAuthHeader, type RetryTimeoutOptions } from '@pnpm/fetching-types'
import type { CustomFetchers, GitFetcher, DirectoryFetcher } from '@pnpm/fetcher-base'
import { createDirectoryFetcher } from '@pnpm/directory-fetcher'
import { createGitFetcher } from '@pnpm/git-fetcher'
import { createTarballFetcher, type TarballFetchers } from '@pnpm/tarball-fetcher'
import { createGetAuthHeaderByURI } from '@pnpm/network.auth-header'
import mapValues from 'ramda/src/map'
export type { ResolveFunction }
export type ClientOptions = {
authConfig: Record<string, string>
customFetchers?: CustomFetchers
ignoreScripts?: boolean
rawConfig: Record<string, string>
sslConfigs?: Record<string, SslConfig>
retry?: RetryTimeoutOptions
timeout?: number
unsafePerm?: boolean
userAgent?: string
userConfig?: Record<string, string>
gitShallowHosts?: string[]
resolveSymlinksInInjectedDirs?: boolean
includeOnlyPackageFiles?: boolean
} & ResolverFactoryOptions & AgentOptions
export interface Client {
fetchers: Fetchers
resolve: ResolveFunction
clearResolutionCache: () => void
}
export function createClient (opts: ClientOptions): Client {
const fetchFromRegistry = createFetchFromRegistry(opts)
const getAuthHeader = createGetAuthHeaderByURI({ allSettings: opts.authConfig, userSettings: opts.userConfig })
const { resolve, clearCache: clearResolutionCache } = _createResolver(fetchFromRegistry, getAuthHeader, opts)
return {
fetchers: createFetchers(fetchFromRegistry, getAuthHeader, opts, opts.customFetchers),
resolve,
clearResolutionCache,
}
}
export function createResolver (opts: ClientOptions): { resolve: ResolveFunction, clearCache: () => void } {
const fetchFromRegistry = createFetchFromRegistry(opts)
const getAuthHeader = createGetAuthHeaderByURI({ allSettings: opts.authConfig, userSettings: opts.userConfig })
return _createResolver(fetchFromRegistry, getAuthHeader, opts)
}
type Fetchers = {
git: GitFetcher
directory: DirectoryFetcher
} & TarballFetchers
function createFetchers (
fetchFromRegistry: FetchFromRegistry,
getAuthHeader: GetAuthHeader,
opts: Pick<ClientOptions, 'rawConfig' | 'retry' | 'gitShallowHosts' | 'resolveSymlinksInInjectedDirs' | 'unsafePerm' | 'includeOnlyPackageFiles'>,
customFetchers?: CustomFetchers
): Fetchers {
const defaultFetchers = {
...createTarballFetcher(fetchFromRegistry, getAuthHeader, opts),
...createGitFetcher(opts),
...createDirectoryFetcher({ resolveSymlinks: opts.resolveSymlinksInInjectedDirs, includeOnlyPackageFiles: opts.includeOnlyPackageFiles }),
}
const overwrites = mapValues(
(factory: any) => factory({ defaultFetchers }), // eslint-disable-line @typescript-eslint/no-explicit-any
customFetchers ?? {} as any // eslint-disable-line @typescript-eslint/no-explicit-any
)
return {
...defaultFetchers,
...overwrites,
}
}
``` | /content/code_sandbox/pkg-manager/client/src/index.ts | xml | 2016-01-28T07:40:43 | 2024-08-16T12:38:47 | pnpm | pnpm/pnpm | 28,869 | 774 |
```xml
export interface PackageInfo extends PackageSummary {
homepage?: string;
initStrykerConfig?: Record<string, unknown>;
}
export interface PackageSummary {
name: string;
keywords: string[];
version: string;
}
``` | /content/code_sandbox/packages/core/src/initializer/package-info.ts | xml | 2016-02-12T13:14:28 | 2024-08-15T18:38:25 | stryker-js | stryker-mutator/stryker-js | 2,561 | 48 |
```xml
import * as React from 'react';
import { Divider } from '@fluentui/react-northstar';
const DividerExampleContent = () => <Divider>Some text</Divider>;
export default DividerExampleContent;
``` | /content/code_sandbox/packages/fluentui/docs/src/examples/components/Divider/Types/DividerExampleContent.tsx | xml | 2016-06-06T15:03:44 | 2024-08-16T18:49:29 | fluentui | microsoft/fluentui | 18,221 | 44 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="path_to_url" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="ru" original="../LocalizableStrings.resx">
<body>
<trans-unit id="AddProjectSolutionFolderArgumentDescription">
<source>The destination solution folder path to add the projects to.</source>
<target state="translated"> , .</target>
<note />
</trans-unit>
<trans-unit id="AppFullName">
<source>.NET modify solution file command</source>
<target state="translated"> .NET " "</target>
<note />
</trans-unit>
<trans-unit id="AppDescription">
<source>Command to add, remove, and list projects from the solution (SLN) file.</source>
<target state="translated"> , (SLN) .</target>
<note />
</trans-unit>
<trans-unit id="AppHelpText">
<source>Projects to add or to remove from the solution.</source>
<target state="translated">, .</target>
<note />
</trans-unit>
<trans-unit id="AddAppFullName">
<source>Add one or more projects to a solution file.</source>
<target state="translated"> .</target>
<note />
</trans-unit>
<trans-unit id="InRoot">
<source>Place project in root of the solution, rather than creating a solution folder.</source>
<target state="translated"> .</target>
<note />
</trans-unit>
<trans-unit id="ListSolutionFoldersArgumentDescription">
<source>Display solution folder paths.</source>
<target state="translated"> .</target>
<note />
</trans-unit>
<trans-unit id="RemoveAppFullName">
<source>Remove one or more projects from a solution file.</source>
<target state="translated"> .</target>
<note />
</trans-unit>
<trans-unit id="RemoveSubcommandHelpText">
<source>Remove the specified project(s) from the solution. The project is not impacted.</source>
<target state="translated"> . .</target>
<note />
</trans-unit>
<trans-unit id="ListAppFullName">
<source>List all projects in a solution file.</source>
<target state="translated"> .</target>
<note />
</trans-unit>
<trans-unit id="ListSubcommandHelpText">
<source>List all projects in the solution.</source>
<target state="translated"> .</target>
<note />
</trans-unit>
<trans-unit id="SolutionArgumentName">
<source>SLN_FILE</source>
<target state="translated">SLN_FILE</target>
<note />
</trans-unit>
<trans-unit id="SolutionArgumentDescription">
<source>The solution file to operate on. If not specified, the command will search the current directory for one.</source>
<target state="translated"> . , .</target>
<note />
</trans-unit>
<trans-unit id="AddProjectPathArgumentName">
<source>PROJECT_PATH</source>
<target state="translated">PROJECT_PATH</target>
<note />
</trans-unit>
<trans-unit id="AddProjectPathArgumentDescription">
<source>The paths to the projects to add to the solution.</source>
<target state="translated"> , .</target>
<note />
</trans-unit>
<trans-unit id="RemoveProjectPathArgumentName">
<source>PROJECT_PATH</source>
<target state="translated">PROJECT_PATH</target>
<note />
</trans-unit>
<trans-unit id="RemoveProjectPathArgumentDescription">
<source>The paths to the projects to remove from the solution.</source>
<target state="translated"> , .</target>
<note />
</trans-unit>
<trans-unit id="ProjectsHeader">
<source>Project(s)</source>
<target state="translated"></target>
<note />
</trans-unit>
<trans-unit id="SolutionFolderAndInRootMutuallyExclusive">
<source>The --solution-folder and --in-root options cannot be used together; use only one of the options.</source>
<target state="translated"> --solution-folder --in-root options ; .</target>
<note />
</trans-unit>
<trans-unit id="SolutionFolderHeader">
<source>Solution Folder(s)</source>
<target state="translated"> </target>
<note />
</trans-unit>
</body>
</file>
</xliff>
``` | /content/code_sandbox/src/Cli/dotnet/commands/dotnet-sln/xlf/LocalizableStrings.ru.xlf | xml | 2016-07-22T21:26:02 | 2024-08-16T17:23:58 | sdk | dotnet/sdk | 2,627 | 1,099 |
```xml
import { existsSync } from 'fs';
import { join } from 'path';
import { ConfigError } from './Errors';
export function getRootPackageJsonPath(projectRoot: string): string {
const packageJsonPath = join(projectRoot, 'package.json');
if (!existsSync(packageJsonPath)) {
throw new ConfigError(
`The expected package.json path: ${packageJsonPath} does not exist`,
'MODULE_NOT_FOUND'
);
}
return packageJsonPath;
}
``` | /content/code_sandbox/packages/@expo/config/src/resolvePackageJson.ts | xml | 2016-08-15T17:14:25 | 2024-08-16T19:54:44 | expo | expo/expo | 32,004 | 105 |
```xml
import Table from '@erxes/ui/src/components/table';
import { __ } from 'coreui/utils';
import React from 'react';
import TransactionRow from './TransactionRow';
import { ITransaction } from '../../../transactions/types';
interface IProps {
transactions: ITransaction[];
}
const TransactionList = (props: IProps) => {
const { transactions } = props;
return (
<Table $striped>
<thead>
<tr>
<th>{__('Date')}</th>
<th>{__('Type')}</th>
<th>{__('Loan Payment')}</th>
<th>{__('Interest')}</th>
<th>{__('Loss')}</th>
<th>{__('Total')}</th>
</tr>
</thead>
<tbody id="schedules">
{transactions.map((transaction) => (
<TransactionRow
transaction={transaction}
key={transaction._id}
></TransactionRow>
))}
</tbody>
</Table>
);
};
export default TransactionList;
``` | /content/code_sandbox/packages/plugin-loans-ui/src/contracts/components/transaction/TransactionList.tsx | xml | 2016-11-11T06:54:50 | 2024-08-16T10:26:06 | erxes | erxes/erxes | 3,479 | 215 |
```xml
<?xml version="1.0" encoding="UTF-8"?>
<document filename='bm_eu-026-reg.xml'>
<table id='1'>
<region id='1' page='4'>
<instruction instr-id='505'/>
<instruction instr-id='511'/>
<instruction instr-id='517'/>
<instruction instr-id='523'/>
<instruction instr-id='529'/>
<instruction instr-id='535'/>
<instruction instr-id='541'/>
<instruction instr-id='547'/>
<instruction instr-id='553'/>
<instruction instr-id='559'/>
<instruction instr-id='565'/>
<instruction instr-id='571'/>
<instruction instr-id='577'/>
<instruction instr-id='594'/>
<instruction instr-id='600'/>
<instruction instr-id='606'/>
<instruction instr-id='612'/>
<instruction instr-id='618'/>
<instruction instr-id='624'/>
<instruction instr-id='630'/>
<instruction instr-id='642'/>
<instruction instr-id='648'/>
<instruction instr-id='654'/>
<instruction instr-id='660'/>
<instruction instr-id='666'/>
<instruction instr-id='672'/>
<instruction instr-id='678'/>
<instruction instr-id='684'/>
<instruction instr-id='690'/>
<instruction instr-id='696'/>
<instruction instr-id='702'/>
<instruction instr-id='714'/>
<instruction instr-id='720'/>
<instruction instr-id='726'/>
<instruction instr-id='732'/>
<instruction instr-id='738'/>
<instruction instr-id='744'/>
<instruction instr-id='750'/>
<instruction instr-id='756'/>
<instruction instr-id='762'/>
<instruction instr-id='768'/>
<instruction instr-id='774'/>
<instruction instr-id='780'/>
<instruction instr-id='792'/>
<instruction instr-id='798'/>
<instruction instr-id='804'/>
<instruction instr-id='810'/>
<instruction instr-id='827'/>
<instruction instr-id='833'/>
<instruction instr-id='845'/>
<instruction instr-id='851'/>
<instruction instr-id='857'/>
<instruction instr-id='863'/>
<bounding-box x1='80' y1='643' x2='503' y2='718'/>
</region>
</table>
<table id='2'>
<region id='1' page='5'>
<instruction instr-id='712'/>
<instruction instr-id='718'/>
<instruction instr-id='724'/>
<instruction instr-id='730'/>
<instruction instr-id='736'/>
<instruction instr-id='748'/>
<instruction instr-id='754'/>
<instruction instr-id='760'/>
<instruction instr-id='766'/>
<instruction instr-id='772'/>
<instruction instr-id='778'/>
<instruction instr-id='795'/>
<instruction instr-id='807'/>
<instruction instr-id='813'/>
<instruction instr-id='819'/>
<instruction instr-id='825'/>
<instruction instr-id='837'/>
<instruction instr-id='843'/>
<instruction instr-id='849'/>
<instruction instr-id='855'/>
<instruction instr-id='867'/>
<instruction instr-id='873'/>
<instruction instr-id='879'/>
<instruction instr-id='885'/>
<instruction instr-id='897'/>
<instruction instr-id='903'/>
<instruction instr-id='909'/>
<bounding-box x1='82' y1='575' x2='430' y2='635'/>
</region>
</table>
<table id='3'>
<region id='1' page='6'>
<instruction instr-id='1070'/>
<instruction instr-id='1076'/>
<instruction instr-id='1082'/>
<instruction instr-id='1088'/>
<instruction instr-id='1094'/>
<instruction instr-id='1106'/>
<instruction instr-id='1112'/>
<instruction instr-id='1118'/>
<instruction instr-id='1124'/>
<instruction instr-id='1130'/>
<instruction instr-id='1136'/>
<instruction instr-id='1153'/>
<instruction instr-id='1165'/>
<instruction instr-id='1171'/>
<instruction instr-id='1177'/>
<instruction instr-id='1183'/>
<instruction instr-id='1195'/>
<instruction instr-id='1201'/>
<instruction instr-id='1207'/>
<instruction instr-id='1213'/>
<instruction instr-id='1225'/>
<instruction instr-id='1231'/>
<instruction instr-id='1237'/>
<instruction instr-id='1243'/>
<instruction instr-id='1255'/>
<instruction instr-id='1261'/>
<instruction instr-id='1267'/>
<bounding-box x1='80' y1='519' x2='428' y2='580'/>
</region>
</table>
</document>
``` | /content/code_sandbox/tests/files/tabula/icdar2013-dataset/competition-dataset-eu/eu-026-reg.xml | xml | 2016-06-18T11:48:49 | 2024-08-15T18:32:02 | camelot | atlanhq/camelot | 3,628 | 1,063 |
```xml
import { IconObject } from '../../Icon';
import { StyleProp, TextStyle } from 'react-native';
export interface HeaderIcon extends IconObject {
icon?: string;
text?: string;
color?: string;
style?: StyleProp<TextStyle>;
}
``` | /content/code_sandbox/packages/base/src/Header/components/HeaderIcon.tsx | xml | 2016-09-08T14:21:41 | 2024-08-16T10:11:29 | react-native-elements | react-native-elements/react-native-elements | 24,875 | 54 |
```xml
import { Accessibility, AriaRole } from '../../types';
import { treeBehavior, TreeBehaviorProps } from './treeBehavior';
import { treeItemAsListItemBehavior } from './treeItemAsListItemBehavior';
/**
* @specification
* Adds role 'list' to 'root' slot.
*/
export const treeAsListBehavior: Accessibility<TreeBehaviorProps> = props => {
const behavior = treeBehavior(props);
const definition = {
attributes: {
root: {
...behavior.attributes.root,
role: 'list' as AriaRole,
},
},
keyActions: behavior.keyActions,
focusZone: behavior.focusZone,
childBehaviors: {
item: treeItemAsListItemBehavior,
},
};
if (process.env.NODE_ENV !== 'production') {
definition.attributes.root['data-aa-class'] = 'TreeList';
}
return definition;
};
``` | /content/code_sandbox/packages/fluentui/accessibility/src/behaviors/Tree/treeAsListBehavior.ts | xml | 2016-06-06T15:03:44 | 2024-08-16T18:49:29 | fluentui | microsoft/fluentui | 18,221 | 190 |
```xml
import { startActivityAsync, ActivityAction } from 'expo-intent-launcher';
import React from 'react';
import { Platform, ScrollView, Text, ToastAndroid, View } from 'react-native';
import Button from '../components/Button';
export default class IntentLauncherScreen extends React.Component {
static navigationOptions = {
title: 'IntentLauncher',
};
renderSettingsLink(title: string, activityAction: ActivityAction, intentParams = {}) {
return (
<View>
<Button
onPress={async () => {
try {
const result = await startActivityAsync(activityAction, intentParams);
ToastAndroid.show(`Activity finished: ${JSON.stringify(result)}`, ToastAndroid.SHORT);
} catch (e) {
ToastAndroid.show(`An error occurred: ${e.message}`, ToastAndroid.SHORT);
}
}}
title={title}
style={{ marginBottom: 10 }}
/>
</View>
);
}
render() {
if (Platform.OS !== 'android') {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>IntentLauncherAndroid is only available on Android.</Text>
</View>
);
}
return (
<ScrollView style={{ padding: 10 }}>
{this.renderSettingsLink('Location Settings', ActivityAction.LOCATION_SOURCE_SETTINGS)}
{this.renderSettingsLink('Wireless Settings', ActivityAction.WIRELESS_SETTINGS)}
{this.renderSettingsLink(
'Application Details for Expo Go',
ActivityAction.APPLICATION_DETAILS_SETTINGS,
{
data: 'package:host.exp.exponent',
}
)}
{this.renderSettingsLink(
'Application Details for Play Store',
ActivityAction.APPLICATION_DETAILS_SETTINGS,
{
data: 'package:com.android.vending',
}
)}
{this.renderSettingsLink(
'Application Details for not existing package',
ActivityAction.APPLICATION_DETAILS_SETTINGS,
{
data: 'package:package.name.that.doesnt.exist',
}
)}
</ScrollView>
);
}
}
``` | /content/code_sandbox/apps/native-component-list/src/screens/IntentLauncherScreen.android.tsx | xml | 2016-08-15T17:14:25 | 2024-08-16T19:54:44 | expo | expo/expo | 32,004 | 435 |
```xml
import { Button, Dialog, Input } from '@fluentui/react-northstar';
import * as React from 'react';
const DialogExampleFullWidth: React.FC = () => (
<Dialog
cancelButton="Cancel"
confirmButton="Confirm"
content={<Input fluid />}
header="Full width content"
trigger={<Button content="Open a dialog" />}
/>
);
export default DialogExampleFullWidth;
``` | /content/code_sandbox/packages/fluentui/docs/src/examples/components/Dialog/Content/DialogExampleFullWidth.shorthand.tsx | xml | 2016-06-06T15:03:44 | 2024-08-16T18:49:29 | fluentui | microsoft/fluentui | 18,221 | 88 |
```xml
import Component from './Component';
import { toLowerCase } from '../../utils/mixins';
export default class ComponentTableCell extends Component {
get defaults() {
return {
// @ts-ignore
...super.defaults,
type: 'cell',
tagName: 'td',
draggable: ['tr'],
};
}
static isComponent(el: HTMLElement) {
return ['td', 'th'].indexOf(toLowerCase(el.tagName)) >= 0;
}
}
``` | /content/code_sandbox/src/dom_components/model/ComponentTableCell.ts | xml | 2016-01-22T00:23:19 | 2024-08-16T11:20:59 | grapesjs | GrapesJS/grapesjs | 21,687 | 98 |
```xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<epp xmlns="urn:ietf:params:xml:ns:epp-1.0"
xmlns:xsi="path_to_url">
<command>
<create>
<domain:create
xmlns:domain="urn:ietf:params:xml:ns:domain-1.0">
<domain:name>example.tld</domain:name>
<domain:period unit="y">2</domain:period>
<domain:ns>
<domain:hostObj>ns1.example.net</domain:hostObj>
<domain:hostObj>ns2.example.net</domain:hostObj>
</domain:ns>
<domain:registrant>jd1234</domain:registrant>
<domain:contact type="admin">sh8013</domain:contact>
<domain:contact type="tech">sh8013</domain:contact>
<domain:authInfo>
<domain:pw>2fooBAR</domain:pw>
</domain:authInfo>
</domain:create>
</create>
<extension>
<secDNS:create
xmlns:secDNS="urn:ietf:params:xml:ns:secDNS-1.1">
<secDNS:dsData>
<secDNS:keyTag>12345</secDNS:keyTag>
<secDNS:alg>3</secDNS:alg>
<secDNS:digestType>1</secDNS:digestType>
<secDNS:digest>49FD46E6C4B45C55D4AC</secDNS:digest>
</secDNS:dsData>
<secDNS:dsData>
<secDNS:keyTag>12346</secDNS:keyTag>
<secDNS:alg>3</secDNS:alg>
<secDNS:digestType>1</secDNS:digestType>
<secDNS:digest>49FD46E6C4B45C55D4AC</secDNS:digest>
</secDNS:dsData>
<secDNS:dsData>
<secDNS:keyTag>12347</secDNS:keyTag>
<secDNS:alg>3</secDNS:alg>
<secDNS:digestType>1</secDNS:digestType>
<secDNS:digest>49FD46E6C4B45C55D4AC</secDNS:digest>
</secDNS:dsData>
<secDNS:dsData>
<secDNS:keyTag>12348</secDNS:keyTag>
<secDNS:alg>3</secDNS:alg>
<secDNS:digestType>1</secDNS:digestType>
<secDNS:digest>49FD46E6C4B45C55D4AC</secDNS:digest>
</secDNS:dsData>
<secDNS:dsData>
<secDNS:keyTag>12349</secDNS:keyTag>
<secDNS:alg>3</secDNS:alg>
<secDNS:digestType>1</secDNS:digestType>
<secDNS:digest>49FD46E6C4B45C55D4AC</secDNS:digest>
</secDNS:dsData>
<secDNS:dsData>
<secDNS:keyTag>12350</secDNS:keyTag>
<secDNS:alg>3</secDNS:alg>
<secDNS:digestType>1</secDNS:digestType>
<secDNS:digest>49FD46E6C4B45C55D4AC</secDNS:digest>
</secDNS:dsData>
<secDNS:dsData>
<secDNS:keyTag>12351</secDNS:keyTag>
<secDNS:alg>3</secDNS:alg>
<secDNS:digestType>1</secDNS:digestType>
<secDNS:digest>49FD46E6C4B45C55D4AC</secDNS:digest>
</secDNS:dsData>
<secDNS:dsData>
<secDNS:keyTag>12352</secDNS:keyTag>
<secDNS:alg>3</secDNS:alg>
<secDNS:digestType>1</secDNS:digestType>
<secDNS:digest>49FD46E6C4B45C55D4AC</secDNS:digest>
</secDNS:dsData>
<secDNS:dsData>
<secDNS:keyTag>12353</secDNS:keyTag>
<secDNS:alg>3</secDNS:alg>
<secDNS:digestType>1</secDNS:digestType>
<secDNS:digest>49FD46E6C4B45C55D4AC</secDNS:digest>
</secDNS:dsData>
</secDNS:create>
</extension>
<clTRID>ABC-12345</clTRID>
</command>
</epp>
``` | /content/code_sandbox/core/src/test/resources/google/registry/flows/domain/domain_create_dsdata_9_records.xml | xml | 2016-02-29T20:16:48 | 2024-08-15T19:49:29 | nomulus | google/nomulus | 1,685 | 1,094 |
```xml
import * as assert from 'assert';
import { Cargo } from '../../src/toolchain';
suite('Launch configuration', () => {
suite('Lens', () => {
test('A binary', async () => {
const args = Cargo.artifactSpec(["build", "--package", "pkg_name", "--bin", "pkg_name"]);
assert.deepEqual(args.cargoArgs, ["build", "--package", "pkg_name", "--bin", "pkg_name", "--message-format=json"]);
assert.deepEqual(args.filter, undefined);
});
test('One of Multiple Binaries', async () => {
const args = Cargo.artifactSpec(["build", "--package", "pkg_name", "--bin", "bin1"]);
assert.deepEqual(args.cargoArgs, ["build", "--package", "pkg_name", "--bin", "bin1", "--message-format=json"]);
assert.deepEqual(args.filter, undefined);
});
test('A test', async () => {
const args = Cargo.artifactSpec(["test", "--package", "pkg_name", "--lib", "--no-run"]);
assert.deepEqual(args.cargoArgs, ["test", "--package", "pkg_name", "--lib", "--no-run", "--message-format=json"]);
assert.notDeepEqual(args.filter, undefined);
});
});
suite('QuickPick', () => {
test('A binary', async () => {
const args = Cargo.artifactSpec(["run", "--package", "pkg_name", "--bin", "pkg_name"]);
assert.deepEqual(args.cargoArgs, ["build", "--package", "pkg_name", "--bin", "pkg_name", "--message-format=json"]);
assert.deepEqual(args.filter, undefined);
});
test('One of Multiple Binaries', async () => {
const args = Cargo.artifactSpec(["run", "--package", "pkg_name", "--bin", "bin2"]);
assert.deepEqual(args.cargoArgs, ["build", "--package", "pkg_name", "--bin", "bin2", "--message-format=json"]);
assert.deepEqual(args.filter, undefined);
});
test('A test', async () => {
const args = Cargo.artifactSpec(["test", "--package", "pkg_name", "--lib"]);
assert.deepEqual(args.cargoArgs, ["test", "--package", "pkg_name", "--lib", "--message-format=json", "--no-run"]);
assert.notDeepEqual(args.filter, undefined);
});
});
});
``` | /content/code_sandbox/rust-analyzer/editors/code/tests/unit/launch_config.test.ts | xml | 2016-09-02T22:57:33 | 2024-07-31T15:03:56 | vscode-rust | rust-lang/vscode-rust | 1,388 | 505 |
```xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<jalopy>
<general>
<compliance>
<version>15</version>
</compliance>
<style>
<description>Sun Java Coding Convention</description>
<name>Sun</name>
</style>
</general>
<inspector>
<enable>false</enable>
<naming>
<classes>
<abstract>[A-Z][a-zA-Z0-9]+</abstract>
<general>[A-Z][a-zA-Z0-9]+</general>
</classes>
<fields>
<default>[a-z][\w]+</default>
<defaultStatic>[a-z][\w]+</defaultStatic>
<defaultStaticFinal>[a-zA-Z][\w]+</defaultStaticFinal>
<private>[a-z][\w]+</private>
<privateStatic>[a-z][\w]+</privateStatic>
<privateStaticFinal>[a-zA-Z][\w]+</privateStaticFinal>
<protected>[a-z][\w]+</protected>
<protectedStatic>[a-z][\w]+</protectedStatic>
<protectedStaticFinal>[a-zA-Z][\w]+</protectedStaticFinal>
<public>[a-z][\w]+</public>
<publicStatic>[a-z][\w]+</publicStatic>
<publicStaticFinal>[a-zA-Z][\w]+</publicStaticFinal>
</fields>
<interfaces>[A-Z][a-zA-Z0-9]+</interfaces>
<labels>\w+</labels>
<methods>
<default>[a-z][\w]+</default>
<defaultStatic>[a-z][\w]+</defaultStatic>
<defaultStaticFinal>[a-z][\w]+</defaultStaticFinal>
<private>[a-z][\w]+</private>
<privateStatic>[a-z][\w]+</privateStatic>
<privateStaticFinal>[a-z][\w]+</privateStaticFinal>
<protected>[a-z][\w]+</protected>
<protectedStatic>[a-z][\w]+</protectedStatic>
<protectedStaticFinal>[a-z][\w]+</protectedStaticFinal>
<public>[a-z][\w]+</public>
<publicStatic>[a-z][\w]+</publicStatic>
<publicStaticFinal>[a-z][\w]+</publicStaticFinal>
</methods>
<packages>[a-z]+(?:\.[a-z]+)*</packages>
<parameters>
<default>[a-z][\w]+</default>
<final>[a-z][\w]+</final>
</parameters>
<variables>[a-z][\w]*</variables>
</naming>
<tips>
<adhereToNamingConvention>false</adhereToNamingConvention>
<alwaysOverrideHashCode>false</alwaysOverrideHashCode>
<avoidThreadGroups>false</avoidThreadGroups>
<declareCollectionComment>false</declareCollectionComment>
<dontIgnoreExceptions>false</dontIgnoreExceptions>
<dontSubstituteObjectEquals>false</dontSubstituteObjectEquals>
<neverDeclareException>false</neverDeclareException>
<neverDeclareThrowable>false</neverDeclareThrowable>
<neverInvokeWaitOutsideLoop>false</neverInvokeWaitOutsideLoop>
<neverReturnZeroArrays>false</neverReturnZeroArrays>
<neverUseEmptyFinally>false</neverUseEmptyFinally>
<obeyContractEquals>false</obeyContractEquals>
<overrideToString>false</overrideToString>
<referToObjectsByInterface>false</referToObjectsByInterface>
<replaceStructureWithClass>false</replaceStructureWithClass>
<stringLiterallI18n>false</stringLiterallI18n>
<useInterfaceOnlyForTypes>false</useInterfaceOnlyForTypes>
<wrongCollectionComment>false</wrongCollectionComment>
</tips>
</inspector>
<internal>
<version>6</version>
</internal>
<messages>
<priority>
<general>30000</general>
<parser>30000</parser>
<parserJavadoc>30000</parserJavadoc>
<printer>30000</printer>
<printerJavadoc>30000</printerJavadoc>
<transform>30000</transform>
</priority>
<showErrorStackTrace>true</showErrorStackTrace>
</messages>
<misc>
<threadCount>1</threadCount>
</misc>
<printer>
<alignment>
<methodCallChain>true</methodCallChain>
<parameterMethodDeclaration>true</parameterMethodDeclaration>
<ternaryOperator>false</ternaryOperator>
<variableAssignment>false</variableAssignment>
<variableDeclAssignment>false</variableDeclAssignment>
<variableIdentifier>true</variableIdentifier>
</alignment>
<backup>
<directory>bak</directory>
<level>0</level>
</backup>
<blanklines>
<after>
<block>1</block>
<braceLeft>0</braceLeft>
<class>1</class>
<declaration>0</declaration>
<footer>1</footer>
<header>0</header>
<interface>1</interface>
<lastImport>1</lastImport>
<method>1</method>
<package>1</package>
</after>
<before>
<block>1</block>
<braceRight>0</braceRight>
<caseBlock>1</caseBlock>
<comment>
<javadoc>1</javadoc>
<multiline>1</multiline>
<singleline>1</singleline>
</comment>
<controlStatement>1</controlStatement>
<declaration>1</declaration>
<footer>0</footer>
<header>0</header>
<package>1</package>
</before>
<keepUpTo>1</keepUpTo>
</blanklines>
<brace>
<comment>false</comment>
</brace>
<braces>
<empty>
<cuddle>false</cuddle>
<insertStatement>false</insertStatement>
</empty>
<insert>
<dowhile>true</dowhile>
<for>true</for>
<ifelse>true</ifelse>
<while>true</while>
</insert>
<remove>
<block>true</block>
<dowhile>false</dowhile>
<for>false</for>
<ifelse>false</ifelse>
<while>false</while>
</remove>
<treatDifferent>
<methodClass>true</methodClass>
<methodClassIfWrapped>false</methodClassIfWrapped>
</treatDifferent>
</braces>
<chunks>
<blanklines>false</blanklines>
<comments>false</comments>
</chunks>
<comments>
<format>
<multiline>true</multiline>
</format>
<javadoc>
<check>
<innerclass>false</innerclass>
<tags>false</tags>
<throwsTags>true</throwsTags>
</check>
<fieldsShort>true</fieldsShort>
<generate>
<class>5</class>
<constructor>5</constructor>
<field>0</field>
<method>0</method>
</generate>
<parseComments>false</parseComments>
<parseDescription>false</parseDescription>
<skip>
<ifml>true</ifml>
</skip>
<tags>
<in-line/>
<standard/>
</tags>
<templates>
<class>/**| * DOCUMENT ME!| *| * @author TBD| * @version TBD| */</class>
<constructor>
<bottom> */</bottom>
<exception> * @throws $exceptionType$ DOCUMENT ME!</exception>
<param> * @param $paramType$ DOCUMENT ME!</param>
<top>/**| * Creates a new {@code $objectType$} object.</top>
</constructor>
<interface>/**| * DOCUMENT ME!| *| * @author TBD| * @version TBD| */</interface>
<method>
<bottom> */</bottom>
<exception> * @throws $exceptionType$ DOCUMENT ME!</exception>
<param> * @param $paramType$ DOCUMENT ME!</param>
<return> * @return DOCUMENT ME!</return>
<top>/**| * DOCUMENT ME!</top>
</method>
<variable>/**| * DOCUMENT ME!| */</variable>
</templates>
</javadoc>
<remove>
<javadoc>false</javadoc>
<multiline>false</multiline>
<singleline>false</singleline>
</remove>
<separator>
<fillCharacter>-</fillCharacter>
<insert>true</insert>
<insertRecursive>true</insertRecursive>
<text>
<annotation>Annotations</annotation>
<class>Inner Classes</class>
<constructor>Constructors</constructor>
<enum>Enumerations</enum>
<field>Instance fields</field>
<initializer>Instance initializers</initializer>
<interface>Inner Interfaces</interface>
<method>Methods</method>
<static>Static fields/initializers</static>
</text>
</separator>
</comments>
<environment/>
<footer>
<ignoreIfExists>false</ignoreIfExists>
<keys/>
<smartMode>0</smartMode>
<use>false</use>
</footer>
<header>
<ignoreIfExists>true</ignoreIfExists>
<keys>author</keys>
<smartMode>0</smartMode>
<use>true</use>
</header>
<history>
<method>adler32</method>
<policy>file</policy>
</history>
<imports>
<grouping>
<defaultDepth>2</defaultDepth>
<packages>omr:2|*:0|java:1|javax:1</packages>
</grouping>
<policy>disabled</policy>
<sort>true</sort>
</imports>
<indentation>
<caseFromSwitch>false</caseFromSwitch>
<continuation>
<block>false</block>
<operator>false</operator>
</continuation>
<firstColumnComments>true</firstColumnComments>
<label>true</label>
<policy>
<deep>true</deep>
</policy>
<sizes>
<braceCuddled>1</braceCuddled>
<braceLeft>1</braceLeft>
<braceRight>0</braceRight>
<braceRightAfter>1</braceRightAfter>
<continuation>4</continuation>
<deep>90</deep>
<extends>4</extends>
<general>4</general>
<implements>4</implements>
<leading>0</leading>
<tabs>8</tabs>
<throws>4</throws>
<trailingComment>1</trailingComment>
</sizes>
<tabs>
<enable>false</enable>
<onlyLeading>false</onlyLeading>
</tabs>
</indentation>
<misc>
<arrayBracketsAfterIdent>false</arrayBracketsAfterIdent>
<forceFinalModifier>false</forceFinalModifier>
<forceFormatting>true</forceFormatting>
<insertExpressionParentheses>true</insertExpressionParentheses>
<insertLoggingConditional>false</insertLoggingConditional>
<insertTrailingNewline>true</insertTrailingNewline>
<insertUID>false</insertUID>
<method>
<forceFinalModifier>false</forceFinalModifier>
</method>
</misc>
<sorting>
<declaration>
<annotation>true</annotation>
<class>true</class>
<constructor>true</constructor>
<enable>true</enable>
<enum>false</enum>
<interface>true</interface>
<method>true<bean>false</bean>
</method>
<order>static|enum|field|initializer|constructor|method|interface|class|annotation</order>
<variable>false</variable>
</declaration>
<modifier>
<enable>true</enable>
<order>public=true|protected=true|private=true|abstract=true|static=true|final=true|synchronized=true|transient=true|volatile=true|native=true|strictfp=true</order>
</modifier>
</sorting>
<whitespace>
<after>
<comma>true</comma>
<semicolon>true</semicolon>
<typeCast>true</typeCast>
</after>
<before>
<braces>true</braces>
<brackets>false</brackets>
<bracketsTypes>false</bracketsTypes>
<caseColon>true</caseColon>
<operator>
<not>false</not>
</operator>
<parentheses>
<methodCall>false</methodCall>
<methodDeclaration>true</methodDeclaration>
<statement>true</statement>
</parentheses>
</before>
<padding>
<braces>true</braces>
<brackets>false</brackets>
<operator>
<assignment>true</assignment>
<bitwise>true</bitwise>
<logical>true</logical>
<mathematical>true</mathematical>
<relational>true</relational>
<shift>true</shift>
</operator>
<parenthesis>false</parenthesis>
<typeCast>false</typeCast>
</padding>
</whitespace>
<wrapping>
<always>
<after>
<arrayElement>0</arrayElement>
<braceRight>false</braceRight>
<extendsTypes>false</extendsTypes>
<implementsTypes>false</implementsTypes>
<label>true</label>
<methodCallChained>false</methodCallChained>
<ternaryOperator>
<first>false</first>
<second>false</second>
</ternaryOperator>
<throwsTypes>false</throwsTypes>
</after>
<before>
<braceLeft>false</braceLeft>
<extends>true</extends>
<implements>true</implements>
<throws>true</throws>
</before>
<parameter>
<methodCall>false</methodCall>
<methodCallNested>false</methodCallNested>
<methodDeclaration>true</methodDeclaration>
</parameter>
</always>
<anon>
<align>
<after>2147483647</after>
</align>
<lcurly>
<newline>true</newline>
</lcurly>
</anon>
<anondef>
<align>
<after>2147483647</after>
</align>
<lcurly>
<nonewline>true</nonewline>
</lcurly>
</anondef>
<enum>
<align>
<after>1</after>
</align>
<lcurly>
<nonewline>false</nonewline>
</lcurly>
</enum>
<general>
<beforeOperator>false</beforeOperator>
<enable>true</enable>
<lineLength>100</lineLength>
</general>
<ondemand>
<after>
<assignment>false</assignment>
<leftParenthesis>false</leftParenthesis>
<parameter>true</parameter>
<types>
<extends>false</extends>
<implements>false</implements>
<throws>false</throws>
</types>
</after>
<before>
<rightParenthesis>false</rightParenthesis>
</before>
<deep>
<parameter>true</parameter>
</deep>
<groupingParentheses>false</groupingParentheses>
<hard>
<parameter>true</parameter>
</hard>
</ondemand>
</wrapping>
</printer>
</jalopy>
``` | /content/code_sandbox/dev/jalopy/java-convention.xml | xml | 2016-09-07T13:31:03 | 2024-08-14T06:25:10 | audiveris | Audiveris/audiveris | 1,488 | 3,015 |
```xml
import { useConfig, useSubscription, useUser } from '@proton/components/hooks';
import useOfferFlags from '../../hooks/useOfferFlags';
import type { Operation } from '../../interface';
import config from './configuration';
import getIsEligible from './eligibility';
const useOffer = (): Operation => {
const [user, userLoading] = useUser();
const [subscription, loading] = useSubscription();
const { isActive, loading: flagsLoading } = useOfferFlags(config);
const protonConfig = useConfig();
const isLoading = flagsLoading || userLoading || loading;
const isEligible = getIsEligible({ user, subscription, protonConfig }) && isActive;
const isValid = isEligible && isActive;
return { isValid, config, isLoading, isEligible };
};
export default useOffer;
``` | /content/code_sandbox/packages/components/containers/offers/operations/goUnlimited2022/useOffer.ts | xml | 2016-06-08T11:16:51 | 2024-08-16T14:14:27 | WebClients | ProtonMail/WebClients | 4,300 | 177 |
```xml
<?xml version="1.0" encoding="UTF-8"?>
<!--suppress MavenModelInspection -->
<project xmlns="path_to_url"
xmlns:xsi="path_to_url"
xsi:schemaLocation="path_to_url path_to_url">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.crossoverJie</groupId>
<artifactId>SSM</artifactId>
<version>2.2.0-SNAPSHOT</version>
</parent>
<artifactId>SSM-SERVICE</artifactId>
<name>${project.artifactId}</name>
<packaging>war</packaging>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
</plugin>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.2</version>
<configuration>
<verbose>true</verbose>
<overwrite>true</overwrite>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<packagingExcludes>**/config.properties</packagingExcludes>
</configuration>
</plugin>
<plugin>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>9.1.0.RC0</version>
<configuration>
<webApp>
<contextPath>/</contextPath>
</webApp>
<scanIntervalSeconds>0</scanIntervalSeconds>
<scanTargetPatterns>
<scanTargetPattern>
<directory>src/main/webapp</directory>
<includes>
<include>**/*.xml</include>
<include>**/*.properties</include>
</includes>
</scanTargetPattern>
</scanTargetPatterns>
<httpConnector>
<port>9998</port>
<idleTimeout>60000</idleTimeout>
</httpConnector>
<systemProperties>
<systemProperty>
<name>config.properties</name>
<value>classpath:config.properties</value>
</systemProperty>
<systemProperty>
<name>dubbo.application.logger</name>
<value>slf4j</value>
</systemProperty>
</systemProperties>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring.version>4.1.4.RELEASE</spring.version>
<jackson.version>2.5.0</jackson.version>
<lucene.version>6.0.1</lucene.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.crossoverJie</groupId>
<artifactId>SSM-API</artifactId>
</dependency>
<dependency>
<groupId>com.crossoverJie</groupId>
<artifactId>SSM-TRACE-FILTER</artifactId>
</dependency>
<dependency>
<groupId>com.crossoverJie</groupId>
<artifactId>SSM-HTTP-PROVIDER</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>dubbo</artifactId>
<exclusions>
<exclusion>
<artifactId>log4j</artifactId>
<groupId>log4j</groupId>
</exclusion>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
<exclusion>
<artifactId>spring</artifactId>
<groupId>org.springframework</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.github.sgroschupf</groupId>
<artifactId>zkclient</artifactId>
</dependency>
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
</dependency>
<!-- Servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
</dependency>
<!-- spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<scope>test</scope>
</dependency>
<!-- SpringMVC -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
<!-- hibernate jpa -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
</dependency>
<!-- log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
</dependency>
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
</dependency>
<!-- json -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<classifier>jdk15</classifier><!--jdk -->
</dependency>
<!-- aop -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
</dependency>
<!-- servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<!-- -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
</dependency>
<!--lucene-->
<!-- path_to_url -->
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-core</artifactId>
</dependency>
<!-- path_to_url -->
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-queryparser</artifactId>
</dependency>
<!-- path_to_url -->
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-analyzers-common</artifactId>
</dependency>
<!--lucene-->
<!-- path_to_url -->
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-analyzers-smartcn</artifactId>
</dependency>
<!--lucene-->
<!-- path_to_url -->
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-highlighter</artifactId>
</dependency>
<!--shiro-->
<!-- path_to_url -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
</dependency>
<!-- path_to_url -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</dependency>
<!-- path_to_url -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-web</artifactId>
</dependency>
<!-- path_to_url -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
</dependency>
<!--cxf-->
<!-- path_to_url -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxws</artifactId>
</dependency>
<!-- path_to_url -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-core</artifactId>
</dependency>
<!-- path_to_url -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http</artifactId>
</dependency>
<dependency>
<groupId>javax.websocket</groupId>
<artifactId>javax.websocket-api</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-websocket</artifactId>
</dependency>
<!-- path_to_url -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
</dependency>
<!--redis-->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
</dependency>
</dependencies>
</project>
``` | /content/code_sandbox/SSM-SERVICE/pom.xml | xml | 2016-06-21T10:09:02 | 2024-08-07T01:16:34 | SSM | crossoverJie/SSM | 3,440 | 2,490 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.