type
stringclasses 7
values | content
stringlengths 4
9.55k
| repo
stringlengths 7
96
| path
stringlengths 4
178
| language
stringclasses 1
value |
|---|---|---|---|---|
ClassDeclaration
|
@Component({
selector: 'app-event',
templateUrl: './event.component.html',
styleUrls: ['./event.component.css']
})
export class EventComponent implements OnInit {
@Input('event') event: any;
constructor(private router:Router,public eventService:EventService) { }
ngOnInit() {
}
more() {
//this.eventService.serviceData = this.event;
this.router.navigate(['event',"{{event.id}}"]);
}
}
|
MakMuftic/ppij
|
frontend/hustle-app/src/app/Components/event/event.component.ts
|
TypeScript
|
MethodDeclaration
|
ngOnInit() {
}
|
MakMuftic/ppij
|
frontend/hustle-app/src/app/Components/event/event.component.ts
|
TypeScript
|
MethodDeclaration
|
more() {
//this.eventService.serviceData = this.event;
this.router.navigate(['event',"{{event.id}}"]);
}
|
MakMuftic/ppij
|
frontend/hustle-app/src/app/Components/event/event.component.ts
|
TypeScript
|
ClassDeclaration
|
@Component({templateUrl: 'home.component.html'})
export class HomeComponent implements OnInit {
currentUser: User;
users: User[] = [];
constructor(private userService: UserService) {
this.currentUser = JSON.parse(localStorage.getItem('currentUser'));
}
ngOnInit() {
}
}
|
himanshuvbhatt/angular-6
|
src/app/home/home.component.ts
|
TypeScript
|
MethodDeclaration
|
ngOnInit() {
}
|
himanshuvbhatt/angular-6
|
src/app/home/home.component.ts
|
TypeScript
|
ArrowFunction
|
(): string => {
return uniqueNamesGenerator({dictionaries: [adjectives, animals]})
}
|
ably-labs/Club
|
web/public/ts/names.ts
|
TypeScript
|
ArrowFunction
|
() => this.QueueText(
"* Zwölf Boxkämpfer jagen Viktor quer über den großen Sylter Deich."
)
|
Spooghetti420/Spamton-NEO
|
src/Scene/OverworldScene.ts
|
TypeScript
|
ClassDeclaration
|
export class OverworldScene extends Scene
{
private readonly rails: Rail[] = [];
public readonly player = new Kris();
private textQueue: TextBox[] = [];
private playingMusic: SoundFile = ResourceManager.getSound("assets/mus/spamton_basement.ogg");
init()
{
for (let i = 0; i < 2; i++) {
for (let j = 0; j < 3; j++) {
this.rails.push(new Rail(320 * i, 90 + 30 * j));
}
}
// Game.AddEvent(
// // Spamton mock encounter
// new GameEvent(
// () => {
// return this.player.x < 180
// },
// () => {
// this.player.canMove = false;
// }
// )
// )
if (!debug)
{
this.playingMusic.loop();
this.playingMusic.play();
}
Game.AddEvent(
AfterNFrames(4, () => this.QueueText(
"* Zwölf Boxkämpfer jagen Viktor quer über den großen Sylter Deich."
)
)
)
}
private scroll(): void
{
// return;
const scrollAmount = this.player.makeMove()[0]; // Get x value from player movement
if (this.player.x > 120 && this.player.x < 510)
this.camera.x += scrollAmount;
}
update()
{
background(0);
this.scroll();
Background.draw();
for (let rail of this.rails)
{
rail.draw();
}
this.player.update();
this.player.draw();
// Draw any active textboxes
const textbox = this.textQueue[0];
if (textbox)
{
textbox.update();
textbox.draw();
if (textbox.IsComplete())
{
this.textQueue.splice(0, 1);
if (this.textQueue.length === 0)
this.player.canMove = true;
}
}
}
public QueueText(...texts: string[])
{
this.player.canMove = false;
for (const str of texts)
{
this.textQueue.push(new TextBox(str));
}
}
}
|
Spooghetti420/Spamton-NEO
|
src/Scene/OverworldScene.ts
|
TypeScript
|
MethodDeclaration
|
init()
{
for (let i = 0; i < 2; i++) {
for (let j = 0; j < 3; j++) {
this.rails.push(new Rail(320 * i, 90 + 30 * j));
}
}
// Game.AddEvent(
// // Spamton mock encounter
// new GameEvent(
// () => {
// return this.player.x < 180
// },
// () => {
// this.player.canMove = false;
// }
// )
// )
if (!debug)
{
this.playingMusic.loop();
this.playingMusic.play();
}
Game.AddEvent(
AfterNFrames(4, () => this.QueueText(
"* Zwölf Boxkämpfer jagen Viktor quer über den großen Sylter Deich."
)
)
)
}
|
Spooghetti420/Spamton-NEO
|
src/Scene/OverworldScene.ts
|
TypeScript
|
MethodDeclaration
|
private scroll(): void
{
// return;
const scrollAmount = this.player.makeMove()[0]; // Get x value from player movement
if (this.player.x > 120 && this.player.x < 510)
this.camera.x += scrollAmount;
}
|
Spooghetti420/Spamton-NEO
|
src/Scene/OverworldScene.ts
|
TypeScript
|
MethodDeclaration
|
update()
{
background(0);
this.scroll();
Background.draw();
for (let rail of this.rails)
{
rail.draw();
}
this.player.update();
this.player.draw();
// Draw any active textboxes
const textbox = this.textQueue[0];
if (textbox)
{
textbox.update();
textbox.draw();
if (textbox.IsComplete())
{
this.textQueue.splice(0, 1);
if (this.textQueue.length === 0)
this.player.canMove = true;
}
}
}
|
Spooghetti420/Spamton-NEO
|
src/Scene/OverworldScene.ts
|
TypeScript
|
MethodDeclaration
|
public QueueText(...texts: string[])
{
this.player.canMove = false;
for (const str of texts)
{
this.textQueue.push(new TextBox(str));
}
}
|
Spooghetti420/Spamton-NEO
|
src/Scene/OverworldScene.ts
|
TypeScript
|
ArrowFunction
|
(props: RichTextProps): JSX.Element => {
const { internalLinksSelector = 'a[href^="/"]', ...rest } = props;
const hasText = props.field && props.field.value;
const isEditing = props.editable && props.field && props.field.editable;
const router = useRouter();
const richTextRef = useRef<HTMLElement>(null);
useEffect(() => {
// NOT IN EXPERIENCE EDITOR
if (hasText && !isEditing) {
initializeLinks();
}
});
const routeHandler = (ev: MouseEvent) => {
if (!ev.target) return;
ev.preventDefault();
const pathname = (ev.target as HTMLAnchorElement).pathname;
router.push(pathname, pathname, { locale: false });
};
const initializeLinks = () => {
const node = richTextRef.current;
// selects all links that start with '/'
const internalLinks = node && node.querySelectorAll<HTMLAnchorElement>(internalLinksSelector);
if (!internalLinks || !internalLinks.length) return;
internalLinks.forEach((link) => {
if (!prefetched[link.pathname]) {
router.prefetch(link.pathname, undefined, { locale: false });
prefetched[link.pathname] = true;
}
link.removeEventListener('click', routeHandler, false);
link.addEventListener('click', routeHandler, false);
});
};
return <ReactRichText ref={richTextRef} {...rest} />;
}
|
C-Sharper/jss
|
packages/sitecore-jss-nextjs/src/components/RichText.tsx
|
TypeScript
|
ArrowFunction
|
() => {
// NOT IN EXPERIENCE EDITOR
if (hasText && !isEditing) {
initializeLinks();
}
}
|
C-Sharper/jss
|
packages/sitecore-jss-nextjs/src/components/RichText.tsx
|
TypeScript
|
ArrowFunction
|
(ev: MouseEvent) => {
if (!ev.target) return;
ev.preventDefault();
const pathname = (ev.target as HTMLAnchorElement).pathname;
router.push(pathname, pathname, { locale: false });
}
|
C-Sharper/jss
|
packages/sitecore-jss-nextjs/src/components/RichText.tsx
|
TypeScript
|
ArrowFunction
|
() => {
const node = richTextRef.current;
// selects all links that start with '/'
const internalLinks = node && node.querySelectorAll<HTMLAnchorElement>(internalLinksSelector);
if (!internalLinks || !internalLinks.length) return;
internalLinks.forEach((link) => {
if (!prefetched[link.pathname]) {
router.prefetch(link.pathname, undefined, { locale: false });
prefetched[link.pathname] = true;
}
link.removeEventListener('click', routeHandler, false);
link.addEventListener('click', routeHandler, false);
});
}
|
C-Sharper/jss
|
packages/sitecore-jss-nextjs/src/components/RichText.tsx
|
TypeScript
|
ArrowFunction
|
(link) => {
if (!prefetched[link.pathname]) {
router.prefetch(link.pathname, undefined, { locale: false });
prefetched[link.pathname] = true;
}
link.removeEventListener('click', routeHandler, false);
link.addEventListener('click', routeHandler, false);
}
|
C-Sharper/jss
|
packages/sitecore-jss-nextjs/src/components/RichText.tsx
|
TypeScript
|
TypeAliasDeclaration
|
export type RichTextProps = ReactRichTextProps & {
/**
* Selector which should be used in order to prefetch it and attach event listeners
* @default 'a[href^="/"]'
*/
internalLinksSelector?: string;
};
|
C-Sharper/jss
|
packages/sitecore-jss-nextjs/src/components/RichText.tsx
|
TypeScript
|
ClassDeclaration
|
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class ContactsRoutingModule { }
|
sumitgaita/youth
|
src/app/contacts/contacts-routing.module.ts
|
TypeScript
|
ClassDeclaration
|
export declare class QueryAction implements IQueryAction {
protected table: QueryTable;
constructor(table: QueryTable);
/**
* Performs a COUNT on the table.
*/
count(): QueryFilter;
/**
* Performs a DELETE on the table.
*
* @param options.returning If `true`, return the deleted row(s) in the response.
*/
delete(options?: {
returning: boolean;
}): QueryFilter;
/**
* Performs an INSERT into the table.
*
* @param values The values to insert.
* @param options.returning If `true`, return the inserted row(s) in the response.
*/
insert(values: Dictionary<any>[], options?: {
returning: boolean;
}): QueryFilter;
/**
* Performs vertical filtering with SELECT.
*
* @param columns the query columns, by default set to '*'.
*/
select(columns?: string[]): QueryFilter;
/**
* Performs an UPDATE on the table.
*
* @param value The value to update.
* @param options.returning If `true`, return the updated row(s) in the response.
*/
update(value: Dictionary<any>, options?: {
returning: boolean;
}): QueryFilter;
}
|
johndpope/grid
|
dist/query/QueryAction.d.ts
|
TypeScript
|
InterfaceDeclaration
|
export interface IQueryAction {
count: () => IQueryFilter;
delete: (options?: {
returning: boolean;
}) => IQueryFilter;
insert: (values: Dictionary<any> | Dictionary<any>[], options?: {
returning: boolean;
}) => IQueryFilter;
select: (columns?: string[]) => IQueryFilter;
update: (value: Dictionary<any>, options?: {
returning: boolean;
}) => IQueryFilter;
}
|
johndpope/grid
|
dist/query/QueryAction.d.ts
|
TypeScript
|
MethodDeclaration
|
/**
* Performs a COUNT on the table.
*/
count(): QueryFilter;
|
johndpope/grid
|
dist/query/QueryAction.d.ts
|
TypeScript
|
MethodDeclaration
|
/**
* Performs a DELETE on the table.
*
* @param options.returning If `true`, return the deleted row(s) in the response.
*/
delete(options?: {
returning: boolean;
}): QueryFilter;
|
johndpope/grid
|
dist/query/QueryAction.d.ts
|
TypeScript
|
MethodDeclaration
|
/**
* Performs an INSERT into the table.
*
* @param values The values to insert.
* @param options.returning If `true`, return the inserted row(s) in the response.
*/
insert(values: Dictionary<any>[], options?: {
returning: boolean;
}): QueryFilter;
|
johndpope/grid
|
dist/query/QueryAction.d.ts
|
TypeScript
|
MethodDeclaration
|
/**
* Performs vertical filtering with SELECT.
*
* @param columns the query columns, by default set to '*'.
*/
select(columns?: string[]): QueryFilter;
|
johndpope/grid
|
dist/query/QueryAction.d.ts
|
TypeScript
|
MethodDeclaration
|
/**
* Performs an UPDATE on the table.
*
* @param value The value to update.
* @param options.returning If `true`, return the updated row(s) in the response.
*/
update(value: Dictionary<any>, options?: {
returning: boolean;
}): QueryFilter;
|
johndpope/grid
|
dist/query/QueryAction.d.ts
|
TypeScript
|
ArrowFunction
|
e => this._onMouseDown(e)
|
JesseStolwijk/xterm.js
|
src/ui/MouseZoneManager.ts
|
TypeScript
|
ArrowFunction
|
e => this._onMouseMove(e)
|
JesseStolwijk/xterm.js
|
src/ui/MouseZoneManager.ts
|
TypeScript
|
ArrowFunction
|
e => this._onMouseLeave(e)
|
JesseStolwijk/xterm.js
|
src/ui/MouseZoneManager.ts
|
TypeScript
|
ArrowFunction
|
e => this._onClick(e)
|
JesseStolwijk/xterm.js
|
src/ui/MouseZoneManager.ts
|
TypeScript
|
ArrowFunction
|
() => this._onTooltip(e)
|
JesseStolwijk/xterm.js
|
src/ui/MouseZoneManager.ts
|
TypeScript
|
ClassDeclaration
|
/**
* The MouseZoneManager allows components to register zones within the terminal
* that trigger hover and click callbacks.
*
* This class was intentionally made not so robust initially as the only case it
* needed to support was single-line links which never overlap. Improvements can
* be made in the future.
*/
export class MouseZoneManager extends Disposable implements IMouseZoneManager {
private _zones: IMouseZone[] = [];
private _areZonesActive: boolean = false;
private _mouseMoveListener: (e: MouseEvent) => any;
private _mouseLeaveListener: (e: MouseEvent) => any;
private _clickListener: (e: MouseEvent) => any;
private _tooltipTimeout: number = null;
private _currentZone: IMouseZone = null;
private _lastHoverCoords: [number, number] = [null, null];
constructor(
private _terminal: ITerminal
) {
super();
this.register(addDisposableDomListener(this._terminal.element, 'mousedown', e => this._onMouseDown(e)));
// These events are expensive, only listen to it when mouse zones are active
this._mouseMoveListener = e => this._onMouseMove(e);
this._mouseLeaveListener = e => this._onMouseLeave(e);
this._clickListener = e => this._onClick(e);
}
public dispose(): void {
super.dispose();
this._deactivate();
}
public add(zone: IMouseZone): void {
this._zones.push(zone);
if (this._zones.length === 1) {
this._activate();
}
}
public clearAll(start?: number, end?: number): void {
// Exit if there's nothing to clear
if (this._zones.length === 0) {
return;
}
// Clear all if start/end weren't set
if (!end) {
start = 0;
end = this._terminal.rows - 1;
}
// Iterate through zones and clear them out if they're within the range
for (let i = 0; i < this._zones.length; i++) {
const zone = this._zones[i];
if ((zone.y1 > start && zone.y1 <= end + 1) ||
(zone.y2 > start && zone.y2 <= end + 1) ||
(zone.y1 < start && zone.y2 > end + 1)) {
if (this._currentZone && this._currentZone === zone) {
this._currentZone.leaveCallback();
this._currentZone = null;
}
this._zones.splice(i--, 1);
}
}
// Deactivate the mouse zone manager if all the zones have been removed
if (this._zones.length === 0) {
this._deactivate();
}
}
private _activate(): void {
if (!this._areZonesActive) {
this._areZonesActive = true;
this._terminal.element.addEventListener('mousemove', this._mouseMoveListener);
this._terminal.element.addEventListener('mouseleave', this._mouseLeaveListener);
this._terminal.element.addEventListener('click', this._clickListener);
}
}
private _deactivate(): void {
if (this._areZonesActive) {
this._areZonesActive = false;
this._terminal.element.removeEventListener('mousemove', this._mouseMoveListener);
this._terminal.element.removeEventListener('mouseleave', this._mouseLeaveListener);
this._terminal.element.removeEventListener('click', this._clickListener);
}
}
private _onMouseMove(e: MouseEvent): void {
// TODO: Ideally this would only clear the hover state when the mouse moves
// outside of the mouse zone
if (this._lastHoverCoords[0] !== e.pageX || this._lastHoverCoords[1] !== e.pageY) {
this._onHover(e);
// Record the current coordinates
this._lastHoverCoords = [e.pageX, e.pageY];
}
}
private _onHover(e: MouseEvent): void {
const zone = this._findZoneEventAt(e);
// Do nothing if the zone is the same
if (zone === this._currentZone) {
return;
}
// Fire the hover end callback and cancel any existing timer if a new zone
// is being hovered
if (this._currentZone) {
this._currentZone.leaveCallback();
this._currentZone = null;
if (this._tooltipTimeout) {
clearTimeout(this._tooltipTimeout);
}
}
// Exit if there is not zone
if (!zone) {
return;
}
this._currentZone = zone;
// Trigger the hover callback
if (zone.hoverCallback) {
zone.hoverCallback(e);
}
// Restart the tooltip timeout
this._tooltipTimeout = <number><any>setTimeout(() => this._onTooltip(e), HOVER_DURATION);
}
private _onTooltip(e: MouseEvent): void {
this._tooltipTimeout = null;
const zone = this._findZoneEventAt(e);
if (zone && zone.tooltipCallback) {
zone.tooltipCallback(e);
}
}
private _onMouseDown(e: MouseEvent): void {
// Ignore the event if there are no zones active
if (!this._areZonesActive) {
return;
}
// Find the active zone, prevent event propagation if found to prevent other
// components from handling the mouse event.
const zone = this._findZoneEventAt(e);
if (zone) {
if (zone.willLinkActivate(e)) {
e.preventDefault();
e.stopImmediatePropagation();
}
}
}
private _onMouseLeave(e: MouseEvent): void {
// Fire the hover end callback and cancel any existing timer if the mouse
// leaves the terminal element
if (this._currentZone) {
this._currentZone.leaveCallback();
this._currentZone = null;
if (this._tooltipTimeout) {
clearTimeout(this._tooltipTimeout);
}
}
}
private _onClick(e: MouseEvent): void {
// Find the active zone and click it if found
const zone = this._findZoneEventAt(e);
if (zone) {
zone.clickCallback(e);
e.preventDefault();
e.stopImmediatePropagation();
}
}
private _findZoneEventAt(e: MouseEvent): IMouseZone {
const coords = this._terminal.mouseHelper.getCoords(e, this._terminal.screenElement, this._terminal.charMeasure, this._terminal.cols, this._terminal.rows);
if (!coords) {
return null;
}
const x = coords[0];
const y = coords[1];
for (let i = 0; i < this._zones.length; i++) {
const zone = this._zones[i];
if (zone.y1 === zone.y2) {
// Single line link
if (y === zone.y1 && x >= zone.x1 && x < zone.x2) {
return zone;
}
} else {
// Multi-line link
if ((y === zone.y1 && x >= zone.x1) ||
(y === zone.y2 && x < zone.x2) ||
(y > zone.y1 && y < zone.y2)) {
return zone;
}
}
}
return null;
}
}
|
JesseStolwijk/xterm.js
|
src/ui/MouseZoneManager.ts
|
TypeScript
|
ClassDeclaration
|
export class MouseZone implements IMouseZone {
constructor(
public x1: number,
public y1: number,
public x2: number,
public y2: number,
public clickCallback: (e: MouseEvent) => any,
public hoverCallback: (e: MouseEvent) => any,
public tooltipCallback: (e: MouseEvent) => any,
public leaveCallback: () => void,
public willLinkActivate: (e: MouseEvent) => boolean
) {
}
}
|
JesseStolwijk/xterm.js
|
src/ui/MouseZoneManager.ts
|
TypeScript
|
MethodDeclaration
|
public dispose(): void {
super.dispose();
this._deactivate();
}
|
JesseStolwijk/xterm.js
|
src/ui/MouseZoneManager.ts
|
TypeScript
|
MethodDeclaration
|
public add(zone: IMouseZone): void {
this._zones.push(zone);
if (this._zones.length === 1) {
this._activate();
}
}
|
JesseStolwijk/xterm.js
|
src/ui/MouseZoneManager.ts
|
TypeScript
|
MethodDeclaration
|
public clearAll(start?: number, end?: number): void {
// Exit if there's nothing to clear
if (this._zones.length === 0) {
return;
}
// Clear all if start/end weren't set
if (!end) {
start = 0;
end = this._terminal.rows - 1;
}
// Iterate through zones and clear them out if they're within the range
for (let i = 0; i < this._zones.length; i++) {
const zone = this._zones[i];
if ((zone.y1 > start && zone.y1 <= end + 1) ||
(zone.y2 > start && zone.y2 <= end + 1) ||
(zone.y1 < start && zone.y2 > end + 1)) {
if (this._currentZone && this._currentZone === zone) {
this._currentZone.leaveCallback();
this._currentZone = null;
}
this._zones.splice(i--, 1);
}
}
// Deactivate the mouse zone manager if all the zones have been removed
if (this._zones.length === 0) {
this._deactivate();
}
}
|
JesseStolwijk/xterm.js
|
src/ui/MouseZoneManager.ts
|
TypeScript
|
MethodDeclaration
|
private _activate(): void {
if (!this._areZonesActive) {
this._areZonesActive = true;
this._terminal.element.addEventListener('mousemove', this._mouseMoveListener);
this._terminal.element.addEventListener('mouseleave', this._mouseLeaveListener);
this._terminal.element.addEventListener('click', this._clickListener);
}
}
|
JesseStolwijk/xterm.js
|
src/ui/MouseZoneManager.ts
|
TypeScript
|
MethodDeclaration
|
private _deactivate(): void {
if (this._areZonesActive) {
this._areZonesActive = false;
this._terminal.element.removeEventListener('mousemove', this._mouseMoveListener);
this._terminal.element.removeEventListener('mouseleave', this._mouseLeaveListener);
this._terminal.element.removeEventListener('click', this._clickListener);
}
}
|
JesseStolwijk/xterm.js
|
src/ui/MouseZoneManager.ts
|
TypeScript
|
MethodDeclaration
|
private _onMouseMove(e: MouseEvent): void {
// TODO: Ideally this would only clear the hover state when the mouse moves
// outside of the mouse zone
if (this._lastHoverCoords[0] !== e.pageX || this._lastHoverCoords[1] !== e.pageY) {
this._onHover(e);
// Record the current coordinates
this._lastHoverCoords = [e.pageX, e.pageY];
}
}
|
JesseStolwijk/xterm.js
|
src/ui/MouseZoneManager.ts
|
TypeScript
|
MethodDeclaration
|
private _onHover(e: MouseEvent): void {
const zone = this._findZoneEventAt(e);
// Do nothing if the zone is the same
if (zone === this._currentZone) {
return;
}
// Fire the hover end callback and cancel any existing timer if a new zone
// is being hovered
if (this._currentZone) {
this._currentZone.leaveCallback();
this._currentZone = null;
if (this._tooltipTimeout) {
clearTimeout(this._tooltipTimeout);
}
}
// Exit if there is not zone
if (!zone) {
return;
}
this._currentZone = zone;
// Trigger the hover callback
if (zone.hoverCallback) {
zone.hoverCallback(e);
}
// Restart the tooltip timeout
this._tooltipTimeout = <number><any>setTimeout(() => this._onTooltip(e), HOVER_DURATION);
}
|
JesseStolwijk/xterm.js
|
src/ui/MouseZoneManager.ts
|
TypeScript
|
MethodDeclaration
|
private _onTooltip(e: MouseEvent): void {
this._tooltipTimeout = null;
const zone = this._findZoneEventAt(e);
if (zone && zone.tooltipCallback) {
zone.tooltipCallback(e);
}
}
|
JesseStolwijk/xterm.js
|
src/ui/MouseZoneManager.ts
|
TypeScript
|
MethodDeclaration
|
private _onMouseDown(e: MouseEvent): void {
// Ignore the event if there are no zones active
if (!this._areZonesActive) {
return;
}
// Find the active zone, prevent event propagation if found to prevent other
// components from handling the mouse event.
const zone = this._findZoneEventAt(e);
if (zone) {
if (zone.willLinkActivate(e)) {
e.preventDefault();
e.stopImmediatePropagation();
}
}
}
|
JesseStolwijk/xterm.js
|
src/ui/MouseZoneManager.ts
|
TypeScript
|
MethodDeclaration
|
private _onMouseLeave(e: MouseEvent): void {
// Fire the hover end callback and cancel any existing timer if the mouse
// leaves the terminal element
if (this._currentZone) {
this._currentZone.leaveCallback();
this._currentZone = null;
if (this._tooltipTimeout) {
clearTimeout(this._tooltipTimeout);
}
}
}
|
JesseStolwijk/xterm.js
|
src/ui/MouseZoneManager.ts
|
TypeScript
|
MethodDeclaration
|
private _onClick(e: MouseEvent): void {
// Find the active zone and click it if found
const zone = this._findZoneEventAt(e);
if (zone) {
zone.clickCallback(e);
e.preventDefault();
e.stopImmediatePropagation();
}
}
|
JesseStolwijk/xterm.js
|
src/ui/MouseZoneManager.ts
|
TypeScript
|
MethodDeclaration
|
private _findZoneEventAt(e: MouseEvent): IMouseZone {
const coords = this._terminal.mouseHelper.getCoords(e, this._terminal.screenElement, this._terminal.charMeasure, this._terminal.cols, this._terminal.rows);
if (!coords) {
return null;
}
const x = coords[0];
const y = coords[1];
for (let i = 0; i < this._zones.length; i++) {
const zone = this._zones[i];
if (zone.y1 === zone.y2) {
// Single line link
if (y === zone.y1 && x >= zone.x1 && x < zone.x2) {
return zone;
}
} else {
// Multi-line link
if ((y === zone.y1 && x >= zone.x1) ||
(y === zone.y2 && x < zone.x2) ||
(y > zone.y1 && y < zone.y2)) {
return zone;
}
}
}
return null;
}
|
JesseStolwijk/xterm.js
|
src/ui/MouseZoneManager.ts
|
TypeScript
|
ArrowFunction
|
(): void => {
it('returns an empty Uint8Array when null provided', (): void => {
expect(
hexToU8a(null)
).toHaveLength(0);
});
it('returns a Uint8Array with the correct values', (): void => {
expect(
hexToU8a('0x80000a')
).toEqual(
new Uint8Array([128, 0, 10])
);
});
it('returns a Uint8Array with the correct values (bitLengfth)', (): void => {
expect(
hexToU8a('0x80000a', 32)
).toEqual(
new Uint8Array([0, 128, 0, 10])
);
});
it('fails when non-hex value provided', (): void => {
expect(
(): Uint8Array => hexToU8a('notahex')
).toThrow(/hex value to convert/);
});
}
|
AcalaNetwork/common
|
packages/util/src/hex/toU8a.spec.ts
|
TypeScript
|
ArrowFunction
|
(): void => {
expect(
hexToU8a(null)
).toHaveLength(0);
}
|
AcalaNetwork/common
|
packages/util/src/hex/toU8a.spec.ts
|
TypeScript
|
ArrowFunction
|
(): void => {
expect(
hexToU8a('0x80000a')
).toEqual(
new Uint8Array([128, 0, 10])
);
}
|
AcalaNetwork/common
|
packages/util/src/hex/toU8a.spec.ts
|
TypeScript
|
ArrowFunction
|
(): void => {
expect(
hexToU8a('0x80000a', 32)
).toEqual(
new Uint8Array([0, 128, 0, 10])
);
}
|
AcalaNetwork/common
|
packages/util/src/hex/toU8a.spec.ts
|
TypeScript
|
ArrowFunction
|
(): void => {
expect(
(): Uint8Array => hexToU8a('notahex')
).toThrow(/hex value to convert/);
}
|
AcalaNetwork/common
|
packages/util/src/hex/toU8a.spec.ts
|
TypeScript
|
ArrowFunction
|
(): Uint8Array => hexToU8a('notahex')
|
AcalaNetwork/common
|
packages/util/src/hex/toU8a.spec.ts
|
TypeScript
|
MethodDeclaration
|
path() {
return 'm 0,0 a 25,25 0 0,1 9,48.3 a 9,9 0 0,1 -18,0 a 25,25 0 0,1 9,-48.3 z';
}
|
morishjs/rocode-entryjs
|
src/playground/skeleton/pebble/pebble_event.ts
|
TypeScript
|
MethodDeclaration
|
box() {
return {
offsetX: -25,
offsetY: 0,
width: 50,
height: 48.3,
marginBottom: 0,
};
}
|
morishjs/rocode-entryjs
|
src/playground/skeleton/pebble/pebble_event.ts
|
TypeScript
|
MethodDeclaration
|
magnets(blockView) {
// apply scale required.
const height = blockView ? Math.max(blockView.height, 49.3) : 49.3;
return {
next: { x: 0, y: height + blockView.offsetY },
};
}
|
morishjs/rocode-entryjs
|
src/playground/skeleton/pebble/pebble_event.ts
|
TypeScript
|
MethodDeclaration
|
contentPos() {
// apply scale required.
return { x: 0, y: 25 };
}
|
morishjs/rocode-entryjs
|
src/playground/skeleton/pebble/pebble_event.ts
|
TypeScript
|
ClassDeclaration
|
@Component({
selector: 'app-version-control',
templateUrl: './version-control.component.html',
styleUrls: ['./version-control.component.scss']
})
export class VersionControlComponent implements OnInit {
releaseLogs: ReleaseLog[] = [];
constructor() { }
ngOnInit(): void {
}
}
|
VictorJSV/angular-cookbook
|
chapter08/start_here/template-driven-forms/src/app/components/version-control/version-control.component.ts
|
TypeScript
|
MethodDeclaration
|
ngOnInit(): void {
}
|
VictorJSV/angular-cookbook
|
chapter08/start_here/template-driven-forms/src/app/components/version-control/version-control.component.ts
|
TypeScript
|
ArrowFunction
|
async (
requirement: SolidarityRequirementChunk,
report: SolidarityReportResults,
context: SolidarityRunContext
) => {
const { tail, pipe, flatten, map } = require('ramda')
const skipRule = require('./skipRule')
const checkDir = require('./checkDir')
const checkFile = require('./checkFile')
const checkShell = require('./checkShell')
const findPluginInfo = require('./findPluginInfo')
const { print, solidarity } = context
const { colors, checkmark, xmark } = print
const prettyBool = async checkingFunction => {
try {
await checkingFunction()
return checkmark + colors.green(' YES')
} catch (e) {
return xmark + colors.red(' NO')
}
}
const rules: SolidarityRequirement = pipe(
tail,
// @ts-ignore - flatten will never get a string bc tail is called first
flatten
)(requirement)
// check each rule for report
const ruleChecks = map(async (rule: SolidarityRule) => {
// Make sure this rule is active
if (skipRule(rule)) return false
switch (rule.rule) {
// Handle CLI rule report
case 'cli':
let binaryVersion
try {
binaryVersion = await solidarity.getVersion(rule, context)
} catch (_e) {
binaryVersion = colors.red('*UNKNOWN*')
}
report.addCLI({
binary: rule.binary,
version: binaryVersion,
desired: rule.semver,
})
break
// Handle ENV rule report
case 'env':
const envValue = process.env[rule.variable] || colors.red('*UNDEFINED*')
report.envRules.push([`$${rule.variable}`, envValue])
break
// Handle dir rule report
case 'directory':
case 'dir':
const dirExists = await prettyBool(async () => checkDir(rule, context))
report.filesystemRules.push([rule.location, 'Dir', dirExists])
break
// Handle file rule report
case 'file':
const fileExists = await prettyBool(async () => checkFile(rule, context))
report.filesystemRules.push([rule.location, 'File', fileExists])
break
case 'shell':
const shellCheckPass = await prettyBool(async () => checkShell(rule, context))
report.shellRules.push([rule.command, rule.match, shellCheckPass])
break
case 'custom':
const customPluginRule = findPluginInfo(rule, context)
if (customPluginRule.success) {
// let plugin update the report
if (customPluginRule.plugin.report) await customPluginRule.plugin.report(rule, context, report)
} else {
throw new Error(customPluginRule.message)
}
break
default:
throw new Error('Encountered unknown rule')
}
}, rules)
// Run all the rule checks for a requirement
return Promise.all(ruleChecks).then(results => {
return results
})
}
|
DanielMSchmidt/solidarity
|
src/extensions/functions/reviewRule.ts
|
TypeScript
|
ArrowFunction
|
async checkingFunction => {
try {
await checkingFunction()
return checkmark + colors.green(' YES')
} catch (e) {
return xmark + colors.red(' NO')
}
}
|
DanielMSchmidt/solidarity
|
src/extensions/functions/reviewRule.ts
|
TypeScript
|
ArrowFunction
|
async (rule: SolidarityRule) => {
// Make sure this rule is active
if (skipRule(rule)) return false
switch (rule.rule) {
// Handle CLI rule report
case 'cli':
let binaryVersion
try {
binaryVersion = await solidarity.getVersion(rule, context)
} catch (_e) {
binaryVersion = colors.red('*UNKNOWN*')
}
report.addCLI({
binary: rule.binary,
version: binaryVersion,
desired: rule.semver,
})
break
// Handle ENV rule report
case 'env':
const envValue = process.env[rule.variable] || colors.red('*UNDEFINED*')
report.envRules.push([`$${rule.variable}`, envValue])
break
// Handle dir rule report
case 'directory':
case 'dir':
const dirExists = await prettyBool(async () => checkDir(rule, context))
report.filesystemRules.push([rule.location, 'Dir', dirExists])
break
// Handle file rule report
case 'file':
const fileExists = await prettyBool(async () => checkFile(rule, context))
report.filesystemRules.push([rule.location, 'File', fileExists])
break
case 'shell':
const shellCheckPass = await prettyBool(async () => checkShell(rule, context))
report.shellRules.push([rule.command, rule.match, shellCheckPass])
break
case 'custom':
const customPluginRule = findPluginInfo(rule, context)
if (customPluginRule.success) {
// let plugin update the report
if (customPluginRule.plugin.report) await customPluginRule.plugin.report(rule, context, report)
} else {
throw new Error(customPluginRule.message)
}
break
default:
throw new Error('Encountered unknown rule')
}
}
|
DanielMSchmidt/solidarity
|
src/extensions/functions/reviewRule.ts
|
TypeScript
|
ArrowFunction
|
async () => checkDir(rule, context)
|
DanielMSchmidt/solidarity
|
src/extensions/functions/reviewRule.ts
|
TypeScript
|
ArrowFunction
|
async () => checkFile(rule, context)
|
DanielMSchmidt/solidarity
|
src/extensions/functions/reviewRule.ts
|
TypeScript
|
ArrowFunction
|
async () => checkShell(rule, context)
|
DanielMSchmidt/solidarity
|
src/extensions/functions/reviewRule.ts
|
TypeScript
|
ArrowFunction
|
results => {
return results
}
|
DanielMSchmidt/solidarity
|
src/extensions/functions/reviewRule.ts
|
TypeScript
|
ArrowFunction
|
({ auth }: Store) => auth
|
APISuite/apisuite-fe
|
src/components/SignUpForm/selector.ts
|
TypeScript
|
ArrowFunction
|
(auth) => ({
signUpError: auth.signUpError,
isSignUpWorking: auth.isSignUpWorking,
})
|
APISuite/apisuite-fe
|
src/components/SignUpForm/selector.ts
|
TypeScript
|
ArrowFunction
|
(auth) => ({
signUpName: auth.signUpName,
signUpEmail: auth.signUpEmail,
})
|
APISuite/apisuite-fe
|
src/components/SignUpForm/selector.ts
|
TypeScript
|
ArrowFunction
|
(auth) => ({
signUpOrgName: auth.signUpOrgName,
signUpOrgWebsite: auth.signUpOrgWebsite,
})
|
APISuite/apisuite-fe
|
src/components/SignUpForm/selector.ts
|
TypeScript
|
ArrowFunction
|
() => {
it("pass thru if the first arg token is 'generate'", async () => {
const callback1 = jest.fn();
const callback2 = jest.fn();
const app = applyMiddleware(prefixGenerate, forwardCommand({
'command1': (ctx, next) => {
callback1();
ctx.installDependency({ package: 'lodash', version: 'latest' });
},
'command2': (ctx, next) => {
callback2();
}
}));
const context = new Context({
'wd': 'never-mind',
args: ['generate', 'command1'],
options: {}
});
await app(context, nullExecutable);
expect(callback1.mock.calls.length).toBe(1);
expect(callback2.mock.calls.length).toBe(0);
expect(context.executor.instructions.length).toBe(1);
expect(context.executor.instructions[0]).toEqual({
type: 'installDependency',
detail: { package: 'lodash', version: 'latest', dev: undefined, mock: false }
});
});
it("pass thru if the first arg token is not 'generate'", async () => {
const callback1 = jest.fn();
const callback2 = jest.fn();
const app = applyMiddleware(prefixGenerate, forwardCommand({
'command1': (ctx, next) => {
callback1();
ctx.installDependency({ package: 'lodash', version: 'latest' });
},
'command2': (ctx, next) => {
callback2();
}
}));
const context = new Context({
'wd': 'never-mind',
args: ['command1'],
options: {}
});
await app(context, nullExecutable);
expect(callback1.mock.calls.length).toBe(1);
expect(callback2.mock.calls.length).toBe(0);
expect(context.executor.instructions.length).toBe(1);
expect(context.executor.instructions[0]).toEqual({
type: 'installDependency',
detail: { package: 'lodash', version: 'latest', dev: undefined, mock: false }
});
});
}
|
zhanghao-zhoushan/scaffold-kit
|
tests/middlewares/prefixGenerate.ts
|
TypeScript
|
ArrowFunction
|
async () => {
const callback1 = jest.fn();
const callback2 = jest.fn();
const app = applyMiddleware(prefixGenerate, forwardCommand({
'command1': (ctx, next) => {
callback1();
ctx.installDependency({ package: 'lodash', version: 'latest' });
},
'command2': (ctx, next) => {
callback2();
}
}));
const context = new Context({
'wd': 'never-mind',
args: ['generate', 'command1'],
options: {}
});
await app(context, nullExecutable);
expect(callback1.mock.calls.length).toBe(1);
expect(callback2.mock.calls.length).toBe(0);
expect(context.executor.instructions.length).toBe(1);
expect(context.executor.instructions[0]).toEqual({
type: 'installDependency',
detail: { package: 'lodash', version: 'latest', dev: undefined, mock: false }
});
}
|
zhanghao-zhoushan/scaffold-kit
|
tests/middlewares/prefixGenerate.ts
|
TypeScript
|
ArrowFunction
|
(ctx, next) => {
callback1();
ctx.installDependency({ package: 'lodash', version: 'latest' });
}
|
zhanghao-zhoushan/scaffold-kit
|
tests/middlewares/prefixGenerate.ts
|
TypeScript
|
ArrowFunction
|
(ctx, next) => {
callback2();
}
|
zhanghao-zhoushan/scaffold-kit
|
tests/middlewares/prefixGenerate.ts
|
TypeScript
|
ArrowFunction
|
async () => {
const callback1 = jest.fn();
const callback2 = jest.fn();
const app = applyMiddleware(prefixGenerate, forwardCommand({
'command1': (ctx, next) => {
callback1();
ctx.installDependency({ package: 'lodash', version: 'latest' });
},
'command2': (ctx, next) => {
callback2();
}
}));
const context = new Context({
'wd': 'never-mind',
args: ['command1'],
options: {}
});
await app(context, nullExecutable);
expect(callback1.mock.calls.length).toBe(1);
expect(callback2.mock.calls.length).toBe(0);
expect(context.executor.instructions.length).toBe(1);
expect(context.executor.instructions[0]).toEqual({
type: 'installDependency',
detail: { package: 'lodash', version: 'latest', dev: undefined, mock: false }
});
}
|
zhanghao-zhoushan/scaffold-kit
|
tests/middlewares/prefixGenerate.ts
|
TypeScript
|
ArrowFunction
|
(modulePath) => {
const pluginsPathParts = modulePath.split(path.sep).slice(0, -1);
if (pluginsPathParts.includes('site-packages')) {
// ansible-config returns default builtin configured module path
// as ``<python-path>/site-packages/ansible/modules`` to copy other plugins
// to local cache strip the ``modules`` part from the path and append
// ``plugins`` folder.
pluginsPathParts.push('plugins');
}
builtin_plugin_locations.push(pluginsPathParts.join(path.sep));
}
|
ekmixon/ansible-language-server
|
src/services/executionEnvironment.ts
|
TypeScript
|
ArrowFunction
|
(command) => {
try {
child_process.execSync(command, {
cwd: URI.parse(this.context.workspaceFolder.uri).path,
});
} catch (error) {
// container already stopped and/or removed
}
}
|
ekmixon/ansible-language-server
|
src/services/executionEnvironment.ts
|
TypeScript
|
ArrowFunction
|
(srcPath) => {
updatedHostDocPath.push(path.join(hostPluginDocCacheBasePath, srcPath));
}
|
ekmixon/ansible-language-server
|
src/services/executionEnvironment.ts
|
TypeScript
|
ArrowFunction
|
(srcPath) => {
if (
srcPath === '' ||
!this.isPluginInPath(containerName, srcPath, searchKind)
) {
return;
}
const destPath = path.join(hostPluginDocCacheBasePath, srcPath);
const destPathFolder = destPath
.split(path.sep)
.slice(0, -1)
.join(path.sep);
fs.mkdirSync(destPath, { recursive: true });
const copyCommand = `docker cp ${containerName}:${srcPath} ${destPathFolder}`;
this.connection.console.log(
`Copying plugins from container to local cache path ${copyCommand}`
);
asyncExec(copyCommand, {
encoding: 'utf-8',
});
updatedHostDocPath.push(destPath);
}
|
ekmixon/ansible-language-server
|
src/services/executionEnvironment.ts
|
TypeScript
|
ArrowFunction
|
(srcPath) => {
const destPath = path.join(cacheBasePath, srcPath);
if (fs.existsSync(destPath)) {
localCachePaths.push(destPath);
}
}
|
ekmixon/ansible-language-server
|
src/services/executionEnvironment.ts
|
TypeScript
|
MethodDeclaration
|
public async initialize(): Promise<void> {
try {
const settings = await this.context.documentSettings.get(
this.context.workspaceFolder.uri
);
if (!settings.executionEnvironment.enabled) {
return;
}
this._container_image = settings.executionEnvironment.image;
this._container_engine = settings.executionEnvironment.containerEngine;
if (this._container_engine === 'auto') {
for (const ce of ['podman', 'docker']) {
try {
child_process.execSync(`which ${ce}`, {
encoding: 'utf-8',
});
} catch (error) {
this.connection.console.info(`Container engine '${ce}' not found`);
continue;
}
this._container_engine = <IContainerEngine>ce;
this.connection.console.log(`Container engine set to: '${ce}'`);
break;
}
} else {
try {
child_process.execSync(`which ${this._container_engine}`, {
encoding: 'utf-8',
});
} catch (error) {
this.connection.window.showErrorMessage(
`Container engine '${this._container_engine}' not found. Failed with error '${error}'`
);
return;
}
}
if (!['podman', 'docker'].includes(this._container_engine)) {
this.connection.window.showInformationMessage(
'No valid container engine found.'
);
return;
}
const imagePuller = new ImagePuller(
this.connection,
this.context,
this._container_engine,
this._container_image,
settings.executionEnvironment.pullPolicy
);
const setupDone = await imagePuller.setupImage();
if (!setupDone) {
this.connection.window.showErrorMessage(
`Execution environment image '${this._container_image}' setup failed.
For more details check output console logs for ansible-language-server`
);
return;
}
this.fetchPluginDocs();
} catch (error) {
if (error instanceof Error) {
this.connection.window.showErrorMessage(error.message);
} else {
this.connection.console.error(
`Exception in ExecutionEnvironment service: ${JSON.stringify(error)}`
);
}
}
}
|
ekmixon/ansible-language-server
|
src/services/executionEnvironment.ts
|
TypeScript
|
MethodDeclaration
|
async fetchPluginDocs(): Promise<void> {
const ansibleConfig = await this.context.ansibleConfig;
const containerName = `${this._container_image.replace(
/[^a-z0-9]/gi,
'_'
)}`;
let progressTracker;
try {
const containerImageIdCommand = `${this._container_engine} images ${this._container_image} --format="{{.ID}}" | head -n 1`;
this.connection.console.log(containerImageIdCommand);
this._container_image_id = child_process
.execSync(containerImageIdCommand, {
encoding: 'utf-8',
})
.trim();
const hostCacheBasePath = path.resolve(
`${process.env.HOME}/.cache/ansible-language-server/${containerName}/${this._container_image_id}`
);
const isContainerRunning = this.runContainer(containerName);
if (!isContainerRunning) {
return;
}
if (fs.existsSync(hostCacheBasePath)) {
ansibleConfig.collections_paths = this.updateCachePaths(
ansibleConfig.collections_paths,
hostCacheBasePath
);
ansibleConfig.module_locations = this.updateCachePaths(
ansibleConfig.module_locations,
hostCacheBasePath
);
} else {
if (this.useProgressTracker) {
progressTracker =
await this.connection.window.createWorkDoneProgress();
}
if (progressTracker) {
progressTracker.begin(
'execution-environment',
undefined,
`Copy plugin docs from '${this._container_image} to host cache path`,
true
);
}
ansibleConfig.collections_paths = await this.copyPluginDocFiles(
hostCacheBasePath,
containerName,
ansibleConfig.collections_paths,
'**/ansible_collections'
);
const builtin_plugin_locations: string[] = [];
ansibleConfig.module_locations.forEach((modulePath) => {
const pluginsPathParts = modulePath.split(path.sep).slice(0, -1);
if (pluginsPathParts.includes('site-packages')) {
// ansible-config returns default builtin configured module path
// as ``<python-path>/site-packages/ansible/modules`` to copy other plugins
// to local cache strip the ``modules`` part from the path and append
// ``plugins`` folder.
pluginsPathParts.push('plugins');
}
builtin_plugin_locations.push(pluginsPathParts.join(path.sep));
});
// Copy builtin plugins
await this.copyPluginDocFiles(
hostCacheBasePath,
containerName,
builtin_plugin_locations,
'*'
);
// Copy builtin modules
ansibleConfig.module_locations = await this.copyPluginDocFiles(
hostCacheBasePath,
containerName,
ansibleConfig.module_locations,
'**/modules'
);
}
} catch (error) {
this.connection.window.showErrorMessage(
`Exception in ExecutionEnvironment service while fetching docs: ${JSON.stringify(
error
)}`
);
} finally {
if (progressTracker) {
progressTracker.done();
}
this.cleanUpContainer(containerName);
}
}
|
ekmixon/ansible-language-server
|
src/services/executionEnvironment.ts
|
TypeScript
|
MethodDeclaration
|
public wrapContainerArgs(command: string, mountPaths?: Set<string>): string {
const workspaceFolderPath = URI.parse(
this.context.workspaceFolder.uri
).path;
const containerCommand: Array<string> = [this._container_engine];
containerCommand.push(...['run', '--rm']);
containerCommand.push(...['--workdir', workspaceFolderPath]);
containerCommand.push(
...['-v', `${workspaceFolderPath}:${workspaceFolderPath}`]
);
for (const mountPath of mountPaths || []) {
const volumeMountPath = `${mountPath}:${mountPath}`;
if (containerCommand.includes(volumeMountPath)) {
continue;
}
containerCommand.push('-v', volumeMountPath);
}
if (this._container_engine === 'podman') {
// container namespace stuff
containerCommand.push('--group-add=root');
containerCommand.push('--ipc=host');
// docker does not support this option
containerCommand.push('--quiet');
} else {
containerCommand.push(`--user=${process.getuid()}`);
}
containerCommand.push(`--name ansible_language_server_${uuidv4()}`);
containerCommand.push(this._container_image);
containerCommand.push(command);
const generatedCommand = containerCommand.join(' ');
this.connection.console.log(
`container engine invocation: ${generatedCommand}`
);
return generatedCommand;
}
|
ekmixon/ansible-language-server
|
src/services/executionEnvironment.ts
|
TypeScript
|
MethodDeclaration
|
public cleanUpContainer(containerName: string): void {
[
`${this._container_engine} stop ${containerName}`,
`${this._container_engine} rm ${containerName}`,
].forEach((command) => {
try {
child_process.execSync(command, {
cwd: URI.parse(this.context.workspaceFolder.uri).path,
});
} catch (error) {
// container already stopped and/or removed
}
});
}
|
ekmixon/ansible-language-server
|
src/services/executionEnvironment.ts
|
TypeScript
|
MethodDeclaration
|
private isPluginInPath(
containerName: string,
searchPath: string,
pluginFolderPath: string
): boolean {
const command = `${this._container_engine} exec ${containerName} find ${searchPath} -path '${pluginFolderPath}'`;
try {
this.connection.console.info(`Executing command ${command}`);
const result = child_process
.execSync(command, {
encoding: 'utf-8',
})
.trim();
return result !== '';
} catch (error) {
this.connection.console.error(error);
return false;
}
}
|
ekmixon/ansible-language-server
|
src/services/executionEnvironment.ts
|
TypeScript
|
MethodDeclaration
|
private runContainer(containerName: string): boolean {
// ensure container is not running
this.cleanUpContainer(containerName);
try {
const command = `${this._container_engine} run --rm -it -d --name ${containerName} ${this._container_image} bash`;
this.connection.console.log(`run container with command '${command}'`);
child_process.execSync(command, {
encoding: 'utf-8',
});
} catch (error) {
this.connection.window.showErrorMessage(
`Failed to initialize execution environment '${this._container_image}': ${error}`
);
return false;
}
return true;
}
|
ekmixon/ansible-language-server
|
src/services/executionEnvironment.ts
|
TypeScript
|
MethodDeclaration
|
private async copyPluginDocFiles(
hostPluginDocCacheBasePath: string,
containerName: string,
containerPluginPaths: string[],
searchKind: string
): Promise<string[]> {
const updatedHostDocPath: string[] = [];
if (fs.existsSync(hostPluginDocCacheBasePath)) {
containerPluginPaths.forEach((srcPath) => {
updatedHostDocPath.push(path.join(hostPluginDocCacheBasePath, srcPath));
});
} else {
containerPluginPaths.forEach((srcPath) => {
if (
srcPath === '' ||
!this.isPluginInPath(containerName, srcPath, searchKind)
) {
return;
}
const destPath = path.join(hostPluginDocCacheBasePath, srcPath);
const destPathFolder = destPath
.split(path.sep)
.slice(0, -1)
.join(path.sep);
fs.mkdirSync(destPath, { recursive: true });
const copyCommand = `docker cp ${containerName}:${srcPath} ${destPathFolder}`;
this.connection.console.log(
`Copying plugins from container to local cache path ${copyCommand}`
);
asyncExec(copyCommand, {
encoding: 'utf-8',
});
updatedHostDocPath.push(destPath);
});
}
return updatedHostDocPath;
}
|
ekmixon/ansible-language-server
|
src/services/executionEnvironment.ts
|
TypeScript
|
MethodDeclaration
|
private updateCachePaths(
pluginPaths: string[],
cacheBasePath: string
): string[] {
const localCachePaths: string[] = [];
pluginPaths.forEach((srcPath) => {
const destPath = path.join(cacheBasePath, srcPath);
if (fs.existsSync(destPath)) {
localCachePaths.push(destPath);
}
});
return localCachePaths;
}
|
ekmixon/ansible-language-server
|
src/services/executionEnvironment.ts
|
TypeScript
|
FunctionDeclaration
|
// import utilStyles from "../styles/utils.module.css";
export default function Issues({ allIssuesData }: { allIssuesData: Meta[] }): JSX.Element {
const theme = useThemeState();
return (
<Layout
title={`${siteConfig.name} | All Issues`}
|
anuraghazra/scriptified
|
pages/issues.tsx
|
TypeScript
|
ArrowFunction
|
data => (
<li key={data.number}>
<IssueListItem issueData
|
anuraghazra/scriptified
|
pages/issues.tsx
|
TypeScript
|
ArrowFunction
|
async () => {
const data = await issueAPI.allIssuesReversed();
return {
props: {
allIssuesData: getAllIssuesMeta(data),
},
revalidate: 180,
};
}
|
anuraghazra/scriptified
|
pages/issues.tsx
|
TypeScript
|
ArrowFunction
|
async ({
senderAccount,
senderWalletId,
amount: amountRaw,
address,
targetConfirmations,
memo,
sendAll,
twoFAToken,
}: PayOnChainByWalletIdWithTwoFAArgs): Promise<PaymentSendStatus | ApplicationError> => {
const amount = sendAll
? await LedgerService().getWalletBalance(senderWalletId)
: checkedToSats(amountRaw)
if (amount instanceof Error) return amount
const user = await UsersRepository().findById(senderAccount.ownerId)
if (user instanceof Error) return user
const { twoFA } = user
const twoFACheck = twoFA?.secret
? await checkAndVerifyTwoFA({
walletId: senderWalletId,
amount,
twoFASecret: twoFA.secret,
twoFAToken,
account: senderAccount,
})
: true
if (twoFACheck instanceof Error) return twoFACheck
return payOnChainByWalletId({
senderAccount,
senderWalletId,
amount,
address,
targetConfirmations,
memo,
sendAll,
})
}
|
AustinKelsay/galoy
|
src/app/wallets/pay-on-chain.ts
|
TypeScript
|
ArrowFunction
|
async ({
senderAccount,
senderWalletId,
amount: amountRaw,
address,
targetConfirmations,
memo,
sendAll,
}: PayOnChainByWalletIdArgs): Promise<PaymentSendStatus | ApplicationError> => {
const checkedAmount = sendAll
? await LedgerService().getWalletBalance(senderWalletId)
: checkedToSats(amountRaw)
if (checkedAmount instanceof Error) return checkedAmount
const validator = PaymentInputValidator(WalletsRepository().findById)
const validationResult = await validator.validatePaymentInput({
amount: checkedAmount,
senderAccount,
senderWalletId,
})
if (validationResult instanceof Error) return validationResult
const { amount, senderWallet } = validationResult
const onchainLogger = baseLogger.child({
topic: "payment",
protocol: "onchain",
transactionType: "payment",
address,
amount,
memo,
sendAll,
})
const checkedAddress = checkedToOnChainAddress({
network: BTC_NETWORK,
value: address,
})
if (checkedAddress instanceof Error) return checkedAddress
const checkedTargetConfirmations = checkedToTargetConfs(targetConfirmations)
if (checkedTargetConfirmations instanceof Error) return checkedTargetConfirmations
const wallets = WalletsRepository()
const recipientWallet = await wallets.findByAddress(checkedAddress)
const isIntraLedger = !(recipientWallet instanceof Error)
if (isIntraLedger)
return executePaymentViaIntraledger({
senderAccount,
senderWalletId,
recipientWallet,
amount,
address: checkedAddress,
memo,
sendAll,
logger: onchainLogger,
})
return executePaymentViaOnChain({
senderWallet,
senderAccount,
amount,
address: checkedAddress,
targetConfirmations: checkedTargetConfirmations,
memo,
sendAll,
logger: onchainLogger,
})
}
|
AustinKelsay/galoy
|
src/app/wallets/pay-on-chain.ts
|
TypeScript
|
ArrowFunction
|
async ({
senderAccount,
senderWalletId,
recipientWallet,
amount,
address,
memo,
sendAll,
logger,
}: {
senderAccount: Account
senderWalletId: WalletId
recipientWallet: Wallet
amount: Satoshis
address: OnChainAddress
memo: string | null
sendAll: boolean
logger: Logger
}): Promise<PaymentSendStatus | ApplicationError> => {
if (recipientWallet.id === senderWalletId) return new SelfPaymentError()
const intraledgerLimitCheck = await checkIntraledgerLimits({
amount,
walletId: senderWalletId,
account: senderAccount,
})
if (intraledgerLimitCheck instanceof Error) return intraledgerLimitCheck
const usdPerSat = await getCurrentPrice()
if (usdPerSat instanceof Error) return usdPerSat
const fee = toSats(0)
const sats = toSats(amount + fee)
const usd = sats * usdPerSat
const usdFee = fee * usdPerSat
const recipientAccount = await AccountsRepository().findById(recipientWallet.accountId)
if (recipientAccount instanceof Error) return recipientAccount
return LockService().lockWalletId(
{ walletId: senderWalletId, logger },
async (lock) => {
const balance = await LedgerService().getWalletBalance(senderWalletId)
if (balance instanceof Error) return balance
if (balance < sats)
return new InsufficientBalanceError(
`Payment amount '${sats}' exceeds balance '${balance}'`,
)
const onchainLoggerOnUs = logger.child({ balance, onUs: true })
const journal = await LockService().extendLock(
{ logger: onchainLoggerOnUs, lock },
async () =>
LedgerService().addOnChainIntraledgerTxSend({
senderWalletId,
description: "",
sats,
fee,
usd,
usdFee,
payeeAddresses: [address],
sendAll,
recipientWalletId: recipientWallet.id,
senderUsername: senderAccount.username,
recipientUsername: recipientAccount.username,
memoPayer: memo ?? null,
}),
)
if (journal instanceof Error) return journal
const notificationsService = NotificationsService(logger)
notificationsService.intraLedgerPaid({
senderWalletId,
recipientWalletId: recipientWallet.id,
amount: sats,
usdPerSat,
})
onchainLoggerOnUs.info(
{
success: true,
type: "onchain_on_us",
pending: false,
fee,
usd,
usdFee,
},
"onchain payment succeed",
)
return PaymentSendStatus.Success
},
)
}
|
AustinKelsay/galoy
|
src/app/wallets/pay-on-chain.ts
|
TypeScript
|
ArrowFunction
|
async (lock) => {
const balance = await LedgerService().getWalletBalance(senderWalletId)
if (balance instanceof Error) return balance
if (balance < sats)
return new InsufficientBalanceError(
`Payment amount '${sats}' exceeds balance '${balance}'`,
)
const onchainLoggerOnUs = logger.child({ balance, onUs: true })
const journal = await LockService().extendLock(
{ logger: onchainLoggerOnUs, lock },
async () =>
LedgerService().addOnChainIntraledgerTxSend({
senderWalletId,
description: "",
sats,
fee,
usd,
usdFee,
payeeAddresses: [address],
sendAll,
recipientWalletId: recipientWallet.id,
senderUsername: senderAccount.username,
recipientUsername: recipientAccount.username,
memoPayer: memo ?? null,
}),
)
if (journal instanceof Error) return journal
const notificationsService = NotificationsService(logger)
notificationsService.intraLedgerPaid({
senderWalletId,
recipientWalletId: recipientWallet.id,
amount: sats,
usdPerSat,
})
onchainLoggerOnUs.info(
{
success: true,
type: "onchain_on_us",
pending: false,
fee,
usd,
usdFee,
},
"onchain payment succeed",
)
return PaymentSendStatus.Success
}
|
AustinKelsay/galoy
|
src/app/wallets/pay-on-chain.ts
|
TypeScript
|
ArrowFunction
|
async () =>
LedgerService().addOnChainIntraledgerTxSend({
senderWalletId,
description: "",
sats,
fee,
usd,
usdFee,
payeeAddresses: [address],
sendAll,
recipientWalletId: recipientWallet.id,
senderUsername: senderAccount.username,
recipientUsername: recipientAccount.username,
memoPayer: memo ?? null,
})
|
AustinKelsay/galoy
|
src/app/wallets/pay-on-chain.ts
|
TypeScript
|
ArrowFunction
|
async ({
senderWallet,
senderAccount,
amount,
address,
targetConfirmations,
memo,
sendAll,
logger,
}: {
senderWallet: Wallet
senderAccount: Account
amount: Satoshis
address: OnChainAddress
targetConfirmations: TargetConfirmations
memo: string | null
sendAll: boolean
logger: Logger
}): Promise<PaymentSendStatus | ApplicationError> => {
const ledgerService = LedgerService()
const withdrawalFeeCalculator = WithdrawalFeeCalculator()
const onChainService = OnChainService(TxDecoder(BTC_NETWORK))
if (onChainService instanceof Error) return onChainService
const withdrawalLimitCheck = await checkWithdrawalLimits({
amount,
walletId: senderWallet.id,
account: senderAccount,
})
if (withdrawalLimitCheck instanceof Error) return withdrawalLimitCheck
const estimatedFee = await getOnChainFeeByWalletId({
walletId: senderWallet.id,
amount,
address,
targetConfirmations,
})
if (estimatedFee instanceof Error) return estimatedFee
const amountToSend = sendAll ? toSats(amount - estimatedFee) : amount
if (amountToSend < dustThreshold)
return new LessThanDustThresholdError(
`Use lightning to send amounts less than ${dustThreshold}`,
)
const onChainAvailableBalance = await onChainService.getBalance()
if (onChainAvailableBalance instanceof Error) return onChainAvailableBalance
if (onChainAvailableBalance < amountToSend + estimatedFee)
return new RebalanceNeededError()
const usdPerSat = await getCurrentPrice()
if (usdPerSat instanceof Error) return usdPerSat
return LockService().lockWalletId(
{ walletId: senderWallet.id, logger },
async (lock) => {
const balance = await LedgerService().getWalletBalance(senderWallet.id)
if (balance instanceof Error) return balance
if (balance < amountToSend + estimatedFee)
return new InsufficientBalanceError(
`Payment amount '${amountToSend + estimatedFee}' exceeds balance '${balance}'`,
)
const journal = await LockService().extendLock({ logger, lock }, async () => {
const txHash = await onChainService.payToAddress({
address,
amount: amountToSend,
targetConfirmations,
})
if (txHash instanceof Error) {
logger.error(
{ err: txHash, address, tokens: amountToSend, success: false },
"Impossible to sendToChainAddress",
)
return txHash
}
let onChainTxFee = await onChainService.lookupOnChainFee({
txHash,
scanDepth: ONCHAIN_SCAN_DEPTH_OUTGOING,
})
if (onChainTxFee instanceof Error) {
logger.fatal({ err: onChainTxFee }, "impossible to get fee for onchain payment")
onChainTxFee = toSats(0)
}
const fee = onChainTxFee
? withdrawalFeeCalculator.onChainWithdrawalFee({
onChainFee: onChainTxFee,
walletFee: toSats(senderAccount.withdrawFee),
})
: estimatedFee
const sats = toSats(amountToSend + fee)
const usd = sats * usdPerSat
const usdFee = fee * usdPerSat
return ledgerService.addOnChainTxSend({
walletId: senderWallet.id,
txHash,
description: memo || "",
sats,
fee,
bankFee: toSats(senderAccount.withdrawFee),
usd,
usdFee,
payeeAddress: address,
sendAll,
})
})
if (journal instanceof Error) return journal
return PaymentSendStatus.Success
},
)
}
|
AustinKelsay/galoy
|
src/app/wallets/pay-on-chain.ts
|
TypeScript
|
ArrowFunction
|
async (lock) => {
const balance = await LedgerService().getWalletBalance(senderWallet.id)
if (balance instanceof Error) return balance
if (balance < amountToSend + estimatedFee)
return new InsufficientBalanceError(
`Payment amount '${amountToSend + estimatedFee}' exceeds balance '${balance}'`,
)
const journal = await LockService().extendLock({ logger, lock }, async () => {
const txHash = await onChainService.payToAddress({
address,
amount: amountToSend,
targetConfirmations,
})
if (txHash instanceof Error) {
logger.error(
{ err: txHash, address, tokens: amountToSend, success: false },
"Impossible to sendToChainAddress",
)
return txHash
}
let onChainTxFee = await onChainService.lookupOnChainFee({
txHash,
scanDepth: ONCHAIN_SCAN_DEPTH_OUTGOING,
})
if (onChainTxFee instanceof Error) {
logger.fatal({ err: onChainTxFee }, "impossible to get fee for onchain payment")
onChainTxFee = toSats(0)
}
const fee = onChainTxFee
? withdrawalFeeCalculator.onChainWithdrawalFee({
onChainFee: onChainTxFee,
walletFee: toSats(senderAccount.withdrawFee),
})
: estimatedFee
const sats = toSats(amountToSend + fee)
const usd = sats * usdPerSat
const usdFee = fee * usdPerSat
return ledgerService.addOnChainTxSend({
walletId: senderWallet.id,
txHash,
description: memo || "",
sats,
fee,
bankFee: toSats(senderAccount.withdrawFee),
usd,
usdFee,
payeeAddress: address,
sendAll,
})
})
if (journal instanceof Error) return journal
return PaymentSendStatus.Success
}
|
AustinKelsay/galoy
|
src/app/wallets/pay-on-chain.ts
|
TypeScript
|
ArrowFunction
|
async () => {
const txHash = await onChainService.payToAddress({
address,
amount: amountToSend,
targetConfirmations,
})
if (txHash instanceof Error) {
logger.error(
{ err: txHash, address, tokens: amountToSend, success: false },
"Impossible to sendToChainAddress",
)
return txHash
}
let onChainTxFee = await onChainService.lookupOnChainFee({
txHash,
scanDepth: ONCHAIN_SCAN_DEPTH_OUTGOING,
})
if (onChainTxFee instanceof Error) {
logger.fatal({ err: onChainTxFee }, "impossible to get fee for onchain payment")
onChainTxFee = toSats(0)
}
const fee = onChainTxFee
? withdrawalFeeCalculator.onChainWithdrawalFee({
onChainFee: onChainTxFee,
walletFee: toSats(senderAccount.withdrawFee),
})
: estimatedFee
const sats = toSats(amountToSend + fee)
const usd = sats * usdPerSat
const usdFee = fee * usdPerSat
return ledgerService.addOnChainTxSend({
walletId: senderWallet.id,
txHash,
description: memo || "",
sats,
fee,
bankFee: toSats(senderAccount.withdrawFee),
usd,
usdFee,
payeeAddress: address,
sendAll,
})
}
|
AustinKelsay/galoy
|
src/app/wallets/pay-on-chain.ts
|
TypeScript
|
ClassDeclaration
|
export class DomainExistsRequest {
constructor(public Name: string, public TLD: string) {}
}
|
4cadia-foundation/jns
|
packages/core/src/Domain/Entity/DomainExistsRequest.ts
|
TypeScript
|
ArrowFunction
|
() => this.onDidChangeTreeDataEmitter.fire()
|
markvincze/vscode-codeFragments
|
src/codeFragmentsTreeItem.ts
|
TypeScript
|
ArrowFunction
|
resolve => {
resolve(
this.fragmentManager.getAll().map(f =>
new CodeFragmentTreeItem(
f.label,
f.id,
vscode.TreeItemCollapsibleState.None,
{
arguments: [f.id],
command: 'codeFragments.insertCodeFragment',
title: 'Insert Code Fragment',
tooltip: 'Insert Code Fragment'
}),
)
);
}
|
markvincze/vscode-codeFragments
|
src/codeFragmentsTreeItem.ts
|
TypeScript
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.