Datasets:

blob_id
large_stringlengths
40
40
language
large_stringclasses
1 value
repo_name
large_stringlengths
5
119
path
large_stringlengths
4
271
score
float64
2.52
4.84
int_score
int64
3
5
text
stringlengths
26
4.09M
ec065383b6699ed13b44c05cf03ccc12f8997cca
TypeScript
diosney/node-iproute
/src/commands/link/virtual-link-types/erspan-ip6erspan.interfaces.ts
2.828125
3
import { ErspanDirections } from '../../link.constants'; /** * Add link erspan & IP6 erspan type arguments. * @category Interfaces */ export interface AddLinkErspanIp6erspanTypeArgs { /** Specifies the remote address of the tunnel. */ remote: string; /** * Specifies the fixed local address for tunneled packets. * It must be an address on another interface on this host. */ local: string; /** * Enable sequence numbering of ERSPAN packets. * This can be useful for detecting packet loss. */ seq: true; /** A 32-bit key to identify the GRE tunnel. */ key: number; /** * TODO: Add an enum for validator? * * Specifies the ERSPAN version number. * `version` indicates the ERSPAN version to be created: * * 0 for version 0 type I, * 1 for version 1 (type II) * or 2 for version 2 (type III). */ erspan_ver: number; /** * Specifies the ERSPAN v1 index field. * IDX indicates a 20 bit index/port number associated with the ERSPAN * traffic's source port and direction. */ erspan?: number; /** Specifies the ERSPAN v2 mirrored traffic's direction. */ erspan_dir?: ErspanDirections; /** * A unique identifier of an ERSPAN v2 engine within a system. * `hwid` is a 6-bit value for users to configure. */ erspan_hwid?: number; /** Specifies whether to allow remote endpoint to have an address configured on local host. */ 'allow-localremote'?: boolean; /** @see {@link['allow-localremote']} */ 'noallow-localremote'?: boolean; /** * Make this tunnel externally controlled (or not, which is the default). * * In the kernel, this is referred to as collect metadata mode. * This flag is mutually exclusive with the {@link remote}, {@link local}, {@link erspan_ver}, * {@link erspan}, {@link erspan_dir} and {@link erspan_hwid} options. */ external?: true; }
85c65533bf00711559ea313d0ef51a2b2829f80a
TypeScript
exportarts/ngx-prismic
/libs/universal/src/lib/routes.ts
2.90625
3
import { PrismicDocument } from '@prismicio/types'; import { getPrismicUids, resolveDocumentIds } from './prismic-uids'; import { RouteConfig, DEFAULT_EXTRA_OPTIONS, PrismicRoute } from './routes.model'; /** * Loads all documents with the provided doc types from Prismic, * maps them with the provided mapping function and returns an array * of routes that may be used for prerendering. * * @param config Configuration to resolve and return all routes * @param options Specify optional configuration */ export async function getRoutes(config: RouteConfig, options = DEFAULT_EXTRA_OPTIONS): Promise<PrismicRoute[]> { options.logFunc('Starting to collect routes\n'); config.includeDocumentData = config.includeDocumentData || false; const prismicRoutes: PrismicRoute[] = []; for (const docTypeConfig of config.docTypeConfigs) { let documents: PrismicDocument[] = []; if (Array.isArray(config.documentIds) && config.documentIds.length) { const resolved = await resolveDocumentIds({ repositoryName: config.repositoryName, documentIds: config.documentIds, includeDocumentData: config.includeDocumentData, additionalConfig: config.additionalConfig }); documents = resolved.filter(doc => doc.type === docTypeConfig.documentType); if (documents.length) { options.logFunc(`Resolved ${documents.length} document(s) by their ids:`); for (const document of documents) { options.logFunc(`${document.id} => ${document.uid}`); } } else { options.logFunc(`Did not find any documents of type "${docTypeConfig.documentType}" with the provided ids: ${JSON.stringify(config.documentIds)}`); } } else { documents = await getPrismicUids( config.repositoryName, docTypeConfig.documentType, config.includeDocumentData, config.additionalConfig ); } const mappedRoutes = documents.map(doc => { let resolvedRouteOrRoutes = docTypeConfig.uidMappingFunc(doc.uid, doc); if (!Array.isArray(resolvedRouteOrRoutes)) { resolvedRouteOrRoutes = [resolvedRouteOrRoutes]; } const resolvedRoutes: PrismicRoute[] = resolvedRouteOrRoutes.map(route => ({ route, doc })); return resolvedRoutes; }); const flattenedMappedRoutes = flatten(mappedRoutes) prismicRoutes.push(...flattenedMappedRoutes); options.logFunc(`Found ${mappedRoutes.length} routes for document type "${docTypeConfig.documentType}"`); } options.logFunc(`Found ${prismicRoutes.length} total routes\n`); return Promise.resolve(prismicRoutes); } /** * Flattens an array up to the specified depth. * * Use recursion, decrementing depth by 1 for each level of depth. * Use Array.prototype.reduce() and Array.prototype.concat() to merge * elements or arrays. Base case, for depth equal to 1 stops recursion. * Omit the second argument, depth to flatten only to a depth of 1 (single flatten). * * From: https://30secondsofcode.org/#flatten */ function flatten(arr, depth = 1) { return arr.reduce((a, v) => a.concat(depth > 1 && Array.isArray(v) ? flatten(v, depth - 1) : v), []); }
93a7b71dc73723bc484ac9f5d427fd570ce13d22
TypeScript
zachweintraub/tap-room
/src/app/price.pipe.ts
2.671875
3
import { Pipe, PipeTransform } from '@angular/core'; import { Keg } from './models/keg.model'; @Pipe({ name: "price", pure: false }) export class PricePipe implements PipeTransform { transform(input: Keg[], desiredPrice) { let output: Keg[] = []; if(desiredPrice == "budget"){ for(let i = 0; i < input.length; i++){ if(input[i].price <= 5){ output.push(input[i]); } } } else if (desiredPrice == "premium"){ for(let i = 0; i < input.length; i++){ if(input[i].price > 5){ output.push(input[i]); } } } else { output = input; } return output; } }
3e9a90f315c01f281a7de7dff31e5491cc8e9694
TypeScript
LiamWiddop/__old__study
/server/entities/diagnostic.ts
2.578125
3
import {Entity, PrimaryGeneratedColumn, Column, OneToMany, OneToOne, JoinColumn, BaseEntity, ManyToMany} from "typeorm"; import disease from "./disease"; @Entity() export default class Diagnostic extends BaseEntity { @PrimaryGeneratedColumn() id: number; @Column({ default: "" }) name: string; @Column({ default: "" }) description: string; @ManyToMany(type => disease, disease => disease.diagnostic) disease: disease[]; }
75863ce7a25708256b894a975379532fad88509d
TypeScript
htoooth/typescript-study
/src/test9/main.ts
2.828125
3
import Express from './Express'; function main() { let a = Express.of(3) let b = Express.of(4) let c = Express.of(5) let d = Express.of(6) let e = Express.of(a, '+', b) let f = Express.of(c, '-', d) let g = Express.of(e, '*', f) let h = Express.of(f, '/', g) console.log(h.toString(), ' = ', h.calculate()) } main()
5a35bff392855fea95947cd84fb134f7e88b4586
TypeScript
WIStudent/rxjs-examples
/01-example.ts
2.84375
3
import {from} from 'rxjs'; // Observable that emits 1 to 3 const observable = from([1,2,3]); const subscription = observable.subscribe({ next(value) { console.log(value); }, complete() { console.log('complete') }, error(e) { console.log(e) } });
7a12cef1631d2475dcb8fc41cd601f9751978571
TypeScript
BisiDavi/reminisce
/server/src/controllers/posts.ts
2.5625
3
import express, { Request, Response } from "express"; import mongoose from "mongoose"; import { IPost } from "../types"; import { PostMessage } from "../imports"; const router = express.Router(); export const getPosts = async (req: Request, res: Response): Promise<any> => { try { const postMessages = await PostMessage.find({}); res.status(200).json(postMessages); } catch (error) { res.status(404).json({ message: error.message }); } }; export const getPost = async (req: Request, res: Response): Promise<any> => { const { id } = req.params; try { const post = await PostMessage.findById(id); res.status(200).json(post); } catch (error) { res.status(404).json({ message: error.message }); } }; export const createPost = async (req: Request, res: Response) => { const { title, message, selectedFile, creator, tags }: IPost = req.body; const newPost = new PostMessage({ title, message, selectedFile, creator, tags }); try { await newPost.save(); res.status(201).json(newPost); } catch (error) { res.status(409).json({ message: error.message }); } }; export const updatePost = async (req: any, res: any): Promise<any> => { const { id } = req.params; const { title, message, creator, selectedFile, tags }: IPost = req.body; if (!mongoose.Types.ObjectId.isValid(id)) { return res.status(404).send(`No post with idL ${id}`); } const updatedPost = { creator, title, message, tags, selectedFile, _id: id }; await PostMessage.findByIdAndUpdate(id, updatedPost, { new: true }); res.json(updatedPost); }; export const deletePost = async (req: Request, res: Response) => { const { id } = req.params; if (!mongoose.Types.ObjectId.isValid(id)) { return res.status(404).send(`No post with id: ${id}`); } await PostMessage.findByIdAndRemove(id); res.json({ message: "Post deleted successfully" }); }; export const likePost = async (req: Request, res: Response): Promise<any> => { const { id } = req.params; if (!mongoose.Types.ObjectId.isValid(id)) { return res.status(404).send(`No post with id: ${id}`); } const post: any = await PostMessage.findById(id); const updatedPost = await PostMessage.findByIdAndUpdate( id, { likeCount: post.likeCount + 1 }, { new: true } ); res.json(updatedPost); }; export default router;
a82b2fdaaa5efa28649cbe84d74d73dc32479066
TypeScript
xmtrinidad/Ionic-N10-007
/src/data/resources.ts
2.609375
3
import { Resource } from '../models/resource'; export const RESOURCES: Resource[] = [ { "objectiveNumber": "1.1", "title": "Introduction to IP", "description": "We rely on IP as the fundamental protocol on today’s networks. In this video, you’ll learn about the fundamentals of IP, TCP, UDP, and ICMP.", "img": "https://i.ytimg.com/vi/M5c9HdaQqh0/maxresdefault.jpg", "link": "https://www.youtube.com/watch?v=M5c9HdaQqh0" }, { "objectiveNumber": "1.1", "title": "Common Ports", "description": "As you manage your network devices, you’ll notice that certain port numbers will be commonly used. In this video, you’ll learn about these common TCP and UDP ports and how to recognize applications that are using these well-known port numbers.", "img": "https://i.ytimg.com/vi/vp_ZxQ0CTJk/maxresdefault.jpg", "link": "https://www.youtube.com/watch?v=vp_ZxQ0CTJk" }, { "objectiveNumber": "1.2", "title": "Understanding the OSI Model", "description": "The OSI model is one of the most common methods of describing application data flows. In this video, you’ll learn about the seven layers of the OSI model and how they are associated with real-world hardware and software components.", "img": "https://i.ytimg.com/vi/G7aVKgGUe9c/maxresdefault.jpg", "link": "https://www.youtube.com/watch?v=G7aVKgGUe9c" }, { "objectiveNumber": "1.3", "title": "Introduction to Ethernet", "description": "Ethernet is the most common network topology in the world. In this video, you’ll learn the fundamentals of how Ethernet communicates from one device to another and how half-duplex and full-duplex configuration can effect this data transfer.", "img": "https://i.ytimg.com/vi/iXfBbs9SSFQ/maxresdefault.jpg", "link": "https://www.youtube.com/watch?v=iXfBbs9SSFQ" }, { "objectiveNumber": "1.3", "title": "Network Switching Overview", "description": "The network switch is perhaps the most common piece of networking equipment in use today. In this video, you’ll learn how the switch makes forwarding decisions, how the switch reacts when it doesn’t know the destination of a frame, and how the ARP command can be used to validate a switch’s forwarding table.", "img": "https://i.ytimg.com/vi/jR3VoKZWJyc/maxresdefault.jpg", "link": "https://www.youtube.com/watch?v=jR3VoKZWJyc" }, { "objectiveNumber": "1.3", "title": "Broadcast Domains and Collision Domains", "description": "A foundational knowledge of network architecture starts with the concepts of broadcast domains and collision domains. In this video, you’ll learn how modern network design has eliminated collision domains and how you can minimize the impact of broadcasts through the use of properly engineered broadcast domains.", "img": "https://i.ytimg.com/vi/SGbtLjIEVeo/maxresdefault.jpg", "link": "https://www.youtube.com/watch?v=SGbtLjIEVeo" }, { "objectiveNumber": "1.3", "title": "Unicasts, Broadcasts, and Multicasts", "description": "There are many different ways to communicate across the network. In this video, you’ll compare the differences between unicasts, broadcasts, and multicasts.", "img": "https://i.ytimg.com/vi/jotgabyT-uI/maxresdefault.jpg", "link": "https://www.youtube.com/watch?v=jotgabyT-uI" }, { "objectiveNumber": "1.3", "title": "Protocol Data Units", "description": "PDUs are the building blocks of network communication. In this video, you’ll learn about protocol data units and how they are used at different layers of the OSI model.", "img": "https://i.ytimg.com/vi/3RQW9s-aB6k/maxresdefault.jpg", "link": "https://www.youtube.com/watch?v=3RQW9s-aB6k" }, { "objectiveNumber": "1.3", "title": "Network Segmentation", "description": "We commonly use network segmentation technologies to provide security and separation between logical areas of the network. In this video, you’ll learn about physical segmentation, logical VLAN segmentation, and 802.1Q VLAN trunking.", "img": "https://i.ytimg.com/vi/9L4qDmvKPjQ/maxresdefault.jpg", "link": "https://www.youtube.com/watch?v=9L4qDmvKPjQ" }, { "objectiveNumber": "1.3", "title": "Spanning Tree Protocol", "description": "We rely on STP to prevent loops on our switched networks. In this video, you’ll learn the fundamentals of Spanning Tree Protocol and how STP reacts when changes occur to the network.", "img": "https://i.ytimg.com/vi/mLCpdsOZM9c/maxresdefault.jpg", "link": "https://www.youtube.com/watch?v=mLCpdsOZM9c" }, { "objectiveNumber": "1.3", "title": "Switch Interface Properties", "description": "There are many different options available when configuring an interface on a switch. In this video, you’ll learn about basic interface settings, VLAN configurations, power over Ethernet, and much more.", "img": "https://i.ytimg.com/vi/dqQny4UXiX0/maxresdefault.jpg", "link": "https://www.youtube.com/watch?v=dqQny4UXiX0" }, { "objectiveNumber": "1.3", "title": "Static and Dynamic Routing", "description": "A network administrator has many options for configuring and maintaining the routing table between layer 3 devices. In this video, you’ll learn about static routing, dynamic routing, and default routes.", "img": "https://i.ytimg.com/vi/YRzr56cwgCg/maxresdefault.jpg", "link": "https://www.youtube.com/watch?v=YRzr56cwgCg" }, { "objectiveNumber": "1.3", "title": "IGP and EGP", "description": "Choosing a dynamic routing protocol is an important network design consideration. In this video, you’ll learn about autonomous systems, interior gateway protocols, and exterior gateway protocols.", "img": "https://i.ytimg.com/vi/14s-M01m1fQ/maxresdefault.jpg", "link": "https://www.youtube.com/watch?v=14s-M01m1fQ" }, { "objectiveNumber": "1.3", "title": "Dynamic Routing Protocols", "description": "Different dynamic routing protocols use different criteria to determine which route is really the best. In this video, you’ll learn the differences between distance-vector, link-state, and hybrid routing protocols.", "img": "https://i.ytimg.com/vi/9390huk39mU/maxresdefault.jpg", "link": "https://www.youtube.com/watch?v=9390huk39mU" }, { "objectiveNumber": "1.3", "title": "IPv4 and IPv6 Addressing", "description": "You’ll be working with IPv4 and IPv6 throughout your networking career. In this video, you’ll learn about the structure of an IPv4 address and an IPv6 address, and you’ll learn how to compress and uncompress IPv6 addresses.", "img": "https://i.ytimg.com/vi/U2IxdEYgoEg/maxresdefault.jpg", "link": "https://www.youtube.com/watch?v=U2IxdEYgoEg" }, { "objectiveNumber": "1.3", "title": "Configuring IPv6", "description": "IPv6 has a number of differences from traditional IPv4. In this video, you’ll learn about dual-stack routing, IPv6 tunneling protocols, and the many uses of the IPv6 Neighbor Discovery Protocol.", "img": "https://i.ytimg.com/vi/NhRjwjt2Aog/maxresdefault.jpg", "link": "https://www.youtube.com/watch?v=NhRjwjt2Aog" }, { "objectiveNumber": "1.3", "title": "Prioritizing Traffic", "description": "Most organizations are using many different applications, and certain applications will have a higher priority than others. In this video, you’ll learn how to prioritize this traffic as it traverses the network using packet shaping and quality of service options in your routers and switches.", "img": "https://i.ytimg.com/vi/uEKDZqI5osA/maxresdefault.jpg", "link": "https://www.youtube.com/watch?v=uEKDZqI5osA" }, { "objectiveNumber": "1.3", "title": "Network Address Translation", "description": "We rely on NAT for our Internet access and to allow external access to our internal services. In this video, you’ll learn about private IP addresses, port address translation, and port forwarding.", "img": "https://i.ytimg.com/vi/JAYpfBvGVI8/maxresdefault.jpg", "link": "https://www.youtube.com/watch?v=JAYpfBvGVI8" }, { "objectiveNumber": "1.3", "title": "Access Control Lists", "description": "Access control lists are used as packet filtering mechanisms on our enterprise networks. In this video, you’ll learn about ACLs and how they can be used to protect services on our networks.", "img": "https://i.ytimg.com/vi/6Yj1-pZmHvY/maxresdefault.jpg", "link": "https://www.youtube.com/watch?v=6Yj1-pZmHvY" }, { "objectiveNumber": "1.3", "title": "Circuit Switching and Packet Switching", "description": "There are many different ways to get data from one end of the network to the other. In this video, you’ll learn about some of the popular technologies that use circuit switching and packet switching.", "img": "https://i.ytimg.com/vi/uBpacYBwYwM/maxresdefault.jpg", "link": "https://www.youtube.com/watch?v=uBpacYBwYwM" }, { "objectiveNumber": "1.3", "title": "Software-Defined Networking", "description": "SDN has changed the way we design and implement services on modern networks. In this video, you’ll get an overview of SDN and how you can use distributed switching to virtualize your network.", "img": "https://i.ytimg.com/vi/EdVOeGDYHCU/maxresdefault.jpg", "link": "https://www.youtube.com/watch?v=EdVOeGDYHCU" }, { "objectiveNumber": "1.4", "title": "Binary Math", "description": "You’ll work with binary throughout your career, and you’ll often need to convert between binary and decimal values. In this video, you’ll learn my shortcut for quickly performing binary to decimal conversions.", "img": "https://i.ytimg.com/vi/mIbNZzoWE3k/maxresdefault.jpg", "link": "https://www.youtube.com/watch?v=mIbNZzoWE3k" }, { "objectiveNumber": "1.4", "title": "IPv4 Addresses", "description": "Configuring IPv4 is more than just a single IP address. In this video, you’ll learn about the structure of an IPv4 address and the important configuration options to use IPv4 on your network.", "img": "https://i.ytimg.com/vi/aEMtAFvouNU/maxresdefault.jpg", "link": "https://www.youtube.com/watch?v=aEMtAFvouNU" }, { "objectiveNumber": "1.4", "title": "Classful Subnetting", "description": "The first step in learning to subnet IPv4 is to understand the starting point. In this video, you’ll learn about IP classes and how to quickly calculate network values from an IP address and subnet mask.", "img": "https://i.ytimg.com/vi/GxE395bCANM/maxresdefault.jpg", "link": "https://www.youtube.com/watch?v=GxE395bCANM" }, { "objectiveNumber": "1.4", "title": "IPv4 Subnet Masks", "description": "An important skill when working with IP subnets is the ability to quickly translate between dotted-decimal notation and CIDR-block notation. In this video, you’ll learn how to quickly calculate these subnet mask notations.", "img": "https://i.ytimg.com/vi/L3dsWxn5RBU/maxresdefault.jpg", "link": "https://www.youtube.com/watch?v=L3dsWxn5RBU" }, { "objectiveNumber": "1.4", "title": "IPv6 Subnet Masks", "description": "Subnetting an IPv6 network is a bit less involved than IPv4. In this video, you’ll learn how to quickly configure IPv6 subnets for your network.", "img": "https://i.ytimg.com/vi/8IqXQ88QXfc/maxresdefault.jpg", "link": "https://www.youtube.com/watch?v=8IqXQ88QXfc" }, { "objectiveNumber": "1.4", "title": "Calculating IPv4 Subnets and Hosts", "description": "The process of subnetting an IPv4 address can be calculated quickly with powers of two. In this video, you’ll learn how to quickly calculate the number of IP subnets and hosts per IP subnet.", "img": "https://i.ytimg.com/vi/qQEaAb_p8_E/maxresdefault.jpg", "link": "https://www.youtube.com/watch?v=qQEaAb_p8_E" }, { "objectiveNumber": "Seven Second Subnetting", "title": "Professor Messer", "description": "", "img": "https://i.ytimg.com/vi/ZxAwQB8TZsM/maxresdefault.jpg", "link": "https://www.youtube.com/watch?v=ZxAwQB8TZsM" }, { "objectiveNumber": "1.4", "title": "Assigning IPv4 Addresses", "description": "There are many different ways to configure a device with an IPv4 address. In this video, you’ll learn about DHCP, manual addressing, DHCP reservations, and APIPA.", "img": "https://i.ytimg.com/vi/Q0Aq_cYBcR0/maxresdefault.jpg", "link": "https://www.youtube.com/watch?v=Q0Aq_cYBcR0" }, { "objectiveNumber": "1.4", "title": "Assigning IPv6 Addresses", "description": "The IPv6 addressing of a device has similarities to IPv4, but there are also some significant differences. In this video, you’ll learn about DHCPv6 and how to modify a MAC address for use as a static IP address.", "img": "https://i.ytimg.com/vi/lfCFsniHsPk/maxresdefault.jpg", "link": "https://www.youtube.com/watch?v=lfCFsniHsPk" }, { "objectiveNumber": "1.5", "title": "Network Topologies", "description": "We often reference our network topologies as standard types, such as star, ring, and mesh. In this video, you’ll learn about physical and logical network documentation using these standard network topologies.", "img": "https://i.ytimg.com/vi/4nPnQVaRj4k/maxresdefault.jpg", "link": "https://www.youtube.com/watch?v=4nPnQVaRj4k" }, { "objectiveNumber": "1.5", "title": "Common Network Types", "description": "We use a number of different network types throughout our day. In this video, you’ll learn about the different network types that are used to get our data across the Internet.", "img": "https://i.ytimg.com/vi/BrGirZH0FzQ/maxresdefault.jpg", "link": "https://www.youtube.com/watch?v=BrGirZH0FzQ" }, { "objectiveNumber": "1.5", "title": "Internet of Things Topologies", "description": "We’re connecting an increasing number of devices to the Internet. These Internet of Things topologies are similar to traditional networks, but there are some important differences when compared to traditional networks. In this video, you’ll learn about some of the more popular IoT topologies, such as Z-Wave, ANT+, NFC, and more.", "img": "https://i.ytimg.com/vi/g9F5FauEWL4/maxresdefault.jpg", "link": "https://www.youtube.com/watch?v=g9F5FauEWL4" }, { "objectiveNumber": "1.6", "title": "Wireless Standards", "description": "There have been many 802.11 wireless standards through the years. In this video, you’ll learn about the differences between 802.11a, 802.11b, 802.11g, 802.11n, and 802.11ac.", "img": "https://i.ytimg.com/vi/r3pZ0WYSk9g/maxresdefault.jpg", "link": "https://www.youtube.com/watch?v=r3pZ0WYSk9g" }, { "objectiveNumber": "1.6", "title": "Cellular Network Standards", "description": "Cellular networks are complex technologies that have been made easy enough for everyone to use. In this video, you’ll learn about GSM, CDMA and LTE cellular technologies.", "img": "https://i.ytimg.com/vi/GShWfJH6p2c/maxresdefault.jpg", "link": "https://www.youtube.com/watch?v=GShWfJH6p2c" }, { "objectiveNumber": "1.6", "title": "Wireless Network Technologies", "description": "802.11 wireless network technologies are many and varied. In this video, you’ll learn about 802.11 frequency use, MIMO, MU-MIMO, power levels, antenna types, and more.", "img": "https://i.ytimg.com/vi/eV9Mu3njz_M/maxresdefault.jpg", "link": "https://www.youtube.com/watch?v=eV9Mu3njz_M" }, { "objectiveNumber": "1.7", "title": "Cloud Services and Delivery Models", "description": "The cloud has become an integrated part of today’s networks. In this video, you’ll learn about various cloud delivery models and how to manage cloud security policies.", "img": "https://i.ytimg.com/vi/iiUbTb3s1xc/maxresdefault.jpg", "link": "https://www.youtube.com/watch?v=iiUbTb3s1xc" }, { "objectiveNumber": "1.8", "title": "An Overview of DNS", "description": "Domain Name Services provide an important conversion between FQDN and IP address. In this video, you’ll learn about the process that DNS uses to resolve a fully-qualified domain name to an IP address.", "img": "https://i.ytimg.com/vi/VqQQMXNhZBM/maxresdefault.jpg", "link": "https://www.youtube.com/watch?v=VqQQMXNhZBM" }, { "objectiveNumber": "1.8", "title": "DNS Record Types", "description": "DNS uses many different resource record types for network name services. In this video, you’ll learn about the DNS forward lookup file and some of the most common DNS record types.", "img": "https://i.ytimg.com/vi/D37RhTJ0ALY/maxresdefault.jpg", "link": "https://www.youtube.com/watch?v=D37RhTJ0ALY" }, { "objectiveNumber": "1.8", "title": "DHCP Addressing Overview", "description": "We rely on DHCP for the automatic configuration of our network devices. In this video, you’ll learn about the four steps of the DHCP process and how a DHCP relay can provide flexibility with DHCP services.", "img": "https://i.ytimg.com/vi/uLJpp8HFNBc/maxresdefault.jpg", "link": "https://www.youtube.com/watch?v=uLJpp8HFNBc" }, { "objectiveNumber": "1.8", "title": "Configuring DHCP", "description": "There are many options when configuring a DHCP server. In this video, you’ll learn about DHCP scopes, address allocation options, address reservations, and DHCP lease timers.", "img": "https://i.ytimg.com/vi/pEDFFH0Y4C4/maxresdefault.jpg", "link": "https://www.youtube.com/watch?v=pEDFFH0Y4C4" }, { "objectiveNumber": "1.8", "title": "An Overview of NTP", "description": "We rely on NTP to synchronize the clocks on all of our network-connected devices. In this video, you’ll learn about NTP servers, NTP clients, and how to configure NTP options on your workstation.", "img": "https://i.ytimg.com/vi/1GtySPUW-XA/maxresdefault.jpg", "link": "https://www.youtube.com/watch?v=1GtySPUW-XA" }, { "objectiveNumber": "2.1", "title": "Copper Cabling", "description": "Copper cables are the foundation of our networks, but not every copper cable is the same. In this video, you’ll learn about unshielded and shielded twisted pair, network cabling standards, and different types of network cabling.", "img": "https://i.ytimg.com/vi/v9m6uBaKD2s/maxresdefault.jpg", "link": "https://www.youtube.com/watch?v=v9m6uBaKD2s" }, { "objectiveNumber": "2.1", "title": "Copper Connectors", "description": "There are many different ways to connect copper cable to your networking equipment. In this video, you’ll learn about RJ11, RJ45, BNC, DB-9/DB-25, and F connectors.", "img": "https://i.ytimg.com/vi/_MF8oQdTCgo/maxresdefault.jpg", "link": "https://www.youtube.com/watch?v=_MF8oQdTCgo" }, { "objectiveNumber": "2.1", "title": "Optical Fiber", "description": "Optical fiber operates with very different physics than copper cabling. In this video, you’ll learn about multimode fiber, single-mode fiber, and the difference between UPC and APC connections.", "img": "https://i.ytimg.com/vi/_AnY7JMKVCg/maxresdefault.jpg", "link": "https://www.youtube.com/watch?v=_AnY7JMKVCg" }, { "objectiveNumber": "2.1", "title": "Optical Fiber Connectors", "description": "The connector types between fiber-connected devices can vary. In this video, you’ll learn about ST, SC, LC, and MT-RJ fiber connectors.", "img": "https://i.ytimg.com/vi/WyMNUdi0ZRM/maxresdefault.jpg", "link": "https://www.youtube.com/watch?v=WyMNUdi0ZRM" }, { "objectiveNumber": "2.1", "title": "Copper Termination Standards", "description": "Once you’ve picked your copper cabling, you’ll need to terminate it properly. In this video, you’ll learn about the different standards associated with copper cabling.", "img": "https://i.ytimg.com/vi/jaUww4A8LeU/maxresdefault.jpg", "link": "https://www.youtube.com/watch?v=jaUww4A8LeU" }, { "objectiveNumber": "2.1", "title": "Network Termination Points", "description": "Most network designs follow similar methods to connect the end stations to the network. In this video, you’ll learn about patch panels, punch-down blocks, patch panels, and fiber distribution panels.", "img": "https://i.ytimg.com/vi/QYdYnF-YUG8/maxresdefault.jpg", "link": "https://www.youtube.com/watch?v=QYdYnF-YUG8" }, { "objectiveNumber": "2.1", "title": "Network Transceivers", "description": "Transceivers can provide options when connecting infrastructure equipment to the network. In this video, you’ll learn about transceiver technology, duplex and bi-directional transceivers, GBICs, SFP/SFP+, and QSFP transceivers.", "img": "https://i.ytimg.com/vi/UTu5bz6qgkw/maxresdefault.jpg", "link": "https://www.youtube.com/watch?v=UTu5bz6qgkw" }, { "objectiveNumber": "2.1", "title": "Ethernet Standards", "description": "The IEEE maintains Ethernet standards that apply to many different speeds and media. In this video, you’ll learn about 100BASE-TX, 1000BASE-T, 1000BASE-SX, 1000BASE-LX, and 10GBASE-T standards.", "img": "https://i.ytimg.com/vi/X8MofnwqOSI/maxresdefault.jpg", "link": "https://www.youtube.com/watch?v=X8MofnwqOSI" }, { "objectiveNumber": "2.2", "title": "Networking Devices", "description": "If you walk into multiple data centers, you’ll probably start to see some similarities. In this video, you’ll learn about some of the most common network devices on today’s networks.", "img": "https://i.ytimg.com/vi/kKKm5InEmH8/maxresdefault.jpg", "link": "https://www.youtube.com/watch?v=kKKm5InEmH8" }, { "objectiveNumber": "2.3", "title": "Advanced Networking Devices", "description": "Some networking environments are highly specialized. In this video, you’ll learn about devices that provide unique solutions for today’s networks.", "img": "https://i.ytimg.com/vi/5i3yxEksaiU/maxresdefault.jpg", "link": "https://www.youtube.com/watch?v=5i3yxEksaiU" }, { "objectiveNumber": "2.4", "title": "Virtual Networking", "description": "Now that we’ve virtualized the data center, what happens to the network? In this video, you’ll learn about network virtualization deployment strategies.", "img": "https://i.ytimg.com/vi/CQsGjPWasAI/maxresdefault.jpg", "link": "https://www.youtube.com/watch?v=CQsGjPWasAI" }, { "objectiveNumber": "2.4", "title": "Network Storage", "description": "There are many ways to provide access to storage across the network. In this video, you’ll learn about Fibre Channel, iSCSI, InfiniBand, and more.", "img": "https://i.ytimg.com/vi/41OgCdAjLI4/maxresdefault.jpg", "link": "https://www.youtube.com/watch?v=41OgCdAjLI4" }, { "objectiveNumber": "2.5", "title": "WAN Services", "description": "You have many options when connecting WAN services. In this video, you’ll learn about T1, ISDN, DSL, and other WAN connectivity options.", "img": "https://i.ytimg.com/vi/7JUpUDYUSxY/maxresdefault.jpg", "link": "https://www.youtube.com/watch?v=7JUpUDYUSxY" }, { "objectiveNumber": "2.5", "title": "WAN Transmission Mediums", "description": "Which WAN medium are you using? In this video, you’ll learn about satellite, copper, fiber, and wireless WAN options.", "img": "https://i.ytimg.com/vi/aCoSDXdg68A/maxresdefault.jpg", "link": "https://www.youtube.com/watch?v=aCoSDXdg68A" }, { "objectiveNumber": "2.5", "title": "WAN Technologies", "description": "Our choice of wide area network technologies can depend on the type of connection. In this video, you’ll learn about Frame Relay, ATM, MPLS, DMVPN, SIP trunking, and much more.", "img": "https://i.ytimg.com/vi/byENdIkwBpA/maxresdefault.jpg", "link": "https://www.youtube.com/watch?v=byENdIkwBpA" }, { "objectiveNumber": "2.5", "title": "WAN Termination", "description": "Once a WAN connection has made it’s way across the country or the world, it needs a place to terminate. In this video, you’ll learn about demarcation points, CSU/DSU connectivity, and smartjacks.", "img": "https://i.ytimg.com/vi/LYzvM6i14wI/maxresdefault.jpg", "link": "https://www.youtube.com/watch?v=LYzvM6i14wI" }, { "objectiveNumber": "3.1", "title": "Network Documentation", "description": "If you’re managing a network, having the right documentation can save you both time and money. In this video, you’ll learn about network documentation, change management, cable management, and more.", "img": "https://i.ytimg.com/vi/Q5wv592XxlE/maxresdefault.jpg", "link": "https://www.youtube.com/watch?v=Q5wv592XxlE" }, { "objectiveNumber": "3.2", "title": "Availability Concepts", "description": "Keeping all of your systems and networks running is one of the most important tasks for a network administrator. In this video, you’ll learn about fault tolerance, redundancy, and high availability.", "img": "https://i.ytimg.com/vi/g36k1zgYuu4/maxresdefault.jpg", "link": "https://www.youtube.com/watch?v=g36k1zgYuu4" }, { "objectiveNumber": "3.2", "title": "Power Management", "description": "Maintaining a power source is obviously important for maintaining uptime and availability. In this video, you’ll learn about UPS devices, generators, and dual-power supplies.", "img": "https://i.ytimg.com/vi/ujhX3iSJXD8/maxresdefault.jpg", "link": "https://www.youtube.com/watch?v=ujhX3iSJXD8" }, { "objectiveNumber": "3.2", "title": "Recovery Sites", "description": "When a disaster strikes, you’ll need to establish a new base of operation. In this video, you’ll learn about cold sites, warm sites, and hot sites.", "img": "https://i.ytimg.com/vi/8Y-ykV42R_M/maxresdefault.jpg", "link": "https://www.youtube.com/watch?v=8Y-ykV42R_M" }, { "objectiveNumber": "3.2", "title": "Backup and Recovery", "description": "Always have a good backup. In this video, you’ll learn about the archive bit, incremental backups, and differential backups.", "img": "https://i.ytimg.com/vi/68hbHE6Zk4g/maxresdefault.jpg", "link": "https://www.youtube.com/watch?v=68hbHE6Zk4g" }, { "objectiveNumber": "3.3", "title": "Process Monitoring", "description": "There are many different ways to monitor the processes running across your network. In this video, you’ll learn about log management, port scanning, patch management, and much more.", "img": "https://i.ytimg.com/vi/ThXm2qbFIH8/maxresdefault.jpg", "link": "https://www.youtube.com/watch?v=ThXm2qbFIH8" }, { "objectiveNumber": "3.3", "title": "Event Management", "description": "An important part of network management is the handling of events and alerts. In this video, you’ll learn how to monitor interfaces, gather SNMP statistics, walk a MIB, and much more.", "img": "https://i.ytimg.com/vi/DjDfL3ic5Qo/maxresdefault.jpg", "link": "https://www.youtube.com/watch?v=DjDfL3ic5Qo" }, { "objectiveNumber": "3.3", "title": "Performance Metrics", "description": "Interface statistics can provide you with information about the overall health of a network connection. In this video, you’ll learn about interface monitoring methods and which interface metrics can provide information about performance and availability.", "img": "https://i.ytimg.com/vi/7jBtOw1-3ow/maxresdefault.jpg", "link": "https://www.youtube.com/watch?v=7jBtOw1-3ow" }, { "objectiveNumber": "3.4", "title": "Remote Access", "description": "You have many options when accessing devices remotely. In this video, you’ll learn about VPN options, transferring files, managing devices remotely, and more.", "img": "https://i.ytimg.com/vi/34ldGdtlvmk/maxresdefault.jpg", "link": "https://www.youtube.com/watch?v=34ldGdtlvmk" }, { "objectiveNumber": "3.5", "title": "Policies and Best Practices", "description": "Every organization uses numerous processes and procedures during the normal course of business. In this video, you’ll learn about user agreements, on-boarding, licensing, export controls, and many other policies.", "img": "https://i.ytimg.com/vi/D5ukHdq_JOk/maxresdefault.jpg", "link": "https://www.youtube.com/watch?v=D5ukHdq_JOk" } ];
f2fc9605f0b728059f67da836273f11bf7494416
TypeScript
gsanta/silhouette-people
/tests/QuadraticLineEquation.test.ts
2.9375
3
import { QuadraticLineEquation } from "../src/model/math/QuadraticLineEquation"; describe('Solving quadratic equation', () => { it ('gives two roots', () => { const quadratic = new QuadraticLineEquation(2, -5, -3); expect(quadratic.solve()).toEqual([3, - 0.5]); }); it ('gives one root if zero discriminant', () => { const quadratic = new QuadraticLineEquation(1, 4, 4); expect(quadratic.solve()).toEqual([-2, undefined]); }); it ('gives undefined when denominator is zero', () => { const quadratic = new QuadraticLineEquation(0, 4, 4); expect(quadratic.solve()).toEqual(undefined); }); });
b967932c2b31a1689666f497c9948eb370620193
TypeScript
Pjaerr/Politico-Final-Year-Project
/src/systems/GameDataManager/GameDataManager.ts
2.71875
3
import IGameDataManager from "./IGameDataManager"; import IGameData from "../../interfaces/IGameData"; import IProvince from "../../interfaces/IProvince"; import Provinces from "../../data/Provinces"; import { generateRandomPopulation, generateRandomHappiness, generateRandomPopulationDensity, generateRandomNumberOfUniversities, generateRandomAverageSalary, generateRandomNonWhiteBritishEthnicPercentage, randomNumber, getPoliticalLeaning, getPoliticalLeaningAsString } from "../../utils/utils"; import IAttributes from "../../interfaces/IAttributes"; import { DecisionConsequences, FinancialImpact, ForeignApproval, PoliticalLeaning } from "../../interfaces/IDecision"; const generateProvinces = (): Promise<IProvince[]> => { return new Promise((resolve, reject) => { const provinces: IProvince[] = []; let partyMembers = 0; const maxPartyMembers = 6; for (const { name } of Provinces) { let isInParty = false; //1 in 6 chance that this province is in the party if ((randomNumber(0, 6) === 5) && partyMembers < maxPartyMembers) { partyMembers++; isInParty = true; } let province = { name, population: generateRandomPopulation(), happiness: generateRandomHappiness(), isInParty, politicalLeaning: PoliticalLeaning.Centre, factors: { populationDensity: generateRandomPopulationDensity(), numberOfUniversities: generateRandomNumberOfUniversities(), averageSalary: generateRandomAverageSalary(), nonWhiteBritishEthnicPercentage: generateRandomNonWhiteBritishEthnicPercentage() } }; provinces.push(province); } let politicalLeaningPromises: Promise<number>[] = []; provinces.forEach(province => { politicalLeaningPromises.push(getPoliticalLeaning(province)); }); Promise.all(politicalLeaningPromises).then((politicalLeaningPromiseResults) => { politicalLeaningPromiseResults.forEach((politicalLeaning, index) => { provinces[index].politicalLeaning = politicalLeaning; }); resolve(provinces); }).catch(reject); }); }; const generateAttributes = (): IAttributes => { return { financial: 70, populationHappiness: 30, domesticPoliticalFavour: 50, foreignPoliticalFavour: 80 }; }; class GameDataManager implements IGameDataManager { financialImpactMap = new Map<FinancialImpact, number>([ [FinancialImpact.VeryNegative, -40], [FinancialImpact.Negative, -20], [FinancialImpact.Neutral, 0], [FinancialImpact.Positive, 10], [FinancialImpact.VeryPositive, 20], ]); foreignApprovalMap = new Map<ForeignApproval, number>([ [ForeignApproval.VeryNegative, -40], [ForeignApproval.Negative, -20], [ForeignApproval.Neutral, 0], [ForeignApproval.Positive, 10], [ForeignApproval.VeryPositive, 20], ]); getFreshGameData(): Promise<IGameData> { return new Promise((resolve, reject) => { generateProvinces().then(provinces => { resolve({ turn: 0, attributes: generateAttributes(), provinces }); }).catch(reject); }) }; updateGameData(currentGameData: IGameData, consequences: DecisionConsequences): Promise<IGameData> { return new Promise<IGameData>((resolve, reject) => { let updatedGameData = currentGameData; console.log(consequences); //Work out numeric adjustments to be made let financialImpact = this.financialImpactMap.get(consequences.financialImpact); let foreignApproval = this.foreignApprovalMap.get(consequences.foreignApproval); if (financialImpact) updatedGameData.attributes.financial += financialImpact; if (foreignApproval) updatedGameData.attributes.foreignPoliticalFavour += foreignApproval; if (updatedGameData.attributes.financial > 100) updatedGameData.attributes.financial = 100; if (updatedGameData.attributes.foreignPoliticalFavour) updatedGameData.attributes.foreignPoliticalFavour = 100; let happiness = currentGameData.attributes.populationHappiness; let domesticPoliticalFavour = currentGameData.attributes.domesticPoliticalFavour; currentGameData.provinces.forEach(province => { const difference = Math.abs(province.politicalLeaning - consequences.politicalLeaning) * 0.01; //Manual hard-coded values let happinessAdjustment = 0; if (difference === 0) { happinessAdjustment = 2.5; } else if (difference > 0 && difference <= 0.15) { happinessAdjustment = 1 } else if (difference > 0.15 && difference <= 0.25) { happinessAdjustment = 0.5 } else if (difference > 0.25 && difference <= 0.5) { happinessAdjustment = -0.5 } else if (difference > 0.5 && difference <= 0.75) { happinessAdjustment = -1; } else if (difference === 1) { happinessAdjustment = -5; } //If we want to scale by province population //Get the province with the highest population count //Get the province with the lowest population count //Map these counts in a range from 0 to 2 //Multiply happinessAdjustment by the result of the range map. happiness += happinessAdjustment; if (province.isInParty) { domesticPoliticalFavour += happinessAdjustment; } }); if (happiness > 100) happiness = 100; if (domesticPoliticalFavour > 100) domesticPoliticalFavour = 100; updatedGameData.attributes.populationHappiness = happiness; updatedGameData.attributes.domesticPoliticalFavour = domesticPoliticalFavour; resolve(updatedGameData); }); } }; export default GameDataManager;
02c28fadd4289606ee4f0c44872919650baa56ea
TypeScript
fabioparra/TypeScript
/tests/cases/fourslash/quickInfoOnCircularTypes.ts
2.65625
3
/// <reference path='fourslash.ts' /> ////interface A { (): B; }; ////declare var a: A; ////var xx = a(); //// ////interface B { (): C; }; ////declare var b: B; ////var yy = b(); //// ////interface C { (): A; }; ////declare var c: C; ////var zz = c(); //// ////x/*B*/x = y/*C*/y; goTo.marker('B'); verify.quickInfoIs('var xx: B'); goTo.marker('C'); verify.quickInfoIs('var yy: C');
dedca15d48e09dae0242327a48ae1bbee4aa2a99
TypeScript
adamfitzpatrick/tslint-stylish
/src/ruleFailure.ts
2.59375
3
/// <reference path="../typings/stylish.d.ts" /> var _ = require("lodash"); type IPalantirRuleFailureObject = Stylish.IPalantirRuleFailureObject; type IRuleFailureObject = Stylish.IRuleFailureObject; type IPosition = Stylish.IPosition; class RuleFailure { protected fileName: string; protected ruleName: string; protected failure: string; protected startPosition: Stylish.IPosition; protected endPosition: Stylish.IPosition; public static ruleFailureFactory(linterOutputArray: IPalantirRuleFailureObject[]): RuleFailure[]; public static ruleFailureFactory(linterOutputArray: IRuleFailureObject[]): RuleFailure[]; public static ruleFailureFactory(linterOutputArray: any[]): RuleFailure[] { return _.map(linterOutputArray, (lint) => new RuleFailure(lint)); } constructor(ruleFailure: IPalantirRuleFailureObject); constructor(ruleFailure: IRuleFailureObject); constructor(ruleFailure: any) { this.fileName = ruleFailure.fileName; this.ruleName = ruleFailure.ruleName; this.failure = ruleFailure.failure; if (ruleFailure.startPosition.lineAndCharacter) { var start = ruleFailure.startPosition; this.startPosition = { position: start.position, line: start.lineAndCharacter.line, character: start.lineAndCharacter.character }; var end = ruleFailure.endPosition; this.endPosition = { position: end.position, line: end.lineAndCharacter.line, character: end.lineAndCharacter.character }; } else { this.startPosition = ruleFailure.startPosition; this.endPosition = ruleFailure.endPosition; } } public getFileName(): string { return this.fileName; } public getRuleName(): string { return this.ruleName; } public getFailure(): string { return this.failure; } public getStartPosition(): IPosition { return this.startPosition; } public getEndPosition(): IPosition { return this.endPosition; } } export = RuleFailure;
8440d031cd0c0100ed8fcbcbcfbc0159cf6aec4b
TypeScript
musings-sphere/micro-hermes
/src/types/loggerService.d.ts
2.71875
3
export declare type LogLevel = "log" | "error" | "warn" | "debug" | "verbose"; export interface LoggerService { log(message: any, context?: string): any; error(message: any, trace?: string, context?: string): any; warn(message: any, context?: string): any; debug?(message: any, context?: string): any; verbose?(message: any, context?: string): any; }
931c2d30680e5fc7b63578ad78c2870436319317
TypeScript
Regesh/full-ngrx-store
/src/app/reducers/router.reducer.ts
2.875
3
import { RouterActionTypes } from '../actions/router'; export interface State { data:any[] } const initialState: State = { data: [] }; export function reducer( state: State = initialState, action: any ): State { switch (action.type) { case RouterActionTypes.pageLoaded: return { data: action.payload } default: return state; } } export const getPageData = (state: State) => state.data;
365c7826d3910d43a4de6f404b0ab84d6563c2a1
TypeScript
mrobinson242/AngularWeatherApplication
/src/app/services/darkSky.service.ts
2.59375
3
import { Injectable, EventEmitter, Output } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Injectable() export class DarkSkyService { // Create JsonData private jsonData: any; // Form Information private state: string; private city: string; private currentLocation: any; private lat: string; private lon: string; // Emitters @Output() darkSkyEmitter = new EventEmitter<any>(); @Output() modalEmitter = new EventEmitter<any>(); /** * Constructor */ constructor(private http: HttpClient){} /** * getDarkSkyData - Request to get data from Dark Sky API * * @param form */ getDarkSkyData(data) { // Get Latitude/Longitude this.lat = data.lat; this.lon = data.lon; // Form URL var url = 'http://octofire.us-east-2.elasticbeanstalk.com/darkSky/?lat=' + this.lat + '&lon=' + this.lon; // Subscribe to Node.js Request this.http.get(url).subscribe(data => { // Set Forecast Data this.jsonData = data; // Publish Data to Subscribers this.darkSkyEmitter.emit(this.jsonData); }); } /** * getModalData * * @param lat * @param lon */ getModalData(lat, lon, time) { // Form URL var url = 'http://octofire.us-east-2.elasticbeanstalk.com/modal/?lat=' + lat + '&lon=' + lon +'&time=' + time; // Subscribe to Node.js Request this.http.get(url).subscribe(data => { // Publish Data to Subscribers this.modalEmitter.emit(data); }); } /** * setFormInfo - Sets the * * @param data */ setFormInfo(city, state) { // Update Form Info this.state = state; this.city = city; } /** * setCurrentLocation - Sets the State of the Current Location CheckBox * * @param currentLocation */ setCurrentLocation(currentLocation) { this.currentLocation = currentLocation; } // Getters getCity() { return this.city; } getState() { return this.state; } getData() { return this.jsonData; } getCurrentLocation() { return this.currentLocation;} getLatitude() { return this.lat; } getLongitude() { return this.lon; } }
83298538edd0876eda5495117469d9da42b98ce9
TypeScript
adinstruments/LightningDeviceSDK
/examples/devices/MentalabExplore/settings.ts
2.59375
3
import { UnitPrefix, IDeviceSetting, IDeviceProxySettingsSys, IDeviceStreamApi, IProxyDevice, DeviceValueType, IDeviceStreamConfiguration } from '../../../public/device-api'; import { UnitsInfo16Bit, UnitsInfoImpl } from '../../../public/device-units'; import { Setting } from '../../../public/device-settings'; export interface IProxyDeviceImpl extends IProxyDevice { settings: DeviceSettings; /** * This is an implementation method, not directly called by Quark. Exposed * here so that the DeviceSettings can call it on their ProxyDevice. * This updates the quark settings. ProxyDeviceSys is the connection to the * proxy device in Quark. * * Quark will then calls the function returned by applyStreamSettingsToHW, * which will send the same settings to the hardware * * @param {number} streamIndex * @param {StreamSettings} streamSettings * @param {Partial<IDeviceStreamConfiguration>} config * @param {boolean} restartAnySampling */ updateStreamSettings( streamIndex: number, streamSettings: IDeviceStreamApi | undefined, config: Partial<IDeviceStreamConfiguration>, restartAnySampling: boolean ): void; } const kSettingsVersion = 1; const kDefaultDecimalPlaces = 3; export const kDefaultNumExGSignals = 8; export const kNumberEnvironmentSignals = 3; const kNumberGyroSignals = 3; const kNumberAccSignals = 3; const kNumberMagSignals = 3; const kNumberTempSignals = 1; const kNumberLightSignals = 1; const kNumberBatterySignals = 1; export const kNumberOfOrientationSignals = kNumberAccSignals + kNumberGyroSignals + kNumberMagSignals; //Stream index value that means the setting is the same across //all EXGStreams, e.g. for this device, the sample rate. export const kAllEXGStreams = -1; // 1000 Hz is currently experimental (23/9/2020) export const kSupportedEXGSamplesPerSec = [/*1000,*/ 500, 250]; export const kDefaultEXGSamplesPerSecIndex = 1; //250 Hz export const kDefaultEXGSamplesPerSec = kSupportedEXGSamplesPerSec[kDefaultEXGSamplesPerSecIndex]; export function findClosestSupportedRateIndex(samplesPerSec: number) { //Assumes kSupportedEXGSamplesPerSec is in descending order. If there is no exact match //use the closest rate < samplesPerSec. const result = kSupportedEXGSamplesPerSec.findIndex( (value) => value <= samplesPerSec ); if (result < 0) { return kSupportedEXGSamplesPerSec.length - 1; } return result; } export function findClosestSupportedRate(samplesPerSec: number) { return kSupportedEXGSamplesPerSec[ findClosestSupportedRateIndex(samplesPerSec) ]; } export const kOrientationSamplesPerSec = 20; export const kEnvironmentSamplesPerSec = 1; export const kNumberOfOtherSignals = kNumberOfOrientationSignals + kNumberEnvironmentSignals; /* Setup for 8 channel device */ export const kEEGStreamNames = [ 'EEG1', 'EEG2', 'EEG3', 'EEG4', 'EEG5', 'EEG6', 'EEG7', 'EEG8' ]; export const kOtherStreamNames = [ 'ACC X', 'ACC Y', 'ACC Z', 'GYRO X', 'GYRO Y', 'GYRO Z', 'MAG X', 'MAG Y', 'MAG Z', 'Temp', 'Light', 'Battery' ]; export function getStreamName(signalIndex: number, totalNumberOfStreams = 20) { const numberOfExGSiganls = totalNumberOfStreams - kOtherStreamNames.length; if (signalIndex < numberOfExGSiganls) { return kEEGStreamNames[signalIndex]; } return kOtherStreamNames[signalIndex - numberOfExGSiganls]; } /** * * Implements {IDeviceSetting} */ const kDefaultEnabled = { settingName: 'Enabled', value: true, options: [ { value: true, display: new Boolean(true).toString() }, { value: false, display: new Boolean(false).toString() } ] }; /** * * Implements {IDeviceSetting} */ const kDefaultDisabled = { settingName: 'Disabled', value: false, options: [ { value: true, display: new Boolean(true).toString() }, { value: false, display: new Boolean(false).toString() } ] }; /* An Analog to Digital Converter collects raw signals and these must be converted into scientifically useful units and numbers. This method will make the correct conversion. It is part of the settings object. It is used per signal in the settings. */ const kUnitsForGain1 = new UnitsInfo16Bit( 'V', //unit name UnitPrefix.kMilli, //unit prefix kDefaultDecimalPlaces, 400, -400 ); const kUnitsForGain2 = new UnitsInfo16Bit( 'V', //unit name UnitPrefix.kMilli, //unit prefix kDefaultDecimalPlaces, 100, -100 ); const kUnitsForGain3 = new UnitsInfo16Bit( 'V', //unit name UnitPrefix.kMilli, //unit prefix kDefaultDecimalPlaces, 50, -50 ); const kUnitsForGain4 = new UnitsInfo16Bit( 'V', //unit name UnitPrefix.kMicro, //unit prefix kDefaultDecimalPlaces, 25000, -25000 ); const kUnitsForGain5 = new UnitsInfo16Bit( 'V', //unit name UnitPrefix.kMicro, //unit prefix kDefaultDecimalPlaces, 12500, -12500 ); const kUnitsForAcc = new UnitsInfo16Bit( ' mG', //unit name UnitPrefix.kNoPrefix, //unit prefix 1, 0x7fff * 0.061, //maxInPrefixedUnits -0x7fff * 0.061 //minInPrefixedUnits ); const kUnitsForGyro = new UnitsInfo16Bit( ' mdps', //unit name UnitPrefix.kNoPrefix, //unit prefix 1, 0x7fff * 8.75, //maxInPrefixedUnits -0x7fff * 8.75 //minInPrefixedUnits ); const kUnitsForMag = new UnitsInfo16Bit( ' mGauss', //unit name UnitPrefix.kNoPrefix, //unit prefix 1, 0x7fff * 1.52, //maxInPrefixedUnits -0x7fff * 1.52 //minInPrefixedUnits ); const kUnitsForTemp = new UnitsInfoImpl( ' \u00B0' + 'C', UnitPrefix.kNoPrefix, 1, 255, //Max in prefixed units 0xff, //Max ADC 0, //Min in prefixed units. 0, //Min in ADC value. 255, //110, //Max valid 0 //Min valid ); const kUnitsForLight = new UnitsInfoImpl( ' lux', UnitPrefix.kNoPrefix, 3, 1000, //100000, Max in prefixed units. Direct sunlight is 100000. https://en.wikipedia.org/wiki/Lux 0x0fff, // Max in ADC values 0, //Min in prefixed units. 0, //Min in ADC value. 0x0fff, //100000, //Max valid 0 ); const kUnitsForBattery = new UnitsInfoImpl( ' %', UnitPrefix.kNoPrefix, 0, 100, 100, 0, 0, 100, 0 ); export function unitsFromPosFullScale(posFullScale: number) { switch (posFullScale) { case kUnitsForGain1.maxInPrefixedUnits: return kUnitsForGain1; case kUnitsForGain2.maxInPrefixedUnits: return kUnitsForGain2; case kUnitsForGain3.maxInPrefixedUnits: return kUnitsForGain3; case kUnitsForGain4.maxInPrefixedUnits: return kUnitsForGain4; case kUnitsForGain5.maxInPrefixedUnits: return kUnitsForGain5; case kUnitsForAcc.maxInPrefixedUnits: return kUnitsForAcc; case kUnitsForGyro.maxInPrefixedUnits: return kUnitsForGyro; case kUnitsForMag.maxInPrefixedUnits: return kUnitsForMag; case kUnitsForTemp.maxInPrefixedUnits: return kUnitsForTemp; case kUnitsForLight.maxInPrefixedUnits: return kUnitsForLight; case kUnitsForBattery.maxInPrefixedUnits: return kUnitsForBattery; } console.warn( 'Unknown positive full scale value: ' + posFullScale + 'using default' ); return kUnitsForGain1; } export class DeviceSettings implements IDeviceProxySettingsSys { version = kSettingsVersion; //This device's streams all sample at the same rate deviceSamplesPerSec: Setting; numberExgSignals: number; dataInStreams: IDeviceStreamApi[]; constructor(proxy: IProxyDeviceImpl, nEXGStreams: number) { //This device's streams all sample at the same rate this.numberExgSignals = nEXGStreams; this.deviceSamplesPerSec = new Setting( kDefaultExGRates, (setting: IDeviceSetting, newValue: DeviceValueType) => { proxy.updateStreamSettings(kAllEXGStreams, undefined, {}, true); return newValue; } ); this.dataInStreams = getDataInStreams(this, this.numberExgSignals); } } export function getDefaultDisabledStreamSettings( deviceSettings: DeviceSettings, numberOfExGSignals = kDefaultNumExGSignals ) { return getDataInStreams( deviceSettings, numberOfExGSignals, kDefaultDisabled ); } export function getDefaultSettingsForStream( numberOfSignals: number, unit: UnitsInfo16Bit, rate: IDeviceSetting, enabledSetting = kDefaultEnabled ) { return [...Array(numberOfSignals)].map(() => { return { enabled: enabledSetting, inputSettings: getInputSettings(unit), samplesPerSec: rate }; }); } export function getDataInStreams( deviceSettings: DeviceSettings, numberOfExGSiganls = kDefaultNumExGSignals, enabledSetting = kDefaultEnabled ) { return [ ...getDefaultSettingsForStream( numberOfExGSiganls, kUnitsForGain1, deviceSettings.deviceSamplesPerSec, enabledSetting ), ...getDefaultSettingsForStream( kNumberAccSignals, kUnitsForAcc, kDefaultOrientationRate, enabledSetting ), ...getDefaultSettingsForStream( kNumberGyroSignals, kUnitsForGyro, kDefaultOrientationRate, enabledSetting ), ...getDefaultSettingsForStream( kNumberMagSignals, kUnitsForMag, kDefaultOrientationRate, enabledSetting ), ...getDefaultSettingsForStream( kNumberTempSignals, kUnitsForTemp, kDefaultEnvironmentRate, enabledSetting ), ...getDefaultSettingsForStream( kNumberLightSignals, kUnitsForLight, kDefaultEnvironmentRate, enabledSetting ), ...getDefaultSettingsForStream( kNumberBatterySignals, kUnitsForBattery, kDefaultEnvironmentRate, enabledSetting ) ]; } export function getDefaultSettings( proxy: IProxyDeviceImpl, numberOfExGSignals = kDefaultNumExGSignals ) { const kDefaultSettings = new DeviceSettings(proxy, numberOfExGSignals); return kDefaultSettings; // const kDefaultSettings = { // version: 1, // dataInStreams: getDataInStreams(proxy.settings, numberOfExGSignals) // }; // return kDefaultSettings; } /** * * Implements {IDeviceInputSettingsSys} */ function getInputSettings(unitsInfo: UnitsInfo16Bit) { if (unitsInfo.maxInPrefixedUnits === kUnitsForGain1.maxInPrefixedUnits) { return { range: { settingName: 'Range', value: kUnitsForGain1.maxInPrefixedUnits, options: [ { value: kUnitsForGain1.maxInPrefixedUnits, display: kUnitsForGain1.rangeDisplayString }, { value: kUnitsForGain2.maxInPrefixedUnits, display: kUnitsForGain2.rangeDisplayString }, { value: kUnitsForGain3.maxInPrefixedUnits, display: kUnitsForGain3.rangeDisplayString }, { value: kUnitsForGain4.maxInPrefixedUnits, display: kUnitsForGain4.rangeDisplayString }, { value: kUnitsForGain5.maxInPrefixedUnits, display: kUnitsForGain5.rangeDisplayString } ] } }; } return { range: { settingName: 'Range', value: unitsInfo.maxInPrefixedUnits, options: [ { value: unitsInfo.maxInPrefixedUnits, display: unitsInfo.rangeDisplayString } ] } }; } /** * * Implements {IDeviceSetting} */ const kDefaultExGRates = { settingName: 'Rate', value: kDefaultEXGSamplesPerSec, options: [ { value: kSupportedEXGSamplesPerSec[0], display: kSupportedEXGSamplesPerSec[0].toString() + ' Hz' }, { value: kSupportedEXGSamplesPerSec[1], display: kSupportedEXGSamplesPerSec[1].toString() + ' Hz' } // 1000 Hz is currently experimental (23/9/2020) // { // value: kSupportedEXGSamplesPerSec[2], // display: kSupportedEXGSamplesPerSec[2].toString() + ' Hz' // } ] }; const kDefaultOrientationRate = { settingName: 'Rate', value: kOrientationSamplesPerSec, options: [ { value: kOrientationSamplesPerSec, display: kOrientationSamplesPerSec + ' Hz' } ] }; const kDefaultEnvironmentRate = { settingName: 'Rate', value: kEnvironmentSamplesPerSec, options: [ { value: kEnvironmentSamplesPerSec, display: kEnvironmentSamplesPerSec.toString() + ' Hz' } ] };
edcec877cdfafbe879d13f0cddcd97afb40889ab
TypeScript
jhoijune/algorithm
/src/Programmers/intermediateLetter.ts
3.25
3
import {} from 'module'; const solution = (s: string): string => { /** * 가운데 글자 가져오기 * time complexity: O(1) * space complexity: O(1) */ const size = s.length; if (size % 2 === 0) { return s.slice(Math.floor(size / 2) - 1, Math.floor(size / 2) + 1); } return s[Math.floor(size / 2)]; };
15519d189ae30ead50c105f2db2f4805fd7e0c10
TypeScript
zansito/detrans
/web/src/app/shared/button/button.ts
2.6875
3
import { ILabel, LabelFactory } from './../label'; import { IAction, ActionFactory } from './../action'; import { IButton } from './button.interface'; class Button implements IButton { constructor( public label, public clazz='', public icon?, public enabled?, public visible?, public show?, public action?, public children=[]) { } } abstract class ButtonFactory { static get(rawButton: any): IButton { return new Button( LabelFactory.get(rawButton.label||{}), rawButton['class'], rawButton.icon, rawButton.enabled||function(){return true}, rawButton.visible||function(){return true}, rawButton.show||function(){return true}, ActionFactory.get(rawButton.action), ButtonFactory.many(rawButton.children) ); } static many(rawButtons: any[]): IButton[] { return Array.isArray(rawButtons) ? rawButtons.map( rawAction => ButtonFactory.get(rawAction) ) : []; } } export { IButton, Button, ButtonFactory }
174bca2004cba0ea1b8b06980f0c059cc168c12e
TypeScript
MarcosRochaPrimordial/decorated-router
/src/route.ts
2.546875
3
import { Response, Request, NextFunction, Express } from 'express'; import * as express from 'express'; import { DiContainer } from './diContainer'; import { Parameter } from './Action'; import { Server } from './server'; export class Route { private server: Express; constructor( private instanceServer: Server ) { this.server = this.instanceServer.getInstanceServer(); } public route({ url, auth = null, cors = null }, instance: any, propertyKey: string, parameters: Parameter[], method: string, path: string) { let router = express.Router(); this.server.use(express.json()); this.server.use(url, (req: Request, res: Response, next: NextFunction) => { if (cors !== null) { res.header('Access-Control-Allow-Origin', cors); } res.header('Access-Control-Allow-Methods', this.instanceServer.getMethods().join(', ')); res.header('Access-Control-Allow-Headers', this.instanceServer.getHeaders().join(', ')); next(); }); this.server.use(url, router); if (auth !== null) { router.use(auth); } router[method](path, (req: Request, res: Response) => { this.determinate(instance, propertyKey, parameters, req, res); }); } private determinate(classInstance, key, parameters: Parameter[], req, res) { let params = parameters.map((v, k) => { const token = Reflect.getMetadata('design:paramtypes', classInstance, key)[k]; return this[v.parameterType](req, token, v.parameterKey); }); const retrn = classInstance[key](...params, res); if (!!retrn) { if (!!retrn.then) { retrn .then((result: any) => { res.json(result); }) .catch((err: any) => { res.status(500).send(err); }); } else { res.json(retrn); } } } private mapper<T>(from: any, to: T): T { Object.keys(from).forEach(fromValue => { if (!!from[fromValue]) { to[fromValue] = from[fromValue]; } }); return to; } private convertToTypes(parameter: string, type: string) { switch (type) { case 'Number': return !!parameter ? Number(parameter) : null; case 'Boolean': return !!parameter ? Boolean(JSON.parse(parameter)) : false; default: return parameter; } } PARAM(req, token: any, parameterKey: string) { return this.convertToTypes(req['query'][parameterKey], token.name); } PATHVARIABLE(req, token: any, parameterKey: string,) { return this.convertToTypes(req['params'][parameterKey], token.name); } BODY(req, token: any) { if (token.name === 'Number' || token.name === 'String' || token.name === 'Bigint' || token.name === 'Boolean') { return req.body; } const instance = DiContainer.resolve(token); return this.mapper(req.body, instance); } }
0be3c7e271b6c5eaa4ccefde5013bd223a855f3f
TypeScript
coreweave/argo
/ui/src/app/shared/history.ts
2.828125
3
import {uiUrl} from './base'; import {Utils} from './utils'; /** * Return a URL suitable to use with `history.push(..)`. Optionally saving the "namespace" parameter as the current namespace. * Only "truthy" values are put into the query parameters. I.e. "falsey" values include null, undefined, false, "", 0. */ export const historyUrl = (path: string, params: {[key: string]: any}) => { const queryParams: string[] = []; Object.entries(params) .filter(([, v]) => v !== null) .forEach(([k, v]) => { const searchValue = '{' + k + '}'; if (path.includes(searchValue)) { path = path.replace(searchValue, v != null ? v : ''); } else if (v) { queryParams.push(k + '=' + v); } if (k === 'namespace') { Utils.currentNamespace = v; } }); return uiUrl(path.replace(/{[^}]*}/g, '')) + '?' + queryParams.join('&'); };
866b3ee3ccfaf605c2a87683b44223119f124720
TypeScript
moktadirkhan/my_portfolio
/data.ts
2.625
3
import {RiComputerLine} from 'react-icons/ri' import { IProject, IService, ISkill } from './type' import {FaServer} from 'react-icons/fa' import { AiOutlineAntDesign,AiOutlineApi } from 'react-icons/ai' import {MdDeveloperMode} from 'react-icons/md' import {BsCircleFill} from 'react-icons/bs' // getting the struture from type.ts export const services:IService[]=[ { Icon:RiComputerLine, title:"Frontend Developement", about:"Experienced in <b> HTML</b>,<b> CSS </b>,<b> Bootstrap </b> and <b> React.js </b>", }, { Icon:FaServer, title:"Backend Developement", about:"Experienced in <b> Laravel </b>, <b> Django </b>, <b> PHP </b> and <b> Next.js </b>", }, ] export const languages:ISkill[]=[ { name:'Python', level:'70', Icon:BsCircleFill }, { name:'C/C++', level:'90', Icon:BsCircleFill }, { name:'PHP', level:'60', Icon:BsCircleFill }, { name:'JavaScript', level:'70', Icon:BsCircleFill }, ] export const Backend:ISkill[]=[ { name:'Laravel', level:'60', Icon:BsCircleFill }, { name:'Django', level:'70', Icon:BsCircleFill }, { name:'Next.js', level:'30', Icon:BsCircleFill } ] export const Projects:IProject[]=[ { id:1, name:"Docket", description:"This project was made for academic purpose.A website to keep track of Anime, Movies, Tv Series, Games and Books. Also writing review blogs and sharing with friends", image_path:"/images/Docket.png", github_url:"https://github.com/moktadirkhan/Docket", category:["PHP"], key_tech:["PHP","Javascript","HTML","CSS"] }, { id:2, name:"Watch Store", description:"This project was made for self-developement.A ecommerce website for watch store done with laravel frame work with admin dashboard.", image_path:"/images/watch_store.png", github_url:"https://github.com/moktadirkhan/Ecommerce_watch_store_with_Dashboard", category:["Laravel"], key_tech:["Laravel","PHP","HTML","CSS"] } ]
96a799be5c6d8b24fc2714769f78330d24eae244
TypeScript
Alfresco/alfresco-js-api
/src/api/model-rest-api/api/aspects.api.ts
2.515625
3
/*! * @license * Copyright © 2005-2023 Hyland Software, Inc. and its affiliates. All rights reserved. * * 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 { AspectEntry } from '../model/aspectEntry'; import { AspectPaging } from '../model/aspectPaging'; import { BaseApi } from './base.api'; import { throwIfNotDefined } from '../../../assert'; import { buildCollectionParam } from '../../../alfrescoApiClient'; export class ListAspectsOpts { /** * Optionally filter the list. Here are some examples: * * An aspect should be represented in the following format(prefix:name). e.g 'cm:title'. * * The following where clause will only return aspects from the namespace1:model and namespace2:model. * * - where=(modelId in ('namespace1:model','namespace2:model')) * - where=(modelId in ('namespace1:model INCLUDESUBASPECTS','namespace2:model')) * * The following where clause will only return sub aspects for the given parents. * * - where=(parentId in ('namespace1:parent','namespace2:parent')) * * The following where clause will only return aspects that match the pattern. * * - where=(namespaceUri matches('http://www.alfresco.*')) * * The following where clause will only return aspects that don't match the pattern. * * - where=(not namespaceUri matches('http://www.alfresco.*')) */ where?: string; // The number of entities that exist in the collection before those included in this list. // If not supplied then the default value is 0. skipCount?: number; // The maximum number of items to return in the list. // If not supplied then the default value is 100. maxItems?: number; /** * Returns additional information about the aspect. The following optional fields can be requested: * - properties * - mandatoryAspects * - associations */ include?: string[]; } /** * Aspects service. * @module AspectsApi */ export class AspectsApi extends BaseApi { /** * Get an aspect * * **Note:** This is available in Alfresco 7.0.0 and newer versions. Get information for aspect **aspectId**. * * @param aspectId The Qname of an aspect(prefix:name) e.g 'cm:title' * @return Promise<AspectEntry> */ getAspect(aspectId: string): Promise<AspectEntry> { throwIfNotDefined(aspectId, 'aspectId'); const pathParams = { aspectId }; return this.get<AspectEntry>({ path: '/aspects/{aspectId}', pathParams, returnType: AspectEntry }) } /** * List aspects * * **Note:** This is available in Alfresco 7.0.0 and newer versions. Gets a list of aspects from the data dictionary. The System aspects will be ignored by default. JSON { \"list\": { \"pagination\": { \"count\": 0, \"hasMoreItems\": true, \"totalItems\": 0, \"skipCount\": 0, \"maxItems\": 0 }, \"entries\": [ { \"entry\": { \"associations\": [], \"mandatoryAspects\": [], \"includedInSupertypeQuery\": true, \"description\": \"Titled\", \"isContainer\": false, \"model\": { \"id\": \"cm:contentmodel\", \"author\": \"Alfresco\", \"description\": \"Alfresco Content Domain Model\", \"namespaceUri\": \"http://www.alfresco.org/model/content/1.0\", \"namespacePrefix\": \"cm\" }, \"id\": \"cm:titled\", \"title\": \"Titled\", \"properties\": [ { \"id\": \"cm:title\", \"title\": \"Title\", \"description\": \"Content Title\", \"dataType\": \"d:mltext\", \"isMultiValued\": false, \"isMandatory\": false, \"isMandatoryEnforced\": false, \"isProtected\": false }, { ... } ] } }, { \"entry\": { ... } }, { \"entry\": { ... } }, ] } } * * @param opts Optional parameters * @return Promise<AspectPaging> */ listAspects(opts?: ListAspectsOpts): Promise<AspectPaging> { const queryParams = { where: opts?.where, skipCount: opts?.skipCount, maxItems: opts?.maxItems, include: buildCollectionParam(opts?.include, 'csv') }; return this.get<AspectPaging>({ path: '/aspects', queryParams, returnType: AspectPaging }) } }
c3314bd9b096594aadae70a4bbe33f39ad822388
TypeScript
balena-io-modules/balena-sync
/lib/shell.ts
2.796875
3
import * as child_process from 'child_process'; import * as os from 'os'; import * as Promise from 'bluebird'; import * as _ from 'lodash'; import * as rindle from 'rindle'; interface SubShellCommand { program: string; args: string[]; } /** * @summary Get sub shell command * @function * @protected * * @param {String} command - command * @returns {SubShellCommand} sub shell command * * @example * subShellCommand = shell.getSubShellCommand('foo') */ export const getSubShellCommand = function (command: string): SubShellCommand { if (os.platform() === 'win32') { return { program: 'cmd.exe', args: ['/s', '/c', command], }; } else { return { program: '/bin/sh', args: ['-c', command], }; } }; /** * @summary Run a command in a subshell * @function * @protected * * @description * stdin is inherited from the parent process. * * @param {String} command - command * @param {String} cwd - current working directory * @returns {Promise} * * @example * shell.runCommand('echo hello').then -> * console.log('Done!') */ export const runCommand = function (command: string, cwd?: string) { return Promise.try(function () { const env: any = {}; if (os.platform() === 'win32') { // Under Windows, openssh attempts to read SSH keys from // `/home/<username>`, however this makes no sense in Windows. // As a workaround, we can set the %HOME% environment variable // to `/<home drive letter>/Users/<user>` to trick openssh // to read ssh keys from `<home drive letter>:\Users\<user>\.ssh` const homedrive = _.get(process, 'env.homedrive', 'C:') .slice(0, 1) .toLowerCase(); const homepath = _.get(process, 'env.homepath', '').replace(/\\/g, '/'); env.HOME = `/${homedrive}${homepath}`; } const subShellCommand = getSubShellCommand(command); const spawn = child_process.spawn( subShellCommand.program, subShellCommand.args, { stdio: 'inherit', env: _.merge(env, process.env), cwd, // This is an internal undocumented option that causes // spawn to execute multiple word commands correctly // on Windows when passing them to `cmd.exe` // See https://github.com/nodejs/node-v0.x-archive/issues/2318#issuecomment-3220048 windowsVerbatimArguments: true, }, ); return rindle.wait(spawn).spread(function (code) { if (code === 0) { return; } throw new Error(`Child process exited with code ${code}`); }); }); };
1f2831fb33c7cbff3afa5d3da2e47ae83016eba4
TypeScript
SahenJavac/Fast-track-training-with-Krish
/pet-clinic-nestjs-angular/pet-clinic-front/src/app/pet/model/animal.model.ts
2.59375
3
export interface Animal { type: string; breed: string; age: number; diagnosis: string; }
efacf4204812ab0f1ae08256d53988b6e8b030d9
TypeScript
jimxshaw/samples-typescript
/LibraryManagerVS/LibraryManagerVS/app.ts
3.4375
3
function GetAllBooks() { let books = [ { id: 1, title: "The Hobbit", author: "J.R.R. Tolkein", available: true, category: Category.Fantasy }, { id: 2, title: "Of Mice and Men", author: "John Steinbeck", available: true, category: Category.Fiction }, { id: 3, title: "Dune", author: "Frank Herbert", available: true, category: Category.ScienceFiction }, { id: 4, title: "The Gunslinger", author: "Stephen King", available: true, category: Category.Fantasy }, { id: 5, title: "Democracy in America", author: "Alexis de Tocqueville", available: false, category: Category.History } ]; return books; } function LogFirstAvailable(books = GetAllBooks()): void { const numberOfBooks: number = books.length; let firstAvailable: string; for (let currentBook of books) { if (currentBook.available) { firstAvailable = currentBook.title; break; } } console.log(`Total books: ${numberOfBooks}`); console.log(`First available: ${firstAvailable}`); } enum Category { Fiction, NonFiction, Fantasy, ScienceFiction, History, Biography, Poetry }; function GetBookTitlesByCategory(categoryFilter: Category = Category.Fiction): Array<string> { console.log(`Getting books in category: ${Category[categoryFilter]}`); const allBooks = GetAllBooks(); const filteredTitles: string[] = []; for (let currentBook of allBooks) { if (currentBook.category === categoryFilter) { filteredTitles.push(currentBook.title); } } return filteredTitles; } function LogBookTitles(titles: string[]): void { for (let title of titles) { console.log(`Title: ${title}`); } } function GetBookByID(id: number) { const allBooks = GetAllBooks(); return allBooks.filter(book => book.id === id)[0]; } function CreateCustomerID(name: string, id: number): string { return name + id; } function CreateCustomer(name: string, age?: number, city?: string): void { console.log(`Creating customer: ${name}`); if (age) { console.log(`Age: ${age}`); } if (city) { console.log(`City: ${city}`); } } function CheckoutBooks(customer: string, ...bookIDs: number[]): string[] { console.log(`Checking out books for: ${customer}`); let booksCheckedOut: string[] = []; for (let id of bookIDs) { let book = GetBookByID(id); if (book.available) { booksCheckedOut.push(book.title); } } return booksCheckedOut; } function GetTitles(author: string): string[]; function GetTitles(available: boolean): string[]; function GetTitles(bookProperty: any): string[] { const allBooks = GetAllBooks(); const foundTitles: string[] = []; if (typeof bookProperty === "string") { // Get all books by a particular author. for (let book of allBooks) { if (book.author === bookProperty) { foundTitles.push(book.title); } } } else if (typeof bookProperty === "boolean") { // Get all books by a particular author. for (let book of allBooks) { if (book.available === bookProperty) { foundTitles.push(book.title); } } } return foundTitles; } //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ let checkedOutBooks = GetTitles(false); checkedOutBooks.forEach(title => console.log(title)); //let myBooks: string[] = CheckoutBooks("Jon", 4, 3, 2, 1); //myBooks.forEach(title => console.log(title)); //LogFirstAvailable(); //let fictionBooks = GetBookTitlesByCategory(); //fictionBooks.forEach(bookTitle => console.log(bookTitle)); //CreateCustomer("Barack"); //CreateCustomer("Barack", 43); //CreateCustomer("Barack", 43, "Washington DC"); //let x: number; //x = 9; //let IdGenerator: (chars: string, nums: number) => string; //IdGenerator = (name: string, id: number) => { return name + id }; //console.log(IdGenerator("Sam", 28)); //let myID: string = CreateCustomerID("John", 88); //console.log(myID); //const fantasyBooks = GetBookTitlesByCategory(Category.Fantasy); //fantasyBooks.forEach((val, idx, arr) => console.log(++idx + " - " + val));
ed68e371e0bf9b4edcad97bc7b7f00854ce7a67e
TypeScript
hsneden/crosswords-game
/src/app/crosswords/services/remote-data.service.ts
2.625
3
import { Injectable } from '@angular/core'; import { Http } from '@angular/http'; import { Axis, Word } from '../models/word.model'; import { Crossword } from '../models/crossword.model'; import { Issue } from '../models/issue.model'; @Injectable() export class RemoteDataService { constructor(private _http: Http) { } public getIssues(crosswordsPerIssue: number): Promise<number> { return this._http .get('api/crosswords/count.json') .toPromise() .then(response => response.json()) .then(json => { return Math.ceil(json.Count / crosswordsPerIssue); }); } public getIssue(id: number): Promise<Issue> { return this._http .get(`api/crosswords/list/page${id}.json`) .toPromise() .then(response => response.json()) .then(json => { let issue = new Issue(id); json.Crosswords.forEach(crosswordId => { issue.addCrossword(crosswordId); }); return issue; }); } public getCrossword(id: string): Promise<Crossword> { return this._http .get(`api/crosswords/${id}.json`) .toPromise() .then(response => response.json()) .then(json => { return this.converJsonToCrossword(json); }); } private converJsonToCrossword(json: any): Crossword { let id = json.Id; let words: Array<Word> = new Array<Word>(); json.Words.forEach(word => { let crosswordWord = this.convertJsonToWord(word); words.push(crosswordWord); }); return new Crossword(id, words); } private convertJsonToWord(json: any): Word { let x = json.X; let y = json.Y; let clue = json.Clue; let question = json.Question; let answer = json.Answer; let axis = json.Axis === 'X' ? Axis.x : json.Axis === 'Y' ? Axis.y : null; return new Word(x, y, clue, axis, question, answer); } }
9b7030750222507e754708019122565075aa6f61
TypeScript
vicimpa/road-keys
/lib/keyboard.ts
2.9375
3
export const keySymbols = `abcdefghijklmnopqrstuvwxyz1234567890-=+_)(*&^%$#@!/?\`'"\\|.,` export const accessSymbols = keySymbols.split('') accessSymbols.push(' ') for (let sym of accessSymbols) if (sym !== sym.toUpperCase()) accessSymbols.push(sym.toUpperCase()) accessSymbols.push('Enter') accessSymbols.push('Escape') accessSymbols.push('Backspace') let onInputKey: (key: string) => void export function subscribe(subscriber: (key: string) => void) { onInputKey = subscriber } window.addEventListener('keydown', (e: KeyboardEvent) => { e.preventDefault() if (accessSymbols.indexOf(e.key) === -1) return if (onInputKey) onInputKey(e.key) })
699c109f0eee33387124b31f47640d6daa71eccc
TypeScript
idledeity/renderbox
/source/render/renderer/open_gl/open_gl_renderer.ts
2.609375
3
import OpenGLContext from "./open_gl_context.js" import Renderer from "../renderer.js" import SolidColorProgram from "../../shader/shaders/solid_color.js"; import VertexColorProgram from "../../shader/shaders/vertex_color.js"; import OpenGLShaderProgram from "./open_gl_shader_program.js"; import Vector2 from "math/vector/vector2.js"; import ColorRGB32 from "render/color.js"; export default class OpenGLRenderer extends Renderer { private _SolidColorProgram: SolidColorProgram; private _VertexColorProgram: VertexColorProgram; /** * Constructor * @param {RenderContext} context - The render context for the renderer to use */ constructor(canvasElement: HTMLCanvasElement) { super(canvasElement); this._SolidColorProgram = new SolidColorProgram(); this._SolidColorProgram.initialize(this.context); this._VertexColorProgram = new VertexColorProgram(); this._VertexColorProgram.initialize(this.context); } get gl(): WebGLRenderingContext { return (this.context as OpenGLContext).gl; } get SolidColorProgram(): SolidColorProgram { return this._SolidColorProgram; } get VertexColorProgram(): VertexColorProgram { return this._VertexColorProgram } makeContext(canvasElement: HTMLCanvasElement) { return new OpenGLContext(canvasElement); } beginFrame() { this.gl.viewport(0, 0, this.gl.canvas.width, this.gl.canvas.height); this.gl.clearColor(0, 0, 0, 1.0); this.gl.clear(this.gl.COLOR_BUFFER_BIT); } drawTriangle2D(verts: Vector2[], colors: ColorRGB32[]) { let gl_program = (this.VertexColorProgram.shader as OpenGLShaderProgram).gl_program; if (gl_program) { this.gl.useProgram(gl_program); const positionArray = new Float32Array(2 * 3); positionArray.set(verts[0].coords, 0); positionArray.set(verts[1].coords, 2); positionArray.set(verts[2].coords, 4); let positionBuffer = this.gl.createBuffer(); this.gl.bindBuffer(this.gl.ARRAY_BUFFER, positionBuffer); this.gl.bufferData(this.gl.ARRAY_BUFFER, positionArray, this.gl.STATIC_DRAW); let positionAttributeLocation = this.gl.getAttribLocation(gl_program, "aVertPos"); this.gl.enableVertexAttribArray(positionAttributeLocation); this.gl.vertexAttribPointer(positionAttributeLocation, 2, this.gl.FLOAT, false, 0, 0); const colorArray = new Float32Array(4 * 3); colorArray.set(colors[0].values, 0); colorArray.set(colors[1].values, 4); colorArray.set(colors[2].values, 8); let colorBuffer = this.gl.createBuffer(); this.gl.bindBuffer(this.gl.ARRAY_BUFFER, colorBuffer); this.gl.bufferData(this.gl.ARRAY_BUFFER, colorArray, this.gl.STATIC_DRAW); let colorAttributeLocation = this.gl.getAttribLocation(gl_program, 'aVertColor'); this.gl.enableVertexAttribArray(colorAttributeLocation); this.gl.vertexAttribPointer(colorAttributeLocation, 4, this.gl.FLOAT, false, 0, 0); // draw var primitiveType = this.gl.TRIANGLES; var offset = 0; var count = 3; this.gl.drawArrays(primitiveType, offset, count); } } }
da74b0a6a2fd9a03088d13143fd3a2c440733b9a
TypeScript
Automattic/danger-settings
/org/pr/milestone.ts
2.8125
3
// Danger ignores Danger's imports at runtime and actually would give a build // failure if we tried to use them here and then import this file. What authors // should do, instead, is simply assume it's there. // // See https://danger.systems/js/usage/extending-danger.html#writing-your-plugin // // In order to write tests for these files, though, we need to define // interfaces for the Danger functionalities we'll use. These don't affect // runtime and do provide better dev-time typing experience. // // A richer example of this can be found here: // https://github.com/orta/danger-plugin-yarn/blob/5e906e57331b952afced3f6e773ed6c68d5898c0/src/index.ts#L1-L8 import { DangerDSLType } from "../../node_modules/danger/distribution/dsl/DangerDSL" declare var danger: DangerDSLType export declare function warn(message: string): void export async function checkMilestone() { // Create consts for everything we need from `danger` object as soon as possible // so it's not dropped during await operation const githubLabels = danger.github.issue.labels; const targetsDevelop = danger.github.pr.base.ref == "develop"; const targetsRelease = danger.github.pr.base.ref.startsWith("release/"); const currentPR = await danger.github.api.pulls.get(danger.github.thisPR); // Skip for draft PRs if (currentPR.data.draft) { return; } if (githubLabels.length != 0) { // Skip for PRs with "Releases" label const releases = githubLabels.some(label => label.name.includes("Releases")); if (releases) { return; } // Skip for PRs for wip features unless the PR is against "develop" or "release/x.x" branches const wipFeature = githubLabels.some(label => label.name.includes("Part of a WIP Feature")); if (!targetsDevelop && !targetsRelease && wipFeature) { return; } } // Warn if the PR doesn't have a milestone if (currentPR.data.milestone == null) { warn("PR is not assigned to a milestone."); } }; // Not exactly sure why, but in order for the multiple files + import setup to // work we need to split the export of this function and its declaration as the // default export. I'm guessing it has to do with how TypeScript resolves // these? export default checkMilestone
606d9c6f6b3a70b9babe43bd4370a356696d3d29
TypeScript
juanwolf/enter-the-wiki
/src/domain/items/item.ts
2.828125
3
import { Field, ObjectType } from "type-graphql"; @ObjectType() export class Item { @Field() name: string; @Field() description: string; @Field() quality: string; constructor(name: string, description: string, quality: string) { this.name = name; this.description = description; this.quality = quality; }; }
e1bc2b02d64b12477342f4d841e27281aa2da022
TypeScript
Adyen/adyen-node-api-library
/src/typings/payout/address.ts
2.609375
3
/* * The version of the OpenAPI document: v68 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit this class manually. */ export class Address { /** * The name of the city. Maximum length: 3000 characters. */ 'city': string; /** * The two-character ISO-3166-1 alpha-2 country code. For example, **US**. > If you don\'t know the country or are not collecting the country from the shopper, provide `country` as `ZZ`. */ 'country': string; /** * The number or name of the house. Maximum length: 3000 characters. */ 'houseNumberOrName': string; /** * A maximum of five digits for an address in the US, or a maximum of ten characters for an address in all other countries. */ 'postalCode': string; /** * The two-character ISO 3166-2 state or province code. For example, **CA** in the US or **ON** in Canada. > Required for the US and Canada. */ 'stateOrProvince'?: string; /** * The name of the street. Maximum length: 3000 characters. > The house number should not be included in this field; it should be separately provided via `houseNumberOrName`. */ 'street': string; static discriminator: string | undefined = undefined; static attributeTypeMap: Array<{name: string, baseName: string, type: string}> = [ { "name": "city", "baseName": "city", "type": "string" }, { "name": "country", "baseName": "country", "type": "string" }, { "name": "houseNumberOrName", "baseName": "houseNumberOrName", "type": "string" }, { "name": "postalCode", "baseName": "postalCode", "type": "string" }, { "name": "stateOrProvince", "baseName": "stateOrProvince", "type": "string" }, { "name": "street", "baseName": "street", "type": "string" } ]; static getAttributeTypeMap() { return Address.attributeTypeMap; } }
66f3c107b686a9ee77529ae292cf0594c6044f43
TypeScript
dsshard/reply-count-loop
/src/index.ts
3.15625
3
export interface ReplayCountLoopOptions { attempts?: number onError?: (err) => void delay?: number } export default function replayCountLoop <T> (fn, options: ReplayCountLoopOptions = {}): Promise<T> { if (!fn) throw new Error('first parameter (fn) is required') let attempt = 0 async function replay () { try { return await fn({ attempt }) } catch (err) { attempt += 1 if (options.attempts > 0 && attempt > options.attempts) throw new Error(err) if (typeof options.onError === 'function') options.onError(err) return new Promise((resolve) => { setTimeout(() => { resolve(replay()) }, options.delay || 0) }) } } return replay() }
8ec872fbd8a9221689bc37664bf403665ee249ac
TypeScript
ziccardi/json-data-validator
/test/rules/SimpleRulesPack/IsAsciiRule.test.ts
2.578125
3
import {RuleFactory} from '../../../src/rules/RuleFactory'; import {test} from '../../utils'; describe('isAscii', () => { const rule = RuleFactory.create({ type: 'isAscii', }); it('Should evaluate if string is an ASCII string', () => { test(rule, { path: 'field1.field2', valid: ['abcdefghi 1=+-[]{}$%^!@><,./'], invalid: ['abcdefghi-*/\u1000'], }); }); });
1ec221c4b89f12bc27cc8f50adbbbc9fb7c8ab61
TypeScript
andyriffic/CNB
/src/server/src/uplift/sockets/mob-mode/points-to-player-castle.ts
2.703125
3
import { Debugger } from 'debug'; import { playerService } from '../../services/player'; import { Player } from '../../services/player/types'; import { MobGame } from './types'; function setAttackingPlayer(player: Player | undefined, log: Debugger): void { if (!player) { log('No Attacking player to set'); return; } log('Setting attacking player: ', player.id); const newTags = [ ...player.tags.filter((t) => t !== 'castle_attacker'), `castle_attacker`, ]; playerService.updatePlayerTags(player, newTags).then(() => { log('Set attacking player: ', player.id); }); } function clearAttackingPlayer(player: Player | undefined, log: Debugger): void { if (!player) { log('No Attacking player'); return; } log('Clearing attacking player: ', player.id); const newTags = player.tags.filter((t) => t !== 'castle_attacker'); playerService.updatePlayerTags(player, newTags).then(() => { log('Cleared attacking player: ', player.id); }); } function getWinningAttackerId(mobGame: MobGame): string { const survivingMobPlayers = mobGame.mobPlayers.filter((mp) => mp.active); const mugWinner = survivingMobPlayers.length === 0 && mobGame.mugPlayer.lives > 0; const soleMobSurvivor = survivingMobPlayers.length === 1 ? survivingMobPlayers[0] : undefined; if (mugWinner || survivingMobPlayers.length > 1) { return mobGame.mugPlayer.playerId; } if (soleMobSurvivor) { return soleMobSurvivor.playerId; } console.log('Could not determine Winning player for castle game'); return ''; } export function pointsToPlayersCastle(mobGame: MobGame, log: Debugger) { playerService.getPlayersAsync().then((allPlayers) => { //TODO: need to remove attack tag from a player if they didn't play the game const existingAttackingPlayer = allPlayers.find((p) => p.tags.includes('castle_attacker') ); const newAttackingPlayerId = getWinningAttackerId(mobGame); const newAttackingPlayer = newAttackingPlayerId ? allPlayers.find((p) => p.id === newAttackingPlayerId) : undefined; if (existingAttackingPlayer?.id !== newAttackingPlayer?.id) { clearAttackingPlayer(existingAttackingPlayer, log); setAttackingPlayer(newAttackingPlayer, log); } }); }
70abcbf9342e5c5a40d95aafb7b3a1ba2202ce36
TypeScript
LIAUTAUD-Canelle/API-OpenFoodFacts
/src/app/classes/contact.ts
2.765625
3
export class Contact { id: number; nomFamille: string; prenom: string; email: string; genre: number; age: number; constructor(id: number, nomFamille: string, prenom: string, email: string, genre: number, age: number) { this.id = id; this.nomFamille = nomFamille; this.prenom = prenom; this.email = email; this.genre = genre; this.age = age; } }
470ddbf19ea091b0b3f8a4986d5380be383343b3
TypeScript
PinaryDevelopment/torahis.life
/src/frontend/src/models/shiur.ts
2.671875
3
import { Tag } from './tag'; import { TagType } from './tag-type.enum'; import { Author } from './author'; export class Shiur { public title: string; public tags: Tag[]; public date: Date; public duration: string; public id: number; public previousId?: number; public nextId?: number; public author: Author; constructor({ title = '', tags = [], date, duration = '', id, previousId, nextId, author }) { this.title = title; this.tags = tags; this.date = date; this.duration = duration; this.id = id; this.previousId = previousId; this.nextId = nextId; this.author = author; } public get series() { return this.tags.map(tag => tag.tag); } }
41d1c169f8f1fe2ff5f9cf8b4cff61abf7b9d6de
TypeScript
asiec-inverntory/frontend
/src/stores/listing/AttributesStore.ts
2.890625
3
import { makeAutoObservable } from 'mobx'; import keyBy from 'lodash/keyBy'; import { get } from 'utils/fetch'; import { AttributeValueType, ObjectWithIds } from 'utils/types'; export type AttributeType = { id: string; // AttributeValueType means type of attribute valueType // valueType describe type of specific attribute valueType: AttributeValueType; humanReadable: string; values?: (string | number)[]; minimum?: number; maximum?: number; } export type PropertiesType = ObjectWithIds<string, AttributeType>; export type EquipmentTypesDataType = ObjectWithIds<string, PropertiesType> & { humanReadableTypeNameById: Record<string, string>; }; type DataType = [ { [key: string]: AttributeType[]; }, { [key: string]: string; } ] class AttributesStore { types: EquipmentTypesDataType = { byIds: {}, ids: [], humanReadableTypeNameById: {}, }; isLoading = true; constructor() { makeAutoObservable(this); } fetch = async() => { this.isLoading = true; const dataRaw = await get('attribute/list'); const data: DataType = dataRaw.body; const humanReadableTypeNameById = data[1]; const typesIds = Object.keys(humanReadableTypeNameById); const typesByIds = {}; typesIds.map((id) => { const properties = data[0][id]; const propertiesByIds = keyBy(properties, 'id'); const propertyIds = Object.keys(propertiesByIds); typesByIds[id] = { byIds: propertiesByIds, ids: propertyIds, }; }); const newState: EquipmentTypesDataType = { byIds: typesByIds, ids: typesIds, humanReadableTypeNameById, }; this.types = newState; this.isLoading = false; } } export default AttributesStore;
0d771df26adc53e1ce42539fbf30938b829101c8
TypeScript
kabarakh/diceRollerV2
/src/app/services/abstractStorage.service.ts
2.6875
3
import { Injectable } from '@angular/core'; import store from 'store2'; @Injectable() export abstract class AbstractStorageService { abstract storageName: string; abstract storageType: string; storage: any; constructor() { } initializeObject = () => { if (!this.storageName || !this.storageType) { throw new Error('storageName and storageType have to be set'); } if (this.storageType === 'local') { this.storage = store.local; } else if (this.storageName === 'session') { this.storage = store.session; } else { throw new Error('storageType has to be "session" or "local", "' + this.storageType + '" given'); } } public loadData() { if (!this.storage) { this.initializeObject(); } return this.storage.get(this.storageName); } public storeData(data) { if (!this.storage) { this.initializeObject(); } this.storage.set(this.storageName, data); } public clear() { if (!this.storage) { this.initializeObject(); } this.storage.remove(this.storageName); } }
6f7343a95a70d172406763889eca61313d368647
TypeScript
NW12/spotStar
/scripts/deploy.ts
2.59375
3
// We require the Hardhat Runtime Environment explicitly here. This is optional but useful for running the // script in a standalone fashion through `node <script>`. When running the script with `hardhat run <script>`, // you'll find the Hardhat Runtime Environment's members available in the global scope. import hre, { ethers } from "hardhat"; import { Console } from "node:console"; import { SpotStarIco,SpotStarIco__factory } from "../typechain"; async function main(): Promise<void> { const signers = await hre.ethers.getSigners() const SpotStarIco = await ethers.getContractFactory("SpotStarIco") as SpotStarIco__factory; // spotStar Token mainnet address is 0x810bdba1eb5c70c4dc0dbe3bbaf18fffd31c01d1 // this is test token address for testing purposes 0x318f4d534e9A03A96ad9cA35AeBC2b097D860000 const ico: SpotStarIco = await SpotStarIco.deploy("0x318f4d534e9A03A96ad9cA35AeBC2b097D860000",signers[0].address); await ico.deployed(); console.log("Deployer :",signers[0].address); console.log("SpotStarIco deployed to: ", ico.address); } // We recommend this pattern to be able to use async/await everywhere and properly handle errors. main() .then(() => process.exit(0)) .catch((error: Error) => { console.error(error); process.exit(1); });
bcb5553cd7f45088f6d8f15749b46c5c0921f2ff
TypeScript
darrickyee/ui
/ts/models/uetypes.ts
2.96875
3
import { types, Instance } from 'mobx-state-tree'; import { has } from 'ramda'; const arrayMapper = (props: string[] = []) => types .model({}) .views((self) => ({ toArray() { return props.map((p) => has('toArray', self[p]) ? self[p].toArray() : has('toJSON', self[p]) ? self[p].toJSON() : self[p] ); }, })) .actions((self) => ({ fromArray(arr: any[]) { props.forEach((p, i) => { self['setValue'](p, arr[i]); }); }, })); const propSetter = <T>(base: T) => types.model({}).actions((self: Instance<T>) => ({ setValue(prop: keyof Instance<T>, value) { if (Array.isArray(value) && has('fromArray', self[prop])) self[prop]['fromArray'](value); else self[prop] = value; }, })); const VectorBase = types.model({ x: 0.0, y: 0.0, z: 0.0 }); const RotationBase = types.model({ roll: 0.0, pitch: 0.0, yaw: 0.0 }); export const Vector = types.compose( 'Vector', VectorBase, arrayMapper(['x', 'y', 'z']), propSetter(VectorBase) ); export const Rotation = types.compose( 'Rotation', RotationBase, arrayMapper(['roll', 'pitch', 'yaw']), propSetter(RotationBase) ); const TransformBase = types.model('Transform', { translation: types.optional(Vector, {}), rotation: types.optional(Rotation, {}), scale: types.optional(Vector, {}), }); export const Transform = types.compose( 'Transform', TransformBase, arrayMapper(['translation', 'rotation', 'scale']), propSetter(TransformBase) ); export type VectorModel = Instance<typeof Vector>; export type RotationModel = Instance<typeof Rotation>; export type TransformModel = Instance<typeof Transform>;
b888b4247949ac9b0dce288680e7270a7a9ccbcc
TypeScript
Luke-Gurgel/rn-tdd-cdd
/src/utils/make-test-id.ts
2.703125
3
export function makeTestId(str: string, pathPrefix = ''): string { if (!str) throw Error('makeTestId(): an empty string was passed in') return pathPrefix + str.toLowerCase().replace(/ /g, '-') }
c7bbffb6876371fb5ee281aaa32afc64e6b23e2e
TypeScript
NaOH123321/angular-taskmgr
/src/app/actions/task-list.action.ts
2.90625
3
import { Action } from '@ngrx/store'; import { TaskList, User } from './../domain'; /** * For each action type in an action group, make a simple * enum object for all of this group's action types. */ export enum TaskListActionTypes { TASKLIST_LOAD = '[TaskList] TaskList Load', TASKLIST_LOAD_SUCCESS = '[TaskList] TaskList Load Success', TASKLIST_LOAD_FAIL = '[TaskList] TaskList Load Fail', TASKLIST_ADD = '[TaskList] TaskList Add', TASKLIST_ADD_SUCCESS = '[TaskList] TaskList Add Success', TASKLIST_ADD_FAIL = '[TaskList] TaskList Add Fail', TASKLIST_UPDATE = '[TaskList] TaskList Update', TASKLIST_UPDATE_SUCCESS = '[TaskList] TaskList Update Success', TASKLIST_UPDATE_FAIL = '[TaskList] TaskList Update Fail', TASKLIST_DELETE = '[TaskList] TaskList Delete', TASKLIST_DELETE_SUCCESS = '[TaskList] TaskList Delete Success', TASKLIST_DELETE_FAIL = '[TaskList] TaskList Delete Fail', TASKLIST_SWAP = '[TaskList] TaskList Swap', TASKLIST_SWAP_SUCCESS = '[TaskList] TaskList Swap Success', TASKLIST_SWAP_FAIL = '[TaskList] TaskList Swap Fail', }; /** * Every action is comprised of at least a type and an optional * payload. Expressing actions as classes enables powerful * type checking in reducer functions. */ export class TaskListLoadAction implements Action { readonly type = TaskListActionTypes.TASKLIST_LOAD; constructor(public payload: string) { } } export class TaskListLoadSuccessAction implements Action { readonly type = TaskListActionTypes.TASKLIST_LOAD_SUCCESS; constructor(public payload: TaskList[]) { } } export class TaskListLoadFailAction implements Action { readonly type = TaskListActionTypes.TASKLIST_LOAD_FAIL; constructor(public payload: string) { } } export class TaskListAddAction implements Action { readonly type = TaskListActionTypes.TASKLIST_ADD; constructor(public payload: TaskList) { } } export class TaskListAddSuccessAction implements Action { readonly type = TaskListActionTypes.TASKLIST_ADD_SUCCESS; constructor(public payload: TaskList) { } } export class TaskListAddFailAction implements Action { readonly type = TaskListActionTypes.TASKLIST_ADD_FAIL; constructor(public payload: string) { } } export class TaskListUpdateAction implements Action { readonly type = TaskListActionTypes.TASKLIST_UPDATE; constructor(public payload: TaskList) { } } export class TaskListUpdateSuccessAction implements Action { readonly type = TaskListActionTypes.TASKLIST_UPDATE_SUCCESS; constructor(public payload: TaskList) { } } export class TaskListUpdateFailAction implements Action { readonly type = TaskListActionTypes.TASKLIST_UPDATE_FAIL; constructor(public payload: string) { } } export class TaskListDeleteAction implements Action { readonly type = TaskListActionTypes.TASKLIST_DELETE; constructor(public payload: TaskList) { } } export class TaskListDeleteSuccessAction implements Action { readonly type = TaskListActionTypes.TASKLIST_DELETE_SUCCESS; constructor(public payload: TaskList) { } } export class TaskListDeleteFailAction implements Action { readonly type = TaskListActionTypes.TASKLIST_DELETE_FAIL; constructor(public payload: string) { } } export class TaskListSwapAction implements Action { readonly type = TaskListActionTypes.TASKLIST_SWAP; constructor(public payload: { src: TaskList, target: TaskList }) { } } export class TaskListSwapSuccessAction implements Action { readonly type = TaskListActionTypes.TASKLIST_SWAP_SUCCESS; constructor(public payload: TaskList[]) { } } export class TaskListSwapFailAction implements Action { readonly type = TaskListActionTypes.TASKLIST_SWAP_FAIL; constructor(public payload: string) { } } /** * Export a type alias of all actions in this action group * so that reducers can easily compose action types */ export type TaskListActions = TaskListAddAction | TaskListAddSuccessAction | TaskListAddFailAction | TaskListLoadAction | TaskListLoadSuccessAction | TaskListLoadFailAction | TaskListUpdateAction | TaskListUpdateSuccessAction | TaskListUpdateFailAction | TaskListDeleteAction | TaskListDeleteSuccessAction | TaskListDeleteFailAction | TaskListSwapAction | TaskListSwapSuccessAction | TaskListSwapFailAction;
c8a033c5b9b9582cad4b809879f8ce49a1750a83
TypeScript
KProskuryakov/kproskuryakov.github.io
/src/lasergame/LaserSegment.ts
2.84375
3
import Color from "./Color"; import Direction, { getOppositeDirection } from "./Direction"; import Tile, { copyTile } from "./Tile"; export default interface LaserSegment { tile: Tile; dir: Direction; color: Color; } export function getOppositeLaserSegment(laser: LaserSegment): LaserSegment { return { tile: copyTile(laser.tile), dir: getOppositeDirection(laser.dir), color: laser.color }; } export function copyLaserSegment(laser: LaserSegment): LaserSegment { return { tile: copyTile(laser.tile), dir: laser.dir, color: laser.color }; }
450337a6ad085a09238cb96dac389d5da74ae4f0
TypeScript
InnoCampusLife/frontend
/src/modules.ts
2.609375
3
import config from './config' import storage from './storage' function ajax(type: string, url: string, data: Object, successCallback: Function, errorCallback: Function): void { const xhr = new XMLHttpRequest() xhr.open(type, url, true) xhr.onload = function() { if (xhr.response && xhr.response.result) { // console.log('Response status: ', xhr.response.status); if (successCallback) successCallback(xhr.response.result) } else if (xhr.response && xhr.response.error) { console.error('Response error: ', xhr.response.error) if (errorCallback) errorCallback(xhr.response.error) } else { console.error('Response is absent.') } } xhr.responseType = 'json' if (!(url.indexOf("getBio") > -1)) xhr.setRequestHeader('Content-Type', 'application/json') xhr.send(JSON.stringify(data)) } const apiURL = config.server.apiURL // const testAccounts = require('entry-dir!!./modules/modules.config.js'); // console.log(testAccounts); export const modules = { get token() { return storage.getItem(config.tokenName) }, set token(value) { storage.setItem(config.tokenName, value) }, accounts: { roles: [ 'ghost', 'student', 'moderator', ], have(role) { return !!(this.roles.indexOf(role.toLowerCase()) > -1) }, // Data id: null, username: null, role: null, firstName: null, lastName: null, patronymic: null, studyGroup: null, tgId: null, get token() { return storage.getItem(config.tokenName) }, set token(value) { storage.setItem(config.tokenName, value) }, get fullName() { const ln = (!!this.lastName ? this.lastName + ' ' : '') const fn = (!!this.firstName ? this.firstName : '') const pn = (!!this.patronymic ? ' ' + this.patronymic : '') return fn + ln + pn }, get loggedIn() { return storage.getItem(config.tokenName) ? true: false }, get isGhost() { return !!this.is('ghost') }, get isStudent() { return !!this.is('student') }, get isModerator() { return !!this.is('moderator') }, is(ofType) { return !!this.role && !!this.have(ofType) && !!(this.role.toLowerCase() === ofType.toLowerCase()) }, clear() { this.id = null this.role = null this.firstName = null this.lastName = null this.patronymic = null this.studyGroup = null this.token = null storage.clear() }, set(data) { if (data.id) this.id = data.id if (data.username) this.username = data.username if (data.role) this.role = data.role if (data.firstName) this.firstName = data.firstName if (data.lastName) this.lastName = data.lastName if (data.patronymic) this.patronymic = data.patronymic if (data.studyGroup) this.studyGroup = data.studyGroup if (data.token) this.token = data.token }, version: 1, name: "accounts", get url() { return apiURL + "v" + this.version + "/" + this.name + "/" }, get(successCallback, errorCallback) { const type = "GET" const url = this.url + this.token const data = '' fetch('') ajax(type, url, data, successCallback, errorCallback) }, update(successCallback, errorCallback) { const self = this this.get((result) => { console.log('Called update with result: ', result) self.set(result) if (successCallback) successCallback(result) }, errorCallback) }, preferences: { save(successCallback, errorCallback) { const that = this const type = "PUT", url = this.url + modules.accounts.token + '/updatePreferences', data = { preferences: that, } ajax(type, url, data, successCallback, errorCallback) }, get(successCallback, errorCallback) { const type = "GET", url = this.url + modules.accounts.token + '/getPreferences', data = '' ajax(type, url, data, successCallback, errorCallback) }, }, create(password, email, successCallback, errorCallback) { const type = "POST", url = this.url, data = { username: this.username, password: password, email: email, firstName: this.firstName, lastName: this.lastName, studyGroup: this.studyGroup, } ajax(type, url, data, successCallback, errorCallback) }, authorize(password, successCallback, errorCallback) { const type = "POST", url = this.url + "auth", data = { username: this.username, password: password, } ajax(type, url, data, successCallback, errorCallback) }, // Moderator methods list(successCallback, errorCallback) { const type = "GET", url = this.url + this.token + "/listAccounts", data = '' ajax(type, url, data, successCallback, errorCallback) }, updateRole(account_id, new_role, successCallback, errorCallback) { const type = "PUT", url = this.url + this.token + "/updateRole", data = { accountId: account_id, newRole: new_role } ajax(type, url, data, successCallback, errorCallback) }, exists(args, successCallback, errorCallback) { const type = "GET", url = this.url + this.token + "/exists?" + (args.id ? "id=" + args.id : "username=" + args.username), data = '' ajax(type, url, data, successCallback, errorCallback) }, getBio(args, successCallback, errorCallback) { const type = "GET", url = this.url + this.token + "/getBio?" + (args.id ? "id=" + args.id : "username=" + args.username), data = '' ajax(type, url, data, successCallback, errorCallback) }, }, innopoints: { roles: [ 'student', 'admin', ], have (role) { return !!(this.roles.indexOf(role) > -1) }, data: { id : null, amount : null, role : null, get isStudent() { return !!this.is('student') }, get isAdmin() { return !!this.is('admin') }, is(ofType) { return !!this.role && !!modules.innopoints.have(ofType) && !!(this.role.toLowerCase() === ofType.toLowerCase()) }, update(successCallback, errorCallback) { const that = this modules.innopoints.api.user.get({ successCallback: result => { that.id = result.id that.amount = result.points_amount || 0 that.role = result.type if (successCallback) successCallback(result) }, errorCallback: errorCallback, }) }, }, api: { version: 1, name: "points", get url() { return apiURL + "v" + this.version + "/" + this.name + "/" }, getActivities(args) { const type = "GET", url = this.url + "activities" + (args.cat_id ? '/' + args.cat_id: ''), data = { skip: args.skip_count || null, limit: args.limit_count || null } ajax(type, url, data, args.successCallback, args.errorCallback) }, getCategories(args) { const type = "GET", url = this.url + "categories", data = { skip: args.skip_count || null, limit: args.limit_count || null } ajax(type, url, data, args.successCallback, args.errorCallback) }, store: { get url() { return modules.innopoints.api.url + "shop/" }, getItems(args) { const type = "GET", url = this.url + "items", data = { skip: args.skip_count || null, limit: args.limit_count || null, fields: args.fields || 'title', order: args.order || 'ASC', category_id: args.category_id || null, } ajax(type, url, data, args.successCallback, args.errorCallback) }, getItem(id, successCallback, errorCallback) { const type = "GET", url = this.url + "items/" + id, data = '' ajax(type, url, data, successCallback, errorCallback) }, order: { get url() { return modules.innopoints.api.user.url }, create(args) { const type = "POST", url = this.url + modules.accounts.token + '/orders', data = args.order ajax(type, url, data, args.successCallback, args.errorCallback) }, update(args) { const type = "POST", url = this.url + modules.accounts.token + '/orders/' + args.id + '/contributors/' + args.action, data = '' ajax(type, url, data, args.successCallback, args.errorCallback) }, delete(args) { const type = "DELETE", url = this.url + modules.accounts.token + '/orders/' + args.id, data = '' ajax(type, url, data, args.successCallback, args.errorCallback) }, }, }, user: { get isAdmin() { return modules.innopoints.data.isAdmin }, get url() { return modules.innopoints.api.url + (this.isAdmin ? "admin/": "accounts/") }, get(args) { let type = "GET", url = modules.innopoints.api.url + 'accounts/' + modules.accounts.token, data = '' if (this.isAdmin) if(args.id) url += "/accounts/" + args.id ajax(type, url, data, args.successCallback, args.errorCallback) }, create(successCallback, errorCallback) { const type = "POST", url = this.url + modules.accounts.token, data = '' ajax(type, url, data, successCallback, errorCallback) }, getFile(appl_id, file_id, successCallback, errorCallback) { const type = "GET", url = this.url + modules.accounts.token + "/applications/" + appl_id + "/files/" + file_id, data = '' ajax(type, url, data, successCallback, errorCallback) }, getAccounts(args) { const type = "GET", url = this.url + modules.accounts.token, data = { skip: args.skip_count || null, limit: args.limit_count || null } ajax(type, url, data, args.successCallback, args.errorCallback) }, updateAccount(args) { const type = "PUT", url = this.url + modules.accounts.token + "/accounts/" + args.id, data = { points_amount: args.points } ajax(type, url, data, args.successCallback, args.errorCallback) }, getListOfOrders(successCallback, errorCallback) { const type = "GET", url = this.url + modules.accounts.token + '/orders', data = '' ajax(type, url, data, successCallback, errorCallback) }, application: { get url() { return modules.innopoints.api.user.url }, create(application, successCallback, errorCallback) { const type = "POST", url = this.url + modules.accounts.token + "/applications", data = { application:application } ajax(type, url, data, successCallback, errorCallback) }, update(appl_id, new_params, successCallback, errorCallback) { const type = "PUT", url = this.url + modules.accounts.token + "/applications/" + appl_id, data = new_params ajax(type, url, data, successCallback, errorCallback) }, send(appl_id, successCallback, errorCallback) { const type = "PUT", url = this.url + modules.accounts.token + "/applications/" + appl_id + '/approve', data = '' ajax(type, url, data, successCallback, errorCallback) }, get(appl_id, successCallback, errorCallback) { const type = "GET", url = this.url + modules.accounts.token + "/applications/" + appl_id, data = '' ajax(type, url, data, successCallback, errorCallback) }, delete(appl_id, successCallback, errorCallback) { const type = "DELETE", url = this.url + modules.accounts.token + "/applications/" + appl_id, data = '' ajax(type, url, data, successCallback, errorCallback) }, approve(appl_id, successCallback, errorCallback) { const type = "PUT", url = this.url + modules.accounts.token + "/applications/" + appl_id + "/approve", data = '' ajax(type, url, data, successCallback, errorCallback) }, reject(appl_id, successCallback, errorCallback) { const type = "PUT", url = this.url + modules.accounts.token + "/applications/" + appl_id + "/reject", data = '' ajax(type, url, data, successCallback, errorCallback) }, to_rework({ appl_id, comment }, successCallback, errorCallback) { const type = "PUT", url = this.url + modules.accounts.token + "/applications/" + appl_id + "/to_rework", data = { comment } ajax(type, url, data, successCallback, errorCallback) }, dismiss(appl_id, successCallback, errorCallback) { const type = "PUT", url = this.url + modules.accounts.token + "/applications/" + appl_id + "/to_rework", data = '' ajax(type, url, data, successCallback, errorCallback) }, }, applications: { get url() { return modules.innopoints.api.user.url }, get(args) { if (args.status === 'all') args.status = null const type = "GET", url = this.url + modules.accounts.token + "/applications" + (args.status ? '/' + args.status: ''), data = { skip: args.skip_count, limit: args.limit_count } ajax(type, url, data, args.successCallback, args.errorCallback) }, }, }, }, }, } export default modules
3864ca0e533ea7adecbb1278ee01e0e3913c73b3
TypeScript
MonchiLin/modern-magic
/projects/TNOA/chapter4/particle-system-406/sketch.ts
2.515625
3
import "p5" import ParticleSystem from "./particel-system"; import Repeller from "./repeller"; let particleSystem: ParticleSystem let repeller: Repeller function setup() { createCanvas(640, 640) particleSystem = new ParticleSystem(createVector(width / 2, 50)) repeller = new Repeller(createVector(width / 2, height / 2)) } function draw() { background(255) particleSystem.addParticle() particleSystem.applyForce(createVector(0, 0.1)) particleSystem.applyRepeller(repeller) particleSystem.run() repeller.display() } function mousePressed() { } // @ts-ignore window.setup = setup // @ts-ignore window.draw = draw // @ts-ignore window.mousePressed = mousePressed
a43fa66eda24382f724539c727aacacc15a688b6
TypeScript
green-fox-academy/Kerk1990
/week1/day4_typescripts/diamonddrawing.ts
3.421875
3
export {} 'use strict'; let lineCount: number = 7; // Write a program that draws a // diamond like this: // // * // *** // ***** // ******* // ***** // *** // * // // The diamond should have as many lines as lineCount is let mark: string = "*"; let emptyNum: number = lineCount; let decrease: number = lineCount; for ( let i:number = 1; i <= lineCount; i ++){ if (lineCount % 2 == 0){ if (decrease < 0){ break; } if(i <= lineCount/2){ let mrk: string = (" ").repeat(emptyNum); console.log(mrk + mark); mark += "**"; emptyNum --; } else { emptyNum ++; let mrk: string = (" ").repeat(emptyNum); let addMark: string = ("*").repeat(decrease - 1); console.log(mrk + addMark); decrease -= 2; } } else if(lineCount % 2 !== 0){ if (decrease < 0){ break; } if(i <= lineCount/2){ let mrk: string = (" ").repeat(emptyNum); console.log(mrk + mark); mark += "**"; emptyNum --; } else { let mrk: string = (" ").repeat(emptyNum); let addMark: string = ("*").repeat(decrease); console.log(mrk + addMark); decrease -= 2; emptyNum ++; } } }
6d0c64f77faad189f6a73ecca9b5190d7c42ffe8
TypeScript
juancri/covid19-animation-generator
/src/data/preprocessors/DatePlusPreProcessor.ts
3.203125
3
import { DurationLike } from 'luxon'; import * as Enumerable from 'linq'; import { DataPoint, TimeSeries } from '../../util/Types'; interface DatePlusParameters { series: string; plus: DurationLike; limit?: boolean } /** * Shifts the dates for a specific row */ export default class DatePlusPreProcessor { public static async run(series: TimeSeries[], params: unknown): Promise<TimeSeries[]> { const plusParams = params as DatePlusParameters; return series.map(s => DatePlusPreProcessor.shiftSeries(s, plusParams)); } private static shiftSeries(series: TimeSeries, params: DatePlusParameters): TimeSeries { if (series.name !== params.series) return series; const limit = params.limit ? Enumerable .from(series.data) .max(p => +p.date) : null; const data = series.data .map(p => DatePlusPreProcessor.shiftPoint(p, params.plus)) .filter(p => limit === null || +p.date <= limit); return { ...series, data }; } private static shiftPoint(point: DataPoint, plus: DurationLike): DataPoint { return { ...point, date: point.date.plus(plus) }; } }
ae8757497d65c46af552b9d53abafaa9a3ade2e0
TypeScript
Shawn0630/react-dashboard
/__tests__/utilities/array-helper.test.ts
3.4375
3
import { flatten, groupBy } from "~utilities/array-helper"; describe("utilities/array-helper", () => { test("should flatten the array in pure Array", () => { const pureArray: number[] = [1, 2, 3, 4]; expect(flatten(pureArray)).toEqual([1, 2, 3, 4]); }); test("should flatten the array", () => { const pureArray: (number|number[])[] = [1, 2, 3, [4, 5, 6]]; expect(flatten(pureArray)).toEqual([1, 2, 3, 4, 5, 6]); }); test("should group the array by key", () => { interface Car { brand: string; color: string; } const cars: Car[] = [ { brand: "Audi", color: "black" }, { brand: "Audi", color: "white" }, { brand: "Ferarri", color: "red" }, { brand: "Ford", color: "white" }, { brand: "Peugot", color: "white" } ]; const groupByBrand: Function = groupBy("brand"); const groupByColor: Function = groupBy("color"); const carsByBrand: {[key: string]: Car[]} = { "Audi": [ { "brand": "Audi", "color": "black" }, { "brand": "Audi", "color": "white" } ], "Ferarri": [ { "brand": "Ferarri", "color": "red" } ], "Ford": [ { "brand": "Ford", "color": "white" } ], "Peugot": [ { "brand": "Peugot", "color": "white" } ] }; const carsByColor: {[key: string]: Car[]} = { "black": [ { "brand": "Audi", "color": "black" } ], "white": [ { "brand": "Audi", "color": "white" }, { "brand": "Ford", "color": "white" }, { "brand": "Peugot", "color": "white" } ], "red": [ { "brand": "Ferarri", "color": "red" } ] }; expect(groupByBrand(cars)).toEqual(carsByBrand); expect(groupByColor(cars)).toEqual(carsByColor); }); });
3b15884dd48870f5c727bd8b5fb15ff045b7ca0c
TypeScript
clausejs/clausejs
/src/preds/isFn.ts
2.65625
3
export default function isFunction( x ) { var getType = {}; // (x || false) guarantees returning of boolean type return ( x || false ) && [ '[object Function]', '[object GeneratorFunction]' ].indexOf( getType.toString.call( x ) ) >= 0; }
fec91aeddfce4592ba0825c8561e096cf953c21f
TypeScript
daviseford/aos-reminders
/src/factions/ogor_mawtribes/spells.ts
2.5625
3
import { tagAs } from 'factions/metatagger' import { COMBAT_PHASE, HERO_PHASE, WOUND_ALLOCATION_PHASE } from 'types/phases' const Spells = { //BUTCHER SPELLS 'Blood Feast': { effects: [ { name: `Blood Feast`, desc: `Casting value of 7 and a range of 18". Pick 1 friendly OGOR unit that is not a MONSTER and that is wholly within 18" of the caster and visible to them. Add 1 to the Attacks characteristic of that unit's melee weapons until the start of your next hero phase.`, when: [HERO_PHASE], }, ], }, 'Blubbergrub Stench': { effects: [ { name: `Blubbergrub Stench`, desc: `Casting value of 5 and a range of 18". Until the start of your next hero phase, while they are wholly within range of the caster, friendly RHINOX units are treated as MONSTERS for the purposes of the Trampling Charge battle trait; contesting objectives; and carrying out monstrous rampages.`, when: [HERO_PHASE], }, ], }, 'Molten Entrails': { effects: [ { name: `Molten Entrails`, desc: `Casting value of 5. Pick 1 friendly OGOR MAWTRIBES MONSTER wholly within 18" of the caster that is visible to them. Until the start of your next hero phase, add 1 to the Damage characteristic of the melee weapons used by that MONSTER'S mount.`, when: [HERO_PHASE], }, { name: `Molten Entrails`, desc: `If active, add 1 to the Damage characteristic of the melee weapons used by that MONSTER'S mount.`, when: [COMBAT_PHASE], }, ], }, 'Greasy Deluge': { effects: [ { name: `Greasy Deluge`, desc: `Casting value of 6. Pick 1 enemy unit within 18" of the caster that is visible to them. Subtract 1 from hit rolls for attacks made by that unit until the start of your next hero phase.`, when: [HERO_PHASE], }, ], }, //FIREBELLY SPELLS 'Fiery Whirlwind': { effects: [ { name: `Fiery Whirlwind`, desc: `Casting value of 6. Pick one enemy unit and roll 1 dice for each model in that unit that is within 12" of the caster and visible to them. For each 4+, that unit suffers 1 mortal wound. If that unit only has 1 model, roll 3 dice instead of 1.`, when: [HERO_PHASE], }, ], }, 'Billowing Ash': { effects: [ { name: `Billowing Ash`, desc: `Casting value of 6. Until the start of your next hero phase, subtract 1 from hit rolls for attacks that target friendly units wholly within 12" of the caster.`, when: [HERO_PHASE], }, ], }, 'Tongues of Flame': { effects: [ { name: `Tongues of Flame`, desc: `Casting value of 6. Pick 1 enemy unit that has 5 or more models that are within 18" of the caster and visible to them. Until the start of your next hero phase, each time that unit finishes a move, it suffers D3 mortal wounds.`, when: [HERO_PHASE], }, ], }, //UNIT SPELLS 'Voracious Maw': { effects: [ { name: `Voracious Maw`, desc: `Casting value of 7. Pick 1 enemy unit within 18" of the caster that is visible to them. That unit suffers D3 mortal wounds. After resolving any damage, roll a D6. On a 1, 2 or 3, the maw is said to be satisfied and the spell ends. On a 4+, the target unit suffers D3 additional mortal wounds. Keep repeating this process until the maw is satisfied or the target unit is destroyed.`, when: [HERO_PHASE], }, ], }, 'Cascading Fire-cloak': { effects: [ { name: `Cascading Fire-cloak`, desc: `Casting value of 5. Roll 1 dice for each enemy unit within 3" of the caster. On a 4+, that enemy unit suffers D3 mortal wounds. In addition, if this spell is successfully cast, this unit has a ward of 5+ until the start of your next hero phase.`, when: [HERO_PHASE], }, { name: `Cascading Fire-cloak`, desc: `If active, this unit has a ward of 5+ until the start of your next hero phase.`, when: [WOUND_ALLOCATION_PHASE], }, ], }, Rockchomper: { effects: [ { name: `Rockchomper`, desc: `Casting value of 5. Pick 1 friendly unit of Ogor Gluttons wholly within 18" of the caster that is visible to them. Until the start of your next hero phase, rolls made for the Gulping Bite batlle trait cause D6 mortal wounds on a 4+ instead of D3.`, when: [HERO_PHASE], }, ], }, } export default tagAs(Spells, 'spell')
dfffcf3bb25b77b3246564caa2aff7303b4250d7
TypeScript
Jagiello95/wyprawnik
/src/app/shared/directives/control.directive.ts
2.625
3
import { Directive, ElementRef, HostBinding, HostListener, OnInit } from '@angular/core'; import { NgControl } from '@angular/forms'; enum ValidityStatus { valid= "VALID", invalid= "INVALID" } @Directive({ selector: '[formControlName]' }) export class ControlDirective implements OnInit { public blurred: boolean = false; constructor(private control : NgControl, private elementRef: ElementRef) { } ngOnInit() { console.log(this.elementRef) } // @HostBinding('class.is-filled') // public get classRequired(): boolean { // return Array.isArray(this.control.control?.value) ? // this.control.control?.value.length: // this.control.control?.value // } // @HostBinding('class.is-touched') // public get classTouched(): boolean { // return this.control.control?.touched === true; // } // @HostBinding('class.is-dirty') // public get classDirty(): boolean { // return this.control.control?.pristine !== true; // } // @HostBinding('class.is-valid') // public get classValid(): boolean { // return this.control.control?.status === ValidityStatus.valid; // } }
54e033a589a887415841b9fbdae616e7ce4fa9d0
TypeScript
jKelio/eventobserver
/src/lib/event-subject.ts
2.59375
3
export interface EventSubject<T> { subscribe(fn: T): void; unsubscribe(fn: T): void; unsubscribeAll(fn: T): void; emit(...args: Array<any>): void; //Promise<Array<any>>; }
72b6b437a631603cd315b3868bede6e62dfbf1c5
TypeScript
fluidnext/library-sport
/src/soccer/SoccerPlayer.ts
3.09375
3
import { AbstractPlayer } from "../AbstractPlayer"; import { PlayerInterface } from "../PlayerInterface"; /** * @class SoccerPlayer */ export class SoccerPlayer extends AbstractPlayer implements PlayerInterface{ /** * * @param {string} number * @param {string} name */ constructor(number: string, name: string){ super(); this.shirtNumber = number; this.shirtName = name; } }
fef8275c3571e2576c8f0b79b35390832244d240
TypeScript
kjirou/typescript-playground
/examples/omit.ts
2.828125
3
type Foo = { x: number, y: string, z: boolean, }; type Bar = Omit<Foo, 'y'>; type Baz = Omit<Foo, 'x' | 'z'>; const bar: Bar = { x: 1, z: true, }; const baz: Baz = { y: '', }; // NG //const unBar: Bar = { // x: '', // z: true, //}; // NG //const unBaz: Baz = { // x: 1, // y: '', //}; export {}
3b9da1f8b75b35db69f2f5a6dd5c663db4de5cb4
TypeScript
fivetran/typescript-closure-tools
/index/closure-library/closure/goog/demos/xpc/xpcdemo.d.ts
2.5625
3
/// <reference path="../../../../globals.d.ts" /> declare module xpcdemo { /** * Initializes XPC in the containing page. */ function initOuter(): void; /** * Initialization in the iframe. */ function initInner(): void; /** * Kills the peer iframe and the disposes the channel. */ function teardown(): void; /** * Logging function. Inserts log-message into element with it id 'console'. * @param {string} msgString The log-message. */ function log(msgString: string): void; /** * Sends a ping request to the peer. */ function ping(): void; /** * Start mousemove event forwarding. Registers a listener on the document which * sends them over the channel. */ function startMousemoveForwarding(): void; /** * Stop mousemove event forwarding. */ function stopMousemoveForwarding(): void; /** * Send multiple messages. * @param {number} n The number of messages to send. */ function sendN(n: number): void; }
026c2b8757dc196d4fc38b7f2907617e750d5a39
TypeScript
negezor/vk-io
/packages/vk-io/src/structures/contexts/dialog-notification-settings.ts
2.734375
3
import { Context, ContextFactoryOptions, ContextDefaultState } from './context'; import { pickProperties } from '../../utils/helpers'; import { kSerializeData } from '../../utils/constants'; export type DialogNotificationSettingsContextType = 'dialog_notification_settings'; export type DialogNotificationSettingsContextSubType = 'dialog_notification_settings_subscribe' | 'dialog_notification_settings_unsubscribe'; export interface IDialogNotificationSettingsContextPayload { peer_id: number; sound: 0 | 1; disabled_until: number; } export type DialogNotificationSettingsContextOptions<S> = ContextFactoryOptions<[number, IDialogNotificationSettingsContextPayload], S>; export class DialogNotificationSettingsContext<S = ContextDefaultState> extends Context< IDialogNotificationSettingsContextPayload, S, DialogNotificationSettingsContextType, DialogNotificationSettingsContextSubType > { public constructor(options: DialogNotificationSettingsContextOptions<S>) { const [, payload] = options.payload; const { disabled_until } = payload; super({ ...options, type: 'dialog_notification_settings', subTypes: [ disabled_until === 0 ? 'dialog_notification_settings_subscribe' : 'dialog_notification_settings_unsubscribe', ], payload: payload, }); } /** * Returns the peer identifier */ public get peerId(): number { return this.payload.peer_id; } /** * Returns time until that notifications are disabled in seconds */ public get disabledUntil(): number { return this.payload.disabled_until; } /** * Checks that the notifications have sound */ public get hasSound(): boolean { return Boolean(this.payload.sound); } /** * Checks that the user has subscribed to dialog */ public get isSubscribed(): boolean { return this.subTypes.includes('dialog_notification_settings_subscribe'); } /** * Checks that the user has unsubscribed to dialog */ public get isUnsubscribed(): boolean { return this.subTypes.includes('dialog_notification_settings_unsubscribe'); } /** * Returns the custom data */ public [kSerializeData](): object { return pickProperties(this, [ 'peerId', 'hasSound', 'disabledUntil', 'isSubscribed', 'isUnsubscribed', ]); } }
e90fde82d27ad97e8e29d2f7162639e55f660dd0
TypeScript
reynardmh/db-fabricator.js
/test/fabricator.spec.ts
2.765625
3
import { Fabricator } from '../src/fabricator'; import { DataStoreAdaptor } from '../src/data-store-adaptor'; import * as Promise from 'bluebird'; import { expect } from 'chai'; class IdCounter { static counter: Object = {}; static getId(name: string) { if (this.counter.hasOwnProperty(name)) { return ++this.counter[name]; } else { return this.counter[name] = 1; } } } class MemoryDB { private data: Object = {}; create(name: string, doc: any): Object { // console.log(doc); if (!this.data.hasOwnProperty(name)) { this.data[name] = {}; } this.data[name][doc.id] = doc; return doc; } find(name: string, id: number): Object { return this.data[name][id]; } } class MemoryDBAdaptor implements DataStoreAdaptor { constructor(public db?: MemoryDB) {} createData(tableName: string, finalAttr: Object): Promise<any> { let doc = Object.assign({}, finalAttr, { id: IdCounter.getId(tableName) }); if (this.db) { this.db.create(tableName, doc) } return new Promise<any>((resolve, reject): any => { resolve(doc); }); } } describe('fabricator', () => { let DB = new MemoryDB(); before(() => { Fabricator.setAdaptor(new MemoryDBAdaptor(DB)); }); describe('with non async function attribute', function() { before(() => { Fabricator.clearTemplate(); Fabricator.template({ name: 'user', attr: { firstName: 'Bob', lastName: 'Smith', username: (obj) => `${obj.firstName}.${obj.lastName}` } }); }); it('creates object with composed attribute', function(done) { Fabricator.fabricate('user') .then((user) => { expect(user.firstName).to.equal('Bob'); expect(user.username).to.equal('Bob.Smith'); done(); }); }); it('creates object with overriden attributes', function(done) { Fabricator.fabricate('user', { firstName: 'Jon' }) .then((user) => { expect(user.firstName).to.equal('Jon'); expect(user.username).to.equal('Jon.Smith'); done(); }); }); it('creates object with overidden function attribute', function(done) { Fabricator.fabricate('user', { firstName: 'Jon', username: 'jon123' }) .then((user) => { expect(user.firstName).to.equal('Jon'); expect(user.lastName).to.equal('Smith'); expect(user.username).to.equal('jon123'); done(); }); }); }); describe('with nested async function attributes', () => { before(() => { Fabricator.clearTemplate(); Fabricator.template({ name: 'organization', attr: { name: 'Fabricator Inc' } }); Fabricator.template({ name: 'department', attr: { name: 'IT', organizationId: () => Fabricator.fabGetId('organization') } }); Fabricator.template({ name: 'user', attr: { firstName: 'Bob', lastName: 'Smith', username: (obj) => `${obj.firstName}.${obj.lastName}`, departmentId: () => Fabricator.fabGetId('department') } }); Fabricator.template({ name: 'user-fulltime', from: 'user', attr: { type: 'fulltime' } }); Fabricator.template({ name: 'user-fulltime-US', from: 'user-fulltime', attr: { country: 'US' } }); }); it('creates object with composed attribute', function(done) { Fabricator.fabricate('user') .then((user) => { expect(user.username).to.equal('Bob.Smith'); let dept = <any>DB.find('department', user.departmentId); let org = <any>DB.find('organization', dept.organizationId); expect(dept.name).to.equal('IT'); expect(org.name).to.equal('Fabricator Inc'); done(); }); }); it('create using nested templates', function(done) { Promise.all([ Fabricator.fabricate('user-fulltime', { firstName: 'Tom' }), Fabricator.fabricate('user-fulltime-US', { firstName: 'Matt' }) ]).spread((user1: any, user2: any) => { expect(user1.type).to.equal('fulltime'); expect(user2.type).to.equal('fulltime'); expect(user1.firstName).to.equal('Tom'); expect(user2.firstName).to.equal('Matt'); expect(user2.country).to.equal('US'); done(); }); }); it('create using promise as attribute', function(done) { let orgPromise = Fabricator.fabricate('organization'); let deptPromise = Fabricator.fabricate('department', { organizationId: Fabricator.getId(orgPromise) }); Promise.all([orgPromise, deptPromise]).spread((org: any, dept: any) => { expect(dept.organizationId).to.equal(org.id); done(); }); }); }); describe('with after create hook', () => { before(() => { Fabricator.clearTemplate(); Fabricator.template({ name: 'department', attr: { name: 'IT', organizationId: () => Fabricator.fabGetId('organization') } }); Fabricator.template({ name: 'organization', attr: { name: 'Fabricator Inc' }, afterCreate: (org) => { let promises: any[] = []; promises.push(Fabricator.fabricate('department', { organizationId: org.id })); return Promise.all(promises).then((departments) => { org.departments = departments; return org; }); } }); }); it('create org.departments with after create hook', function() { Fabricator.fabricate('organization').then(org => { expect(org.departments.length).to.equal(1); expect(org.departments[0].organizationId).to.equal(org.id); }); }); }); });
443d5d28a5d820efa10d1d88e6d204919513ff33
TypeScript
imsks/donatecart-assignment
/src/controllers/index.ts
2.59375
3
import { Request, Response } from 'express'; import moment from 'moment'; import { CampaignData } from '../interfaces'; import Campaigns from '../assets/campaigns.json'; // 1. Get all campaigns with descending order of total amount export const getAllCampaigns = async ( request: Request, response: Response, ): Promise<void> => { const campaignsData = Campaigns.result as Array<CampaignData>; campaignsData.sort((prev, next) => next.totalAmount - prev.totalAmount); response.status(200).json({ status: true, payload: campaignsData, }); }; // 2. Get all campaigns active since last month export const getActiveCampaignsCreatedLastMonth = async ( request: Request, response: Response, ): Promise<void> => { const campaignsData = Campaigns.result as Array<CampaignData>; // Filter all active campaigns const allActiveCampagns = campaignsData.filter(campaignData => { const { endDate } = campaignData; const endDateMoment = moment(endDate); const todayMoment = moment(); return endDateMoment.isAfter(todayMoment); }); // Filter all active campaigns created last month const activeCampaignsCreatedLastMonth = allActiveCampagns.filter( campaignData => { const { created } = campaignData; const createdDateMoment = moment(created); const todayMoment = moment(); return createdDateMoment.isAfter(todayMoment.subtract(1, 'month')); }, ); response.status(200).json({ status: true, payload: activeCampaignsCreatedLastMonth, }); }; // 3. Get all closed campaigns export const getClosedCampaigns = async ( request: Request, response: Response, ): Promise<void> => { const campaignsData = Campaigns.result as Array<CampaignData>; // Filter all closed campaigns const allClosedCampagns = campaignsData.filter(campaignData => { const { endDate } = campaignData; const endDateMoment = moment(endDate); const todayMoment = moment(); return endDateMoment.isBefore(todayMoment); }); response.status(200).json({ status: true, payload: allClosedCampagns, }); };
3a53f159b80f7186ae4c00840eefb51157e7730e
TypeScript
richinhim/ngTodo1
/js/rxjs/05_count.ts
3
3
import {Observable} from "rxjs"; // 최종처리 operator: 한개의 최종값을 Observable로 리턴 // 최종처리 연산자-단일값으로 리턴하고, 스트림을 끝내고 싶을때 사용해야 const source = Observable.of(1, 2, 3, 4); const result = source.count(); const subscribe = result.subscribe(val => console.log('Sum:', val));
13d72f789ed24efe81bc6404e8762acabb4254c7
TypeScript
sanity-io/get-it
/src/middleware/agent/node-agent.ts
2.921875
3
import {Agent as HttpAgent, AgentOptions} from 'http' import {Agent as HttpsAgent} from 'https' const isHttpsProto = /^https:/i /** * Constructs a http.Agent and uses it for all requests. * This can be used to override settings such as `maxSockets`, `maxTotalSockets` (to limit concurrency) or change the `timeout`. * @public */ export function agent(opts?: AgentOptions): any { const httpAgent = new HttpAgent(opts) const httpsAgent = new HttpsAgent(opts) const agents = {http: httpAgent, https: httpsAgent} return { finalizeOptions: (options: any) => { if (options.agent) { return options } // When maxRedirects>0 we're using the follow-redirects package and this supports the `agents` option. if (options.maxRedirects > 0) { return {...options, agents} } // ... otherwise we'll have to detect which agent to use: const isHttps = isHttpsProto.test(options.href || options.protocol) return {...options, agent: isHttps ? httpsAgent : httpAgent} }, } }
aba8bbca02ec126d6415ce323dc839faff1dd132
TypeScript
krumyc3/ng2-project-management
/src/app/store/actions/user.actions.ts
2.5625
3
import { Injectable } from '@angular/core'; import { User } from '../../models/user'; export interface UserAction { type: string; payload?: any; } @Injectable() export class UserActions { static SIGN_UP_USER = 'SIGN_UP_USER'; static SING_IN_USER = 'SIGN_IN_USER'; static CLEAR_USER = 'CLEAR_USER'; static UPDATE_USER_INFO = 'UPDATE_USER_INFO'; updateUserInfo(user: User): UserAction { return { type: UserActions.UPDATE_USER_INFO, payload: { ...user } }; } clearUser(): UserAction { return { type: UserActions.CLEAR_USER, }; } signInUser(id: string, email: string, token: string): UserAction { return { type: UserActions.SING_IN_USER, payload: { id, email, token } }; } signUpUser(id: string, email: string, token: string): UserAction { return { type: UserActions.SIGN_UP_USER, payload: { id, email, token } }; } }
da1efcea02ddf71b0eadbb83d92fa726fdcb0ad5
TypeScript
developerprofile/docker-run
/src/common/error.ts
2.671875
3
import { DEFAULT_FILE_NAME } from "./constants"; export class NoFolderOrWorkspaceOpenedError extends Error { constructor(message: string = "No folder or workspace opened") { super(message); this.name = 'No Folder Or Workspace Opened Error'; } } export class AutoGenerateConfigDisabledError extends Error { constructor(message: string) { super(message); this.name = 'Disabled Auto Generate Config Error'; } } export class AutoStopNonRelatedDisabledError extends Error { constructor(message: string) { super(message); this.name = 'Disabled Auto Stop Non Related Error'; } } export class SelectedNoError extends Error { constructor(message: string) { super(message); this.name = 'Selected No Error'; } } export class DockerrcNotFoundError extends Error { constructor(message: string = `No ${DEFAULT_FILE_NAME} provided`) { super(message); this.name = `Config File Not Found`; } } export class EmptyConfigError extends Error { constructor(message: string, fileName: string) { super(message); this.setFileName(fileName); } setFileName(fileName: string) { this.name = `Empty Config [${fileName}]`; } } export class EmptyConfigArrayError extends EmptyConfigError { constructor(message = 'Configuration Array Is Empty', fileName = "Config Util") { super(message, fileName); } } export class EmptyConfigFileError extends EmptyConfigError { constructor(message = 'Configuration File Is Empty', fileName = "Config Util") { super(message, fileName); } } export class NoContainersFoundError extends Error { constructor(message = 'No Containers Found') { super(message); } } export const handleError = (error: Error) => console.warn(error);
b6cf714b2237f39c78118185c8ad4b828f843bb2
TypeScript
varyandeveloper/ts-boilerplate
/modules/api/exception/exception.ts
3.078125
3
export default class Exception extends Error { protected _statusCode: number; constructor(message: string, statusCode = 500) { super(message); this._statusCode = statusCode; Object.setPrototypeOf(this, Exception.prototype); } get statusCode(): number { return this._statusCode; } }
db4fabb0e655b4bd4cd561f034da380bb2d9966c
TypeScript
brychanthomas/game-3
/src/player.ts
3
3
import { GameMap } from './scenes.js'; interface wasdKeys { 'W'?: Phaser.Input.Keyboard.Key, 'A'?: Phaser.Input.Keyboard.Key, 'S'?: Phaser.Input.Keyboard.Key, 'D'?: Phaser.Input.Keyboard.Key } /** * Abstract class that creates sprite and scene properties * for players. */ abstract class Player { protected sprite: Phaser.GameObjects.Sprite; protected scene: GameMap; /** Whether or not player is chaser */ protected isChaser: boolean; constructor(x: number, y: number, scene: GameMap) { this.sprite = scene.physics.add.sprite(x, y, 'player'); this.sprite.setScale(0.3); this.sprite.body.setSize(250/2.2, 250/2.2); this.sprite.depth = 19; //bring forwards but behind fog of war this.scene = scene; this.isChaser = false; } /** * Remove the sprite from the scene. */ destroy() { this.sprite.destroy(); } /** * Give the player sprite a red tint, indicating they are the chaser. */ private makeRed() { this.sprite.setTint(0xff0000); } /** * Set the texture of the player to "chaser" or "player" */ private set texture(t: "chaser"|"player") { this.sprite.setTexture(t); let tex = this.scene.textures.get(t); let frame = tex.frames[tex.firstFrame]; //set physics body size based on new texture let sideLength = (t==="chaser") ? frame.width : frame.width/2.2; this.sprite.body.setSize(sideLength, sideLength); } /** * Change the player's texture and move them to (1000, 200). They are the chaser. */ chosen() { //this.makeRed(); this.isChaser = true; this.texture = 'chaser'; this.sprite.x = 1000; this.sprite.y = 200; } public get x() { return this.sprite.x; } public get y() { return this.sprite.y; } /** * Apply the correct animation based on player's velocity. */ protected updateAnimation() { let prefix = this.isChaser ? 'chaser' : 'player'; let velX = this.sprite.body.velocity.x; let velY = this.sprite.body.velocity.y if (velX !== 0 || velY !== 0) { let direction = ''; direction += (velY===0 ? '' : (velY>0 ? 'S' : 'N')); direction += (velX===0 ? '' : (velX>0 ? 'E' : 'W')); this.sprite.anims.play(prefix+'-'+direction, true); } } } /** * Class representing the player that is being controlled * by the user, as opposed to a remote multiplayer player. */ export class LocalPlayer extends Player { private keys: wasdKeys; private previousVelocityX: number; private previousVelocityY: number; private amCaught: boolean; public speed: number; /** If the player is locked they can't move */ public locked: boolean; constructor(x: number, y: number, obstacleLayer: Phaser.Tilemaps.StaticTilemapLayer, scene: GameMap) { super(x, y, scene); scene.cameras.main.startFollow(this.sprite); this.keys = scene.input.keyboard.addKeys('W,A,S,D'); scene.physics.add.collider(this.sprite, obstacleLayer); this.speed = 200; this.locked = false; } /** * Update the velocity of the player based on the WASD keys. */ update() { if (!this.locked) { var blockedTop = this.sprite.body.top <= 0; var blockedBtm = this.sprite.body.bottom >= this.scene.height; var blockedLft = this.sprite.body.left <= 0; var blockedRgt = this.sprite.body.right >= this.scene.width var velX = 0; var velY = 0; if (this.keys.W.isDown && !blockedTop) { velY = -this.speed; } else if (this.keys.S.isDown && !blockedBtm) { velY = this.speed; } if (this.keys.A.isDown && !blockedLft) { velX = -this.speed; } else if (this.keys.D.isDown && !blockedRgt) { velX = this.speed; } if (velX !== 0 && velY !== 0) { velX = Math.sqrt((this.speed**2)/2) * velX/Math.abs(velX); velY = Math.sqrt((this.speed**2)/2) * velY/Math.abs(velY); } this.sprite.body.setVelocityX(Math.round(velX)); this.sprite.body.setVelocityY(Math.round(velY)); } else { this.sprite.body.setVelocityX(0); this.sprite.body.setVelocityY(0); } this.updateAnimation(); } /** * Checks if X or Y velocity has changed since last time method * was called. Always false if player has been caught. */ hasVelocityChanged() { if (this.amCaught) { return false; } var changed = false; if (this.velocityX !== this.previousVelocityX) { this.previousVelocityX = this.velocityX; changed = true; } if (this.velocityY !== this.previousVelocityY) { this.previousVelocityY = this.velocityY; changed = true; } return changed; } /** * Gets the x velocity of the player. If they are pushing against an obstacle * 0 is returned. */ get velocityX() { if (this.sprite.body.velocity.x > 0 && this.sprite.body.blocked.right) { return 0; } if (this.sprite.body.velocity.x < 0 && this.sprite.body.blocked.left) { return 0; } return this.sprite.body.velocity.x; } /** * Gets the y velocity of the player. If they are pushing against an obstacle * 0 is returned. */ get velocityY() { if (this.sprite.body.velocity.y > 0 && this.sprite.body.blocked.down) { return 0; } if (this.sprite.body.velocity.y < 0 && this.sprite.body.blocked.up) { return 0; } return this.sprite.body.velocity.y; } /** * When caught is set to true, the player becomes transparent, * collisions are disabled, speed is set to 200 and velocity * updates are not sent. */ set caught(c: boolean) { this.amCaught = c; this.sprite.setAlpha(c ? 0.4 : 1); if (c === true) { this.speed = 200; this.sprite.body.checkCollision = { down: false, left: false, none: true, right: false, up: false } } else { this.sprite.body.checkCollision = { down: true, left: true, none: false, right: true, up: true } } } get caught() { return this.amCaught; } /** Check if W, A, S or D is down */ get keyDown() { return (this.keys.W.isDown || this.keys.S.isDown || this.keys.A.isDown || this.keys.D.isDown); } } /** * Class to represent a player that isn't being controlled * by the user, and is being controlled remotely as part of * multiplayer. */ export class RemotePlayer extends Player { public id: number; private nametag: Phaser.GameObjects.Text; constructor(x: number, y: number, id: number, username: string, scene: GameMap) { super(x, y, scene); this.id = id; this.nametag = scene.add.text(x, y-30, username, {backgroundColor: '#000'}); this.nametag.setOrigin(0.5); this.nametag.setAlpha(0.6); this.nametag.setDepth(19); } set x(x: number) { this.sprite.x = x; } set y(y: number) { this.sprite.y = y; } set velocityX(velX: number) { this.sprite.body.setVelocityX(velX); this.updateAnimation(); } set velocityY(velY: number) { this.sprite.body.setVelocityY(velY); this.updateAnimation(); } /** * Move the nametag to the position of the player */ updateNametag() { this.nametag.x = this.sprite.x; this.nametag.y = this.sprite.body.top-10; } get x() { return this.sprite.x; } get y() { return this.sprite.y; } /** * Set visibility of sprite and nametag. */ set visible(v: boolean) { this.sprite.visible = v; this.nametag.visible = v; } public destroy() { this.sprite.destroy(); this.nametag.destroy(); } }
e0df6ec60cd3fe431814ea2d0bd2cf09b2bac0eb
TypeScript
WilliamRitson/CS-Sideprojects
/src/app/set-theory/set-parser.ts
2.796875
3
import { TokenError } from '@angular/compiler/src/ml_parser/lexer'; import { Scanner, Token, TokenType } from './set-scanner'; import * as exprs from './set-expr'; enum TokenEvalType { infix, groupingLeft, groupingRight, rightUnary, value } class TokenSetting { type: TokenEvalType; priority: number; generator: exprs.SetExprNewable; constructor(type: TokenEvalType, priority: number, generator: exprs.SetExprNewable) { this.type = type; this.priority = priority; this.generator = generator; } } const parserSettings = new Map<TokenType, TokenSetting>([ [TokenType.variable, new TokenSetting(TokenEvalType.value, 1, exprs.VariableSetExpr)], [TokenType.universal, new TokenSetting(TokenEvalType.value, 1, exprs.UniversalSetExpr)], [TokenType.empty, new TokenSetting(TokenEvalType.value, 1, exprs.EmptySetExpr)], [TokenType.left_paren, new TokenSetting(TokenEvalType.groupingLeft, 4, exprs.ParenSetExpr)], [TokenType.right_paren, new TokenSetting(TokenEvalType.groupingRight, 4, exprs.ParenSetExpr)], [TokenType.union, new TokenSetting(TokenEvalType.infix, 2, exprs.UnionSetExpr)], [TokenType.intersection, new TokenSetting(TokenEvalType.infix, 2, exprs.IntersectionSetExpr)], [TokenType.complement, new TokenSetting(TokenEvalType.rightUnary, 1, exprs.ComplementSetExpr)], [TokenType.difference, new TokenSetting(TokenEvalType.infix, 2, exprs.DifferenceSetExpr)] ]); export class Parser { private scanner: Scanner; constructor() { this.scanner = new Scanner(); } parse(source: string): exprs.SetTreeExpr { let tokens = this.scanner.tokenize(source); return this.parseTokens(tokens); } private getLowestPriority(tokens: Array<Token>): number { let lowestIndex = { index: 0, priority: Infinity, parenLevel: Infinity } let parenLevel = 0; for (let i = 0; i < tokens.length; i++) { let token = tokens[i]; if (token.type === TokenType.left_paren) parenLevel++; let priority = -parserSettings.get(tokens[i].type).priority; //console.log(parenLevel, TokenType[token.type], priority, parenLevel, parenLevel <= lowestIndex.parenLevel, priority <= lowestIndex.priority); if (parenLevel < lowestIndex.parenLevel || parenLevel == lowestIndex.parenLevel && priority <= lowestIndex.priority) { lowestIndex = { index: i, priority: priority, parenLevel: parenLevel }; //console.log('lin', lowestIndex); } if (token.type === TokenType.right_paren) parenLevel--; } return lowestIndex.index; } private getGroupEnd(type: TokenType, tokens: Array<Token>): number { let complement = type == TokenType.left_paren ? TokenType.right_paren : TokenType.left_paren; let counter = 1; for (let i = tokens.length - 1; i >= 0; i--) { if (tokens[i].type == type) counter++; if (tokens[i].type == complement) counter--; if (counter == 0) return i + 1; } return tokens.length - 1; } private parseTokens(tokens: Array<Token>): exprs.SetTreeExpr { let index = this.getLowestPriority(tokens); let token = tokens[index]; let settings = parserSettings.get(token.type); let left = tokens.slice(0, index); let right = tokens.slice(index + 1, tokens.length); // console.log("pt", index, TokenType[tokens[index].type]); switch (settings.type) { case (TokenEvalType.infix): return new settings.generator( token, this.parseTokens(left), this.parseTokens(right) ); case (TokenEvalType.groupingRight): let groupedTokens = left.slice(this.getGroupEnd(token.type, left), left.length); return new settings.generator( token, this.parseTokens(groupedTokens), null );; case (TokenEvalType.rightUnary): return new settings.generator( token, this.parseTokens(left), null ); case (TokenEvalType.value): return new settings.generator(token, null, null); } } }
8e6379f4c364102238708439f5c8744d7cd5e8f1
TypeScript
BigBadAlien/places
/src/app/actions/auth.ts
2.671875
3
import { ThunkAction } from 'redux-thunk'; import { RootState } from '../reducers'; import { AnyAction } from 'redux'; import { ApiSignInPayload } from '../models/ApiSignInPayload'; import { createAction } from 'redux-actions'; import { ApiUserResponse } from '../models/ApiUserResponse'; import { environment } from '../../environment'; import { ApiError } from '../models/ApiError'; export namespace AuthActions { export enum Type { AUTH_SET_CURRENT_USER = 'AUTH_SET_CURRENT_USER', AUTH_SET_ERROR = 'AUTH_SET_ERROR', AUTH_RESET_ERROR = 'AUTH_RESET_ERROR', } export const signIn = function ( payload: ApiSignInPayload ): ThunkAction<void, RootState, void, AnyAction> { return (dispatch) => { return ApiPostAuth(payload) .then((user) => { dispatch(setCurrentUser(user)); }) .catch((error: Error | ApiError) => { dispatch(setAuthError(error)); }); }; }; const ApiPostAuth = (payload: ApiSignInPayload): Promise<ApiUserResponse> => { return fetch(environment.api.auth, { method: 'POST', body: `email=${payload.email}&password=${payload.password}`, headers: new Headers({'Content-Type': 'application/x-www-form-urlencoded'}), }).then((response) => { return response.json() .then((responseData) => { if (response.status === 200) { return responseData; } throw responseData; }); }); }; export const setCurrentUser = createAction<ApiUserResponse>(Type.AUTH_SET_CURRENT_USER); export const setAuthError = createAction<Error | ApiError>(Type.AUTH_SET_ERROR); export const resetAuthError = createAction<void>(Type.AUTH_RESET_ERROR); } export type AuthActions = Omit<typeof AuthActions, 'Type'>;
e7022d2b304b9a7adccc4a7cc9cce8df5dc48525
TypeScript
herculesinc/nova.azure-functions
/lib/util.ts
2.921875
3
// IMPORTS // ================================================================================================= import { Credentials, StringBag } from '@nova/azure-functions'; // MODULE VARIABLES // ================================================================================================= const IPV4_REGEX = /[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}/; // HEADERS // ================================================================================================= export function parseAuthHeader(headers: StringBag): Credentials { const header = headers['authorization'] || headers['Authorization'] if (!header) return undefined; const authParts = header.split(' '); if(authParts.length !== 2) return null; return { type : authParts[0], data : authParts[1] }; } export function getIpAddress (headers: StringBag): string { const header = headers['x-forwarded-for'] || headers['X-Forwarded-For']; if (!header) return undefined; const addresses = parseForwardedHeader(header); const clientAddress = addresses[0]; if (!clientAddress) return undefined; let ip = matchIpV4(clientAddress); if (ip) return ip; // TODO: implement IPV6 parsing } // IP PARSING // ================================================================================================= function parseForwardedHeader(header: string): string[] { let end = header.length; let list = []; let start = header.length; // gather addresses, backwards for (let i = header.length - 1; i >= 0; i--) { switch (header.charCodeAt(i)) { case 0x20: /* */ { if (start === end) { start = end = i; } break; } case 0x2c: /* , */ { if (start !== end) { list.push(header.substring(start, end)); } start = end = i; break; } default: { start = i; break; } } } // final address if (start !== end) { list.push(header.substring(start, end)); } return list; } export function matchIpV4(value: string): string { if (!value) return undefined; const result = value.match(IPV4_REGEX); if (result) return result[0]; } // PATH CHECKING // ================================================================================================= export function cleanPath(path: string) { if (!path) throw new TypeError(`Path '${path}' is not valid`); if (typeof path !== 'string') throw new TypeError(`Path '${path}' is not valid: path must be a string`); if (path.charAt(0) !== '/') throw new TypeError(`Path '${path}' is not valid: path must start with '/'`); if (path !== '/') { while (path.charAt(path.length - 1) === '/') { path = path.slice(0, -1); // removes last character if (path.length === 1) break; } } return path; } // FUNCTION CHECKING // ================================================================================================= export function isRegularFunction(fun: Function): boolean { if (typeof fun !== 'function') return false; const definition = fun.toString(); return (definition.startsWith('function') || definition.startsWith('async function')); }
8f9810e0b0b18a9517b34ae76c21f53e2ba897bb
TypeScript
rd113267/WordOfGodForEachDayArabic
/app/bibleRef.ts
2.703125
3
export const sequence: number[] = [ 1, 40, 2, 41, 3, 4, 5, 42, 6, 43, 7, 8, 44, 9, 10, 45, 11, 46, 12, 13, 14, 47, 15, 48, 16, 49, 17, 50, 18, 51, 19, 52, 20, 53, 21, 22, 54, 23, 55, 24, 25, 56, 57, 26, 58, 27, 59, 28, 60, 61, 29, 30, 31, 32, 62, 33, 34, 35, 36, 63, 64, 65, 37, 38, 39, 66, ]; const bookInfo: { [key: number]: { length: number } } = { // Genesis 1: { length: 46, }, // Exodus 2: { length: 26, }, // Leviticus 3: { length: 13, }, // Numbers 4: { length: 17, }, // Deuteronomy 5: { length: 19, }, // Joshua 6: { length: 18, }, // Judges 7: { length: 16, }, // Ruth 8: { length: 4, }, // 1 Samuel 9: { length: 22, }, // 2 Samuel 10: { length: 10, }, // 1 Kings 11: { length: 17, }, // 2 Kings 12: { length: 12, }, // 1 Chronicles 13: { length: 1, }, // 2 Chronicles 14: { length: 2, }, // Ezra 15: { length: 10, }, // Nehemiah 16: { length: 11, }, // Esther 17: { length: 10, }, // Job 18: { length: 30, }, // Psalms 19: { length: 48, }, // Proverbs 20: { length: 28, }, // Ecclesiastes 21: { length: 11, }, // Song 22: { length: 1, }, // Isaiah 23: { length: 38, }, // Jeremiah 24: { length: 26, }, // Lamentations 25: { length: 3, }, // Ezekiel 26: { length: 11, }, // Daniel 27: { length: 9, }, // Hosea 28: { length: 6, }, // Joel 29: { length: 1, }, // Amos 30: { length: 1, }, // Obadiah 31: { length: 1, }, // Jonah 32: { length: 4, }, // Micah 33: { length: 2, }, // Nahum 34: { length: 2, }, // Habakkuk 35: { length: 3, }, // Zephaniah 36: { length: 2, }, // Haggai 37: { length: 1, }, // Zechariah 38: { length: 5, }, // Malachi 39: { length: 2, }, // N E W T E S T A M E N T // Matthew 40: { length: 28, }, // Mark 41: { length: 16, }, // Luke 42: { length: 24, }, // John 43: { length: 21, }, // Acts 44: { length: 28, }, // Romans 45: { length: 16, }, // 1 Corinthians 46: { length: 16, }, // 2 Corinthians 47: { length: 13, }, // Galatians 48: { length: 6, }, // Ephesians 49: { length: 6, }, // Philippians 50: { length: 4, }, // Colossians 51: { length: 4, }, // 1 Thessalonians 52: { length: 8, }, // 2 Thessalonians 53: { length: 10, }, // 1 Timothy 54: { length: 6, }, // 2 Timothy 55: { length: 4, }, // Titus 56: { length: 13, }, // Philemon 57: { length: 5, }, // Hebrews 58: { length: 13, }, // James 59: { length: 7, }, // 1 Peter 60: { length: 5, }, // 2 Peter 61: { length: 22, }, // 1 John 62: { length: 5, }, // 2 John 63: { length: 1, }, // 3 John 64: { length: 1, }, // Jude 65: { length: 1, }, // Revelation 66: { length: 22, }, }; export default bookInfo;
f9f78acc3df38f072484ce0e67f7e99a57aedf7d
TypeScript
randalvance/skyhigh-web
/src/app/stores/site/site.reducer.ts
2.71875
3
import { Action } from '@ngrx/store'; import { SiteActions } from './site.actions'; export interface SiteState { siteName: string } const initialState: SiteState = { siteName: 'My Awesome Site' }; export function siteReducer(state = initialState, action: Action): SiteState { switch (action.type) { default: return state; } }
ca5b2f1e5ea58f1558f94d5abffff38442e51fbc
TypeScript
teamsignprompt/sveltekit-oidc
/src/lib/_keycloak/cookie.ts
3.078125
3
const decode = decodeURIComponent; const encode = encodeURIComponent; var pairSplitRegExp = /; */; /** * RegExp to match field-content in RFC 7230 sec 3.2 * * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ] * field-vchar = VCHAR / obs-text * obs-text = %x80-FF */ const fieldContentRegExp = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/; export const parseCookie = (str: string, options?: any) => { if (typeof str !== 'string') { throw new TypeError('argument str must be a string'); } var obj = {}; var opt = options || {}; var pairs = str.split(pairSplitRegExp); var dec = opt.decode || decode; for (var i = 0; i < pairs.length; i++) { var pair = pairs[i]; var eq_idx = pair.indexOf('='); // skip things that don't look like key=value if (eq_idx < 0) { continue; } var key = pair.substr(0, eq_idx).trim() var val = pair.substr(++eq_idx, pair.length).trim(); // quoted values if ('"' == val[0]) { val = val.slice(1, -1); } // only assign once if (undefined == obj[key]) { obj[key] = tryDecode(val, dec); } } return obj; } /** * Try decoding a string using a decoding function. * * @param {string} str * @param {function} decode * @private */ function tryDecode(str, decode) { try { return decode(str); } catch (e) { return str; } }
44c40495386361ba80169137f3951e44463739c3
TypeScript
kilometerskang/angulartist
/src/app/board/board.component.ts
2.859375
3
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-board', templateUrl: './board.component.html', styleUrls: ['./board.component.css'] }) export class BoardComponent implements OnInit { squares: string[]; selectMode: boolean; lastI: number; gameOver: boolean; constructor() { } ngOnInit(): void { this.newGame(); } newGame() { this.squares = ["color-1", "color-2", "color-3", "color-4", "color-5", "color-6", "color-7"]; this.selectMode = true; this.shuffleSquares(); } shuffleSquares() { for (let i = 0; i < this.squares.length; i++) { let j = Math.floor(Math.random() * this.squares.length - i) + i; let tmp = this.squares[i]; this.squares[i] = this.squares[j]; this.squares[j] = tmp; } } makeMove(i: number) { if (this.selectMode) { // Select color. this.lastI = i; } else { // Swap square classes (colors). let tmp = this.squares[i]; this.squares.splice(i, 1, this.squares[this.lastI]); this.squares.splice(this.lastI, 1, tmp); } this.selectMode = !this.selectMode; // Check if all are sorted. this.checkWin(); } checkWin() { let tmp = true; for (let i = 0; i < this.squares.length; i++) { if (this.squares[i] !== `color-${i + 1}`) { tmp = false; } } if (tmp === true) { this.gameOver = true; } } }
9aff58d3cd6c2ce209141ec80b8344905c5106ba
TypeScript
juanbelieni/if-carga-horaria-app
/src/utils/usePersistedState.ts
3.109375
3
import { useState, useEffect, Dispatch, SetStateAction, } from 'react'; type persistedState<T> = [T, Dispatch<SetStateAction<T>>] export default function usePersistedState<T>(key: string, defaultValue: T) : persistedState<T> { const [state, setState] = useState<T>(() => { const localValue = localStorage.getItem(key); if (localValue) { return JSON.parse(localValue); } return defaultValue; }); useEffect(() => { localStorage.setItem(key, JSON.stringify(state)); }, [key, state]); return [state, setState]; }
54bb9f6eb3763365fbb241e735b7ee1f0e5768c6
TypeScript
IlieCiotir/talk.timjs.typescript
/introduction/live/live.ts
4.0625
4
let a = 5; const b = 'awe'; for (var i = 0; i < 100; i++) { let c = 5; let b = 5; } let c: string; let d: number; let e: boolean; let f: any; let favNumbers = [1, 2, 3, 4]; enum Languages { Java = 10, Javascript, Csharp } let preferredLanguage = Languages.Csharp; function doSomething(x: Person, ocupataion?: string): string { return x.nume + '5'; } // let ilie: Person = { nume: 'Ilie', age: 2 }; // doSomething(ilie); interface Pong { (name: string): number } let pong: Pong = (m: string) => 1; interface Person { nume: string, age: number, nationality?: string, prezent: () => void } let v: any = pong; v.name = 5; function ping(pong: (message: string) => void) { pong('m'); } class Om { } class Animal { } class Presenter extends Om implements Person { constructor(public nume: string, public age: number) { super(); } prezent() { console.log() } get description() { return `${this.nume} Is awesome`; } } let p: Person = new Presenter('Ilie', 2); p.prezent();
25164fe4b42088eb2449dbb5d781745f063e24c3
TypeScript
green-fox-academy/lantos14
/week-02/day-5/hexagon/hexagon.ts
2.953125
3
'use strict'; const canvas = document.querySelector('.main-canvas') as HTMLCanvasElement; const ctx = canvas.getContext('2d'); // one hexagon subfunction function drawHexa (x,y) { ctx.beginPath(); ctx.moveTo (x,y); ctx.lineTo (x+20,y); ctx.strokeStyle = 'black'; ctx.stroke(); ctx.beginPath(); ctx.moveTo (x+20,y); ctx.lineTo (x+30,y+15); ctx.strokeStyle = 'red'; ctx.stroke(); ctx.beginPath(); ctx.moveTo (x+30,y+15); ctx.lineTo (x+20,y+30); ctx.strokeStyle = 'red'; ctx.stroke();ctx.stroke(); ctx.beginPath(); ctx.moveTo (x+20,y+30); ctx.lineTo (x,y+30); ctx.strokeStyle = 'red'; ctx.stroke(); ctx.beginPath(); ctx.moveTo (x,y+30); ctx.lineTo (x-10,y+15); ctx.strokeStyle = 'red'; ctx.stroke(); ctx.beginPath(); ctx.moveTo (x-10,y+15); ctx.lineTo (x,y); ctx.strokeStyle = 'red'; ctx.stroke(); } // main function let firstHexaX = 0; let firstHexaY = 0; function drawHexTable (x,y) { drawHexa (x,y); // upper half for (let i:number = 1; i < 4; i++) { x -= 30; y += 15; drawHexa (x,y); firstHexaX = x; for (let j:number = 1; j <= i; j++) { x += 60; drawHexa (x,y); } x = firstHexaX; } // middle rows for (let j:number = 1; j < 4; j++) { y += 30; firstHexaY = y; drawHexa (x,y); for (let k:number = 1; k <= 3; k++) { x += 30; y -= 15; drawHexa (x,y); x += 30; y += 15; drawHexa (x,y); } x = firstHexaX; } x = firstHexaX; // bottom half for (let i:number = 1; i < 4; i++) { x += 30; y += 15 drawHexa (x,y); firstHexaX = x; for (let j:number = 3; j > i; j--) { x += 60; drawHexa (x,y); } x = firstHexaX; } } drawHexTable (180,50);
0f0cbbf2cbf31d82d9ad71d46ce75cbd02aff7a3
TypeScript
MarqusJonsson/M7011E
/backend/simulator/src/db/populate.ts
2.578125
3
import { userTypeResolver } from './resolvers/userType' import { buildingTypeResolver } from './resolvers/buildingType' import { generatorTypeResolver } from './resolvers/generatorType' import { userResolver } from './resolvers/user' import { buildingResolver } from './resolvers/building' import { generatorResolver } from './resolvers/generator' import { Prosumer } from '../users/prosumer'; import { House } from '../buildings/house' import { WindTurbine } from '../generators/windTurbine' import { CoalPowerPlant } from '../buildings/coalPowerPlant' import { CoalGenerator } from '../generators/coalGenerator' import { BaseUser } from '../users/baseUser' import { Manager } from '../users/manager' import { BaseBuilding } from '../buildings/baseBuilding' export function populate(users: BaseUser<House | BaseBuilding>[]) { Promise.all([ userTypeResolver.create(Prosumer.name), userTypeResolver.create(Manager.name), buildingTypeResolver.create(House.name), buildingTypeResolver.create(CoalPowerPlant.name), generatorTypeResolver.create(WindTurbine.name), generatorTypeResolver.create(CoalGenerator.name) ]).then((values: [any, any, any, any, any, any]) => { const prosumerType = values[0] const managerType = values[1] const houseType = values[2] const coalPowerPlantType = values[3] const windTurbineType = values[4] const coalGeneratorType = values[5] for (let i = 0; i < users.length; i++) { const user = users[i]; switch (users[i].type) { case Prosumer.name: const prosumer = <Prosumer> user; // Create prosumer users in database userResolver.create( prosumer.type + '_' + prosumer.id + '@email.dom', prosumer.currency, prosumerType.id ).then((dbProsumer) => { // Create prosumer houses in database const house = prosumer.building; buildingResolver.create( house.battery.buffer, house.battery.capacity, houseType.id, dbProsumer.id ).then((dbHouse) => { // Create prosumer houses generators in database const generators = house.generators.values(); for (const generator of generators) { generatorResolver.create( generator.baseOutput, generator.isBroken, windTurbineType.id, dbHouse.id ); } }); }); break; case Manager.name: const manager = <Manager> user; // Create manager users in database userResolver.create( manager.type + '_' + manager.id + '@email.dom', manager.currency, managerType.id ).then((dbManager) => { // Create manager powerPlants in database const powerPlant = manager.building; buildingResolver.create( powerPlant.battery.buffer, powerPlant.battery.capacity, coalPowerPlantType.id, dbManager.id ).then((dbPowerPlant) => { // Create manager powerPlants generators in database const generators = powerPlant.generators.values(); for (const generator of generators) { generatorResolver.create( generator.baseOutput, generator.isBroken, coalGeneratorType.id, dbPowerPlant.id ); } }); }); break; default: break; } } }); }
05f4c56f8d58bbc9f638548ce5c8bc113c218391
TypeScript
spacemeowx2/ikaWidget2stat.ink
/types.d.ts
2.609375
3
interface Stage { ID: number } interface Game { key: string type: string modeKey: string ruleKey: string } interface Weapon { ID: number } interface Gear { ID: number } interface Skill { ID: number } interface GearSkill { main: Skill sub: Skill[] } interface Player { name: string principalID: string rank: number weapon: Weapon sortScore: number kill: number death: number assist: number special: number allKill: number paintPoint: number udemae: number udemaeName: string udemaeIsX: boolean udemaeIsReached: boolean starRank: number headGear: Gear clothesGear: Gear shoesGear: Gear headSkills: GearSkill clothesSkills: GearSkill shoesSkills: GearSkill } interface Result { no: number stage: Stage game: Game player: Player win: boolean myCount: number otherCount: number xPower: number gachiEstimateXPower: number gachiEstimatePower: number leaguePower: number leagueMaxPower: number leagueTeamEstimatePower: number leagueOtherEstimatePower: number fesPoint: number fesPower: number fesMaxPower: number fesTeamEstimatePower: number fesOtherEstimatePower: number startTime: string elapsedTime: number myMembers: Player[] otherMembers: Player[] } type RankStr = 'c-' | 'c' | 'c+' | 'b-' | 'b' | 'b+' | 'a-' | 'a' | 'a+' | 's' | 's+' | 'x' type FestTitleStr = 'fanboy' | 'fiend' | 'defender' | 'champion' | 'king' interface StatGear { gear: string primary_ability: string secondary_abilities: [string | null, string | null, string | null] } interface StatGears { headgear: StatGear clothing: StatGear shoes: StatGear } interface StatPlayer { team: 'my' | 'his' is_me: 'yes' | 'no' weapon: string level: number star_rank: string rank: RankStr rank_in_team: number kill: number death: number kill_or_assist: number special: number point: number my_kill: number name: string species: 'inkling' | 'octoling' gender: 'boy' | 'girl' fest_title: FestTitleStr top_500: boolean splatnet_id: string } interface StatResult { uuid: string splatnet_number: number lobby: 'standard' | 'squad_2' | 'squad_4' | 'private' mode: 'regular' | 'gachi' | 'fest' | 'private' rule: 'nawabari' | 'area' | 'yagura' | 'hoko' | 'asari' stage: string weapon: string result: 'win' | 'lose' knock_out: 'yes' | 'no' rank_in_team: number // 1-4 kill: number death: number max_kill_combo: number max_kill_streak: number kill_or_assist: number special: number level: number level_after: number star_rank: number rank: RankStr rank_exp: number rank_after: RankStr rank_exp_after: number x_power: number x_power_after: number estimate_x_power: number my_point: number estimate_gachi_power: number league_point: number my_team_estimate_league_point: number his_team_estimate_league_point: number my_team_point: number his_team_point: number my_team_percent: number his_team_percent: number my_team_count: number his_team_count: number my_team_id: string his_team_id: string species: 'inkling' | 'octoling' gender: 'boy' | 'girl' fest_title: FestTitleStr fest_exp: number fest_title_after: FestTitleStr fest_exp_after: number fest_power: number my_team_estimate_fest_power: number his_team_estimate_fest_power: number my_team_fest_theme: string his_team_fest_theme: string gears: StatGears players: StatPlayer[] death_reasons: Record<string, string> events: Array<any> splatnet_json: any automated: 'yes' | 'no' link_url: string note: string private_note: string agent: string agent_version: string agent_custom: string agent_variables: Record<string, string> start_at: number end_at: number }
1dec855b525407cce8ce08a4b6dd93983ae1faa2
TypeScript
mdasmendel/loopback-sdk-builder
/tests/ng2web/src/app/shared/sdk/reducers/auth.ts
2.515625
3
/* tslint:disable */ import { SDKToken, LoopbackAction } from '../models/BaseModels'; import { LoopbackAuthActionTypes } from '../actions/auth'; import { AccountActionTypes } from '../actions/Account'; const initialState: SDKToken = { id: null, ttl: null, scopes: null, created: null, userId: null, user: null, rememberMe: null }; /** * @module LoopbackAuthReducer * @author João Ribeiro <@JonnyBGod> <github:JonnyBGod> * @license MIT * @description * Provides with a LoopBack compatible authentication reducer. */ export function LoopbackAuthReducer(state = initialState, action: LoopbackAction): SDKToken { switch (action.type) { case AccountActionTypes.LOGIN_SUCCESS: case LoopbackAuthActionTypes.SET_TOKEN: case LoopbackAuthActionTypes.LOAD_TOKEN_SUCCESS: { const token: SDKToken = action.payload; return Object.assign({}, token); } case LoopbackAuthActionTypes.SET_USER: { const user: any = action.payload; let updateState = Object.assign({}, state); updateState.user = user; updateState.userId = user.id; return updateState; } case AccountActionTypes.LOGOUT_SUCCESS: case AccountActionTypes.LOGOUT_FAIL: { return Object.assign({}, initialState); } case LoopbackAuthActionTypes.UPDATE_USER_PROPERTIES_SUCCESS: case LoopbackAuthActionTypes.UPDATE_USER_STATE_SUCCESS: { const userProperties: any = action.payload; let updateState = Object.assign({}, state); updateState.user = Object.assign({}, updateState.user, userProperties); return updateState; } default: { return state; } } } export const getLoopbackAuthState = (state: any) => state.LoopbackAuth; export const getLoopbackAuthToken = (state: any) => state.LoopbackAuth; export const getLoopbackAuthAccount = (state: any) => state.LoopbackAuth.user; export const getLoopbackAuthAccountId = (state: any) => state.LoopbackAuth.userId;
3c78fd8bcb79d44a49d70857019e2dde50b4a0a1
TypeScript
uploadcare/image-fns
/src/has-transparency.ts
2.828125
3
import createCanvas from './create-canvas' const hasTransparency = (input: HTMLCanvasElement) => { const canvasSize = 50 const {canvas, context} = createCanvas(canvasSize, canvasSize) let transparency = false if (context) { context.drawImage(input, 0, 0, canvasSize, canvasSize) const data = context.getImageData(0, 0, canvasSize, canvasSize).data canvas.width = canvas.height = 1 for (let i = 3; i < data.length; i += 4) { if (data[i] < 254) { transparency = true break } } } return transparency } export default hasTransparency
8c8c222efc14b415bf817bdc8c32443ebb081419
TypeScript
RecuencoJones/httpr
/app/Core/Body/Form.ts
2.875
3
import {HttprBody} from '../HttprBody'; import {PlainObject} from '../../Type/PlainObject'; import {MediaTypes} from '../../Enum/MediaTypes'; import {urlEncode} from '../HttprUtils'; /** * Form body for URL Encoded data media. */ export class Form extends HttprBody<PlainObject> { public constructor(data: PlainObject) { super(MediaTypes.FORM_URLENCODED, data); } /** * Serialize body content as string. * * @return {string} body. */ public toString(): string { return urlEncode(this._content); } }
0cc8ecaaa50216c926e0542f26c7f03c1ba174d3
TypeScript
wley3337/my-style-react-ts
/src/redux/AutoLogin.redux/AutoLogin.test.ts
2.609375
3
import { cloneableGenerator } from "@redux-saga/testing-utils"; import { call, put } from "redux-saga/effects"; import { createMemoryHistory } from "history"; import { BASE_URL, setUser, autoLogin, watchAutoLogin, handleAutoLogin } from "../actions"; import { AUTO_LOGIN } from "./AutoLogin.types"; describe("AutoLogin", () => { const history = createMemoryHistory(); const testAction = { type: AUTO_LOGIN, payload: history }; describe("AutoLogin Action", () => { it("returns correct action", () => { const res = testAction; expect(autoLogin(history)).toEqual(res); }); }); describe("watchAutoLogin", () => { const gen = cloneableGenerator(watchAutoLogin)(); it("yields handleAutoLogin and finishes", () => { expect(gen.next().value.payload.args).toEqual([ AUTO_LOGIN, handleAutoLogin ]); expect(gen.next().done).toBe(true); }); }); describe("handleAutoLogin flow", () => { const options = { method: "GET", headers: { "Content-Type": "application/json; charset=utf-8", Accept: "application/json", //null is the token value to account for no local token Authorization: `Bearer null` } }; const userObj = { username: "Jr", firstName: "Bob", lastName: "Patt" }; const mockResObj = { success: true, user: userObj, token: "fakeToken", json: jest.fn() }; const gen = cloneableGenerator(handleAutoLogin)(testAction); expect(gen.next().value).toEqual( call(fetch, BASE_URL + "/auto_login", options) ); expect(gen.next(mockResObj).value).toEqual(call([mockResObj, "json"])); test("on success adds user to store", () => { const clone = gen.clone(); expect(clone.next(mockResObj).value).toEqual( put(setUser(mockResObj.user)) ); expect(clone.next().done).toBe(true); }); }); });
1d7f3852f1d994706a05ad4bf889d7e6ad0b06e0
TypeScript
SuperSai/egret_wqGame
/src/wqgame/modules/battle/view/item/BattleBlood.ts
2.578125
3
/** * 战斗中的血条 */ class BattleBlood extends BaseEuiItem { private bar: CustomProgressBar; private txt_blood: eui.Label; public constructor() { super(SkinName.BattleBloodSkin); } public onAwake($data: any = null): void { super.onAwake($data); this.bar.labelDisplay.visible = false; this.bar.bg.source = "battle_bar_json.ui_zdn_xuedi"; let barUrl: string = ""; if (this.data) { if (this.data.team == TEAM_TYPE.BLUE) { barUrl = "battle_bar_json.ui_zdn_xuelan"; } else { barUrl = "battle_bar_json.ui_zdn_xuehong"; } (this.bar.thumb as eui.Image).source = barUrl; this.addEvents(); } } private addEvents(): void { App.NotificationCenter.addListener(EventsType.UPDATE_BLOOD, this.onUpdateBlood, this); } public removeEvents(): void { super.removeEvents(); App.NotificationCenter.removeListener(EventsType.UPDATE_BLOOD, this.onUpdateBlood, this); } private onUpdateBlood(team: number, durable: number): void { if (team != this.data.team) { this.bar.value -= durable; this.txt_blood.text = this.bar.value + ""; } } /** 设置血量 */ public setCurrBlood(blood: number, isMaxBlood: boolean = false): void { if (isMaxBlood) { this.bar.maximum = blood; } this.bar.value = blood; this.txt_blood.text = blood + ""; } } window["BattleBlood"] = BattleBlood;
c5a16aa761d7f70ea8c907b52dd0ea43ce6941b4
TypeScript
ahmedbasuny/weather-app
/Frontend-angular/weather/src/app/services/weather.service.ts
2.78125
3
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; import { map } from 'rxjs/operators'; @Injectable({ providedIn: 'root' }) export class WeatherService { API_KEY = "47ebd0fc8b07106aa80fe498e6e86132"; API_URL = "http://api.openweathermap.org/data/2.5/forecast?q="; UNIT = 'metric'; constructor(private http: HttpClient) { } /** * get weather status. * @returns object of temp and weather description. * @param city * @author Ahmed Basuny */ getCurrentWeather(city: string): Observable<any> { const apiCall = `https://api.openweathermap.org/data/2.5/weather?q=${city}&units=${this.UNIT}&APPID=${this.API_KEY}`; console.log('apiCall', apiCall); return this.http.get<any>(apiCall).pipe( map(resp => { console.log('Response', resp); const weather = resp.weather[0]; const temp = resp.main.temp; const x = { weather, temp }; console.log(x); return x; })); } }
0fe6b11d832fb6f6c90eb3cdcadc537cb288eb1d
TypeScript
igor-kokorin/AppointmentsManagerAPI
/utilities/lib/default-value-setter.ts
3.21875
3
export class DefaultValueSetter { static set<T, P extends keyof T, D extends T[P]>(obj: T, propertyName: P, defaultValue: D) { if ((typeof obj[propertyName] === 'undefined') || ((defaultValue !== null) && (obj[propertyName] === null))) { obj[propertyName] = defaultValue; } } }
360d85b348149fe272ce613e328595e03a2ca463
TypeScript
asynccat/project-alpha
/frontend/src/utils/ValidationSchemes.ts
2.53125
3
import * as Yup from 'yup' export const validationSchema = { validationEmail: Yup.object({ email: Yup.string() .required('Enter your new Email') .email('This is not email') }), validationPassword: Yup.object({ oldPassword: Yup.string() .required('Enter your old password'), newPassword: Yup.string() .required('Enter your new password') .notOneOf([Yup.ref('oldPassword')], 'Old and new passwords must be different'), confirmPassword: Yup.string() .required('Confirm your password') .oneOf([Yup.ref('newPassword')], 'Passwords do not match') }), }
6d5f40f566d8bb5678dab89c8e4f4ef43b26806c
TypeScript
Matinho/Angular6-Pruebas
/src/app/basicas/numeros/numeros.spec.ts
2.734375
3
import { incrementar } from './numeros'; describe( 'Prueba de números' , () => { it( 'Debe devolver 100 si el numero ingresado es mayor a 100', () => { const res = incrementar( 300 ); expect( res ).toBe( 100 ); }); it( 'Debe devolver el numero más 1 si el numero ingresado es menor a 100', () => { const numero = 99; const res = incrementar( numero ); expect( res ).toBe( numero + 1 ); }); });
985c47079a7e7bbd70b46862f775e5057effd226
TypeScript
rohits2712/Angular
/src/app/department-list/department-list.component.ts
2.71875
3
import { Component, OnInit } from '@angular/core'; import { department } from 'src/department'; import{Router,ActivatedRoute,ParamMap} from '@angular/router'; @Component({ selector: 'app-department-list', template: ` <h3>Department list</h3> <ul class= "items"> <li (click)="onSelect(department)" [class.selected] = "IsSelectedId(department)" *ngFor="let department of departments"> <span class= "badge">{{department.id}}</span> {{department.name}} </li> </ul> `, styles: [] }) export class DepartmentListComponent implements OnInit { departments:department[] = [ { id:1, name:'Angular' }, { id:2, name:'C#' }, { id:3, name:'.NET' }, ] public selectedId; constructor(private router:Router, private route:ActivatedRoute) { this.route.paramMap.subscribe((params:ParamMap) => { let id = parseInt(params.get('id')); this.selectedId=id; }) } ngOnInit() { } onSelect(department){ //this.router.navigate(['/departments', department.id]) //pass linked parameter array //but above messes up when the route is changed in the initial page ex departments changed to department-list //Hence this.router.navigate([department.id], {relativeTo: this.route}); //Relative navigation says append id and send to the route } IsSelectedId(department) { return department.id == this.selectedId; } }
36bcd068d95ec9423d961742840aa69496452b09
TypeScript
on3iro/aeons-end-randomizer
/src/aer-data/src/createNormalizedData.ts
2.59375
3
import * as types from '../../aer-types/types' export const createNormalizedData = ( data: types.IExpansionData ): types.NormalizedData => { const expansions = Object.keys(data) const normalize = (array: Array<any>) => array.reduce( (acc, entity) => ({ entities: { ...acc.entities, [entity.id]: entity, }, ids: [...acc.ids, entity.id], }), { entities: {}, ids: [], } as { entities: { [key: string]: Object } ids: string[] } ) return expansions.reduce( (acc: types.NormalizedData, id: string) => { const expansion = data[id] const nemeses = normalize(expansion.nemeses) const mages = normalize(expansion.mages) const cards = normalize(expansion.cards) const treasures = normalize(expansion.treasures || []) const basicNemesisCards = normalize(expansion.basicNemesisCards || []) const upgradedBasicNemesisCards = normalize( expansion.upgradedBasicNemesisCards || [] ) return { expansions: { ...acc.expansions, [id]: { id, name: expansion.name, wave: expansion.wave, type: expansion.type, }, }, nemeses: { ...acc.nemeses, ...nemeses.entities, }, mages: { ...acc.mages, ...mages.entities, }, cards: { ...acc.cards, ...cards.entities, }, treasures: { ...acc.treasures, ...treasures.entities, }, basicNemesisCards: { ...acc.basicNemesisCards, ...basicNemesisCards.entities, }, upgradedBasicNemesisCards: { ...acc.upgradedBasicNemesisCards, ...upgradedBasicNemesisCards.entities, }, expansionIds: [...acc.expansionIds, id], nemesisIds: [...acc.nemesisIds, ...nemeses.ids], mageIds: [...acc.mageIds, ...mages.ids], cardIds: [...acc.cardIds, ...cards.ids], treasureIds: [...acc.treasureIds, ...treasures.ids], basicNemesisCardIds: [ ...acc.basicNemesisCardIds, ...basicNemesisCards.ids, ], upgradedBasicNemesisCardIds: [ ...acc.upgradedBasicNemesisCardIds, ...upgradedBasicNemesisCards.ids, ], } }, { expansions: {}, nemeses: {}, mages: {}, cards: {}, treasures: {}, basicNemesisCards: {}, upgradedBasicNemesisCards: {}, expansionIds: [], nemesisIds: [], mageIds: [], cardIds: [], treasureIds: [], basicNemesisCardIds: [], upgradedBasicNemesisCardIds: [], } ) }
6fd7ad3b29ca72bf0e6f5022f2564e04f244fdc6
TypeScript
tanlh/typescript-study
/generic/src/app.ts
4.28125
4
//======================================================== // Introduction about generic const names: Array<string> = []; // equals string[] const promise: Promise<string> = new Promise((resolve, _reject) => { setTimeout(() => { resolve("String"); }, 1000); }); promise.then((data) => data.split(" ")); //======================================================== // Generic function // no constraint function merge1<T, U>(objA: T, objB: U) { return Object.assign(objA, objB); } const mergeObj1 = merge1({ name: "Tan" }, { age: 26 }); console.log(mergeObj1); // {name: 'Tan', age: 26} console.log(mergeObj1.name); // Tan const mergeObj2 = merge1({ name: "Trang" }, 26); console.log(mergeObj2); // {name: 'Trang'} // with constraint // T, U must be object function merge2<T extends object, U extends object>(objA: T, objB: U) { return Object.assign(objA, objB); } const mergeObj3 = merge2({ name: "Trang" }, { age: 25 }); console.log(mergeObj3); // {name: 'Trang', age: 25} // const mergeObj4 = merge2({ name: "Trang cute" }, 20); ERROR, 20 is not an object // constraint with 'keyof' // U is type of keys of T function extractAndConvert<T extends object, U extends keyof T>( obj: T, key: U ) { return "Value " + obj[key]; } extractAndConvert({ name: "Tan", age: 26, 0: "Ahihi" }, "name"); extractAndConvert({ name: "Tan", age: 26, 0: "Ahihi" }, 0); //======================================================== // Generic class class DataStorage<T> { constructor(private data: T[] = []) {} addItem(item: T) { this.data.push(item); } removeItem(item: T) { this.data = this.data.filter((i) => i !== item); } getItems() { return [...this.data]; } } const textStorage = new DataStorage<string>(); textStorage.addItem("Tan"); textStorage.addItem("Trang"); console.log(textStorage.getItems()); // ["Tan", "Trang"] textStorage.removeItem("Tan"); console.log(textStorage.getItems()); // ["Trang"] const numberStorage = new DataStorage<number>(); numberStorage.addItem(258); numberStorage.addItem(154); console.log(numberStorage.getItems()); // [258, 154] numberStorage.removeItem(154); console.log(numberStorage.getItems()); // [258]
067c7298da25b9c8ecab7d6b2add2765d9825937
TypeScript
godiagonal/nations-client
/src/app/models/hours.model.ts
3.171875
3
export class Hours { open: Date; close: Date; get isKnown() { return this.open != null || this.close != null; } constructor(open: Date = null, close: Date = null) { this.open = open; this.close = close; } static fromObject(obj) { if (!obj) return new Hours(); return new Hours( obj.open ? new Date(obj.open) : null, obj.close ? new Date(obj.close) : null); } }
19a421ef0d052c593b431579aa7b302f401a37ea
TypeScript
yugef3h/Novel-Map
/orm/article.ts
2.53125
3
import { Model, STRING, INTEGER, Sequelize, TEXT } from 'sequelize' class ArtPage extends Model { public id!: number public title!: string public desc!: string public cover!: string public tags!: string public pid!: number public content!: string public state!: number public ctime!: string public mtime!: string public level!: number public extra!: string } export default ArtPage export const modelItem = { id: { type: INTEGER().UNSIGNED, autoIncrement: true, comment: '自增id', primaryKey: true }, pid: { type: INTEGER().UNSIGNED, allowNull: true, defaultValue: 0, comment: '父级 id' }, state: { type: INTEGER, allowNull: false, defaultValue: 1, comment: '-1 删除,1 已发布,2 草稿' }, cover: { type: STRING(255), allowNull: true, defaultValue: '', comment: '缺省' }, extra: { type: STRING(255), allowNull: true, defaultValue: '', comment: '额外字段,不暴露给前端' }, tags: { type: STRING(255), allowNull: true, comment: '标签' }, title: { type: STRING(255), allowNull: false, defaultValue: '无题', comment: '文章标题' }, desc: { type: STRING(255), allowNull: true, comment: '描述' }, content: { type: TEXT, allowNull: false, defaultValue: '', comment: '内容,格式:html' }, level: { type: INTEGER, allowNull: true, defaultValue: 0, comment: 'tree 层级' } } export function init(sequelize: Sequelize) { return ArtPage.init(modelItem, { timestamps: false, tableName: 'art_page', sequelize, createdAt: 'ctime', updatedAt: 'mtime', deletedAt: false, paranoid: false }) }
ac939a759486b37e54a68bc371b4617c4ef0ad88
TypeScript
cieloazul310/ol-vectortile
/src/styles/index.ts
2.640625
3
import Style from 'ol/style/Style'; import Stroke from 'ol/style/Stroke'; import Fill from 'ol/style/Fill'; import type { FeatureLike } from 'ol/Feature'; import roadStyle from './road'; import railwayStyle from './railway'; import labelStyle from './label'; export default function vtStyle(feature: FeatureLike, resolution: number) { const properties = feature.getProperties(); if (properties.layer === 'road') { return roadStyle(feature, resolution); } else if (properties.layer === 'railway') { return railwayStyle(feature, resolution); } else if (properties.layer === 'coastline') { return new Style({ stroke: new Stroke({ color: '#bbbbd7', }), }); } else if (properties.layer === 'label') { return labelStyle(feature); } else if (properties.layer === 'contour') { return new Style({ stroke: new Stroke({ color: resolution > 19.11 ? '#e7dddd' : '#f7eeee', width: 1, }), }); } else if (properties.layer === 'building') { return new Style({ fill: new Fill({ color: '#eee' }), }); } else if (properties.layer === 'boundary') { return new Style({ stroke: new Stroke({ color: '#bbd7bb', lineDash: [2, 2] }), }); } else if (properties.layer === 'searoute') { return new Style({ stroke: new Stroke({ color: '#bbbbd7', lineDash: [4, 4] }), }); } return new Style({ fill: new Fill({ color: '#dddde7', }), }); }
6ba914d6e60161504d2bfaf552b7e57d86dedd33
TypeScript
vihong/gented
/app/utils/array.ts
2.828125
3
export function findIndexOfWord(words: string[], wordToFind: string) { return words.findIndex((option) => option === wordToFind) }
43e086b8d45c404fe2003a4cf65d505f50c02c63
TypeScript
babelcoder-dummy/set-007-socket
/ui/src/modules/chat/slice.ts
2.671875
3
import { createSlice, PayloadAction } from '@reduxjs/toolkit' import { AppThunk } from 'modules/reducers' import * as ws from 'lib/web-socket' export type ChatMessage = { text: string } type ChatState = { messages: ChatMessage[] } const initialState: ChatState = { messages: [] } const chatSlice = createSlice({ name: 'chat', initialState, reducers: { addMessage(state, action: PayloadAction<ChatMessage>) { state.messages.push(action.payload) } } }) export const { addMessage } = chatSlice.actions export const pollMessages = (): AppThunk => async dispatch => { ws.subscribe('chat message', (message: ChatMessage) => dispatch(addMessage(message))) } export const disableMessages = (): AppThunk => () => ws.unsubscribe('chat message') export const sendMessage = (message: ChatMessage['text']): AppThunk => () => { ws.emit('chat message', message) } export default chatSlice.reducer
5b67ed8bd5ffbe7f47109b7dd2ef150df705ae6b
TypeScript
eduardotrandafilov/typescript
/conceitos_basicos/propriedades_opcionais.ts
2.921875
3
function resumo(usuario:{nome:string,idade?:number}){ if(usuario.idade !== undefined){ return `Olá ${usuario.nome} , tudo bem ?! Você tem ${usuario.idade} anos`; }else{ return `Olá ${usuario.nome} , tudo bem ?!`; } } let u = { nome:'eduardo', }; console.log(resumo(u));
f3cc0a8f54ce30bb2766525e1448b77061d7f903
TypeScript
goulash1971/typeconv
/lib/tests/ts-to-openapi.test.ts
2.5625
3
import { makeConverter, getTypeScriptReader, getOpenApiWriter } from "../" describe( "ts-to-openapi", ( ) => { it( "typescript to openapi", async ( ) => { const input = ` type Thing = { x: 6 y: string } export type Foo = { a: string b: null c: number d: boolean e: Thing } `; const { convert } = makeConverter( getTypeScriptReader( ), getOpenApiWriter( { format: 'yaml', title: 'My API', version: 'v1' } ) ); const { data } = await convert( { data: input } ); expect( data ).toMatchSnapshot( ); }); } );
ee545392b9b1b91aca0975177d309ae586d9c1a3
TypeScript
puphs/react-social-network
/src/redux/appReducer.ts
2.953125
3
import { ThunkType } from '../types/types'; import { getAuthUserData } from './authReducer'; import { InferActionsTypes } from './reduxStore'; const SET_INITIALIZED = 'app/SET_INITIALIZED'; const SHOW_ERROR = 'app/SHOW_ERROR'; const HIDE_ERROR = 'app/HIDE_ERROR'; const initialState = { initialized: false as boolean, errorShown: false as boolean, errorText: null as string | null, }; type InitialStateType = typeof initialState; type ActionTypes = InferActionsTypes<typeof actions>; export const appReducer = (state = initialState, action: ActionTypes): InitialStateType => { switch (action.type) { case SET_INITIALIZED: return { ...state, initialized: true, }; case SHOW_ERROR: return { ...state, errorShown: true, errorText: action.errorText, }; case HIDE_ERROR: return { ...state, errorShown: false, }; default: return state; } }; export const actions = { setInitialized: () => ({ type: SET_INITIALIZED, } as const), showError: (errorText: string) => ({ type: SHOW_ERROR, errorText, } as const), hideError: () => ({ type: HIDE_ERROR, } as const), }; export const initialize = (): ThunkType<ActionTypes> => async (dispatch) => { await Promise.all([dispatch(getAuthUserData())]); dispatch(actions.setInitialized()); }; export const showAndHideError = (errorText: string): ThunkType<ActionTypes> => async (dispatch) => { dispatch(actions.showError(errorText)); setTimeout(() => { dispatch(actions.hideError()); }, 2500); };
a9d22cab79395874a680ae45a68aa8cd28ff60b2
TypeScript
BuildForSDGCohort2/Team-60-BackEnd
/src/middleware/validator.ts
2.53125
3
import { check, body } from "express-validator"; import { isBoolean } from "util"; const validator: any = {}; validator.login = [ body("email") .exists() .withMessage("Email must be provided") .isEmail() .withMessage("Invalid email address.") .trim() .escape(), body("password") .exists() .withMessage("Password must be provided") .isLength({ min: 5 }) .withMessage("Passord must be at least 5 chars long") .trim() .escape(), ]; validator.register = [ body("email") .exists() .withMessage("Email must be provided") .isEmail() .withMessage("Invalid email address.") .trim() .escape(), body("name") .exists() .withMessage("Name must be provided") .isLength({ min: 3 }) .withMessage("Name must be at least 3 chars long.") .trim() .escape(), body("username") .exists() .withMessage("Username must be provided") .isLength({ min: 3 }) .withMessage("Username must be at least 3 chars long.") .trim() .escape(), body("password") .exists() .withMessage("Password must be provided") .isLength({ min: 5 }) .withMessage("Password must be at least 5 chars long") .trim() .escape(), body("healthWorker") .exists() .withMessage("HealthWorker must be provided") .isBoolean(), body("hospital") .exists() .withMessage("Hospital must be provided") .isBoolean(), ]; export default validator;
4ea8252f3311a1578addf447863c6a6c9fc8db92
TypeScript
M0nsuta/rpgconsole
/src/personnages/Personnage.ts
2.984375
3
import { Arme } from './../armes/Arme'; export class Personnage { _name: string; _pv: number; _pvMax: number _arme: Arme _cible?: Personnage constructor(name: string = "", arme: Arme = new Arme()) { this._name = name; this._pv = Math.floor(Math.random() * 100 + 50); this._pvMax = this._pv; this._arme = arme; this._cible = undefined } get name(): string { return this._name; } set name(name: string) { this._name = name; } get pv(): number { return this._pv; } set pv(pv: number) { this._pv = pv; } get arme(): Arme { return this._arme; } set arme(arme: Arme) { this._arme = arme; } get cible(): Personnage | undefined { return this._cible; } set cible(cible: Personnage | undefined) { this._cible = cible; } attaquer = (): string => { let result = "" if (this.cible) { let degat = this.arme.degat() this.cible.pv -= degat result = `${this.name} attaque ${this.cible.name} et fait ${degat}. Il reste ${this.cible.pv} de vie à ${this.cible.name}` } return result } }
7afd7c7cf3338d0b9b97273f0c794aacbda6c5d0
TypeScript
ChenAi29/pocket-aircraft
/major/assets/gamecommon/Script/GameCommon/SoundManager.ts
2.703125
3
import { UserData } from "./UserData"; const { ccclass, property } = cc._decorator; @ccclass export class SoundManager extends cc.Component { protected static gameSoundMap: Map<string, cc.AudioClip> = new Map(); protected static readonly _dic: Map<cc.AudioClip, number> = new Map(); /** * 播放音效 只播放一次 * @param audioName 音效的名称,在编辑器中的名称 */ public static playAudio(audioName: string): void { if (!UserData.data.gameSound) { return; } let audioClip: cc.AudioClip = this.getAudioByName(audioName); if (audioClip) { //关闭正在播放的同种音效 if (this._dic.has(audioClip)) { var id = this._dic.get(audioClip); var audio = cc.audioEngine._id2audio[id]; if (audio != null) { audio.destroy(); } } var id = cc.audioEngine.playEffect(audioClip, false); this._dic.set(audioClip, id); return; } cc.loader.loadRes("sound/" + audioName, cc.AudioClip, function (err, assets) { if (err) { cc.error(err); return; } if (!assets) { return; } audioClip = assets; SoundManager.gameSoundMap.set(audioName, audioClip); var id = cc.audioEngine.playEffect(audioClip, false); SoundManager._dic.set(audioClip, id); }); } /** * 获取音效对应的AudioClip * @param audioName 音效的名称,在编辑器中的名称 */ protected static getAudioByName(audioName: string): cc.AudioClip { if (audioName == null) { return; } return this.gameSoundMap.get(audioName); } /** * 停止播放音效 * @param audioName 音效的名称,在编辑器中的名称 */ public static stop(audioName: string): void { var audioClip = this.getAudioByName(audioName); if (audioClip == null) { return; } if (this._dic.has(audioClip)) { var id = this._dic.get(audioClip); var audio = cc.audioEngine._id2audio[id]; if (audio) { audio.stop(); } } } /** * 播放背景音乐 * @param audioName */ public static playBGMusic(audioName: string): void { if (!UserData.data.gameSound) { return; } let audioClip: cc.AudioClip = this.getAudioByName(audioName); if (audioClip) { cc.audioEngine.playMusic(audioClip, true); return; } cc.loader.loadRes("sound/" + audioName, cc.AudioClip, function (err, assets) { if (err) { cc.error(err); return; } if (!assets) { return; } audioClip = assets; SoundManager.gameSoundMap.set(audioName, audioClip); cc.audioEngine.playMusic(audioClip, true); }); } /** * 停止播放背景音乐 * @param audioName */ public static stopBGMusic(): void { cc.audioEngine.stopMusic(); } /** * 停止所有正在播放的音效 */ public static stopAllAudio(): void { cc.audioEngine.stopAll(); } }
088ec0f4ef1942a240fb74490b1c86d79671a11f
TypeScript
boldscot/angular6-weather-app
/src/app/left-panel/left-panel.component.ts
2.625
3
import { Component, OnInit, Input} from '@angular/core'; import { WeatherDataService } from '../weather-data.service'; import { Day } from '../day'; import { Hour } from '../hour'; @Component({ selector: 'app-left-panel', templateUrl: './left-panel.component.html', styleUrls: ['./left-panel.component.css'] }) export class LeftPanelComponent implements OnInit { weatherData$: Object; temp: number; iconUrl: string; description: string; humidity: string; nextThreeDays: Map<string, Hour[]>; threeDayForecast: Day[]; selectedLocation: string; constructor(private data: WeatherDataService) { this.nextThreeDays = new Map(); this.threeDayForecast = []; //get the current city name to display data for from the service this.selectedLocation = this.data.getSelectedCity(); } ngOnInit() { // initial api call this.apiCall(this.data.getCityID(this.selectedLocation, this.data.getCities())); // set the api call to update every hour setInterval(() => { this.apiCall(this.data.getCityID(this.selectedLocation, this.data.getCities())); }, 3600000) } ngDoCheck() { // check if the selectedCity from the service has changed if (this.data.getSelectedCity() !== this.selectedLocation) { // set the selectedlocation to the new value this.selectedLocation = this.data.getSelectedCity(); // clear three day map this.nextThreeDays.clear(); this.threeDayForecast = []; //mkae the api call this.apiCall(this.data.getCityID(this.selectedLocation, this.data.getCities())); } } // get the current weather using the selectedLocation getCurrentWeatherCall(id:string) { this.data.getCurrentWeatherDataByID(id).subscribe( data => {this.weatherData$ = data}, err => console.error(err), () => { if (this.weatherData$ != null) { this.temp = this.weatherData$.main.temp; this.humidity = this.weatherData$.main.humidity; this.description = this.weatherData$.weather[0].description; this.iconUrl = `http://openweathermap.org/img/w/${this.weatherData$.weather[0].icon}.png`; } }); } apiCall(id:string) { // update the current weather this.getCurrentWeatherCall(id); this.data.getWeatherData(id).subscribe( data => {this.weatherData$ = data}, err => console.error(err), () => { let today = new Date().toLocaleDateString("ire", {weekday: 'long'}); let day = today; // Loop over the ap response and pull out the data for the next three days, store it in the map // Using the day name to group hours together for that day for(let i = 0; i < this.weatherData$.list.length; i++) { let obj = this.weatherData$.list[i]; day = new Date(obj.dt_txt).toLocaleDateString("ire",{weekday: 'long'}); // We want data to represent the next three days excluding today, // So continue to the next loop iteration if the day === today if (day === today) continue; // Check the size of the map, if we have enough data break the loop else if (this.nextThreeDays.size < 4) { // Entry found for the day, add to the array for that day if(this.nextThreeDays.has(day)) { this.nextThreeDays.get(day).push({ dayName: day, time: obj.dt_txt.substring(11), highTemp: obj.main.temp_max, lowTemp: obj.main.temp_min, iconUrl: `http://openweathermap.org/img/w/${obj.weather[0].icon}.png`, description: '' }); } else { // No entry in the map so create one this.nextThreeDays.set(day, new Array); } } else { // The map size goes to 4, but the array 4th entry will be empty, so drop the entry this.nextThreeDays.delete(day); break; } } this.nextThreeDays.forEach((value: Array<Hour>, key: string) => { let high = 0.00; let low = 999.00; let icon = ''; value.forEach(hr => { if (hr.highTemp > high) high = hr.highTemp; if (hr.lowTemp < low) low = hr.lowTemp; if (icon === '') { if ( hr.time === '12:00:00' || hr.time === '15:00:00' || hr.time === '18:00:00' || hr.time === '21:00:00') { icon = hr.iconUrl; } } }); this.threeDayForecast.push({ dayName: key, highTemp: high, lowTemp: low, iconUrl: icon, description: '' }); }); }); } }