type
stringclasses 7
values | content
stringlengths 4
9.55k
| repo
stringlengths 7
96
| path
stringlengths 4
178
| language
stringclasses 1
value |
|---|---|---|---|---|
ArrowFunction
|
() => {
return (
<></>
)
}
|
tarwaterk/transport-disc
|
src/components/headerContent/HeaderContent.tsx
|
TypeScript
|
ArrowFunction
|
async (tweet) => {
const userQueryResponse = await this.qnaMaker.getResponse(tweet.text)
if (userQueryResponse !== 'I cannot understand what you are saying' && userQueryResponse !== 'Oops!! An error occured.') {
console.log(`${tweet.text} => ${userQueryResponse}`)
// const response = await this.twitterClient.post('statuses/update', { in_reply_to_status_id: tweet.id_str, status: `@${tweet.user.screen_name} ${userQueryResponse}\n PS: This is a bot message.` })
// console.log(response.data.text)
}
}
|
jonathankamau/faqbot
|
src/services/TwitterService.ts
|
TypeScript
|
ArrowFunction
|
(error, safaricomTweets) => {
if (error) {
console.log(error)
return
}
safaricomTweets.forEach(safaricomTweet => {
if (safaricomTweet.in_reply_to_status_id_str) {
this.twitterClient.get('statuses/show', { id: `${safaricomTweet.in_reply_to_status_id_str}` }, (error, originalTweetToSafaricom) => {
if (error) {
console.log(error)
return
}
if (originalTweetToSafaricom.in_reply_to_status_id_str) {
return
}
// console.log(safaricomTweet)
// console.log(`From: @${originalTweetToSafaricom.user.screen_name} ${originalTweetToSafaricom.text}`)
console.log(originalTweetToSafaricom.text)
// console.log(`===>${tweet.text}`)
console.log(` ${safaricomTweet.text}`)
console.log('\n')
})
}
})
}
|
jonathankamau/faqbot
|
src/services/TwitterService.ts
|
TypeScript
|
ArrowFunction
|
safaricomTweet => {
if (safaricomTweet.in_reply_to_status_id_str) {
this.twitterClient.get('statuses/show', { id: `${safaricomTweet.in_reply_to_status_id_str}` }, (error, originalTweetToSafaricom) => {
if (error) {
console.log(error)
return
}
if (originalTweetToSafaricom.in_reply_to_status_id_str) {
return
}
// console.log(safaricomTweet)
// console.log(`From: @${originalTweetToSafaricom.user.screen_name} ${originalTweetToSafaricom.text}`)
console.log(originalTweetToSafaricom.text)
// console.log(`===>${tweet.text}`)
console.log(` ${safaricomTweet.text}`)
console.log('\n')
})
}
}
|
jonathankamau/faqbot
|
src/services/TwitterService.ts
|
TypeScript
|
ArrowFunction
|
(error, originalTweetToSafaricom) => {
if (error) {
console.log(error)
return
}
if (originalTweetToSafaricom.in_reply_to_status_id_str) {
return
}
// console.log(safaricomTweet)
// console.log(`From: @${originalTweetToSafaricom.user.screen_name} ${originalTweetToSafaricom.text}`)
console.log(originalTweetToSafaricom.text)
// console.log(`===>${tweet.text}`)
console.log(` ${safaricomTweet.text}`)
console.log('\n')
}
|
jonathankamau/faqbot
|
src/services/TwitterService.ts
|
TypeScript
|
ClassDeclaration
|
export class TwitterService {
private twitterClient
private qnaMaker: QnAMaker
constructor() {
this.twitterClient = new Twitter({
consumer_key: process.env.TWITTER_CONSUMER_KEY,
consumer_secret: process.env.TWITTER_CONSUMER_SECRET,
access_token: process.env.TWITTER_ACCESS_TOKEN,
access_token_secret: process.env.TWITTER_ACCESS_TOKEN_SECRET
})
this.qnaMaker = new QnAMaker()
}
fetchAllSafaricomTweets(): void {
const safaricomCareTweetToStream = this.twitterClient.stream('statuses/filter', { track: '@Safaricom_Care' })
safaricomCareTweetToStream.on('tweet', async (tweet) => {
const userQueryResponse = await this.qnaMaker.getResponse(tweet.text)
if (userQueryResponse !== 'I cannot understand what you are saying' && userQueryResponse !== 'Oops!! An error occured.') {
console.log(`${tweet.text} => ${userQueryResponse}`)
// const response = await this.twitterClient.post('statuses/update', { in_reply_to_status_id: tweet.id_str, status: `@${tweet.user.screen_name} ${userQueryResponse}\n PS: This is a bot message.` })
// console.log(response.data.text)
}
})
this.twitterClient.get('statuses/user_timeline', { screen_name: '@Safaricom_Care' }, (error, safaricomTweets) => {
if (error) {
console.log(error)
return
}
safaricomTweets.forEach(safaricomTweet => {
if (safaricomTweet.in_reply_to_status_id_str) {
this.twitterClient.get('statuses/show', { id: `${safaricomTweet.in_reply_to_status_id_str}` }, (error, originalTweetToSafaricom) => {
if (error) {
console.log(error)
return
}
if (originalTweetToSafaricom.in_reply_to_status_id_str) {
return
}
// console.log(safaricomTweet)
// console.log(`From: @${originalTweetToSafaricom.user.screen_name} ${originalTweetToSafaricom.text}`)
console.log(originalTweetToSafaricom.text)
// console.log(`===>${tweet.text}`)
console.log(` ${safaricomTweet.text}`)
console.log('\n')
})
}
})
})
// safaricomCareTweetFromStream.on('tweet', async (tweet) => {
// console.log(tweet)
// })
}
}
|
jonathankamau/faqbot
|
src/services/TwitterService.ts
|
TypeScript
|
MethodDeclaration
|
fetchAllSafaricomTweets(): void {
const safaricomCareTweetToStream = this.twitterClient.stream('statuses/filter', { track: '@Safaricom_Care' })
safaricomCareTweetToStream.on('tweet', async (tweet) => {
const userQueryResponse = await this.qnaMaker.getResponse(tweet.text)
if (userQueryResponse !== 'I cannot understand what you are saying' && userQueryResponse !== 'Oops!! An error occured.') {
console.log(`${tweet.text} => ${userQueryResponse}`)
// const response = await this.twitterClient.post('statuses/update', { in_reply_to_status_id: tweet.id_str, status: `@${tweet.user.screen_name} ${userQueryResponse}\n PS: This is a bot message.` })
// console.log(response.data.text)
}
})
this.twitterClient.get('statuses/user_timeline', { screen_name: '@Safaricom_Care' }, (error, safaricomTweets) => {
if (error) {
console.log(error)
return
}
safaricomTweets.forEach(safaricomTweet => {
if (safaricomTweet.in_reply_to_status_id_str) {
this.twitterClient.get('statuses/show', { id: `${safaricomTweet.in_reply_to_status_id_str}` }, (error, originalTweetToSafaricom) => {
if (error) {
console.log(error)
return
}
if (originalTweetToSafaricom.in_reply_to_status_id_str) {
return
}
// console.log(safaricomTweet)
// console.log(`From: @${originalTweetToSafaricom.user.screen_name} ${originalTweetToSafaricom.text}`)
console.log(originalTweetToSafaricom.text)
// console.log(`===>${tweet.text}`)
console.log(` ${safaricomTweet.text}`)
console.log('\n')
})
}
})
})
// safaricomCareTweetFromStream.on('tweet', async (tweet) => {
// console.log(tweet)
// })
}
|
jonathankamau/faqbot
|
src/services/TwitterService.ts
|
TypeScript
|
ClassDeclaration
|
export default class LivingObjectMessageMessage extends Message {
public msgId: number;
public timeStamp: number;
public owner: string;
public objectGenericId: number;
constructor(msgId = 0, timeStamp = 0, owner = "", objectGenericId = 0) {
super();
this.msgId = msgId;
this.timeStamp = timeStamp;
this.owner = owner;
this.objectGenericId = objectGenericId;
}
}
|
Joryss/cookietouch
|
src/cookie/protocol/network/messages/LivingObjectMessageMessage.ts
|
TypeScript
|
ClassDeclaration
|
export class Holder extends Entity {
constructor(id: string) {
super();
this.set("id", Value.fromString(id));
}
save(): void {
let id = this.get("id");
assert(id !== null, "Cannot save Holder entity without an ID");
assert(
id.kind == ValueKind.STRING,
"Cannot save Holder entity with non-string ID. " +
'Considering using .toHex() to convert the "id" to a string.'
);
store.set("Holder", id.toString(), this);
}
static load(id: string): Holder | null {
return store.get("Holder", id) as Holder | null;
}
get id(): string {
let value = this.get("id");
return value.toString();
}
set id(value: string) {
this.set("id", Value.fromString(value));
}
get address(): string {
let value = this.get("address");
return value.toString();
}
set address(value: string) {
this.set("address", Value.fromString(value));
}
get balance(): BigInt {
let value = this.get("balance");
return value.toBigInt();
}
set balance(value: BigInt) {
this.set("balance", Value.fromBigInt(value));
}
}
|
jasonliudan/erc20-holders-subgraph
|
generated/schema.ts
|
TypeScript
|
MethodDeclaration
|
save(): void {
let id = this.get("id");
assert(id !== null, "Cannot save Holder entity without an ID");
assert(
id.kind == ValueKind.STRING,
"Cannot save Holder entity with non-string ID. " +
'Considering using .toHex() to convert the "id" to a string.'
);
store.set("Holder", id.toString(), this);
}
|
jasonliudan/erc20-holders-subgraph
|
generated/schema.ts
|
TypeScript
|
MethodDeclaration
|
static load(id: string): Holder | null {
return store.get("Holder", id) as Holder | null;
}
|
jasonliudan/erc20-holders-subgraph
|
generated/schema.ts
|
TypeScript
|
ArrowFunction
|
() => (
<>
<Helmet>
<meta
property="description"
|
koriaf/tradetrust-website
|
src/pages/webinar.tsx
|
TypeScript
|
FunctionDeclaration
|
function getSchemaType(typeName: string): SchemaType | null {
const schemaMod = require('part:@sanity/base/schema')
const schema = schemaMod.default || schemaMod
const type = schema.get(typeName)
if (!type) return null
return type
}
|
Kaliber/sanity
|
packages/@sanity/desk-tool/src/panes/document/documentPanel/DocumentPanel.tsx
|
TypeScript
|
ArrowFunction
|
({$disabled}) => {
if ($disabled) {
return {height: '100%'}
}
return css`
height: 100%;
overflow: auto;
position: relative;
scroll-behavior: smooth;
outline: none;
`
}
|
Kaliber/sanity
|
packages/@sanity/desk-tool/src/panes/document/documentPanel/DocumentPanel.tsx
|
TypeScript
|
ArrowFunction
|
() => Boolean(getSchemaType(documentType)?.liveEdit)
|
Kaliber/sanity
|
packages/@sanity/desk-tool/src/panes/document/documentPanel/DocumentPanel.tsx
|
TypeScript
|
ArrowFunction
|
() => {
return {...value, _id: liveEdit ? 'dummy-id' : 'drafts.dummy-id'}
}
|
Kaliber/sanity
|
packages/@sanity/desk-tool/src/panes/document/documentPanel/DocumentPanel.tsx
|
TypeScript
|
ArrowFunction
|
() => views.find((view) => view.id === activeViewId) || views[0] || {type: 'form'}
|
Kaliber/sanity
|
packages/@sanity/desk-tool/src/panes/document/documentPanel/DocumentPanel.tsx
|
TypeScript
|
ArrowFunction
|
(view) => view.id === activeViewId
|
Kaliber/sanity
|
packages/@sanity/desk-tool/src/panes/document/documentPanel/DocumentPanel.tsx
|
TypeScript
|
ArrowFunction
|
() => {
if (layoutCollapsed) {
return [headerRect?.height || 0, 0, footerHeight ? footerHeight + 2 : 2, 0]
}
return [0, 0, 2, 0]
}
|
Kaliber/sanity
|
packages/@sanity/desk-tool/src/panes/document/documentPanel/DocumentPanel.tsx
|
TypeScript
|
ArrowFunction
|
() =>
activeView.type === 'component' &&
activeView.component &&
createElement(activeView.component, {
document: {
draft: editState?.draft || null,
displayed: displayed || value,
historical: displayed,
published: editState?.published || null,
},
documentId,
options: activeView.options,
schemaType: documentSchema,
})
|
Kaliber/sanity
|
packages/@sanity/desk-tool/src/panes/document/documentPanel/DocumentPanel.tsx
|
TypeScript
|
ArrowFunction
|
() => {
if (!documentScrollElement?.scrollTo) return
documentScrollElement.scrollTo(0, 0)
}
|
Kaliber/sanity
|
packages/@sanity/desk-tool/src/panes/document/documentPanel/DocumentPanel.tsx
|
TypeScript
|
InterfaceDeclaration
|
interface DocumentPanelProps {
footerHeight: number | null
rootElement: HTMLDivElement | null
}
|
Kaliber/sanity
|
packages/@sanity/desk-tool/src/panes/document/documentPanel/DocumentPanel.tsx
|
TypeScript
|
MethodDeclaration
|
Boolean(permissions?.granted)
|
Kaliber/sanity
|
packages/@sanity/desk-tool/src/panes/document/documentPanel/DocumentPanel.tsx
|
TypeScript
|
ArrowFunction
|
(डिफल्ट:
|
AugustinVoiMa/bitcoin
|
src/qt/locale/pizcoin_ne.ts
|
TypeScript
|
ClassDeclaration
|
@Component({
selector: 'dt-example-expandable-section-interactive',
templateUrl: 'expandable-section-interactive-example.html',
})
export class DtExampleExpandableSectionInteractive {
text = `Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et
dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum.
Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.
Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore
magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum.
Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.`;
sectionDisabled = false;
}
|
Dynatrace/barista
|
libs/examples/src/expandable-section/expandable-section-interactive-example/expandable-section-interactive-example.ts
|
TypeScript
|
ClassDeclaration
|
@Injectable({
providedIn: 'root'
})
export class ProductService {
constructor() { }
getProducts(): Product[]{
return PRODUCTS;
}
}
|
caiofellipe/app-nutricao
|
src/app/product/product.service.ts
|
TypeScript
|
MethodDeclaration
|
getProducts(): Product[]{
return PRODUCTS;
}
|
caiofellipe/app-nutricao
|
src/app/product/product.service.ts
|
TypeScript
|
FunctionDeclaration
|
export function Content({ selectedGenreId }: Props ) {
const [movies, setMovies] = useState<MovieProps[]>([]);
useEffect(() => {
api.get<MovieProps[]>(`movies/?Genre_id=${selectedGenreId}`).then(response => {
setMovies(response.data);
});
}, [selectedGenreId])
return (
<div className="movies-list">
{movies.map(movie => (
<MovieCard key ={movie.imdbID} title={movie.Title} poster={movie.Poster} runtime={movie.Runtime} rating={movie.Ratings[0].Value} />
))}
</div>
)
}
|
NatanaelPJ/Desafio-02---Componentizando-a-aplica-o
|
src/components/Content.tsx
|
TypeScript
|
ArrowFunction
|
() => {
api.get<MovieProps[]>(`movies/?Genre_id=${selectedGenreId}`).then(response => {
setMovies(response.data);
});
}
|
NatanaelPJ/Desafio-02---Componentizando-a-aplica-o
|
src/components/Content.tsx
|
TypeScript
|
ArrowFunction
|
response => {
setMovies(response.data);
}
|
NatanaelPJ/Desafio-02---Componentizando-a-aplica-o
|
src/components/Content.tsx
|
TypeScript
|
ArrowFunction
|
movie => (
<MovieCard key ={movie.imdbID}
|
NatanaelPJ/Desafio-02---Componentizando-a-aplica-o
|
src/components/Content.tsx
|
TypeScript
|
InterfaceDeclaration
|
interface MovieProps {
imdbID: string;
Title: string;
Poster: string;
Ratings: Array<{
Source: string;
Value: string;
}>;
Runtime: string;
}
|
NatanaelPJ/Desafio-02---Componentizando-a-aplica-o
|
src/components/Content.tsx
|
TypeScript
|
InterfaceDeclaration
|
interface Props {
selectedGenreId: number;
}
|
NatanaelPJ/Desafio-02---Componentizando-a-aplica-o
|
src/components/Content.tsx
|
TypeScript
|
ArrowFunction
|
({ circle, ...cardProps }: Props) => {
const viewer = useContext(ViewerContext)
const { displayName, description } = circle
const path = toPath({
page: 'circleDetail',
circle,
})
const showLoginToast = () => {
window.dispatchEvent(
new CustomEvent(ADD_TOAST, {
detail: {
color: 'green',
content: (
<Translate
zh_hant="請登入/註冊訂閱圍爐"
zh_hans="请登入/注册订阅围炉"
/>
),
customButton: <LoginButton isPlain />,
buttonPlacement: 'center',
},
}
|
at7211/matters-web
|
src/views/Follow/Feed/FollowingRecommendCircle/index.tsx
|
TypeScript
|
ArrowFunction
|
() => {
window.dispatchEvent(
new CustomEvent(ADD_TOAST, {
detail: {
color: 'green',
content: (
<Translate
zh_hant="請登入/註冊訂閱圍爐"
zh_hans="请登入/注册订阅围炉"
/>
),
customButton: <LoginButton isPlain />,
buttonPlacement: 'center',
}
|
at7211/matters-web
|
src/views/Follow/Feed/FollowingRecommendCircle/index.tsx
|
TypeScript
|
ArrowFunction
|
() =>
window.dispatchEvent(new CustomEvent(OPEN_SUBSCRIBE_CIRCLE_DIALOG, {}))
|
at7211/matters-web
|
src/views/Follow/Feed/FollowingRecommendCircle/index.tsx
|
TypeScript
|
ArrowFunction
|
({ circle: prevCircle }, { circle }) => {
return (
prevCircle.id === circle.id && prevCircle.isMember === circle.isMember
)
}
|
at7211/matters-web
|
src/views/Follow/Feed/FollowingRecommendCircle/index.tsx
|
TypeScript
|
TypeAliasDeclaration
|
type Props = {
circle: FollowingFeedRecommendCirclePublic &
FollowingFeedRecommendCirclePrivate
} & CardProps
|
at7211/matters-web
|
src/views/Follow/Feed/FollowingRecommendCircle/index.tsx
|
TypeScript
|
TypeAliasDeclaration
|
type MemoizedRecommendCircleType = React.MemoExoticComponent<
React.FC<Props>
> & {
fragments: typeof fragments
}
|
at7211/matters-web
|
src/views/Follow/Feed/FollowingRecommendCircle/index.tsx
|
TypeScript
|
ArrowFunction
|
async (context: $TSContext) => {
const inputParams = constructInputParams(context);
const projectPath = process.cwd();
if (inputParams.sandboxId) {
try {
await preDeployPullBackend(context, inputParams.sandboxId);
} catch (e) {
context.print.error(`Failed to pull sandbox app: ${e.message || 'An unknown error occurred.'}`);
showTroubleshootingURL();
}
return;
}
if (stateManager.currentMetaFileExists(projectPath)) {
const { appId: inputAppId, envName: inputEnvName } = inputParams.amplify;
const teamProviderInfo = stateManager.getTeamProviderInfo(projectPath);
const { envName } = stateManager.getLocalEnvInfo(projectPath);
const appId = _.get(teamProviderInfo, [envName, 'awscloudformation', 'AmplifyAppId'], false);
const localEnvNames = Object.keys(teamProviderInfo);
if (inputAppId && appId && inputAppId !== appId) {
context.print.error('Amplify appId mismatch.');
context.print.info(`You are currently working in the amplify project with Id ${appId}`);
await context.usageData.emitError(new AppIdMismatchError());
showTroubleshootingURL();
process.exit(1);
} else if (!appId) {
context.print.error(`Environment '${envName}' not found.`);
context.print.info(`Try running "amplify env add" to add a new environment.`);
context.print.info(`If this backend already exists, try restoring its definition in your team-provider-info.json file.`);
await context.usageData.emitError(new EnvironmentDoesNotExistError());
showTroubleshootingURL();
process.exit(1);
}
if (inputEnvName) {
if (inputEnvName === envName) {
await pullBackend(context, inputParams);
} else if (localEnvNames.includes(inputEnvName)) {
context.parameters.options = {};
context.parameters.first = inputEnvName;
await envCheckout(context);
} else {
inputParams.amplify.appId = inputAppId;
await attachBackend(context, inputParams);
}
} else {
await pullBackend(context, inputParams);
}
} else {
await attachBackend(context, inputParams);
}
}
|
Booligoosh/amplify-cli
|
packages/amplify-cli/src/commands/pull.ts
|
TypeScript
|
ArrowFunction
|
(demands: {[index: string]: number | undefined}): {[index: string]: number} =>
Object.keys(demands)
.reduce<{[index: string]: number}>((acc, k) => {
if (demands[k] !== undefined) {
acc[k] = demands[k] ?? 0
}
return acc
}, {})
|
xmakina/progressciv
|
src/utils/GenerateDemands.ts
|
TypeScript
|
ArrowFunction
|
(acc, k) => {
if (demands[k] !== undefined) {
acc[k] = demands[k] ?? 0
}
return acc
}
|
xmakina/progressciv
|
src/utils/GenerateDemands.ts
|
TypeScript
|
FunctionDeclaration
|
async function main(): Promise<void> {
await bot.launch();
for (let emote of registryV1.list) {
if (!emote.safe) continue;
if (!(await db.has(`emote_uploaded_file_id:${emote.id}`))) {
console.log('downloading', emote.ref);
let cachedData = await db.getOptional(`download:${emote.url}:data`, { asBuffer: true });
let cachedFileType = await db.getOptional(`download:${emote.url}:file_type`, {
asBuffer: false,
});
if (cachedData != null && cachedFileType != null) {
cachedData = databaseM.ensureBuffer(cachedData);
cachedFileType = databaseM.ensureString(cachedFileType);
} else {
let response = await fetch(emote.url, { agent });
if (!response.ok) {
throw new Error(`HTTP error: ${response.status} ${response.statusText}`);
}
cachedData = await response.buffer();
cachedFileType = response.headers.get('content-type') ?? 'application/octet-stream';
await db.set(`download:${emote.url}:data`, cachedData);
await db.set(`download:${emote.url}:file_type`, cachedFileType);
}
const IMAGEMAGICK_FORMAT_MAPPING = new Map<string, string>([
['image/png', 'png'],
['image/gif', 'gif'],
]);
console.log('processing', emote.ref);
let imagemagickFormat = IMAGEMAGICK_FORMAT_MAPPING.get(cachedFileType);
if (imagemagickFormat == null) {
throw new Error(`Unknown emote file type: ${cachedFileType}`);
}
// Apparently calling out to an ImageMagick subprocess is a viable method
// of image processing in JS.
let program = 'convert';
let args: string[] = [];
// read from stdin
args.push(`${imagemagickFormat}:-`);
// replace the background with black color
// <https://legacy.imagemagick.org/Usage/anim_mods/#remove_trans>
args.push('-coalesce', '-background', 'black');
// resize and fit into a 128x128 px square
args.push('-gravity', 'Center', '-resize', '128x128', '-extent', '128x128');
// add a 16px black border
args.push('-bordercolor', 'black', '-border', '16');
// <https://legacy.imagemagick.org/Usage/anim_basics/#types>
// <https://legacy.imagemagick.org/Usage/anim_basics/#overlay>
// <https://legacy.imagemagick.org/Usage/anim_opt/>
args.push('-layers', 'Optimize');
// write to stdout
args.push(`${imagemagickFormat}:-`);
// Again, the stupid insanely-hard-to-use stream APIs... I hope I did
// everything correctly here. Also, spawnSync can't be used for
// simplification because it is limited by a fixed buffer size, and if
// the size of subprocess'es output exceeds this buffer size, the whole
// operation fails with an exception. On the other hand, the async
// variant of spawn allows for unbounded input and output.
let processedImage: Buffer = await new Promise((resolve, reject) => {
let proc = subprocess.spawn(program, args, {
stdio: [/* stdin */ 'pipe', /* stdout */ 'pipe', /* stderr */ 'inherit'],
});
proc.on('error', (err: Error) => {
reject(err);
});
let chunks: Buffer[] = [];
proc.stdout.on('data', (data: Buffer) => {
chunks.push(data);
});
proc.stdout.on('error', (err: Error) => {
reject(err);
});
proc.on('close', (code: number | null) => {
if (code !== 0) {
reject(new Error(`Command failed with a non-zero exit code: ${code}`));
} else {
resolve(Buffer.concat(chunks));
}
});
proc.stdin.end(cachedData);
});
console.log('uploading', emote.ref);
let sendChatId = config.cdnChatId;
let sendInputFile: tt.InputFile = { source: processedImage };
let sendExtra = { caption: emote.id };
let fileId: string;
if (emote.animated) {
let msg: tt.Message.AnimationMessage = await telegramUtils.retryAfterRatelimit(() => {
return bot.telegram.sendAnimation(sendChatId, sendInputFile, sendExtra);
});
fileId = msg.animation.file_id;
} else {
let msg: tt.Message.PhotoMessage = await telegramUtils.retryAfterRatelimit(() => {
return bot.telegram.sendPhoto(sendChatId, sendInputFile, sendExtra);
});
fileId = msg.photo[0].file_id;
}
console.log('saving', emote.ref);
await db.set(`emote_uploaded_file_id:${emote.id}`, fileId);
}
}
console.log('done uploading emotes');
}
|
dmitmel/cc-emotes-telegram-bot
|
src/main.ts
|
TypeScript
|
ArrowFunction
|
async (ctx: TelegrafContext, next: () => Promise<void>): Promise<void> => {
let inlineQuery = ctx.inlineQuery!;
let page = parseInt(inlineQuery.offset, INLINE_QUERY_PAGE_NUMBER_BASE);
if (Number.isNaN(page)) page = 0;
let offset = page * INLINE_QUERY_PAGE_SIZE;
let limit = INLINE_QUERY_PAGE_SIZE;
let matchedEmotes: Array<{ emote: EmoteRegistryEntry; fileId: string }> = [];
let queryRegex = new RegExp(utils.escapeRegExp(inlineQuery.query), 'i');
let matchCounter = 0;
for (let emote of registryV1.list) {
if (matchedEmotes.length >= limit) break;
if (!emote.safe) continue;
if (!(queryRegex.test(emote.name) || queryRegex.test(emote.guild_name))) continue;
let fileId = await db.getOptional(`emote_uploaded_file_id:${emote.id}`, { asBuffer: false });
if (fileId == null) continue;
fileId = databaseM.ensureString(fileId);
if (matchCounter >= offset) {
matchedEmotes.push({ emote, fileId: fileId });
}
matchCounter++;
}
let queryDebugStr = JSON.stringify(inlineQuery.query);
console.log(
`search:${queryDebugStr} offset:${offset} limit:${limit} results:${matchedEmotes.length}`,
);
let results: tt.InlineQueryResult[] = matchedEmotes.map(({ emote, fileId }) => {
let id = `emote:${emote.id}`;
let caption = emote.name;
if (emote.animated) {
let result: tt.InlineQueryResultCachedGif = {
type: 'gif',
id,
title: caption,
caption,
gif_file_id: fileId,
};
return result;
} else {
let result: tt.InlineQueryResultCachedPhoto = {
type: 'photo',
id,
title: caption,
caption,
photo_file_id: fileId,
};
return result;
}
});
await ctx.answerInlineQuery(results, {
cache_time: 0,
is_personal: false,
next_offset: (page + 1).toString(INLINE_QUERY_PAGE_NUMBER_BASE),
});
return next();
}
|
dmitmel/cc-emotes-telegram-bot
|
src/main.ts
|
TypeScript
|
ArrowFunction
|
({ emote, fileId }) => {
let id = `emote:${emote.id}`;
let caption = emote.name;
if (emote.animated) {
let result: tt.InlineQueryResultCachedGif = {
type: 'gif',
id,
title: caption,
caption,
gif_file_id: fileId,
};
return result;
} else {
let result: tt.InlineQueryResultCachedPhoto = {
type: 'photo',
id,
title: caption,
caption,
photo_file_id: fileId,
};
return result;
}
}
|
dmitmel/cc-emotes-telegram-bot
|
src/main.ts
|
TypeScript
|
ArrowFunction
|
(resolve, reject) => {
let proc = subprocess.spawn(program, args, {
stdio: [/* stdin */ 'pipe', /* stdout */ 'pipe', /* stderr */ 'inherit'],
});
proc.on('error', (err: Error) => {
reject(err);
});
let chunks: Buffer[] = [];
proc.stdout.on('data', (data: Buffer) => {
chunks.push(data);
});
proc.stdout.on('error', (err: Error) => {
reject(err);
});
proc.on('close', (code: number | null) => {
if (code !== 0) {
reject(new Error(`Command failed with a non-zero exit code: ${code}`));
} else {
resolve(Buffer.concat(chunks));
}
});
proc.stdin.end(cachedData);
}
|
dmitmel/cc-emotes-telegram-bot
|
src/main.ts
|
TypeScript
|
ArrowFunction
|
(err: Error) => {
reject(err);
}
|
dmitmel/cc-emotes-telegram-bot
|
src/main.ts
|
TypeScript
|
ArrowFunction
|
(data: Buffer) => {
chunks.push(data);
}
|
dmitmel/cc-emotes-telegram-bot
|
src/main.ts
|
TypeScript
|
ArrowFunction
|
(code: number | null) => {
if (code !== 0) {
reject(new Error(`Command failed with a non-zero exit code: ${code}`));
} else {
resolve(Buffer.concat(chunks));
}
}
|
dmitmel/cc-emotes-telegram-bot
|
src/main.ts
|
TypeScript
|
ArrowFunction
|
() => {
return bot.telegram.sendAnimation(sendChatId, sendInputFile, sendExtra);
}
|
dmitmel/cc-emotes-telegram-bot
|
src/main.ts
|
TypeScript
|
ArrowFunction
|
() => {
return bot.telegram.sendPhoto(sendChatId, sendInputFile, sendExtra);
}
|
dmitmel/cc-emotes-telegram-bot
|
src/main.ts
|
TypeScript
|
InterfaceDeclaration
|
interface EmoteRegistry {
version: 1;
list: EmoteRegistryEntry[];
}
|
dmitmel/cc-emotes-telegram-bot
|
src/main.ts
|
TypeScript
|
InterfaceDeclaration
|
interface EmoteRegistryEntry {
ref: string;
id: string;
name: string;
requires_colons: boolean;
animated: boolean;
url: string;
safe: boolean;
guild_id: string;
guild_name: string;
}
|
dmitmel/cc-emotes-telegram-bot
|
src/main.ts
|
TypeScript
|
ArrowFunction
|
(user) => user.score
|
mohamed-marwane-bellagha/apicardgames
|
src/scores/model/entities/score.entity.ts
|
TypeScript
|
ArrowFunction
|
() => Partie
|
mohamed-marwane-bellagha/apicardgames
|
src/scores/model/entities/score.entity.ts
|
TypeScript
|
ArrowFunction
|
(partie) => partie.score
|
mohamed-marwane-bellagha/apicardgames
|
src/scores/model/entities/score.entity.ts
|
TypeScript
|
ClassDeclaration
|
@Index("iduser", ["iduser"], {})
@Index("idpartie", ["idpartie"], {})
@Entity("score", { schema: "jeux" })
export class Score {
@PrimaryGeneratedColumn({ type: "int", name: "id" })
public id: number;
@Column("int", { name: "score" })
public score: number;
@Column("int", { name: "iduser" })
public iduser: number;
@Column("int", { name: "idpartie" })
public idpartie: number;
@ManyToOne(() => User, (user) => user.score, {
onDelete: "CASCADE",
onUpdate: "CASCADE",
})
@JoinColumn([{ name: "iduser", referencedColumnName: "id" }])
public iduser2: User;
@ManyToOne(() => Partie, (partie) => partie.score, {
onDelete: "CASCADE",
onUpdate: "CASCADE",
})
@JoinColumn([{ name: "idpartie", referencedColumnName: "id" }])
public idpartie2: Partie;
}
|
mohamed-marwane-bellagha/apicardgames
|
src/scores/model/entities/score.entity.ts
|
TypeScript
|
InterfaceDeclaration
|
export interface ListPicker {
destroy: () => void;
}
|
yasir2000/brown-bear
|
src/scripts/lib/list-picker/src/type.ts
|
TypeScript
|
InterfaceDeclaration
|
export interface ListPickerOptions {
readonly locale?: string | undefined;
placeholder?: string;
is_filterable?: boolean;
none_value?: string | null;
items_template_formatter?: (
html: typeof HTMLTemplateStringProcessor,
value_id: string,
item_label: string
) => Promise<TemplateResult>;
keep_none_value?: boolean;
}
|
yasir2000/brown-bear
|
src/scripts/lib/list-picker/src/type.ts
|
TypeScript
|
InterfaceDeclaration
|
export interface ListPickerItem {
id: string;
template: TemplateResult;
label: string;
value: string;
is_disabled: boolean;
is_selected: boolean;
group_id: string;
element: Element;
target_option: HTMLOptionElement;
}
|
yasir2000/brown-bear
|
src/scripts/lib/list-picker/src/type.ts
|
TypeScript
|
InterfaceDeclaration
|
export interface LegacyColorRGB {
red: number;
green: number;
blue: number;
}
|
yasir2000/brown-bear
|
src/scripts/lib/list-picker/src/type.ts
|
TypeScript
|
InterfaceDeclaration
|
export interface ListPickerItemGroup {
id: string;
label: string;
root_element: Element;
list_element: Element;
}
|
yasir2000/brown-bear
|
src/scripts/lib/list-picker/src/type.ts
|
TypeScript
|
InterfaceDeclaration
|
export interface ListPickerComponent {
wrapper_element: HTMLElement;
list_picker_element: Element;
dropdown_element: HTMLElement;
selection_element: HTMLElement;
placeholder_element: Element;
dropdown_list_element: Element;
search_field_element: HTMLInputElement;
}
|
yasir2000/brown-bear
|
src/scripts/lib/list-picker/src/type.ts
|
TypeScript
|
InterfaceDeclaration
|
export interface ListPickerSelectionStateSingle {
selected_item: ListPickerItem;
selected_value_element: DocumentFragment;
}
|
yasir2000/brown-bear
|
src/scripts/lib/list-picker/src/type.ts
|
TypeScript
|
InterfaceDeclaration
|
export interface ListPickerSelectionStateMultiple {
selected_items: ListPickerItemMap;
selected_value_elements: Map<string, Element>;
}
|
yasir2000/brown-bear
|
src/scripts/lib/list-picker/src/type.ts
|
TypeScript
|
InterfaceDeclaration
|
export interface SelectionManager {
readonly processSelection: (element: Element) => void;
readonly initSelection: () => void;
readonly handleBackspaceKey: (event: KeyboardEvent) => void;
readonly resetAfterDependenciesUpdate: () => void;
}
|
yasir2000/brown-bear
|
src/scripts/lib/list-picker/src/type.ts
|
TypeScript
|
InterfaceDeclaration
|
export interface ScrollCoordinates {
x_position: number;
y_position: number;
}
|
yasir2000/brown-bear
|
src/scripts/lib/list-picker/src/type.ts
|
TypeScript
|
TypeAliasDeclaration
|
export type ListPickerItemMap = Map<string, ListPickerItem>;
|
yasir2000/brown-bear
|
src/scripts/lib/list-picker/src/type.ts
|
TypeScript
|
ArrowFunction
|
({ columns }: Row) => (
<div style={
|
miejs/pyrene
|
pyrene/src/components/Accordion/Accordion.examples.tsx
|
TypeScript
|
ArrowFunction
|
(column, index) => (
<div
style={
|
miejs/pyrene
|
pyrene/src/components/Accordion/Accordion.examples.tsx
|
TypeScript
|
ArrowFunction
|
(column1: string, column2: string, column3: string) => () => (
<div style={
|
miejs/pyrene
|
pyrene/src/components/Accordion/Accordion.examples.tsx
|
TypeScript
|
ArrowFunction
|
() => (
<div style={
|
miejs/pyrene
|
pyrene/src/components/Accordion/Accordion.examples.tsx
|
TypeScript
|
ArrowFunction
|
() => column1
|
miejs/pyrene
|
pyrene/src/components/Accordion/Accordion.examples.tsx
|
TypeScript
|
ArrowFunction
|
() => column2
|
miejs/pyrene
|
pyrene/src/components/Accordion/Accordion.examples.tsx
|
TypeScript
|
ArrowFunction
|
() => column3
|
miejs/pyrene
|
pyrene/src/components/Accordion/Accordion.examples.tsx
|
TypeScript
|
ArrowFunction
|
() => (
<>
<div>Categories
|
miejs/pyrene
|
pyrene/src/components/Accordion/Accordion.examples.tsx
|
TypeScript
|
ArrowFunction
|
() => <Placeholder />,
|
miejs/pyrene
|
pyrene/src/components/Accordion/Accordion.examples.tsx
|
TypeScript
|
ArrowFunction
|
() => (
<AccordionComponent
sections={[{
iconProps: ({ name: 'info', color: 'blue500' }),
renderContent: renderCustomAccordionContent,
title: renderCustomAccordionTitle('youtu.be:443', 'Excluded by destination domain', 'GET connect'),
}, {
iconProps: ({ name: 'info', color: 'blue500' }),
renderContent: renderCustomAccordionContent,
title: renderCustomAccordionTitle('https://youtu.be/', 'Excluded by destination domain', 'GET something'),
}, {
iconProps: ({ name: 'error', color: 'red500' }),
renderContent: renderCustomAccordionContent,
title: renderCustomAccordionTitle('www.youtu.com:443', 'Member of required user group', 'GET anything'),
}, {
iconProps: ({ name: 'resolved', color: 'green600' }),
renderContent: renderCustomAccordionContent,
title: renderCustomAccordionTitle('https://control.open.ch/docs', 'Member of required user group', 'GET request'),
}]}
/>
|
miejs/pyrene
|
pyrene/src/components/Accordion/Accordion.examples.tsx
|
TypeScript
|
TypeAliasDeclaration
|
type Column = {
width: string,
renderContent: () => React.ReactNode
};
|
miejs/pyrene
|
pyrene/src/components/Accordion/Accordion.examples.tsx
|
TypeScript
|
TypeAliasDeclaration
|
type Row = {
columns: Column[]
};
|
miejs/pyrene
|
pyrene/src/components/Accordion/Accordion.examples.tsx
|
TypeScript
|
MethodDeclaration
|
Entertainment<
|
miejs/pyrene
|
pyrene/src/components/Accordion/Accordion.examples.tsx
|
TypeScript
|
ArrowFunction
|
(theme: Theme) =>
createStyles({
root: {
width: "100%",
},
heading: {
fontSize: theme.typography.pxToRem(15),
flexBasis: "33.33%",
flexShrink: 0,
},
})
|
Kestava-keikkatyo/innoFrontend
|
src/pages/GigRequest/RequestInfo.tsx
|
TypeScript
|
ArrowFunction
|
() => {
const classes = useStyles()
const [expanded, setExpanded] = React.useState<string | false>(false)
const handleChange =
(panel: string) => (event: React.ChangeEvent<{}>, isExpanded: boolean) => {
setExpanded(isExpanded ? panel : false)
}
return (
<div className={classes.root}>
<Accordion
expanded={expanded === "panel1"}
onChange={handleChange("panel1")}
>
<AccordionSummary
expandIcon={<ExpandMoreIcon />}
aria-controls="panel1bh-content"
id="panel1bh-header"
>
<Typography className={classes.heading}>Corsair</Typography>
<Typography>Siivooja yrityksellemme</Typography>
</AccordionSummary>
<AccordionDetails>
<Typography variant="body2">
Etsimme siivoojaa kesäksi ajalle 1.5.2021 - 1.8.2021
</Typography>
</AccordionDetails>
<AccordionDetails>
<Typography variant="body2">
Tarkoituksena olisi löytää siivooja, jolla työkokemusta ainakin
2-vuotta
</Typography>
</AccordionDetails>
<AccordionDetails>
<Typography variant="body2">
Siivojan työ koostuu 8h päivistä, joissa käydään läpi omistamiamme
kiinteistöjen siivoamista
</Typography>
</AccordionDetails>
<AccordionDetails>
<Typography variant="body2">
Aikaisemmin meillä on työskennellyt Jarmo Test ja voisitko kysyä
onko hän vielä vapaana?
</Typography>
</AccordionDetails>
<AccordionDetails>
<Typography variant="body2">
Viestiä voi laittaa sähköpostiin: test@test.com ja Viestiä numeroon:
040 000 12
</Typography>
</AccordionDetails>
</Accordion>
</div>
|
Kestava-keikkatyo/innoFrontend
|
src/pages/GigRequest/RequestInfo.tsx
|
TypeScript
|
ArrowFunction
|
(panel: string) => (event: React.ChangeEvent<{}>, isExpanded: boolean) => {
setExpanded(isExpanded ? panel : false)
}
|
Kestava-keikkatyo/innoFrontend
|
src/pages/GigRequest/RequestInfo.tsx
|
TypeScript
|
ArrowFunction
|
(event: React.ChangeEvent<{}>, isExpanded: boolean) => {
setExpanded(isExpanded ? panel : false)
}
|
Kestava-keikkatyo/innoFrontend
|
src/pages/GigRequest/RequestInfo.tsx
|
TypeScript
|
MethodDeclaration
|
handleChange("panel1")
|
Kestava-keikkatyo/innoFrontend
|
src/pages/GigRequest/RequestInfo.tsx
|
TypeScript
|
FunctionDeclaration
|
export function buildIamBindingEntityKey({
binding,
projectName,
resource,
}: {
binding: cloudasset_v1.Schema$Binding;
projectName: string | undefined | null;
resource: string | undefined | null;
}) {
// There are no unique values returned from this result so use everything
// available to make the binding key unique.
const keyBuilders = ['binding'];
if (projectName) keyBuilders.push('project:' + projectName);
if (resource) keyBuilders.push('resource:' + resource);
if (binding.role) keyBuilders.push('role:' + binding.role);
if (binding.members)
keyBuilders.push('members:' + hashArray(binding.members));
if (binding.condition?.expression)
keyBuilders.push('condition:' + binding.condition.expression);
return keyBuilders.join('|');
}
|
Creativice-Oy/graph-google-cloud
|
src/steps/cloud-asset/converters.ts
|
TypeScript
|
FunctionDeclaration
|
export function createIamBindingEntity({
_key,
binding,
projectId,
projectName,
resource,
folders,
organization,
permissions,
}: {
_key: string;
binding: cloudasset_v1.Schema$Binding;
projectId?: string;
projectName?: string | null;
resource?: string | null;
folders?: string[] | null;
organization?: string | null;
permissions?: string[] | null;
}): BindingEntity {
const namePrefix = 'Role Binding for Resource: ';
return createGoogleCloudIntegrationEntity(binding, {
entityData: {
source: binding,
assign: {
_class: bindingEntities.BINDINGS._class,
_type: bindingEntities.BINDINGS._type,
_key,
name: snakeCase(namePrefix) + resource,
displayName: namePrefix + resource,
/**
* The full resource name of the resource associated with this IAM policy.
* Example: `//compute.googleapis.com/projects/my_project_123/zones/zone1/instances/instance1`.
* See [Cloud Asset Inventory Resource Name Format](https://cloud.google.com/asset-inventory/docs/resource-name-format)
* for more information. To search against the `resource`: * use a field query. Example: `resource:organizations/123`
*/
resource,
role: binding.role,
members: binding.members,
projectId,
projectName,
folders,
organization,
'condition.title': binding.condition?.title,
'condition.description': binding.condition?.description,
'condition.expression': binding.condition?.expression,
'condition.location': binding.condition?.location,
permissions: permissions,
readonly: permissions?.some((p) => !isReadOnlyPermission(p)) ?? true, // default to true if there are no permissions
},
},
}) as BindingEntity;
}
|
Creativice-Oy/graph-google-cloud
|
src/steps/cloud-asset/converters.ts
|
TypeScript
|
ArrowFunction
|
(p) => !isReadOnlyPermission(p)
|
Creativice-Oy/graph-google-cloud
|
src/steps/cloud-asset/converters.ts
|
TypeScript
|
InterfaceDeclaration
|
export interface BindingEntity extends Entity {
resource: string;
role: string;
members: string;
projectId: string;
projectName?: string;
folders?: string[];
organization?: string;
'condition.title': string;
'condition.description': string;
'condition.expression': string;
'condition.location': string;
readonly: boolean;
}
|
Creativice-Oy/graph-google-cloud
|
src/steps/cloud-asset/converters.ts
|
TypeScript
|
ArrowFunction
|
async (ctx) => {
const accounts = await ctx.web3.eth.getAccounts();
ctx.set('owner', accounts[0]);
ctx.set('bob', accounts[1]);
ctx.set('jane', accounts[2]);
ctx.set('zeroAddress', '0x0000000000000000000000000000000000000000');
}
|
SparkAssets/framework
|
packages/0xcert-ethereum-order-gateway-contracts/src/tests/transfer-instance-method-any-taker/transfer-erc20s.test.ts
|
TypeScript
|
ArrowFunction
|
async (ctx) => {
const jane = ctx.get('jane');
const zxc = await ctx.deploy({
src: '@0xcert/ethereum-erc20-contracts/build/token-mock.json',
contract: 'TokenMock',
args: ['ERC20', 'ERC', 18, '300000000000000000000000000'],
from: jane,
});
ctx.set('zxc', zxc);
}
|
SparkAssets/framework
|
packages/0xcert-ethereum-order-gateway-contracts/src/tests/transfer-instance-method-any-taker/transfer-erc20s.test.ts
|
TypeScript
|
ArrowFunction
|
async (ctx) => {
const jane = ctx.get('jane');
const bnb = await ctx.deploy({
src: '@0xcert/ethereum-erc20-contracts/build/token-mock.json',
contract: 'TokenMock',
args: ['ERC20', 'ERC', 18, '300000000000000000000000000'],
from: jane,
});
ctx.set('bnb', bnb);
}
|
SparkAssets/framework
|
packages/0xcert-ethereum-order-gateway-contracts/src/tests/transfer-instance-method-any-taker/transfer-erc20s.test.ts
|
TypeScript
|
ArrowFunction
|
async (ctx) => {
const bob = ctx.get('bob');
const gnt = await ctx.deploy({
src: '@0xcert/ethereum-erc20-contracts/build/token-mock.json',
contract: 'TokenMock',
args: ['ERC20', 'ERC', 18, '300000000000000000000000000'],
from: bob,
});
ctx.set('gnt', gnt);
}
|
SparkAssets/framework
|
packages/0xcert-ethereum-order-gateway-contracts/src/tests/transfer-instance-method-any-taker/transfer-erc20s.test.ts
|
TypeScript
|
ArrowFunction
|
async (ctx) => {
const bob = ctx.get('bob');
const omg = await ctx.deploy({
src: '@0xcert/ethereum-erc20-contracts/build/token-mock.json',
contract: 'TokenMock',
args: ['ERC20', 'ERC', 18, '300000000000000000000000000'],
from: bob,
});
ctx.set('omg', omg);
}
|
SparkAssets/framework
|
packages/0xcert-ethereum-order-gateway-contracts/src/tests/transfer-instance-method-any-taker/transfer-erc20s.test.ts
|
TypeScript
|
ArrowFunction
|
async (ctx) => {
const tokenProxy = await ctx.deploy({
src: '@0xcert/ethereum-proxy-contracts/build/token-transfer-proxy.json',
contract: 'TokenTransferProxy',
});
ctx.set('tokenProxy', tokenProxy);
}
|
SparkAssets/framework
|
packages/0xcert-ethereum-order-gateway-contracts/src/tests/transfer-instance-method-any-taker/transfer-erc20s.test.ts
|
TypeScript
|
ArrowFunction
|
async (ctx) => {
const tokenProxy = ctx.get('tokenProxy');
const owner = ctx.get('owner');
const orderGateway = await ctx.deploy({
src: './build/order-gateway.json',
contract: 'OrderGateway',
});
await orderGateway.instance.methods.grantAbilities(owner, OrderGatewayAbilities.SET_PROXIES).send();
await orderGateway.instance.methods.addProxy(tokenProxy.receipt._address).send({ from: owner });
ctx.set('orderGateway', orderGateway);
}
|
SparkAssets/framework
|
packages/0xcert-ethereum-order-gateway-contracts/src/tests/transfer-instance-method-any-taker/transfer-erc20s.test.ts
|
TypeScript
|
ArrowFunction
|
async (ctx) => {
const tokenProxy = ctx.get('tokenProxy');
const orderGateway = ctx.get('orderGateway');
const owner = ctx.get('owner');
await tokenProxy.instance.methods.grantAbilities(orderGateway.receipt._address, TokenTransferProxyAbilities.EXECUTE).send({ from: owner });
}
|
SparkAssets/framework
|
packages/0xcert-ethereum-order-gateway-contracts/src/tests/transfer-instance-method-any-taker/transfer-erc20s.test.ts
|
TypeScript
|
ArrowFunction
|
async (ctx) => {
const orderGateway = ctx.get('orderGateway');
const tokenProxy = ctx.get('tokenProxy');
const jane = ctx.get('jane');
const bob = ctx.get('bob');
const zeroAddress = ctx.get('zeroAddress');
const zxc = ctx.get('zxc');
const gnt = ctx.get('gnt');
const zxcAmount = 3000;
const gntAmount = 50000;
const actions = [
{
kind: 1,
proxy: 0,
token: zxc.receipt._address,
from: jane,
to: zeroAddress,
value: zxcAmount,
},
{
kind: 1,
proxy: 0,
token: gnt.receipt._address,
from: zeroAddress,
to: jane,
value: gntAmount,
},
];
const orderData = {
maker: jane,
taker: zeroAddress,
actions,
seed: common.getCurrentTime(),
expiration: common.getCurrentTime() + 600,
};
const orderDataTuple = ctx.tuple(orderData);
const claim = await orderGateway.instance.methods.getOrderDataClaim(orderDataTuple).call();
const signature = await ctx.web3.eth.sign(claim, jane);
const signatureData = {
r: signature.substr(0, 66),
s: `0x${signature.substr(66, 64)}`,
v: parseInt(`0x${signature.substr(130, 2)}`) + 27,
kind: 0,
};
const signatureDataTuple = ctx.tuple(signatureData);
await zxc.instance.methods.approve(tokenProxy.receipt._address, zxcAmount).send({ from: jane });
await gnt.instance.methods.approve(tokenProxy.receipt._address, gntAmount).send({ from: bob });
const logs = await orderGateway.instance.methods.performAnyTaker(orderDataTuple, signatureDataTuple).send({from: bob});
ctx.not(logs.events.Perform, undefined);
const bobBalance = await zxc.instance.methods.balanceOf(bob).call();
const janeBalance = await gnt.instance.methods.balanceOf(jane).call();
ctx.is(bobBalance, zxcAmount.toString());
ctx.is(janeBalance, gntAmount.toString());
}
|
SparkAssets/framework
|
packages/0xcert-ethereum-order-gateway-contracts/src/tests/transfer-instance-method-any-taker/transfer-erc20s.test.ts
|
TypeScript
|
ArrowFunction
|
async (ctx) => {
const orderGateway = ctx.get('orderGateway');
const tokenProxy = ctx.get('tokenProxy');
const jane = ctx.get('jane');
const bob = ctx.get('bob');
const zeroAddress = ctx.get('zeroAddress');
const zxc = ctx.get('zxc');
const gnt = ctx.get('gnt');
const bnb = ctx.get('bnb');
const omg = ctx.get('omg');
const zxcAmount = 500;
const gntAmount = 30;
const bnbAmount = 1;
const omgAmount = 5;
const actions = [
{
kind: 1,
proxy: 0,
token: zxc.receipt._address,
from: jane,
to: zeroAddress,
value: zxcAmount,
},
{
kind: 1,
proxy: 0,
token: bnb.receipt._address,
from: jane,
to: zeroAddress,
value: bnbAmount,
},
{
kind: 1,
proxy: 0,
token: gnt.receipt._address,
from: zeroAddress,
to: jane,
value: gntAmount,
},
{
kind: 1,
proxy: 0,
token: omg.receipt._address,
from: zeroAddress,
to: jane,
value: omgAmount,
},
];
const orderData = {
maker: jane,
taker: zeroAddress,
actions,
seed: common.getCurrentTime(),
expiration: common.getCurrentTime() + 600,
};
const orderDataTuple = ctx.tuple(orderData);
const claim = await orderGateway.instance.methods.getOrderDataClaim(orderDataTuple).call();
const signature = await ctx.web3.eth.sign(claim, jane);
const signatureData = {
r: signature.substr(0, 66),
s: `0x${signature.substr(66, 64)}`,
v: parseInt(`0x${signature.substr(130, 2)}`) + 27,
kind: 0,
};
const signatureDataTuple = ctx.tuple(signatureData);
await zxc.instance.methods.approve(tokenProxy.receipt._address, zxcAmount).send({ from: jane });
await bnb.instance.methods.approve(tokenProxy.receipt._address, bnbAmount).send({ from: jane });
await gnt.instance.methods.approve(tokenProxy.receipt._address, gntAmount).send({ from: bob });
await omg.instance.methods.approve(tokenProxy.receipt._address, omgAmount).send({ from: bob });
const logs = await orderGateway.instance.methods.performAnyTaker(orderDataTuple, signatureDataTuple).send({from: bob});
ctx.not(logs.events.Perform, undefined);
const bobZxcBalance = await zxc.instance.methods.balanceOf(bob).call();
const bobBnbBalance = await bnb.instance.methods.balanceOf(bob).call();
const janeGntBalance = await gnt.instance.methods.balanceOf(jane).call();
const janeOmgBalance = await omg.instance.methods.balanceOf(jane).call();
ctx.is(bobZxcBalance, zxcAmount.toString());
ctx.is(bobBnbBalance, bnbAmount.toString());
ctx.is(janeGntBalance, gntAmount.toString());
ctx.is(janeOmgBalance, omgAmount.toString());
}
|
SparkAssets/framework
|
packages/0xcert-ethereum-order-gateway-contracts/src/tests/transfer-instance-method-any-taker/transfer-erc20s.test.ts
|
TypeScript
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.