commit
stringlengths 40
40
| old_file
stringlengths 4
150
| new_file
stringlengths 4
150
| old_contents
stringlengths 0
3.26k
| new_contents
stringlengths 1
4.43k
| subject
stringlengths 15
501
| message
stringlengths 15
4.06k
| lang
stringclasses 4
values | license
stringclasses 13
values | repos
stringlengths 5
91.5k
| diff
stringlengths 0
4.35k
|
---|---|---|---|---|---|---|---|---|---|---|
cfe8dc32021cfddd601887dfab94647af85198a9 | app/src/ui/multi-commit-operation/warn-force-push-dialog.tsx | app/src/ui/multi-commit-operation/warn-force-push-dialog.tsx | import * as React from 'react'
import { Checkbox, CheckboxValue } from '../lib/checkbox'
import { Dispatcher } from '../dispatcher'
import { DialogFooter, DialogContent, Dialog } from '../dialog'
import { OkCancelButtonGroup } from '../dialog/ok-cancel-button-group'
interface IWarnForcePushProps {
/**
* This is expected to be capitalized for correct output on windows and macOs.
*
* Examples:
* - Rebase
* - Squash
* - Reorder
*/
readonly operation: string
readonly dispatcher: Dispatcher
readonly askForConfirmationOnForcePush: boolean
readonly onBegin: () => void
readonly onDismissed: () => void
}
interface IWarnForcePushState {
readonly askForConfirmationOnForcePush: boolean
}
export class WarnForcePushDialog extends React.Component<
IWarnForcePushProps,
IWarnForcePushState
> {
public constructor(props: IWarnForcePushProps) {
super(props)
this.state = {
askForConfirmationOnForcePush: props.askForConfirmationOnForcePush,
}
}
public render() {
const { operation, onDismissed } = this.props
const title = __DARWIN__
? `${operation} Will Require Force Push`
: `${operation} will require force push'`
return (
<Dialog
title={title}
onDismissed={this.props.onDismissed}
onSubmit={this.onBegin}
dismissable={false}
type="warning"
>
<DialogContent>
<p>Are you sure you want to {operation}?</p>
<p>
At the end of the {operation.toLowerCase()} flow, GitHub Desktop
will enable you to force push the branch to update the upstream
branch. Force pushing will alter the history on the remote and
potentially cause problems for others collaborating on this branch.
</p>
<div>
<Checkbox
label="Do not show this message again"
value={
this.state.askForConfirmationOnForcePush
? CheckboxValue.Off
: CheckboxValue.On
}
onChange={this.onAskForConfirmationOnForcePushChanged}
/>
</div>
</DialogContent>
<DialogFooter>
<OkCancelButtonGroup
okButtonText={
__DARWIN__ ? `Begin ${operation}` : `Begin ${operation}`
}
onCancelButtonClick={this.props.onDismissed}
/>
</DialogFooter>
</Dialog>
)
}
private onAskForConfirmationOnForcePushChanged = (
event: React.FormEvent<HTMLInputElement>
) => {
const value = !event.currentTarget.checked
this.setState({ askForConfirmationOnForcePush: value })
}
private onBegin = async () => {
this.props.dispatcher.setConfirmForcePushSetting(
this.state.askForConfirmationOnForcePush
)
this.props.onBegin()
}
}
| Create resusable warn force push-dialog | Create resusable warn force push-dialog
| TypeScript | mit | j-f1/forked-desktop,desktop/desktop,artivilla/desktop,j-f1/forked-desktop,desktop/desktop,desktop/desktop,shiftkey/desktop,shiftkey/desktop,say25/desktop,shiftkey/desktop,say25/desktop,j-f1/forked-desktop,shiftkey/desktop,j-f1/forked-desktop,artivilla/desktop,artivilla/desktop,say25/desktop,say25/desktop,desktop/desktop,artivilla/desktop | ---
+++
@@ -0,0 +1,101 @@
+import * as React from 'react'
+import { Checkbox, CheckboxValue } from '../lib/checkbox'
+import { Dispatcher } from '../dispatcher'
+import { DialogFooter, DialogContent, Dialog } from '../dialog'
+import { OkCancelButtonGroup } from '../dialog/ok-cancel-button-group'
+
+interface IWarnForcePushProps {
+ /**
+ * This is expected to be capitalized for correct output on windows and macOs.
+ *
+ * Examples:
+ * - Rebase
+ * - Squash
+ * - Reorder
+ */
+ readonly operation: string
+ readonly dispatcher: Dispatcher
+ readonly askForConfirmationOnForcePush: boolean
+ readonly onBegin: () => void
+ readonly onDismissed: () => void
+}
+
+interface IWarnForcePushState {
+ readonly askForConfirmationOnForcePush: boolean
+}
+
+export class WarnForcePushDialog extends React.Component<
+ IWarnForcePushProps,
+ IWarnForcePushState
+> {
+ public constructor(props: IWarnForcePushProps) {
+ super(props)
+
+ this.state = {
+ askForConfirmationOnForcePush: props.askForConfirmationOnForcePush,
+ }
+ }
+
+ public render() {
+ const { operation, onDismissed } = this.props
+
+ const title = __DARWIN__
+ ? `${operation} Will Require Force Push`
+ : `${operation} will require force push'`
+
+ return (
+ <Dialog
+ title={title}
+ onDismissed={this.props.onDismissed}
+ onSubmit={this.onBegin}
+ dismissable={false}
+ type="warning"
+ >
+ <DialogContent>
+ <p>Are you sure you want to {operation}?</p>
+ <p>
+ At the end of the {operation.toLowerCase()} flow, GitHub Desktop
+ will enable you to force push the branch to update the upstream
+ branch. Force pushing will alter the history on the remote and
+ potentially cause problems for others collaborating on this branch.
+ </p>
+ <div>
+ <Checkbox
+ label="Do not show this message again"
+ value={
+ this.state.askForConfirmationOnForcePush
+ ? CheckboxValue.Off
+ : CheckboxValue.On
+ }
+ onChange={this.onAskForConfirmationOnForcePushChanged}
+ />
+ </div>
+ </DialogContent>
+ <DialogFooter>
+ <OkCancelButtonGroup
+ okButtonText={
+ __DARWIN__ ? `Begin ${operation}` : `Begin ${operation}`
+ }
+ onCancelButtonClick={this.props.onDismissed}
+ />
+ </DialogFooter>
+ </Dialog>
+ )
+ }
+
+ private onAskForConfirmationOnForcePushChanged = (
+ event: React.FormEvent<HTMLInputElement>
+ ) => {
+ const value = !event.currentTarget.checked
+
+ this.setState({ askForConfirmationOnForcePush: value })
+ }
+
+ private onBegin = async () => {
+ this.props.dispatcher.setConfirmForcePushSetting(
+ this.state.askForConfirmationOnForcePush
+ )
+
+ this.props.onBegin()
+ }
+} |
|
90f8544c853f695ea0bdaaeac20d79e9a49f803d | applications/web/pages/auth/index.tsx | applications/web/pages/auth/index.tsx | import React, { FC , useEffect, useState } from "react";
import styled from "styled-components";
export const Main: FC = () => {
const [ code, setCode ] = useState("")
const [ codeState, setCodeState ] = useState("")
const [ auth, setAuth ] = useState(false)
const Message = styled.div`
width:600px;
padding: 30px;
font-size: 14px;
font-family: roboto;
justify-self: center;
position: absolute;
top: 200px;
left: 50%;
margin-left: -300px;
background-color: #f2f2f2;
border-radius: 4px;
`
useEffect( () =>{
const params = new URLSearchParams(window.location.search)
setCode(params.get("code"))
setCodeState(params.get("state"))
})
useEffect( () => {
if( code !== "" && codeState !== "") {
oauthGithub()
}
}, [code, codeState])
const oauthGithub = () => {
fetch(`https://play-oauth-server-gjjwxcr82.vercel.app/github?code=${code}&state=${codeState}`)
.then(res => res.json())
.then(data => {
if ( data.access_token !== undefined){
localStorage.setItem("token", data.access_token)
setAuth(true)
}
})
}
return (
<>
<Message>
{ auth
?
<>
<h3>Authentication Successful!</h3>
<p>Go back to the application and click on the 'Connect to Github' button again. You can close this window now.</p>
</>
:
<>
<h3>Authenticating...</h3>
</>
}
</Message>
</>
);
}
export default Main;
| Add auth login to client | Add auth login to client
| TypeScript | bsd-3-clause | nteract/composition,nteract/nteract,nteract/nteract,nteract/composition,nteract/composition,nteract/nteract,nteract/nteract,nteract/nteract | ---
+++
@@ -0,0 +1,68 @@
+import React, { FC , useEffect, useState } from "react";
+import styled from "styled-components";
+
+export const Main: FC = () => {
+const [ code, setCode ] = useState("")
+const [ codeState, setCodeState ] = useState("")
+const [ auth, setAuth ] = useState(false)
+
+const Message = styled.div`
+ width:600px;
+ padding: 30px;
+ font-size: 14px;
+ font-family: roboto;
+ justify-self: center;
+ position: absolute;
+ top: 200px;
+ left: 50%;
+ margin-left: -300px;
+ background-color: #f2f2f2;
+ border-radius: 4px;
+`
+
+
+useEffect( () =>{
+ const params = new URLSearchParams(window.location.search)
+ setCode(params.get("code"))
+ setCodeState(params.get("state"))
+})
+
+useEffect( () => {
+ if( code !== "" && codeState !== "") {
+ oauthGithub()
+ }
+}, [code, codeState])
+
+const oauthGithub = () => {
+ fetch(`https://play-oauth-server-gjjwxcr82.vercel.app/github?code=${code}&state=${codeState}`)
+ .then(res => res.json())
+ .then(data => {
+ if ( data.access_token !== undefined){
+ localStorage.setItem("token", data.access_token)
+ setAuth(true)
+ }
+ })
+}
+
+return (
+ <>
+ <Message>
+ { auth
+ ?
+ <>
+ <h3>Authentication Successful!</h3>
+
+ <p>Go back to the application and click on the 'Connect to Github' button again. You can close this window now.</p>
+ </>
+
+ :
+ <>
+ <h3>Authenticating...</h3>
+ </>
+ }
+ </Message>
+ </>
+ );
+}
+
+export default Main; |
|
3f49591cb8b9d34da2fc7a38c6a5bc942048c89e | src/pages/post/[date]/[name]/index.tsx | src/pages/post/[date]/[name]/index.tsx | import type {GetStaticProps} from "next"
import {TRPCError} from "@trpc/server"
import type {FC} from "react"
import {router} from "server/trpc/route"
import {Post} from "server/db/entity/Post"
import getEmptyPaths from "lib/util/getEmptyPaths"
interface Props {
post: Post
}
interface Query {
date: string
name: string
}
export const getStaticPaths = getEmptyPaths
export const getStaticProps: GetStaticProps<Props> = async ({params}) => {
const {date, name} = params as unknown as Query
try {
const post = await router.createCaller({}).query("post.getBySlug", {
slug: [date, name].join("/")
})
return {
props: {
post
}
}
} catch (error) {
if (error instanceof TRPCError && error.code === "NOT_FOUND") {
return {
notFound: true
}
}
throw error
}
}
const PostPage: FC<Props> = () => (
<div>Post will be here</div>
)
export default PostPage
| Add page for blog post | Add page for blog post
| TypeScript | mit | octet-stream/eri,octet-stream/eri | ---
+++
@@ -0,0 +1,49 @@
+import type {GetStaticProps} from "next"
+import {TRPCError} from "@trpc/server"
+import type {FC} from "react"
+
+import {router} from "server/trpc/route"
+import {Post} from "server/db/entity/Post"
+
+import getEmptyPaths from "lib/util/getEmptyPaths"
+
+interface Props {
+ post: Post
+}
+
+interface Query {
+ date: string
+ name: string
+}
+
+export const getStaticPaths = getEmptyPaths
+
+export const getStaticProps: GetStaticProps<Props> = async ({params}) => {
+ const {date, name} = params as unknown as Query
+
+ try {
+ const post = await router.createCaller({}).query("post.getBySlug", {
+ slug: [date, name].join("/")
+ })
+
+ return {
+ props: {
+ post
+ }
+ }
+ } catch (error) {
+ if (error instanceof TRPCError && error.code === "NOT_FOUND") {
+ return {
+ notFound: true
+ }
+ }
+
+ throw error
+ }
+}
+
+const PostPage: FC<Props> = () => (
+ <div>Post will be here</div>
+)
+
+export default PostPage |
|
be864c195e8b8513318aa9cec35423c35f18f642 | src/datastore/postgres/schema/v14.ts | src/datastore/postgres/schema/v14.ts | import { IDatabase } from "pg-promise";
export const runSchema = async(db: IDatabase<unknown>) => {
await db.none(`
ALTER TABLE events ALTER COLUMN roomid TEXT NOT NULL;
ALTER TABLE events ALTER COLUMN eventid TEXT NOT NULL;
ALTER TABLE events ALTER COLUMN slackchannel TEXT NOT NULL;
ALTER TABLE events ALTER COLUMN slackts TEXT NOT NULL;
ALTER TABLE events ALTER COLUMN extras TEXT NOT NULL;
`);
};
| Make columns in events not nullable | Make columns in events not nullable
| TypeScript | apache-2.0 | matrix-org/matrix-appservice-slack,matrix-org/matrix-appservice-slack,matrix-org/matrix-appservice-slack,matrix-org/matrix-appservice-slack | ---
+++
@@ -0,0 +1,11 @@
+import { IDatabase } from "pg-promise";
+
+export const runSchema = async(db: IDatabase<unknown>) => {
+ await db.none(`
+ ALTER TABLE events ALTER COLUMN roomid TEXT NOT NULL;
+ ALTER TABLE events ALTER COLUMN eventid TEXT NOT NULL;
+ ALTER TABLE events ALTER COLUMN slackchannel TEXT NOT NULL;
+ ALTER TABLE events ALTER COLUMN slackts TEXT NOT NULL;
+ ALTER TABLE events ALTER COLUMN extras TEXT NOT NULL;
+ `);
+}; |
|
c3c9a28a1c2dda05408cb3c40f7fa99259ebd1ff | app/db/migrations/1517782491551-RemoveMediaThumbs.ts | app/db/migrations/1517782491551-RemoveMediaThumbs.ts | import {MigrationInterface, QueryRunner} from "typeorm";
export class RemoveMediaThumbs1517782491551 implements MigrationInterface {
public async up(queryRunner: QueryRunner): Promise<any> {
console.log('Removing thumb_s3key from table media_storage')
queryRunner.query(`ALTER TABLE media_storage DROP COLUMN thumb_s3key`)
}
public async down(queryRunner: QueryRunner): Promise<any> {
console.log('Adding thumb_s3key to table media_storage (defaulting to "" for existing entries)')
queryRunner.query(`ALTER TABLE media_storage ADD COLUMN thumb_s3key VARCHAR(64) NOT NULL DEFAULT ''`)
queryRunner.query(`ALTER TABLE media_storage ALTER COLUMN thumb_s3key DROP DEFAULT`)
}
}
| Remove the thumb s3key from DB | Remove the thumb s3key from DB
| TypeScript | mit | seanmiddleditch/campman,seanmiddleditch/campman,seanmiddleditch/campman | ---
+++
@@ -0,0 +1,16 @@
+import {MigrationInterface, QueryRunner} from "typeorm";
+
+export class RemoveMediaThumbs1517782491551 implements MigrationInterface {
+
+ public async up(queryRunner: QueryRunner): Promise<any> {
+ console.log('Removing thumb_s3key from table media_storage')
+ queryRunner.query(`ALTER TABLE media_storage DROP COLUMN thumb_s3key`)
+ }
+
+ public async down(queryRunner: QueryRunner): Promise<any> {
+ console.log('Adding thumb_s3key to table media_storage (defaulting to "" for existing entries)')
+ queryRunner.query(`ALTER TABLE media_storage ADD COLUMN thumb_s3key VARCHAR(64) NOT NULL DEFAULT ''`)
+ queryRunner.query(`ALTER TABLE media_storage ALTER COLUMN thumb_s3key DROP DEFAULT`)
+ }
+
+} |
|
517e603bb2ba10002a9a43b4664f9cb28ad2db33 | webui/reactutil_test.ts | webui/reactutil_test.ts | /// <reference path="../node_modules/react-typescript/declarations/react.d.ts" />
import react = require('react');
import reactutil = require('./reactutil');
import testLib = require('../lib/test');
testLib.addTest('merge props', (assert) => {
assert.deepEqual(reactutil.mergeProps({
id: 'instanceId',
className: 'instanceClass',
onClick: 'event handler'
},{
className: 'componentClass'
}),{
id: 'instanceId',
className: 'componentClass instanceClass',
onClick: 'event handler'
});
});
testLib.addTest('map to component array', (assert) => {
var firstChild = react.DOM.div({id:'first'});
var secondChild = react.DOM.div({id:'second'});
var map = {
firstChild: firstChild,
secondChild: secondChild
};
var ary = reactutil.mapToComponentArray(map);
ary.forEach((_component) => {
var component = <any>_component;
if (component.props.id == 'first') {
assert.equal(component.props.key, 'firstChild');
} else if (component.props.id == 'second') {
assert.equal(component.props.key, 'secondChild');
}
});
});
testLib.start();
| Add unit test module for webui/reactutil | Add unit test module for webui/reactutil
| TypeScript | bsd-3-clause | robertknight/passcards,robertknight/passcards,robertknight/passcards,robertknight/passcards | ---
+++
@@ -0,0 +1,42 @@
+/// <reference path="../node_modules/react-typescript/declarations/react.d.ts" />
+
+import react = require('react');
+
+import reactutil = require('./reactutil');
+import testLib = require('../lib/test');
+
+testLib.addTest('merge props', (assert) => {
+ assert.deepEqual(reactutil.mergeProps({
+ id: 'instanceId',
+ className: 'instanceClass',
+ onClick: 'event handler'
+ },{
+ className: 'componentClass'
+ }),{
+ id: 'instanceId',
+ className: 'componentClass instanceClass',
+ onClick: 'event handler'
+ });
+});
+
+testLib.addTest('map to component array', (assert) => {
+ var firstChild = react.DOM.div({id:'first'});
+ var secondChild = react.DOM.div({id:'second'});
+ var map = {
+ firstChild: firstChild,
+ secondChild: secondChild
+ };
+ var ary = reactutil.mapToComponentArray(map);
+
+ ary.forEach((_component) => {
+ var component = <any>_component;
+ if (component.props.id == 'first') {
+ assert.equal(component.props.key, 'firstChild');
+ } else if (component.props.id == 'second') {
+ assert.equal(component.props.key, 'secondChild');
+ }
+ });
+});
+
+testLib.start();
+ |
|
75949578ff56622ed841999425dab60044016f02 | tests/cases/fourslash/getDeclarationDiagnostics.ts | tests/cases/fourslash/getDeclarationDiagnostics.ts | /// <reference path="fourslash.ts" />
// @declaration: true
// @out: true
// @Filename: inputFile1.ts
//// module m {
//// export class C implements I { }
//// interface I { }
//// } /*1*/
// @Filename: input2.ts
//// var x = "hello world"; /*2*/
debugger;
goTo.marker("1");
verify.numberOfErrorsInCurrentFile(1);
goTo.marker("2");
verify.numberOfErrorsInCurrentFile(0);
| Add test case to make sure that we only report an error from target file | Add test case to make sure that we only report an error from target file
| TypeScript | apache-2.0 | blakeembrey/TypeScript,billti/TypeScript,mszczepaniak/TypeScript,pcan/TypeScript,shiftkey/TypeScript,evgrud/TypeScript,Eyas/TypeScript,chuckjaz/TypeScript,DanielRosenwasser/TypeScript,moander/TypeScript,evgrud/TypeScript,OlegDokuka/TypeScript,keir-rex/TypeScript,thr0w/Thr0wScript,zhengbli/TypeScript,Microsoft/TypeScript,suto/TypeScript,vilic/TypeScript,SaschaNaz/TypeScript,mihailik/TypeScript,microsoft/TypeScript,mauricionr/TypeScript,ziacik/TypeScript,mmoskal/TypeScript,zmaruo/TypeScript,hitesh97/TypeScript,mmoskal/TypeScript,shovon/TypeScript,matthewjh/TypeScript,RyanCavanaugh/TypeScript,DLehenbauer/TypeScript,ionux/TypeScript,Mqgh2013/TypeScript,samuelhorwitz/typescript,msynk/TypeScript,fearthecowboy/TypeScript,nojvek/TypeScript,Microsoft/TypeScript,jamesrmccallum/TypeScript,rgbkrk/TypeScript,vilic/TypeScript,RyanCavanaugh/TypeScript,weswigham/TypeScript,ropik/TypeScript,chuckjaz/TypeScript,bpowers/TypeScript,jdavidberger/TypeScript,tempbottle/TypeScript,plantain-00/TypeScript,Eyas/TypeScript,ziacik/TypeScript,keir-rex/TypeScript,progre/TypeScript,AbubakerB/TypeScript,bpowers/TypeScript,Raynos/TypeScript,AbubakerB/TypeScript,JohnZ622/TypeScript,pcan/TypeScript,ropik/TypeScript,jbondc/TypeScript,SimoneGianni/TypeScript,Viromo/TypeScript,Eyas/TypeScript,suto/TypeScript,samuelhorwitz/typescript,ziacik/TypeScript,billti/TypeScript,plantain-00/TypeScript,jeremyepling/TypeScript,evgrud/TypeScript,SaschaNaz/TypeScript,Raynos/TypeScript,microsoft/TypeScript,hitesh97/TypeScript,jnetterf/typescript-react-jsx,minestarks/TypeScript,fabioparra/TypeScript,webhost/TypeScript,erikmcc/TypeScript,Eyas/TypeScript,msynk/TypeScript,MartyIX/TypeScript,nojvek/TypeScript,fdecampredon/jsx-typescript,keir-rex/TypeScript,shiftkey/TypeScript,erikmcc/TypeScript,AbubakerB/TypeScript,jamesrmccallum/TypeScript,kpreisser/TypeScript,fabioparra/TypeScript,synaptek/TypeScript,rodrigues-daniel/TypeScript,thr0w/Thr0wScript,yortus/TypeScript,kumikumi/TypeScript,shanexu/TypeScript,mihailik/TypeScript,minestarks/TypeScript,jteplitz602/TypeScript,nojvek/TypeScript,impinball/TypeScript,zhengbli/TypeScript,nagyistoce/TypeScript,yortus/TypeScript,donaldpipowitch/TypeScript,thr0w/Thr0wScript,bpowers/TypeScript,gonifade/TypeScript,tinganho/TypeScript,kpreisser/TypeScript,jeremyepling/TypeScript,DanielRosenwasser/TypeScript,samuelhorwitz/typescript,moander/TypeScript,hitesh97/TypeScript,jteplitz602/TypeScript,OlegDokuka/TypeScript,progre/TypeScript,ziacik/TypeScript,RReverser/TypeScript,yukulele/TypeScript,yazeng/TypeScript,HereSinceres/TypeScript,kimamula/TypeScript,fdecampredon/jsx-typescript,abbasmhd/TypeScript,abbasmhd/TypeScript,jwbay/TypeScript,fdecampredon/jsx-typescript,mcanthony/TypeScript,zmaruo/TypeScript,minestarks/TypeScript,enginekit/TypeScript,DanielRosenwasser/TypeScript,moander/TypeScript,sassson/TypeScript,jwbay/TypeScript,synaptek/TypeScript,pcan/TypeScript,blakeembrey/TypeScript,mihailik/TypeScript,impinball/TypeScript,ionux/TypeScript,mcanthony/TypeScript,sassson/TypeScript,fabioparra/TypeScript,evgrud/TypeScript,TukekeSoft/TypeScript,kumikumi/TypeScript,Mqgh2013/TypeScript,tinganho/TypeScript,suto/TypeScript,basarat/TypeScript,Viromo/TypeScript,jbondc/TypeScript,kimamula/TypeScript,donaldpipowitch/TypeScript,kimamula/TypeScript,alexeagle/TypeScript,Viromo/TypeScript,impinball/TypeScript,mauricionr/TypeScript,blakeembrey/TypeScript,alexeagle/TypeScript,jamesrmccallum/TypeScript,SmallAiTT/TypeScript,germ13/TypeScript,Microsoft/TypeScript,Mqgh2013/TypeScript,germ13/TypeScript,shovon/TypeScript,shanexu/TypeScript,TukekeSoft/TypeScript,kitsonk/TypeScript,shanexu/TypeScript,chocolatechipui/TypeScript,kimamula/TypeScript,DLehenbauer/TypeScript,tempbottle/TypeScript,enginekit/TypeScript,yazeng/TypeScript,webhost/TypeScript,DanielRosenwasser/TypeScript,mcanthony/TypeScript,JohnZ622/TypeScript,kumikumi/TypeScript,SimoneGianni/TypeScript,chuckjaz/TypeScript,mmoskal/TypeScript,OlegDokuka/TypeScript,mszczepaniak/TypeScript,donaldpipowitch/TypeScript,progre/TypeScript,kingland/TypeScript,jdavidberger/TypeScript,weswigham/TypeScript,mmoskal/TypeScript,gonifade/TypeScript,jbondc/TypeScript,TukekeSoft/TypeScript,nagyistoce/TypeScript,MartyIX/TypeScript,germ13/TypeScript,SmallAiTT/TypeScript,chocolatechipui/TypeScript,erikmcc/TypeScript,RReverser/TypeScript,RyanCavanaugh/TypeScript,rodrigues-daniel/TypeScript,jeremyepling/TypeScript,DLehenbauer/TypeScript,MartyIX/TypeScript,ropik/TypeScript,nagyistoce/TypeScript,abbasmhd/TypeScript,MartyIX/TypeScript,rodrigues-daniel/TypeScript,sassson/TypeScript,kpreisser/TypeScript,ropik/TypeScript,vilic/TypeScript,ZLJASON/TypeScript,alexeagle/TypeScript,nycdotnet/TypeScript,hoanhtien/TypeScript,SimoneGianni/TypeScript,AbubakerB/TypeScript,basarat/TypeScript,jteplitz602/TypeScript,SaschaNaz/TypeScript,jdavidberger/TypeScript,shovon/TypeScript,RReverser/TypeScript,JohnZ622/TypeScript,synaptek/TypeScript,yukulele/TypeScript,blakeembrey/TypeScript,donaldpipowitch/TypeScript,tinganho/TypeScript,rgbkrk/TypeScript,moander/TypeScript,kingland/TypeScript,gonifade/TypeScript,ZLJASON/TypeScript,nycdotnet/TypeScript,fdecampredon/jsx-typescript,ZLJASON/TypeScript,fearthecowboy/TypeScript,ionux/TypeScript,rodrigues-daniel/TypeScript,kingland/TypeScript,HereSinceres/TypeScript,rgbkrk/TypeScript,shanexu/TypeScript,samuelhorwitz/typescript,yukulele/TypeScript,Viromo/TypeScript,mszczepaniak/TypeScript,fabioparra/TypeScript,weswigham/TypeScript,nojvek/TypeScript,erikmcc/TypeScript,mihailik/TypeScript,plantain-00/TypeScript,nycdotnet/TypeScript,tempbottle/TypeScript,chocolatechipui/TypeScript,synaptek/TypeScript,kitsonk/TypeScript,enginekit/TypeScript,zhengbli/TypeScript,zmaruo/TypeScript,mauricionr/TypeScript,thr0w/Thr0wScript,Raynos/TypeScript,jwbay/TypeScript,matthewjh/TypeScript,gdi2290/TypeScript,Raynos/TypeScript,mauricionr/TypeScript,ionux/TypeScript,fearthecowboy/TypeScript,basarat/TypeScript,billti/TypeScript,webhost/TypeScript,chuckjaz/TypeScript,JohnZ622/TypeScript,DLehenbauer/TypeScript,plantain-00/TypeScript,shiftkey/TypeScript,SmallAiTT/TypeScript,matthewjh/TypeScript,yortus/TypeScript,hoanhtien/TypeScript,HereSinceres/TypeScript,yazeng/TypeScript,msynk/TypeScript,vilic/TypeScript,SaschaNaz/TypeScript,basarat/TypeScript,hoanhtien/TypeScript,yortus/TypeScript,microsoft/TypeScript,jnetterf/typescript-react-jsx,jwbay/TypeScript,jnetterf/typescript-react-jsx,kitsonk/TypeScript,nycdotnet/TypeScript,mcanthony/TypeScript | ---
+++
@@ -0,0 +1,20 @@
+/// <reference path="fourslash.ts" />
+
+// @declaration: true
+// @out: true
+
+// @Filename: inputFile1.ts
+//// module m {
+//// export class C implements I { }
+//// interface I { }
+//// } /*1*/
+
+// @Filename: input2.ts
+//// var x = "hello world"; /*2*/
+
+debugger;
+goTo.marker("1");
+verify.numberOfErrorsInCurrentFile(1);
+
+goTo.marker("2");
+verify.numberOfErrorsInCurrentFile(0); |
|
7ad4716f24002ef48a0c0562b938c09ce0dd17a4 | tests/test_newton.ts | tests/test_newton.ts | import * as Newton from '../src/newton';
import { expect } from 'chai';
import 'mocha';
describe('Newton numeric solver', () => {
it('Root of f(x) = x - 1. Should return approximately 1', () => {
const result = Newton.NewtonRoot((x) => x - 1, (x) => 1, 0, 0.001);
expect(result).approximately(1,0.1);
expect(result - 1).approximately(0,0.001);
});
it('Root of f(x) = cos^2(x). Should return approximately pi/2', () => {
const result = Newton.NewtonRoot((x) => Math.cos(x)*Math.cos(x), (x) => -2*Math.cos(x)*Math.sin(x), Math.PI/4, 0.001);
expect(result).approximately(Math.PI/2,0.1);
expect(Math.cos(result)*Math.cos(result)).approximately(0,0.001);
});
}); | Add test for Newton Numeric Solver | Add test for Newton Numeric Solver
| TypeScript | mit | THeK3nger/calendar-generator,THeK3nger/calendar-generator | ---
+++
@@ -0,0 +1,17 @@
+import * as Newton from '../src/newton';
+
+import { expect } from 'chai';
+import 'mocha';
+
+describe('Newton numeric solver', () => {
+ it('Root of f(x) = x - 1. Should return approximately 1', () => {
+ const result = Newton.NewtonRoot((x) => x - 1, (x) => 1, 0, 0.001);
+ expect(result).approximately(1,0.1);
+ expect(result - 1).approximately(0,0.001);
+ });
+ it('Root of f(x) = cos^2(x). Should return approximately pi/2', () => {
+ const result = Newton.NewtonRoot((x) => Math.cos(x)*Math.cos(x), (x) => -2*Math.cos(x)*Math.sin(x), Math.PI/4, 0.001);
+ expect(result).approximately(Math.PI/2,0.1);
+ expect(Math.cos(result)*Math.cos(result)).approximately(0,0.001);
+ });
+}); |
|
1a092b0b221986a65fedecdcb501e4e34ebc8aab | types/styled-jsx/styled-jsx-tests.tsx | types/styled-jsx/styled-jsx-tests.tsx | import * as React from 'react';
import * as css from 'styled-jsx/css';
import flushToReact, { flushToHTML } from 'styled-jsx/server';
const styled = (
<div>
<style jsx>{`
color: rebeccapurple;
`}</style>
</div>
);
const styledGlobal = (
<div>
<style jsx global>{`
color: rebeccapurple;
`}</style>
</div>
);
const buttonColor = 'red';
const separatedCSS = css`button { color: ${buttonColor}; }`;
const withSeparatedCSS = (
<div>
<style jsx>{separatedCSS}</style>
</div>
);
const stylesChildren = flushToReact();
const jsxToRender = (
<head>{ stylesChildren }</head>
);
const stylesAsString: string = flushToHTML();
const html = `
<head>${stylesAsString}</head>
`;
| import * as React from 'react';
import * as css from 'styled-jsx/css';
import flushToReact, { flushToHTML } from 'styled-jsx/server';
const styled = (
<div>
<style jsx>{`
color: rebeccapurple;
`}</style>
</div>
);
const styledGlobal = (
<div>
<style jsx global>{`
color: rebeccapurple;
`}</style>
</div>
);
const buttonColor = 'red';
const separatedCSS = css`button { color: ${buttonColor}; }`;
const withSeparatedCSS = (
<div>
<style jsx>{separatedCSS}</style>
</div>
);
const globalCSS = css.global`body { margin: 0; }`;
const withGlobalCSS = (
<div>
<style jsx global>{globalCSS}</style>
</div>
);
const resolvedCSS = css.resolve`a { color: green; }`;
const withResolvedCSS = (
<div>
<button className={resolvedCSS.className}>About</button>
{resolvedCSS.styles}
</div>
);
const dynamicResolvedCSS = css.resolve`a { color: ${buttonColor}; }`;
const withDynamicResolvedCSS = (
<div>
<button className={dynamicResolvedCSS.className}>About</button>
{dynamicResolvedCSS.styles}
</div>
);
const stylesChildren = flushToReact();
const jsxToRender = (
<head>{ stylesChildren }</head>
);
const stylesAsString: string = flushToHTML();
const html = `
<head>${stylesAsString}</head>
`;
| Update styled-jsx/css typings, add tests for methods css.global and css.resolve | Update styled-jsx/css typings, add tests for methods css.global and css.resolve
| TypeScript | mit | dsebastien/DefinitelyTyped,AgentME/DefinitelyTyped,borisyankov/DefinitelyTyped,georgemarshall/DefinitelyTyped,AgentME/DefinitelyTyped,magny/DefinitelyTyped,AgentME/DefinitelyTyped,AgentME/DefinitelyTyped,georgemarshall/DefinitelyTyped,markogresak/DefinitelyTyped,dsebastien/DefinitelyTyped,georgemarshall/DefinitelyTyped,mcliment/DefinitelyTyped,magny/DefinitelyTyped,borisyankov/DefinitelyTyped,georgemarshall/DefinitelyTyped | ---
+++
@@ -26,6 +26,29 @@
</div>
);
+const globalCSS = css.global`body { margin: 0; }`;
+const withGlobalCSS = (
+ <div>
+ <style jsx global>{globalCSS}</style>
+ </div>
+);
+
+const resolvedCSS = css.resolve`a { color: green; }`;
+const withResolvedCSS = (
+ <div>
+ <button className={resolvedCSS.className}>About</button>
+ {resolvedCSS.styles}
+ </div>
+);
+
+const dynamicResolvedCSS = css.resolve`a { color: ${buttonColor}; }`;
+const withDynamicResolvedCSS = (
+ <div>
+ <button className={dynamicResolvedCSS.className}>About</button>
+ {dynamicResolvedCSS.styles}
+ </div>
+);
+
const stylesChildren = flushToReact();
const jsxToRender = (
<head>{ stylesChildren }</head> |
efd5c28745c3d673d2c4e877ee4be19080264b5c | src/components/HitTable/EmptyHitTable.tsx | src/components/HitTable/EmptyHitTable.tsx | import * as React from 'react';
import { EmptyState } from '@shopify/polaris';
export interface Props {
onAction: () => void;
}
const EmptyHitTable = ({ onAction }: Props) => {
return (
<EmptyState
heading="You haven't searched any HITs yet."
action={{
content: 'Search HITs',
onAction
}}
image="https://cdn.shopify.com/s/files/1/0757/9955/files/empty-state.svg"
>
<p>Search some HITs to get started.</p>
</EmptyState>
);
};
export default EmptyHitTable; | Add EmptyState component for when no HITs are in the redux store | Add EmptyState component for when no HITs are in the redux store
| TypeScript | mit | Anveio/mturk-engine,Anveio/mturk-engine,Anveio/mturk-engine | ---
+++
@@ -0,0 +1,23 @@
+import * as React from 'react';
+import { EmptyState } from '@shopify/polaris';
+
+export interface Props {
+ onAction: () => void;
+}
+
+const EmptyHitTable = ({ onAction }: Props) => {
+ return (
+ <EmptyState
+ heading="You haven't searched any HITs yet."
+ action={{
+ content: 'Search HITs',
+ onAction
+ }}
+ image="https://cdn.shopify.com/s/files/1/0757/9955/files/empty-state.svg"
+ >
+ <p>Search some HITs to get started.</p>
+ </EmptyState>
+ );
+};
+
+export default EmptyHitTable; |
|
00839f3c91dc8fafb514b2fd3a5e174f4ae8de3e | ui/src/flux/components/FluxHeader.tsx | ui/src/flux/components/FluxHeader.tsx | import React, {PureComponent} from 'react'
import {connect} from 'react-redux'
import FluxOverlay from 'src/flux/components/FluxOverlay'
import {OverlayContext} from 'src/shared/components/OverlayTechnology'
import {
showOverlay as showOverlayAction,
ShowOverlay,
} from 'src/shared/actions/overlayTechnology'
import {Service} from 'src/types'
interface Props {
showOverlay: ShowOverlay
service: Service
}
class FluxHeader extends PureComponent<Props> {
public render() {
return (
<div className="page-header full-width">
<div className="page-header--container">
<div className="page-header--left">
<h1 className="page-header--title">Flux Editor</h1>
</div>
<div className="page-header--right">
<button onClick={this.overlay} className="btn btn-sm btn-default">
Edit Connection
</button>
</div>
</div>
</div>
)
}
private overlay = () => {
const {showOverlay, service} = this.props
showOverlay(
<OverlayContext.Consumer>
{({onDismissOverlay}) => (
<FluxOverlay
mode="edit"
service={service}
onDismiss={onDismissOverlay}
/>
)}
</OverlayContext.Consumer>,
{}
)
}
}
const mdtp = {
showOverlay: showOverlayAction,
}
export default connect(null, mdtp)(FluxHeader)
| import React, {PureComponent} from 'react'
import {connect} from 'react-redux'
import FluxOverlay from 'src/flux/components/FluxOverlay'
import {OverlayContext} from 'src/shared/components/OverlayTechnology'
import PageHeader from 'src/shared/components/PageHeader'
import {
showOverlay as showOverlayAction,
ShowOverlay,
} from 'src/shared/actions/overlayTechnology'
import {Service} from 'src/types'
interface Props {
showOverlay: ShowOverlay
service: Service
}
class FluxHeader extends PureComponent<Props> {
public render() {
return (
<PageHeader
title="Flux Editor"
fullWidth={true}
renderOptions={this.renderOptions}
/>
)
}
private renderOptions = (): JSX.Element => {
return (
<button onClick={this.overlay} className="btn btn-sm btn-default">
Edit Connection
</button>
)
}
private overlay = () => {
const {showOverlay, service} = this.props
showOverlay(
<OverlayContext.Consumer>
{({onDismissOverlay}) => (
<FluxOverlay
mode="edit"
service={service}
onDismiss={onDismissOverlay}
/>
)}
</OverlayContext.Consumer>,
{}
)
}
}
const mdtp = {
showOverlay: showOverlayAction,
}
export default connect(null, mdtp)(FluxHeader)
| Implement PageHeader in Flux Editor page | Implement PageHeader in Flux Editor page
| TypeScript | mit | influxdb/influxdb,influxdb/influxdb,mark-rushakoff/influxdb,mark-rushakoff/influxdb,nooproblem/influxdb,influxdata/influxdb,mark-rushakoff/influxdb,nooproblem/influxdb,nooproblem/influxdb,mark-rushakoff/influxdb,influxdata/influxdb,mark-rushakoff/influxdb,nooproblem/influxdb,li-ang/influxdb,influxdb/influxdb,li-ang/influxdb,influxdb/influxdb,influxdb/influxdb,nooproblem/influxdb,mark-rushakoff/influxdb,influxdb/influxdb | ---
+++
@@ -3,6 +3,7 @@
import FluxOverlay from 'src/flux/components/FluxOverlay'
import {OverlayContext} from 'src/shared/components/OverlayTechnology'
+import PageHeader from 'src/shared/components/PageHeader'
import {
showOverlay as showOverlayAction,
ShowOverlay,
@@ -18,18 +19,19 @@
class FluxHeader extends PureComponent<Props> {
public render() {
return (
- <div className="page-header full-width">
- <div className="page-header--container">
- <div className="page-header--left">
- <h1 className="page-header--title">Flux Editor</h1>
- </div>
- <div className="page-header--right">
- <button onClick={this.overlay} className="btn btn-sm btn-default">
- Edit Connection
- </button>
- </div>
- </div>
- </div>
+ <PageHeader
+ title="Flux Editor"
+ fullWidth={true}
+ renderOptions={this.renderOptions}
+ />
+ )
+ }
+
+ private renderOptions = (): JSX.Element => {
+ return (
+ <button onClick={this.overlay} className="btn btn-sm btn-default">
+ Edit Connection
+ </button>
)
}
|
78237739ba60354e6347946b19db7bafd9a1b015 | tests/cases/fourslash/jsDocGenerics1.ts | tests/cases/fourslash/jsDocGenerics1.ts | ///<reference path="fourslash.ts" />
// @allowNonTsExtensions: true
// @Filename: ref.d.ts
//// namespace Thing {
//// export interface Thung {
//// a: number;
//// ]
//// ]
// @Filename: Foo.js
////
//// /** @type {Array<number>} */
//// var v;
//// v[0]./*1*/
////
//// /** @type {{x: Array<Array<number>>}} */
//// var w;
//// w.x[0][0]./*2*/
////
//// /** @type {Array<Thing.Thung>} */
//// var x;
//// x[0].a./*3*/
goTo.marker('1');
verify.memberListContains("toFixed", /*displayText:*/ undefined, /*documentation*/ undefined, "method");
goTo.marker('2');
verify.memberListContains("toFixed", /*displayText:*/ undefined, /*documentation*/ undefined, "method");
goTo.marker('3');
verify.memberListContains("toFixed", /*displayText:*/ undefined, /*documentation*/ undefined, "method");
| Add more complex test scenarios | Add more complex test scenarios
(cherry picked from commit e347c3711cc4b85eda34f1aba844e1a6576ff40c)
# Conflicts:
# tests/cases/fourslash/jsDocGenerics1.ts
| TypeScript | apache-2.0 | fabioparra/TypeScript,fabioparra/TypeScript,fabioparra/TypeScript,fabioparra/TypeScript | ---
+++
@@ -0,0 +1,34 @@
+///<reference path="fourslash.ts" />
+
+// @allowNonTsExtensions: true
+// @Filename: ref.d.ts
+//// namespace Thing {
+//// export interface Thung {
+//// a: number;
+//// ]
+//// ]
+
+
+// @Filename: Foo.js
+////
+//// /** @type {Array<number>} */
+//// var v;
+//// v[0]./*1*/
+////
+//// /** @type {{x: Array<Array<number>>}} */
+//// var w;
+//// w.x[0][0]./*2*/
+////
+//// /** @type {Array<Thing.Thung>} */
+//// var x;
+//// x[0].a./*3*/
+
+
+goTo.marker('1');
+verify.memberListContains("toFixed", /*displayText:*/ undefined, /*documentation*/ undefined, "method");
+
+goTo.marker('2');
+verify.memberListContains("toFixed", /*displayText:*/ undefined, /*documentation*/ undefined, "method");
+
+goTo.marker('3');
+verify.memberListContains("toFixed", /*displayText:*/ undefined, /*documentation*/ undefined, "method"); |
|
6ef0a3f2aef3a4575a71cb185a57f75811221509 | server/src/util/Stack.ts | server/src/util/Stack.ts | // Super simple stack
export default class Stack<T> {
private stack: T[];
constructor() {
this.stack = [];
}
get size() {
return this.stack.length;
}
public push(value: T): void {
this.stack.push(value);
}
public pop(): T {
return this.stack.pop();
}
public peek(): T {
return this.stack[this.size - 1];
}
public empty(): boolean {
return this.size === 0;
}
}
| Add a super simple stack | Add a super simple stack
| TypeScript | mit | rubyide/vscode-ruby,rubyide/vscode-ruby,rubyide/vscode-ruby,rubyide/vscode-ruby,rubyide/vscode-ruby | ---
+++
@@ -0,0 +1,28 @@
+// Super simple stack
+export default class Stack<T> {
+ private stack: T[];
+
+ constructor() {
+ this.stack = [];
+ }
+
+ get size() {
+ return this.stack.length;
+ }
+
+ public push(value: T): void {
+ this.stack.push(value);
+ }
+
+ public pop(): T {
+ return this.stack.pop();
+ }
+
+ public peek(): T {
+ return this.stack[this.size - 1];
+ }
+
+ public empty(): boolean {
+ return this.size === 0;
+ }
+} |
|
0dcada6135b4711c3f550763b0ab2dba12e65dfa | src/api/resource.spec.ts | src/api/resource.spec.ts | import {MockApi} from './mock';
import {describeComponent} from '../tests/component';
describeComponent('reactive queries', [], () => {
let mockApi: MockApi;
let unsubscribeRequestedSpy: jasmine.Spy;
beforeEach(() => {
mockApi = new MockApi();
unsubscribeRequestedSpy = jasmine.createSpy('unsubscribeRequestedSpy');
mockApi.whenPost('/api/queryobserver/unsubscribe', unsubscribeRequestedSpy);
mockApi.createResource('data');
mockApi.simulateDelay(true);
});
it('should be disposable', (done) => {
const subscriber1 = jasmine.createSpy('subscriber1');
const subscriber2 = jasmine.createSpy('subscriber2');
const subscriber3 = jasmine.createSpy('subscriber3');
mockApi.Data.query({}, {reactive: true}).subscribe(subscriber1).dispose();
mockApi.Data.query({}, {reactive: true}).subscribe(subscriber2).dispose();
const subscription3 = mockApi.Data.query({}, {reactive: true}).subscribe(subscriber3);
// Ensure these queries have been delayed.
expect(subscriber1).not.toHaveBeenCalled();
expect(subscriber2).not.toHaveBeenCalled();
expect(subscriber3).not.toHaveBeenCalled();
setTimeout(() => {
expect(subscriber1).not.toHaveBeenCalled();
expect(subscriber2).not.toHaveBeenCalled();
expect(subscriber3).toHaveBeenCalledTimes(1);
mockApi.addItem('data', {id: 1});
expect(subscriber1).not.toHaveBeenCalled();
expect(subscriber2).not.toHaveBeenCalled();
expect(subscriber3).toHaveBeenCalledTimes(2);
subscription3.dispose();
mockApi.addItem('data', {id: 1});
expect(subscriber3).toHaveBeenCalledTimes(2);
done();
}, 100);
});
describe('should make unsubscribe request', () => {
it('after disposing the subscription', (done) => {
const subscription1 = mockApi.Data.query({}, {reactive: true}).subscribe();
setTimeout(() => {
// QueryObserver is initialized.
expect(unsubscribeRequestedSpy).not.toHaveBeenCalled();
subscription1.dispose();
expect(unsubscribeRequestedSpy).toHaveBeenCalled();
done();
}, 100);
});
});
});
| Add unit tests for disposing subscriptions to a reactive query | Add unit tests for disposing subscriptions to a reactive query
| TypeScript | apache-2.0 | hadalin/resolwe-js,genialis/resolwe-js,genialis/resolwe-js,hadalin/resolwe-js | ---
+++
@@ -0,0 +1,65 @@
+import {MockApi} from './mock';
+import {describeComponent} from '../tests/component';
+
+describeComponent('reactive queries', [], () => {
+ let mockApi: MockApi;
+ let unsubscribeRequestedSpy: jasmine.Spy;
+
+ beforeEach(() => {
+ mockApi = new MockApi();
+ unsubscribeRequestedSpy = jasmine.createSpy('unsubscribeRequestedSpy');
+ mockApi.whenPost('/api/queryobserver/unsubscribe', unsubscribeRequestedSpy);
+
+ mockApi.createResource('data');
+ mockApi.simulateDelay(true);
+ });
+
+ it('should be disposable', (done) => {
+ const subscriber1 = jasmine.createSpy('subscriber1');
+ const subscriber2 = jasmine.createSpy('subscriber2');
+ const subscriber3 = jasmine.createSpy('subscriber3');
+
+ mockApi.Data.query({}, {reactive: true}).subscribe(subscriber1).dispose();
+ mockApi.Data.query({}, {reactive: true}).subscribe(subscriber2).dispose();
+ const subscription3 = mockApi.Data.query({}, {reactive: true}).subscribe(subscriber3);
+
+ // Ensure these queries have been delayed.
+ expect(subscriber1).not.toHaveBeenCalled();
+ expect(subscriber2).not.toHaveBeenCalled();
+ expect(subscriber3).not.toHaveBeenCalled();
+
+ setTimeout(() => {
+ expect(subscriber1).not.toHaveBeenCalled();
+ expect(subscriber2).not.toHaveBeenCalled();
+ expect(subscriber3).toHaveBeenCalledTimes(1);
+
+ mockApi.addItem('data', {id: 1});
+ expect(subscriber1).not.toHaveBeenCalled();
+ expect(subscriber2).not.toHaveBeenCalled();
+ expect(subscriber3).toHaveBeenCalledTimes(2);
+
+ subscription3.dispose();
+
+ mockApi.addItem('data', {id: 1});
+ expect(subscriber3).toHaveBeenCalledTimes(2);
+
+ done();
+ }, 100);
+ });
+
+ describe('should make unsubscribe request', () => {
+ it('after disposing the subscription', (done) => {
+ const subscription1 = mockApi.Data.query({}, {reactive: true}).subscribe();
+
+ setTimeout(() => {
+ // QueryObserver is initialized.
+ expect(unsubscribeRequestedSpy).not.toHaveBeenCalled();
+
+ subscription1.dispose();
+ expect(unsubscribeRequestedSpy).toHaveBeenCalled();
+
+ done();
+ }, 100);
+ });
+ });
+}); |
|
6ebcc6e15111dbecea9dce9d1f3f462917136bf9 | src/Test/Ast/SpoilerBlock.ts | src/Test/Ast/SpoilerBlock.ts | import { expect } from 'chai'
import Up from '../../index'
import { DocumentNode } from '../../SyntaxNodes/DocumentNode'
import { PlainTextNode } from '../../SyntaxNodes/PlainTextNode'
import { SectionSeparatorNode } from '../../SyntaxNodes/SectionSeparatorNode'
import { EmphasisNode } from '../../SyntaxNodes/EmphasisNode'
import { ParagraphNode } from '../../SyntaxNodes/ParagraphNode'
import { HeadingNode } from '../../SyntaxNodes/HeadingNode'
import { BlockquoteNode } from '../../SyntaxNodes/BlockquoteNode'
import { SpoilerBlockNode } from '../../SyntaxNodes/SpoilerBlockNode'
import { DescriptionListNode } from '../../SyntaxNodes/DescriptionListNode'
import { DescriptionListItem } from '../../SyntaxNodes/DescriptionListItem'
import { DescriptionTerm } from '../../SyntaxNodes/DescriptionTerm'
import { Description } from '../../SyntaxNodes/Description'
describe('A line consisting solely of "SPOILER:", followed by an indented block of text,', () => {
it('produces a spoiler block node', () => {
const text = `
SPOILER:
Ash said goodbye to Pikachu.
Luckily, Pikachu ultimately decided to stay with Ash.`
expect(Up.toAst(text)).to.be.eql(
new DocumentNode([
new SpoilerBlockNode([
new ParagraphNode([
new PlainTextNode('Hello, world!')
]),
new ParagraphNode([
new PlainTextNode('Goodbye, world!')
])
])
]))
})
}) | Add failing spoiler block test | Add failing spoiler block test
| TypeScript | mit | start/up,start/up | ---
+++
@@ -0,0 +1,37 @@
+import { expect } from 'chai'
+import Up from '../../index'
+import { DocumentNode } from '../../SyntaxNodes/DocumentNode'
+import { PlainTextNode } from '../../SyntaxNodes/PlainTextNode'
+import { SectionSeparatorNode } from '../../SyntaxNodes/SectionSeparatorNode'
+import { EmphasisNode } from '../../SyntaxNodes/EmphasisNode'
+import { ParagraphNode } from '../../SyntaxNodes/ParagraphNode'
+import { HeadingNode } from '../../SyntaxNodes/HeadingNode'
+import { BlockquoteNode } from '../../SyntaxNodes/BlockquoteNode'
+import { SpoilerBlockNode } from '../../SyntaxNodes/SpoilerBlockNode'
+import { DescriptionListNode } from '../../SyntaxNodes/DescriptionListNode'
+import { DescriptionListItem } from '../../SyntaxNodes/DescriptionListItem'
+import { DescriptionTerm } from '../../SyntaxNodes/DescriptionTerm'
+import { Description } from '../../SyntaxNodes/Description'
+
+
+describe('A line consisting solely of "SPOILER:", followed by an indented block of text,', () => {
+ it('produces a spoiler block node', () => {
+ const text = `
+SPOILER:
+ Ash said goodbye to Pikachu.
+
+ Luckily, Pikachu ultimately decided to stay with Ash.`
+
+ expect(Up.toAst(text)).to.be.eql(
+ new DocumentNode([
+ new SpoilerBlockNode([
+ new ParagraphNode([
+ new PlainTextNode('Hello, world!')
+ ]),
+ new ParagraphNode([
+ new PlainTextNode('Goodbye, world!')
+ ])
+ ])
+ ]))
+ })
+}) |
|
94579f9fa1b3aeca7fbc486c5e53c46786546fde | src/lib/plugins/AuthPlugin/AuthPlugin.ts | src/lib/plugins/AuthPlugin/AuthPlugin.ts | import {injectDependency, InjectionDecorator} from '../../core/InjectionClient'
import {exportDependency, PluginConfig, PluginConstructor} from '../../core/PluginConfig'
const AUTH_MANAGER = 'authManager'
export const injectAuth: InjectionDecorator = injectDependency(AUTH_MANAGER)
export const createAuthPlugin: (authClient: AuthClient) => PluginConstructor = (authClient: AuthClient) => {
class AuthManagerPlugin extends PluginConfig {
@exportDependency(AUTH_MANAGER)
authManager = new AuthManager(authClient)
}
return AuthManagerPlugin
}
export class AuthManager {
client: AuthClient
constructor(client: AuthClient) {
this.client = client
}
getToken() {
return this.client.getToken()
}
logout() {
return this.client.logout()
}
}
export interface AuthClient {
getToken(): string | null
logout(): void
}
| Add a basic auth Plugin | Add a basic auth Plugin
| TypeScript | mit | brightinteractive/bright-js-framework,brightinteractive/bright-js-framework,brightinteractive/bright-js-framework | ---
+++
@@ -0,0 +1,38 @@
+import {injectDependency, InjectionDecorator} from '../../core/InjectionClient'
+import {exportDependency, PluginConfig, PluginConstructor} from '../../core/PluginConfig'
+
+const AUTH_MANAGER = 'authManager'
+
+export const injectAuth: InjectionDecorator = injectDependency(AUTH_MANAGER)
+
+export const createAuthPlugin: (authClient: AuthClient) => PluginConstructor = (authClient: AuthClient) => {
+ class AuthManagerPlugin extends PluginConfig {
+ @exportDependency(AUTH_MANAGER)
+ authManager = new AuthManager(authClient)
+ }
+
+ return AuthManagerPlugin
+}
+
+export class AuthManager {
+
+ client: AuthClient
+
+ constructor(client: AuthClient) {
+ this.client = client
+ }
+
+ getToken() {
+ return this.client.getToken()
+ }
+
+ logout() {
+ return this.client.logout()
+ }
+}
+
+export interface AuthClient {
+ getToken(): string | null
+
+ logout(): void
+} |
|
79c5d11e92ca7e2551cb56a46e9e359d971775a9 | src/components/AccordionContext.spec.tsx | src/components/AccordionContext.spec.tsx | import * as React from 'react';
import { render } from 'react-testing-library';
import { Consumer, Provider } from './AccordionContext';
describe('ItemContext', () => {
it('renders children props', () => {
const { getByText } = render(
<Provider>
<Consumer>{(): string => 'Hello World'}</Consumer>
</Provider>,
);
expect(getByText('Hello World')).toBeTruthy();
});
});
| Add unit tests for AccordionContext | Add unit tests for AccordionContext
| TypeScript | mit | springload/react-accessible-accordion,springload/react-accessible-accordion,springload/react-accessible-accordion | ---
+++
@@ -0,0 +1,15 @@
+import * as React from 'react';
+import { render } from 'react-testing-library';
+import { Consumer, Provider } from './AccordionContext';
+
+describe('ItemContext', () => {
+ it('renders children props', () => {
+ const { getByText } = render(
+ <Provider>
+ <Consumer>{(): string => 'Hello World'}</Consumer>
+ </Provider>,
+ );
+
+ expect(getByText('Hello World')).toBeTruthy();
+ });
+}); |
|
287b3217bf37d4b63af69115cbd52721e5e770b9 | iterator/names-list/better-names-list.ts | iterator/names-list/better-names-list.ts | namespace BetterNamesList {
interface NamesIterator {
next(): string;
hasNext(): boolean;
}
interface NamesList {
getIterator(iterator: NamesIterator): NamesIterator;
}
class BetterNamesList implements NamesList {
private namesList: Array<string> = [];
add(name: string): void {
this.namesList.push(name);
}
deleteNameByIndex(index: number): void {
this.namesList.splice(index, 1);
}
getNameByIndex(index: number): string {
return this.namesList[index];
}
getLength(): number {
return this.namesList.length;
}
getIterator(iterator: NamesIterator): NamesIterator {
return iterator;
}
}
class NamesIteratorByOdd implements NamesIterator {
private namesList: BetterNamesList;
private currentIndex: number = 0;
constructor(namesList: BetterNamesList) {
this.namesList = namesList;
}
hasNext(): boolean {
return this.currentIndex < this.namesList.getLength();
}
next(): string {
const currentName: string = this.namesList.getNameByIndex(this.currentIndex);
this.currentIndex = this.currentIndex + 2;
return currentName;
}
}
const namesList: BetterNamesList = new BetterNamesList();
namesList.add('a');
namesList.add('b');
namesList.add('c');
const it: NamesIterator = namesList.getIterator(new NamesIteratorByOdd(namesList));
while (it.hasNext()) {
it.next();
}
}
| Add better names list implementation | Add better names list implementation
| TypeScript | mit | Erichain/design-patterns-in-typescript,Erichain/design-patterns-in-typescript | ---
+++
@@ -0,0 +1,66 @@
+namespace BetterNamesList {
+ interface NamesIterator {
+ next(): string;
+ hasNext(): boolean;
+ }
+
+interface NamesList {
+ getIterator(iterator: NamesIterator): NamesIterator;
+}
+
+class BetterNamesList implements NamesList {
+ private namesList: Array<string> = [];
+
+ add(name: string): void {
+ this.namesList.push(name);
+ }
+
+ deleteNameByIndex(index: number): void {
+ this.namesList.splice(index, 1);
+ }
+
+ getNameByIndex(index: number): string {
+ return this.namesList[index];
+ }
+
+ getLength(): number {
+ return this.namesList.length;
+ }
+
+ getIterator(iterator: NamesIterator): NamesIterator {
+ return iterator;
+ }
+}
+
+class NamesIteratorByOdd implements NamesIterator {
+ private namesList: BetterNamesList;
+ private currentIndex: number = 0;
+
+ constructor(namesList: BetterNamesList) {
+ this.namesList = namesList;
+ }
+
+ hasNext(): boolean {
+ return this.currentIndex < this.namesList.getLength();
+ }
+
+ next(): string {
+ const currentName: string = this.namesList.getNameByIndex(this.currentIndex);
+ this.currentIndex = this.currentIndex + 2;
+
+ return currentName;
+ }
+}
+
+ const namesList: BetterNamesList = new BetterNamesList();
+
+ namesList.add('a');
+ namesList.add('b');
+ namesList.add('c');
+
+ const it: NamesIterator = namesList.getIterator(new NamesIteratorByOdd(namesList));
+
+ while (it.hasNext()) {
+ it.next();
+ }
+} |
|
cb0b95a1630e1e526d402816755df073b109dfc7 | spacer_hr.ts | spacer_hr.ts | <?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.0" language="hr_HR">
<context>
<name>SpacerConfiguration</name>
<message>
<location filename="../spacerconfiguration.ui" line="12"/>
<source>Spacer Settings</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../spacerconfiguration.ui" line="18"/>
<source>Space width:</source>
<translation type="unfinished">Duljina razmaka:</translation>
</message>
<message>
<location filename="../spacerconfiguration.ui" line="38"/>
<source>Space type:</source>
<translation type="unfinished">Vrsta razmaka:</translation>
</message>
<message>
<location filename="../spacerconfiguration.cpp" line="34"/>
<source>lined</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../spacerconfiguration.cpp" line="35"/>
<source>dotted</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../spacerconfiguration.cpp" line="36"/>
<source>invisible</source>
<translation type="unfinished">nevidljiv</translation>
</message>
</context>
</TS>
| Create HR translations for panel and plugins | Create HR translations for panel and plugins
| TypeScript | lgpl-2.1 | lxde/lxqt-l10n | ---
+++
@@ -0,0 +1,37 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!DOCTYPE TS>
+<TS version="2.0" language="hr_HR">
+<context>
+ <name>SpacerConfiguration</name>
+ <message>
+ <location filename="../spacerconfiguration.ui" line="12"/>
+ <source>Spacer Settings</source>
+ <translation type="unfinished"></translation>
+ </message>
+ <message>
+ <location filename="../spacerconfiguration.ui" line="18"/>
+ <source>Space width:</source>
+ <translation type="unfinished">Duljina razmaka:</translation>
+ </message>
+ <message>
+ <location filename="../spacerconfiguration.ui" line="38"/>
+ <source>Space type:</source>
+ <translation type="unfinished">Vrsta razmaka:</translation>
+ </message>
+ <message>
+ <location filename="../spacerconfiguration.cpp" line="34"/>
+ <source>lined</source>
+ <translation type="unfinished"></translation>
+ </message>
+ <message>
+ <location filename="../spacerconfiguration.cpp" line="35"/>
+ <source>dotted</source>
+ <translation type="unfinished"></translation>
+ </message>
+ <message>
+ <location filename="../spacerconfiguration.cpp" line="36"/>
+ <source>invisible</source>
+ <translation type="unfinished">nevidljiv</translation>
+ </message>
+</context>
+</TS> |
|
30e277a4fa4cba910ec18a83dddfc1d887619940 | src/Test/Ast/LineBlock.ts | src/Test/Ast/LineBlock.ts | /// <reference path="../../../typings/mocha/mocha.d.ts" />
/// <reference path="../../../typings/chai/chai.d.ts" />
import { expect } from 'chai'
import * as Up from '../../index'
import { SyntaxNode } from '../../SyntaxNodes/SyntaxNode'
import { LinkNode } from '../../SyntaxNodes/LinkNode'
import { DocumentNode } from '../../SyntaxNodes/DocumentNode'
import { PlainTextNode } from '../../SyntaxNodes/PlainTextNode'
import { EmphasisNode } from '../../SyntaxNodes/EmphasisNode'
import { StressNode } from '../../SyntaxNodes/StressNode'
import { InlineCodeNode } from '../../SyntaxNodes/InlineCodeNode'
import { RevisionInsertionNode } from '../../SyntaxNodes/RevisionInsertionNode'
import { RevisionDeletionNode } from '../../SyntaxNodes/RevisionDeletionNode'
import { SpoilerNode } from '../../SyntaxNodes/SpoilerNode'
import { InlineAsideNode } from '../../SyntaxNodes/InlineAsideNode'
import { ParagraphNode } from '../../SyntaxNodes/ParagraphNode'
import { SectionSeparatorNode } from '../../SyntaxNodes/SectionSeparatorNode'
import { HeadingNode } from '../../SyntaxNodes/HeadingNode'
import { LineBlockNode } from '../../SyntaxNodes/LineBlockNode'
import { LineNode } from '../../SyntaxNodes/LineNode'
function insideDocument(syntaxNodes: SyntaxNode[]): DocumentNode {
return new DocumentNode(syntaxNodes);
}
describe('Consecutive non-blank lines', function() {
it('produce a line block node containing line nodes', function() {
const text =
`
Roses are red
Violets are blue`
expect(Up.ast(text)).to.be.eql(
insideDocument([
new LineBlockNode([
new LineNode([
new PlainTextNode('Roses are red')
]),
new LineNode([
new PlainTextNode('Violets are blue')
]),
]),
]))
})
it('can contain inline conventions', function() {
const text =
`
Roses are red
Violets are **blue**`
expect(Up.ast(text)).to.be.eql(
insideDocument([
new LineBlockNode([
new LineNode([
new PlainTextNode('Roses are red')
]),
new LineNode([
new PlainTextNode('Violets are '),
new StressNode([
new PlainTextNode('blue')
])
]),
]),
]))
})
})
| Add failing line block tests | Add failing line block tests
| TypeScript | mit | start/up,start/up | ---
+++
@@ -0,0 +1,68 @@
+/// <reference path="../../../typings/mocha/mocha.d.ts" />
+/// <reference path="../../../typings/chai/chai.d.ts" />
+
+import { expect } from 'chai'
+import * as Up from '../../index'
+import { SyntaxNode } from '../../SyntaxNodes/SyntaxNode'
+import { LinkNode } from '../../SyntaxNodes/LinkNode'
+import { DocumentNode } from '../../SyntaxNodes/DocumentNode'
+import { PlainTextNode } from '../../SyntaxNodes/PlainTextNode'
+import { EmphasisNode } from '../../SyntaxNodes/EmphasisNode'
+import { StressNode } from '../../SyntaxNodes/StressNode'
+import { InlineCodeNode } from '../../SyntaxNodes/InlineCodeNode'
+import { RevisionInsertionNode } from '../../SyntaxNodes/RevisionInsertionNode'
+import { RevisionDeletionNode } from '../../SyntaxNodes/RevisionDeletionNode'
+import { SpoilerNode } from '../../SyntaxNodes/SpoilerNode'
+import { InlineAsideNode } from '../../SyntaxNodes/InlineAsideNode'
+import { ParagraphNode } from '../../SyntaxNodes/ParagraphNode'
+import { SectionSeparatorNode } from '../../SyntaxNodes/SectionSeparatorNode'
+import { HeadingNode } from '../../SyntaxNodes/HeadingNode'
+import { LineBlockNode } from '../../SyntaxNodes/LineBlockNode'
+import { LineNode } from '../../SyntaxNodes/LineNode'
+
+
+function insideDocument(syntaxNodes: SyntaxNode[]): DocumentNode {
+ return new DocumentNode(syntaxNodes);
+}
+
+
+describe('Consecutive non-blank lines', function() {
+ it('produce a line block node containing line nodes', function() {
+ const text =
+ `
+Roses are red
+Violets are blue`
+ expect(Up.ast(text)).to.be.eql(
+ insideDocument([
+ new LineBlockNode([
+ new LineNode([
+ new PlainTextNode('Roses are red')
+ ]),
+ new LineNode([
+ new PlainTextNode('Violets are blue')
+ ]),
+ ]),
+ ]))
+ })
+
+ it('can contain inline conventions', function() {
+ const text =
+ `
+Roses are red
+Violets are **blue**`
+ expect(Up.ast(text)).to.be.eql(
+ insideDocument([
+ new LineBlockNode([
+ new LineNode([
+ new PlainTextNode('Roses are red')
+ ]),
+ new LineNode([
+ new PlainTextNode('Violets are '),
+ new StressNode([
+ new PlainTextNode('blue')
+ ])
+ ]),
+ ]),
+ ]))
+ })
+}) |
|
45e79f6b1ae15069d2ce4bdce6ac0f4881854bc7 | src/client/app/utils/pagination.helper.ts | src/client/app/utils/pagination.helper.ts | export class PageData{
Display: string;
IsActive: boolean;
constructor(display: string,
isActive: boolean){
this.Display = display;
this.IsActive = isActive;
}
}
export class Pagination{
public TotalItems: number;
public ItemsPerPage: number;
public TotalPages: number;
public PagesDisplay: PageData[];
constructor(totalItems: number,
itemsPerPage: number){
this.TotalItems = totalItems;
this.ItemsPerPage = itemsPerPage;
this.TotalPages = Math.ceil(this.TotalItems / this.ItemsPerPage);
}
GetPageActive(): number{
for (let idx:number = 0; idx < this.PagesDisplay.length; idx++){
if (this.PagesDisplay[idx].IsActive){
return parseInt(this.PagesDisplay[idx].Display);
}
}
return 1;
}
SetPageActive(pageActive: number): void{
let result: PageData[] = [];
if (pageActive > this.TotalPages){
pageActive = this.TotalPages;
}
if (pageActive < 1){
pageActive = 1;
}
if (this.TotalPages <= 6){
for (let id: number = 1; id <= this.TotalPages; id++){
result.push(new PageData(id.toString(), false));
}
result[pageActive - 1].IsActive = true;
}else{
let pagesTemp: number[] = [];
pagesTemp.push(1);
pagesTemp.push(2);
pagesTemp.push(this.TotalPages - 1);
pagesTemp.push(this.TotalPages);
// Add mid page
let midPage = Math.floor((1 + this.TotalPages) / 2);
let preMidPage = midPage - 1;
let nextMidPage = midPage + 1;
pagesTemp.push(preMidPage);
pagesTemp.push(midPage);
pagesTemp.push(nextMidPage);
// Add active page
pagesTemp.push(pageActive);
// Add previous active page
if (pageActive - 1 > 0){
pagesTemp.push(pageActive - 1);
}
// Add next active page
if (pageActive + 1 < this.TotalPages){
pagesTemp.push(pageActive + 1);
}
// Sort pageActive
pagesTemp = pagesTemp.sort((first: number, second: number) => first - second);
for (let id:number = 0; id < pagesTemp.length; id++){
let isActive = false;
if (id + 1 == pageActive){
isActive = true;
}
if (id > 0){
let pageDist = pagesTemp[id] - pagesTemp[id - 1];
if (pageDist == 0){
continue;
}else if (pageDist == 1){
result.push(new PageData(pagesTemp[id].toString(), isActive));
}else if (pageDist > 1){
result.push(new PageData("...", false));
result.push(new PageData(pagesTemp[id].toString(), isActive));
}
}else{
result.push(new PageData(pagesTemp[id].toString(), isActive));
}
}
}
this.PagesDisplay = result;
}
}
| Create utility class for pagination | Create utility class for pagination
| TypeScript | mit | CaoDuyThanh/WebAppClient,CaoDuyThanh/WebAppClient,CaoDuyThanh/WebAppClient | ---
+++
@@ -0,0 +1,106 @@
+export class PageData{
+ Display: string;
+ IsActive: boolean;
+
+ constructor(display: string,
+ isActive: boolean){
+ this.Display = display;
+ this.IsActive = isActive;
+ }
+}
+
+export class Pagination{
+ public TotalItems: number;
+ public ItemsPerPage: number;
+ public TotalPages: number;
+ public PagesDisplay: PageData[];
+
+ constructor(totalItems: number,
+ itemsPerPage: number){
+ this.TotalItems = totalItems;
+ this.ItemsPerPage = itemsPerPage;
+ this.TotalPages = Math.ceil(this.TotalItems / this.ItemsPerPage);
+ }
+
+ GetPageActive(): number{
+ for (let idx:number = 0; idx < this.PagesDisplay.length; idx++){
+ if (this.PagesDisplay[idx].IsActive){
+ return parseInt(this.PagesDisplay[idx].Display);
+ }
+ }
+
+ return 1;
+ }
+
+ SetPageActive(pageActive: number): void{
+ let result: PageData[] = [];
+ if (pageActive > this.TotalPages){
+ pageActive = this.TotalPages;
+ }
+ if (pageActive < 1){
+ pageActive = 1;
+ }
+
+ if (this.TotalPages <= 6){
+ for (let id: number = 1; id <= this.TotalPages; id++){
+ result.push(new PageData(id.toString(), false));
+ }
+ result[pageActive - 1].IsActive = true;
+ }else{
+ let pagesTemp: number[] = [];
+ pagesTemp.push(1);
+ pagesTemp.push(2);
+ pagesTemp.push(this.TotalPages - 1);
+ pagesTemp.push(this.TotalPages);
+
+ // Add mid page
+ let midPage = Math.floor((1 + this.TotalPages) / 2);
+ let preMidPage = midPage - 1;
+ let nextMidPage = midPage + 1;
+ pagesTemp.push(preMidPage);
+ pagesTemp.push(midPage);
+ pagesTemp.push(nextMidPage);
+
+ // Add active page
+ pagesTemp.push(pageActive);
+
+ // Add previous active page
+ if (pageActive - 1 > 0){
+ pagesTemp.push(pageActive - 1);
+ }
+
+ // Add next active page
+ if (pageActive + 1 < this.TotalPages){
+ pagesTemp.push(pageActive + 1);
+ }
+
+ // Sort pageActive
+ pagesTemp = pagesTemp.sort((first: number, second: number) => first - second);
+
+ for (let id:number = 0; id < pagesTemp.length; id++){
+ let isActive = false;
+
+ if (id + 1 == pageActive){
+ isActive = true;
+ }
+
+ if (id > 0){
+ let pageDist = pagesTemp[id] - pagesTemp[id - 1];
+ if (pageDist == 0){
+ continue;
+ }else if (pageDist == 1){
+ result.push(new PageData(pagesTemp[id].toString(), isActive));
+ }else if (pageDist > 1){
+ result.push(new PageData("...", false));
+ result.push(new PageData(pagesTemp[id].toString(), isActive));
+ }
+ }else{
+ result.push(new PageData(pagesTemp[id].toString(), isActive));
+ }
+ }
+
+ }
+ this.PagesDisplay = result;
+
+ }
+} |
|
a4bd75e04f328960130876f7f69411fb38a8f8fb | test/test_configschema.ts | test/test_configschema.ts | import * as yaml from "js-yaml";
import * as Chai from "chai";
import { ConfigValidator } from "matrix-appservice-bridge";
const expect = Chai.expect;
describe("ConfigSchema", () => {
const validator = new ConfigValidator("./config/config.schema.yaml");
it("should successfully validate a minimal config", () => {
const yamlConfig = yaml.safeLoad(`
bridge:
domain: localhost
homeserverUrl: "http://localhost:8008"
auth:
clientID: foo
botToken: foobar`);
validator.validate(yamlConfig);
});
it("should successfully validate the sample config", () => {
validator.validate("./config/config.sample.yaml");
});
});
| Test that the minimal and sample configs pass validation | Test that the minimal and sample configs pass validation
| TypeScript | apache-2.0 | Half-Shot/matrix-appservice-discord | ---
+++
@@ -0,0 +1,22 @@
+import * as yaml from "js-yaml";
+import * as Chai from "chai";
+import { ConfigValidator } from "matrix-appservice-bridge";
+
+const expect = Chai.expect;
+
+describe("ConfigSchema", () => {
+ const validator = new ConfigValidator("./config/config.schema.yaml");
+ it("should successfully validate a minimal config", () => {
+ const yamlConfig = yaml.safeLoad(`
+ bridge:
+ domain: localhost
+ homeserverUrl: "http://localhost:8008"
+ auth:
+ clientID: foo
+ botToken: foobar`);
+ validator.validate(yamlConfig);
+ });
+ it("should successfully validate the sample config", () => {
+ validator.validate("./config/config.sample.yaml");
+ });
+}); |
|
e4af465163ea76c819eaae3e1bd52b0bbd258b29 | packages/mathjax/__tests__/provider.spec.tsx | packages/mathjax/__tests__/provider.spec.tsx | import { shallow } from "enzyme";
import React from "react";
import MathJaxContext from "../src/context";
import MathJaxProvider from "../src/provider";
describe("MathJaxProvider", () => {
it("renders without crashing", () => {
const component = shallow(<MathJaxProvider>$x^2 + y = 3$</MathJaxProvider>);
expect(component.find(MathJaxContext.Provider)).toHaveLength(1);
});
});
| Add render without crash test for MathJax provider | Add render without crash test for MathJax provider
| TypeScript | bsd-3-clause | nteract/nteract,nteract/nteract,nteract/nteract,nteract/nteract,nteract/nteract,nteract/composition,nteract/composition,nteract/composition | ---
+++
@@ -0,0 +1,12 @@
+import { shallow } from "enzyme";
+import React from "react";
+
+import MathJaxContext from "../src/context";
+import MathJaxProvider from "../src/provider";
+
+describe("MathJaxProvider", () => {
+ it("renders without crashing", () => {
+ const component = shallow(<MathJaxProvider>$x^2 + y = 3$</MathJaxProvider>);
+ expect(component.find(MathJaxContext.Provider)).toHaveLength(1);
+ });
+}); |
|
4a860358baf48beeb4fce36adc5d2a44c4813a4e | console/src/app/core/services/mongoose-api-models/MongooseApi.model.ts | console/src/app/core/services/mongoose-api-models/MongooseApi.model.ts | // A class that describes endpoints for Mongoose API.
// See Mongoose API (as for 27.03.2019): ...
// ... https://github.com/emc-mongoose/mongoose-base/tree/master/doc/interfaces/api/remote
export namespace MongooseApi {
// NOTE: API for configuration.
export class Config {
public static readonly CONFIG = "/config";
}
// NOTE: API for configuring Mongoose Run.
export class RunApi {
public static readonly RUN = "/run";
}
// NOTE: API to process Mongoose's Run logs
export class LogsApi {
public static readonly LOGS = "/logs";
}
} | Move Mongoose config API endpoint into MongooseApi namespace. | Move Mongoose config API endpoint into MongooseApi namespace.
| TypeScript | mit | emc-mongoose/console,emc-mongoose/console,emc-mongoose/console | ---
+++
@@ -0,0 +1,21 @@
+// A class that describes endpoints for Mongoose API.
+// See Mongoose API (as for 27.03.2019): ...
+// ... https://github.com/emc-mongoose/mongoose-base/tree/master/doc/interfaces/api/remote
+
+export namespace MongooseApi {
+
+ // NOTE: API for configuration.
+ export class Config {
+ public static readonly CONFIG = "/config";
+ }
+
+ // NOTE: API for configuring Mongoose Run.
+ export class RunApi {
+ public static readonly RUN = "/run";
+ }
+
+ // NOTE: API to process Mongoose's Run logs
+ export class LogsApi {
+ public static readonly LOGS = "/logs";
+ }
+} |
|
40d384c3803c1fd2835a44cc8d54ed1d46968759 | frontend/terminal/__tests__/support_test.ts | frontend/terminal/__tests__/support_test.ts | const mockTerminal: Pick<Terminal, "open"> = {
open: jest.fn(),
};
jest.mock("xterm", () => {
return {
Terminal: function () {
return mockTerminal;
}
};
});
import { Terminal } from "xterm";
import { attachTerminal, getCredentials } from "../support";
describe("getCredentials", () => {
it("returns credentials whe possible", () => {
const session = {
token: {
encoded: "password456",
unencoded: {
mqtt_ws: "ws://localhost:4567/x",
bot: "device_37"
}
}
};
localStorage.setItem("session", JSON.stringify(session));
const result = getCredentials();
expect(result.password).toEqual(session.token.encoded);
expect(result.username).toEqual(session.token.unencoded.bot);
expect(result.url).toEqual(session.token.unencoded.mqtt_ws);
});
it("redirects to home if no credentials are loaded", () => {
localStorage.clear();
getCredentials();
expect(window.location.assign).toHaveBeenCalled();
});
});
describe("attachTerminal", () => {
it("attaches to the DOM if possible", () => {
const root = document.createElement("DIV");
root.id = "root";
document.body.appendChild(root);
const terminal = attachTerminal();
expect(terminal).toBe(mockTerminal);
expect(terminal.open).toHaveBeenCalledWith(root);
root.remove();
});
it("ignores the DOM if missing", () => {
expect(document.getElementById("root")).toBeFalsy();
const terminal = attachTerminal();
expect(terminal).toBe(mockTerminal);
});
});
| Test coverage for TerminalSession support methods | Test coverage for TerminalSession support methods
| TypeScript | mit | FarmBot/Farmbot-Web-API,FarmBot/farmbot-web-app,FarmBot/Farmbot-Web-API,FarmBot/farmbot-web-app,FarmBot/Farmbot-Web-API,FarmBot/farmbot-web-app,FarmBot/Farmbot-Web-API,FarmBot/Farmbot-Web-API | ---
+++
@@ -0,0 +1,57 @@
+const mockTerminal: Pick<Terminal, "open"> = {
+ open: jest.fn(),
+};
+
+jest.mock("xterm", () => {
+ return {
+ Terminal: function () {
+ return mockTerminal;
+ }
+ };
+});
+
+import { Terminal } from "xterm";
+import { attachTerminal, getCredentials } from "../support";
+
+describe("getCredentials", () => {
+ it("returns credentials whe possible", () => {
+ const session = {
+ token: {
+ encoded: "password456",
+ unencoded: {
+ mqtt_ws: "ws://localhost:4567/x",
+ bot: "device_37"
+ }
+ }
+ };
+ localStorage.setItem("session", JSON.stringify(session));
+ const result = getCredentials();
+ expect(result.password).toEqual(session.token.encoded);
+ expect(result.username).toEqual(session.token.unencoded.bot);
+ expect(result.url).toEqual(session.token.unencoded.mqtt_ws);
+ });
+
+ it("redirects to home if no credentials are loaded", () => {
+ localStorage.clear();
+ getCredentials();
+ expect(window.location.assign).toHaveBeenCalled();
+ });
+});
+
+describe("attachTerminal", () => {
+ it("attaches to the DOM if possible", () => {
+ const root = document.createElement("DIV");
+ root.id = "root";
+ document.body.appendChild(root);
+ const terminal = attachTerminal();
+ expect(terminal).toBe(mockTerminal);
+ expect(terminal.open).toHaveBeenCalledWith(root);
+ root.remove();
+ });
+
+ it("ignores the DOM if missing", () => {
+ expect(document.getElementById("root")).toBeFalsy();
+ const terminal = attachTerminal();
+ expect(terminal).toBe(mockTerminal);
+ });
+}); |
|
b54de6a58cd9ef9b85fddae9467b40486036a63e | test/unit/core/java/java-version-parser.spec.ts | test/unit/core/java/java-version-parser.spec.ts | import {JavaVersionParser} from '../../../../app/core/java/java-version-parser';
/**
* @author Thomas Kleinke
*/
describe('JavaVersionParser', () => {
it('parse Java version', () => {
expect(JavaVersionParser.parse('java version "1.8.0_152"')).toBe(8);
expect(JavaVersionParser.parse('java version "9"')).toBe(9);
expect(JavaVersionParser.parse('java version "10.0.1" 2018-04-17')).toBe(10);
expect(JavaVersionParser.parse('invalid string')).toBe(0);
});
}); | Add unit test for JavaVersionParser | Add unit test for JavaVersionParser
| TypeScript | apache-2.0 | codarchlab/idai-field-client,codarchlab/idai-field-client,codarchlab/idai-field-client,codarchlab/idai-field-client | ---
+++
@@ -0,0 +1,16 @@
+import {JavaVersionParser} from '../../../../app/core/java/java-version-parser';
+
+
+/**
+ * @author Thomas Kleinke
+ */
+describe('JavaVersionParser', () => {
+
+ it('parse Java version', () => {
+
+ expect(JavaVersionParser.parse('java version "1.8.0_152"')).toBe(8);
+ expect(JavaVersionParser.parse('java version "9"')).toBe(9);
+ expect(JavaVersionParser.parse('java version "10.0.1" 2018-04-17')).toBe(10);
+ expect(JavaVersionParser.parse('invalid string')).toBe(0);
+ });
+}); |
|
683657a28132eec10db48a21ee82cba730392276 | app/javascript/retrospring/utilities/notifications.ts | app/javascript/retrospring/utilities/notifications.ts | export function showErrorNotification(text: string): void {
showNotification(text, false);
}
export function showNotification(text: string, status = true): void {
window['showNotification'](text, status);
} | Add TypeScript wrapper around legacy notification functionality | Add TypeScript wrapper around legacy notification functionality
| TypeScript | agpl-3.0 | Retrospring/retrospring,Retrospring/retrospring,Retrospring/retrospring,Retrospring/retrospring,Retrospring/retrospring | ---
+++
@@ -0,0 +1,7 @@
+export function showErrorNotification(text: string): void {
+ showNotification(text, false);
+}
+
+export function showNotification(text: string, status = true): void {
+ window['showNotification'](text, status);
+} |
|
2b430f1c6fa0070298be96683508470b988876da | app/src/lib/progress/push-progress-parser.ts | app/src/lib/progress/push-progress-parser.ts | import { StepProgressParser } from './step-progress'
/**
* Highly approximate (some would say outright inaccurate) division
* of the individual progress reporting steps in a push operation
*/
const steps = [
{ title: 'Compressing objects', weight: 0.2 },
{ title: 'Writing objects', weight: 0.7 },
{ title: 'remote: Resolving deltas', weight: 0.1 },
]
/**
* A utility class for interpreting the output from `git push --progress`
* and turning that into a percentage value estimating the overall progress
* of the clone.
*/
export class PushProgressParser {
private readonly parser: StepProgressParser
public constructor() {
this.parser = new StepProgressParser(steps)
}
/**
* Parses a single line of output from 'git push --progress'.
* Returns a fractional value between 0 and 1 indicating the
* overall progress so far or null if progress is still
* indeterminate.
*/
public parse(line: string): number | null {
const progress = this.parser.parse(line)
return progress ? progress.percent : null
}
}
| Add a push progress parser | Add a push progress parser
| TypeScript | mit | shiftkey/desktop,desktop/desktop,j-f1/forked-desktop,BugTesterTest/desktops,say25/desktop,hjobrien/desktop,artivilla/desktop,gengjiawen/desktop,BugTesterTest/desktops,shiftkey/desktop,say25/desktop,shiftkey/desktop,kactus-io/kactus,j-f1/forked-desktop,hjobrien/desktop,BugTesterTest/desktops,gengjiawen/desktop,desktop/desktop,hjobrien/desktop,gengjiawen/desktop,shiftkey/desktop,desktop/desktop,kactus-io/kactus,artivilla/desktop,desktop/desktop,say25/desktop,j-f1/forked-desktop,j-f1/forked-desktop,kactus-io/kactus,hjobrien/desktop,BugTesterTest/desktops,say25/desktop,artivilla/desktop,gengjiawen/desktop,artivilla/desktop,kactus-io/kactus | ---
+++
@@ -0,0 +1,36 @@
+import { StepProgressParser } from './step-progress'
+
+/**
+ * Highly approximate (some would say outright inaccurate) division
+ * of the individual progress reporting steps in a push operation
+ */
+const steps = [
+ { title: 'Compressing objects', weight: 0.2 },
+ { title: 'Writing objects', weight: 0.7 },
+ { title: 'remote: Resolving deltas', weight: 0.1 },
+]
+
+/**
+ * A utility class for interpreting the output from `git push --progress`
+ * and turning that into a percentage value estimating the overall progress
+ * of the clone.
+ */
+export class PushProgressParser {
+
+ private readonly parser: StepProgressParser
+
+ public constructor() {
+ this.parser = new StepProgressParser(steps)
+ }
+
+ /**
+ * Parses a single line of output from 'git push --progress'.
+ * Returns a fractional value between 0 and 1 indicating the
+ * overall progress so far or null if progress is still
+ * indeterminate.
+ */
+ public parse(line: string): number | null {
+ const progress = this.parser.parse(line)
+ return progress ? progress.percent : null
+ }
+} |
|
82668071e4b4c4e981755f81a586770f87ebd577 | client/src/app/users/add-user.component.spec.ts | client/src/app/users/add-user.component.spec.ts | import {async, ComponentFixture, TestBed} from '@angular/core/testing';
import {MatDialogRef, MAT_DIALOG_DATA, MATERIAL_COMPATIBILITY_MODE} from '@angular/material';
import {AddUserComponent} from "./add-user.component";
import {CustomModule} from "../custom.module";
describe('Add user component', () => {
let addUserComponent: AddUserComponent;
let calledClose: boolean;
let mockMatDialogRef = {
close() { calledClose = true }
};
let data = null;
let fixture: ComponentFixture<AddUserComponent>;
beforeEach(async( () => {
TestBed.configureTestingModule({
imports: [CustomModule],
declarations: [AddUserComponent],
providers: [
{ provide: MatDialogRef, useValue: mockMatDialogRef },
{ provide: MAT_DIALOG_DATA, useValue: data },
{ provide: MATERIAL_COMPATIBILITY_MODE, useValue: true }]
}).compileComponents().catch(error => {
expect(error).toBeNull();
});
}));
beforeEach(() => {
calledClose = false;
fixture = TestBed.createComponent(AddUserComponent);
addUserComponent = fixture.componentInstance;
});
it('closes properly', () => {
addUserComponent.onNoClick();
expect(calledClose).toBe(true);
})
});
| Write karma tests for `AddUserComponent` | Write karma tests for `AddUserComponent`
This gives us 100% coverage for `AddUserComponent`. You might argue it
was an awful lot of work for a fairly small improvement in coverage,
but I learned some useful things about mocking so that was nice.
| TypeScript | mit | UMM-CSci-3601/3601-lab4_mongo,UMM-CSci-3601/3601-lab4_mongo,UMM-CSci-3601/3601-lab4_mongo,UMM-CSci-3601/3601-lab4_mongo | ---
+++
@@ -0,0 +1,42 @@
+import {async, ComponentFixture, TestBed} from '@angular/core/testing';
+
+import {MatDialogRef, MAT_DIALOG_DATA, MATERIAL_COMPATIBILITY_MODE} from '@angular/material';
+
+import {AddUserComponent} from "./add-user.component";
+import {CustomModule} from "../custom.module";
+
+describe('Add user component', () => {
+
+ let addUserComponent: AddUserComponent;
+ let calledClose: boolean;
+ let mockMatDialogRef = {
+ close() { calledClose = true }
+ };
+ let data = null;
+ let fixture: ComponentFixture<AddUserComponent>;
+
+ beforeEach(async( () => {
+ TestBed.configureTestingModule({
+ imports: [CustomModule],
+ declarations: [AddUserComponent],
+ providers: [
+ { provide: MatDialogRef, useValue: mockMatDialogRef },
+ { provide: MAT_DIALOG_DATA, useValue: data },
+ { provide: MATERIAL_COMPATIBILITY_MODE, useValue: true }]
+ }).compileComponents().catch(error => {
+ expect(error).toBeNull();
+ });
+ }));
+
+ beforeEach(() => {
+ calledClose = false;
+ fixture = TestBed.createComponent(AddUserComponent);
+ addUserComponent = fixture.componentInstance;
+ });
+
+ it('closes properly', () => {
+ addUserComponent.onNoClick();
+ expect(calledClose).toBe(true);
+ })
+
+}); |
|
d92d475c8986c89933c3c8b3da6c9a3624798e39 | packages/@glimmer/syntax/lib/traversal/errors.ts | packages/@glimmer/syntax/lib/traversal/errors.ts | import * as AST from '../types/nodes';
import { Option } from '@glimmer/interfaces';
class TraversalError extends Error {
constructor(message: string, public node: AST.Node, public parent: Option<AST.Node>, public key: string) {
super(message);
}
}
TraversalError.prototype = Object.create(Error.prototype);
TraversalError.prototype.constructor = TraversalError;
export default TraversalError;
export function cannotRemoveNode(node: AST.Node, parent:AST.Node, key: string) {
return new TraversalError(
"Cannot remove a node unless it is part of an array",
node, parent, key
);
}
export function cannotReplaceNode(node: AST.Node, parent: AST.Node, key: string) {
return new TraversalError(
"Cannot replace a node with multiple nodes unless it is part of an array",
node, parent, key
);
}
export function cannotReplaceOrRemoveInKeyHandlerYet(node: AST.Node, key: string) {
return new TraversalError(
"Replacing and removing in key handlers is not yet supported.",
node, null, key
);
}
| import * as AST from '../types/nodes';
import { Option } from '@glimmer/interfaces';
export interface TraversalError extends Error {
constructor: TraversalErrorConstructor;
key: string;
node: AST.Node;
parent: Option<AST.Node>;
}
export interface TraversalErrorConstructor {
new (message: string, node: AST.Node, parent: Option<AST.Node>, key: string): TraversalError;
readonly prototype: TraversalError;
}
const TraversalError: TraversalErrorConstructor = (function () {
TraversalError.prototype = Object.create(Error.prototype);
TraversalError.prototype.constructor = TraversalError;
function TraversalError(this: TraversalError, message: string, node: AST.Node, parent: Option<AST.Node>, key: string) {
let error = Error.call(this, message);
this.key = key;
this.message = message;
this.node = node;
this.parent = parent;
this.stack = error.stack;
}
return TraversalError as any;
}());
export default TraversalError;
export function cannotRemoveNode(node: AST.Node, parent:AST.Node, key: string) {
return new TraversalError(
"Cannot remove a node unless it is part of an array",
node, parent, key
);
}
export function cannotReplaceNode(node: AST.Node, parent: AST.Node, key: string) {
return new TraversalError(
"Cannot replace a node with multiple nodes unless it is part of an array",
node, parent, key
);
}
export function cannotReplaceOrRemoveInKeyHandlerYet(node: AST.Node, key: string) {
return new TraversalError(
"Replacing and removing in key handlers is not yet supported.",
node, null, key
);
}
| Convert TraversalError class to ES5 syntax | Convert TraversalError class to ES5 syntax
The `prototype` property on classes is readonly.
| TypeScript | mit | lbdm44/glimmer-vm,tildeio/glimmer,tildeio/glimmer,lbdm44/glimmer-vm,tildeio/glimmer,glimmerjs/glimmer-vm,glimmerjs/glimmer-vm,lbdm44/glimmer-vm,glimmerjs/glimmer-vm | ---
+++
@@ -1,14 +1,34 @@
import * as AST from '../types/nodes';
import { Option } from '@glimmer/interfaces';
-class TraversalError extends Error {
- constructor(message: string, public node: AST.Node, public parent: Option<AST.Node>, public key: string) {
- super(message);
- }
+export interface TraversalError extends Error {
+ constructor: TraversalErrorConstructor;
+ key: string;
+ node: AST.Node;
+ parent: Option<AST.Node>;
}
-TraversalError.prototype = Object.create(Error.prototype);
-TraversalError.prototype.constructor = TraversalError;
+export interface TraversalErrorConstructor {
+ new (message: string, node: AST.Node, parent: Option<AST.Node>, key: string): TraversalError;
+ readonly prototype: TraversalError;
+}
+
+const TraversalError: TraversalErrorConstructor = (function () {
+ TraversalError.prototype = Object.create(Error.prototype);
+ TraversalError.prototype.constructor = TraversalError;
+
+ function TraversalError(this: TraversalError, message: string, node: AST.Node, parent: Option<AST.Node>, key: string) {
+ let error = Error.call(this, message);
+
+ this.key = key;
+ this.message = message;
+ this.node = node;
+ this.parent = parent;
+ this.stack = error.stack;
+ }
+
+ return TraversalError as any;
+}());
export default TraversalError;
|
5b02616d037d047af8dc5b3d2630899c94474b8a | webpack/account/__tests__/state_to_props_test.ts | webpack/account/__tests__/state_to_props_test.ts | import { mapStateToProps } from "../state_to_props";
import { fakeState } from "../../__test_support__/fake_state";
describe("mapStateToProps()", () => {
it("populates user", () => {
const result = mapStateToProps(fakeState());
expect(result.user).toBeTruthy();
expect(result.user).toBeInstanceOf(Object);
});
});
| import { mapStateToProps } from "../state_to_props";
import { fakeState } from "../../__test_support__/fake_state";
describe("mapStateToProps()", () => {
it("populates data", () => {
const result = mapStateToProps(fakeState());
expect(result.user).toBeTruthy();
expect(result.user).toBeInstanceOf(Object);
expect(() => result.dispatch()).toThrow();
});
});
| Add fake user to fakeState() | Add fake user to fakeState()
| TypeScript | mit | gabrielburnworth/Farmbot-Web-App,RickCarlino/farmbot-web-app,FarmBot/Farmbot-Web-API,FarmBot/farmbot-web-app,gabrielburnworth/Farmbot-Web-App,FarmBot/Farmbot-Web-API,RickCarlino/farmbot-web-app,FarmBot/farmbot-web-app,gabrielburnworth/Farmbot-Web-App,gabrielburnworth/Farmbot-Web-App,FarmBot/Farmbot-Web-API,FarmBot/farmbot-web-app,RickCarlino/farmbot-web-app,RickCarlino/farmbot-web-app,FarmBot/Farmbot-Web-API,RickCarlino/farmbot-web-app,FarmBot/Farmbot-Web-API,gabrielburnworth/Farmbot-Web-App | ---
+++
@@ -2,9 +2,10 @@
import { fakeState } from "../../__test_support__/fake_state";
describe("mapStateToProps()", () => {
- it("populates user", () => {
+ it("populates data", () => {
const result = mapStateToProps(fakeState());
expect(result.user).toBeTruthy();
expect(result.user).toBeInstanceOf(Object);
+ expect(() => result.dispatch()).toThrow();
});
}); |
0b621f37daf3e8c92263443ff6aef25cdf9584a7 | ui/src/ifql/components/KeyboardShortcuts.tsx | ui/src/ifql/components/KeyboardShortcuts.tsx | import {PureComponent, ReactNode} from 'react'
interface Props {
children: ReactNode
onControlEnter: () => void
}
class KeyboardShortcuts extends PureComponent<Props> {
public componentWillMount() {
document.addEventListener('keydown', this.handleKeyboardShortcuts)
}
public componentWillUnmount() {
document.removeEventListener('keydown', this.handleKeyboardShortcuts)
}
public render() {
return this.props.children
}
private handleKeyboardShortcuts = (e: KeyboardEvent) => {
if (e.ctrlKey && e.key === 'Enter') {
this.props.onControlEnter()
e.preventDefault()
}
}
}
export default KeyboardShortcuts
| Add support for keyboard shortcuts | Add support for keyboard shortcuts
| TypeScript | mit | influxdb/influxdb,influxdb/influxdb,mark-rushakoff/influxdb,influxdata/influxdb,influxdb/influxdb,nooproblem/influxdb,influxdb/influxdb,mark-rushakoff/influxdb,influxdata/influxdb,nooproblem/influxdb,nooproblem/influxdb,influxdb/influxdb,influxdb/influxdb,mark-rushakoff/influxdb,mark-rushakoff/influxdb,nooproblem/influxdb,li-ang/influxdb,mark-rushakoff/influxdb,li-ang/influxdb,nooproblem/influxdb,mark-rushakoff/influxdb | ---
+++
@@ -0,0 +1,29 @@
+import {PureComponent, ReactNode} from 'react'
+
+interface Props {
+ children: ReactNode
+ onControlEnter: () => void
+}
+
+class KeyboardShortcuts extends PureComponent<Props> {
+ public componentWillMount() {
+ document.addEventListener('keydown', this.handleKeyboardShortcuts)
+ }
+
+ public componentWillUnmount() {
+ document.removeEventListener('keydown', this.handleKeyboardShortcuts)
+ }
+
+ public render() {
+ return this.props.children
+ }
+
+ private handleKeyboardShortcuts = (e: KeyboardEvent) => {
+ if (e.ctrlKey && e.key === 'Enter') {
+ this.props.onControlEnter()
+ e.preventDefault()
+ }
+ }
+}
+
+export default KeyboardShortcuts |
|
c03e601a5079f67aae15d2780e8c01d2136da18e | types/pg-query-stream/pg-query-stream-tests.ts | types/pg-query-stream/pg-query-stream-tests.ts | import * as QueryStream from 'pg-query-stream';
import * as pg from 'pg';
const options: QueryStream.Options = {
highWaterMark: 1000,
batchSize: 100
};
const query = new QueryStream('SELECT * FROM generate_series(0, $1) num', [1000000], options);
pg.connect('', (err, client, done) => {
const stream = client.query(query);
stream.on('end', () => {
client.end();
});
stream.on('data', (data: any) => {
console.log(data);
});
});
| import * as QueryStream from 'pg-query-stream';
import * as pg from 'pg';
const options: QueryStream.Options = {
highWaterMark: 1000,
batchSize: 100
};
const query = new QueryStream('SELECT * FROM generate_series(0, $1) num', [1000000], options);
const pool = new pg.Pool();
pool.connect((err, client, done) => {
const stream = client.query(query);
stream.on('end', () => {
client.end();
});
stream.on('data', (data: any) => {
console.log(data);
});
});
pool.end();
| Update pg-query-stream test to use [email protected] API. | Update pg-query-stream test to use [email protected] API.
| TypeScript | mit | magny/DefinitelyTyped,benliddicott/DefinitelyTyped,georgemarshall/DefinitelyTyped,abbasmhd/DefinitelyTyped,benishouga/DefinitelyTyped,AgentME/DefinitelyTyped,arusakov/DefinitelyTyped,nycdotnet/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,jimthedev/DefinitelyTyped,alexdresko/DefinitelyTyped,benishouga/DefinitelyTyped,georgemarshall/DefinitelyTyped,rolandzwaga/DefinitelyTyped,aciccarello/DefinitelyTyped,AgentME/DefinitelyTyped,jimthedev/DefinitelyTyped,alexdresko/DefinitelyTyped,arusakov/DefinitelyTyped,magny/DefinitelyTyped,abbasmhd/DefinitelyTyped,rolandzwaga/DefinitelyTyped,zuzusik/DefinitelyTyped,georgemarshall/DefinitelyTyped,arusakov/DefinitelyTyped,AgentME/DefinitelyTyped,aciccarello/DefinitelyTyped,dsebastien/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,zuzusik/DefinitelyTyped,one-pieces/DefinitelyTyped,georgemarshall/DefinitelyTyped,markogresak/DefinitelyTyped,borisyankov/DefinitelyTyped,chrootsu/DefinitelyTyped,nycdotnet/DefinitelyTyped,mcliment/DefinitelyTyped,jimthedev/DefinitelyTyped,borisyankov/DefinitelyTyped,aciccarello/DefinitelyTyped,zuzusik/DefinitelyTyped,laurentiustamate94/DefinitelyTyped,chrootsu/DefinitelyTyped,AgentME/DefinitelyTyped,dsebastien/DefinitelyTyped,benishouga/DefinitelyTyped,AbraaoAlves/DefinitelyTyped | ---
+++
@@ -8,7 +8,8 @@
const query = new QueryStream('SELECT * FROM generate_series(0, $1) num', [1000000], options);
-pg.connect('', (err, client, done) => {
+const pool = new pg.Pool();
+pool.connect((err, client, done) => {
const stream = client.query(query);
stream.on('end', () => {
client.end();
@@ -17,3 +18,4 @@
console.log(data);
});
});
+pool.end(); |
5983672797648211f8ed8116331e494823895722 | src/dashboard-refactor/search-results/types.ts | src/dashboard-refactor/search-results/types.ts | import { AnnotationsSorter } from 'src/sidebar/annotations-sidebar/sorting'
type Note = any
type Page = any
type NoteType = 'search' | 'user' | 'followed'
interface NewNoteFormState {
inputValue: string
// TODO: work out these states (may re-use from sidebar state)
}
interface NoteState {
id: string
// TODO: work out individual note states
}
interface PageState {
id: string
noteType: NoteType
areNotesShown: boolean
sortingFn: AnnotationsSorter
newNoteForm: NewNoteFormState
notes: { [name in NoteType]: NoteState[] }
}
interface ResultsByDay {
date: Date
pages: PageState[]
}
export interface RootState {
results: ResultsByDay[]
areAllNotesShown: boolean
searchType: 'pages' | 'notes'
pagesLookup: { [id: string]: Page }
notesLookup: { [id: string]: Note }
}
| Write first attempt at results state shape | Write first attempt at results state shape
- more complicated than it seems, mainly due to the doubly nested nature of the groupings (days -> pages -> notes)
- main differences from old:
- regardless of search type, the state shape will be the same (in the case of page search, it will always have a single entry at the "days" grouping level)
- keeping actual page and note data in separate lookup keys - I think having these inside the actual doubly nested results structure was one of the most complicated parts of the old state
| TypeScript | mit | WorldBrain/WebMemex,WorldBrain/WebMemex | ---
+++
@@ -0,0 +1,37 @@
+import { AnnotationsSorter } from 'src/sidebar/annotations-sidebar/sorting'
+
+type Note = any
+type Page = any
+type NoteType = 'search' | 'user' | 'followed'
+
+interface NewNoteFormState {
+ inputValue: string
+ // TODO: work out these states (may re-use from sidebar state)
+}
+
+interface NoteState {
+ id: string
+ // TODO: work out individual note states
+}
+
+interface PageState {
+ id: string
+ noteType: NoteType
+ areNotesShown: boolean
+ sortingFn: AnnotationsSorter
+ newNoteForm: NewNoteFormState
+ notes: { [name in NoteType]: NoteState[] }
+}
+
+interface ResultsByDay {
+ date: Date
+ pages: PageState[]
+}
+
+export interface RootState {
+ results: ResultsByDay[]
+ areAllNotesShown: boolean
+ searchType: 'pages' | 'notes'
+ pagesLookup: { [id: string]: Page }
+ notesLookup: { [id: string]: Note }
+} |
|
2d561e9ba741feb93402dce62398c4f91e28d248 | packages/@glimmer/wire-format/lib/opcodes.ts | packages/@glimmer/wire-format/lib/opcodes.ts | export enum Opcodes {
// Statements
Text,
Append,
Comment,
Modifier,
Block,
Component,
OpenElement,
FlushElement,
CloseElement,
StaticAttr,
DynamicAttr,
Yield,
Partial,
DynamicArg,
StaticArg,
TrustingAttr,
Debugger,
ClientSideStatement,
// Expressions
Unknown,
Get,
MaybeLocal,
FixThisBeforeWeMerge,
HasBlock,
HasBlockParams,
Undefined,
Helper,
Concat,
ClientSideExpression
}
| export enum Opcodes {
// Statements
Text,
Append,
Comment,
Modifier,
Block,
Component,
OpenElement,
FlushElement,
CloseElement,
StaticAttr,
DynamicAttr,
Yield,
Partial,
DynamicArg,
StaticArg,
TrustingAttr,
Debugger,
ClientSideStatement,
// Expressions
Unknown,
Get,
MaybeLocal,
HasBlock,
HasBlockParams,
Undefined,
Helper,
Concat,
ClientSideExpression
}
| Remove unused WF opcode (it's now MaybeLocal) | Remove unused WF opcode (it's now MaybeLocal)
| TypeScript | mit | tildeio/glimmer,lbdm44/glimmer-vm,glimmerjs/glimmer-vm,tildeio/glimmer,tildeio/glimmer,glimmerjs/glimmer-vm,lbdm44/glimmer-vm,lbdm44/glimmer-vm,glimmerjs/glimmer-vm | ---
+++
@@ -25,7 +25,6 @@
Unknown,
Get,
MaybeLocal,
- FixThisBeforeWeMerge,
HasBlock,
HasBlockParams,
Undefined, |
894adbc6fdccd58313123a48dcd889be54035b1a | types/client-sessions/client-sessions-tests.ts | types/client-sessions/client-sessions-tests.ts | import * as express from "express";
import * as session from "client-sessions";
const secret = "yolo";
const app = express();
const options = { secret };
let middleware = session(options);
middleware = session({ secret, cookieName: "_s" });
middleware = session({ secret, duration: 600000 });
middleware = session({ secret, activeDuration: 42 });
middleware = session({
secret,
cookie: {
httpOnly: false,
}
});
app.use(middleware);
app.use((req: any, res: any) => {
req.session = { test: true };
});
const encoded = session.util.encode(options, { test: true });
session.util.decode(options, encoded);
| import express = require("express");
import session = require("client-sessions");
const secret = "yolo";
const app = express();
const options = { secret };
let middleware = session(options);
middleware = session({ secret, cookieName: "_s" });
middleware = session({ secret, duration: 600000 });
middleware = session({ secret, activeDuration: 42 });
middleware = session({
secret,
cookie: {
httpOnly: false,
}
});
app.use(middleware);
app.use((req: any, res: any) => {
req.session = { test: true };
});
const encoded = session.util.encode(options, { test: true });
session.util.decode(options, encoded);
| Correct test to use require imports instead of namespace imports. | Correct test to use require imports instead of namespace imports. | TypeScript | mit | ashwinr/DefinitelyTyped,mcliment/DefinitelyTyped,markogresak/DefinitelyTyped,ashwinr/DefinitelyTyped,georgemarshall/DefinitelyTyped,chrootsu/DefinitelyTyped,dsebastien/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,aciccarello/DefinitelyTyped,magny/DefinitelyTyped,borisyankov/DefinitelyTyped,dsebastien/DefinitelyTyped,nycdotnet/DefinitelyTyped,magny/DefinitelyTyped,alexdresko/DefinitelyTyped,benishouga/DefinitelyTyped,AgentME/DefinitelyTyped,nycdotnet/DefinitelyTyped,benliddicott/DefinitelyTyped,laurentiustamate94/DefinitelyTyped,chrootsu/DefinitelyTyped,jimthedev/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,arusakov/DefinitelyTyped,AgentME/DefinitelyTyped,benishouga/DefinitelyTyped,jimthedev/DefinitelyTyped,arusakov/DefinitelyTyped,AgentME/DefinitelyTyped,aciccarello/DefinitelyTyped,borisyankov/DefinitelyTyped,aciccarello/DefinitelyTyped,arusakov/DefinitelyTyped,benishouga/DefinitelyTyped,georgemarshall/DefinitelyTyped,alexdresko/DefinitelyTyped,AgentME/DefinitelyTyped,zuzusik/DefinitelyTyped,abbasmhd/DefinitelyTyped,georgemarshall/DefinitelyTyped,jimthedev/DefinitelyTyped,abbasmhd/DefinitelyTyped,zuzusik/DefinitelyTyped,rolandzwaga/DefinitelyTyped,zuzusik/DefinitelyTyped,rolandzwaga/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,georgemarshall/DefinitelyTyped,one-pieces/DefinitelyTyped | ---
+++
@@ -1,5 +1,5 @@
-import * as express from "express";
-import * as session from "client-sessions";
+import express = require("express");
+import session = require("client-sessions");
const secret = "yolo";
const app = express(); |
aaf21cd2204e65bb79f7fc601ed9e2fab1df9799 | packages/services/test/src/setting/manager.spec.ts | packages/services/test/src/setting/manager.spec.ts | // Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
import expect = require('expect.js');
import {
ServerConnection, SettingManager
} from '../../../lib';
describe('setting', () => {
describe('SettingManager', () => {
describe('#constructor()', () => {
it('should accept no options', () => {
const manager = new SettingManager();
expect(manager).to.be.a(SettingManager);
});
it('should accept options', () => {
const manager = new SettingManager({
serverSettings: ServerConnection.makeSettings()
});
expect(manager).to.be.a(SettingManager);
});
});
describe('#serverSettings', () => {
it('should be the server settings', () => {
const baseUrl = 'foo';
const serverSettings = ServerConnection.makeSettings({ baseUrl });
const manager = new SettingManager({ serverSettings });
expect(manager.serverSettings.baseUrl).to.be(baseUrl);
});
});
});
});
| Add initial setting service tests. | Add initial setting service tests.
| TypeScript | bsd-3-clause | jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab | ---
+++
@@ -0,0 +1,44 @@
+// Copyright (c) Jupyter Development Team.
+// Distributed under the terms of the Modified BSD License.
+
+import expect = require('expect.js');
+
+import {
+ ServerConnection, SettingManager
+} from '../../../lib';
+
+
+describe('setting', () => {
+
+ describe('SettingManager', () => {
+
+ describe('#constructor()', () => {
+
+ it('should accept no options', () => {
+ const manager = new SettingManager();
+ expect(manager).to.be.a(SettingManager);
+ });
+
+ it('should accept options', () => {
+ const manager = new SettingManager({
+ serverSettings: ServerConnection.makeSettings()
+ });
+ expect(manager).to.be.a(SettingManager);
+ });
+
+ });
+
+ describe('#serverSettings', () => {
+
+ it('should be the server settings', () => {
+ const baseUrl = 'foo';
+ const serverSettings = ServerConnection.makeSettings({ baseUrl });
+ const manager = new SettingManager({ serverSettings });
+ expect(manager.serverSettings.baseUrl).to.be(baseUrl);
+ });
+
+ });
+
+ });
+
+}); |
|
001b91f9225ca8cde29d2222ec799337d9189866 | src/selectors/searchTable.ts | src/selectors/searchTable.ts | import { createSelector } from 'reselect';
import {
RootState,
SearchResult,
SearchResults,
HitBlockMap,
RequesterBlockMap,
SortingOption
} from '../types';
import { sortBy } from '../utils/sorting';
const searchResultSelector = (state: RootState) => state.search;
const sortOptionSelector = (state: RootState) => state.sortingOption;
const hitBlocklistSelector = (state: RootState) => state.hitBlocklist;
const requesterBlocklistSelector = (state: RootState) =>
state.requesterBlocklist;
export const hideBlockedHitsSelector = createSelector(
[ searchResultSelector, hitBlocklistSelector ],
(hits: SearchResults, blockedHits: HitBlockMap) =>
hits.filter(
(hit: SearchResult) => !blockedHits.get(hit.groupId)
) as SearchResults
);
export const hideBlockedRequestersSelector = createSelector(
[ searchResultSelector, requesterBlocklistSelector ],
(hits: SearchResults, blockedRequesters: RequesterBlockMap) =>
hits.filter(
(hit: SearchResult) => !blockedRequesters.get(hit.requester.id)
) as SearchResults
);
export const hideUnwantedResultsSelector = createSelector(
[ hideBlockedHitsSelector, hideBlockedRequestersSelector ],
(
resultsFilteredByBlockedIds: SearchResults,
resultsFilteredByBlockedRequesters: SearchResults
) =>
resultsFilteredByBlockedIds.filter(
(result: SearchResult) =>
!!resultsFilteredByBlockedRequesters.get(result.groupId)
) as SearchResults
);
export const filteredAndSortedResultsSelector = createSelector(
[ hideUnwantedResultsSelector, sortOptionSelector ],
(hits: SearchResults, sortingOption: SortingOption) =>
hits.sort(sortBy(sortingOption)) as SearchResults
);
export const filteredResultsGroupIdSelector = createSelector(
[ filteredAndSortedResultsSelector ],
(hits: SearchResults) =>
hits.map((hit: SearchResult) => hit.groupId).toArray()
);
| Add selectors to filter blocked HITs, filter blocked requesters, and sort results. | Add selectors to filter blocked HITs, filter blocked requesters, and sort results.
| TypeScript | mit | Anveio/mturk-engine,Anveio/mturk-engine,Anveio/mturk-engine | ---
+++
@@ -0,0 +1,56 @@
+import { createSelector } from 'reselect';
+import {
+ RootState,
+ SearchResult,
+ SearchResults,
+ HitBlockMap,
+ RequesterBlockMap,
+ SortingOption
+} from '../types';
+import { sortBy } from '../utils/sorting';
+
+const searchResultSelector = (state: RootState) => state.search;
+const sortOptionSelector = (state: RootState) => state.sortingOption;
+const hitBlocklistSelector = (state: RootState) => state.hitBlocklist;
+const requesterBlocklistSelector = (state: RootState) =>
+ state.requesterBlocklist;
+
+export const hideBlockedHitsSelector = createSelector(
+ [ searchResultSelector, hitBlocklistSelector ],
+ (hits: SearchResults, blockedHits: HitBlockMap) =>
+ hits.filter(
+ (hit: SearchResult) => !blockedHits.get(hit.groupId)
+ ) as SearchResults
+);
+
+export const hideBlockedRequestersSelector = createSelector(
+ [ searchResultSelector, requesterBlocklistSelector ],
+ (hits: SearchResults, blockedRequesters: RequesterBlockMap) =>
+ hits.filter(
+ (hit: SearchResult) => !blockedRequesters.get(hit.requester.id)
+ ) as SearchResults
+);
+
+export const hideUnwantedResultsSelector = createSelector(
+ [ hideBlockedHitsSelector, hideBlockedRequestersSelector ],
+ (
+ resultsFilteredByBlockedIds: SearchResults,
+ resultsFilteredByBlockedRequesters: SearchResults
+ ) =>
+ resultsFilteredByBlockedIds.filter(
+ (result: SearchResult) =>
+ !!resultsFilteredByBlockedRequesters.get(result.groupId)
+ ) as SearchResults
+);
+
+export const filteredAndSortedResultsSelector = createSelector(
+ [ hideUnwantedResultsSelector, sortOptionSelector ],
+ (hits: SearchResults, sortingOption: SortingOption) =>
+ hits.sort(sortBy(sortingOption)) as SearchResults
+);
+
+export const filteredResultsGroupIdSelector = createSelector(
+ [ filteredAndSortedResultsSelector ],
+ (hits: SearchResults) =>
+ hits.map((hit: SearchResult) => hit.groupId).toArray()
+); |
|
aa69b34d04076272d83e398c64053ee27e1f9a51 | test/server/httpCodes.ts | test/server/httpCodes.ts | // NOTE Running these tests requires the crossroads-education/eta-web-test module to be installed.
process.env.ETA_testing = "true";
process.env.ETA_auth_provider = "cre-web-test";
process.env.ETA_db_isReadOnly = "true";
/*
import tests from "../../server/api/tests";
before(function(done) {
this.timeout(10000);
tests.init().then(() => {
done();
}).catch(err => console.error(err));
});
describe("HTTP Codes", () => {
it("should handle a 200 request propermoly", done => {
tests.request()
.get("/test/success")
.expect(200, done);
});
it("should handle a 404 request properly", done => {
tests.request()
.get("/test/foobar")
.expect(404, done);
});
it("should handle a 500 request properly", done => {
tests.request()
.get("/test/error")
.expect(500, done);
});
});
*/
| Implement basic integration tests Not ready for CircleCI, so they're commented out | Implement basic integration tests
Not ready for CircleCI, so they're commented out
| TypeScript | mit | crossroads-education/eta,crossroads-education/eta | ---
+++
@@ -0,0 +1,34 @@
+// NOTE Running these tests requires the crossroads-education/eta-web-test module to be installed.
+process.env.ETA_testing = "true";
+process.env.ETA_auth_provider = "cre-web-test";
+process.env.ETA_db_isReadOnly = "true";
+
+/*
+import tests from "../../server/api/tests";
+
+before(function(done) {
+ this.timeout(10000);
+ tests.init().then(() => {
+ done();
+ }).catch(err => console.error(err));
+});
+
+describe("HTTP Codes", () => {
+ it("should handle a 200 request propermoly", done => {
+ tests.request()
+ .get("/test/success")
+ .expect(200, done);
+ });
+ it("should handle a 404 request properly", done => {
+ tests.request()
+ .get("/test/foobar")
+ .expect(404, done);
+ });
+ it("should handle a 500 request properly", done => {
+ tests.request()
+ .get("/test/error")
+ .expect(500, done);
+ });
+});
+
+*/ |
|
fcef3460bf9134dee6552bb95fe0fb8ec8772d63 | src/utils/decorate.ts | src/utils/decorate.ts | import { Config, defaultConfig } from './config'
/**
* Formats raw title string and returns the formatted string.
* @param {string} title raw title to format
* @param {boolean} [shouldUppercase] whether the title should be uppercased (default: true)
* @return {string} formatted title
*/
const formatTitle: (string, boolean?) => string = (
title: string,
shouldUppercase?: boolean
) => {
return shouldUppercase ? title.toUpperCase() : title
}
/**
* Returns decorated text, formatted according to defined padding and dash
* @export
* @param {string} title title to format
* @param {number} width width of ruler
* @return {string} formatted title
*/
export default function decorate(
title: string,
width: number,
options: Config = defaultConfig
): string {
// resolve settings from config
const { padding: titlePadding, dash, shouldUppercase } = options
const { length: titleLength } = title.trim()
const padding: number = Math.max(((width - titleLength - titlePadding) / 2), 0)
const paddingLeft: number = Math.floor(padding)
const paddingRight: number = Math.ceil(padding)
const titlePaddingStr: string = ' '.repeat(titlePadding)
const formattedTitle: string = formatTitle(title, shouldUppercase)
return (
dash.repeat(paddingLeft) +
titlePaddingStr +
formattedTitle +
titlePaddingStr +
dash.repeat(paddingRight)
)
}
| Add function for the actual formatting of the title | Add function for the actual formatting of the title
| TypeScript | mit | guywald1/vscode-prismo | ---
+++
@@ -0,0 +1,46 @@
+import { Config, defaultConfig } from './config'
+
+/**
+ * Formats raw title string and returns the formatted string.
+ * @param {string} title raw title to format
+ * @param {boolean} [shouldUppercase] whether the title should be uppercased (default: true)
+ * @return {string} formatted title
+ */
+const formatTitle: (string, boolean?) => string = (
+ title: string,
+ shouldUppercase?: boolean
+) => {
+ return shouldUppercase ? title.toUpperCase() : title
+}
+
+/**
+ * Returns decorated text, formatted according to defined padding and dash
+ * @export
+ * @param {string} title title to format
+ * @param {number} width width of ruler
+ * @return {string} formatted title
+ */
+export default function decorate(
+ title: string,
+ width: number,
+ options: Config = defaultConfig
+): string {
+ // resolve settings from config
+ const { padding: titlePadding, dash, shouldUppercase } = options
+
+ const { length: titleLength } = title.trim()
+ const padding: number = Math.max(((width - titleLength - titlePadding) / 2), 0)
+ const paddingLeft: number = Math.floor(padding)
+ const paddingRight: number = Math.ceil(padding)
+ const titlePaddingStr: string = ' '.repeat(titlePadding)
+
+ const formattedTitle: string = formatTitle(title, shouldUppercase)
+
+ return (
+ dash.repeat(paddingLeft) +
+ titlePaddingStr +
+ formattedTitle +
+ titlePaddingStr +
+ dash.repeat(paddingRight)
+ )
+} |
|
6e617f7ebb32997ee206710ddb4dd6411fc26387 | tests/gui/specs/webdriverio.spec.ts | tests/gui/specs/webdriverio.spec.ts | import { describe, expect, it, loadFixture } from '../suite';
import fs from 'fs-extra';
import path from 'path';
import jimp from 'jimp';
describe('webdriverio', () => {
async function compareScreenshot(screenshot: Buffer, baseline: string) {
const result = jimp.diff(
await jimp.read(
await fs.readFile(path.join(__dirname, `../screenshots/${process.env.BROWSER}/${baseline}.png`))
),
await jimp.read(screenshot)
);
expect(result.percent).to.equal(0);
}
it('should take a full page screenshot', async browser => {
await loadFixture('simple');
const screenshot = Buffer.from(await browser.takeScreenshot(), 'base64');
await compareScreenshot(screenshot, 'simple');
});
});
| Add learning tests for webdriverio | Add learning tests for webdriverio
| TypeScript | mit | uberVU/mugshot,uberVU/mugshot | ---
+++
@@ -0,0 +1,25 @@
+import { describe, expect, it, loadFixture } from '../suite';
+import fs from 'fs-extra';
+import path from 'path';
+import jimp from 'jimp';
+
+describe('webdriverio', () => {
+ async function compareScreenshot(screenshot: Buffer, baseline: string) {
+ const result = jimp.diff(
+ await jimp.read(
+ await fs.readFile(path.join(__dirname, `../screenshots/${process.env.BROWSER}/${baseline}.png`))
+ ),
+ await jimp.read(screenshot)
+ );
+
+ expect(result.percent).to.equal(0);
+ }
+
+ it('should take a full page screenshot', async browser => {
+ await loadFixture('simple');
+
+ const screenshot = Buffer.from(await browser.takeScreenshot(), 'base64');
+
+ await compareScreenshot(screenshot, 'simple');
+ });
+}); |
|
3a3cd78552f091ebc09ddaa2497fef0d3b3c0316 | frontend/src/app/Services/chatbot.service.spec.ts | frontend/src/app/Services/chatbot.service.spec.ts | /*
* Copyright (c) 2014-2020 Bjoern Kimminich.
* SPDX-License-Identifier: MIT
*/
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'
import { fakeAsync, inject, TestBed, tick } from '@angular/core/testing'
import { ChatbotService } from './chatbot.service'
describe('ChatbotService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [ChatbotService]
})
})
it('should be created', inject([ChatbotService], (service: ChatbotService) => {
expect(service).toBeTruthy()
}))
it('should get status from the REST API', inject([ChatbotService, HttpTestingController],
fakeAsync((service: ChatbotService, httpMock: HttpTestingController) => {
let res: any
service.getChatbotStatus().subscribe((data) => res = data)
const req = httpMock.expectOne('http://localhost:3000/rest/chatbot/status')
req.flush({ status: true, body: 'apiResponse' })
tick()
expect(req.request.method).toBe('GET')
expect(req.request.body).toBeNull()
expect(res.status).toBeTrue()
expect(res.body).toBe('apiResponse')
httpMock.verify()
})
))
it('should get query response from the REST API', inject([ChatbotService, HttpTestingController],
fakeAsync((service: ChatbotService, httpMock: HttpTestingController) => {
let res: any
service.getResponse('apiQuery').subscribe((data) => res = data)
const req = httpMock.expectOne('http://localhost:3000/rest/chatbot/respond')
req.flush({ action: 'response', body: 'apiResponse' })
tick()
expect(req.request.method).toBe('POST')
expect(req.request.body.query).toBe('apiQuery')
expect(res.action).toBe('response')
expect(res.body).toBe('apiResponse')
httpMock.verify()
})
))
})
| Add unit tests for chatbot service | Add unit tests for chatbot service
Signed-off-by: Scar26 <[email protected]>
| TypeScript | mit | bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop,bkimminich/juice-shop | ---
+++
@@ -0,0 +1,55 @@
+/*
+ * Copyright (c) 2014-2020 Bjoern Kimminich.
+ * SPDX-License-Identifier: MIT
+ */
+
+import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'
+import { fakeAsync, inject, TestBed, tick } from '@angular/core/testing'
+
+import { ChatbotService } from './chatbot.service'
+
+describe('ChatbotService', () => {
+ beforeEach(() => {
+
+ TestBed.configureTestingModule({
+ imports: [HttpClientTestingModule],
+ providers: [ChatbotService]
+ })
+ })
+
+ it('should be created', inject([ChatbotService], (service: ChatbotService) => {
+ expect(service).toBeTruthy()
+ }))
+
+ it('should get status from the REST API', inject([ChatbotService, HttpTestingController],
+ fakeAsync((service: ChatbotService, httpMock: HttpTestingController) => {
+ let res: any
+ service.getChatbotStatus().subscribe((data) => res = data)
+ const req = httpMock.expectOne('http://localhost:3000/rest/chatbot/status')
+ req.flush({ status: true, body: 'apiResponse' })
+
+ tick()
+ expect(req.request.method).toBe('GET')
+ expect(req.request.body).toBeNull()
+ expect(res.status).toBeTrue()
+ expect(res.body).toBe('apiResponse')
+ httpMock.verify()
+ })
+ ))
+
+ it('should get query response from the REST API', inject([ChatbotService, HttpTestingController],
+ fakeAsync((service: ChatbotService, httpMock: HttpTestingController) => {
+ let res: any
+ service.getResponse('apiQuery').subscribe((data) => res = data)
+ const req = httpMock.expectOne('http://localhost:3000/rest/chatbot/respond')
+ req.flush({ action: 'response', body: 'apiResponse' })
+
+ tick()
+ expect(req.request.method).toBe('POST')
+ expect(req.request.body.query).toBe('apiQuery')
+ expect(res.action).toBe('response')
+ expect(res.body).toBe('apiResponse')
+ httpMock.verify()
+ })
+ ))
+}) |
|
087745ea3103ad964c825860822da5058b6402a2 | src/app/components/search/search.resource.spec.ts | src/app/components/search/search.resource.spec.ts | import { SearchResource } from './search.resource';
describe('Resource Search', () => {
beforeEach(angular.mock.module('roam'));
it('should be registered', inject((searchResource: SearchResource) => {
expect(searchResource).not.toBeNull();
}));
});
| Add Search Resource Unit Test: | Add Search Resource Unit Test:
Added unit test for the resource.
| TypeScript | mit | marksmall/mapuse,marksmall/mapuse,marksmall/mapuse | ---
+++
@@ -0,0 +1,9 @@
+import { SearchResource } from './search.resource';
+
+describe('Resource Search', () => {
+ beforeEach(angular.mock.module('roam'));
+
+ it('should be registered', inject((searchResource: SearchResource) => {
+ expect(searchResource).not.toBeNull();
+ }));
+}); |
|
2ccaa61888725040d612d0683fa457a0badc09d4 | src/utils/returnHit.ts | src/utils/returnHit.ts | import axios from 'axios';
import { API_URL } from '../constants';
import { stringToDomElement } from './parsing';
export const returnHit = async (hitId: string) => {
try {
const response = await axios.get(
`${API_URL}/mturk/return?hitId=${hitId}&inPipeline=false`
);
const rawHtml: string = response.data;
return validateHitReturn(rawHtml);
} catch (e) {
return false;
}
};
const validateHitReturn = (html: string): boolean => {
const table = stringToDomElement(html);
const alertBox = findAlertBox(table);
return alertBox ? validateAlertBoxText(alertBox) : false;
};
const findAlertBox = (el: HTMLTableElement) => {
const alertBox = el.querySelector('span#alertBoxHeader');
return alertBox ? alertBox as HTMLSpanElement : false;
};
const validateAlertBoxText = (el: HTMLSpanElement) => {
return el.innerText.trim() === 'The HIT has been returned.';
};
| Add requesting and parsing for returning a HIT. | Add requesting and parsing for returning a HIT.
| TypeScript | mit | Anveio/mturk-engine,Anveio/mturk-engine,Anveio/mturk-engine | ---
+++
@@ -0,0 +1,30 @@
+import axios from 'axios';
+import { API_URL } from '../constants';
+import { stringToDomElement } from './parsing';
+
+export const returnHit = async (hitId: string) => {
+ try {
+ const response = await axios.get(
+ `${API_URL}/mturk/return?hitId=${hitId}&inPipeline=false`
+ );
+ const rawHtml: string = response.data;
+ return validateHitReturn(rawHtml);
+ } catch (e) {
+ return false;
+ }
+};
+
+const validateHitReturn = (html: string): boolean => {
+ const table = stringToDomElement(html);
+ const alertBox = findAlertBox(table);
+ return alertBox ? validateAlertBoxText(alertBox) : false;
+};
+
+const findAlertBox = (el: HTMLTableElement) => {
+ const alertBox = el.querySelector('span#alertBoxHeader');
+ return alertBox ? alertBox as HTMLSpanElement : false;
+};
+
+const validateAlertBoxText = (el: HTMLSpanElement) => {
+ return el.innerText.trim() === 'The HIT has been returned.';
+}; |
|
43d7bcf5858de0ac827b067168b0eef51bd9f92b | src/core/test/ts/browser/InlineEditorRemoveTest.ts | src/core/test/ts/browser/InlineEditorRemoveTest.ts | import { Assertions, GeneralSteps, Pipeline, Logger, Step } from '@ephox/agar';
import EditorManager from 'tinymce/core/api/EditorManager';
import Theme from 'tinymce/themes/modern/Theme';
import { UnitTest } from '@ephox/bedrock';
import ViewBlock from '../module/test/ViewBlock';
UnitTest.asynctest('browser.tinymce.core.InlineEditorRemoveTest', (success, failure) => {
const viewBlock = ViewBlock();
Theme();
const sCreateInlineEditors = function (html) {
return Step.async(function (done) {
viewBlock.update(html);
EditorManager.init({
selector: '.tinymce',
inline: true,
skin_url: '/project/js/tinymce/skins/lightgray'
}).then(function () {
done();
});
});
};
const sRemoveEditors = Step.sync(function () {
EditorManager.remove();
});
viewBlock.attach();
Pipeline.async({}, [
Logger.t('Removing inline editor should remove all data-mce-bogus tags', GeneralSteps.sequence([
sCreateInlineEditors('<div class="tinymce"></div>'),
Step.sync(function () {
EditorManager.get(0).getBody().innerHTML = '<p data-mce-bogus="all">b</p><p data-mce-bogus="1">b</p>';
}),
sRemoveEditors,
Step.sync(function () {
const bogusEl = viewBlock.get().querySelector('[data-mce-bogus]');
Assertions.assertEq('Should not be any data-mce-bogus tags present', false, !!bogusEl);
}),
]))
], function () {
viewBlock.detach();
success();
}, failure);
});
| Create test for inline editor removal | TINY-1669: Create test for inline editor removal
| TypeScript | lgpl-2.1 | FernCreek/tinymce,tinymce/tinymce,FernCreek/tinymce,tinymce/tinymce,TeamupCom/tinymce,danielpunkass/tinymce,danielpunkass/tinymce,FernCreek/tinymce,tinymce/tinymce,danielpunkass/tinymce,TeamupCom/tinymce | ---
+++
@@ -0,0 +1,47 @@
+import { Assertions, GeneralSteps, Pipeline, Logger, Step } from '@ephox/agar';
+import EditorManager from 'tinymce/core/api/EditorManager';
+import Theme from 'tinymce/themes/modern/Theme';
+import { UnitTest } from '@ephox/bedrock';
+import ViewBlock from '../module/test/ViewBlock';
+
+UnitTest.asynctest('browser.tinymce.core.InlineEditorRemoveTest', (success, failure) => {
+ const viewBlock = ViewBlock();
+
+ Theme();
+
+ const sCreateInlineEditors = function (html) {
+ return Step.async(function (done) {
+ viewBlock.update(html);
+
+ EditorManager.init({
+ selector: '.tinymce',
+ inline: true,
+ skin_url: '/project/js/tinymce/skins/lightgray'
+ }).then(function () {
+ done();
+ });
+ });
+ };
+
+ const sRemoveEditors = Step.sync(function () {
+ EditorManager.remove();
+ });
+
+ viewBlock.attach();
+ Pipeline.async({}, [
+ Logger.t('Removing inline editor should remove all data-mce-bogus tags', GeneralSteps.sequence([
+ sCreateInlineEditors('<div class="tinymce"></div>'),
+ Step.sync(function () {
+ EditorManager.get(0).getBody().innerHTML = '<p data-mce-bogus="all">b</p><p data-mce-bogus="1">b</p>';
+ }),
+ sRemoveEditors,
+ Step.sync(function () {
+ const bogusEl = viewBlock.get().querySelector('[data-mce-bogus]');
+ Assertions.assertEq('Should not be any data-mce-bogus tags present', false, !!bogusEl);
+ }),
+ ]))
+ ], function () {
+ viewBlock.detach();
+ success();
+ }, failure);
+}); |
|
442bc56fc2b1a4ba862cd33895f3185dafc85044 | tests/cases/fourslash/getOutliningSpansForRegions.ts | tests/cases/fourslash/getOutliningSpansForRegions.ts | /// <reference path="fourslash.ts"/>
////// basic region
////[|// #region
////
////// #endregion|]
////
////// region with label
////[|// #region label1
////
////// #endregion|]
////
////// region with extra whitespace in all valid locations
////[| // #region label2 label3
////
//// // #endregion|]
////
////// No space before directive
////[|//#region label4
////
//////#endregion|]
////
////// Nested regions
////[|// #region outer
////
////[|// #region inner
////
////// #endregion inner|]
////
////// #endregion outer|]
////
////// region delimiters not valid when preceding text on line
//// test // #region invalid1
////
////test // #endregion
////
////// region delimiters not valid when in multiline comment
/////*
////// #region invalid2
////*/
////
/////*
////// #endregion
////*/
verify.outliningSpansInCurrentFile(test.ranges()); | Add test for region spans | Add test for region spans
| TypeScript | apache-2.0 | nojvek/TypeScript,kitsonk/TypeScript,synaptek/TypeScript,kpreisser/TypeScript,basarat/TypeScript,RyanCavanaugh/TypeScript,microsoft/TypeScript,alexeagle/TypeScript,weswigham/TypeScript,minestarks/TypeScript,microsoft/TypeScript,alexeagle/TypeScript,Eyas/TypeScript,Eyas/TypeScript,nojvek/TypeScript,TukekeSoft/TypeScript,TukekeSoft/TypeScript,SaschaNaz/TypeScript,Eyas/TypeScript,kpreisser/TypeScript,synaptek/TypeScript,synaptek/TypeScript,minestarks/TypeScript,basarat/TypeScript,SaschaNaz/TypeScript,kpreisser/TypeScript,microsoft/TypeScript,Microsoft/TypeScript,nojvek/TypeScript,donaldpipowitch/TypeScript,basarat/TypeScript,alexeagle/TypeScript,basarat/TypeScript,TukekeSoft/TypeScript,donaldpipowitch/TypeScript,SaschaNaz/TypeScript,synaptek/TypeScript,weswigham/TypeScript,minestarks/TypeScript,Eyas/TypeScript,RyanCavanaugh/TypeScript,weswigham/TypeScript,nojvek/TypeScript,donaldpipowitch/TypeScript,RyanCavanaugh/TypeScript,kitsonk/TypeScript,SaschaNaz/TypeScript,donaldpipowitch/TypeScript,kitsonk/TypeScript,Microsoft/TypeScript,Microsoft/TypeScript | ---
+++
@@ -0,0 +1,46 @@
+/// <reference path="fourslash.ts"/>
+
+////// basic region
+////[|// #region
+////
+////// #endregion|]
+////
+////// region with label
+////[|// #region label1
+////
+////// #endregion|]
+////
+////// region with extra whitespace in all valid locations
+////[| // #region label2 label3
+////
+//// // #endregion|]
+////
+////// No space before directive
+////[|//#region label4
+////
+//////#endregion|]
+////
+////// Nested regions
+////[|// #region outer
+////
+////[|// #region inner
+////
+////// #endregion inner|]
+////
+////// #endregion outer|]
+////
+////// region delimiters not valid when preceding text on line
+//// test // #region invalid1
+////
+////test // #endregion
+////
+////// region delimiters not valid when in multiline comment
+/////*
+////// #region invalid2
+////*/
+////
+/////*
+////// #endregion
+////*/
+
+verify.outliningSpansInCurrentFile(test.ranges()); |
|
a353b56c2a803209804a5f0ff2f8daaa018c95a7 | client/test/Combatant.test.ts | client/test/Combatant.test.ts | import { StatBlock } from "../../common/StatBlock";
import { InitializeSettings } from "../Settings/Settings";
import { buildEncounter } from "./buildEncounter";
describe("Combatant", () => {
beforeEach(() => {
InitializeSettings();
});
test("Should have its Max HP set from the statblock", () => {
const encounter = buildEncounter();
const combatant = encounter.AddCombatantFromStatBlock({ ...StatBlock.Default(), HP: { Value: 10, Notes: "" } });
expect(combatant.MaxHP).toBe(10);
});
}); | Test that combatant gets its HP from its statblock | Test that combatant gets its HP from its statblock
| TypeScript | mit | cynicaloptimist/improved-initiative,cynicaloptimist/improved-initiative,cynicaloptimist/improved-initiative | ---
+++
@@ -0,0 +1,16 @@
+import { StatBlock } from "../../common/StatBlock";
+import { InitializeSettings } from "../Settings/Settings";
+import { buildEncounter } from "./buildEncounter";
+
+describe("Combatant", () => {
+ beforeEach(() => {
+ InitializeSettings();
+ });
+
+ test("Should have its Max HP set from the statblock", () => {
+ const encounter = buildEncounter();
+ const combatant = encounter.AddCombatantFromStatBlock({ ...StatBlock.Default(), HP: { Value: 10, Notes: "" } });
+
+ expect(combatant.MaxHP).toBe(10);
+ });
+}); |
|
e2b75720a9f9392e3e04d508ca774020c6a702ae | src/notebook/notebook/widgetfactory.ts | src/notebook/notebook/widgetfactory.ts | // Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
'use strict';
import {
IKernelId
} from 'jupyter-js-services';
import {
IWidgetFactory, IDocumentContext
} from 'jupyter-js-ui/lib/docmanager';
import {
RenderMime
} from 'jupyter-js-ui/lib/rendermime';
import {
MimeData as IClipboard
} from 'phosphor-dragdrop';
import {
Widget
} from 'phosphor-widget';
import {
INotebookModel
} from './model';
import {
NotebookPanel
} from './panel';
/**
* A widget factory for notebook panels.
*/
export
class NotebookWidgetFactory implements IWidgetFactory<NotebookPanel> {
/**
* Construct a new notebook widget factory.
*/
constructor(rendermime: RenderMime<Widget>, clipboard: IClipboard) {
this._rendermime = rendermime;
this._clipboard = clipboard;
}
/**
* Get whether the factory has been disposed.
*/
get isDisposed(): boolean {
return this._rendermime === null;
}
/**
* Dispose of the resources used by the factory.
*/
dispose(): void {
this._rendermime = null;
this._clipboard = null;
}
/**
* Create a new widget.
*/
createNew(model: INotebookModel, context: IDocumentContext, kernel?: IKernelId): NotebookPanel {
let rendermime = this._rendermime.clone();
if (kernel) {
context.changeKernel(kernel);
}
return new NotebookPanel(model, rendermime, context, this._clipboard);
}
/**
* Take an action on a widget before closing it.
*
* @returns A promise that resolves to true if the document should close
* and false otherwise.
*/
beforeClose(model: INotebookModel, context: IDocumentContext, widget: NotebookPanel): Promise<boolean> {
// No special action required.
return Promise.resolve(true);
}
private _rendermime: RenderMime<Widget> = null;
private _clipboard: IClipboard = null;
}
| Add a notebook widget factory | Add a notebook widget factory
| TypeScript | bsd-3-clause | jupyter/jupyterlab,charnpreetsingh185/jupyterlab,TypeFox/jupyterlab,jupyter/jupyterlab,charnpreetsingh185/jupyterlab,eskirk/jupyterlab,charnpreetsingh185/jupyterlab,TypeFox/jupyterlab,TypeFox/jupyterlab,jupyter/jupyterlab,eskirk/jupyterlab,charnpreetsingh185/jupyterlab,eskirk/jupyterlab,jupyter/jupyterlab,TypeFox/jupyterlab,jupyter/jupyterlab,eskirk/jupyterlab,charnpreetsingh185/jupyterlab,eskirk/jupyterlab,TypeFox/jupyterlab | ---
+++
@@ -0,0 +1,86 @@
+// Copyright (c) Jupyter Development Team.
+// Distributed under the terms of the Modified BSD License.
+'use strict';
+
+import {
+ IKernelId
+} from 'jupyter-js-services';
+
+import {
+ IWidgetFactory, IDocumentContext
+} from 'jupyter-js-ui/lib/docmanager';
+
+import {
+ RenderMime
+} from 'jupyter-js-ui/lib/rendermime';
+
+import {
+ MimeData as IClipboard
+} from 'phosphor-dragdrop';
+
+import {
+ Widget
+} from 'phosphor-widget';
+
+import {
+ INotebookModel
+} from './model';
+
+import {
+ NotebookPanel
+} from './panel';
+
+
+/**
+ * A widget factory for notebook panels.
+ */
+export
+class NotebookWidgetFactory implements IWidgetFactory<NotebookPanel> {
+ /**
+ * Construct a new notebook widget factory.
+ */
+ constructor(rendermime: RenderMime<Widget>, clipboard: IClipboard) {
+ this._rendermime = rendermime;
+ this._clipboard = clipboard;
+ }
+
+ /**
+ * Get whether the factory has been disposed.
+ */
+ get isDisposed(): boolean {
+ return this._rendermime === null;
+ }
+
+ /**
+ * Dispose of the resources used by the factory.
+ */
+ dispose(): void {
+ this._rendermime = null;
+ this._clipboard = null;
+ }
+
+ /**
+ * Create a new widget.
+ */
+ createNew(model: INotebookModel, context: IDocumentContext, kernel?: IKernelId): NotebookPanel {
+ let rendermime = this._rendermime.clone();
+ if (kernel) {
+ context.changeKernel(kernel);
+ }
+ return new NotebookPanel(model, rendermime, context, this._clipboard);
+ }
+
+ /**
+ * Take an action on a widget before closing it.
+ *
+ * @returns A promise that resolves to true if the document should close
+ * and false otherwise.
+ */
+ beforeClose(model: INotebookModel, context: IDocumentContext, widget: NotebookPanel): Promise<boolean> {
+ // No special action required.
+ return Promise.resolve(true);
+ }
+
+ private _rendermime: RenderMime<Widget> = null;
+ private _clipboard: IClipboard = null;
+} |
|
919bc2eb1b720571a9098254d685fa71e32f9d94 | src/smc-webapp/smc-react/examples/example_actions.ts | src/smc-webapp/smc-react/examples/example_actions.ts | import { Store, store_definition } from "../Store";
import { redux, Actions } from "../../smc-react";
// Basic Store
interface bakeryState {
cake: string;
pie: string;
}
let init_state: bakeryState = {
cake: "chocolate",
pie: "pizza"
};
let store = redux.createStore("test", init_state);
class bakeryActions extends Actions<bakeryState> {
change_pie(new_pie: string): void {
this.setState({pie: new_pie})
}
}
let actions = redux.createActions("test", bakeryActions, init_state)
actions.change_pie("Savory") | Add an example for actions | Add an example for actions
| TypeScript | agpl-3.0 | DrXyzzy/smc,DrXyzzy/smc,tscholl2/smc,sagemathinc/smc,tscholl2/smc,sagemathinc/smc,tscholl2/smc,DrXyzzy/smc,tscholl2/smc,DrXyzzy/smc,sagemathinc/smc,tscholl2/smc,sagemathinc/smc | ---
+++
@@ -0,0 +1,27 @@
+import { Store, store_definition } from "../Store";
+import { redux, Actions } from "../../smc-react";
+
+
+// Basic Store
+interface bakeryState {
+ cake: string;
+ pie: string;
+}
+
+let init_state: bakeryState = {
+ cake: "chocolate",
+ pie: "pizza"
+};
+
+let store = redux.createStore("test", init_state);
+
+
+
+class bakeryActions extends Actions<bakeryState> {
+ change_pie(new_pie: string): void {
+ this.setState({pie: new_pie})
+ }
+}
+
+let actions = redux.createActions("test", bakeryActions, init_state)
+actions.change_pie("Savory") |
|
5b83f59c3a224263baa07ef87ff37abca2e39cdd | src/app/app.component.spec.ts | src/app/app.component.spec.ts | import { provide } from 'angular2/core';
import { it, describe, expect, beforeEach, beforeEachProviders, inject, injectAsync } from 'angular2/testing';
import { AppComponent } from './app.component';
describe('AppComponent', () => {
beforeEachProviders(() => [ AppComponent ]);
it('should be instantiated and injected', inject([AppComponent], (appComponent: AppComponent) => {
expect(appComponent).toBeAnInstanceOf(AppComponent);
}));
});
| Add a silly app component test | Add a silly app component test
| TypeScript | agpl-3.0 | PRX/publish.prx.org,PRX/publish.prx.org,PRX/publish.prx.org,PRX/publish.prx.org | ---
+++
@@ -0,0 +1,13 @@
+import { provide } from 'angular2/core';
+import { it, describe, expect, beforeEach, beforeEachProviders, inject, injectAsync } from 'angular2/testing';
+import { AppComponent } from './app.component';
+
+describe('AppComponent', () => {
+
+ beforeEachProviders(() => [ AppComponent ]);
+
+ it('should be instantiated and injected', inject([AppComponent], (appComponent: AppComponent) => {
+ expect(appComponent).toBeAnInstanceOf(AppComponent);
+ }));
+
+}); |
|
45d4a9aed53981bbd6d016b9e2d17c28eee54658 | packages/elasticsearch-store/test/helpers/template-index.ts | packages/elasticsearch-store/test/helpers/template-index.ts | import { Overwrite } from '@terascope/utils';
export interface TemplateRecord {
some_id: string;
search_keyword: string;
random_number: number;
}
export type TemplateRecordInput = Overwrite<TemplateRecord, {
random_number?: number;
}>;
export const templateRecordSchema = {
additionalProperties: false,
properties: {
some_id: {
type: 'string'
},
search_keyword: {
type: 'string'
},
random_number: {
type: 'number',
default: Math.round(Math.random() * 10000),
}
},
required: ['some_id', 'search_keyword']
};
export const simpleMapping = {
_all: {
enabled: false
},
dynamic: false,
properties: {
some_id: {
type: 'keyword'
},
search_keyword: {
type: 'keyword'
},
random_number: {
type: 'integer'
},
_created: {
type: 'date'
},
_updated: {
type: 'date'
}
}
};
| Add Template Index helper file | Add Template Index helper file
| TypeScript | apache-2.0 | terascope/teraslice,terascope/teraslice,terascope/teraslice,terascope/teraslice | ---
+++
@@ -0,0 +1,52 @@
+import { Overwrite } from '@terascope/utils';
+
+export interface TemplateRecord {
+ some_id: string;
+ search_keyword: string;
+ random_number: number;
+}
+
+export type TemplateRecordInput = Overwrite<TemplateRecord, {
+ random_number?: number;
+}>;
+
+export const templateRecordSchema = {
+ additionalProperties: false,
+ properties: {
+ some_id: {
+ type: 'string'
+ },
+ search_keyword: {
+ type: 'string'
+ },
+ random_number: {
+ type: 'number',
+ default: Math.round(Math.random() * 10000),
+ }
+ },
+ required: ['some_id', 'search_keyword']
+};
+
+export const simpleMapping = {
+ _all: {
+ enabled: false
+ },
+ dynamic: false,
+ properties: {
+ some_id: {
+ type: 'keyword'
+ },
+ search_keyword: {
+ type: 'keyword'
+ },
+ random_number: {
+ type: 'integer'
+ },
+ _created: {
+ type: 'date'
+ },
+ _updated: {
+ type: 'date'
+ }
+ }
+}; |
|
2e16e330efe865f67e3595f28d1058c5cf6f5272 | src/providers/busca-produto-service.ts | src/providers/busca-produto-service.ts | import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
@Injectable()
export class BuscaProdutoService {
constructor(public http: Http) {
console.log('Hello BuscaProdutoService Provider');
}
getProduto(cep: string) : Promise<Response> {
return this.http.get('https://viacep.com.br/ws/'+ cep.trim() +'/json/').toPromise();
}
}
| Test consumes api new files | Test consumes api new files
| TypeScript | mit | fernandofraga109/ionic-2-course,fernandofraga109/ionic-2-course,fernandofraga109/ionic-2-course,fernandofraga109/ionic-2-course,fernandofraga109/ionic-2-course,fernandofraga109/ionic-2-course,fernandofraga109/ionic-2-course,fernandofraga109/ionic-2-course | ---
+++
@@ -0,0 +1,18 @@
+import { Injectable } from '@angular/core';
+import { Http, Response } from '@angular/http';
+import 'rxjs/add/operator/map';
+import 'rxjs/add/operator/toPromise';
+
+
+@Injectable()
+export class BuscaProdutoService {
+
+ constructor(public http: Http) {
+ console.log('Hello BuscaProdutoService Provider');
+ }
+
+ getProduto(cep: string) : Promise<Response> {
+ return this.http.get('https://viacep.com.br/ws/'+ cep.trim() +'/json/').toPromise();
+ }
+
+} |
|
746b3c409981ba780078d89378445f46634f6a38 | meter/meter.view.ts | meter/meter.view.ts | namespace $.$mol {
export class $mol_meter extends $.$mol_meter {
request_id = 0;
constructor() {
super()
this.defer_task()
}
defer_task( next?: $mol_defer, force?: $mol_atom_force ) {
this.request_id = requestAnimationFrame( () => {
const elem = this.dom_node() as HTMLElement
const rect = elem.getBoundingClientRect()
this.width( rect.width )
this.height( rect.height )
this.top( rect.top )
this.bottom( rect.bottom )
this.left( rect.left )
this.right( rect.right )
this.defer_task( void 0, $mol_atom_force )
} )
}
destroyed( next?: boolean ) {
if( next ) cancelAnimationFrame( this.request_id )
return super.destroyed( next )
}
}
}
| namespace $.$mol {
export class $mol_meter extends $.$mol_meter {
_request_id = 0;
constructor() {
super()
this.defer_task()
}
defer_task( next?: $mol_defer, force?: $mol_atom_force ) {
this._request_id = requestAnimationFrame( () => {
const elem = this.dom_node() as HTMLElement
const rect = elem.getBoundingClientRect()
this.width( rect.width )
this.height( rect.height )
this.top( rect.top )
this.bottom( rect.bottom )
this.left( rect.left )
this.right( rect.right )
this.defer_task( void 0, $mol_atom_force )
} )
}
destroyed( next?: boolean ) {
if( next ) cancelAnimationFrame( this._request_id )
return super.destroyed( next )
}
}
}
| Add underscore to private variable name (request_id) | Add underscore to private variable name (request_id)
| TypeScript | mit | eigenmethod/mol,nin-jin/mol,eigenmethod/mol,nin-jin/mol,eigenmethod/mol,nin-jin/mol | ---
+++
@@ -1,7 +1,7 @@
namespace $.$mol {
export class $mol_meter extends $.$mol_meter {
- request_id = 0;
+ _request_id = 0;
constructor() {
super()
@@ -9,7 +9,7 @@
}
defer_task( next?: $mol_defer, force?: $mol_atom_force ) {
- this.request_id = requestAnimationFrame( () => {
+ this._request_id = requestAnimationFrame( () => {
const elem = this.dom_node() as HTMLElement
const rect = elem.getBoundingClientRect()
@@ -25,7 +25,7 @@
}
destroyed( next?: boolean ) {
- if( next ) cancelAnimationFrame( this.request_id )
+ if( next ) cancelAnimationFrame( this._request_id )
return super.destroyed( next )
}
|
6e0df4d8bd7240cc38694c281337ab378b499d19 | packages/ivi/__tests__/render_element_factory.spec.ts | packages/ivi/__tests__/render_element_factory.spec.ts | import { elementFactory } from "../src/vdom/element";
import { render } from "./utils";
import * as h from "./utils/html";
test(`<div></div>`, () => {
const e = elementFactory(h.div());
const n = render<HTMLElement>(e());
expect(n.tagName.toLowerCase()).toBe("div");
});
test(`predefined className: <div class="a"></div>`, () => {
const e = elementFactory(h.div("a"));
const n = render<HTMLElement>(e());
expect(n.classList.length).toBe(1);
expect(n.classList.contains("a")).toBeTruthy();
});
test(`<div class="a"></div>`, () => {
const e = elementFactory(h.div());
const n = render<HTMLElement>(e("a"));
expect(n.classList.length).toBe(1);
expect(n.classList.contains("a")).toBeTruthy();
});
test(`<div id="123"></div>`, () => {
const e = elementFactory(h.div().a({ id: "123" }));
const n = render<HTMLElement>(e());
expect(n.attributes.length).toBe(1);
expect(n.getAttribute("id")).toBe("123");
});
test(`render twice: <div id="123"></div>`, () => {
const e = elementFactory(h.div().a({ id: "123" }));
render(e());
const n = render<HTMLElement>(e());
expect(n.tagName.toLowerCase()).toBe("div");
expect(n.attributes.length).toBe(1);
expect(n.getAttribute("id")).toBe("123");
});
| Add tests for element factories | Add tests for element factories
| TypeScript | mit | ivijs/ivi,ivijs/ivi | ---
+++
@@ -0,0 +1,44 @@
+import { elementFactory } from "../src/vdom/element";
+import { render } from "./utils";
+import * as h from "./utils/html";
+
+test(`<div></div>`, () => {
+ const e = elementFactory(h.div());
+ const n = render<HTMLElement>(e());
+
+ expect(n.tagName.toLowerCase()).toBe("div");
+});
+
+test(`predefined className: <div class="a"></div>`, () => {
+ const e = elementFactory(h.div("a"));
+ const n = render<HTMLElement>(e());
+
+ expect(n.classList.length).toBe(1);
+ expect(n.classList.contains("a")).toBeTruthy();
+});
+
+test(`<div class="a"></div>`, () => {
+ const e = elementFactory(h.div());
+ const n = render<HTMLElement>(e("a"));
+
+ expect(n.classList.length).toBe(1);
+ expect(n.classList.contains("a")).toBeTruthy();
+});
+
+test(`<div id="123"></div>`, () => {
+ const e = elementFactory(h.div().a({ id: "123" }));
+ const n = render<HTMLElement>(e());
+
+ expect(n.attributes.length).toBe(1);
+ expect(n.getAttribute("id")).toBe("123");
+});
+
+test(`render twice: <div id="123"></div>`, () => {
+ const e = elementFactory(h.div().a({ id: "123" }));
+ render(e());
+ const n = render<HTMLElement>(e());
+
+ expect(n.tagName.toLowerCase()).toBe("div");
+ expect(n.attributes.length).toBe(1);
+ expect(n.getAttribute("id")).toBe("123");
+}); |
|
288c8e68562fe6633d868cccf178d7e5dfcc09fd | src/Test/Html/TableOfContents.ts | src/Test/Html/TableOfContents.ts | /*import { expect } from 'chai'
import Up from '../../index'
import { LinkNode } from '../../SyntaxNodes/LinkNode'
import { ImageNode } from '../../SyntaxNodes/ImageNode'
import { AudioNode } from '../../SyntaxNodes/AudioNode'
import { VideoNode } from '../../SyntaxNodes/VideoNode'
import { DocumentNode } from '../../SyntaxNodes/DocumentNode'
import { PlainTextNode } from '../../SyntaxNodes/PlainTextNode'
import { EmphasisNode } from '../../SyntaxNodes/EmphasisNode'
import { StressNode } from '../../SyntaxNodes/StressNode'
import { InlineCodeNode } from '../../SyntaxNodes/InlineCodeNode'
import { RevisionInsertionNode } from '../../SyntaxNodes/RevisionInsertionNode'
import { RevisionDeletionNode } from '../../SyntaxNodes/RevisionDeletionNode'
import { ParenthesizedNode } from '../../SyntaxNodes/ParenthesizedNode'
import { SquareBracketedNode } from '../../SyntaxNodes/SquareBracketedNode'
import { ActionNode } from '../../SyntaxNodes/ActionNode'
import { InlineSpoilerNode } from '../../SyntaxNodes/InlineSpoilerNode'
import { InlineNsfwNode } from '../../SyntaxNodes/InlineNsfwNode'
import { InlineNsflNode } from '../../SyntaxNodes/InlineNsflNode'
import { SpoilerBlockNode } from '../../SyntaxNodes/SpoilerBlockNode'
import { NsfwBlockNode } from '../../SyntaxNodes/NsfwBlockNode'
import { NsflBlockNode } from '../../SyntaxNodes/NsflBlockNode'
import { FootnoteNode } from '../../SyntaxNodes/FootnoteNode'
import { FootnoteBlockNode } from '../../SyntaxNodes/FootnoteBlockNode'
import { ParagraphNode } from '../../SyntaxNodes/ParagraphNode'
import { BlockquoteNode } from '../../SyntaxNodes/BlockquoteNode'
import { UnorderedListNode } from '../../SyntaxNodes/UnorderedListNode'
import { OrderedListNode } from '../../SyntaxNodes/OrderedListNode'
import { DescriptionListNode } from '../../SyntaxNodes/DescriptionListNode'
import { TableNode } from '../../SyntaxNodes/TableNode'
import { LineBlockNode } from '../../SyntaxNodes/LineBlockNode'
import { HeadingNode } from '../../SyntaxNodes/HeadingNode'
import { CodeBlockNode } from '../../SyntaxNodes/CodeBlockNode'
import { SectionSeparatorNode } from '../../SyntaxNodes/SectionSeparatorNode'
context('A table of contents produces a <nav class="up-table-of-contents"> as the first element of the HTML document.', () => {
context('The <nav> contains elements corresponding to its entries.', () => {
context("Heading entries produce heading elements corresponding to their level. The heading's content is wrapped in a link pointing to that same heading in the document.", () => {
specify('Level 1 headings produce <h1>', () => {
})
})
})
})*/ | Add file for table of contents HTML tests | Add file for table of contents HTML tests
| TypeScript | mit | start/up,start/up | ---
+++
@@ -0,0 +1,45 @@
+/*import { expect } from 'chai'
+import Up from '../../index'
+import { LinkNode } from '../../SyntaxNodes/LinkNode'
+import { ImageNode } from '../../SyntaxNodes/ImageNode'
+import { AudioNode } from '../../SyntaxNodes/AudioNode'
+import { VideoNode } from '../../SyntaxNodes/VideoNode'
+import { DocumentNode } from '../../SyntaxNodes/DocumentNode'
+import { PlainTextNode } from '../../SyntaxNodes/PlainTextNode'
+import { EmphasisNode } from '../../SyntaxNodes/EmphasisNode'
+import { StressNode } from '../../SyntaxNodes/StressNode'
+import { InlineCodeNode } from '../../SyntaxNodes/InlineCodeNode'
+import { RevisionInsertionNode } from '../../SyntaxNodes/RevisionInsertionNode'
+import { RevisionDeletionNode } from '../../SyntaxNodes/RevisionDeletionNode'
+import { ParenthesizedNode } from '../../SyntaxNodes/ParenthesizedNode'
+import { SquareBracketedNode } from '../../SyntaxNodes/SquareBracketedNode'
+import { ActionNode } from '../../SyntaxNodes/ActionNode'
+import { InlineSpoilerNode } from '../../SyntaxNodes/InlineSpoilerNode'
+import { InlineNsfwNode } from '../../SyntaxNodes/InlineNsfwNode'
+import { InlineNsflNode } from '../../SyntaxNodes/InlineNsflNode'
+import { SpoilerBlockNode } from '../../SyntaxNodes/SpoilerBlockNode'
+import { NsfwBlockNode } from '../../SyntaxNodes/NsfwBlockNode'
+import { NsflBlockNode } from '../../SyntaxNodes/NsflBlockNode'
+import { FootnoteNode } from '../../SyntaxNodes/FootnoteNode'
+import { FootnoteBlockNode } from '../../SyntaxNodes/FootnoteBlockNode'
+import { ParagraphNode } from '../../SyntaxNodes/ParagraphNode'
+import { BlockquoteNode } from '../../SyntaxNodes/BlockquoteNode'
+import { UnorderedListNode } from '../../SyntaxNodes/UnorderedListNode'
+import { OrderedListNode } from '../../SyntaxNodes/OrderedListNode'
+import { DescriptionListNode } from '../../SyntaxNodes/DescriptionListNode'
+import { TableNode } from '../../SyntaxNodes/TableNode'
+import { LineBlockNode } from '../../SyntaxNodes/LineBlockNode'
+import { HeadingNode } from '../../SyntaxNodes/HeadingNode'
+import { CodeBlockNode } from '../../SyntaxNodes/CodeBlockNode'
+import { SectionSeparatorNode } from '../../SyntaxNodes/SectionSeparatorNode'
+
+
+context('A table of contents produces a <nav class="up-table-of-contents"> as the first element of the HTML document.', () => {
+ context('The <nav> contains elements corresponding to its entries.', () => {
+ context("Heading entries produce heading elements corresponding to their level. The heading's content is wrapped in a link pointing to that same heading in the document.", () => {
+ specify('Level 1 headings produce <h1>', () => {
+
+ })
+ })
+ })
+})*/ |
|
f5dc2fecb1ecaa7f0298d4c04e3b8acac1393985 | lighthouse-cli/types/types.ts | lighthouse-cli/types/types.ts | interface AuditResult {
displayValue: string;
debugString: string;
comingSoon?: boolean;
score: number;
description: string;
extendedInfo?: {
value: string;
formatter: string;
};
}
interface AggregationResultItem {
overall: number;
name: string;
scored: boolean;
subItems: Array<AuditResult | string>;
}
interface Aggregation {
name: string;
score: Array<AggregationResultItem>;
}
interface Results {
url: string;
aggregations: Array<Aggregation>;
audits: Object;
lighthouseVersion: string;
};
export {
Results,
Aggregation,
AggregationResultItem,
AuditResult,
}
| interface AuditResult {
displayValue: string;
debugString: string;
comingSoon?: boolean;
score: number;
description: string;
name: string;
category: string;
helpText?: string;
requiredArtifacts?: Array<string>;
extendedInfo?: {
value: string;
formatter: string;
};
}
interface AggregationResultItem {
overall: number;
name: string;
scored: boolean;
subItems: Array<AuditResult | string>;
}
interface Aggregation {
name: string;
score: Array<AggregationResultItem>;
}
interface Results {
url: string;
aggregations: Array<Aggregation>;
audits: Object;
lighthouseVersion: string;
};
export {
Results,
Aggregation,
AggregationResultItem,
AuditResult,
}
| Add more object shape properties to AuditResult. | Add more object shape properties to AuditResult.
| TypeScript | apache-2.0 | GoogleChrome/lighthouse,deepanjanroy/lighthouse,tommycli/lighthouse,mixed/lighthouse,tommycli/lighthouse,tkadlec/lighthouse,cedricbellet/lighthouse,deepanjanroy/lighthouse,umaar/lighthouse,mixed/lighthouse,deepanjanroy/lighthouse,ev1stensberg/lighthouse,tommycli/lighthouse,arturmiz/lighthouse,deepanjanroy/lighthouse,mixed/lighthouse,GoogleChrome/lighthouse,cedricbellet/lighthouse,wardpeet/lighthouse,deepanjanroy/lighthouse,GoogleChrome/lighthouse,mixed/lighthouse,ev1stensberg/lighthouse,umaar/lighthouse,arturmiz/lighthouse,tkadlec/lighthouse,tkadlec/lighthouse,GoogleChrome/lighthouse,umaar/lighthouse,arturmiz/lighthouse,arturmiz/lighthouse,wardpeet/lighthouse,wardpeet/lighthouse,tkadlec/lighthouse,cedricbellet/lighthouse,tommycli/lighthouse,cedricbellet/lighthouse,arturmiz/lighthouse,umaar/lighthouse,tommycli/lighthouse,ev1stensberg/lighthouse,GoogleChrome/lighthouse,wardpeet/lighthouse,ev1stensberg/lighthouse,wardpeet/lighthouse,cedricbellet/lighthouse | ---
+++
@@ -4,6 +4,10 @@
comingSoon?: boolean;
score: number;
description: string;
+ name: string;
+ category: string;
+ helpText?: string;
+ requiredArtifacts?: Array<string>;
extendedInfo?: {
value: string;
formatter: string; |
532819a062313d41c01a93f35f40c69668e4cea5 | packages/opencensus-core/test/test-span.ts | packages/opencensus-core/test/test-span.ts | import { Span } from '../src/trace/span';
import { Trace } from '../src/trace/trace';
var assert = require('assert');
describe('Span creation', function () {
let trace;
let span;
before(function () {
trace = new Trace();
span = trace.startSpan('spanName', 'typeSpan');
});
it('should create an span on the trace', function () {
assert.ok(trace instanceof Trace);
span = trace.startSpan('spanName', 'typeSpan');
assert.ok(span instanceof Span);
assert.ok(span.id);
});
it('should start a span', function () {
span.start();
assert.ok(span.started);
});
it('should end a span', function () {
span.end();
assert.ok(span.ended);
});
});
describe('Span checking creation', function () {
let trace;
let span;
before(function () {
trace = new Trace();
span = trace.startSpan('spanName', 'typeSpan');
});
it('should not start span after it ended', function () {
span.end();
assert.equal(span.ended, true);
});
});
describe('Span data', function () {
let trace;
before(function () {
trace = new Trace();
});
it('generates unique numeric span ID strings', function () {
var numberOfSpansToCheck = 5;
for (var i = 0; i < numberOfSpansToCheck; i++) {
var span = trace.startSpan('spanName' + i, 'typeSpan' + i);
var spanId = span.id;
assert.ok(typeof spanId === 'string');
assert.ok(spanId.match(/\d+/));
assert.ok(Number(spanId) > 0);
assert.strictEqual(Number(spanId).toString(), spanId);
}
});
// TODO
it('truncates namespace', function(){
this.skip();
});
});
| Add unit tests for span.ts | Add unit tests for span.ts
| TypeScript | apache-2.0 | census-instrumentation/opencensus-node,census-instrumentation/opencensus-node,census-instrumentation/opencensus-node | ---
+++
@@ -0,0 +1,75 @@
+import { Span } from '../src/trace/span';
+import { Trace } from '../src/trace/trace';
+
+var assert = require('assert');
+
+describe('Span creation', function () {
+
+ let trace;
+ let span;
+
+ before(function () {
+ trace = new Trace();
+ span = trace.startSpan('spanName', 'typeSpan');
+ });
+
+ it('should create an span on the trace', function () {
+ assert.ok(trace instanceof Trace);
+ span = trace.startSpan('spanName', 'typeSpan');
+ assert.ok(span instanceof Span);
+ assert.ok(span.id);
+ });
+
+ it('should start a span', function () {
+ span.start();
+ assert.ok(span.started);
+ });
+
+ it('should end a span', function () {
+ span.end();
+ assert.ok(span.ended);
+ });
+});
+
+describe('Span checking creation', function () {
+
+ let trace;
+ let span;
+
+ before(function () {
+ trace = new Trace();
+ span = trace.startSpan('spanName', 'typeSpan');
+ });
+
+ it('should not start span after it ended', function () {
+ span.end();
+ assert.equal(span.ended, true);
+ });
+});
+
+describe('Span data', function () {
+
+ let trace;
+
+ before(function () {
+ trace = new Trace();
+ });
+
+ it('generates unique numeric span ID strings', function () {
+ var numberOfSpansToCheck = 5;
+ for (var i = 0; i < numberOfSpansToCheck; i++) {
+ var span = trace.startSpan('spanName' + i, 'typeSpan' + i);
+ var spanId = span.id;
+ assert.ok(typeof spanId === 'string');
+ assert.ok(spanId.match(/\d+/));
+ assert.ok(Number(spanId) > 0);
+ assert.strictEqual(Number(spanId).toString(), spanId);
+ }
+ });
+
+ // TODO
+ it('truncates namespace', function(){
+ this.skip();
+ });
+});
+ |
|
9fbc1e7f68ba1c1880fdce2fc4157608b8e2943c | src/app/audiologist-navigation/audiologist-navigation.component.spec.ts | src/app/audiologist-navigation/audiologist-navigation.component.spec.ts | import { AudiologistNavigationComponent } from './audiologist-navigation.component';
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { NO_ERRORS_SCHEMA } from '@angular/core';
/*
Unit tests for the Audiologist Navigation comoponent
*/
fdescribe('AudiologistNavigationComponent', () => {
let component: AudiologistNavigationComponent;
let fixture: ComponentFixture<AudiologistNavigationComponent>;
beforeEach(async() => {
TestBed.configureTestingModule({
schemas: [NO_ERRORS_SCHEMA],
declarations: [ AudiologistNavigationComponent ]
}).compileComponents();
fixture = TestBed.createComponent(AudiologistNavigationComponent);
component = fixture.debugElement.componentInstance;
fixture.detectChanges();
});
fit('should create', () => {
expect(component).toBeTruthy();
});
});
| Add initial unit test starter file and code | Add initial unit test starter file and code
| TypeScript | mit | marissa-hagglund/VA-Audiology-Website,marissa-hagglund/VA-Audiology-Website,marissa-hagglund/VA-Audiology-Website | ---
+++
@@ -0,0 +1,27 @@
+import { AudiologistNavigationComponent } from './audiologist-navigation.component';
+import { async, ComponentFixture, TestBed } from '@angular/core/testing';
+import { NO_ERRORS_SCHEMA } from '@angular/core';
+
+/*
+ Unit tests for the Audiologist Navigation comoponent
+*/
+fdescribe('AudiologistNavigationComponent', () => {
+ let component: AudiologistNavigationComponent;
+ let fixture: ComponentFixture<AudiologistNavigationComponent>;
+
+ beforeEach(async() => {
+ TestBed.configureTestingModule({
+ schemas: [NO_ERRORS_SCHEMA],
+ declarations: [ AudiologistNavigationComponent ]
+ }).compileComponents();
+
+ fixture = TestBed.createComponent(AudiologistNavigationComponent);
+ component = fixture.debugElement.componentInstance;
+
+ fixture.detectChanges();
+ });
+
+ fit('should create', () => {
+ expect(component).toBeTruthy();
+ });
+}); |
|
0763774831bff6a22f3f578572109db408ff3e4b | test/custom_decorator.spec.ts | test/custom_decorator.spec.ts | import {
getType,
} from '../src';
function UserDecorator(target: any) { }
function OtherDecorator(target: any) { }
@UserDecorator
export class MyClassA {
a: string;
}
@OtherDecorator
export class MyClassB {
a: string;
}
describe('Custom Decorators', () => {
// Note UserDecorator is configured in webpack.test.js
it('should allow UserDecorator', () => {
const clsType = getType(MyClassA);
expect(clsType).not.toBeNull();
});
it('should throw on non-decorated', () => {
expect(() => {
getType(MyClassB);
}).toThrow();
});
});
| Add test for support of custom decorator names. | Add test for support of custom decorator names.
| TypeScript | mit | goloveychuk/tsruntime,goloveychuk/tsruntime | ---
+++
@@ -0,0 +1,34 @@
+import {
+ getType,
+} from '../src';
+
+
+function UserDecorator(target: any) { }
+
+function OtherDecorator(target: any) { }
+
+@UserDecorator
+export class MyClassA {
+ a: string;
+}
+
+@OtherDecorator
+export class MyClassB {
+ a: string;
+}
+
+describe('Custom Decorators', () => {
+ // Note UserDecorator is configured in webpack.test.js
+ it('should allow UserDecorator', () => {
+ const clsType = getType(MyClassA);
+ expect(clsType).not.toBeNull();
+ });
+
+ it('should throw on non-decorated', () => {
+ expect(() => {
+ getType(MyClassB);
+ }).toThrow();
+ });
+
+});
+ |
|
7c15168ce4ff08c75f3e5a8b3ac9599424825e1d | src/lib/plugins/ControllerMountSpyPlugin/ControllerMountSpyPlugin.ts | src/lib/plugins/ControllerMountSpyPlugin/ControllerMountSpyPlugin.ts | import { PluginConfig, exportDependency, PluginConstructor } from '../../core/PluginConfig'
import { memoize } from 'lodash';
export type MountSpyCondition = (x: React.Component) => boolean
export interface MountSpyObserver {
condition: MountSpyCondition
resolve: () => void
}
export interface ControllerMountSpyPlugin extends PluginConfig {
waitFor(condition: MountSpyCondition): Promise<void>
}
export interface ControllerMountSpy {
didMount(controller: React.Component): void
}
export const ControllerMountSpy = 'ControllerMountSpy'
export const mountSpy: () => PluginConstructor<ControllerMountSpyPlugin> = memoize(() => {
class ControllerMountSpyPluginImpl extends PluginConfig implements ControllerMountSpyPluginImpl {
private observers: MountSpyObserver[] = []
waitFor(condition: MountSpyCondition): Promise<void> {
return new Promise((resolve) => {
this.observers.push({ condition, resolve })
})
}
@exportDependency(ControllerMountSpy)
mountSpy: ControllerMountSpy = {
didMount: (controller: React.Component) => {
this.observers.forEach((observer) => {
if (observer.condition(controller)) {
observer.resolve()
}
})
}
}
}
return ControllerMountSpyPluginImpl
})
| Add ControllerMountSpy plugin, allowing test cases to wait for async-loaded controllers to mount | Add ControllerMountSpy plugin, allowing test cases to wait for async-loaded controllers to mount
| TypeScript | mit | brightinteractive/bright-js-framework,brightinteractive/bright-js-framework,brightinteractive/bright-js-framework | ---
+++
@@ -0,0 +1,44 @@
+import { PluginConfig, exportDependency, PluginConstructor } from '../../core/PluginConfig'
+import { memoize } from 'lodash';
+
+export type MountSpyCondition = (x: React.Component) => boolean
+
+export interface MountSpyObserver {
+ condition: MountSpyCondition
+ resolve: () => void
+}
+
+export interface ControllerMountSpyPlugin extends PluginConfig {
+ waitFor(condition: MountSpyCondition): Promise<void>
+}
+
+export interface ControllerMountSpy {
+ didMount(controller: React.Component): void
+}
+
+export const ControllerMountSpy = 'ControllerMountSpy'
+
+export const mountSpy: () => PluginConstructor<ControllerMountSpyPlugin> = memoize(() => {
+ class ControllerMountSpyPluginImpl extends PluginConfig implements ControllerMountSpyPluginImpl {
+ private observers: MountSpyObserver[] = []
+
+ waitFor(condition: MountSpyCondition): Promise<void> {
+ return new Promise((resolve) => {
+ this.observers.push({ condition, resolve })
+ })
+ }
+
+ @exportDependency(ControllerMountSpy)
+ mountSpy: ControllerMountSpy = {
+ didMount: (controller: React.Component) => {
+ this.observers.forEach((observer) => {
+ if (observer.condition(controller)) {
+ observer.resolve()
+ }
+ })
+ }
+ }
+ }
+
+ return ControllerMountSpyPluginImpl
+}) |
|
26390cd46c4278b764317057710b0d241c20ed7f | src/Test/Ast/CodeBlock.ts | src/Test/Ast/CodeBlock.ts | /// <reference path="../../../typings/mocha/mocha.d.ts" />
/// <reference path="../../../typings/chai/chai.d.ts" />
import { expect } from 'chai'
import * as Up from '../../index'
import { SyntaxNode } from '../../SyntaxNodes/SyntaxNode'
import { DocumentNode } from '../../SyntaxNodes/DocumentNode'
import { PlainTextNode } from '../../SyntaxNodes/PlainTextNode'
import { CodeBlockNode } from '../../SyntaxNodes/CodeBlockNode'
function insideDocument(syntaxNodes: SyntaxNode[]): DocumentNode {
return new DocumentNode(syntaxNodes);
}
describe('Text surrounded (underlined and overlined) by streaks of backticks', function() {
it('produces a code block node containing the surrounded text', function() {
const text =
`
\`\`\`
let x = y
\`\`\``
expect(Up.ast(text)).to.be.eql(
insideDocument([
new CodeBlockNode([
new PlainTextNode('let x = y')
]),
]))
})
})
| Add failing code block test | Add failing code block test
| TypeScript | mit | start/up,start/up | ---
+++
@@ -0,0 +1,31 @@
+/// <reference path="../../../typings/mocha/mocha.d.ts" />
+/// <reference path="../../../typings/chai/chai.d.ts" />
+
+import { expect } from 'chai'
+import * as Up from '../../index'
+import { SyntaxNode } from '../../SyntaxNodes/SyntaxNode'
+import { DocumentNode } from '../../SyntaxNodes/DocumentNode'
+import { PlainTextNode } from '../../SyntaxNodes/PlainTextNode'
+import { CodeBlockNode } from '../../SyntaxNodes/CodeBlockNode'
+
+
+function insideDocument(syntaxNodes: SyntaxNode[]): DocumentNode {
+ return new DocumentNode(syntaxNodes);
+}
+
+
+describe('Text surrounded (underlined and overlined) by streaks of backticks', function() {
+ it('produces a code block node containing the surrounded text', function() {
+ const text =
+ `
+\`\`\`
+let x = y
+\`\`\``
+ expect(Up.ast(text)).to.be.eql(
+ insideDocument([
+ new CodeBlockNode([
+ new PlainTextNode('let x = y')
+ ]),
+ ]))
+ })
+}) |
|
ca328eff28e80235755e6f180dba8d0b8459ca26 | src/notebook/widgetfactory.ts | src/notebook/widgetfactory.ts | // Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
'use strict';
import {
IKernelId
} from 'jupyter-js-services';
import {
IWidgetFactory, IDocumentContext
} from 'jupyter-js-ui/lib/docmanager';
import {
RenderMime
} from 'jupyter-js-ui/lib/rendermime';
import {
MimeData as IClipboard
} from 'phosphor-dragdrop';
import {
Widget
} from 'phosphor-widget';
import {
INotebookModel
} from './model';
import {
NotebookPanel
} from './panel';
/**
* A widget factory for notebook panels.
*/
export
class NotebookWidgetFactory implements IWidgetFactory<NotebookPanel> {
/**
* Construct a new notebook widget factory.
*/
constructor(rendermime: RenderMime<Widget>, clipboard: IClipboard) {
this._rendermime = rendermime;
this._clipboard = clipboard;
}
/**
* Get whether the factory has been disposed.
*/
get isDisposed(): boolean {
return this._rendermime === null;
}
/**
* Dispose of the resources used by the factory.
*/
dispose(): void {
this._rendermime = null;
this._clipboard = null;
}
/**
* Create a new widget.
*/
createNew(model: INotebookModel, context: IDocumentContext, kernel?: IKernelId): NotebookPanel {
let rendermime = this._rendermime.clone();
if (kernel) {
context.changeKernel(kernel);
}
return new NotebookPanel(model, rendermime, context, this._clipboard);
}
/**
* Take an action on a widget before closing it.
*
* @returns A promise that resolves to true if the document should close
* and false otherwise.
*/
beforeClose(model: INotebookModel, context: IDocumentContext, widget: NotebookPanel): Promise<boolean> {
// No special action required.
return Promise.resolve(true);
}
private _rendermime: RenderMime<Widget> = null;
private _clipboard: IClipboard = null;
}
| Add a notebook widget factory | Add a notebook widget factory
| TypeScript | bsd-3-clause | jupyter/jupyter-js-notebook,jupyter/jupyter-js-notebook,jupyter/jupyter-js-notebook,jupyter/jupyter-js-notebook,jupyter/jupyter-js-notebook | ---
+++
@@ -0,0 +1,86 @@
+// Copyright (c) Jupyter Development Team.
+// Distributed under the terms of the Modified BSD License.
+'use strict';
+
+import {
+ IKernelId
+} from 'jupyter-js-services';
+
+import {
+ IWidgetFactory, IDocumentContext
+} from 'jupyter-js-ui/lib/docmanager';
+
+import {
+ RenderMime
+} from 'jupyter-js-ui/lib/rendermime';
+
+import {
+ MimeData as IClipboard
+} from 'phosphor-dragdrop';
+
+import {
+ Widget
+} from 'phosphor-widget';
+
+import {
+ INotebookModel
+} from './model';
+
+import {
+ NotebookPanel
+} from './panel';
+
+
+/**
+ * A widget factory for notebook panels.
+ */
+export
+class NotebookWidgetFactory implements IWidgetFactory<NotebookPanel> {
+ /**
+ * Construct a new notebook widget factory.
+ */
+ constructor(rendermime: RenderMime<Widget>, clipboard: IClipboard) {
+ this._rendermime = rendermime;
+ this._clipboard = clipboard;
+ }
+
+ /**
+ * Get whether the factory has been disposed.
+ */
+ get isDisposed(): boolean {
+ return this._rendermime === null;
+ }
+
+ /**
+ * Dispose of the resources used by the factory.
+ */
+ dispose(): void {
+ this._rendermime = null;
+ this._clipboard = null;
+ }
+
+ /**
+ * Create a new widget.
+ */
+ createNew(model: INotebookModel, context: IDocumentContext, kernel?: IKernelId): NotebookPanel {
+ let rendermime = this._rendermime.clone();
+ if (kernel) {
+ context.changeKernel(kernel);
+ }
+ return new NotebookPanel(model, rendermime, context, this._clipboard);
+ }
+
+ /**
+ * Take an action on a widget before closing it.
+ *
+ * @returns A promise that resolves to true if the document should close
+ * and false otherwise.
+ */
+ beforeClose(model: INotebookModel, context: IDocumentContext, widget: NotebookPanel): Promise<boolean> {
+ // No special action required.
+ return Promise.resolve(true);
+ }
+
+ private _rendermime: RenderMime<Widget> = null;
+ private _clipboard: IClipboard = null;
+} |
|
72f30a830825b6c4d9d5428e4eeb8eb8745680ae | tests/cases/conformance/classes/constructorDeclarations/quotedConstructors.ts | tests/cases/conformance/classes/constructorDeclarations/quotedConstructors.ts | class C {
x: number;
"constructor"() {
this.x = 0;
}
}
(new C).constructor(); // Error
class D {
x: number;
'constructor'() {
this.x = 0;
}
}
(new C).constructor(); // Error
class E {
x: number;
['constructor']() {
this.x = 0;
}
}
(new E).constructor();
| Add test for quoted constructors | Add test for quoted constructors
| TypeScript | apache-2.0 | weswigham/TypeScript,RyanCavanaugh/TypeScript,nojvek/TypeScript,kitsonk/TypeScript,RyanCavanaugh/TypeScript,minestarks/TypeScript,alexeagle/TypeScript,SaschaNaz/TypeScript,RyanCavanaugh/TypeScript,kpreisser/TypeScript,Microsoft/TypeScript,kpreisser/TypeScript,weswigham/TypeScript,microsoft/TypeScript,Microsoft/TypeScript,nojvek/TypeScript,kitsonk/TypeScript,kpreisser/TypeScript,minestarks/TypeScript,nojvek/TypeScript,weswigham/TypeScript,microsoft/TypeScript,kitsonk/TypeScript,SaschaNaz/TypeScript,nojvek/TypeScript,alexeagle/TypeScript,SaschaNaz/TypeScript,microsoft/TypeScript,SaschaNaz/TypeScript,Microsoft/TypeScript,alexeagle/TypeScript,minestarks/TypeScript | ---
+++
@@ -0,0 +1,23 @@
+class C {
+ x: number;
+ "constructor"() {
+ this.x = 0;
+ }
+}
+(new C).constructor(); // Error
+
+class D {
+ x: number;
+ 'constructor'() {
+ this.x = 0;
+ }
+}
+(new C).constructor(); // Error
+
+class E {
+ x: number;
+ ['constructor']() {
+ this.x = 0;
+ }
+}
+(new E).constructor(); |
|
2a12e545a918a620e8496887d8991770accd2457 | spec/executor.spec.ts | spec/executor.spec.ts | import Executor from '../src/executor';
import * as sinon from 'sinon';
import { expect } from 'chai';
describe('executor', () => {
const executorOptions = {
maxRatePerSecond: 5,
maxConcurrentTasks: 10
};
let executor;
beforeEach(() => {
executor = new Executor(executorOptions);
});
describe('task execution', () => {
it('should execute submitted tasks', (done) => {
let producedValues: Array<number> = [];
let values = [1, 2, 3, 4, 5];
values.forEach((value, idx) => {
executor.submit(() => {
producedValues.push(values[idx]);
return Promise.resolve();
});
});
executor.start();
setTimeout(function waitForEmptyQueue() {
const isQueueEmpty = executor.queue.length == 0;
if (isQueueEmpty) {
expect(producedValues).to.eql(values);
executor.stop();
done();
} else {
setTimeout(waitForEmptyQueue, 10)
}
}, 10);
});
});
});
| Add first unit test for Executor. | Add first unit test for Executor.
| TypeScript | mit | antivanov/js-crawler,antivanov/js-crawler,antivanov/js-crawler,antivanov/js-crawler | ---
+++
@@ -0,0 +1,42 @@
+import Executor from '../src/executor';
+import * as sinon from 'sinon';
+import { expect } from 'chai';
+
+describe('executor', () => {
+
+ const executorOptions = {
+ maxRatePerSecond: 5,
+ maxConcurrentTasks: 10
+ };
+ let executor;
+
+ beforeEach(() => {
+ executor = new Executor(executorOptions);
+ });
+
+ describe('task execution', () => {
+
+ it('should execute submitted tasks', (done) => {
+ let producedValues: Array<number> = [];
+ let values = [1, 2, 3, 4, 5];
+ values.forEach((value, idx) => {
+ executor.submit(() => {
+ producedValues.push(values[idx]);
+ return Promise.resolve();
+ });
+ });
+ executor.start();
+
+ setTimeout(function waitForEmptyQueue() {
+ const isQueueEmpty = executor.queue.length == 0;
+ if (isQueueEmpty) {
+ expect(producedValues).to.eql(values);
+ executor.stop();
+ done();
+ } else {
+ setTimeout(waitForEmptyQueue, 10)
+ }
+ }, 10);
+ });
+ });
+}); |
|
930ff3e28df1ea550d25525b498a7af93dd88643 | src/ts/googledrive.ts | src/ts/googledrive.ts | import { loadingIndicator } from './ui/loading';
import {
getGoogleDriveKey,
refreshGoogleDriveTokenApi,
saveToGoogleDriveApi,
} from './requests';
import { ChromeLocalStorage, ChromeSyncStorage, OAuth2 } from './types';
import {
notifySaveToCloudSuccessful,
notifyUnableToUpload,
} from '../js/libs/notifications';
import { lessThanTimeAgo } from '../js/libs/helpers';
async function openGoogleDriveAuthPage(): Promise<void> {
const response = await getGoogleDriveKey();
const data: { googledrive_key: string } = await response.json();
const key = data.googledrive_key;
chrome.tabs.create({
url: `https://accounts.google.com/o/oauth2/v2/auth?scope=https%3A//www.googleapis.com/auth/drive.file&access_type=offline&response_type=code&redirect_uri=https://ayoisaiah.github.io/stellar-photos&client_id=${key}`,
});
}
async function refreshGoogleDriveToken(): Promise<
ChromeLocalStorage['googledrive'] | void
> {
const localData: ChromeLocalStorage = await chrome.storage.local.get();
const syncData: ChromeSyncStorage = await chrome.storage.sync.get();
const googleDriveAuth = localData.googledrive;
const { googleDriveRefreshToken } = syncData;
if (googleDriveAuth) {
if (!googleDriveRefreshToken) return;
const response = await refreshGoogleDriveTokenApi(googleDriveRefreshToken);
const data: OAuth2 = await response.json();
OAuth2.check(data);
const googledrive = {
timestamp: Date.now(),
...data,
};
chrome.storage.local.set({ googledrive });
return googledrive;
}
}
async function saveToGoogleDrive(imageId: string, url: string): Promise<void> {
try {
const localData: ChromeLocalStorage = await chrome.storage.local.get();
if (!localData.googledrive) {
await openGoogleDriveAuthPage();
return;
}
loadingIndicator().start();
const tokenExpired = lessThanTimeAgo(
localData.googledrive.timestamp,
localData.googledrive.expires_in
);
if (!tokenExpired) {
const data = await refreshGoogleDriveToken();
if (data && data.access_token) {
localData.googledrive = data;
} else {
openGoogleDriveAuthPage();
return;
}
}
const token = localData.googledrive.access_token;
await saveToGoogleDriveApi(imageId, token, url);
notifySaveToCloudSuccessful('Google Drive', imageId);
} catch (err) {
notifyUnableToUpload('Google Drive', imageId);
} finally {
loadingIndicator().stop();
}
}
export { openGoogleDriveAuthPage, refreshGoogleDriveToken, saveToGoogleDrive };
| Add support for saving photos to Google Drive | Add support for saving photos to Google Drive
| TypeScript | mit | ayoisaiah/stellar-photos,ayoisaiah/stellar-photos,ayoisaiah/stellar-photos,ayoisaiah/stellar-photos,ayoisaiah/stellar-photos | ---
+++
@@ -0,0 +1,82 @@
+import { loadingIndicator } from './ui/loading';
+import {
+ getGoogleDriveKey,
+ refreshGoogleDriveTokenApi,
+ saveToGoogleDriveApi,
+} from './requests';
+import { ChromeLocalStorage, ChromeSyncStorage, OAuth2 } from './types';
+import {
+ notifySaveToCloudSuccessful,
+ notifyUnableToUpload,
+} from '../js/libs/notifications';
+import { lessThanTimeAgo } from '../js/libs/helpers';
+
+async function openGoogleDriveAuthPage(): Promise<void> {
+ const response = await getGoogleDriveKey();
+ const data: { googledrive_key: string } = await response.json();
+ const key = data.googledrive_key;
+ chrome.tabs.create({
+ url: `https://accounts.google.com/o/oauth2/v2/auth?scope=https%3A//www.googleapis.com/auth/drive.file&access_type=offline&response_type=code&redirect_uri=https://ayoisaiah.github.io/stellar-photos&client_id=${key}`,
+ });
+}
+
+async function refreshGoogleDriveToken(): Promise<
+ ChromeLocalStorage['googledrive'] | void
+> {
+ const localData: ChromeLocalStorage = await chrome.storage.local.get();
+ const syncData: ChromeSyncStorage = await chrome.storage.sync.get();
+ const googleDriveAuth = localData.googledrive;
+ const { googleDriveRefreshToken } = syncData;
+
+ if (googleDriveAuth) {
+ if (!googleDriveRefreshToken) return;
+ const response = await refreshGoogleDriveTokenApi(googleDriveRefreshToken);
+ const data: OAuth2 = await response.json();
+
+ OAuth2.check(data);
+
+ const googledrive = {
+ timestamp: Date.now(),
+ ...data,
+ };
+
+ chrome.storage.local.set({ googledrive });
+ return googledrive;
+ }
+}
+
+async function saveToGoogleDrive(imageId: string, url: string): Promise<void> {
+ try {
+ const localData: ChromeLocalStorage = await chrome.storage.local.get();
+ if (!localData.googledrive) {
+ await openGoogleDriveAuthPage();
+ return;
+ }
+
+ loadingIndicator().start();
+
+ const tokenExpired = lessThanTimeAgo(
+ localData.googledrive.timestamp,
+ localData.googledrive.expires_in
+ );
+ if (!tokenExpired) {
+ const data = await refreshGoogleDriveToken();
+ if (data && data.access_token) {
+ localData.googledrive = data;
+ } else {
+ openGoogleDriveAuthPage();
+ return;
+ }
+ }
+
+ const token = localData.googledrive.access_token;
+ await saveToGoogleDriveApi(imageId, token, url);
+ notifySaveToCloudSuccessful('Google Drive', imageId);
+ } catch (err) {
+ notifyUnableToUpload('Google Drive', imageId);
+ } finally {
+ loadingIndicator().stop();
+ }
+}
+
+export { openGoogleDriveAuthPage, refreshGoogleDriveToken, saveToGoogleDrive }; |
|
ea52f695a6f9d7b013212bb93a9583b3a2f2534f | src/contentRepo.ts | src/contentRepo.ts | import { MatrixClient } from "matrix-bot-sdk";
/**
* Get the HTTP URL for an MXC URI.
* @param {string} baseUrl The base homeserver url which has a content repo.
* @param {string} mxc The mxc:// URI.
* @param {Number} width The desired width of the thumbnail.
* @param {Number} height The desired height of the thumbnail.
* @param resizeMethod The thumbnail resize method to use, either
* "crop" or "scale".
* @param allowDirectLinks If true, return any non-mxc URLs
* directly. Fetching such URLs will leak information about the user to
* anyone they share a room with. If false, will return the emptry string
* for such URLs.
* @return The complete URL to the content. May be empty string if mxc is not a string.
*/
function getHttpUriForMxc(baseUrl: string, mxc: string, width?: number, height?: number,
resizeMethod?: "crop"|"scale", allowDirectLinks?: boolean): string {
console.warn("Deprecated call to ContentRepo.getHttpUriForMxc, prefer to use Intent.matrixClient.mxcToHttp");
if (typeof mxc !== "string" || !mxc) {
return "";
}
if (!mxc.startsWith("mxc://")) {
return allowDirectLinks ? mxc : "";
}
if (width || height || resizeMethod) {
return new MatrixClient(baseUrl, "").mxcToHttpThumbnail(
// Types are possibly not defined here, but this matches the previous implementation
mxc, width as number, height as number, resizeMethod as "crop"|"scale"
);
}
return new MatrixClient(baseUrl, "").mxcToHttp(mxc);
}
export const ContentRepo = {
getHttpUriForMxc: getHttpUriForMxc,
}
| Add a simple shim for the ContentRepo | Add a simple shim for the ContentRepo
| TypeScript | apache-2.0 | matrix-org/matrix-appservice-bridge,matrix-org/matrix-appservice-bridge,matrix-org/matrix-appservice-bridge | ---
+++
@@ -0,0 +1,37 @@
+import { MatrixClient } from "matrix-bot-sdk";
+
+/**
+ * Get the HTTP URL for an MXC URI.
+ * @param {string} baseUrl The base homeserver url which has a content repo.
+ * @param {string} mxc The mxc:// URI.
+ * @param {Number} width The desired width of the thumbnail.
+ * @param {Number} height The desired height of the thumbnail.
+ * @param resizeMethod The thumbnail resize method to use, either
+ * "crop" or "scale".
+ * @param allowDirectLinks If true, return any non-mxc URLs
+ * directly. Fetching such URLs will leak information about the user to
+ * anyone they share a room with. If false, will return the emptry string
+ * for such URLs.
+ * @return The complete URL to the content. May be empty string if mxc is not a string.
+ */
+function getHttpUriForMxc(baseUrl: string, mxc: string, width?: number, height?: number,
+ resizeMethod?: "crop"|"scale", allowDirectLinks?: boolean): string {
+ console.warn("Deprecated call to ContentRepo.getHttpUriForMxc, prefer to use Intent.matrixClient.mxcToHttp");
+ if (typeof mxc !== "string" || !mxc) {
+ return "";
+ }
+ if (!mxc.startsWith("mxc://")) {
+ return allowDirectLinks ? mxc : "";
+ }
+ if (width || height || resizeMethod) {
+ return new MatrixClient(baseUrl, "").mxcToHttpThumbnail(
+ // Types are possibly not defined here, but this matches the previous implementation
+ mxc, width as number, height as number, resizeMethod as "crop"|"scale"
+ );
+ }
+ return new MatrixClient(baseUrl, "").mxcToHttp(mxc);
+}
+
+export const ContentRepo = {
+ getHttpUriForMxc: getHttpUriForMxc,
+} |
|
0c7b03cad321a84ac8832b1423543befc2efde0c | src/reducers/__tests__/settings.node.tsx | src/reducers/__tests__/settings.node.tsx | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
import {default as reducer, updateSettings, Tristate} from '../settings';
test('init', () => {
const res = reducer(undefined, {type: 'INIT'});
expect(res.enableAndroid).toBeTruthy();
});
test('updateSettings', () => {
const initialSettings = reducer(undefined, {type: 'INIT'});
const updatedSettings = Object.assign(initialSettings, {
enableAndroid: false,
enablePrefetching: Tristate.True,
jsApps: {
webAppLauncher: {
height: 900,
},
},
});
const res = reducer(initialSettings, updateSettings(updatedSettings));
expect(res.enableAndroid).toBeFalsy();
expect(res.enablePrefetching).toEqual(Tristate.True);
expect(res.jsApps.webAppLauncher.height).toEqual(900);
expect(res.jsApps.webAppLauncher.width).toEqual(
initialSettings.jsApps.webAppLauncher.width,
);
});
| Add tests for settings reducer | Add tests for settings reducer
Summary: yiss_tests
Reviewed By: jknoxville
Differential Revision: D18851134
fbshipit-source-id: 53ffb9b516773df19c258e7d819962e3cd523751
| TypeScript | mit | facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper,facebook/flipper | ---
+++
@@ -0,0 +1,36 @@
+/**
+ * Copyright (c) Facebook, Inc. and its affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ *
+ * @format
+ */
+
+import {default as reducer, updateSettings, Tristate} from '../settings';
+
+test('init', () => {
+ const res = reducer(undefined, {type: 'INIT'});
+ expect(res.enableAndroid).toBeTruthy();
+});
+
+test('updateSettings', () => {
+ const initialSettings = reducer(undefined, {type: 'INIT'});
+ const updatedSettings = Object.assign(initialSettings, {
+ enableAndroid: false,
+ enablePrefetching: Tristate.True,
+ jsApps: {
+ webAppLauncher: {
+ height: 900,
+ },
+ },
+ });
+ const res = reducer(initialSettings, updateSettings(updatedSettings));
+
+ expect(res.enableAndroid).toBeFalsy();
+ expect(res.enablePrefetching).toEqual(Tristate.True);
+ expect(res.jsApps.webAppLauncher.height).toEqual(900);
+ expect(res.jsApps.webAppLauncher.width).toEqual(
+ initialSettings.jsApps.webAppLauncher.width,
+ );
+}); |
|
544be459c8f248354dfca600fb2f2201ffafc9d8 | server/src/Linter.ts | server/src/Linter.ts | import URI from 'vscode-uri';
import { empty, iif, from, Observable } from 'rxjs';
import { map, mergeMap, switchMap } from 'rxjs/operators';
import { Diagnostic, TextDocument } from 'vscode-languageserver';
import {
documentConfigurationCache,
RubyEnvironment,
workspaceRubyEnvironmentCache,
RubyConfiguration,
RubyLintConfiguration,
} from './SettingsCache';
import { ILinter, LinterConfig, RuboCop, Reek } from './linters';
import { documents, DocumentEvent, DocumentEventKind } from './DocumentManager';
const LINTER_MAP = {
rubocop: RuboCop,
reek: Reek,
};
export type LintResult = {
document: TextDocument;
diagnostics: Diagnostic[];
error?: string;
};
function getLinter(
name: string,
document: TextDocument,
env: RubyEnvironment,
config: RubyConfiguration
): ILinter {
const lintConfig: RubyLintConfiguration =
typeof config.lint[name] === 'object' ? config.lint[name] : {};
const linterConfig: LinterConfig = {
env,
executionRoot: URI.parse(config.workspaceFolderUri).fsPath,
config: lintConfig,
};
return new LINTER_MAP[name](document, linterConfig);
}
function lint(document: TextDocument): Observable<LintResult> {
return from(documentConfigurationCache.get(document)).pipe(
mergeMap(
config => workspaceRubyEnvironmentCache.get(config.workspaceFolderUri),
(config, env) => {
return { config, env };
}
),
switchMap(({ config, env }) => {
return from(Object.keys(config.lint)).pipe(
mergeMap(l => {
return iif(() => config.lint[l], getLinter(l, document, env, config).lint(), empty());
})
);
}),
map(diagnostics => {
return {
document,
diagnostics,
};
})
);
}
export const linter = documents.subject.pipe(
switchMap((event: DocumentEvent) =>
iif(
() =>
event.kind === DocumentEventKind.OPEN || event.kind === DocumentEventKind.CHANGE_CONTENT,
lint(event.document)
)
)
);
| Add base linter which emits diagnostics on document events | Add base linter which emits diagnostics on document events
| TypeScript | mit | rubyide/vscode-ruby,rubyide/vscode-ruby,rubyide/vscode-ruby,rubyide/vscode-ruby,rubyide/vscode-ruby | ---
+++
@@ -0,0 +1,74 @@
+import URI from 'vscode-uri';
+import { empty, iif, from, Observable } from 'rxjs';
+import { map, mergeMap, switchMap } from 'rxjs/operators';
+import { Diagnostic, TextDocument } from 'vscode-languageserver';
+import {
+ documentConfigurationCache,
+ RubyEnvironment,
+ workspaceRubyEnvironmentCache,
+ RubyConfiguration,
+ RubyLintConfiguration,
+} from './SettingsCache';
+import { ILinter, LinterConfig, RuboCop, Reek } from './linters';
+import { documents, DocumentEvent, DocumentEventKind } from './DocumentManager';
+
+const LINTER_MAP = {
+ rubocop: RuboCop,
+ reek: Reek,
+};
+
+export type LintResult = {
+ document: TextDocument;
+ diagnostics: Diagnostic[];
+ error?: string;
+};
+
+function getLinter(
+ name: string,
+ document: TextDocument,
+ env: RubyEnvironment,
+ config: RubyConfiguration
+): ILinter {
+ const lintConfig: RubyLintConfiguration =
+ typeof config.lint[name] === 'object' ? config.lint[name] : {};
+ const linterConfig: LinterConfig = {
+ env,
+ executionRoot: URI.parse(config.workspaceFolderUri).fsPath,
+ config: lintConfig,
+ };
+ return new LINTER_MAP[name](document, linterConfig);
+}
+
+function lint(document: TextDocument): Observable<LintResult> {
+ return from(documentConfigurationCache.get(document)).pipe(
+ mergeMap(
+ config => workspaceRubyEnvironmentCache.get(config.workspaceFolderUri),
+ (config, env) => {
+ return { config, env };
+ }
+ ),
+ switchMap(({ config, env }) => {
+ return from(Object.keys(config.lint)).pipe(
+ mergeMap(l => {
+ return iif(() => config.lint[l], getLinter(l, document, env, config).lint(), empty());
+ })
+ );
+ }),
+ map(diagnostics => {
+ return {
+ document,
+ diagnostics,
+ };
+ })
+ );
+}
+
+export const linter = documents.subject.pipe(
+ switchMap((event: DocumentEvent) =>
+ iif(
+ () =>
+ event.kind === DocumentEventKind.OPEN || event.kind === DocumentEventKind.CHANGE_CONTENT,
+ lint(event.document)
+ )
+ )
+); |
|
6bbe2ba52c8ce36df8db1343c36b2e0b39471fa6 | app/test/unit/format-commit-message.ts | app/test/unit/format-commit-message.ts | import * as chai from 'chai'
const expect = chai.expect
import { formatCommitMessage } from '../../src/lib/format-commit-message'
describe('formatCommitMessage', () => {
it('omits description when null', () => {
expect(formatCommitMessage({ summary: 'test', description: null }))
.to.equal('test')
})
it('omits description when empty string', () => {
expect(formatCommitMessage({ summary: 'test', description: '' }))
.to.equal('test')
})
it('adds two newlines between summary and description', () => {
expect(formatCommitMessage({ summary: 'foo', description: 'bar' }))
.to.equal('foo\n\nbar')
})
})
| Add some smoke tests for formatCommitMessage | Add some smoke tests for formatCommitMessage
| TypeScript | mit | j-f1/forked-desktop,gengjiawen/desktop,j-f1/forked-desktop,hjobrien/desktop,gengjiawen/desktop,gengjiawen/desktop,shiftkey/desktop,desktop/desktop,desktop/desktop,artivilla/desktop,say25/desktop,hjobrien/desktop,say25/desktop,desktop/desktop,kactus-io/kactus,hjobrien/desktop,say25/desktop,kactus-io/kactus,j-f1/forked-desktop,gengjiawen/desktop,BugTesterTest/desktops,artivilla/desktop,shiftkey/desktop,kactus-io/kactus,desktop/desktop,shiftkey/desktop,BugTesterTest/desktops,kactus-io/kactus,j-f1/forked-desktop,artivilla/desktop,artivilla/desktop,hjobrien/desktop,BugTesterTest/desktops,say25/desktop,shiftkey/desktop,BugTesterTest/desktops | ---
+++
@@ -0,0 +1,21 @@
+import * as chai from 'chai'
+const expect = chai.expect
+
+import { formatCommitMessage } from '../../src/lib/format-commit-message'
+
+describe('formatCommitMessage', () => {
+ it('omits description when null', () => {
+ expect(formatCommitMessage({ summary: 'test', description: null }))
+ .to.equal('test')
+ })
+
+ it('omits description when empty string', () => {
+ expect(formatCommitMessage({ summary: 'test', description: '' }))
+ .to.equal('test')
+ })
+
+ it('adds two newlines between summary and description', () => {
+ expect(formatCommitMessage({ summary: 'foo', description: 'bar' }))
+ .to.equal('foo\n\nbar')
+ })
+}) |
|
b71710de9c05479ffc270c0c08be3ced1ee4534e | console/src/app/common/HttpUtils.ts | console/src/app/common/HttpUtils.ts | export class HttpUtils {
// NOTE: Checks if string matches an IP by pattern.
public static isIpAddressValid(ipAddress: string): boolean {
let ipValidationRegex: RegExp = new RegExp(/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/);
return ipValidationRegex.test(ipAddress);
}
public static shouldPerformMongooseRunRequest(mongooseAddress: string): boolean {
// NOTE: Temporarily checking only IP address.
let isIpValid: boolean = HttpUtils.isIpAddressValid(mongooseAddress);
let isIpPointsToLocalhost: boolean = mongooseAddress.includes("localhost");
return ((isIpValid) || (isIpPointsToLocalhost));
}
å
} | Add HTTP utils (validation, etc.). | Add HTTP utils (validation, etc.).
| TypeScript | mit | emc-mongoose/console,emc-mongoose/console,emc-mongoose/console | ---
+++
@@ -0,0 +1,16 @@
+export class HttpUtils {
+
+ // NOTE: Checks if string matches an IP by pattern.
+ public static isIpAddressValid(ipAddress: string): boolean {
+ let ipValidationRegex: RegExp = new RegExp(/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/);
+ return ipValidationRegex.test(ipAddress);
+ }
+
+ public static shouldPerformMongooseRunRequest(mongooseAddress: string): boolean {
+ // NOTE: Temporarily checking only IP address.
+ let isIpValid: boolean = HttpUtils.isIpAddressValid(mongooseAddress);
+ let isIpPointsToLocalhost: boolean = mongooseAddress.includes("localhost");
+ return ((isIpValid) || (isIpPointsToLocalhost));
+ }
+å
+} |
|
a94a9b899e5e01d5aaba13be92340bac54e501b3 | app/services/tts/tts.service.spec.ts | app/services/tts/tts.service.spec.ts | /// <reference path="./../../../typings/index.d.ts" />
import { inject, async, TestBed, fakeAsync, tick } from '@angular/core/testing';
import { TtsService } from './tts.service';
import { config } from './../../config';
describe('TtsService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [ TtsService ]
});
});
it('should have voice from config file', inject([TtsService], (service) => {
expect(service.options.voice).toEqual(config.voicebox.ttsVoice);
expect(service.voice).toEqual(config.voicebox.ttsVoice);
}));
}); | Add unit test for TtsService | Add unit test for TtsService
| TypeScript | mit | alvinmvbt/mirror-mirror,alvinmvbt/mirror-mirror,alvinmvbt/mirror-mirror | ---
+++
@@ -0,0 +1,17 @@
+/// <reference path="./../../../typings/index.d.ts" />
+import { inject, async, TestBed, fakeAsync, tick } from '@angular/core/testing';
+import { TtsService } from './tts.service';
+import { config } from './../../config';
+
+describe('TtsService', () => {
+ beforeEach(() => {
+ TestBed.configureTestingModule({
+ providers: [ TtsService ]
+ });
+ });
+
+ it('should have voice from config file', inject([TtsService], (service) => {
+ expect(service.options.voice).toEqual(config.voicebox.ttsVoice);
+ expect(service.voice).toEqual(config.voicebox.ttsVoice);
+ }));
+}); |
|
0f01e1b2cb6ba31720de6c4376d5298bc5e472e3 | ng2-components/ng2-alfresco-search/src/forms/search-term-validator.spec.ts | ng2-components/ng2-alfresco-search/src/forms/search-term-validator.spec.ts | /*!
* @license
* Copyright 2016 Alfresco Software, Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { Control } from '@angular/common';
import { SearchTermValidator } from './search-term-validator.ts';
describe('Search term validator', () => {
it('should pass validation for a value with the specified required number of alphanumeric characters', () => {
const control = new Control('ab', SearchTermValidator.minAlphanumericChars(2));
expect(control.valid).toBe(true);
});
it('should pass validation for a value with more than the specified required number of alphanumeric characters', () => {
const control = new Control('abc', SearchTermValidator.minAlphanumericChars(2));
expect(control.valid).toBe(true);
});
it('should fail validation for a value with less than the specified required number of alphanumeric characters', () => {
const control = new Control('a', SearchTermValidator.minAlphanumericChars(2));
expect(control.valid).toBe(true);
});
/* tslint:disable:max-line-length */
it('should fail validation for a value with less than the specified required number of alphanumeric characters but with other non-alphanumeric characters', () => {
const control = new Control('a ._-?b', SearchTermValidator.minAlphanumericChars(3));
expect(control.valid).toBe(true);
});
});
| Add tests for search term field validator | Add tests for search term field validator
Refs #195
| TypeScript | apache-2.0 | Alfresco/alfresco-ng2-components,Alfresco/alfresco-ng2-components,Alfresco/alfresco-ng2-components,Alfresco/alfresco-ng2-components | ---
+++
@@ -0,0 +1,44 @@
+/*!
+ * @license
+ * Copyright 2016 Alfresco Software, Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { Control } from '@angular/common';
+import { SearchTermValidator } from './search-term-validator.ts';
+
+describe('Search term validator', () => {
+
+ it('should pass validation for a value with the specified required number of alphanumeric characters', () => {
+ const control = new Control('ab', SearchTermValidator.minAlphanumericChars(2));
+ expect(control.valid).toBe(true);
+ });
+
+ it('should pass validation for a value with more than the specified required number of alphanumeric characters', () => {
+ const control = new Control('abc', SearchTermValidator.minAlphanumericChars(2));
+ expect(control.valid).toBe(true);
+ });
+
+ it('should fail validation for a value with less than the specified required number of alphanumeric characters', () => {
+ const control = new Control('a', SearchTermValidator.minAlphanumericChars(2));
+ expect(control.valid).toBe(true);
+ });
+
+ /* tslint:disable:max-line-length */
+ it('should fail validation for a value with less than the specified required number of alphanumeric characters but with other non-alphanumeric characters', () => {
+ const control = new Control('a ._-?b', SearchTermValidator.minAlphanumericChars(3));
+ expect(control.valid).toBe(true);
+ });
+
+}); |
|
054ad0b00c4472ec2d4ba4537fd13dc48aa2946f | src/color-regex.ts | src/color-regex.ts | 'use strict';
// const COLOR_REGEX = /(#(?:[\da-f]{3}){1,2}|rgb\((?:\d{1,3},\s*){2}\d{1,3}\)|rgba\((?:\d{1,3},\s*){3}\d*\.?\d+\)|hsl\(\d{1,3}(?:,\s*\d{1,3}%){2}\)|hsla\(\d{1,3}(?:,\s*\d{1,3}%){2},\s*\d*\.?\d+\))/gi
// const HEXA_COLOR = /#(?:[\da-f]{3}($| |,|;)){1}|(?:(#(?:[\da-f]{3}){2})(\t|$| |,|;))/gi
/**
* Utils object for color manipulation
*/
export const HEXA_COLOR = /(#[\da-f]{3}|#[\da-f]{6})($|,| |;|\n)/gi;
export default { HEXA_COLOR };
| Create css hexa color regex | Create css hexa color regex
| TypeScript | apache-2.0 | KamiKillertO/vscode-colorize,KamiKillertO/vscode-colorize | ---
+++
@@ -0,0 +1,12 @@
+'use strict';
+
+// const COLOR_REGEX = /(#(?:[\da-f]{3}){1,2}|rgb\((?:\d{1,3},\s*){2}\d{1,3}\)|rgba\((?:\d{1,3},\s*){3}\d*\.?\d+\)|hsl\(\d{1,3}(?:,\s*\d{1,3}%){2}\)|hsla\(\d{1,3}(?:,\s*\d{1,3}%){2},\s*\d*\.?\d+\))/gi
+// const HEXA_COLOR = /#(?:[\da-f]{3}($| |,|;)){1}|(?:(#(?:[\da-f]{3}){2})(\t|$| |,|;))/gi
+
+
+/**
+ * Utils object for color manipulation
+ */
+export const HEXA_COLOR = /(#[\da-f]{3}|#[\da-f]{6})($|,| |;|\n)/gi;
+
+export default { HEXA_COLOR }; |
|
28c57c3b68803818f62f44f364b803c9f062346e | src/utils/children.ts | src/utils/children.ts | import * as React from 'react';
const childrenToMap = (children: React.ReactNode): Map<string, React.ReactChild> => {
const childrenArray = React.Children.toArray(children);
const childMap: Map<string, React.ReactChild> = new Map();
childrenArray.forEach((child) => {
childMap.set(child.key, child);
});
return childMap;
};
const compareChildren = (children1: Map<string, React.ReactNode>, children2: Map<string, React.ReactNode>): boolean => {
const keys1 = Array.from(children1.keys());
const keys2 = Array.from(children2.keys());
return keys1 === keys2;
};
export {
childrenToMap,
compareChildren,
} | Move helper funcs into file | Move helper funcs into file
| TypeScript | mit | bkazi/react-layout-transition,bkazi/react-layout-transition,bkazi/react-layout-transition | ---
+++
@@ -0,0 +1,22 @@
+import * as React from 'react';
+
+const childrenToMap = (children: React.ReactNode): Map<string, React.ReactChild> => {
+ const childrenArray = React.Children.toArray(children);
+ const childMap: Map<string, React.ReactChild> = new Map();
+ childrenArray.forEach((child) => {
+ childMap.set(child.key, child);
+ });
+ return childMap;
+};
+
+const compareChildren = (children1: Map<string, React.ReactNode>, children2: Map<string, React.ReactNode>): boolean => {
+ const keys1 = Array.from(children1.keys());
+ const keys2 = Array.from(children2.keys());
+
+ return keys1 === keys2;
+};
+
+export {
+ childrenToMap,
+ compareChildren,
+} |
|
acb491ac38698bfa6d9d54bf177c70d05807b871 | app/src/lib/enterprise.ts | app/src/lib/enterprise.ts | /**
* The oldest officially supported version of GitHub Enterprise.
* This information is used in user-facing text and shouldn't be
* considered a hard limit, i.e. older versions of GitHub Enterprise
* might (and probably do) work just fine but this should be a fairly
* recent version that we can safely say that we'll work well with.
*
* I picked the current minimum (2.8) because it was the version
* running on our internal GitHub Enterprise instance at the time
* we implemented Enterprise sign in (desktop/desktop#664)
*/
export const minimumSupportedEnterpriseVersion = '2.8.0'
| Add a shared value for the minimum supported Enterprise version | Add a shared value for the minimum supported Enterprise version
| TypeScript | mit | BugTesterTest/desktops,BugTesterTest/desktops,desktop/desktop,hjobrien/desktop,hjobrien/desktop,kactus-io/kactus,BugTesterTest/desktops,kactus-io/kactus,shiftkey/desktop,kactus-io/kactus,BugTesterTest/desktops,artivilla/desktop,shiftkey/desktop,j-f1/forked-desktop,say25/desktop,desktop/desktop,j-f1/forked-desktop,say25/desktop,j-f1/forked-desktop,say25/desktop,gengjiawen/desktop,artivilla/desktop,desktop/desktop,artivilla/desktop,say25/desktop,artivilla/desktop,j-f1/forked-desktop,shiftkey/desktop,gengjiawen/desktop,gengjiawen/desktop,gengjiawen/desktop,hjobrien/desktop,shiftkey/desktop,desktop/desktop,hjobrien/desktop,kactus-io/kactus | ---
+++
@@ -0,0 +1,12 @@
+/**
+ * The oldest officially supported version of GitHub Enterprise.
+ * This information is used in user-facing text and shouldn't be
+ * considered a hard limit, i.e. older versions of GitHub Enterprise
+ * might (and probably do) work just fine but this should be a fairly
+ * recent version that we can safely say that we'll work well with.
+ *
+ * I picked the current minimum (2.8) because it was the version
+ * running on our internal GitHub Enterprise instance at the time
+ * we implemented Enterprise sign in (desktop/desktop#664)
+ */
+export const minimumSupportedEnterpriseVersion = '2.8.0' |
|
285fb1fce59669b7e734765b1400a856dcf3d931 | applebot-type-node/src/messageHandlers/twitchUptime.ts | applebot-type-node/src/messageHandlers/twitchUptime.ts | import MessageHandler from "../messageHandler";
import ExtendedInfo from "../extendedInfo";
import TwitchExtendedInfo from "../extendedInfos/twitchExtendedInfo";
import MessageFloodgate from "../messageFloodgate";
import fetch from "node-fetch";
import * as fs from "fs";
function readSettings(): Promise<string> {
return new Promise((resolve, reject) => {
fs.readFile("resources/twitchUptime.json", "utf8", (err, data) => {
if (err) {
reject(err);
} else {
resolve(data);
}
})
});
}
class TwitchUptime implements MessageHandler {
private _channel: string;
private constructor(channel: string) {
this._channel = channel;
}
public static async create() {
const data = await readSettings();
const channel = JSON.parse(data).channel;
return new TwitchUptime(channel);
}
private _floodgate = new MessageFloodgate(10);
async handleMessage(responder: (content: string) => Promise<void>, content: string, info: ExtendedInfo | undefined) {
const resp = this._floodgate.createResponder(responder);
if (info == undefined || info.type != "TWITCH")
return;
if (/^!uptime$/.test(content)) {
try {
const request = await fetch(`https://decapi.me/twitch/uptime?channel=${this._channel}`);
const text = await request.text();
if (text.indexOf("offline") == -1) {
await resp(`Live for ${text}.`, false);
} else {
await resp(`Offline. (API updates are sometimes delayed)`, false);
}
} catch {
await resp("Couldn't retrieve uptime info—error in request?", false);
}
}
}
}
export default TwitchUptime; | Fix case on TwitchUptime filename | Fix case on TwitchUptime filename
| TypeScript | mit | Zogzer/Applebot,Zogzer/Applebot,Yen/Applebot | ---
+++
@@ -0,0 +1,59 @@
+import MessageHandler from "../messageHandler";
+import ExtendedInfo from "../extendedInfo";
+import TwitchExtendedInfo from "../extendedInfos/twitchExtendedInfo";
+import MessageFloodgate from "../messageFloodgate";
+import fetch from "node-fetch";
+import * as fs from "fs";
+
+function readSettings(): Promise<string> {
+ return new Promise((resolve, reject) => {
+ fs.readFile("resources/twitchUptime.json", "utf8", (err, data) => {
+ if (err) {
+ reject(err);
+ } else {
+ resolve(data);
+ }
+ })
+ });
+}
+
+class TwitchUptime implements MessageHandler {
+
+ private _channel: string;
+
+ private constructor(channel: string) {
+ this._channel = channel;
+ }
+
+ public static async create() {
+ const data = await readSettings();
+ const channel = JSON.parse(data).channel;
+ return new TwitchUptime(channel);
+ }
+
+ private _floodgate = new MessageFloodgate(10);
+
+ async handleMessage(responder: (content: string) => Promise<void>, content: string, info: ExtendedInfo | undefined) {
+ const resp = this._floodgate.createResponder(responder);
+ if (info == undefined || info.type != "TWITCH")
+ return;
+
+ if (/^!uptime$/.test(content)) {
+ try {
+ const request = await fetch(`https://decapi.me/twitch/uptime?channel=${this._channel}`);
+ const text = await request.text();
+ if (text.indexOf("offline") == -1) {
+ await resp(`Live for ${text}.`, false);
+ } else {
+ await resp(`Offline. (API updates are sometimes delayed)`, false);
+ }
+
+ } catch {
+ await resp("Couldn't retrieve uptime info—error in request?", false);
+ }
+ }
+ }
+
+}
+
+export default TwitchUptime; |
|
08f726e09ffa757fdbd72e3f77c0fbab165f4054 | src/commands/simple/thrust.ts | src/commands/simple/thrust.ts | import { getCurrentBranchName, getRemotes } from '../../lib/git.ts';
import { exec, OutputMode } from '../../dependencies/exec.ts';
import { getBranchRemote } from '../../lib/git/getBranchRemote.ts';
interface Args {
force: boolean,
// Test thingies
isTestRun: boolean,
}
export const command = 'thrust';
export const aliases = [ 't' ];
export const describe = 'Pushes local changes to a remote';
export async function builder (yargs: any) {
return yargs.usage('usage: gut thrust [options]')
.option('force', {
alias: 'f',
describe: 'Force the push. This erases concurrent server-modifications',
type: 'boolean',
});
}
export async function handler ({ force, isTestRun }: Args) {
const remotes = await getRemotes();
const remoteOfTrackedBranch = await getBranchRemote();
const currentBranchName = await getCurrentBranchName();
const remote = remotes[ 0 ]; // TODO: prompt user when there are multiple remotes
const forceArg = force ? '--force-with-lease' : '';
const setUpstreamArg = remoteOfTrackedBranch ? `--set-upstream ${remote}` : '';
const outputMode = isTestRun ? OutputMode.Capture : OutputMode.StdOut;
return exec(`git push ${forceArg} ${setUpstreamArg} ${currentBranchName}`, { output: outputMode });
}
export const test = {};
| import { getCurrentBranchName, getRemotes } from '../../lib/git.ts';
import { exec, OutputMode } from '../../dependencies/exec.ts';
import { getBranchRemote } from '../../lib/git/getBranchRemote.ts';
interface Args {
force: boolean,
// Test thingies
isTestRun: boolean,
}
export const command = 'thrust';
export const aliases = [ 't' ];
export const describe = 'Pushes local changes to a remote';
export async function builder (yargs: any) {
return yargs.usage('usage: gut thrust [options]')
.option('force', {
alias: 'f',
describe: 'Force the push. This erases concurrent server-modifications',
type: 'boolean',
});
}
export async function handler ({ force, isTestRun }: Args) {
const remotes = await getRemotes();
const remoteOfTrackedBranch = await getBranchRemote();
const currentBranchName = await getCurrentBranchName();
const remote = remotes[ 0 ]; // TODO: prompt user when there are multiple remotes
const forceArg = force ? '--force-with-lease' : '';
const setUpstreamArg = remoteOfTrackedBranch ? '' : `--set-upstream ${remote}`;
const outputMode = isTestRun ? OutputMode.Capture : OutputMode.StdOut;
return exec(`git push ${forceArg} ${setUpstreamArg} ${currentBranchName}`, { output: outputMode });
}
export const test = {};
| Fix set upstream conditional inversion | :bug: Fix set upstream conditional inversion
| TypeScript | apache-2.0 | quilicicf/Gut,quilicicf/Gut | ---
+++
@@ -29,7 +29,7 @@
const remote = remotes[ 0 ]; // TODO: prompt user when there are multiple remotes
const forceArg = force ? '--force-with-lease' : '';
- const setUpstreamArg = remoteOfTrackedBranch ? `--set-upstream ${remote}` : '';
+ const setUpstreamArg = remoteOfTrackedBranch ? '' : `--set-upstream ${remote}`;
const outputMode = isTestRun ? OutputMode.Capture : OutputMode.StdOut;
return exec(`git push ${forceArg} ${setUpstreamArg} ${currentBranchName}`, { output: outputMode });
} |
85fc817cc7689b833a71755967b1a11124769cbe | src/migration/types.ts | src/migration/types.ts | /**
* Represent the data structure of a game in v1.0.0
*/
export interface IOldGameData {
/**
* Current round of the game
*/
currentRound: number
/**
* The index of maker of this round. Points to the players array.
*/
maker: number
/**
* Array of players in the game
*/
players: IOldPlayers[]
/**
* Current stage of the game
*/
state: IOldState
/**
* Total number of rounds of the game
*/
totalRounds: number
}
/**
* Represent the data structure of a player in v1.0.0
*/
export interface IOldPlayers {
/**
* Bid for the current round.
*/
bid: number
/**
* Win for the current round.
*/
win: number
/**
* Score of each round.
* Index of the array represent the round number.
* While value is the score this player got on that round.
*/
score: number[]
/**
* Name of this player
*/
name: string
}
/**
* The enum for state property under IOldGameData
*/
export enum IOldState {
/**
* No info is filled in. Game is not yet started.
*/
notStarted = 0,
/**
* bid for stack before each round
*/
bid = 1,
/**
* Wait for user to input win stack
*/
inputWin = 2,
/**
* This round has ended. Showing this round result and wait for next round to start
*/
waiting = 3,
/**
* Game has end by reaching the last round and ended
*/
gameEnd = 4
}
| Add type interface for old data structures | Add type interface for old data structures
| TypeScript | mit | Holi0317/bridge-calc,Holi0317/bridge-calc,Holi0317/bridge-calc | ---
+++
@@ -0,0 +1,75 @@
+/**
+ * Represent the data structure of a game in v1.0.0
+ */
+export interface IOldGameData {
+ /**
+ * Current round of the game
+ */
+ currentRound: number
+ /**
+ * The index of maker of this round. Points to the players array.
+ */
+ maker: number
+ /**
+ * Array of players in the game
+ */
+ players: IOldPlayers[]
+ /**
+ * Current stage of the game
+ */
+ state: IOldState
+ /**
+ * Total number of rounds of the game
+ */
+ totalRounds: number
+}
+
+/**
+ * Represent the data structure of a player in v1.0.0
+ */
+export interface IOldPlayers {
+ /**
+ * Bid for the current round.
+ */
+ bid: number
+ /**
+ * Win for the current round.
+ */
+ win: number
+ /**
+ * Score of each round.
+ * Index of the array represent the round number.
+ * While value is the score this player got on that round.
+ */
+ score: number[]
+ /**
+ * Name of this player
+ */
+ name: string
+}
+
+/**
+ * The enum for state property under IOldGameData
+ */
+export enum IOldState {
+ /**
+ * No info is filled in. Game is not yet started.
+ */
+ notStarted = 0,
+ /**
+ * bid for stack before each round
+ */
+ bid = 1,
+ /**
+ * Wait for user to input win stack
+ */
+ inputWin = 2,
+ /**
+ * This round has ended. Showing this round result and wait for next round to start
+ */
+ waiting = 3,
+ /**
+ * Game has end by reaching the last round and ended
+ */
+ gameEnd = 4
+} |
|
8c02413227a31668f6ea394c8c8ac5526aab332c | src/client/app/components/admin/CreateUserComponent.tsx | src/client/app/components/admin/CreateUserComponent.tsx | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import * as React from 'react';
import HeaderContainer from '../../containers/HeaderContainer';
import FooterComponent from '../../components/FooterComponent';
export default function CreateUserComponent() {
return (
<div>
<HeaderContainer />
<h1> Create User </h1>
<FooterComponent />
</div>
)
} | Add stub component for creating users | Add stub component for creating users
| TypeScript | mpl-2.0 | OpenEnergyDashboard/OED,OpenEnergyDashboard/OED,OpenEnergyDashboard/OED,OpenEnergyDashboard/OED | ---
+++
@@ -0,0 +1,17 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import * as React from 'react';
+import HeaderContainer from '../../containers/HeaderContainer';
+import FooterComponent from '../../components/FooterComponent';
+
+export default function CreateUserComponent() {
+ return (
+ <div>
+ <HeaderContainer />
+ <h1> Create User </h1>
+ <FooterComponent />
+ </div>
+ )
+} |
|
b7d600778f988784dd75bb6a130201d00f4f68b0 | lib/src/components/stretchyFlatList.tsx | lib/src/components/stretchyFlatList.tsx | import React from 'react';
import { View, Animated } from 'react-native';
import { commonStyles as styles } from './styles';
import { StretchyFlatListComponent } from '../types';
import { useStretchy } from '../hooks/useStretchy';
import { StretchyImage } from './stretchyImage';
export const StretchyFlatList: StretchyFlatListComponent = ({
backgroundColor,
children,
foreground,
gradient,
image,
imageHeight,
imageResizeMode,
imageWrapperStyle,
onScroll,
style,
data,
...otherProps
}) => {
const stretchy = useStretchy(image, imageHeight, onScroll);
return (
<View style={[styles.container, { backgroundColor }]}>
<StretchyImage
image={image}
imageResizeMode={imageResizeMode}
imageWrapperStyle={imageWrapperStyle}
gradient={gradient}
animation={stretchy.animation}
imageHeight={stretchy.heightBasedOnRatio}
onImageLoad={stretchy.onImageLoad}
onLayout={stretchy.onImageWrapperLayout}
/>
<Animated.FlatList
{...otherProps}
data={data}
style={[style, styles.contentContainer]}
scrollEventThrottle={1}
ListHeaderComponent={
<View
style={[
styles.foregroundContainer,
{ height: stretchy.heightBasedOnRatio },
]}>
{foreground}
</View>
}
onScroll={stretchy.onScroll}
/>
</View>
);
};
| Add new StretchyFlatList in TS format | Add new StretchyFlatList in TS format
| TypeScript | mit | hamidhadi/react-native-stretchy,hamidhadi/react-native-stretchy,hamidhadi/react-native-stretchy,hamidhadi/react-native-stretchy | ---
+++
@@ -0,0 +1,54 @@
+import React from 'react';
+import { View, Animated } from 'react-native';
+import { commonStyles as styles } from './styles';
+import { StretchyFlatListComponent } from '../types';
+import { useStretchy } from '../hooks/useStretchy';
+import { StretchyImage } from './stretchyImage';
+
+export const StretchyFlatList: StretchyFlatListComponent = ({
+ backgroundColor,
+ children,
+ foreground,
+ gradient,
+ image,
+ imageHeight,
+ imageResizeMode,
+ imageWrapperStyle,
+ onScroll,
+ style,
+ data,
+ ...otherProps
+}) => {
+ const stretchy = useStretchy(image, imageHeight, onScroll);
+
+ return (
+ <View style={[styles.container, { backgroundColor }]}>
+ <StretchyImage
+ image={image}
+ imageResizeMode={imageResizeMode}
+ imageWrapperStyle={imageWrapperStyle}
+ gradient={gradient}
+ animation={stretchy.animation}
+ imageHeight={stretchy.heightBasedOnRatio}
+ onImageLoad={stretchy.onImageLoad}
+ onLayout={stretchy.onImageWrapperLayout}
+ />
+ <Animated.FlatList
+ {...otherProps}
+ data={data}
+ style={[style, styles.contentContainer]}
+ scrollEventThrottle={1}
+ ListHeaderComponent={
+ <View
+ style={[
+ styles.foregroundContainer,
+ { height: stretchy.heightBasedOnRatio },
+ ]}>
+ {foreground}
+ </View>
+ }
+ onScroll={stretchy.onScroll}
+ />
+ </View>
+ );
+}; |
|
cc99b300b0e5742a15a7909e25309e1821130796 | src/common-ui/components/markdown-preview-insert-menu.tsx | src/common-ui/components/markdown-preview-insert-menu.tsx | import React from 'react'
import styled from 'styled-components'
import {
MarkdownPreview,
Props as MarkdownPreviewProps,
} from './markdown-preview'
interface MenuItemProps {
name: string
getTextToInsert: () => string
}
export interface Props extends MarkdownPreviewProps {
menuItems: MenuItemProps[]
updateInputValue: (value: string) => void
}
interface State {
isOpen: boolean
}
export class MarkdownPreviewAnnotationInsertMenu extends React.Component<
Props,
State
> {
markdownPreviewRef = React.createRef<MarkdownPreview>()
state: State = { isOpen: false }
private toggleOpenState = () =>
this.setState((state) => ({ isOpen: !state.isOpen }))
private handleItemClick: (
getTextToInsert: MenuItemProps['getTextToInsert'],
) => React.MouseEventHandler = (getTextToInsert) => (e) => {
const newValue = getTextInsertedAtInputSelection(
getTextToInsert(),
this.markdownPreviewRef.current.mainInputRef.current,
)
this.props.updateInputValue(newValue)
}
private renderInsertMenu = () => (
<MenuContainer>
<MenuBtn onClick={this.toggleOpenState}>Insert</MenuBtn>
{this.state.isOpen && (
<Menu>
{this.props.menuItems.map((props, i) => (
<MenuItem
key={i}
onClick={this.handleItemClick(
props.getTextToInsert,
)}
>
{props.name}
</MenuItem>
))}
</Menu>
)}
</MenuContainer>
)
render() {
return (
<MarkdownPreview
ref={this.markdownPreviewRef}
{...this.props}
renderSecondaryBtn={this.renderInsertMenu}
/>
)
}
}
const MenuContainer = styled.div``
const MenuItem = styled.li``
const MenuBtn = styled.button``
const Menu = styled.ul``
export const annotationMenuItems: MenuItemProps[] = [
{
name: 'YouTube Timestamp',
getTextToInsert() {
const videoEl = document.querySelector<HTMLVideoElement>(
'.video-stream',
)
const timestampSecs = Math.trunc(videoEl?.currentTime ?? 0)
const humanTimestamp = `${Math.floor(timestampSecs / 60)}:${(
timestampSecs % 60
)
.toString()
.padStart(2, '0')}`
// TODO: Derive properly
const videoId = 'TESTID'
return `[${humanTimestamp}](https://youtu.be/${videoId}?t=${timestampSecs})`
},
},
{
name: 'Link',
getTextToInsert() {
return document.location.href
},
},
]
// TODO: Move this somewhere where it can be more useful
export const getTextInsertedAtInputSelection = (
toInsert: string,
{
value,
selectionStart,
selectionEnd,
}: HTMLInputElement | HTMLTextAreaElement,
): string =>
value.substring(0, selectionStart) +
toInsert +
value.substring(selectionEnd, value.length)
| Write MarkdownPreview wrapper with insert menu support | Write MarkdownPreview wrapper with insert menu support
- includes base YT timestamp implementation + link insertion
| TypeScript | mit | WorldBrain/WebMemex,WorldBrain/WebMemex | ---
+++
@@ -0,0 +1,121 @@
+import React from 'react'
+import styled from 'styled-components'
+
+import {
+ MarkdownPreview,
+ Props as MarkdownPreviewProps,
+} from './markdown-preview'
+
+interface MenuItemProps {
+ name: string
+ getTextToInsert: () => string
+}
+
+export interface Props extends MarkdownPreviewProps {
+ menuItems: MenuItemProps[]
+ updateInputValue: (value: string) => void
+}
+
+interface State {
+ isOpen: boolean
+}
+
+export class MarkdownPreviewAnnotationInsertMenu extends React.Component<
+ Props,
+ State
+> {
+ markdownPreviewRef = React.createRef<MarkdownPreview>()
+
+ state: State = { isOpen: false }
+
+ private toggleOpenState = () =>
+ this.setState((state) => ({ isOpen: !state.isOpen }))
+
+ private handleItemClick: (
+ getTextToInsert: MenuItemProps['getTextToInsert'],
+ ) => React.MouseEventHandler = (getTextToInsert) => (e) => {
+ const newValue = getTextInsertedAtInputSelection(
+ getTextToInsert(),
+ this.markdownPreviewRef.current.mainInputRef.current,
+ )
+
+ this.props.updateInputValue(newValue)
+ }
+
+ private renderInsertMenu = () => (
+ <MenuContainer>
+ <MenuBtn onClick={this.toggleOpenState}>Insert</MenuBtn>
+ {this.state.isOpen && (
+ <Menu>
+ {this.props.menuItems.map((props, i) => (
+ <MenuItem
+ key={i}
+ onClick={this.handleItemClick(
+ props.getTextToInsert,
+ )}
+ >
+ {props.name}
+ </MenuItem>
+ ))}
+ </Menu>
+ )}
+ </MenuContainer>
+ )
+
+ render() {
+ return (
+ <MarkdownPreview
+ ref={this.markdownPreviewRef}
+ {...this.props}
+ renderSecondaryBtn={this.renderInsertMenu}
+ />
+ )
+ }
+}
+
+const MenuContainer = styled.div``
+const MenuItem = styled.li``
+const MenuBtn = styled.button``
+const Menu = styled.ul``
+
+export const annotationMenuItems: MenuItemProps[] = [
+ {
+ name: 'YouTube Timestamp',
+ getTextToInsert() {
+ const videoEl = document.querySelector<HTMLVideoElement>(
+ '.video-stream',
+ )
+
+ const timestampSecs = Math.trunc(videoEl?.currentTime ?? 0)
+ const humanTimestamp = `${Math.floor(timestampSecs / 60)}:${(
+ timestampSecs % 60
+ )
+ .toString()
+ .padStart(2, '0')}`
+
+ // TODO: Derive properly
+ const videoId = 'TESTID'
+
+ return `[${humanTimestamp}](https://youtu.be/${videoId}?t=${timestampSecs})`
+ },
+ },
+ {
+ name: 'Link',
+ getTextToInsert() {
+ return document.location.href
+ },
+ },
+]
+
+// TODO: Move this somewhere where it can be more useful
+export const getTextInsertedAtInputSelection = (
+ toInsert: string,
+ {
+ value,
+ selectionStart,
+ selectionEnd,
+ }: HTMLInputElement | HTMLTextAreaElement,
+): string =>
+ value.substring(0, selectionStart) +
+ toInsert +
+ value.substring(selectionEnd, value.length) |
|
47de35b0f37c90df47d9107d64b1614adbe6bafb | src/scripts/exportChartDataNamespace.ts | src/scripts/exportChartDataNamespace.ts | // Script to export the data_values for all variables attached to charts
import * as path from 'path'
import * as db from '../db'
import * as _ from 'lodash'
import * as settings from '../settings'
import { exec } from '../admin/serverUtil'
const namespace = process.argv[2]
if (!namespace) {
const programName = path.basename(process.argv[1])
console.log(`Usage:\n${programName} [namespace]`)
process.exit(1)
}
async function dataExport() {
await db.connect()
const tmpFile = `/tmp/owid_chartdata_${namespace}.sql`
// This will also retrieve variables that are not in the specified namespace
// but are used in a chart that has at least one variable from the specified
// namespace.
// This is necessary in order to reproduce the charts from the live grapher
// accurately.
const rows = await db.query(`
SELECT DISTINCT chart_dimensions.variableId
FROM chart_dimensions
WHERE chart_dimensions.chartId IN (
SELECT DISTINCT charts.id
FROM charts
JOIN chart_dimensions ON chart_dimensions.chartId = charts.id
JOIN variables ON variables.id = chart_dimensions.variableId
JOIN datasets ON datasets.id = variables.datasetId
WHERE datasets.namespace = ?
)
`, [namespace])
const variableIds = rows.map((row: any) => row.variableId)
console.log(`Exporting data for ${variableIds.length} variables to ${tmpFile}`)
await exec(`rm -f ${tmpFile}`)
let count = 0
for (const chunk of _.chunk(variableIds, 100)) {
await exec(`mysqldump --no-create-info ${settings.DB_NAME} data_values --where="variableId IN (${chunk.join(",")})" >> ${tmpFile}`)
count += chunk.length
console.log(count)
}
await db.end()
}
dataExport()
| Create a data export script for a namespace | Create a data export script for a namespace
| TypeScript | mit | OurWorldInData/owid-grapher,OurWorldInData/owid-grapher,OurWorldInData/our-world-in-data-grapher,owid/owid-grapher,OurWorldInData/owid-grapher,owid/owid-grapher,OurWorldInData/owid-grapher,owid/owid-grapher,OurWorldInData/owid-grapher,owid/owid-grapher,owid/owid-grapher,OurWorldInData/our-world-in-data-grapher,OurWorldInData/our-world-in-data-grapher,OurWorldInData/our-world-in-data-grapher | ---
+++
@@ -0,0 +1,58 @@
+// Script to export the data_values for all variables attached to charts
+
+import * as path from 'path'
+import * as db from '../db'
+import * as _ from 'lodash'
+import * as settings from '../settings'
+
+import { exec } from '../admin/serverUtil'
+
+const namespace = process.argv[2]
+
+if (!namespace) {
+ const programName = path.basename(process.argv[1])
+ console.log(`Usage:\n${programName} [namespace]`)
+ process.exit(1)
+}
+
+async function dataExport() {
+ await db.connect()
+
+ const tmpFile = `/tmp/owid_chartdata_${namespace}.sql`
+
+ // This will also retrieve variables that are not in the specified namespace
+ // but are used in a chart that has at least one variable from the specified
+ // namespace.
+ // This is necessary in order to reproduce the charts from the live grapher
+ // accurately.
+ const rows = await db.query(`
+ SELECT DISTINCT chart_dimensions.variableId
+ FROM chart_dimensions
+ WHERE chart_dimensions.chartId IN (
+ SELECT DISTINCT charts.id
+ FROM charts
+ JOIN chart_dimensions ON chart_dimensions.chartId = charts.id
+ JOIN variables ON variables.id = chart_dimensions.variableId
+ JOIN datasets ON datasets.id = variables.datasetId
+ WHERE datasets.namespace = ?
+ )
+ `, [namespace])
+
+ const variableIds = rows.map((row: any) => row.variableId)
+
+ console.log(`Exporting data for ${variableIds.length} variables to ${tmpFile}`)
+
+ await exec(`rm -f ${tmpFile}`)
+
+ let count = 0
+ for (const chunk of _.chunk(variableIds, 100)) {
+ await exec(`mysqldump --no-create-info ${settings.DB_NAME} data_values --where="variableId IN (${chunk.join(",")})" >> ${tmpFile}`)
+
+ count += chunk.length
+ console.log(count)
+ }
+
+ await db.end()
+}
+
+dataExport() |
|
2c814f4413cbc83a88c711823b0aea5125e8d343 | tests/cases/fourslash/jsdocNullableUnion.ts | tests/cases/fourslash/jsdocNullableUnion.ts | ///<reference path="fourslash.ts" />
// @allowNonTsExtensions: true
// @Filename: Foo.js
////
//// * @param {never | {x: string}} p1
//// * @param {undefined | {y: number}} p2
//// * @param {null | {z: boolean}} p3
//// * @returns {void} nothing
//// */
////function f(p1, p2, p3) {
//// p1./*1*/
//// p2./*2*/
//// p3./*3*/
////}
goTo.marker('1');
verify.memberListContains("x");
goTo.marker('2');
verify.memberListContains("y");
goTo.marker('3');
verify.memberListContains("z");
| Add jsdoc nullable union test case to fourslash | Add jsdoc nullable union test case to fourslash
| TypeScript | apache-2.0 | erikmcc/TypeScript,TukekeSoft/TypeScript,RyanCavanaugh/TypeScript,DLehenbauer/TypeScript,Microsoft/TypeScript,nojvek/TypeScript,thr0w/Thr0wScript,SaschaNaz/TypeScript,basarat/TypeScript,donaldpipowitch/TypeScript,weswigham/TypeScript,vilic/TypeScript,vilic/TypeScript,RyanCavanaugh/TypeScript,erikmcc/TypeScript,Eyas/TypeScript,synaptek/TypeScript,Microsoft/TypeScript,vilic/TypeScript,SaschaNaz/TypeScript,Eyas/TypeScript,minestarks/TypeScript,SaschaNaz/TypeScript,thr0w/Thr0wScript,chuckjaz/TypeScript,erikmcc/TypeScript,donaldpipowitch/TypeScript,thr0w/Thr0wScript,mihailik/TypeScript,kpreisser/TypeScript,erikmcc/TypeScript,thr0w/Thr0wScript,kpreisser/TypeScript,Eyas/TypeScript,jwbay/TypeScript,DLehenbauer/TypeScript,chuckjaz/TypeScript,mihailik/TypeScript,RyanCavanaugh/TypeScript,microsoft/TypeScript,kitsonk/TypeScript,donaldpipowitch/TypeScript,synaptek/TypeScript,basarat/TypeScript,chuckjaz/TypeScript,microsoft/TypeScript,DLehenbauer/TypeScript,jeremyepling/TypeScript,TukekeSoft/TypeScript,kitsonk/TypeScript,Eyas/TypeScript,TukekeSoft/TypeScript,jwbay/TypeScript,kpreisser/TypeScript,jwbay/TypeScript,SaschaNaz/TypeScript,nojvek/TypeScript,weswigham/TypeScript,nojvek/TypeScript,jeremyepling/TypeScript,basarat/TypeScript,jeremyepling/TypeScript,basarat/TypeScript,kitsonk/TypeScript,microsoft/TypeScript,minestarks/TypeScript,vilic/TypeScript,mihailik/TypeScript,alexeagle/TypeScript,jwbay/TypeScript,mihailik/TypeScript,chuckjaz/TypeScript,weswigham/TypeScript,alexeagle/TypeScript,synaptek/TypeScript,donaldpipowitch/TypeScript,DLehenbauer/TypeScript,minestarks/TypeScript,alexeagle/TypeScript,synaptek/TypeScript,Microsoft/TypeScript,nojvek/TypeScript | ---
+++
@@ -0,0 +1,23 @@
+///<reference path="fourslash.ts" />
+// @allowNonTsExtensions: true
+// @Filename: Foo.js
+////
+//// * @param {never | {x: string}} p1
+//// * @param {undefined | {y: number}} p2
+//// * @param {null | {z: boolean}} p3
+//// * @returns {void} nothing
+//// */
+////function f(p1, p2, p3) {
+//// p1./*1*/
+//// p2./*2*/
+//// p3./*3*/
+////}
+
+goTo.marker('1');
+verify.memberListContains("x");
+
+goTo.marker('2');
+verify.memberListContains("y");
+
+goTo.marker('3');
+verify.memberListContains("z"); |
|
3478099a853d53ea166e0467c6b19293bf5325b9 | tests/cases/fourslash/incrementalParsingInsertIntoMethod1.ts | tests/cases/fourslash/incrementalParsingInsertIntoMethod1.ts | /// <reference path='fourslash.ts' />
////class C {
//// public foo1() { }
//// public foo2() {
//// return 1/*1*/;
//// }
//// public foo3() { }
////}
debugger;
goTo.marker("1");
edit.insert(" + 1"); | Add incremental parsing LS test. | Add incremental parsing LS test.
| TypeScript | apache-2.0 | tinganho/TypeScript,enginekit/TypeScript,plantain-00/TypeScript,jamesrmccallum/TypeScript,alexeagle/TypeScript,billti/TypeScript,matthewjh/TypeScript,DanielRosenwasser/TypeScript,Viromo/TypeScript,gonifade/TypeScript,webhost/TypeScript,chocolatechipui/TypeScript,msynk/TypeScript,SmallAiTT/TypeScript,nagyistoce/TypeScript,RyanCavanaugh/TypeScript,evgrud/TypeScript,hoanhtien/TypeScript,blakeembrey/TypeScript,hoanhtien/TypeScript,mauricionr/TypeScript,donaldpipowitch/TypeScript,minestarks/TypeScript,Eyas/TypeScript,JohnZ622/TypeScript,SimoneGianni/TypeScript,ZLJASON/TypeScript,basarat/TypeScript,mszczepaniak/TypeScript,evgrud/TypeScript,thr0w/Thr0wScript,enginekit/TypeScript,yazeng/TypeScript,samuelhorwitz/typescript,ropik/TypeScript,JohnZ622/TypeScript,msynk/TypeScript,nagyistoce/TypeScript,shovon/TypeScript,Eyas/TypeScript,thr0w/Thr0wScript,jwbay/TypeScript,sassson/TypeScript,Raynos/TypeScript,Mqgh2013/TypeScript,bpowers/TypeScript,mauricionr/TypeScript,plantain-00/TypeScript,yortus/TypeScript,nycdotnet/TypeScript,chuckjaz/TypeScript,OlegDokuka/TypeScript,yukulele/TypeScript,mihailik/TypeScript,sassson/TypeScript,tinganho/TypeScript,gonifade/TypeScript,plantain-00/TypeScript,impinball/TypeScript,weswigham/TypeScript,fearthecowboy/TypeScript,DLehenbauer/TypeScript,suto/TypeScript,mcanthony/TypeScript,synaptek/TypeScript,mmoskal/TypeScript,fdecampredon/jsx-typescript,kimamula/TypeScript,tempbottle/TypeScript,zmaruo/TypeScript,fdecampredon/jsx-typescript,kingland/TypeScript,kimamula/TypeScript,jeremyepling/TypeScript,kumikumi/TypeScript,jteplitz602/TypeScript,JohnZ622/TypeScript,billti/TypeScript,fearthecowboy/TypeScript,abbasmhd/TypeScript,chuckjaz/TypeScript,zhengbli/TypeScript,hitesh97/TypeScript,Mqgh2013/TypeScript,RyanCavanaugh/TypeScript,blakeembrey/TypeScript,shiftkey/TypeScript,rodrigues-daniel/TypeScript,nagyistoce/TypeScript,Eyas/TypeScript,yukulele/TypeScript,kumikumi/TypeScript,rodrigues-daniel/TypeScript,jbondc/TypeScript,nycdotnet/TypeScript,jwbay/TypeScript,progre/TypeScript,HereSinceres/TypeScript,alexeagle/TypeScript,ropik/TypeScript,mauricionr/TypeScript,jdavidberger/TypeScript,jamesrmccallum/TypeScript,tempbottle/TypeScript,fdecampredon/jsx-typescript,shanexu/TypeScript,zmaruo/TypeScript,germ13/TypeScript,zmaruo/TypeScript,jamesrmccallum/TypeScript,zhengbli/TypeScript,kpreisser/TypeScript,mcanthony/TypeScript,webhost/TypeScript,mszczepaniak/TypeScript,gonifade/TypeScript,mmoskal/TypeScript,shanexu/TypeScript,shanexu/TypeScript,ziacik/TypeScript,fabioparra/TypeScript,blakeembrey/TypeScript,moander/TypeScript,matthewjh/TypeScript,ropik/TypeScript,synaptek/TypeScript,fdecampredon/jsx-typescript,rgbkrk/TypeScript,jbondc/TypeScript,OlegDokuka/TypeScript,Mqgh2013/TypeScript,mmoskal/TypeScript,minestarks/TypeScript,ziacik/TypeScript,shiftkey/TypeScript,progre/TypeScript,ziacik/TypeScript,SmallAiTT/TypeScript,gdi2290/TypeScript,shanexu/TypeScript,kingland/TypeScript,abbasmhd/TypeScript,ionux/TypeScript,nycdotnet/TypeScript,impinball/TypeScript,Raynos/TypeScript,samuelhorwitz/typescript,mszczepaniak/TypeScript,jteplitz602/TypeScript,fabioparra/TypeScript,HereSinceres/TypeScript,Viromo/TypeScript,moander/TypeScript,SaschaNaz/TypeScript,ziacik/TypeScript,rgbkrk/TypeScript,yortus/TypeScript,AbubakerB/TypeScript,TukekeSoft/TypeScript,keir-rex/TypeScript,jdavidberger/TypeScript,ionux/TypeScript,kingland/TypeScript,jbondc/TypeScript,nojvek/TypeScript,billti/TypeScript,ZLJASON/TypeScript,tempbottle/TypeScript,donaldpipowitch/TypeScript,progre/TypeScript,weswigham/TypeScript,DLehenbauer/TypeScript,nojvek/TypeScript,microsoft/TypeScript,jeremyepling/TypeScript,hitesh97/TypeScript,RReverser/TypeScript,yortus/TypeScript,yazeng/TypeScript,kpreisser/TypeScript,HereSinceres/TypeScript,OlegDokuka/TypeScript,kimamula/TypeScript,keir-rex/TypeScript,AbubakerB/TypeScript,RyanCavanaugh/TypeScript,yukulele/TypeScript,MartyIX/TypeScript,chuckjaz/TypeScript,samuelhorwitz/typescript,abbasmhd/TypeScript,Microsoft/TypeScript,bpowers/TypeScript,microsoft/TypeScript,ionux/TypeScript,alexeagle/TypeScript,ionux/TypeScript,germ13/TypeScript,AbubakerB/TypeScript,kpreisser/TypeScript,evgrud/TypeScript,rodrigues-daniel/TypeScript,hoanhtien/TypeScript,moander/TypeScript,Raynos/TypeScript,rgbkrk/TypeScript,mihailik/TypeScript,yazeng/TypeScript,vilic/TypeScript,webhost/TypeScript,minestarks/TypeScript,SimoneGianni/TypeScript,erikmcc/TypeScript,ropik/TypeScript,SaschaNaz/TypeScript,DLehenbauer/TypeScript,DanielRosenwasser/TypeScript,jdavidberger/TypeScript,SmallAiTT/TypeScript,Viromo/TypeScript,fabioparra/TypeScript,mihailik/TypeScript,weswigham/TypeScript,thr0w/Thr0wScript,bpowers/TypeScript,shiftkey/TypeScript,vilic/TypeScript,fearthecowboy/TypeScript,nojvek/TypeScript,jeremyepling/TypeScript,chuckjaz/TypeScript,RReverser/TypeScript,DanielRosenwasser/TypeScript,synaptek/TypeScript,evgrud/TypeScript,AbubakerB/TypeScript,suto/TypeScript,rodrigues-daniel/TypeScript,synaptek/TypeScript,MartyIX/TypeScript,mcanthony/TypeScript,matthewjh/TypeScript,pcan/TypeScript,kimamula/TypeScript,chocolatechipui/TypeScript,jteplitz602/TypeScript,shovon/TypeScript,mmoskal/TypeScript,jwbay/TypeScript,DanielRosenwasser/TypeScript,kitsonk/TypeScript,pcan/TypeScript,Microsoft/TypeScript,impinball/TypeScript,TukekeSoft/TypeScript,blakeembrey/TypeScript,kumikumi/TypeScript,Raynos/TypeScript,samuelhorwitz/typescript,pcan/TypeScript,JohnZ622/TypeScript,basarat/TypeScript,erikmcc/TypeScript,thr0w/Thr0wScript,donaldpipowitch/TypeScript,vilic/TypeScript,nojvek/TypeScript,yortus/TypeScript,MartyIX/TypeScript,Microsoft/TypeScript,hitesh97/TypeScript,msynk/TypeScript,TukekeSoft/TypeScript,SaschaNaz/TypeScript,SaschaNaz/TypeScript,chocolatechipui/TypeScript,ZLJASON/TypeScript,basarat/TypeScript,basarat/TypeScript,donaldpipowitch/TypeScript,jwbay/TypeScript,mauricionr/TypeScript,mihailik/TypeScript,plantain-00/TypeScript,DLehenbauer/TypeScript,erikmcc/TypeScript,Eyas/TypeScript,fabioparra/TypeScript,mcanthony/TypeScript,sassson/TypeScript,tinganho/TypeScript,SimoneGianni/TypeScript,MartyIX/TypeScript,suto/TypeScript,moander/TypeScript,Viromo/TypeScript,zhengbli/TypeScript,nycdotnet/TypeScript,kitsonk/TypeScript,RReverser/TypeScript,shovon/TypeScript,enginekit/TypeScript,vilic/TypeScript,microsoft/TypeScript,erikmcc/TypeScript,keir-rex/TypeScript,germ13/TypeScript,kitsonk/TypeScript | ---
+++
@@ -0,0 +1,13 @@
+/// <reference path='fourslash.ts' />
+
+////class C {
+//// public foo1() { }
+//// public foo2() {
+//// return 1/*1*/;
+//// }
+//// public foo3() { }
+////}
+
+debugger;
+goTo.marker("1");
+edit.insert(" + 1"); |
|
ad6847c0adbf438c7342ff0a8a08ab8c77110b7c | app/src/ui/history/drag-and-drop-intro.ts | app/src/ui/history/drag-and-drop-intro.ts | /** Type of the drag and drop intro popover. Each value represents a feature. */
export enum DragAndDropIntroType {
CherryPick = 'cherry-pick',
Squash = 'squash',
Reorder = 'reorder',
}
/** Structure to describe the drag and drop intro popover. */
export type DragAndDropIntro = {
readonly title: string
readonly body: string
}
/** List of all available drag and drop intro types. */
export const AvailableDragAndDropIntroKeys = Object.values(
DragAndDropIntroType
) as ReadonlyArray<DragAndDropIntroType>
/** Map with all available drag and drop intros. */
export const AvailableDragAndDropIntros: Record<
DragAndDropIntroType,
DragAndDropIntro
> = {
[DragAndDropIntroType.CherryPick]: {
title: 'Cherry-pick!',
body:
'Copy commits to another branch by dragging and dropping them onto a branch in the branch menu, or by right clicking on a commit.',
},
[DragAndDropIntroType.Squash]: {
title: 'Squash!',
body:
'Squash commits by dragging and dropping them onto another commit, or by right clicking on multiple commits.',
},
[DragAndDropIntroType.Reorder]: {
title: 'Reorder!',
body:
'Reorder commits to tidy up your history by dragging and dropping them to a different position.',
},
}
| Create new types for drag&drop intros | Create new types for drag&drop intros
| TypeScript | mit | shiftkey/desktop,j-f1/forked-desktop,j-f1/forked-desktop,j-f1/forked-desktop,say25/desktop,artivilla/desktop,artivilla/desktop,desktop/desktop,say25/desktop,shiftkey/desktop,say25/desktop,artivilla/desktop,say25/desktop,artivilla/desktop,j-f1/forked-desktop,desktop/desktop,desktop/desktop,desktop/desktop,shiftkey/desktop,shiftkey/desktop | ---
+++
@@ -0,0 +1,39 @@
+/** Type of the drag and drop intro popover. Each value represents a feature. */
+export enum DragAndDropIntroType {
+ CherryPick = 'cherry-pick',
+ Squash = 'squash',
+ Reorder = 'reorder',
+}
+
+/** Structure to describe the drag and drop intro popover. */
+export type DragAndDropIntro = {
+ readonly title: string
+ readonly body: string
+}
+
+/** List of all available drag and drop intro types. */
+export const AvailableDragAndDropIntroKeys = Object.values(
+ DragAndDropIntroType
+) as ReadonlyArray<DragAndDropIntroType>
+
+/** Map with all available drag and drop intros. */
+export const AvailableDragAndDropIntros: Record<
+ DragAndDropIntroType,
+ DragAndDropIntro
+> = {
+ [DragAndDropIntroType.CherryPick]: {
+ title: 'Cherry-pick!',
+ body:
+ 'Copy commits to another branch by dragging and dropping them onto a branch in the branch menu, or by right clicking on a commit.',
+ },
+ [DragAndDropIntroType.Squash]: {
+ title: 'Squash!',
+ body:
+ 'Squash commits by dragging and dropping them onto another commit, or by right clicking on multiple commits.',
+ },
+ [DragAndDropIntroType.Reorder]: {
+ title: 'Reorder!',
+ body:
+ 'Reorder commits to tidy up your history by dragging and dropping them to a different position.',
+ },
+} |
|
ff1877a9406f74ece24810a1c42e989847adc8b3 | platforms/platform-alexa/src/cli/smapi/SkillPackageManagement.ts | platforms/platform-alexa/src/cli/smapi/SkillPackageManagement.ts | import { execAsync } from '@jovotech/cli-core';
import { UnknownObject } from '@jovotech/framework';
import { getAskError } from '../utilities';
export async function createNewUploadUrl(): Promise<string> {
try {
const { stdout } = await execAsync('ask smapi create-upload-url');
const uploadUrl: string = JSON.parse(stdout!);
return uploadUrl;
} catch (error) {
throw getAskError('smapiCreateUploadUrl', error.stderr);
}
}
export async function createSkillPackage(location: string, askProfile?: string): Promise<string> {
try {
const cmd: string[] = [
'ask smapi create-skill-package',
'--full-response',
`--location ${location}`,
];
if (askProfile) {
cmd.push(`-p ${askProfile}`);
}
const { stdout } = await execAsync(cmd.join(' '));
return parseImportUrl(JSON.parse(stdout!));
} catch (error) {
throw getAskError('smapiCreateSkillPackage', error.stderr);
}
}
export async function importSkillPackage(
location: string,
skillId: string,
askProfile?: string,
): Promise<string> {
try {
const cmd: string[] = [
'ask smapi import-skill-package',
'--full-response',
`--location ${location}`,
`-s ${skillId}`,
];
if (askProfile) {
cmd.push(`-p ${askProfile}`);
}
const { stdout } = await execAsync(cmd.join(' '));
return parseImportUrl(JSON.parse(stdout!));
} catch (error) {
throw getAskError('smapiImportSkillPackage', error.stderr);
}
}
function parseImportUrl({ headers }: UnknownObject): string {
// Try to parse the import url from command result
// TODO: Test & Typings
return (
// @ts-ignore
headers
// @ts-ignore
.find((header) => header.key === 'location')
.value.split('/')
.pop()
);
}
| Implement SMAPI Skill Package Management functions | :sparkles: Implement SMAPI Skill Package Management functions
| TypeScript | apache-2.0 | jovotech/jovo-framework-nodejs,jovotech/jovo-framework-nodejs | ---
+++
@@ -0,0 +1,69 @@
+import { execAsync } from '@jovotech/cli-core';
+import { UnknownObject } from '@jovotech/framework';
+import { getAskError } from '../utilities';
+
+export async function createNewUploadUrl(): Promise<string> {
+ try {
+ const { stdout } = await execAsync('ask smapi create-upload-url');
+ const uploadUrl: string = JSON.parse(stdout!);
+ return uploadUrl;
+ } catch (error) {
+ throw getAskError('smapiCreateUploadUrl', error.stderr);
+ }
+}
+
+export async function createSkillPackage(location: string, askProfile?: string): Promise<string> {
+ try {
+ const cmd: string[] = [
+ 'ask smapi create-skill-package',
+ '--full-response',
+ `--location ${location}`,
+ ];
+
+ if (askProfile) {
+ cmd.push(`-p ${askProfile}`);
+ }
+
+ const { stdout } = await execAsync(cmd.join(' '));
+ return parseImportUrl(JSON.parse(stdout!));
+ } catch (error) {
+ throw getAskError('smapiCreateSkillPackage', error.stderr);
+ }
+}
+
+export async function importSkillPackage(
+ location: string,
+ skillId: string,
+ askProfile?: string,
+): Promise<string> {
+ try {
+ const cmd: string[] = [
+ 'ask smapi import-skill-package',
+ '--full-response',
+ `--location ${location}`,
+ `-s ${skillId}`,
+ ];
+
+ if (askProfile) {
+ cmd.push(`-p ${askProfile}`);
+ }
+
+ const { stdout } = await execAsync(cmd.join(' '));
+ return parseImportUrl(JSON.parse(stdout!));
+ } catch (error) {
+ throw getAskError('smapiImportSkillPackage', error.stderr);
+ }
+}
+
+function parseImportUrl({ headers }: UnknownObject): string {
+ // Try to parse the import url from command result
+ // TODO: Test & Typings
+ return (
+ // @ts-ignore
+ headers
+ // @ts-ignore
+ .find((header) => header.key === 'location')
+ .value.split('/')
+ .pop()
+ );
+} |
|
28617b23fb93f3542fa8fc1208638c957403e876 | extraterm/src/render_process/settings/frames/FrameRuleConfigUi.ts | extraterm/src/render_process/settings/frames/FrameRuleConfigUi.ts | /*
* Copyright 2019 Simon Edwards <[email protected]>
*
* This source code is licensed under the MIT license which is detailed in the LICENSE.txt file.
*/
import Component from 'vue-class-component';
import Vue from 'vue';
import { FrameRule } from '../../../Config';
import { trimBetweenTags } from 'extraterm-trim-between-tags';
@Component(
{
props: {
frameRule: String,
frameRuleLines: Number
},
template: trimBetweenTags(`
<div class="gui-packed-row width-100pc">
<select @change="onFrameRuleChange" class="char-width-20">
<option v-for="option in frameRuleOptions" v-bind:value="option.id" v-bind:selected="option.id == frameRule">
{{ option.name }}
</option>
</select>
<input
class="char-width-4"
min="1"
max="9999"
v-if="frameRule == 'frame_if_lines'"
type="number"
v-bind:value="frameRuleLines"
@change="onFrameRuleLinesChange"
/>
<div v-if="frameRule == 'frame_if_lines'"> lines</div>
</div>`)
}
)
export class FrameRuleConfigUi extends Vue {
// Props
frameRule: FrameRule;
frameRuleLines: number;
onFrameRuleChange(event: Event): void {
this.$emit("update:frame-rule", (<HTMLSelectElement> event.target).value);
}
get frameRuleOptions(): {id: string, name: string}[] {
return [
{ id: "always_frame", name: "Always frame command output" },
{ id: "never_frame", name: "Never frame command output" },
{ id: "frame_if_lines", name: "Frame command output if longer than" },
];
}
onFrameRuleLinesChange(event: Event): void {
this.$emit("update:frame-rule-lines", (<HTMLInputElement> event.target).value);
}
}
| Add part of the frame config UI | Add part of the frame config UI
| TypeScript | mit | sedwards2009/extraterm,sedwards2009/extraterm,sedwards2009/extraterm,sedwards2009/extraterm,sedwards2009/extraterm | ---
+++
@@ -0,0 +1,60 @@
+/*
+ * Copyright 2019 Simon Edwards <[email protected]>
+ *
+ * This source code is licensed under the MIT license which is detailed in the LICENSE.txt file.
+ */
+import Component from 'vue-class-component';
+import Vue from 'vue';
+
+import { FrameRule } from '../../../Config';
+import { trimBetweenTags } from 'extraterm-trim-between-tags';
+
+
+@Component(
+ {
+ props: {
+ frameRule: String,
+ frameRuleLines: Number
+ },
+ template: trimBetweenTags(`
+ <div class="gui-packed-row width-100pc">
+ <select @change="onFrameRuleChange" class="char-width-20">
+ <option v-for="option in frameRuleOptions" v-bind:value="option.id" v-bind:selected="option.id == frameRule">
+ {{ option.name }}
+ </option>
+ </select>
+
+ <input
+ class="char-width-4"
+ min="1"
+ max="9999"
+ v-if="frameRule == 'frame_if_lines'"
+ type="number"
+ v-bind:value="frameRuleLines"
+ @change="onFrameRuleLinesChange"
+ />
+ <div v-if="frameRule == 'frame_if_lines'"> lines</div>
+ </div>`)
+ }
+)
+export class FrameRuleConfigUi extends Vue {
+ // Props
+ frameRule: FrameRule;
+ frameRuleLines: number;
+
+ onFrameRuleChange(event: Event): void {
+ this.$emit("update:frame-rule", (<HTMLSelectElement> event.target).value);
+ }
+
+ get frameRuleOptions(): {id: string, name: string}[] {
+ return [
+ { id: "always_frame", name: "Always frame command output" },
+ { id: "never_frame", name: "Never frame command output" },
+ { id: "frame_if_lines", name: "Frame command output if longer than" },
+ ];
+ }
+
+ onFrameRuleLinesChange(event: Event): void {
+ this.$emit("update:frame-rule-lines", (<HTMLInputElement> event.target).value);
+ }
+} |
|
11843a76f28167f56c3ae08102c492bc1d60a98c | types/is-empty/is-empty-tests.ts | types/is-empty/is-empty-tests.ts | import isEmpty from 'is-empty';
isEmpty({});
isEmpty(null);
isEmpty(undefined);
isEmpty(9);
isEmpty(new Object());
isEmpty(Array);
isEmpty('');
isEmpty(() => {});
| import isEmpty = require('is-empty');
isEmpty({});
isEmpty(null);
isEmpty(undefined);
isEmpty(9);
isEmpty(new Object());
isEmpty(Array);
isEmpty('');
isEmpty(() => {});
| Change test to require isEmpty dependency | Change test to require isEmpty dependency | TypeScript | mit | dsebastien/DefinitelyTyped,rolandzwaga/DefinitelyTyped,mcliment/DefinitelyTyped,georgemarshall/DefinitelyTyped,magny/DefinitelyTyped,borisyankov/DefinitelyTyped,markogresak/DefinitelyTyped,AgentME/DefinitelyTyped,dsebastien/DefinitelyTyped,borisyankov/DefinitelyTyped,AgentME/DefinitelyTyped,AgentME/DefinitelyTyped,one-pieces/DefinitelyTyped,rolandzwaga/DefinitelyTyped,georgemarshall/DefinitelyTyped,AgentME/DefinitelyTyped,georgemarshall/DefinitelyTyped,georgemarshall/DefinitelyTyped,magny/DefinitelyTyped | ---
+++
@@ -1,4 +1,4 @@
-import isEmpty from 'is-empty';
+import isEmpty = require('is-empty');
isEmpty({});
isEmpty(null); |
f759603a2b869aa7faf1559b11f10ae3355b838f | src/Test/Ast/EdgeCases/InlineOverlapping.ts | src/Test/Ast/EdgeCases/InlineOverlapping.ts | /// <reference path="../../../../typings/mocha/mocha.d.ts" />
/// <reference path="../../../../typings/chai/chai.d.ts" />
import { expect } from 'chai'
import * as Up from '../../../index'
import { insideDocumentAndParagraph } from '../Helpers'
import { SyntaxNode } from '../../../SyntaxNodes/SyntaxNode'
import { LinkNode } from '../../../SyntaxNodes/LinkNode'
import { DocumentNode } from '../../../SyntaxNodes/DocumentNode'
import { PlainTextNode } from '../../../SyntaxNodes/PlainTextNode'
import { EmphasisNode } from '../../../SyntaxNodes/EmphasisNode'
import { StressNode } from '../../../SyntaxNodes/StressNode'
import { InlineCodeNode } from '../../../SyntaxNodes/InlineCodeNode'
import { RevisionInsertionNode } from '../../../SyntaxNodes/RevisionInsertionNode'
import { RevisionDeletionNode } from '../../../SyntaxNodes/RevisionDeletionNode'
import { SpoilerNode } from '../../../SyntaxNodes/SpoilerNode'
import { InlineAsideNode } from '../../../SyntaxNodes/InlineAsideNode'
import { ParagraphNode } from '../../../SyntaxNodes/ParagraphNode'
import { SectionSeparatorNode } from '../../../SyntaxNodes/SectionSeparatorNode'
describe('Overlapped stressed and deleted text', () => {
it('produces a stress node, a nested revision deletion node, then a non-nested revision deletion node', () => {
expect(Up.ast('I **love ~~drinking** whole~~ milk.')).to.be.eql(
insideDocumentAndParagraph([
new PlainTextNode('I '),
new StressNode([
new PlainTextNode('love '),
new RevisionDeletionNode([
new PlainTextNode('drinking')
])
]),
new RevisionDeletionNode([
new PlainTextNode(' whole')
]),
new PlainTextNode(' milk.')
]))
})
}) | Add failing inline overlapping test | Add failing inline overlapping test
| TypeScript | mit | start/up,start/up | ---
+++
@@ -0,0 +1,39 @@
+/// <reference path="../../../../typings/mocha/mocha.d.ts" />
+/// <reference path="../../../../typings/chai/chai.d.ts" />
+
+import { expect } from 'chai'
+import * as Up from '../../../index'
+import { insideDocumentAndParagraph } from '../Helpers'
+import { SyntaxNode } from '../../../SyntaxNodes/SyntaxNode'
+import { LinkNode } from '../../../SyntaxNodes/LinkNode'
+import { DocumentNode } from '../../../SyntaxNodes/DocumentNode'
+import { PlainTextNode } from '../../../SyntaxNodes/PlainTextNode'
+import { EmphasisNode } from '../../../SyntaxNodes/EmphasisNode'
+import { StressNode } from '../../../SyntaxNodes/StressNode'
+import { InlineCodeNode } from '../../../SyntaxNodes/InlineCodeNode'
+import { RevisionInsertionNode } from '../../../SyntaxNodes/RevisionInsertionNode'
+import { RevisionDeletionNode } from '../../../SyntaxNodes/RevisionDeletionNode'
+import { SpoilerNode } from '../../../SyntaxNodes/SpoilerNode'
+import { InlineAsideNode } from '../../../SyntaxNodes/InlineAsideNode'
+import { ParagraphNode } from '../../../SyntaxNodes/ParagraphNode'
+import { SectionSeparatorNode } from '../../../SyntaxNodes/SectionSeparatorNode'
+
+
+describe('Overlapped stressed and deleted text', () => {
+ it('produces a stress node, a nested revision deletion node, then a non-nested revision deletion node', () => {
+ expect(Up.ast('I **love ~~drinking** whole~~ milk.')).to.be.eql(
+ insideDocumentAndParagraph([
+ new PlainTextNode('I '),
+ new StressNode([
+ new PlainTextNode('love '),
+ new RevisionDeletionNode([
+ new PlainTextNode('drinking')
+ ])
+ ]),
+ new RevisionDeletionNode([
+ new PlainTextNode(' whole')
+ ]),
+ new PlainTextNode(' milk.')
+ ]))
+ })
+}) |
|
96a1146cdab67999add011ce79611b8544a9dcb2 | sandboxed-module/sandboxed-module-tests.ts | sandboxed-module/sandboxed-module-tests.ts | // Type definitions for sandboxed-module v2.0.3
// Project: https://github.com/felixge/node-sandboxed-module
// Definitions by: Sven Reglitzki <https://github.com/svi3c/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="sandboxed-module.d.ts" />
import SandboxedModule = require("sandboxed-module");
var sandboxedModule:SandboxedModule = SandboxedModule.load("foo");
var sandboxedModuleExports:any = SandboxedModule.require("foo");
var sandboxedModuleExportsWithOptions:any = SandboxedModule.require("foo", {
requires: {
someDep: {}
},
globals: {
theAnswer: 42
},
locals: {
someLocal: 1
},
sourceTransformers: {
identity: (src:string) => src
},
singleOnly: true,
sourceTransformersSingleOnly: true
});
| Add some tests to sandboxed-module | Add some tests to sandboxed-module
| TypeScript | mit | HPFOD/DefinitelyTyped,sclausen/DefinitelyTyped,markogresak/DefinitelyTyped,RX14/DefinitelyTyped,Dashlane/DefinitelyTyped,mcliment/DefinitelyTyped,isman-usoh/DefinitelyTyped,nakakura/DefinitelyTyped,raijinsetsu/DefinitelyTyped,Zzzen/DefinitelyTyped,stephenjelfs/DefinitelyTyped,flyfishMT/DefinitelyTyped,ryan10132/DefinitelyTyped,CodeZombieCH/DefinitelyTyped,Softpagehomeware/DefinitelyTyped,mcrawshaw/DefinitelyTyped,tan9/DefinitelyTyped,AyaMorisawa/DefinitelyTyped,Softpagehomeware/DefinitelyTyped,behzad888/DefinitelyTyped,applesaucers/lodash-invokeMap,frogcjn/DefinitelyTyped,reppners/DefinitelyTyped,trystanclarke/DefinitelyTyped,jraymakers/DefinitelyTyped,axelcostaspena/DefinitelyTyped,stacktracejs/DefinitelyTyped,damianog/DefinitelyTyped,gandjustas/DefinitelyTyped,subash-a/DefinitelyTyped,wilfrem/DefinitelyTyped,one-pieces/DefinitelyTyped,amanmahajan7/DefinitelyTyped,pwelter34/DefinitelyTyped,ajtowf/DefinitelyTyped,MugeSo/DefinitelyTyped,benishouga/DefinitelyTyped,johan-gorter/DefinitelyTyped,sledorze/DefinitelyTyped,sledorze/DefinitelyTyped,scriby/DefinitelyTyped,psnider/DefinitelyTyped,musicist288/DefinitelyTyped,smrq/DefinitelyTyped,micurs/DefinitelyTyped,pocesar/DefinitelyTyped,nainslie/DefinitelyTyped,gyohk/DefinitelyTyped,chrismbarr/DefinitelyTyped,stephenjelfs/DefinitelyTyped,arusakov/DefinitelyTyped,mattblang/DefinitelyTyped,mareek/DefinitelyTyped,aciccarello/DefinitelyTyped,GiedriusGrabauskas/DefinitelyTyped,alexdresko/DefinitelyTyped,rschmukler/DefinitelyTyped,mattblang/DefinitelyTyped,Dashlane/DefinitelyTyped,zuzusik/DefinitelyTyped,Ptival/DefinitelyTyped,reppners/DefinitelyTyped,abner/DefinitelyTyped,ashwinr/DefinitelyTyped,benishouga/DefinitelyTyped,hellopao/DefinitelyTyped,psnider/DefinitelyTyped,OpenMaths/DefinitelyTyped,esperco/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,Zorgatone/DefinitelyTyped,nycdotnet/DefinitelyTyped,nfriend/DefinitelyTyped,aciccarello/DefinitelyTyped,mhegazy/DefinitelyTyped,nakakura/DefinitelyTyped,jasonswearingen/DefinitelyTyped,trystanclarke/DefinitelyTyped,subash-a/DefinitelyTyped,YousefED/DefinitelyTyped,AgentME/DefinitelyTyped,minodisk/DefinitelyTyped,Penryn/DefinitelyTyped,gandjustas/DefinitelyTyped,nitintutlani/DefinitelyTyped,DzmitryDulko/DefinitelyTyped,Zorgatone/DefinitelyTyped,Ptival/DefinitelyTyped,alexdresko/DefinitelyTyped,schmuli/DefinitelyTyped,shlomiassaf/DefinitelyTyped,ashwinr/DefinitelyTyped,borisyankov/DefinitelyTyped,progre/DefinitelyTyped,xStrom/DefinitelyTyped,vagarenko/DefinitelyTyped,jimthedev/DefinitelyTyped,chbrown/DefinitelyTyped,paulmorphy/DefinitelyTyped,nycdotnet/DefinitelyTyped,emanuelhp/DefinitelyTyped,vagarenko/DefinitelyTyped,martinduparc/DefinitelyTyped,greglo/DefinitelyTyped,nobuoka/DefinitelyTyped,jasonswearingen/DefinitelyTyped,pocesar/DefinitelyTyped,schmuli/DefinitelyTyped,ryan-codingintrigue/DefinitelyTyped,hellopao/DefinitelyTyped,hellopao/DefinitelyTyped,arusakov/DefinitelyTyped,newclear/DefinitelyTyped,isman-usoh/DefinitelyTyped,gcastre/DefinitelyTyped,Karabur/DefinitelyTyped,georgemarshall/DefinitelyTyped,slavomirvojacek/adbrain-typescript-definitions,sclausen/DefinitelyTyped,Pro/DefinitelyTyped,QuatroCode/DefinitelyTyped,georgemarshall/DefinitelyTyped,dsebastien/DefinitelyTyped,mcrawshaw/DefinitelyTyped,nainslie/DefinitelyTyped,gyohk/DefinitelyTyped,ajtowf/DefinitelyTyped,rcchen/DefinitelyTyped,emanuelhp/DefinitelyTyped,damianog/DefinitelyTyped,donnut/DefinitelyTyped,optical/DefinitelyTyped,benishouga/DefinitelyTyped,slavomirvojacek/DefinitelyTyped,gcastre/DefinitelyTyped,arma-gast/DefinitelyTyped,benliddicott/DefinitelyTyped,sergey-buturlakin/DefinitelyTyped,slavomirvojacek/adbrain-typescript-definitions,HPFOD/DefinitelyTyped,YousefED/DefinitelyTyped,progre/DefinitelyTyped,Karabur/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,OpenMaths/DefinitelyTyped,syuilo/DefinitelyTyped,abbasmhd/DefinitelyTyped,daptiv/DefinitelyTyped,DzmitryDulko/DefinitelyTyped,shlomiassaf/DefinitelyTyped,MugeSo/DefinitelyTyped,chrootsu/DefinitelyTyped,bennett000/DefinitelyTyped,jraymakers/DefinitelyTyped,GlennQuirynen/DefinitelyTyped,alvarorahul/DefinitelyTyped,mareek/DefinitelyTyped,chrismbarr/DefinitelyTyped,minodisk/DefinitelyTyped,amanmahajan7/DefinitelyTyped,alextkachman/DefinitelyTyped,teves-castro/DefinitelyTyped,alvarorahul/DefinitelyTyped,glenndierckx/DefinitelyTyped,behzad888/DefinitelyTyped,rolandzwaga/DefinitelyTyped,teves-castro/DefinitelyTyped,Dominator008/DefinitelyTyped,florentpoujol/DefinitelyTyped,use-strict/DefinitelyTyped,danfma/DefinitelyTyped,pwelter34/DefinitelyTyped,wilfrem/DefinitelyTyped,QuatroCode/DefinitelyTyped,Litee/DefinitelyTyped,GlennQuirynen/DefinitelyTyped,GiedriusGrabauskas/DefinitelyTyped,pocesar/DefinitelyTyped,greglo/DefinitelyTyped,georgemarshall/DefinitelyTyped,martinduparc/DefinitelyTyped,bennett000/DefinitelyTyped,applesaucers/lodash-invokeMap,georgemarshall/DefinitelyTyped,rschmukler/DefinitelyTyped,philippstucki/DefinitelyTyped,magny/DefinitelyTyped,glenndierckx/DefinitelyTyped,CodeZombieCH/DefinitelyTyped,jimthedev/DefinitelyTyped,optical/DefinitelyTyped,sergey-buturlakin/DefinitelyTyped,abner/DefinitelyTyped,AgentME/DefinitelyTyped,laurentiustamate94/DefinitelyTyped,slavomirvojacek/DefinitelyTyped,Pro/DefinitelyTyped,UzEE/DefinitelyTyped,nobuoka/DefinitelyTyped,danfma/DefinitelyTyped,donnut/DefinitelyTyped,arma-gast/DefinitelyTyped,abbasmhd/DefinitelyTyped,paulmorphy/DefinitelyTyped,esperco/DefinitelyTyped,borisyankov/DefinitelyTyped,magny/DefinitelyTyped,Dominator008/DefinitelyTyped,AgentME/DefinitelyTyped,frogcjn/DefinitelyTyped,onecentlin/DefinitelyTyped,zuzusik/DefinitelyTyped,zuzusik/DefinitelyTyped,nitintutlani/DefinitelyTyped,use-strict/DefinitelyTyped,amir-arad/DefinitelyTyped,johan-gorter/DefinitelyTyped,AgentME/DefinitelyTyped,flyfishMT/DefinitelyTyped,xStrom/DefinitelyTyped,aciccarello/DefinitelyTyped,AyaMorisawa/DefinitelyTyped,eugenpodaru/DefinitelyTyped,chrootsu/DefinitelyTyped,rolandzwaga/DefinitelyTyped,dsebastien/DefinitelyTyped,alextkachman/DefinitelyTyped,yuit/DefinitelyTyped,UzEE/DefinitelyTyped,smrq/DefinitelyTyped,rcchen/DefinitelyTyped,RX14/DefinitelyTyped,Zzzen/DefinitelyTyped,Penryn/DefinitelyTyped,EnableSoftware/DefinitelyTyped,psnider/DefinitelyTyped,stacktracejs/DefinitelyTyped,syuilo/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,onecentlin/DefinitelyTyped,tan9/DefinitelyTyped,martinduparc/DefinitelyTyped,EnableSoftware/DefinitelyTyped,schmuli/DefinitelyTyped,philippstucki/DefinitelyTyped,jimthedev/DefinitelyTyped,mhegazy/DefinitelyTyped,arusakov/DefinitelyTyped,florentpoujol/DefinitelyTyped,scriby/DefinitelyTyped,raijinsetsu/DefinitelyTyped,yuit/DefinitelyTyped,Litee/DefinitelyTyped,newclear/DefinitelyTyped | ---
+++
@@ -0,0 +1,28 @@
+// Type definitions for sandboxed-module v2.0.3
+// Project: https://github.com/felixge/node-sandboxed-module
+// Definitions by: Sven Reglitzki <https://github.com/svi3c/>
+// Definitions: https://github.com/borisyankov/DefinitelyTyped
+
+/// <reference path="sandboxed-module.d.ts" />
+
+import SandboxedModule = require("sandboxed-module");
+
+var sandboxedModule:SandboxedModule = SandboxedModule.load("foo");
+var sandboxedModuleExports:any = SandboxedModule.require("foo");
+
+var sandboxedModuleExportsWithOptions:any = SandboxedModule.require("foo", {
+ requires: {
+ someDep: {}
+ },
+ globals: {
+ theAnswer: 42
+ },
+ locals: {
+ someLocal: 1
+ },
+ sourceTransformers: {
+ identity: (src:string) => src
+ },
+ singleOnly: true,
+ sourceTransformersSingleOnly: true
+}); |
|
41055f98dd3b448c2307a11790575cd84a050cfa | tests/scheduling-messages/test00008.test.ts | tests/scheduling-messages/test00008.test.ts | import {
getConsumer,
getMessageManager,
getProducer,
getQueueManagerFrontend,
} from '../common';
import { Message } from '../../src/message';
import { delay, promisifyAll } from 'bluebird';
test("Make sure scheduled messages aren't published if destination queue is deleted", async () => {
const msg = new Message();
msg.setScheduledCron('*/3 * * * * *').setBody({ hello: 'world' });
const producer = getProducer('queue_A');
const r = await producer.produceAsync(msg);
expect(r).toBe(true);
const consumer = getConsumer({ queueName: 'queue_B' });
await consumer.runAsync();
const messageManager = promisifyAll(await getMessageManager());
const s1 = await messageManager.getScheduledMessagesAsync(0, 99);
expect(s1.total).toBe(1);
await delay(10000);
const queueManager = promisifyAll(await getQueueManagerFrontend());
const m1 = await queueManager.getQueueMetricsAsync(producer.getQueue());
expect(m1.pending > 0).toBe(true);
await producer.shutdownAsync();
await queueManager.deleteMessageQueueAsync(producer.getQueue());
await delay(10000);
const m2 = await queueManager.getQueueMetricsAsync(producer.getQueue());
expect(m2.pending).toBe(0);
const s2 = await messageManager.getScheduledMessagesAsync(0, 99);
expect(s2.total).toBe(0);
});
| Test scheduled messages publication when dst queue is deleted | Test scheduled messages publication when dst queue is deleted
| TypeScript | mit | weyoss/redis-smq,weyoss/redis-smq,weyoss/redis-smq | ---
+++
@@ -0,0 +1,39 @@
+import {
+ getConsumer,
+ getMessageManager,
+ getProducer,
+ getQueueManagerFrontend,
+} from '../common';
+import { Message } from '../../src/message';
+import { delay, promisifyAll } from 'bluebird';
+
+test("Make sure scheduled messages aren't published if destination queue is deleted", async () => {
+ const msg = new Message();
+ msg.setScheduledCron('*/3 * * * * *').setBody({ hello: 'world' });
+
+ const producer = getProducer('queue_A');
+ const r = await producer.produceAsync(msg);
+ expect(r).toBe(true);
+
+ const consumer = getConsumer({ queueName: 'queue_B' });
+ await consumer.runAsync();
+
+ const messageManager = promisifyAll(await getMessageManager());
+ const s1 = await messageManager.getScheduledMessagesAsync(0, 99);
+ expect(s1.total).toBe(1);
+
+ await delay(10000);
+ const queueManager = promisifyAll(await getQueueManagerFrontend());
+ const m1 = await queueManager.getQueueMetricsAsync(producer.getQueue());
+ expect(m1.pending > 0).toBe(true);
+
+ await producer.shutdownAsync();
+ await queueManager.deleteMessageQueueAsync(producer.getQueue());
+
+ await delay(10000);
+ const m2 = await queueManager.getQueueMetricsAsync(producer.getQueue());
+ expect(m2.pending).toBe(0);
+
+ const s2 = await messageManager.getScheduledMessagesAsync(0, 99);
+ expect(s2.total).toBe(0);
+}); |
|
7eb891eac465593decd867286dbb8075b57847eb | app/pages/_document.tsx | app/pages/_document.tsx | import Document, {
Html,
Head,
Main,
NextScript,
DocumentContext,
} from "next/document";
class MyDocument extends Document {
static async getInitialProps(ctx: DocumentContext) {
const initialProps = await Document.getInitialProps(ctx);
return { ...initialProps };
}
render() {
return (
<Html lang="en">
<Head />
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
}
export default MyDocument;
| Add document to make sure lang is set correctly | Add document to make sure lang is set correctly
| TypeScript | apache-2.0 | thenickreynolds/popcorngif,thenickreynolds/popcorngif | ---
+++
@@ -0,0 +1,28 @@
+import Document, {
+ Html,
+ Head,
+ Main,
+ NextScript,
+ DocumentContext,
+} from "next/document";
+
+class MyDocument extends Document {
+ static async getInitialProps(ctx: DocumentContext) {
+ const initialProps = await Document.getInitialProps(ctx);
+ return { ...initialProps };
+ }
+
+ render() {
+ return (
+ <Html lang="en">
+ <Head />
+ <body>
+ <Main />
+ <NextScript />
+ </body>
+ </Html>
+ );
+ }
+}
+
+export default MyDocument; |
|
767ae358b41dea810ce14844b135540055c283f4 | src/apps/rss/index.ts | src/apps/rss/index.ts | import express from 'express'
import redis from 'redis'
import apolloMiddleware from 'v2/apollo/middleware'
import withStaticRouter from 'v2/hocs/WithStaticRouter'
import pageResolver from 'v2/components/UI/XmlPage/resolver'
import { Routes } from './Routes'
import { REDIS_URL } from 'config.js'
const client = redis.createClient(REDIS_URL, {
retry_strategy: () => undefined,
})
client.on('error', err => {
console.error('Error connecting to Redis', err)
})
const expiresIn = 60 * 10 * 10
const setCache = (key, data) => {
if (!client || !client.connected) return null
client.set(key, data)
client.expire(key, expiresIn)
}
const getCache = (key, callback) => {
if (!client || !client.connected) return callback()
return client.get(key, callback)
}
const middlewareStack = [apolloMiddleware]
const app = express()
const resolve = [
...middlewareStack,
(req, res, next) => {
const key = req.originalUrl
getCache(key, (err, data) => {
if (err) return next(err)
if (data) {
res.status(200)
res.send(data)
res.end()
} else {
req.apollo
.render(withStaticRouter(Routes), {}, { mode: 'bare' })
.then(apolloRes => {
const feed = pageResolver({ apolloRes })
setCache(key, feed)
res.status(200)
res.send(feed)
res.end()
})
.catch(err => {
return next(err)
})
}
})
},
]
app.get('/explore/feed/rss', ...resolve)
app.get('/:username/feed/rss', ...resolve)
app.get('/:username/:slug/feed/rss', ...resolve)
// TODO: reimplement this
// app.get("/blog/feed/rss", ...resolve)
module.exports = app
| Rename directory and clean up | Rename directory and clean up
| TypeScript | mit | aredotna/ervell,aredotna/ervell,aredotna/ervell,aredotna/ervell,aredotna/ervell | ---
+++
@@ -0,0 +1,71 @@
+import express from 'express'
+import redis from 'redis'
+import apolloMiddleware from 'v2/apollo/middleware'
+import withStaticRouter from 'v2/hocs/WithStaticRouter'
+import pageResolver from 'v2/components/UI/XmlPage/resolver'
+import { Routes } from './Routes'
+
+import { REDIS_URL } from 'config.js'
+
+const client = redis.createClient(REDIS_URL, {
+ retry_strategy: () => undefined,
+})
+
+client.on('error', err => {
+ console.error('Error connecting to Redis', err)
+})
+
+const expiresIn = 60 * 10 * 10
+
+const setCache = (key, data) => {
+ if (!client || !client.connected) return null
+ client.set(key, data)
+ client.expire(key, expiresIn)
+}
+
+const getCache = (key, callback) => {
+ if (!client || !client.connected) return callback()
+ return client.get(key, callback)
+}
+
+const middlewareStack = [apolloMiddleware]
+
+const app = express()
+
+const resolve = [
+ ...middlewareStack,
+ (req, res, next) => {
+ const key = req.originalUrl
+ getCache(key, (err, data) => {
+ if (err) return next(err)
+ if (data) {
+ res.status(200)
+ res.send(data)
+ res.end()
+ } else {
+ req.apollo
+ .render(withStaticRouter(Routes), {}, { mode: 'bare' })
+ .then(apolloRes => {
+ const feed = pageResolver({ apolloRes })
+ setCache(key, feed)
+
+ res.status(200)
+ res.send(feed)
+ res.end()
+ })
+ .catch(err => {
+ return next(err)
+ })
+ }
+ })
+ },
+]
+
+app.get('/explore/feed/rss', ...resolve)
+app.get('/:username/feed/rss', ...resolve)
+app.get('/:username/:slug/feed/rss', ...resolve)
+
+// TODO: reimplement this
+// app.get("/blog/feed/rss", ...resolve)
+
+module.exports = app |
|
43a2d9a4539e45e6438c17f5838d2e9d9db9bd2d | src/Test/Ast/PlusMinusSign.ts | src/Test/Ast/PlusMinusSign.ts | import { expect } from 'chai'
import Up from '../../index'
import { insideDocumentAndParagraph } from './Helpers'
import { PlainTextNode } from '../../SyntaxNodes/PlainTextNode'
context('A plus symbol followed by a hyphen normally produces a plus-minus sign', () => {
context('This applies within regular text:', () => {
specify('Between words', () => {
expect(Up.toAst("Yeah, it uses base HP+-4.")).to.be.eql(
insideDocumentAndParagraph([
new PlainTextNode("Yeah, it uses base HP±4.")
]))
})
specify('Following a word', () => {
expect(Up.toAst("I have 10+- ...")).to.be.eql(
insideDocumentAndParagraph([
new PlainTextNode("I have 10± ...")
]))
})
specify('Preceding a word', () => {
expect(Up.toAst('I have three homes, +-two.')).to.be.eql(
insideDocumentAndParagraph([
new PlainTextNode('I have three homes, ±two.')
]))
})
specify('Surrounded by whitespace', () => {
expect(Up.toAst("Well, +- a million.")).to.be.eql(
insideDocumentAndParagraph([
new PlainTextNode("Well, ± a million.")
]))
})
})
})
| Add 4 failing plus-minus tests | Add 4 failing plus-minus tests
| TypeScript | mit | start/up,start/up | ---
+++
@@ -0,0 +1,37 @@
+import { expect } from 'chai'
+import Up from '../../index'
+import { insideDocumentAndParagraph } from './Helpers'
+import { PlainTextNode } from '../../SyntaxNodes/PlainTextNode'
+
+
+context('A plus symbol followed by a hyphen normally produces a plus-minus sign', () => {
+ context('This applies within regular text:', () => {
+ specify('Between words', () => {
+ expect(Up.toAst("Yeah, it uses base HP+-4.")).to.be.eql(
+ insideDocumentAndParagraph([
+ new PlainTextNode("Yeah, it uses base HP±4.")
+ ]))
+ })
+
+ specify('Following a word', () => {
+ expect(Up.toAst("I have 10+- ...")).to.be.eql(
+ insideDocumentAndParagraph([
+ new PlainTextNode("I have 10± ...")
+ ]))
+ })
+
+ specify('Preceding a word', () => {
+ expect(Up.toAst('I have three homes, +-two.')).to.be.eql(
+ insideDocumentAndParagraph([
+ new PlainTextNode('I have three homes, ±two.')
+ ]))
+ })
+
+ specify('Surrounded by whitespace', () => {
+ expect(Up.toAst("Well, +- a million.")).to.be.eql(
+ insideDocumentAndParagraph([
+ new PlainTextNode("Well, ± a million.")
+ ]))
+ })
+ })
+}) |
|
a747a00ade018175d794cf7a94e43b06663c9059 | packages/@ember/deprecated-features/index.ts | packages/@ember/deprecated-features/index.ts | /* eslint-disable no-implicit-coercion */
// These versions should be the version that the deprecation was _introduced_,
// not the version that the feature will be removed.
export const SEND_ACTION = !!'3.4.0';
export const EMBER_EXTEND_PROTOTYPES = !!'3.2.0-beta.5';
export const RUN_SYNC = !!'3.0.0-beta.4';
export const LOGGER = !!'3.2.0-beta.1';
export const MERGE = !!'3.6.0-beta.1';
export const ROUTER_EVENTS = !!'4.0.0';
export const COMPONENT_MANAGER_STRING_LOOKUP = !!'3.8.0';
export const JQUERY_INTEGRATION = !!'3.9.0';
export const ALIAS_METHOD = !!'3.9.0';
export const APP_CTRL_ROUTER_PROPS = !!'4.0.0';
| /* eslint-disable no-implicit-coercion */
// These versions should be the version that the deprecation was _introduced_,
// not the version that the feature will be removed.
export const SEND_ACTION = !!'3.4.0';
export const EMBER_EXTEND_PROTOTYPES = !!'3.2.0-beta.5';
export const RUN_SYNC = !!'3.0.0-beta.4';
export const LOGGER = !!'3.2.0-beta.1';
export const MERGE = !!'3.6.0-beta.1';
export const ROUTER_EVENTS = !!'4.0.0';
export const COMPONENT_MANAGER_STRING_LOOKUP = !!'3.8.0';
export const JQUERY_INTEGRATION = !!'3.9.0';
export const ALIAS_METHOD = !!'3.9.0';
export const APP_CTRL_ROUTER_PROPS = !!'3.10.0';
| Fix version for APP_CTRL_ROUTER_PROPS deprecation flag | [BETA] Fix version for APP_CTRL_ROUTER_PROPS deprecation flag | TypeScript | mit | asakusuma/ember.js,miguelcobain/ember.js,stefanpenner/ember.js,givanse/ember.js,elwayman02/ember.js,givanse/ember.js,miguelcobain/ember.js,asakusuma/ember.js,tildeio/ember.js,mfeckie/ember.js,fpauser/ember.js,sandstrom/ember.js,GavinJoyce/ember.js,elwayman02/ember.js,cibernox/ember.js,sly7-7/ember.js,knownasilya/ember.js,knownasilya/ember.js,sandstrom/ember.js,cibernox/ember.js,givanse/ember.js,stefanpenner/ember.js,mfeckie/ember.js,fpauser/ember.js,intercom/ember.js,mixonic/ember.js,mixonic/ember.js,stefanpenner/ember.js,knownasilya/ember.js,mixonic/ember.js,elwayman02/ember.js,asakusuma/ember.js,cibernox/ember.js,intercom/ember.js,GavinJoyce/ember.js,givanse/ember.js,GavinJoyce/ember.js,fpauser/ember.js,mfeckie/ember.js,tildeio/ember.js,intercom/ember.js,miguelcobain/ember.js,asakusuma/ember.js,mfeckie/ember.js,miguelcobain/ember.js,sandstrom/ember.js,intercom/ember.js,emberjs/ember.js,cibernox/ember.js,tildeio/ember.js,GavinJoyce/ember.js,sly7-7/ember.js,sly7-7/ember.js,emberjs/ember.js,emberjs/ember.js,fpauser/ember.js,elwayman02/ember.js | ---
+++
@@ -12,4 +12,4 @@
export const COMPONENT_MANAGER_STRING_LOOKUP = !!'3.8.0';
export const JQUERY_INTEGRATION = !!'3.9.0';
export const ALIAS_METHOD = !!'3.9.0';
-export const APP_CTRL_ROUTER_PROPS = !!'4.0.0';
+export const APP_CTRL_ROUTER_PROPS = !!'3.10.0'; |
29bf3b2414e2a611ee98fda86b9256016a908fa1 | rethinkdb/rethinkdb-tests.ts | rethinkdb/rethinkdb-tests.ts | /// <reference path="rethinkdb.d.ts" />
import r = require("rethinkdb")
r.connect({host:"localhost", port: 28015}, function(err, conn) {
console.log("HI", err, conn)
var testDb = r.db('test')
testDb.tableCreate('users').run(conn, function(err, stuff) {
var users = testDb.table('users')
users.insert({name: "bob"}).run(conn, function() {})
users.filter(function(doc?) {
return doc("henry").eq("bob")
})
.between("james", "beth")
.limit(4)
.run(conn, function(err, cursor) {
cursor.toArray().then(rows => {
console.log(rows);
});
})
})
})
// use promises instead of callbacks
r.connect({host:"localhost", port: 28015}).then(function(conn) {
console.log("HI", conn)
var testDb = r.db('test')
testDb.tableCreate('users').run(conn).then(function(stuff) {
var users = testDb.table('users')
users.insert({name: "bob"}).run(conn, function() {})
users.filter(function(doc?) {
return doc("henry").eq("bob")
})
.between("james", "beth")
.limit(4)
.run(conn);
})
})
| /// <reference path="rethinkdb.d.ts" />
import r = require("rethinkdb");
r.connect({ host: "localhost", port: 28015 }, function(err, conn) {
console.log("HI", err, conn);
const testDb = r.db("test");
testDb.tableCreate("users").run(conn, function(err, stuff) {
const users = testDb.table("users");
users.insert({ name: "bob" }).run(conn, function() {
});
users.filter(function(doc?) {
return doc("henry").eq("bob");
})
.between("james", "beth")
.limit(4)
.run(conn, function(err, cursor) {
cursor.toArray().then(rows => {
console.log(rows);
});
});
});
});
// use promises instead of callbacks
r.connect({ host: "localhost", port: 28015 }).then(function(conn) {
console.log("HI", conn);
const testDb = r.db("test");
testDb.tableCreate("users").run(conn).then(function(stuff) {
const users = testDb.table("users");
users.insert({ name: "bob" }).run(conn, function() {
});
users.filter(function(doc?) {
return doc("henry").eq("bob");
})
.between("james", "beth")
.limit(4)
.run(conn);
});
});
| Clean up the listing issues in the test | [rethinkdb] Clean up the listing issues in the test
| TypeScript | mit | alexdresko/DefinitelyTyped,use-strict/DefinitelyTyped,YousefED/DefinitelyTyped,borisyankov/DefinitelyTyped,isman-usoh/DefinitelyTyped,GiedriusGrabauskas/DefinitelyTyped,slavomirvojacek/DefinitelyTyped,rolandzwaga/DefinitelyTyped,jimthedev/DefinitelyTyped,damianog/DefinitelyTyped,HPFOD/DefinitelyTyped,ashwinr/DefinitelyTyped,hellopao/DefinitelyTyped,QuatroCode/DefinitelyTyped,scriby/DefinitelyTyped,GiedriusGrabauskas/DefinitelyTyped,yuit/DefinitelyTyped,subash-a/DefinitelyTyped,rcchen/DefinitelyTyped,benliddicott/DefinitelyTyped,aciccarello/DefinitelyTyped,AgentME/DefinitelyTyped,subash-a/DefinitelyTyped,psnider/DefinitelyTyped,jimthedev/DefinitelyTyped,georgemarshall/DefinitelyTyped,damianog/DefinitelyTyped,pocesar/DefinitelyTyped,zuzusik/DefinitelyTyped,ashwinr/DefinitelyTyped,markogresak/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,laurentiustamate94/DefinitelyTyped,smrq/DefinitelyTyped,yuit/DefinitelyTyped,micurs/DefinitelyTyped,chrismbarr/DefinitelyTyped,AgentME/DefinitelyTyped,georgemarshall/DefinitelyTyped,schmuli/DefinitelyTyped,use-strict/DefinitelyTyped,psnider/DefinitelyTyped,magny/DefinitelyTyped,shlomiassaf/DefinitelyTyped,QuatroCode/DefinitelyTyped,AgentME/DefinitelyTyped,alexdresko/DefinitelyTyped,AgentME/DefinitelyTyped,arusakov/DefinitelyTyped,borisyankov/DefinitelyTyped,amir-arad/DefinitelyTyped,danfma/DefinitelyTyped,aciccarello/DefinitelyTyped,danfma/DefinitelyTyped,rcchen/DefinitelyTyped,slavomirvojacek/DefinitelyTyped,sledorze/DefinitelyTyped,pocesar/DefinitelyTyped,nycdotnet/DefinitelyTyped,alvarorahul/DefinitelyTyped,magny/DefinitelyTyped,arusakov/DefinitelyTyped,nycdotnet/DefinitelyTyped,one-pieces/DefinitelyTyped,johan-gorter/DefinitelyTyped,zuzusik/DefinitelyTyped,arusakov/DefinitelyTyped,hellopao/DefinitelyTyped,martinduparc/DefinitelyTyped,pocesar/DefinitelyTyped,HPFOD/DefinitelyTyped,mcrawshaw/DefinitelyTyped,minodisk/DefinitelyTyped,zuzusik/DefinitelyTyped,AbraaoAlves/DefinitelyTyped,psnider/DefinitelyTyped,benishouga/DefinitelyTyped,dsebastien/DefinitelyTyped,sledorze/DefinitelyTyped,johan-gorter/DefinitelyTyped,martinduparc/DefinitelyTyped,smrq/DefinitelyTyped,daptiv/DefinitelyTyped,syuilo/DefinitelyTyped,mcliment/DefinitelyTyped,georgemarshall/DefinitelyTyped,isman-usoh/DefinitelyTyped,schmuli/DefinitelyTyped,chrismbarr/DefinitelyTyped,minodisk/DefinitelyTyped,abbasmhd/DefinitelyTyped,abbasmhd/DefinitelyTyped,chrootsu/DefinitelyTyped,scriby/DefinitelyTyped,jimthedev/DefinitelyTyped,rolandzwaga/DefinitelyTyped,shlomiassaf/DefinitelyTyped,hellopao/DefinitelyTyped,mcrawshaw/DefinitelyTyped,benishouga/DefinitelyTyped,aciccarello/DefinitelyTyped,YousefED/DefinitelyTyped,dsebastien/DefinitelyTyped,syuilo/DefinitelyTyped,martinduparc/DefinitelyTyped,progre/DefinitelyTyped,benishouga/DefinitelyTyped,chrootsu/DefinitelyTyped,progre/DefinitelyTyped,georgemarshall/DefinitelyTyped,alvarorahul/DefinitelyTyped,schmuli/DefinitelyTyped | ---
+++
@@ -1,17 +1,20 @@
/// <reference path="rethinkdb.d.ts" />
-import r = require("rethinkdb")
+import r = require("rethinkdb");
-r.connect({host:"localhost", port: 28015}, function(err, conn) {
- console.log("HI", err, conn)
- var testDb = r.db('test')
- testDb.tableCreate('users').run(conn, function(err, stuff) {
- var users = testDb.table('users')
+r.connect({ host: "localhost", port: 28015 }, function(err, conn) {
+ console.log("HI", err, conn);
- users.insert({name: "bob"}).run(conn, function() {})
+ const testDb = r.db("test");
+
+ testDb.tableCreate("users").run(conn, function(err, stuff) {
+ const users = testDb.table("users");
+
+ users.insert({ name: "bob" }).run(conn, function() {
+ });
users.filter(function(doc?) {
- return doc("henry").eq("bob")
+ return doc("henry").eq("bob");
})
.between("james", "beth")
.limit(4)
@@ -19,26 +22,27 @@
cursor.toArray().then(rows => {
console.log(rows);
});
- })
-
- })
-})
+ });
+ });
+});
// use promises instead of callbacks
-r.connect({host:"localhost", port: 28015}).then(function(conn) {
- console.log("HI", conn)
- var testDb = r.db('test')
- testDb.tableCreate('users').run(conn).then(function(stuff) {
- var users = testDb.table('users')
+r.connect({ host: "localhost", port: 28015 }).then(function(conn) {
+ console.log("HI", conn);
- users.insert({name: "bob"}).run(conn, function() {})
+ const testDb = r.db("test");
+
+ testDb.tableCreate("users").run(conn).then(function(stuff) {
+ const users = testDb.table("users");
+
+ users.insert({ name: "bob" }).run(conn, function() {
+ });
users.filter(function(doc?) {
- return doc("henry").eq("bob")
+ return doc("henry").eq("bob");
})
.between("james", "beth")
.limit(4)
.run(conn);
-
- })
-})
+ });
+}); |
89030a176258b6fe26903c7996c2dc1a8cb64ada | source/message/messagebus.ts | source/message/messagebus.ts | /**
* A convenience singleton to convey messages around the system.
* Typically the view will grab a handle on this and propogate
* the messages to the UI. Because it is a singleton anything can
* grab a handle and start spitting out messages.
*
* Neither the consumer or the emitter is aware of each other so
* it should stay nicely decoupled (and it is highly cohesive).
*
* There is nothing stopping multiple listeners from grabbing this
* so for example it could be grabbed by a logger and the
* message be logged somewhere.
*/
export class MessageBus extends THREE.EventDispatcher {
static instance = new MessageBus();
constructor() {
super();
if (MessageBus.instance) {
throw new Error("Use the static instance property. Do not create a new on");
}
}
clear() {
this.dispatchEvent({
type: "clear"
});
}
success(message: string, duration: number = 10000) {
this.dispatchEvent({
type: "success",
data: message,
duration
});
}
log(message: string, duration: number = 10000) {
this.dispatchEvent({
type: "log",
data: message,
duration
});
}
warn(message: string, duration: number = 10000) {
this.dispatchEvent({
type: "warn",
data: message,
duration
});
}
error(message: string, duration: number = 10000) {
this.dispatchEvent({
type: "error",
data: message,
duration
});
}
} | Create the message bus singleton | Create the message bus singleton
| TypeScript | apache-2.0 | Tomella/cossap-3d,Tomella/cossap-3d,Tomella/cossap-3d,Tomella/cossap-3d | ---
+++
@@ -0,0 +1,62 @@
+/**
+ * A convenience singleton to convey messages around the system.
+ * Typically the view will grab a handle on this and propogate
+ * the messages to the UI. Because it is a singleton anything can
+ * grab a handle and start spitting out messages.
+ *
+ * Neither the consumer or the emitter is aware of each other so
+ * it should stay nicely decoupled (and it is highly cohesive).
+ *
+ * There is nothing stopping multiple listeners from grabbing this
+ * so for example it could be grabbed by a logger and the
+ * message be logged somewhere.
+ */
+
+export class MessageBus extends THREE.EventDispatcher {
+ static instance = new MessageBus();
+
+ constructor() {
+ super();
+ if (MessageBus.instance) {
+ throw new Error("Use the static instance property. Do not create a new on");
+ }
+ }
+
+ clear() {
+ this.dispatchEvent({
+ type: "clear"
+ });
+ }
+
+ success(message: string, duration: number = 10000) {
+ this.dispatchEvent({
+ type: "success",
+ data: message,
+ duration
+ });
+ }
+
+ log(message: string, duration: number = 10000) {
+ this.dispatchEvent({
+ type: "log",
+ data: message,
+ duration
+ });
+ }
+
+ warn(message: string, duration: number = 10000) {
+ this.dispatchEvent({
+ type: "warn",
+ data: message,
+ duration
+ });
+ }
+
+ error(message: string, duration: number = 10000) {
+ this.dispatchEvent({
+ type: "error",
+ data: message,
+ duration
+ });
+ }
+} |
|
e3f2d8a9b3c5b685c923150ba4a2283e114cfc24 | server/api/redis.ts | server/api/redis.ts | import * as eta from "../../eta";
import * as redis from "redis";
const client: redis.RedisClient = undefined;
export default client;
export function connect(): redis.RedisClient {
const tempClient: redis.RedisClient = redis.createClient(eta.config.http.session.port, eta.config.http.session.host);
tempClient.on("connect", () => {
eta.logger.info("Successfully connected to the Redis server.");
});
tempClient.on("error", (err: Error) => {
eta.logger.error(err);
});
return tempClient;
}
| Add Redis API for Eta | Add Redis API for Eta
| TypeScript | mit | crossroads-education/eta,crossroads-education/eta | ---
+++
@@ -0,0 +1,16 @@
+import * as eta from "../../eta";
+import * as redis from "redis";
+
+const client: redis.RedisClient = undefined;
+export default client;
+
+export function connect(): redis.RedisClient {
+ const tempClient: redis.RedisClient = redis.createClient(eta.config.http.session.port, eta.config.http.session.host);
+ tempClient.on("connect", () => {
+ eta.logger.info("Successfully connected to the Redis server.");
+ });
+ tempClient.on("error", (err: Error) => {
+ eta.logger.error(err);
+ });
+ return tempClient;
+} |
|
70ca18e91c507fb3f088866109f04ac89f74d6ed | tests/cases/conformance/types/contextualTypes/jsxAttributes/contextuallyTypedStringLiteralsInJsxAttributes02.tsx | tests/cases/conformance/types/contextualTypes/jsxAttributes/contextuallyTypedStringLiteralsInJsxAttributes02.tsx | // @filename: file.tsx
// @jsx: preserve
// @module: amd
// @noLib: true
// @libFiles: react.d.ts,lib.d.ts
import React = require('react')
export interface ClickableProps {
children?: string;
className?: string;
}
export interface ButtonProps extends ClickableProps {
onClick: (k: "left" | "right") => void;
}
export interface LinkProps extends ClickableProps {
goTo: "home" | "contact";
}
export function MainButton(buttonProps: ButtonProps): JSX.Element;
export function MainButton(linkProps: LinkProps): JSX.Element;
export function MainButton(props: ButtonProps | LinkProps): JSX.Element {
const linkProps = props as LinkProps;
if(linkProps.goTo) {
return this._buildMainLink(props);
}
return this._buildMainButton(props);
}
const b0 = <MainButton {...{onClick: (k) => {console.log(k)}}} extra />; // k has type any
const b2 = <MainButton onClick={(k)=>{console.log(k)}} extra />; // k has type "left" | "right"
const b3 = <MainButton {...{goTo:"home"}} extra />; // goTo has type"home" | "contact"
const b4 = <MainButton goTo="home" extra />; // goTo has type "home" | "contact"
export function NoOverload(buttonProps: ButtonProps): JSX.Element { return undefined }
const c1 = <NoOverload {...{onClick: (k) => {console.log(k)}}} extra />; // k has type any
export function NoOverload1(linkProps: LinkProps): JSX.Element { return undefined }
const d1 = <NoOverload1 {...{goTo:"home"}} extra />; // goTo has type "home" | "contact"
| Add a test for contextual type in JSXAttributes | Add a test for contextual type in JSXAttributes
| TypeScript | apache-2.0 | donaldpipowitch/TypeScript,basarat/TypeScript,kitsonk/TypeScript,kitsonk/TypeScript,Eyas/TypeScript,SaschaNaz/TypeScript,alexeagle/TypeScript,chuckjaz/TypeScript,mihailik/TypeScript,kpreisser/TypeScript,DLehenbauer/TypeScript,donaldpipowitch/TypeScript,donaldpipowitch/TypeScript,synaptek/TypeScript,synaptek/TypeScript,Microsoft/TypeScript,TukekeSoft/TypeScript,kitsonk/TypeScript,DLehenbauer/TypeScript,nojvek/TypeScript,erikmcc/TypeScript,minestarks/TypeScript,TukekeSoft/TypeScript,nojvek/TypeScript,erikmcc/TypeScript,chuckjaz/TypeScript,mihailik/TypeScript,Microsoft/TypeScript,donaldpipowitch/TypeScript,kpreisser/TypeScript,kpreisser/TypeScript,chuckjaz/TypeScript,jwbay/TypeScript,SaschaNaz/TypeScript,basarat/TypeScript,RyanCavanaugh/TypeScript,DLehenbauer/TypeScript,synaptek/TypeScript,synaptek/TypeScript,jwbay/TypeScript,nojvek/TypeScript,nojvek/TypeScript,microsoft/TypeScript,alexeagle/TypeScript,basarat/TypeScript,mihailik/TypeScript,basarat/TypeScript,weswigham/TypeScript,minestarks/TypeScript,RyanCavanaugh/TypeScript,RyanCavanaugh/TypeScript,weswigham/TypeScript,minestarks/TypeScript,Eyas/TypeScript,erikmcc/TypeScript,SaschaNaz/TypeScript,Eyas/TypeScript,Microsoft/TypeScript,microsoft/TypeScript,weswigham/TypeScript,mihailik/TypeScript,jwbay/TypeScript,SaschaNaz/TypeScript,chuckjaz/TypeScript,alexeagle/TypeScript,TukekeSoft/TypeScript,microsoft/TypeScript,erikmcc/TypeScript,jwbay/TypeScript,DLehenbauer/TypeScript,Eyas/TypeScript | ---
+++
@@ -0,0 +1,42 @@
+// @filename: file.tsx
+// @jsx: preserve
+// @module: amd
+// @noLib: true
+// @libFiles: react.d.ts,lib.d.ts
+
+import React = require('react')
+
+export interface ClickableProps {
+ children?: string;
+ className?: string;
+}
+
+export interface ButtonProps extends ClickableProps {
+ onClick: (k: "left" | "right") => void;
+}
+
+export interface LinkProps extends ClickableProps {
+ goTo: "home" | "contact";
+}
+
+export function MainButton(buttonProps: ButtonProps): JSX.Element;
+export function MainButton(linkProps: LinkProps): JSX.Element;
+export function MainButton(props: ButtonProps | LinkProps): JSX.Element {
+ const linkProps = props as LinkProps;
+ if(linkProps.goTo) {
+ return this._buildMainLink(props);
+ }
+
+ return this._buildMainButton(props);
+}
+
+const b0 = <MainButton {...{onClick: (k) => {console.log(k)}}} extra />; // k has type any
+const b2 = <MainButton onClick={(k)=>{console.log(k)}} extra />; // k has type "left" | "right"
+const b3 = <MainButton {...{goTo:"home"}} extra />; // goTo has type"home" | "contact"
+const b4 = <MainButton goTo="home" extra />; // goTo has type "home" | "contact"
+
+export function NoOverload(buttonProps: ButtonProps): JSX.Element { return undefined }
+const c1 = <NoOverload {...{onClick: (k) => {console.log(k)}}} extra />; // k has type any
+
+export function NoOverload1(linkProps: LinkProps): JSX.Element { return undefined }
+const d1 = <NoOverload1 {...{goTo:"home"}} extra />; // goTo has type "home" | "contact" |
|
dccc6f867f2e926c4ebd5b1ee5bc8d15d61a3382 | src/components/CalendarHeatMap/CompletedHitItem.tsx | src/components/CalendarHeatMap/CompletedHitItem.tsx | import * as React from 'react';
import { RootState, HitDatabaseEntry } from '../../types';
import { connect, Dispatch } from 'react-redux';
import { EditBonus, editBonus } from '../../actions/bonus';
import { ResourceList } from '@shopify/polaris';
export interface OwnProps {
readonly id: string;
}
export interface Props {
readonly hit: HitDatabaseEntry;
}
export interface Handlers {
readonly onEdit: (id: string, value: number) => void;
}
class CompletedHitItem extends React.PureComponent<
Props & OwnProps & Handlers,
never
> {
public render() {
const { hit } = this.props;
return <ResourceList.Item attributeOne={hit.title} />;
}
}
const mapState = (state: RootState, ownProps: OwnProps): Props => ({
hit: state.hitDatabase.get(ownProps.id)
});
const mapDispatch = (dispatch: Dispatch<EditBonus>): Handlers => ({
onEdit: (id: string, value: number) => dispatch(editBonus(id, value))
});
export default connect(mapState, mapDispatch)(CompletedHitItem);
| Add ResourceList.Item as a connected component to display each completed HIT on a particular day. | Add ResourceList.Item as a connected component to display each completed HIT on a particular day.
| TypeScript | mit | Anveio/mturk-engine,Anveio/mturk-engine,Anveio/mturk-engine | ---
+++
@@ -0,0 +1,37 @@
+import * as React from 'react';
+import { RootState, HitDatabaseEntry } from '../../types';
+import { connect, Dispatch } from 'react-redux';
+import { EditBonus, editBonus } from '../../actions/bonus';
+import { ResourceList } from '@shopify/polaris';
+
+export interface OwnProps {
+ readonly id: string;
+}
+
+export interface Props {
+ readonly hit: HitDatabaseEntry;
+}
+
+export interface Handlers {
+ readonly onEdit: (id: string, value: number) => void;
+}
+
+class CompletedHitItem extends React.PureComponent<
+ Props & OwnProps & Handlers,
+ never
+> {
+ public render() {
+ const { hit } = this.props;
+ return <ResourceList.Item attributeOne={hit.title} />;
+ }
+}
+
+const mapState = (state: RootState, ownProps: OwnProps): Props => ({
+ hit: state.hitDatabase.get(ownProps.id)
+});
+
+const mapDispatch = (dispatch: Dispatch<EditBonus>): Handlers => ({
+ onEdit: (id: string, value: number) => dispatch(editBonus(id, value))
+});
+
+export default connect(mapState, mapDispatch)(CompletedHitItem); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.