max_stars_repo_path
stringlengths 4
384
| max_stars_repo_name
stringlengths 5
120
| max_stars_count
int64 0
208k
| id
stringlengths 1
8
| content
stringlengths 1
1.05M
| score
float64 -1.05
3.83
| int_score
int64 0
4
|
---|---|---|---|---|---|---|
src/context/invoice.tsx | shettayyy/invoice-dashboard | 0 | 1600 | import React, {
createContext,
useCallback,
useContext,
useEffect,
useState,
} from 'react';
import { Invoice } from '../types/invoice';
import data from '../constants/data.json';
type InvoiceById = { [key: string]: Invoice };
interface InvoiceState {
invoicesById: InvoiceById;
setNewInvoice: (invoice: Invoice) => unknown;
updateInvoice: (
id: string,
accessor: keyof Invoice,
value: unknown,
) => unknown;
deleteInvoice: (id: string) => unknown;
}
const INITIAL_INVOICE_STATE = {
invoicesById: {},
setNewInvoice: () => null,
updateInvoice: () => null,
deleteInvoice: () => null,
};
const InvoiceContext = createContext<InvoiceState>(INITIAL_INVOICE_STATE);
InvoiceContext.displayName = 'Invoice Context';
export const InvoiceProvider: React.FC = ({ children }) => {
const [isInvoiceReady, setInvoiceReady] = useState(false);
const [invoicesById, setInvoicesById] = useState<InvoiceById>({});
const setNewInvoice = useCallback((newInvoice: Invoice) => {
setInvoicesById(prevInvoicesById => ({
...prevInvoicesById,
[newInvoice.id]: newInvoice,
}));
}, []);
const updateInvoice = useCallback(
(id: string, accessor: keyof Invoice, value: unknown) => {
setInvoicesById(prevInvoicesById => {
const invoice = prevInvoicesById[id];
invoice[accessor] = value as never;
return {
...prevInvoicesById,
[id]: invoice,
};
});
},
[],
);
const deleteInvoice = useCallback((id: string) => {
setInvoicesById(prevInvoicesById => {
const newInvoicesById = { ...prevInvoicesById };
delete newInvoicesById[id];
return newInvoicesById;
});
}, []);
useEffect(() => {
// Set Invoices List
setInvoicesById(
data.reduce((prevData, dataItem) => {
return {
...prevData,
[dataItem.id]: dataItem,
};
}, {}),
);
// After inital data is set, start the app
setInvoiceReady(true);
}, []);
if (!isInvoiceReady) {
return null;
}
return (
<InvoiceContext.Provider
value={{
invoicesById,
setNewInvoice,
deleteInvoice,
updateInvoice,
}}
>
{children}
</InvoiceContext.Provider>
);
};
export const useInvoice = (): InvoiceState => useContext(InvoiceContext);
| 1.695313 | 2 |
public_gen/app/plugins/panel/heatmap/axes_editor.d.ts | dennisnovac/xy.tools | 0 | 1608 | export declare class AxesEditorCtrl {
panel: any;
panelCtrl: any;
unitFormats: any;
logScales: any;
dataFormats: any;
/** @ngInject */
constructor($scope: any, uiSegmentSrv: any);
setUnitFormat(subItem: any): void;
}
/** @ngInject */
export declare function axesEditor(): {
restrict: string;
scope: boolean;
templateUrl: string;
controller: typeof AxesEditorCtrl;
};
| 1.203125 | 1 |
packages/jellyfish-api-core/src/category/wallet.ts | muirglacier/jellyfish | 65 | 1616 | import { ApiClient } from '../.'
import BigNumber from 'bignumber.js'
export enum Mode {
UNSET = 'UNSET',
ECONOMICAL = 'ECONOMICAL',
CONSERVATIVE = 'CONSERVATIVE'
}
export enum AddressType {
LEGACY = 'legacy',
P2SH_SEGWIT = 'p2sh-segwit',
BECH32 = 'bech32'
}
export enum ScriptType {
NONSTANDARD = 'nonstandard',
PUBKEY = 'pubkey',
PUBKEYHASH = 'pubkeyhash',
SCRIPTHASH = 'scripthash',
MULTISIG = 'multisig',
NULLDATA = 'nulldata',
WITNESS_V0_KEYHASH = 'witness_v0_keyhash',
WITNESS_UNKNOWN = 'witness_unknown',
}
export enum WalletFlag {
AVOID_REUSE = 'avoid_reuse'
}
export enum BIP125 {
YES = 'yes',
NO = 'no',
UNKNOWN = 'unknown'
}
export enum InWalletTransactionCategory {
SEND = 'send',
RECEIVE = 'receive',
GENERATE = 'generate',
IMMATURE = 'immature',
ORPHAN = 'orphan'
}
/**
* Wallet RPCs for DeFi Blockchain
*/
export class Wallet {
private readonly client: ApiClient
constructor (client: ApiClient) {
this.client = client
}
/**
* Returns the total available balance in wallet.
*
* @param {number} minimumConfirmation to include transactions confirmed at least this many times
* @param {boolean} includeWatchOnly for watch-only wallets
* @return Promise<BigNumber>
*/
async getBalance (minimumConfirmation: number = 0, includeWatchOnly: boolean = false): Promise<BigNumber> {
return await this.client.call('getbalance', ['*', minimumConfirmation, includeWatchOnly], 'bignumber')
}
/**
* Identical to getBalance to get untrusted pending balance
*
* @return Promise<BigNumber>
*/
async getUnconfirmedBalance (): Promise<BigNumber> {
return await this.client.call('getunconfirmedbalance', [false], 'bignumber')
}
/**
* Returns an object with all balances.
*
* @return {Promise<WalletBalances>}
*/
async getBalances (): Promise<WalletBalances> {
return await this.client.call('getbalances', [false], 'bignumber')
}
/**
* Get list of UTXOs in wallet.
*
* @param {number} minimumConfirmation default = 1, to filter
* @param {number} maximumConfirmation default = 9999999, to filter
* @param {ListUnspentOptions} [options]
* @param {string[]} [options.addresses] to filter
* @param {boolean} [options.includeUnsafe=true] default = true, include outputs that are not safe to spend
* @param {ListUnspentQueryOptions} [options.queryOptions]
* @param {number} [options.queryOptions.minimumAmount] default = 0, minimum value of each UTXO
* @param {number} [options.queryOptions.maximumAmount] default is 'unlimited', maximum value of each UTXO
* @param {number} [options.queryOptions.maximumCount] default is 'unlimited', maximum number of UTXOs
* @param {number} [options.queryOptions.minimumSumAmount] default is 'unlimited', minimum sum valie of all UTXOs
* @param {string} [options.queryOptions.tokenId] default is 'all', filter by token
* @return {Promise<UTXO[]>}
*/
async listUnspent (
minimumConfirmation = 1,
maximumConfirmation = 9999999,
options: ListUnspentOptions = {}
): Promise<UTXO[]> {
const { addresses = [], includeUnsafe = true, queryOptions = {} } = options
return await this.client.call(
'listunspent',
[
minimumConfirmation, maximumConfirmation,
addresses, includeUnsafe, queryOptions
],
{ amount: 'bignumber' }
)
}
/**
* Create a new wallet
*
* @param {string} walletName
* @param {boolean} disablePrivateKeys
* @param {CreateWalletOptions} [options]
* @param {boolean} [options.blank]
* @param {string} [options.passphrase]
* @param {boolean} [options.avoidReuse]
* @return {Promise<CreateWalletResult>}
*/
async createWallet (
walletName: string,
disablePrivateKeys = false,
options: CreateWalletOptions = {}
): Promise<CreateWalletResult> {
const { blank = false, passphrase = '', avoidReuse = false } = options
return await this.client.call(
'createwallet',
[walletName, disablePrivateKeys, blank, passphrase, avoidReuse],
'number'
)
}
/**
* Return object containing various wallet state info
*
* @return {Promise<WalletInfo>}
*/
async getWalletInfo (): Promise<WalletInfo> {
return await this.client.call('getwalletinfo', [], {
balance: 'bignumber',
unconfirmed_balance: 'bignumber',
immature_balance: 'bignumber',
paytxfee: 'bignumber'
})
}
/**
* Change the state of the given wallet flag for a wallet
*
* @param {WalletFlag} flag to change. eg: avoid_reuse
* @param {boolean} value optional, default = true
* @return {Promise<WalletFlagResult>}
*/
async setWalletFlag (flag: WalletFlag, value: boolean = true): Promise<WalletFlagResult> {
return await this.client.call('setwalletflag', [flag, value], 'number')
}
/**
* Returns a new DeFi address for receiving payments.
* If 'label' is specified, it's added to the address book
* so payments received with the address will be associated with 'label'
*
* @param {string} label for address to be linked to. It can also be set as empty string
* @param {AddressType} addressType to use, eg: legacy, p2sh-segwit, bech32
* @return {Promise<string>}
*/
async getNewAddress (label: string = '', addressType = AddressType.BECH32): Promise<string> {
return await this.client.call('getnewaddress', [label, addressType], 'number')
}
/**
* Validate and return information about the given DFI address
*
* @param {string} address
* @return {Promise<ValidateAddressResult>}
*/
async validateAddress (address: string): Promise<ValidateAddressResult> {
return await this.client.call('validateaddress', [address], 'number')
}
/**
* Return information about the given address
*
* @param {string} address
* @return {Promise<AddressInfo>}
*/
async getAddressInfo (address: string): Promise<AddressInfo> {
return await this.client.call('getaddressinfo', [address], 'number')
}
/**
* Send an amount to given address and return a transaction id
*
* @param {string} address
* @param {number} amount
* @param {SendToAddressOptions} [options]
* @param {string} [options.comment]
* @param {string} [options.commentTo]
* @param {boolean} [options.subtractFeeFromAmount]
* @param {boolean} [options.replaceable]
* @param {number} [options.confTarget]
* @param {Mode} [options.estimateMode]
* @param {boolean} [options.avoidReuse]
* @return {Promise<string>}
*/
async sendToAddress (
address: string,
amount: number,
options: SendToAddressOptions = {}
): Promise<string> {
const {
comment = '',
commentTo = '',
subtractFeeFromAmount = false,
replaceable = false,
confTarget = 6,
estimateMode = Mode.UNSET,
avoidReuse = false
} = options
return await this.client.call(
'sendtoaddress',
[
address, amount, comment, commentTo, subtractFeeFromAmount,
replaceable, confTarget, estimateMode, avoidReuse
],
'bignumber'
)
}
/**
* Lists groups of addresses which have had their common ownership made public
* by common use as inputs or as the resulting change in past transactions
*
* @return {Promise<any[][][]>}
*/
async listAddressGroupings (): Promise<any[][][]> {
return await this.client.call('listaddressgroupings', [], 'bignumber')
}
/**
* Send given amounts to multiple given address and return a transaction id.
*
* @param {Record<string, number>} amounts Dictionary/map with individual addresses and amounts
* @param {string[]} subtractfeefrom Array of addresses from which fee needs to be deducted.
* @param {SendManyOptions} options
* @param {string} [options.comment] A comment
* @param {boolean} [options.replaceable] Allow this transaction to be replaced by a transaction with higher fees via BIP 125
* @param {number} [options.confTarget] Confirmation target (in blocks)
* @param {Mode} [options.estimateMode] The fee estimate mode, must be one of (Mode.UNSET, Mode.ECONOMICAL, Mode.CONSERVATIVE)
* @return {Promise<string>} hex string of the transaction
*/
async sendMany (
amounts: Record<string, number>,
subtractfeefrom: string [] = [],
options: SendManyOptions = {}): Promise<string> {
const {
comment = '',
replaceable = false,
confTarget = 6,
estimateMode = Mode.UNSET
} = options
const dummy: string = '' // Must be set to '' for backward compatibality.
const minconf: number = 0 // Ignored dummy value
return await this.client.call(
'sendmany',
[
dummy, amounts, minconf, comment, subtractfeefrom,
replaceable, confTarget, estimateMode
],
'bignumber'
)
}
/**
* Reveals the private key corresponding to an address.
*
* @param {string} address The DFI address for the private key.
* @return {Promise<string>}
*/
async dumpPrivKey (address: string): Promise<string> {
return await this.client.call('dumpprivkey', [address], 'number')
}
/**
* Adds a private key (as returned by dumpprivkey) to your wallet. Requires a new wallet backup.
*
* @param {string} privkey The private key (see dumpprivkey)
* @param {string} [label=""] current label if address exists, otherwise "".
* @param {boolean} [rescan=true] Rescan the wallet for transactions
*/
async importPrivKey (privkey: string, label: string = '', rescan: boolean = true): Promise<void> {
return await this.client.call('importprivkey', [privkey, label, rescan], 'number')
}
/**
* Get detailed information about in-wallet transaction
*
* @param {string} txid transaction id
* @param {boolean} includeWatchOnly optional, default = true
* @return {Promise<InWalletTransaction>}
*/
async getTransaction (txid: string, includeWatchOnly: boolean = true): Promise<InWalletTransaction> {
return await this.client.call('gettransaction', [txid, includeWatchOnly], { amount: 'bignumber' })
}
}
export interface UTXO {
txid: string
vout: number
address: string
label: string
scriptPubKey: string
amount: BigNumber
tokenId: number
confirmations: number
redeemScript: number
witnessScript: number
spendable: boolean
solvable: boolean
reused: string
desc: string
safe: boolean
}
export interface ListUnspentOptions {
addresses?: string[]
includeUnsafe?: boolean
queryOptions?: ListUnspentQueryOptions
}
export interface ListUnspentQueryOptions {
minimumAmount?: number
maximumAmount?: number
maximumCount?: number
minimumSumAmount?: number
tokenId?: string
}
export interface CreateWalletOptions {
blank?: boolean
passphrase?: string
avoidReuse?: boolean
}
export interface SendToAddressOptions {
comment?: string
commentTo?: string
subtractFeeFromAmount?: boolean
replaceable?: boolean
confTarget?: number
estimateMode?: Mode
avoidReuse?: boolean
}
export interface SendManyOptions {
comment?: string
replaceable?: boolean
confTarget?: number
estimateMode?: Mode
}
export interface CreateWalletResult {
name: string
warning: string
}
export interface WalletInfo {
walletname: string
walletversion: number
balance: BigNumber
unconfirmed_balance: BigNumber
immature_balance: BigNumber
txcount: number
keypoololdest: number
keypoolsize: number
keypoolsize_hd_internal: number
unlocked_until: number
paytxfee: BigNumber
hdseedid: string
private_keys_enabled: boolean
avoid_reuse: boolean
scanning: {
duration: number
progress: number
}
}
export interface ValidateAddressResult {
isvalid: boolean
address: string
scriptPubKey: string
isscript: boolean
iswitness: boolean
witness_version: number
witness_program: string
}
export interface AddressInfo {
address: string
scriptPubKey: string
ismine: boolean
iswatchonly: boolean
solvable: boolean
desc: string
isscript: boolean
ischange: true
iswitness: boolean
witness_version: number
witness_program: string
script: ScriptType
hex: string
pubkeys: string[]
sigsrequired: number
pubkey: string
embedded: {
address: string
scriptPubKey: string
isscript: boolean
iswitness: boolean
witness_version: number
witness_program: string
script: ScriptType
hex: string
sigsrequired: number
pubkey: string
pubkeys: string[]
}
iscompressed: boolean
label: string
timestamp: number
hdkeypath: string
hdseedid: string
hdmasterfingerprint: string
labels: Label[]
}
export interface Label {
name: string
purpose: string
}
export interface WalletFlagResult {
flag_name: string
flag_state: boolean
warnings: string
}
export interface InWalletTransaction {
amount: BigNumber
fee: number
confirmations: number
blockhash: string
blockindex: number
blocktime: number
txid: string
time: number
timereceived: number
bip125replaceable?: BIP125
details: InWalletTransactionDetail[]
hex: string
}
export interface InWalletTransactionDetail {
address: string
category: InWalletTransactionCategory
amount: number
label: string
vout: number
fee: number
abandoned: boolean
}
export interface WalletBalances {
mine: WalletMineBalances
watchonly?: WalletWatchOnlyBalances
}
export interface WalletMineBalances {
trusted: BigNumber
untrusted_pending: BigNumber
immature: BigNumber
used?: BigNumber
}
export interface WalletWatchOnlyBalances {
trusted: BigNumber
untrusted_pending: BigNumber
immature: BigNumber
}
| 1.625 | 2 |
node_modules/cypress/types/cypress-expect.d.ts | felixshiftellecon/lets-go-snippetbox | 39,773 | 1624 | // Cypress adds chai expect and assert to global
declare const expect: Chai.ExpectStatic
declare const assert: Chai.AssertStatic
| 0.378906 | 0 |
node_modules/rxjs/src/observable/ConnectableObservable.ts | nikulinn/angular-gulp | 9 | 1632 | import { Subject, SubjectSubscriber } from '../Subject';
import { Operator } from '../Operator';
import { Observable } from '../Observable';
import { Subscriber } from '../Subscriber';
import { Subscription, TeardownLogic } from '../Subscription';
/**
* @class ConnectableObservable<T>
*/
export class ConnectableObservable<T> extends Observable<T> {
protected _subject: Subject<T>;
protected _refCount: number = 0;
protected _connection: Subscription;
constructor(protected source: Observable<T>,
protected subjectFactory: () => Subject<T>) {
super();
}
protected _subscribe(subscriber: Subscriber<T>) {
return this.getSubject().subscribe(subscriber);
}
protected getSubject(): Subject<T> {
const subject = this._subject;
if (!subject || subject.isStopped) {
this._subject = this.subjectFactory();
}
return this._subject;
}
connect(): Subscription {
let connection = this._connection;
if (!connection) {
connection = this._connection = new Subscription();
connection.add(this.source
.subscribe(new ConnectableSubscriber(this.getSubject(), this)));
if (connection.closed) {
this._connection = null;
connection = Subscription.EMPTY;
} else {
this._connection = connection;
}
}
return connection;
}
refCount(): Observable<T> {
return this.lift(new RefCountOperator<T>(this));
}
}
class ConnectableSubscriber<T> extends SubjectSubscriber<T> {
constructor(destination: Subject<T>,
private connectable: ConnectableObservable<T>) {
super(destination);
}
protected _error(err: any): void {
this._unsubscribe();
super._error(err);
}
protected _complete(): void {
this._unsubscribe();
super._complete();
}
protected _unsubscribe() {
const { connectable } = this;
if (connectable) {
this.connectable = null;
const connection = (<any> connectable)._connection;
(<any> connectable)._refCount = 0;
(<any> connectable)._subject = null;
(<any> connectable)._connection = null;
if (connection) {
connection.unsubscribe();
}
}
}
}
class RefCountOperator<T> implements Operator<T, T> {
constructor(private connectable: ConnectableObservable<T>) {
}
call(subscriber: Subscriber<T>, source: any): TeardownLogic {
const { connectable } = this;
(<any> connectable)._refCount++;
const refCounter = new RefCountSubscriber(subscriber, connectable);
const subscription = source._subscribe(refCounter);
if (!refCounter.closed) {
(<any> refCounter).connection = connectable.connect();
}
return subscription;
}
}
class RefCountSubscriber<T> extends Subscriber<T> {
private connection: Subscription;
constructor(destination: Subscriber<T>,
private connectable: ConnectableObservable<T>) {
super(destination);
}
protected _unsubscribe() {
const { connectable } = this;
if (!connectable) {
this.connection = null;
return;
}
this.connectable = null;
const refCount = (<any> connectable)._refCount;
if (refCount <= 0) {
this.connection = null;
return;
}
(<any> connectable)._refCount = refCount - 1;
if (refCount > 1) {
this.connection = null;
return;
}
///
// Compare the local RefCountSubscriber's connection Subscription to the
// connection Subscription on the shared ConnectableObservable. In cases
// where the ConnectableObservable source synchronously emits values, and
// the RefCountSubscriber's dowstream Observers synchronously unsubscribe,
// execution continues to here before the RefCountOperator has a chance to
// supply the RefCountSubscriber with the shared connection Subscription.
// For example:
// ```
// Observable.range(0, 10)
// .publish()
// .refCount()
// .take(5)
// .subscribe();
// ```
// In order to account for this case, RefCountSubscriber should only dispose
// the ConnectableObservable's shared connection Subscription if the
// connection Subscription exists, *and* either:
// a. RefCountSubscriber doesn't have a reference to the shared connection
// Subscription yet, or,
// b. RefCountSubscriber's connection Subscription reference is identical
// to the shared connection Subscription
///
const { connection } = this;
const sharedConnection = (<any> connectable)._connection;
this.connection = null;
if (sharedConnection && (!connection || sharedConnection === connection)) {
sharedConnection.unsubscribe();
}
}
}
| 1.476563 | 1 |
src/components/Recipes/types.ts | rap0so/Section-food-pack | 1 | 1640 | export type TRecipesProps = {
filterPeople: React.Dispatch<React.SetStateAction<number>>;
filterWeek: React.Dispatch<React.SetStateAction<number>>;
selected: {
people: number;
week: number;
};
};
| 0.625 | 1 |
src/renderer/components/overlays/pref-overlay/entries-pref/EntriesPref.tsx | vaibhawj/mini-diary | 968 | 1648 | import React, { ReactElement } from "react";
import { translations } from "../../../../utils/i18n";
import FutureEntriesPrefContainer from "./future-entries-pref/FutureEntriesPrefContainer";
import HideTitlesPrefContainer from "./hide-titles-pref/HideTitlesPrefContainer";
import SpellcheckPrefContainer from "./spellcheck-pref/SpellcheckPrefContainer";
/**
* Preference fieldset for options related to diary entries
*/
export default function EntriesPref(): ReactElement {
return (
<fieldset className="fieldset-entries">
<legend>{translations["diary-entries"]}</legend>
<div className="fieldset-content">
<HideTitlesPrefContainer />
<br />
<FutureEntriesPrefContainer />
<br />
<SpellcheckPrefContainer />
</div>
</fieldset>
);
}
| 1.007813 | 1 |
src/main/docs/paths.ts | micael95/bdev_ts_api | 0 | 1656 | import {
loginPath, passwordPath,
signUpPath
} from './paths/'
export default {
'/v1/login': loginPath,
'/v1/signup': signUpPath,
'/v1/password': passwordPath
}
| 0.255859 | 0 |
data/src/config/config.ts | erez111/node-skeleton | 5 | 1664 | export const Config = {
environment: process.env.NODE_ENV || 'development',
swaggerPath: 'docs',
// eslint-disable-next-line radix
port: (process.env.PORT && parseInt(process.env.PORT)) ? parseInt(process.env.PORT) : 3100,
};
| 0.371094 | 0 |
packages/mui-styles/navigationMenu/float/floatNavigationMenu.styles.d.ts | Right-Angle-Engineering/mui-treasury | 0 | 1672 | import { Theme } from '@mui/material/styles';
export declare type FloatNavigationMenuStyleProps = {
gutter?: string | number;
};
export declare type FloatNavigationMenuClassKey = keyof ReturnType<typeof floatNavigationMenuStyles>;
declare const floatNavigationMenuStyles: ({ palette, spacing }: Theme) => never;
export default floatNavigationMenuStyles;
| 0.566406 | 1 |
src/components/Theme/Theme.Switch.tsx | cosmo-au/ui | 0 | 1680 | import { Moon, Sun } from 'phosphor-react';
import React from 'react';
import { useDarkMode } from 'usehooks-ts';
import { Button } from '../Button';
import ThemeStyles from './Theme.styles';
const { SwitchWrapper } = ThemeStyles();
export default function Switch(): JSX.Element {
const { isDarkMode, toggle } = useDarkMode();
return (
<SwitchWrapper>
<Button onClick={toggle}>{isDarkMode ? <Moon /> : <Sun />}</Button>
</SwitchWrapper>
);
}
| 1.210938 | 1 |
src/users/users.service.ts | naimkst/Crypto-App-With-Nest-Js-Backend | 0 | 1688 | import {
BadRequestException,
Injectable,
NotFoundException,
UnauthorizedException,
} from '@nestjs/common';
import { hash, compare } from 'bcrypt';
import { CreateUserRequest } from './dto/request/create-user-request.dto';
import { UserResponse } from './dto/response/user-response.dto';
import { CoinbaseAuth } from './models/CoinbaseAuth';
import { User } from './models/User';
import { UsersRepository } from './users.repository';
@Injectable()
export class UsersService {
constructor(private readonly usersRepository: UsersRepository) {}
async createUser(
createUserRequest: CreateUserRequest,
): Promise<UserResponse> {
await this.validateCreateUserRequest(createUserRequest);
const user = await this.usersRepository.insertOne({
...createUserRequest,
password: await hash(createUserRequest.password, 10),
});
return this.buildResponse(user);
}
async updateUser(userId: string, data: Partial<User>): Promise<UserResponse> {
const user = await this.usersRepository.updateOne(userId, data);
if (!user) {
throw new NotFoundException(`User not found by _id: '${userId}'.`);
}
return this.buildResponse(user);
}
private async validateCreateUserRequest(
createUserRequest: CreateUserRequest,
): Promise<void> {
const user = await this.usersRepository.findOneByEmail(
createUserRequest.email,
);
if (user) {
throw new BadRequestException('This email already exists.');
}
}
async validateUser(email: string, password: string): Promise<UserResponse> {
const user = await this.usersRepository.findOneByEmail(email);
if (!user) {
throw new NotFoundException(`User does not exist by email: '${email}'.`);
}
const passwordIsValid = await compare(password, user.password);
if (!passwordIsValid) {
throw new UnauthorizedException('Credentials are invalid');
}
return this.buildResponse(user);
}
async getUserById(userId: string): Promise<UserResponse> {
const user = await this.usersRepository.findOneById(userId);
if (!user) {
throw new NotFoundException(`User not found by _id: '${userId}'.`);
}
return this.buildResponse(user);
}
async getCoinbaseAuth(userId: string): Promise<CoinbaseAuth> {
const user = await this.usersRepository.findOneById(userId);
if (!user) {
throw new NotFoundException(`User not found by _id: '${userId}'.`);
}
if (!user.coinbaseAuth) {
throw new UnauthorizedException(
`User with _id: '${userId}' has not authorized Coinbase.`,
);
}
return user.coinbaseAuth;
}
private buildResponse(user: User): UserResponse {
return {
_id: user._id.toHexString(),
email: user.email,
isCoinbaseAuthorized: !!user.coinbaseAuth,
};
}
}
| 1.585938 | 2 |
src/modules/staking/components/CooldownInfoModal/messages.ts | xam-darnold/aave-ui | 95 | 1696 | import { defineMessages } from 'react-intl';
export default defineMessages({
caption: 'Cooldown & Unstake Window Period',
description:
'The cooldown period is {cooldownPeriod}. After the {cooldownPeriod} of cooldown, you will enter the unstake window of {unstakeWindowPeriod}.',
continueReceiving: 'You will continue receiving rewards during the cooldown and unstake window.',
infoDescription:
'If you do not unstake within the 2 days unstake window you will need to activate the cooldown process again',
cooldownTitle: 'Cooldown period',
unstakeHere: 'You unstake here',
unstakeWindowTitle: 'Unstake window',
checkboxText:
'I understand how the cooldown ({cooldownPeriod}) and unstaking window ({unstakingWindowPeriod}) work',
activateCooldown: 'Activate Cooldown',
});
| 0.828125 | 1 |
app/javascript/components/Datepicker/Datepicker.tsx | hongshaoyang/hn-search | 365 | 1704 | import * as React from "react";
import DayPicker from "react-day-picker";
import format from "date-fns/format";
import fromUnixTime from "date-fns/fromUnixTime";
import subDays from "date-fns/subDays";
import { CSSTransition } from "react-transition-group";
import XCircle from "react-feather/dist/icons/x-circle";
import Calendar from "react-feather/dist/icons/calendar";
import { SearchContext } from "../../providers/SearchProvider";
import useClickOutside from "../../utils/useClickOutside";
const isSelectingFirstDay = (from: Date, to: Date, day: Date) => {
const isBeforeFirstDay = from && DayPicker.DateUtils.isDayBefore(day, from);
const isRangeSelected = from && to;
return !from || isBeforeFirstDay || isRangeSelected;
};
const getUTCDate = (date = new Date()) => {
return new Date(date.getTime() + date.getTimezoneOffset() * 60 * 1000);
};
const DEFAULT_FROM_DATE = subDays(new Date(), 7);
const DEFAULT_TO_DATE = new Date();
export interface DatePickerProps {
isOpen: boolean;
onChange: (from: Date, to: Date) => any;
onCancel: () => any;
onBlur: () => any;
}
const parseDate = (date: string | null, defaultDate: Date): Date => {
if (!date) return defaultDate;
return fromUnixTime(parseInt(date));
};
const DatePicker: React.FC<DatePickerProps> = ({
onCancel,
onChange,
onBlur
}) => {
const {
settings: { dateEnd, dateStart }
} = React.useContext(SearchContext);
const [state, setState] = React.useState({
from: parseDate(dateStart, DEFAULT_FROM_DATE),
to: parseDate(dateEnd, DEFAULT_TO_DATE),
enteredTo: parseDate(dateEnd, DEFAULT_TO_DATE)
});
const handleResetClick = React.useCallback(() => {
setState({
from: null,
to: null,
enteredTo: null
});
}, []);
const handleDayClick = React.useCallback(
(day: Date) => {
const { from, to } = state;
if (from && to && day >= from && day <= to) {
return handleResetClick();
}
if (isSelectingFirstDay(from, to, day)) {
const fromDate = getUTCDate(day);
setState({
from: fromDate,
to: null,
enteredTo: fromDate
});
} else {
const toDate = getUTCDate(day);
setState({
from: state.from,
to: toDate,
enteredTo: toDate
});
}
},
[state]
);
const handleDayMouseEnter = React.useCallback(
(day: Date) => {
const { from, to } = state;
if (!isSelectingFirstDay(from, to, day)) {
setState({
from: state.from,
to: state.to,
enteredTo: day
});
}
},
[state]
);
const wrapOnChangeWithDefaults = () => {
onChange(state.from || DEFAULT_FROM_DATE, state.to || DEFAULT_TO_DATE);
};
const { from, enteredTo } = state;
const modifiers = { start: from, end: enteredTo };
const disabledDays = { after: new Date() };
const selectedDays = [from, { from, to: enteredTo }];
const datePickerRef = React.useRef(null);
useClickOutside(datePickerRef, () => onBlur());
return (
<CSSTransition
appear={true}
classNames="DatepickerAnimation"
in={true}
timeout={0}
>
<div className="DatePicker" ref={datePickerRef}>
<div className="DatePicker-container">
<DayPicker
className="Range"
numberOfMonths={1}
selectedDays={selectedDays}
disabledDays={disabledDays}
modifiers={modifiers}
onDayClick={handleDayClick}
onDayMouseEnter={handleDayMouseEnter}
/>
<form
className="DatePicker_form"
action=""
onSubmit={event => {
event.preventDefault();
onChange(state.from, state.to);
}}
>
<fieldset>
<h3>
<Calendar />
Custom Date Range
</h3>
<div>
<label htmlFor="from">From</label>
<input
id="from"
type="date"
placeholder="From date"
value={format(state.from || DEFAULT_FROM_DATE, "yyyy-MM-dd")}
onChange={({ currentTarget: { value } }) => {
setState({
...state,
from: value ? new Date(value) : null
});
}}
/>
</div>
<div>
<label htmlFor="to">To</label>
<input
id="to"
type="date"
placeholder="To date"
value={format(state.to || DEFAULT_TO_DATE, "yyyy-MM-dd")}
onChange={({ currentTarget: { value } }) => {
setState({
...state,
to: value ? new Date(value) : null
});
}}
/>
</div>
<div className="DatePicker_actions">
<button type="button" onClick={onCancel}>
<XCircle /> Cancel
</button>
<button
type="submit"
disabled={!state.from}
onClick={() => {
onBlur();
wrapOnChangeWithDefaults();
}}
>
Apply
</button>
</div>
</fieldset>
</form>
</div>
</div>
</CSSTransition>
);
};
export default DatePicker;
| 1.710938 | 2 |
packages/graphiql/src/utility/getQueryFacts.ts | ChiragKasat/graphiql | 14,155 | 1712 | /**
* Copyright (c) 2021 GraphQL Contributors.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import {
parse,
typeFromAST,
GraphQLSchema,
DocumentNode,
OperationDefinitionNode,
NamedTypeNode,
GraphQLNamedType,
visit,
} from 'graphql';
export type VariableToType = {
[variable: string]: GraphQLNamedType;
};
export type QueryFacts = {
variableToType?: VariableToType;
operations?: OperationDefinitionNode[];
documentAST?: DocumentNode;
};
/**
* Provided previous "operationFacts", a GraphQL schema, and a query document
* string, return a set of facts about that query useful for GraphiQL features.
*
* If the query cannot be parsed, returns undefined.
*/
export default function getOperationFacts(
schema?: GraphQLSchema,
documentStr?: string | null,
): QueryFacts | undefined {
if (!documentStr) {
return;
}
let documentAST: DocumentNode;
try {
documentAST = parse(documentStr, {
experimentalFragmentVariables: true,
});
} catch {
return;
}
const variableToType = schema
? collectVariables(schema, documentAST)
: undefined;
// Collect operations by their names.
const operations: OperationDefinitionNode[] = [];
visit(documentAST, {
OperationDefinition(node) {
operations.push(node);
},
});
return { variableToType, operations, documentAST };
}
/**
* as a nod to folks who were clever enough to import this utility on their
*/
export const getQueryFacts = getOperationFacts;
/**
* Provided a schema and a document, produces a `variableToType` Object.
*/
export function collectVariables(
schema: GraphQLSchema,
documentAST: DocumentNode,
): VariableToType {
const variableToType: {
[variable: string]: GraphQLNamedType;
} = Object.create(null);
documentAST.definitions.forEach(definition => {
if (definition.kind === 'OperationDefinition') {
const variableDefinitions = definition.variableDefinitions;
if (variableDefinitions) {
variableDefinitions.forEach(({ variable, type }) => {
const inputType = typeFromAST(schema, type as NamedTypeNode);
if (inputType) {
variableToType[variable.name.value] = inputType;
}
});
}
}
});
return variableToType;
}
| 1.5 | 2 |
packages/award-scripts/src/library/export/utils/createPort.ts | Topthinking/award | 1 | 1720 | import find = require('find-process');
const ensurePort = (port: number) => {
// 创建服务并监听该端口
return new Promise(resolve => {
find('port', port).then((list: Array<any>) => {
resolve(list.length);
});
});
};
export default async () => {
let port1 = 1234;
let port2 = 1235;
while (await ensurePort(port1)) {
port1++;
}
while (port2 === port1 || (await ensurePort(port2))) {
port2++;
}
return [port1, port2];
};
| 1.945313 | 2 |
src/hooks/navigation/useMenuHideWindow.ts | mankybansal/ipod-classic-js | 1,129 | 1728 | import { useCallback } from 'react';
import { useWindowContext } from 'hooks';
import useEventListener from '../utils/useEventListener';
import { IpodEvent } from 'utils/events';
/**
* A quick way to use the menu button as a back button.
* Provide an ID that matches the ID of the window you want to close.
*/
const useMenuHideWindow = (id: string) => {
const { windowStack, hideWindow } = useWindowContext();
const handleClick = useCallback(() => {
if (windowStack[windowStack.length - 1].id === id) {
hideWindow();
}
}, [hideWindow, id, windowStack]);
useEventListener<IpodEvent>('menuclick', handleClick);
};
export default useMenuHideWindow;
| 1.515625 | 2 |
extensions/git/src/askpass.ts | Fevre81/vscode | 0 | 1736 | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { window, InputBoxOptions, Uri, Disposable, workspace } from 'vscode';
import { IDisposable, EmptyDisposable, toDisposable } from './util';
import * as path from 'path';
import { IIPCHandler, IIPCServer } from './ipc/ipcServer';
import { CredentialsProvider, Credentials } from './api/git';
export class Askpass implements IIPCHandler {
private disposable: IDisposable = EmptyDisposable;
private cache = new Map<string, Credentials>();
private credentialsProviders = new Set<CredentialsProvider>();
constructor(private ipc?: IIPCServer) {
if (ipc) {
this.disposable = ipc.registerHandler('askpass', this);
}
}
async handle({ request, host }: { request: string; host: string }): Promise<string> {
const config = workspace.getConfiguration('git', null);
const enabled = config.get<boolean>('enabled');
if (!enabled) {
return '';
}
const uri = Uri.parse(host);
const authority = uri.authority.replace(/^.*@/, '');
const password = /password/i.test(request);
const cached = this.cache.get(authority);
if (cached && password) {
this.cache.delete(authority);
return cached.password;
}
if (!password) {
for (const credentialsProvider of this.credentialsProviders) {
try {
const credentials = await credentialsProvider.getCredentials(uri);
if (credentials) {
this.cache.set(authority, credentials);
setTimeout(() => this.cache.delete(authority), 60_000);
return credentials.username;
}
} catch { }
}
}
const options: InputBoxOptions = {
password,
placeHolder: request,
prompt: `Git: ${host}`,
ignoreFocusOut: true
};
return await window.showInputBox(options) || '';
}
getEnv(): { [key: string]: string } {
if (!this.ipc) {
return {
GIT_ASKPASS: path.join(__dirname, 'askpass-empty.sh')
};
}
let env: { [key: string]: string } = {
...this.ipc.getEnv(),
VSCODE_GIT_ASKPASS_NODE: process.execPath,
VSCODE_GIT_ASKPASS_EXTRA_ARGS: (process.versions['electron'] && process.versions['microsoft-build']) ? '--ms-enable-electron-run-as-node' : '',
VSCODE_GIT_ASKPASS_MAIN: path.join(__dirname, 'askpass-main.js')
};
const config = workspace.getConfiguration('git');
if (config.get<boolean>('useIntegratedAskPass')) {
env.GIT_ASKPASS = path.join(__dirname, 'askpass.sh');
}
return env;
}
registerCredentialsProvider(provider: CredentialsProvider): Disposable {
this.credentialsProviders.add(provider);
return toDisposable(() => this.credentialsProviders.delete(provider));
}
dispose(): void {
this.disposable.dispose();
}
}
| 1.492188 | 1 |
src/utils/get-workspace-info.ts | czaplej/nxpm-cli | 34 | 1744 | import { existsSync } from 'fs'
import { readJSONSync } from 'fs-extra'
import { join } from 'path'
import { error, log } from './logging'
export interface WorkspaceInfo {
cli: 'nx' | 'ng'
cwd: string
package: { [key: string]: any }
nx: { [key: string]: any }
type: 'nx' | 'angular'
packageManager: 'npm' | 'yarn'
path: string
workspace: { [key: string]: any }
workspaceJsonPath: string
}
export interface WorkspaceParams {
cwd: string
}
export function getWorkspaceInfo({ cwd }: WorkspaceParams): WorkspaceInfo {
const angularJsonPath = join(cwd, 'angular.json')
const nxJsonPath = join(cwd, 'nx.json')
const packageJsonPath = join(cwd, 'package.json')
const packageLockJsonPath = join(cwd, 'package-lock.json')
const workspaceJsonPath = join(cwd, 'workspace.json')
const yarnLockPath = join(cwd, 'yarn.lock')
const angularJsonExists = existsSync(angularJsonPath)
const packageLockJsonExists = existsSync(packageLockJsonPath)
const workspaceJsonExists = existsSync(workspaceJsonPath)
const yarnLockExists = existsSync(yarnLockPath)
if (!angularJsonExists && !workspaceJsonExists) {
error(`Can't find angular.json or workspace.json in ${cwd}`)
process.exit(1)
}
if (packageLockJsonExists && yarnLockExists) {
log('WARNING', 'Found package-lock.json AND yarn.lock - defaulting to yarn.')
}
const type = workspaceJsonExists ? 'nx' : 'angular'
const cli = workspaceJsonExists ? 'nx' : 'ng'
const workspacePath = workspaceJsonExists ? workspaceJsonPath : angularJsonPath
if (!existsSync(nxJsonPath)) {
throw new Error(`Can't find nx.json in ${nxJsonPath}`)
}
const packageManager = yarnLockExists ? 'yarn' : 'npm'
return {
cli,
cwd,
package: readJSONSync(packageJsonPath),
nx: existsSync(nxJsonPath) ? readJSONSync(nxJsonPath) : {},
path: workspacePath,
type,
workspace: readJSONSync(workspacePath),
workspaceJsonPath: workspacePath,
packageManager,
}
}
| 1.1875 | 1 |
src/widget/configs.entity.ts | tamnpham/myapi | 1 | 1752 | import { ApiProperty } from '@nestjs/swagger';
import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';
@Entity()
export class Config {
@ApiProperty()
@PrimaryGeneratedColumn()
id: number;
@ApiProperty()
@Column()
additionalProp1: number;
@ApiProperty()
@Column()
additionalProp2: number;
@ApiProperty()
@Column()
additionalProp3: number;
}
| 0.84375 | 1 |
src/m365/planner/commands/plan/plan-details-get.ts | reshmee011/cli-microsoft365 | 201 | 1760 | import { Group, PlannerPlanDetails } from '@microsoft/microsoft-graph-types';
import { Logger } from '../../../../cli';
import { CommandOption } from '../../../../Command';
import { accessToken, validation } from '../../../../utils';
import Auth from '../../../../Auth';
import GlobalOptions from '../../../../GlobalOptions';
import request from '../../../../request';
import { planner } from '../../../../utils/planner';
import GraphCommand from '../../../base/GraphCommand';
import commands from '../../commands';
interface CommandArgs {
options: Options;
}
interface Options extends GlobalOptions {
planId?: string;
planTitle?: string;
ownerGroupId?: string;
ownerGroupName?: string;
}
class PlannerPlanDetailsGetCommand extends GraphCommand {
private groupId: string = '';
public get name(): string {
return commands.PLAN_DETAILS_GET;
}
public get description(): string {
return 'Get details of a Microsoft Planner plan';
}
public getTelemetryProperties(args: CommandArgs): any {
const telemetryProps: any = super.getTelemetryProperties(args);
telemetryProps.planId = typeof args.options.planId !== 'undefined';
telemetryProps.planTitle = typeof args.options.planTitle !== 'undefined';
telemetryProps.ownerGroupId = typeof args.options.ownerGroupId !== 'undefined';
telemetryProps.ownerGroupName = typeof args.options.ownerGroupName !== 'undefined';
return telemetryProps;
}
public commandAction(logger: Logger, args: CommandArgs, cb: () => void): void {
if (accessToken.isAppOnlyAccessToken(Auth.service.accessTokens[this.resource].accessToken)) {
this.handleError('This command does not support application permissions.', logger, cb);
return;
}
this
.getGroupId(args)
.then((groupId: string): Promise<string> => {
this.groupId = groupId;
return this.getPlanId(args);
})
.then((planId: string): Promise<PlannerPlanDetails> => {
args.options.planId = planId;
return this.getPlanDetails(args);
})
.then((res: PlannerPlanDetails): void => {
logger.log(res);
cb();
}, (err: any): void => this.handleRejectedODataJsonPromise(err, logger, cb));
}
private getGroupId(args: CommandArgs): Promise<string> {
if (args.options.planId) {
return Promise.resolve('');
}
if (args.options.ownerGroupId) {
return Promise.resolve(args.options.ownerGroupId);
}
const requestOptions: any = {
url: `${this.resource}/v1.0/groups?$filter=displayName eq '${encodeURIComponent(args.options.ownerGroupName as string)}'`,
headers: {
accept: 'application/json;odata.metadata=none'
},
responseType: 'json'
};
return request
.get<{ value: Group[] }>(requestOptions)
.then(response => {
const groupItem: Group | undefined = response.value[0];
if (!groupItem) {
return Promise.reject(`The specified ownerGroup does not exist`);
}
if (response.value.length > 1) {
return Promise.reject(`Multiple ownerGroups with name ${args.options.ownerGroupName} found: Please choose between the following IDs ${response.value.map(x => x.id)}`);
}
return Promise.resolve(groupItem.id as string);
});
}
private getPlanId(args: CommandArgs): Promise<string> {
if (args.options.planId) {
return Promise.resolve(args.options.planId);
}
return planner
.getPlanByName(args.options.planTitle!, this.groupId)
.then(plan => plan.id!);
}
private getPlanDetails(args: CommandArgs): Promise<PlannerPlanDetails> {
const requestOptions: any = {
url: `${this.resource}/v1.0/planner/plans/${args.options.planId}/details`,
headers: {
'accept': 'application/json;odata.metadata=none'
},
responseType: 'json'
};
return request.get<PlannerPlanDetails>(requestOptions);
}
public options(): CommandOption[] {
const options: CommandOption[] = [
{
option: '-i, --planId [planId]'
},
{
option: '-t, --planTitle [planTitle]'
},
{
option: '--ownerGroupId [ownerGroupId]'
},
{
option: '--ownerGroupName [ownerGroupName]'
}
];
const parentOptions: CommandOption[] = super.options();
return options.concat(parentOptions);
}
public validate(args: CommandArgs): boolean | string {
if (!args.options.planId && !args.options.planTitle) {
return 'Specify either planId or planTitle';
}
if (args.options.planId && args.options.planTitle) {
return 'Specify either planId or planTitle';
}
if (args.options.planTitle && !args.options.ownerGroupId && !args.options.ownerGroupName) {
return 'Specify either ownerGroupId or ownerGroupName';
}
if (args.options.planTitle && args.options.ownerGroupId && args.options.ownerGroupName) {
return 'Specify either ownerGroupId or ownerGroupName but not both';
}
if (args.options.ownerGroupId && !validation.isValidGuid(args.options.ownerGroupId as string)) {
return `${args.options.ownerGroupId} is not a valid GUID`;
}
return true;
}
}
module.exports = new PlannerPlanDetailsGetCommand(); | 1.242188 | 1 |
lib/src/components/LanguageFlags.tsx | cschleiden/idiomatically | 0 | 1768 | import * as React from "react";
import { Tooltip } from "antd";
import "./LanguageFlags.scss";
import { FullIdiomEntry_language, FullIdiomEntry_language_countries } from "../__generated__/types";
import { CountryFlag, FlagSize } from "./CountryFlag";
export interface LanguageFlagsProps {
languageInfo: FullIdiomEntry_language;
/**
* Small - 24px
* Default - 32px
* Large - 40px
*/
size?: FlagSize;
showLabel?: boolean;
layoutMode?: "horizontal" | "vertical";
compactMode?: boolean;
hideFlags?: boolean;
}
export const LanguageFlags: React.StatelessComponent<LanguageFlagsProps> = props => {
const languageLabel = `${props.languageInfo.languageName}`;
const layoutMode = props.layoutMode || "horizontal";
const size = props.size || "default";
return (
<div className={["flagAvatarContainer", layoutMode, size].join(" ")}>
{props.showLabel && <div className="flagAfterText">{languageLabel}</div>}
{!props.hideFlags && renderFlag(props.languageInfo.countries, size, props.compactMode)}
</div>
);
};
const renderFlag = (countries: FullIdiomEntry_language_countries[], size?: FlagSize, compactMode?: boolean) => {
if (compactMode) {
// Just pick first country for now, in the future we may want some idea
// of default country that best represents the idiom
countries = countries.sort((a, b) => {
if (a.countryKey === 'US') {
return -1;
}
else if (b.countryKey === 'US') {
return 1;
}
return a.countryName.localeCompare(b.countryName);
}
);
const country = countries[0];
return (
<div className="flagsGroup">
<CountryFlag country={country} size={size} />
{countries.length > 1 && (
<Tooltip
className="flagOverflow"
placement="top"
title={<div className="flagOverflowTooltip">{renderFlagList(countries.slice(1), size)}</div>}
arrowPointAtCenter
>
<span className="flagOverflowText">+{countries.length - 1}</span>
</Tooltip>
)}
</div>
);
} else {
return <div className="flagsGroup">{renderFlagList(countries, size)}</div>;
}
};
const renderFlagList = (countries: FullIdiomEntry_language_countries[], size?: FlagSize) => (
<div className="flagList">{countries.map(f => <CountryFlag key={f.countryKey} country={f} size={size} />)}</div>
); | 1.664063 | 2 |
api/src/system/roles/entities/role.entity.ts | fannyfur/ng-nest-admin | 80 | 1776 |
import { Entity, Column, ManyToMany, PrimaryColumn, JoinTable, ManyToOne } from 'typeorm';
import { User } from '../../users/entities/user.entity';
import { Action } from '../../actions/entities/action.entity';
import { Organization } from '../../organization/entities/organization.entity';
@Entity("system_role")
export class Role {
@PrimaryColumn("uuid", { length: 36 })
id: string;
@Column()
name: string;
@Column({ length: 36 })
organizationId: string;
@ManyToOne(type => Organization, organization => organization.roles, { onDelete: 'CASCADE' })
organization: Organization;
@ManyToMany(type => User, user => user.roles)
@JoinTable({
name: "system_user_role",
joinColumn: { name: 'roleId' },
inverseJoinColumn: { name: 'userId' }
})
users: User[];
@ManyToMany(type => Action, action => action.roles)
@JoinTable({
name: "system_role_action",
joinColumn: { name: 'roleId' },
inverseJoinColumn: { name: 'actionId' }
})
actions: Action[];
} | 1.210938 | 1 |
server/src/routes/publisher.ts | LoganCorey/Watch-Tower | 0 | 1784 | import { Router, Request, Response, NextFunction } from "express";
import Publisher from "../models/publisher";
import {
getAllPublishers,
getPublisherById,
insertPublisherIfNotExists,
deletePublisherById,
} from "../controllers/publisher-controller";
import multer from "multer";
import path from "path";
import crypto from 'crypto';
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(
null,
path.resolve(process.env.APPDATA, "WatchTower", "assets", "publishers")
);
},
filename: (req, file, cb) => {
cb(null, crypto.randomBytes(16).toString("hex") + path.extname(file.originalname)); // Append extension
},
});
const upload = multer({ storage }).single("image");
const router: Router = Router();
/**
* Retrieves all publishers
*/
router.get(
"/publisher",
async (req: Request, res: Response, next: NextFunction) => {
try {
const publishers: Publisher[] = await getAllPublishers();
res.status(200).json({ publishers });
} catch (err) {
next(err);
}
}
);
/**
* Retrieves publisher by id
*/
router.get(
"/publisher/:id",
async (req: Request, res: Response, next: NextFunction) => {
try {
const publisherId: number = parseInt(req.params.id, 10);
const publisher: Publisher = await getPublisherById(publisherId);
if (publisher !== null) {
res.status(200).json({ publisher });
} else {
res.status(404).json(`Publisher does not exist ${publisherId}`);
}
} catch (err) {
next(err);
}
}
);
/**
* Update an issue but do not replace it
*/
router.patch(
"/publisher/:id",
upload,
async (req: Request, res: Response, next: NextFunction) => {
try {
const publisher: Publisher = await getPublisherById(parseInt(req.params.id, 10));
if (req.file) {
const publisherImagePath: string = `publishers/${path.basename(req.file.path)}`;
const updatedPublisher: Publisher = await publisher.update({
...req.body,
publisher_image: publisherImagePath,
});
res.status(200).json(updatedPublisher);
} else {
const updatedPublisher: Publisher = await publisher.update({ ...req.body });
res.status(200).json(updatedPublisher);
}
} catch (err) {
next(err);
}
}
);
/**
* Create a publisher given a name if it does not already exist
*/
router.post(
"/publisher",
upload,
async (req: Request, res: Response, next: NextFunction) => {
try {
const publisherName: string = req.body.publisherName;
const publisherImagePath: string = `publishers/${path.basename(req.file.path)}`;
const insertedPublisher: [
Publisher,
boolean
] = await insertPublisherIfNotExists(publisherName, publisherImagePath);
// resource created
if (insertedPublisher[1] === true) {
res.status(201).json(insertedPublisher[0]);
}
// resource already exists
else {
res.status(409).json(insertedPublisher[0]);
}
} catch (err) {
next(err);
}
}
);
/**
* Deletes a publisher given an id if it exists
*/
router.delete(
"/publisher/:id",
async (req: Request, res: Response, next: NextFunction) => {
try {
const publisherId: number = parseInt(req.params.id, 10);
const publishersDeleted: number = await deletePublisherById(publisherId);
if (publishersDeleted > 0) {
res.status(204).send("Deleted publisher");
} else {
res
.status(404)
.send(`Could not find publisher given id ${publisherId}`);
}
} catch (err) {
next(err);
}
}
);
export default router;
| 1.5625 | 2 |
application.ts | Hexagon/lock | 1 | 1792 | const application = {
"name": "lock",
"version": "0.9.7",
"repo": "https://github.com/Hexagon/lock",
};
export { application };
| 0.365234 | 0 |
node_modules/web3x/utils/hex-ascii.d.ts | sirivus/studioonline | 0 | 1800 | /**
* Should be called to get ascii from it's hex representation
*
* @method hexToAscii
* @param {String} hex
* @returns {String} ascii string representation of hex value
*/
export declare let hexToAscii: (hex: string) => string;
/**
* Should be called to get hex representation (prefixed by 0x) of ascii string
*
* @method asciiToHex
* @param {String} str
* @returns {String} hex representation of input string
*/
export declare let asciiToHex: (str: string) => string;
| 2.296875 | 2 |
packages/vertex-interface/src/components/QuestionHelper/index.tsx | Vertex-DEX/vertex-monorepo | 0 | 1808 | import React, { useCallback, useState } from 'react'
import { HelpCircle as Question } from 'react-feather'
import styled from 'styled-components'
import Tooltip from '../Tooltip'
const QuestionWrapper = styled.div`
display: flex;
align-items: center;
justify-content: center;
padding: 0.2rem;
border: none;
background: none;
outline: none;
cursor: default;
// border-radius: 36px;
background-color: ${({ theme }) => theme.bg2};
color: ${({ theme }) => theme.text2};
:hover,
:focus {
opacity: 0.7;
}
`
const LightQuestionWrapper = styled.div`
display: flex;
align-items: center;
justify-content: center;
padding: 0.2rem;
border: none;
background: none;
outline: none;
cursor: default;
// border-radius: 36px;
width: 24px;
height: 24px;
background-color: rgba(255, 255, 255, 0.1);
color: ${({ theme }) => theme.white};
:hover,
:focus {
opacity: 0.7;
}
`
const QuestionMark = styled.span`
font-size: 1rem;
`
export default function QuestionHelper({ text }: { text: string }) {
const [show, setShow] = useState<boolean>(false)
const open = useCallback(() => setShow(true), [setShow])
const close = useCallback(() => setShow(false), [setShow])
return (
<span style={{ marginLeft: 4 }}>
<Tooltip text={text} show={show}>
<QuestionWrapper onClick={open} onMouseEnter={open} onMouseLeave={close}>
<Question size={16} />
</QuestionWrapper>
</Tooltip>
</span>
)
}
export function LightQuestionHelper({ text }: { text: string }) {
const [show, setShow] = useState<boolean>(false)
const open = useCallback(() => setShow(true), [setShow])
const close = useCallback(() => setShow(false), [setShow])
return (
<span style={{ marginLeft: 4 }}>
<Tooltip text={text} show={show}>
<LightQuestionWrapper onClick={open} onMouseEnter={open} onMouseLeave={close}>
<QuestionMark>?</QuestionMark>
</LightQuestionWrapper>
</Tooltip>
</span>
)
}
| 1.726563 | 2 |
sections/loans/components/ActionBox/ActiveBorrowsTab/LoanList.tsx | artdgn/staking | 63 | 1816 | import { FC, useMemo, useEffect } from 'react';
import styled from 'styled-components';
import { useTranslation } from 'react-i18next';
import { CellProps } from 'react-table';
import media from 'styles/media';
import Table from 'components/Table';
import Currency from 'components/Currency';
import UIContainer from 'containers/UI';
import { Loan } from 'queries/loans/types';
import Loans from 'containers/Loans';
import ModifyLoanMenu from './ModifyLoanMenu';
import { DesktopOrTabletView, MobileOnlyView } from 'components/Media';
import { formatPercent } from 'utils/formatters/number';
import { wei } from '@synthetixio/wei';
const SMALL_COL_WIDTH = 80;
type LoanListProps = {
actions: string[];
};
const LoanList: FC<LoanListProps> = ({ actions }) => {
const { t } = useTranslation();
const { isLoadingLoans: isLoading, loans: data } = Loans.useContainer();
const { setTitle } = UIContainer.useContainer();
const desktopColumns = useMemo(
() => [
{
Header: <>{t('loans.tabs.list.types.debt')}</>,
accessor: 'debt',
sortable: true,
Cell: (cellProps: CellProps<Loan>) => {
const loan = cellProps.row.original;
return (
<CurrencyIconContainer>
<Currency.Name currencyKey={loan.debtAsset} showIcon={true} />
{wei(loan.amount).toString(2)}
</CurrencyIconContainer>
);
},
},
{
Header: <>{t('loans.tabs.list.types.collateral')}</>,
accessor: 'collateral',
sortable: true,
Cell: (cellProps: CellProps<Loan>) => {
const loan = cellProps.row.original;
return (
<CurrencyIconContainer>
<Currency.Name currencyKey={loan.collateralAsset} showIcon={true} />
{wei(loan.collateral).toString(2)}
</CurrencyIconContainer>
);
},
},
{
Header: <>{t('loans.tabs.list.types.cratio')}</>,
accessor: 'cratio',
sortable: true,
width: SMALL_COL_WIDTH,
Cell: (cellProps: CellProps<Loan>) => {
const loan = cellProps.row.original;
return <div>{formatPercent(loan.cratio)}</div>;
},
},
{
Header: <>{t('loans.tabs.list.types.modify')}</>,
id: 'modify',
width: SMALL_COL_WIDTH,
sortable: false,
Cell: (cellProps: CellProps<Loan>) => (
<ModifyLoanMenu loan={cellProps.row.original} {...{ actions }} />
),
},
],
[t, actions]
);
const mobileColumns = useMemo(
() => [
{
Header: <>{t('loans.tabs.list.types.debt')}</>,
accessor: 'debt',
sortable: true,
Cell: (cellProps: CellProps<Loan>) => {
const loan = cellProps.row.original;
return (
<CurrencyIconContainer>
{wei(loan.amount).toString(2)} {loan.debtAsset}
</CurrencyIconContainer>
);
},
},
{
Header: <>{t('loans.tabs.list.types.collateral')}</>,
accessor: 'collateral',
sortable: true,
Cell: (cellProps: CellProps<Loan>) => {
const loan = cellProps.row.original;
return (
<CurrencyIconContainer>
{wei(loan.collateral).toString(2)} {loan.collateralAsset}
</CurrencyIconContainer>
);
},
},
{
Header: <>{t('loans.tabs.list.types.modify')}</>,
id: 'modify',
width: 10,
sortable: false,
Cell: (cellProps: CellProps<Loan>) => (
<ModifyLoanMenu loan={cellProps.row.original} {...{ actions }} />
),
},
],
[t, actions]
);
// header title
useEffect(() => {
setTitle('loans', 'list');
}, [setTitle]);
const noResultsMessage =
!isLoading && data.length === 0 ? (
<NoResultsMessage>{t('loans.no-active-loans')}</NoResultsMessage>
) : null;
return (
<>
<DesktopOrTabletView>
<StyledTable
palette="primary"
{...{ isLoading, data }}
columns={desktopColumns}
noResultsMessage={noResultsMessage}
showPagination={true}
/>
</DesktopOrTabletView>
<MobileOnlyView>
<StyledTable
palette="primary"
{...{ isLoading, data }}
columns={mobileColumns}
noResultsMessage={noResultsMessage}
showPagination={true}
/>
</MobileOnlyView>
</>
);
};
//
const StyledTable = styled(Table)`
.table-row,
.table-body-row {
& > :last-child {
justify-content: flex-end;
}
}
.table-body {
min-height: 300px;
}
`;
const NoResultsMessage = styled.div`
text-align: center;
font-size: 12px;
padding: 20px 0 0;
`;
const CurrencyIconContainer = styled.div`
${media.greaterThan('mdUp')`
display: grid;
align-items: center;
grid-column-gap: 10px;
grid-template-columns: 2fr 1fr;
`}
`;
export default LoanList;
| 1.585938 | 2 |
packages/core/_src/stream/Sink/operations/dropWhileEffect.ts | Matechs-Garage/matechs-effect | 156 | 1824 | import { SinkInternal } from "@effect/core/stream/Sink/operations/_internal/SinkInternal"
/**
* @tsplus static ets/Sink/Ops dropWhileEffect
*/
export function dropWhileEffect<R, E, In>(
p: (input: In) => Effect<R, E, boolean>,
__tsplusTrace?: string
): Sink<R, E, In, In, unknown> {
const loop: Channel<
R,
E,
Chunk<In>,
unknown,
E,
Chunk<In>,
unknown
> = Channel.readWith(
(input: Chunk<In>) =>
Channel.unwrap(
input
.dropWhileEffect(p)
.map((leftover) =>
leftover.isEmpty()
? loop
: Channel.write(leftover) > Channel.identity<E, Chunk<In>, unknown>()
)
),
(err) => Channel.fail(err),
() => Channel.unit
)
return new SinkInternal(loop)
}
| 1.085938 | 1 |
packages/time-utilities/src/lib/TimerManager.ts | Stitch07/utilities | 46 | 1832 | /**
* Manages timers so that this application can be cleanly exited
*/
export class TimerManager extends null {
/**
* A set of timeouts to clear on destroy
*/
private static storedTimeouts = new Set<NodeJS.Timeout>();
/**
* A set of intervals to clear on destroy
*/
private static storedIntervals = new Set<NodeJS.Timeout>();
/**
* Creates a timeout gets cleared when destroyed
* @param fn callback function
* @param delay amount of time before running the callback
* @param args additional arguments to pass back to the callback
*/
public static setTimeout<A = unknown>(fn: (...args: A[]) => void, delay: number, ...args: A[]): NodeJS.Timeout {
const timeout = setTimeout(() => {
this.storedTimeouts.delete(timeout);
fn(...args);
}, delay);
this.storedTimeouts.add(timeout);
return timeout;
}
/**
* Clears a timeout created through this class
* @param timeout The timeout to clear
*/
public static clearTimeout(timeout: NodeJS.Timeout): void {
clearTimeout(timeout);
this.storedTimeouts.delete(timeout);
}
/**
* Creates an interval gets cleared when destroyed
* @param fn callback function
* @param delay amount of time before running the callback
* @param args additional arguments to pass back to the callback
*/
public static setInterval<A = unknown>(fn: (...args: A[]) => void, delay: number, ...args: A[]): NodeJS.Timeout {
const interval = setInterval(fn, delay, ...args);
this.storedIntervals.add(interval);
return interval;
}
/**
* Clears an internal created through this class
* @param interval The interval to clear
*/
public static clearInterval(interval: NodeJS.Timeout): void {
clearInterval(interval);
this.storedIntervals.delete(interval);
}
/**
* Clears running timeouts and intervals created through this class so NodeJS can gracefully exit
*/
public static destroy(): void {
for (const i of this.storedTimeouts) clearTimeout(i);
for (const i of this.storedIntervals) clearInterval(i);
this.storedTimeouts.clear();
this.storedIntervals.clear();
}
}
| 2.15625 | 2 |
src/modules/user/repositories/user.repository.ts | gabrielcowit/estudos-nestjs | 0 | 1840 | import { EntityRepository, getManager, Repository } from 'typeorm';
import { User } from '../entity/user.entity';
import { SignUpDTO } from '../../auth/dto/signup.dto';
@EntityRepository(User)
export class UserRepository extends Repository<User> {
async signup({ username, password, cars }): Promise<void> {
// getManager().transaction((entityManager) => {
//insercao em varias tabelas nao relacionadas
// });
const user = this.create({ username, password, vehicles: cars });
await this.save(user);
}
async findOneByUsername({ username }): Promise<User> {
return this.findOne({ username });
}
}
| 1.210938 | 1 |
src/Dropzone/Resources/assets/test/controller.test.ts | zalesak/ux | 0 | 1848 | /*
* This file is part of the Symfony package.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
'use strict';
import { Application, Controller } from '@hotwired/stimulus';
import { getByTestId, waitFor } from '@testing-library/dom';
import user from '@testing-library/user-event';
import { clearDOM, mountDOM } from '@symfony/stimulus-testing';
import DropzoneController from '../src/controller';
// Controller used to check the actual controller was properly booted
class CheckController extends Controller {
connect() {
this.element.addEventListener('dropzone:connect', () => {
this.element.classList.add('connected');
});
}
}
const startStimulus = () => {
const application = Application.start();
application.register('check', CheckController);
application.register('dropzone', DropzoneController);
};
describe('DropzoneController', () => {
let container;
beforeEach(() => {
container = mountDOM(`
<div class="dropzone-container" data-controller="check dropzone" data-testid="container">
<input type="file"
style="display: none"
data-dropzone-target="input"
data-testid="input" />
<div class="dropzone-placeholder"
data-dropzone-target="placeholder"
data-testid="placeholder">
Placeholder
</div>
<div class="dropzone-preview"
data-dropzone-target="preview"
data-testid="preview"
style="display: none">
<button type="button"
class="dropzone-preview-button"
data-dropzone-target="previewClearButton"
data-testid="button"></button>
<div class="dropzone-preview-image"
data-dropzone-target="previewImage"
data-testid="preview-image"
style="display: none"></div>
<div class="dropzone-preview-filename"
data-dropzone-target="previewFilename"
data-testid="preview-filename"></div>
</div>
</div>
`);
});
afterEach(() => {
clearDOM();
});
it('connect', async () => {
expect(getByTestId(container, 'container')).not.toHaveClass('connected');
startStimulus();
await waitFor(() => expect(getByTestId(container, 'container')).toHaveClass('connected'));
});
it('clear', async () => {
startStimulus();
await waitFor(() => expect(getByTestId(container, 'input')).toHaveStyle({ display: 'block' }));
// Attach a listener to ensure the event is dispatched
let dispatched = false;
getByTestId(container, 'container').addEventListener('dropzone:clear', () => (dispatched = true));
// Manually show preview
getByTestId(container, 'input').style.display = 'none';
getByTestId(container, 'placeholder').style.display = 'none';
getByTestId(container, 'preview').style.display = 'block';
// Click the clear button
getByTestId(container, 'button').click();
await waitFor(() => expect(getByTestId(container, 'input')).toHaveStyle({ display: 'block' }));
await waitFor(() => expect(getByTestId(container, 'placeholder')).toHaveStyle({ display: 'block' }));
await waitFor(() => expect(getByTestId(container, 'preview')).toHaveStyle({ display: 'none' }));
// The event should have been dispatched
expect(dispatched).toBe(true);
});
it('file chosen', async () => {
startStimulus();
await waitFor(() => expect(getByTestId(container, 'input')).toHaveStyle({ display: 'block' }));
// Attach a listener to ensure the event is dispatched
let dispatched = null;
getByTestId(container, 'container').addEventListener('dropzone:change', (event) => (dispatched = event));
// Select the file
const input = getByTestId(container, 'input');
const file = new File(['hello'], 'hello.png', { type: 'image/png' });
user.upload(input, file);
expect(input.files[0]).toStrictEqual(file);
// The dropzone should be in preview mode
await waitFor(() => expect(getByTestId(container, 'input')).toHaveStyle({ display: 'none' }));
await waitFor(() => expect(getByTestId(container, 'placeholder')).toHaveStyle({ display: 'none' }));
// The event should have been dispatched
expect(dispatched).not.toBeNull();
expect(dispatched.detail).toStrictEqual(file);
});
});
| 1.507813 | 2 |
src/containers/Container.tsx | PetKatt/image-uploader | 0 | 1856 | import * as React from 'react';
import { API_URL } from "../config";
import Msg from "../components/Msg";
import InputFile from "../components/InputFile";
import Welcome from "../components/Welcome";
import SpinLoader from "../components/SpinLoader";
import UserPanel from "./UserPanel";
import Header from "../components/Header";
import Footer from "../components/Footer";
interface State {
initializing: boolean,
uploading: boolean,
images: object[],
alertMsg: string
}
class Container extends React.Component<object, State> {
state = {
initializing: true,
uploading: false,
images: [],
alertMsg: ""
}
componentDidMount() { // INITIALIZING SERVER
fetch(`${API_URL}/initialize`)
.then((res) => {
if(res.ok) return this.setState({ initializing: false });
});
}
imageSelectedHandler = (event: any) => {
const myImage = event.target.files[0];
const formData = new FormData();
const types = ['image/jpeg', 'image/png', 'image/gif'];
/* validating input data*/
if(types.every(type => myImage.type !== type)) {
this.setState({ alertMsg: "Your image has invalid format! :(" });
} else if(myImage.size > 200000) {
this.setState({ alertMsg: "Your image is too big! :(" });
} else {
formData.append("myImage", myImage);
}
/* START UPLOADING */
this.setState({ uploading: true });
fetch(`${API_URL}/upload`, {
method: "POST",
body: formData
}).then(res => {
if(!res.ok) {
throw res;
}
return res.json();
}).then(images => {
this.setState({
uploading: false,
images
});
}).catch(err => {
err.json().then((e: object) => {
this.setState({ uploading: false });
});
});
}
removeImage = (): void => {
this.setState({ images: [] });
}
public render() {
const { initializing, uploading, images, alertMsg } = this.state;
const content = (): any => {
switch(true) {
case initializing:
return <Welcome />;
break;
case images.length > 0:
return <UserPanel images={images} />;
break;
case uploading:
return <SpinLoader />;
break;
default:
return <InputFile onChange={this.imageSelectedHandler} />;
break;
}
}
return (
<div className="container" role="uploader">
<Header removeImage={this.removeImage} />
{content()}
{ alertMsg ? <Msg alertMsg={alertMsg} /> : null }
<Footer />
</div>
);
}
}
export default Container; | 1.875 | 2 |
app/src/rendering/projected/projectedrendermanager.ts | paulscottrobson/string-trainer | 0 | 1864 | /// <reference path="../../../lib/phaser.comments.d.ts"/>
class ProjectedRenderManager extends BaseRenderManager implements IRenderManager {
public static yFront:number;
public static yPerBar:number;
public fixed:Phaser.Group;
constructor(game:Phaser.Game,music:IMusic) {
super(game,music);
ProjectedRenderManager.yFront = Configuration.yBase - 10;
ProjectedRenderManager.yPerBar = 550;
}
createRenderer(manager: IRenderManager, game: Phaser.Game, bar: IBar): IRenderer {
return new ProjectedRenderer(this,this.game,bar);
}
createFixed(game: Phaser.Game): void {
this.fixed = new Phaser.Group(game);
for (var s:number = 0;s < Configuration.strings;s++) {
var dbl:boolean = Configuration.instrument.isDoubleString(s);
var dx:number = ProjectedRenderManager.xPos(s,0)-
ProjectedRenderManager.xPos(s,1000);
var dy:number = ProjectedRenderManager.yPos(s,0)-
ProjectedRenderManager.yPos(s,1000);
var adj:number = Math.atan2(dy,dx);
var rail:Phaser.Image = game.add.image(0,0,"sprites",dbl ? "dstring":"string",this.fixed);
rail.x = ProjectedRenderManager.xPos(s,0);
rail.y = ProjectedRenderManager.yPos(s,0);
rail.width = game.height * 3 / 2;
rail.height = dbl ? 20:10;
rail.anchor.x = 1;rail.anchor.y = 0.5;
rail.rotation = adj;
/*
for (var y:number = 0;y <= 1000;y += 100) {
var i:Phaser.Image = game.add.image(0,0,"sprites","rectangle",this.fixed);
i.width = i.height = 9;i.anchor.x = i.anchor.y = 0.5;
i.x = ProjectedRenderManager.xPos(s,y);
i.y = ProjectedRenderManager.yPos(s,y);
if (y > 0) i.tint = 0x00FF00;
if (y == 1000) i.tint = 0xFF0000;
}
*/
}
}
destroyFixed(): void {
this.fixed.destroy();
}
moveTo(barPosition: number): void {
super.moveTo(barPosition);
for (var bn:number = 0;bn < this.music.getBarCount();bn++) {
this.renderers[bn].moveTo((bn-barPosition) * ProjectedRenderManager.yPerBar);
}
}
public static xPos(str:number,yl:number): number {
yl = ProjectedRenderManager.yPos(str,yl);
var xs:number = 0.1*(str-(Configuration.strings-1)/2) *
Configuration.width / (Configuration.strings-1);
xs = xs * (1+yl/120);
return xs + Configuration.width / 2;
}
public static yPos(str:number,y:number): number {
var camera:number = 500;
y = ProjectedRenderManager.yFront -
(1-camera/(y+camera))*(ProjectedRenderManager.yFront-200)*2.1;
return y;
}
} | 1.835938 | 2 |
lib/3id/index.d.ts | MasterVentures/xdvplatform-wallet | 2 | 1872 | export * from './DIDManager';
export * from './IPLDManager';
export * from './W3CVerifiedCredential';
| -0.390625 | 0 |
types/cronjob/CLIArguments.d.ts | mapp-digital/Mapp-Intelligence-Node-Tracking | 0 | 1880 | export declare class CLIArguments {
private readonly args;
constructor(args: Array<string>);
private setArg;
private parseArgs;
getArgs(): {
[key: string]: string;
};
}
| 0.898438 | 1 |
src/hooks/useDialog.ts | marco-bertelli/fullstack-ecommerce | 0 | 1888 | import { useState } from "react"
export const useDialog = () =>{
const [openDialog, setOpenDialog] = useState(false)
return {openDialog,setOpenDialog}
} | 0.914063 | 1 |
packages/react-vapor/src/components/flippable/Flippable.tsx | cestradamiranda/react-vapor | 0 | 1896 | import classNames from 'classnames';
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import {keys} from 'ts-transformer-keys';
import * as _ from 'underscore';
import {BrowserUtils} from '../../utils/BrowserUtils';
export interface IFlippableOwnProps {
id?: string;
front?: React.ReactNode;
back?: React.ReactNode;
className?: string;
allowUnflip?: (e: EventTarget) => boolean;
}
export interface IFlippableDispatchProps {
onRender?: () => void;
onDestroy?: () => void;
onFlip?: () => void;
onUnflip?: () => void;
}
export interface IFlippableStateProps {
isFlipped?: boolean;
}
export interface IFlippableProps extends IFlippableOwnProps, IFlippableDispatchProps, IFlippableStateProps {}
const FlippablePropsToOmit = keys<IFlippableProps>();
export class Flippable extends React.Component<IFlippableProps & React.HTMLProps<HTMLDivElement>, any> {
static CONTAINER_CLASSNAME: string = 'flippable';
static FLIPPER_CLASSNAME: string = 'flipper';
static sides = {
FRONT: 'flipper-front',
BACK: 'flipper-back',
};
static triggers = {
FRONT: 'show-front',
BACK: 'show-back',
};
static defaults: Partial<IFlippableProps> = {
isFlipped: false,
};
private backside: HTMLDivElement;
private frontside: HTMLDivElement;
componentWillMount() {
if (this.props.onRender) {
this.props.onRender();
}
document.addEventListener('click', this.handleOutsideClick);
}
componentWillUnmount() {
document.removeEventListener('click', this.handleOutsideClick);
if (this.props.onDestroy) {
this.props.onDestroy();
}
}
render() {
const containerClassName = classNames(
BrowserUtils.isIE() ? 'flippable-ie' : Flippable.CONTAINER_CLASSNAME,
this.props.isFlipped ? 'show-on-top' : '',
this.props.className
);
const flipperClassName = classNames(
Flippable.FLIPPER_CLASSNAME,
this.props.isFlipped ? Flippable.triggers.BACK : Flippable.triggers.FRONT
);
return (
<div className={containerClassName} {..._.omit(this.props, FlippablePropsToOmit)}>
<div className={flipperClassName}>
<div
className={Flippable.sides.FRONT}
onClick={this.handleClickOnFront}
ref={(frontside: HTMLDivElement) => (this.frontside = frontside)}
>
{this.props.front}
</div>
<div
className={Flippable.sides.BACK}
ref={(backside: HTMLDivElement) => (this.backside = backside)}
>
{this.props.back}
</div>
</div>
</div>
);
}
private handleClickOnFront = () => {
if (this.props.onFlip && !this.props.isFlipped) {
this.props.onFlip();
}
};
private handleOutsideClick = (e: MouseEvent) => {
if (this.props.isFlipped) {
const frontside: Element | Text = ReactDOM.findDOMNode(this.frontside);
const backside: Element | Text = ReactDOM.findDOMNode(this.backside);
const target: Node = e.target as Node;
if (
!backside.contains(target) &&
!frontside.contains(target) &&
(!this.props.allowUnflip || this.props.allowUnflip(target))
) {
this.handleUnflip();
e.preventDefault();
}
}
};
private handleUnflip() {
if (this.props.onUnflip) {
this.props.onUnflip();
}
}
}
| 1.398438 | 1 |
src/config/directory.ts | fachrihawari/nodeasy | 5 | 1904 | import * as path from 'path'
let rootDir = path.dirname(__dirname)
let appDir = path.join(rootDir, 'app')
export default {
config: path.join(rootDir, 'config'),
controller: path.join(appDir, 'Controllers'),
middleware: path.join(appDir, 'Middlewares'),
model: path.join(appDir, 'Models'),
view: path.join(rootDir, 'resources/views'),
lang: path.join(rootDir, 'resources/lang'),
route: path.join(rootDir, 'routes'),
public: path.join(rootDir, 'public'),
core: path.join(rootDir, 'core')
}
| 0.976563 | 1 |
tests/e2e/tests/build/styles/postcss.ts | kareemkibue/angular-cli | 1 | 1912 | import * as glob from 'glob';
import { writeFile, expectFileToMatch } from '../../../utils/fs';
import { ng } from '../../../utils/process';
import { getGlobalVariable } from '../../../utils/env';
import { stripIndents } from 'common-tags';
export default function () {
// Skip this in Appveyor tests.
if (getGlobalVariable('argv').appveyor) {
return Promise.resolve();
}
return writeFile('src/styles.css', stripIndents`
/* normal-comment */
/*! important-comment */
div { flex: 1 }
`)
// uses autoprefixer plugin for all builds
.then(() => ng('build', '--extract-css'))
.then(() => expectFileToMatch('dist/styles.bundle.css', stripIndents`
/* normal-comment */
/*! important-comment */
div { -webkit-box-flex: 1; -ms-flex: 1; flex: 1 }
`))
// uses postcss-discard-comments plugin for prod
.then(() => ng('build', '--prod'))
.then(() => glob.sync('dist/styles.*.bundle.css').find(file => !!file))
.then((stylesBundle) => expectFileToMatch(stylesBundle, stripIndents`
/*! important-comment */div{-webkit-box-flex:1;-ms-flex:1;flex:1}
`));
}
| 1.257813 | 1 |
src/abis/MExchangeCore.bin.ts | gorillafunds/PoC | 0 | 1920 | // tslint:disable-next-line:variable-name
export const MExchangeCoreBytecode = '';
| 0.202148 | 0 |
src/services/currency.service.ts | AlexanderSutul/Currency-API | 0 | 1928 | import axios from 'axios';
import {CurrencyModel} from "../Models/Currency.model";
export class CurrencyService {
static async getCurrency(): Promise<CurrencyModel> {
const url = 'https://www.cbr-xml-daily.ru/daily_json.js';
const response = await axios.get(url);
return new CurrencyModel(response.data);
}
}
| 0.90625 | 1 |
src/lib/apollo/useApollo.ts | takumiya081/ayu | 0 | 1936 | /* eslint-disable global-require */
/* eslint-disable @typescript-eslint/no-var-requires */
// https://github.com/vercel/next.js/blob/canary/examples/api-routes-apollo-server-and-client/apollo/client.js
import {InMemoryCache, NormalizedCacheObject} from 'apollo-cache-inmemory';
import {ApolloClient} from 'apollo-client';
import {useMemo} from 'react';
let apolloClient: ApolloClient<NormalizedCacheObject>;
function createIsomorphLink() {
if (typeof window === 'undefined') {
const {SchemaLink} = require('apollo-link-schema');
const {schema} = require('../../functions/infrastructure/schema');
return new SchemaLink({schema});
}
const {HttpLink} = require('apollo-link-http');
return new HttpLink({
uri: '/api/graphql',
credentials: 'same-origin',
});
}
function createApolloClient() {
return new ApolloClient({
ssrMode: typeof window === 'undefined',
link: createIsomorphLink(),
cache: new InMemoryCache(),
});
}
export function initializeApollo(initialState: NormalizedCacheObject | null = null) {
// eslint-disable-next-line no-underscore-dangle
const _apolloClient = apolloClient ?? createApolloClient();
// If your page has Next.js data fetching methods that use Apollo Client, the initial state
// get hydrated here
if (initialState) {
_apolloClient.cache.restore(initialState);
}
// For SSG and SSR always create a new Apollo Client
if (typeof window === 'undefined') return _apolloClient;
// Create the Apollo Client once in the client
if (!apolloClient) apolloClient = _apolloClient;
return _apolloClient;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function useApollo(initialState: NormalizedCacheObject | null) {
const store = useMemo(() => initializeApollo(initialState), [initialState]);
return store;
}
| 1.414063 | 1 |
cllc-public-app/ClientApp/src/app/models/application-content-type.model.ts | BrendanBeachBC/jag-lcrb-carla-public | 7 | 1944 |
export class ApplicationContentType {
id: string;
category: string;
body: string;
businessTypes: string[];
}
| 0.3125 | 0 |
src/app/components/form/form.component.ts | checkfelix123/socialblog | 1 | 1952 | import { Component, EventEmitter, Input, Output } from '@angular/core';
import { FormGroup } from '@angular/forms';
@Component({
selector: 'app-form',
templateUrl: './form.component.html',
styleUrls: ['./form.component.scss'],
})
export class FormComponent {
@Input()
formGroup: FormGroup;
@Input()
wide = false;
@Output()
submitted = new EventEmitter<FormGroup>();
constructor() {}
onSubmit() {
this.submitted.emit(this.formGroup);
}
}
| 1.085938 | 1 |
packages/ui-shared/src/icons/beachball/container.spec.ts | isabella232/ui-examples | 3 | 1960 | // Copyright 2017-2021 @polkadot/ui-shared authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { container } from './container';
describe('container', (): void => {
it('applies default styles', (): void => {
expect(
// eslint-disable-next-line @typescript-eslint/no-explicit-any,@typescript-eslint/no-unsafe-member-access
(container(100).style as any)._values
).toEqual({
background: 'white',
'border-radius': '50px',
display: 'inline-block',
height: '100px',
margin: '0px',
overflow: 'hidden',
padding: '0px',
width: '100px'
});
});
it('overrides with supplied styles', (): void => {
expect(
// eslint-disable-next-line @typescript-eslint/no-explicit-any,@typescript-eslint/no-unsafe-member-access
(container(50, 'black', '', { display: 'block' }).style as any)._values
).toEqual({
background: 'black',
'border-radius': '25px',
display: 'block',
height: '50px',
margin: '0px',
overflow: 'hidden',
padding: '0px',
width: '50px'
});
});
it('applies the specified className', (): void => {
expect(
container(100, 'blue', 'testClass').className
).toEqual('testClass');
});
});
| 1.445313 | 1 |
vendor/bower-asset/fullcalendar-scheduler/resource-common/src/reducers/resourceSource.ts | repouniverse/tut | 2 | 1968 | import { Calendar, DateProfile, rangesEqual, DateRange } from '@fullcalendar/core'
import { ResourceSource, parseResourceSource, getResourceSourceDef, doesSourceIgnoreRange } from '../structs/resource-source'
import { ResourceAction } from './resources'
export default function(
source: ResourceSource | undefined,
action: ResourceAction,
dateProfile: DateProfile,
calendar: Calendar
): ResourceSource | null {
switch (action.type) {
case 'INIT':
return createSource(calendar.opt('resources'), calendar)
case 'RESET_RESOURCE_SOURCE':
return createSource(action.resourceSourceInput, calendar, true)
case 'PREV': // TODO: how do we track all actions that affect dateProfile :(
case 'NEXT':
case 'SET_DATE':
case 'SET_VIEW_TYPE':
return handleRange(source, dateProfile.activeRange, calendar)
case 'RECEIVE_RESOURCES':
case 'RECEIVE_RESOURCE_ERROR':
return receiveResponse(source, action.fetchId, action.fetchRange)
case 'REFETCH_RESOURCES':
return fetchSource(source, dateProfile.activeRange, calendar)
default:
return source
}
}
let uid = 0
function createSource(input, calendar: Calendar, forceFetch?: boolean) {
if (input) {
let source = parseResourceSource(input)
if (forceFetch || !calendar.opt('refetchResourcesOnNavigate')) { // because assumes handleRange will do it later
source = fetchSource(source, null, calendar)
}
return source
}
return null
}
function handleRange(source: ResourceSource, activeRange: DateRange, calendar: Calendar): ResourceSource {
if (
calendar.opt('refetchResourcesOnNavigate') &&
!doesSourceIgnoreRange(source) &&
(!source.fetchRange || !rangesEqual(source.fetchRange, activeRange))
) {
return fetchSource(source, activeRange, calendar)
} else {
return source
}
}
function fetchSource(source: ResourceSource, fetchRange: DateRange | null, calendar: Calendar): ResourceSource {
let sourceDef = getResourceSourceDef(source.sourceDefId)
let fetchId = String(uid++)
sourceDef.fetch(
{
resourceSource: source,
calendar,
range: fetchRange
},
function(res) {
// HACK
// do before calling dispatch in case dispatch renders synchronously
calendar.afterSizingTriggers._resourcesRendered = [ null ] // fire once
calendar.dispatch({
type: 'RECEIVE_RESOURCES',
fetchId,
fetchRange,
rawResources: res.rawResources
})
},
function(error) {
calendar.dispatch({
type: 'RECEIVE_RESOURCE_ERROR',
fetchId,
fetchRange,
error
})
}
)
return {
...source,
isFetching: true,
latestFetchId: fetchId
}
}
function receiveResponse(source: ResourceSource, fetchId: string, fetchRange: DateRange) {
if (fetchId === source.latestFetchId) {
return {
...source,
isFetching: false,
fetchRange
}
}
return source
}
| 1.4375 | 1 |
tests/update.spec.ts | mtmr0x/nucleo | 101 | 1976 | import { createStore } from '../src/store';
import {
NucleoString,
NucleoNumber,
NucleoBoolean
} from '../src/nucleoTypes/primitive'
import NucleoObject from '../src/nucleoTypes/NucleoObject';
import { expect } from 'chai';
import 'mocha';
describe('Update forbidden attempts', () => {
const completeNameType = new NucleoObject({
name: 'completeName',
fields: {
firstName: NucleoString,
lastName: NucleoString
}
});
const userType = new NucleoObject({
name: 'user',
fields: {
name: completeNameType,
age: NucleoNumber
}
});
const contracts = { user: userType };
const store = createStore(contracts);
const { dispatch, update, cloneState } = store;
it('should use update method and throw for this item in store be empty', () => {
const d = () => update('user')({ name: { firstName: 'John' }});
expect(d).to.throw();
});
it('should dispatch values and then return error tring to update fields violating the contract', () => {
const d = dispatch('user')({
name: { firstName: 'John', lastName: 'Doe' },
age: 27
});
const { errors, data } = update('user')({ name: { name: 'matheus' } });
expect(errors.length).to.equal(1);
const user = cloneState('user') as any;
expect(user.name.firstName).to.equal('John');
expect(user.name.lastName).to.equal('Doe');
expect(user.age).to.equal(27);
});
});
describe('Update method', () => {
const completeNameType = new NucleoObject({
name: 'completeName',
fields: {
firstName: NucleoString,
lastName: NucleoString
}
});
const userAddressType = new NucleoObject({
name: 'userAddressType',
fields: {
street: NucleoString,
streetNumber: NucleoString,
complement: NucleoString
}
});
const userLocationType = new NucleoObject({
name: 'userLocationType',
fields: {
city: NucleoString,
address: userAddressType
}
});
const userType = new NucleoObject({
name: 'user',
fields: {
name: completeNameType,
age: NucleoNumber,
location: userLocationType,
verified: NucleoBoolean
}
});
const contracts = { user: userType };
const store = createStore(contracts);
const { dispatch, update, cloneState, subscribe } = store;
it('should dispatch only one property in deeper levels and just this property should be updated in store', () => {
const d = dispatch('user')({
name: { firstName: 'John', lastName: 'Doe' },
location: {
city: 'NY',
address: {
street: '9 avenue',
streetNumber: '678',
complement: ''
}
},
age: 27,
verified: true
});
update('user')({ name: { firstName: 'Joseph' } });
const user = cloneState('user') as any;
expect(user.name.firstName).to.equal('Joseph');
expect(user.name.lastName).to.equal('Doe');
expect(user.age).to.equal(27);
});
it('should dispatch only one property in first level and just this property should be updated in store', () => {
update('user')({ age: 18 });
const user = cloneState('user') as any;
expect(user.name.firstName).to.equal('Joseph');
expect(user.name.lastName).to.equal('Doe');
expect(user.age).to.equal(18);
});
it('should dispatch a value to a deeper level and save it properly', () => {
update('user')({ location: { address: { complement: 'apartment 2' } } });
const user = cloneState('user') as any;
expect(user.name.firstName).to.equal('Joseph');
expect(user.name.lastName).to.equal('Doe');
expect(user.age).to.equal(18);
expect(user.location.city).to.equal('NY');
expect(user.location.address.street).to.equal('9 avenue');
expect(user.location.address.streetNumber).to.equal('678');
expect(user.location.address.complement).to.equal('apartment 2');
});
it('should update value and listener should receive data properly', () => {
let receivedData:any;
function listener(data: any) {
receivedData = data;
}
subscribe(listener);
update('user')({ location: { address: { complement: 'apartment 3' } } });
const user = cloneState('user') as any;
expect(receivedData.data.name.firstName).to.equal('Joseph');
expect(receivedData.data.name.lastName).to.equal('Doe');
expect(receivedData.data.age).to.equal(18);
expect(receivedData.data.location.city).to.equal('NY');
expect(receivedData.data.location.address.street).to.equal('9 avenue');
expect(receivedData.data.location.address.streetNumber).to.equal('678');
expect(receivedData.data.location.address.complement).to.equal('apartment 3');
expect(user.name.firstName).to.equal('Joseph');
expect(user.name.lastName).to.equal('Doe');
expect(user.age).to.equal(18);
expect(user.location.city).to.equal('NY');
expect(user.location.address.street).to.equal('9 avenue');
expect(user.location.address.streetNumber).to.equal('678');
expect(user.location.address.complement).to.equal('apartment 3');
});
it('should update false javascript values and save it properly', () => {
const { errors, data } = update('user')({
age: 0,
name: {
lastName: ''
},
verified: false
});
const user = cloneState('user') as any;
expect(user.name.lastName).to.equal('');
expect(user.verified).to.equal(false);
expect(user.age).to.equal(0);
});
});
| 1.742188 | 2 |
litmus-portal/frontend/src/pages/UsageStatistics/styles.ts | suryakantpandey/litmus | 0 | 1984 | import { makeStyles, Theme } from '@material-ui/core/styles';
const useStyles = makeStyles((theme: Theme) => ({
Head: {
margin: theme.spacing(1, 0, 2.5),
},
description: {
fontWeight: 400,
fontSize: '1rem',
margin: theme.spacing(3, 0),
color: theme.palette.text.hint,
},
selectDate: {
display: 'flex',
flexDirection: 'row',
height: '2.5rem',
minWidth: '9rem',
border: '0.125rem solid',
marginRight: theme.spacing(3.75),
textTransform: 'none',
borderColor: theme.palette.primary.main,
},
displayDate: {
marginLeft: theme.spacing(1),
width: '100%',
},
dateRangeDiv: {
marginLeft: 'auto',
},
dateRangeIcon: {
width: '0.625rem',
height: '0.625rem',
},
}));
export default useStyles;
| 0.945313 | 1 |
dashboard/src/components/Hint/Hint.tsx | ralphsmith80/kubeapps | 1 | 1992 | import * as React from "react";
import { HelpCircle } from "react-feather";
import ReactTooltip from "react-tooltip";
import "./Hint.css";
interface IHintProps {
reactTooltipOpts?: any;
id?: string;
}
export class Hint extends React.Component<IHintProps> {
public render() {
// Generate a random ID if not given
const id =
this.props.id ||
Math.random()
.toString(36)
.substring(7);
return (
<React.Fragment>
<span data-tip={true} data-for={id}>
<HelpCircle className="icon" color="white" fill="#5F6369" />
</span>
<ReactTooltip
id={id}
className="extraClass"
effect="solid"
{...this.props.reactTooltipOpts}
>
{this.props.children}
</ReactTooltip>
</React.Fragment>
);
}
}
export default Hint;
| 1.335938 | 1 |
src/cpu-sockets/dto/update-cpu-socket.dto.ts | mdhi2000/hardware-store-back | 0 | 2000 | import { PartialType } from '@nestjs/mapped-types';
import { CreateCpuSocketDto } from './create-cpu-socket.dto';
export class UpdateCpuSocketDto extends PartialType(CreateCpuSocketDto) {}
| 0.621094 | 1 |
src/components/Icon/Icon.tsx | pedropbazzo/polaris-react | 0 | 2008 | import React from 'react';
import {classNames, variationName} from '../../utilities/css';
import {useI18n} from '../../utilities/i18n';
import {IconProps} from '../../types';
import styles from './Icon.scss';
const COLORS_WITH_BACKDROPS = [
'teal',
'tealDark',
'greenDark',
'redDark',
'yellowDark',
'ink',
'inkLighter',
];
// This is needed for the polaris
// styleguide to generate the props explorer
interface Props extends IconProps {}
export function Icon({source, color, backdrop, accessibilityLabel}: Props) {
const i18n = useI18n();
if (color && backdrop && COLORS_WITH_BACKDROPS.indexOf(color) < 0) {
// eslint-disable-next-line no-console
console.warn(
i18n.translate('Polaris.Icon.backdropWarning', {
color,
colorsWithBackDrops: COLORS_WITH_BACKDROPS.join(', '),
}),
);
}
const className = classNames(
styles.Icon,
color && styles[variationName('color', color)],
color && color !== 'white' && styles.isColored,
backdrop && styles.hasBackdrop,
);
let contentMarkup: React.ReactNode;
if (typeof source === 'function') {
const SourceComponent = source;
contentMarkup = (
<SourceComponent
className={styles.Svg}
focusable="false"
aria-hidden="true"
/>
);
} else if (source === 'placeholder') {
contentMarkup = <div className={styles.Placeholder} />;
} else {
contentMarkup = (
<img
className={styles.Img}
src={`data:image/svg+xml;utf8,${source}`}
alt=""
aria-hidden="true"
/>
);
}
return (
<span className={className} aria-label={accessibilityLabel}>
{contentMarkup}
</span>
);
}
| 1.554688 | 2 |
packages/gatsby/src/utils/page-mode.ts | 9Fork/gatsby | 7 | 2016 | import { store } from "../redux"
import {
IGatsbyPage,
IGatsbyState,
IMaterializePageMode,
PageMode,
} from "../redux/types"
import { reportOnce } from "./report-once"
import { ROUTES_DIRECTORY } from "../constants"
import { Runner } from "../bootstrap/create-graphql-runner"
import { getDataStore } from "../datastore"
type IPageConfigFn = (arg: { params: Record<string, unknown> }) => {
defer: boolean
}
const pageConfigMap = new Map<string, IPageConfigFn>()
/**
* In develop IGatsbyPage["mode"] can change at any time, so as a general rule we need to resolve it
* every time from page component and IGatsbyPage["defer"] value.
*
* IGatsbyPage["mode"] is only reliable in engines and in `onPostBuild` hook.
*/
export function getPageMode(page: IGatsbyPage, state?: IGatsbyState): PageMode {
const { components } = state ?? store.getState()
// assume SSG until components are actually extracted
const component = components.get(page.componentPath) ?? {
serverData: false,
config: false,
}
return resolvePageMode(page, component)
}
function resolvePageMode(
page: IGatsbyPage,
component: { serverData: boolean; config: boolean }
): PageMode {
let pageMode: PageMode | undefined = undefined
if (component.serverData) {
pageMode = `SSR`
} else if (component.config) {
const pageConfigFn = pageConfigMap.get(page.componentChunkName)
if (!pageConfigFn) {
// This is possible in warm builds when `component.config` was persisted but
// `preparePageTemplateConfigs` hasn't been executed yet
// TODO: if we move `mode` away from page and persist it in the state separately,
// we can just return the old `mode` that should be in sync with `component.config`
return `SSG`
}
const fsRouteParams = (
typeof page.context[`__params`] === `object`
? page.context[`__params`]
: {}
) as Record<string, unknown>
const pageConfig = pageConfigFn({ params: fsRouteParams })
if (typeof pageConfig.defer === `boolean`) {
pageMode = pageConfig.defer ? `DSG` : `SSG`
}
}
if (!pageMode) {
pageMode = page.defer ? `DSG` : `SSG`
}
if (
pageMode !== `SSG` &&
(page.path === `/404.html` || page.path === `/500.html`)
) {
reportOnce(
`Status page "${page.path}" ignores page mode ("${pageMode}") and force sets it to SSG (this page can't be lazily rendered).`
)
pageMode = `SSG`
}
return pageMode
}
/**
* Persist page.mode for SSR/DSG pages to ensure they work with `gatsby serve`
*
* TODO: ideally IGatsbyPage["mode"] should not exist at all and instead we need a different entity
* holding this information: an entity that is only created in the end of the build e.g. Route
* then materializePageMode transforms to createRoutes
*/
export async function materializePageMode(): Promise<void> {
const { pages, components } = store.getState()
let dispatchCount = 0
for (const page of pages.values()) {
const component = components.get(page.componentPath)
if (!component) {
throw new Error(`Could not find matching component for page ${page.path}`)
}
const pageMode = resolvePageMode(page, component)
// Do not materialize for SSG pages: saves some CPU time as `page.mode` === `SSG` by default when creating a page
// and our pages are re-generated on each build, not persisted
// (so no way to get DSG/SSR value from the previous build)
if (pageMode !== `SSG`) {
const action: IMaterializePageMode = {
type: `MATERIALIZE_PAGE_MODE`,
payload: { path: page.path, pageMode },
}
store.dispatch(action)
}
// Do not block task queue of the event loop for too long:
if (dispatchCount++ % 100 === 0) {
await new Promise(resolve => setImmediate(resolve))
}
}
await getDataStore().ready()
}
export async function preparePageTemplateConfigs(
graphql: Runner
): Promise<void> {
const { program } = store.getState()
const pageRendererPath = `${program.directory}/${ROUTES_DIRECTORY}render-page.js`
const pageRenderer = require(pageRendererPath)
global[`__gatsbyGraphql`] = graphql
await Promise.all(
Array.from(store.getState().components.values()).map(async component => {
if (component.config) {
const componentInstance = await pageRenderer.getPageChunk({
componentChunkName: component.componentChunkName,
})
const pageConfigFn = await componentInstance.config()
if (typeof pageConfigFn !== `function`) {
throw new Error(
`Unexpected result of config factory. Expected "function", got "${typeof pageConfigFn}".`
)
}
pageConfigMap.set(component.componentChunkName, pageConfigFn)
}
})
)
delete global[`__gatsbyGraphql`]
}
| 1.367188 | 1 |
packages/spinner/src/index.ts | Apptane/react-ui | 0 | 2024 | export { default as Spinner } from "./Spinner";
export * from "./Spinner.types";
| -0.028442 | 0 |
lib/process-services/task-list/components/task-audit.directive.spec.ts | nbarithel/alfresco-ng2-components | 0 | 2032 | /*!
* @license
* Copyright 2016 Alfresco Software, Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { Component } from '@angular/core';
import {
async,
ComponentFixture,
fakeAsync,
TestBed
} from '@angular/core/testing';
import { of } from 'rxjs';
import { TaskListService } from './../services/tasklist.service';
import { setupTestBed, CoreModule } from '@alfresco/adf-core';
import { TaskAuditDirective } from './task-audit.directive';
declare let jasmine: any;
describe('TaskAuditDirective', () => {
@Component({
selector: 'adf-basic-button',
template: `
<button id="auditButton"
adf-task-audit
[task-id]="currentTaskId"
[download]="download"
[fileName]="fileName"
[format]="format"
(clicked)="onAuditClick($event)">My button
</button>`
})
class BasicButtonComponent {
download: boolean = false;
fileName: string;
format: string;
constructor() {
}
onAuditClick(event: any) {
}
}
let fixture: ComponentFixture<BasicButtonComponent>;
let component: BasicButtonComponent;
let service: TaskListService;
function createFakePdfBlob(): Blob {
let pdfData = atob(
'<KEY>' +
'<KEY>KPDwKICAvVHlwZSAvUGFnZXMKICAv' +
'TWVkaWFCb3ggWyAwIDAgMjAwIDIwMCBdCiAgL0NvdW50IDEKICAvS2lkcyBbIDMgMCBSIF0K' +
'Pj4KZW5kb2JqCgozIDAgb2JqCjw8CiAgL1R5cGUgL1BhZ2UKICAvUGFyZW50IDIgMCBSCiAg' +
'L1Jlc291cmNlcyA8PAogICAgL0ZvbnQgPDwKICAgICAgL0YxIDQgMCBSIAogICAgPj4KICA+' +
'PgogIC9Db250ZW50cyA1IDAgUgo+PgplbmRvYmoKCjQgMCBvYmoKPDwKICAvVHlwZSAvRm9u' +
'dAogIC9TdWJ0eXBlIC9UeXBlMQogIC9CYXNlRm9udCAvVGltZXMtUm9tYW4KPj4KZW5kb2Jq' +
'Cgo1IDAgb2JqICAlIHBhZ2UgY29udGV<KEY>IC9MZW5ndGggNDQKPj4Kc3RyZWFtCkJU' +
'CjcwIDUwIFRECi9GMSAxMiBUZgooSGVsbG8sIHdvcmxkISkgVGoKRVQKZW5kc3RyZWFtCmVu' +
'ZG9iagoKeHJlZgowIDYKMDAwMDAwMDAwMCA2NTUzNSBmIAowMDAwMDAwMDEwIDAwMDAwIG4g' +
'CjAwMDAwMDAwNzkgMDAwMDAgbiAKMDAwMDAwMDE3MyAwMDAwMCBuIAowMDAwMDAwMzAxIDAw' +
'MDAwIG4gCjAwMDAwMDAzODAgMDAwMDAgbiAKdHJhaWxlcgo8PAogIC9TaXplIDYKICAvUm9v' +
'dCAxIDAgUgo+PgpzdGFydHhyZWYKNDkyCiUlRU9G');
return new Blob([pdfData], {type: 'application/pdf'});
}
setupTestBed({
imports: [CoreModule.forRoot()],
declarations: [BasicButtonComponent, TaskAuditDirective],
providers: [TaskListService]
});
beforeEach(async(() => {
fixture = TestBed.createComponent(BasicButtonComponent);
component = fixture.componentInstance;
service = TestBed.get(TaskListService);
jasmine.Ajax.install();
}));
afterEach(() => {
jasmine.Ajax.uninstall();
});
it('should fetch the pdf Blob when the format is pdf', fakeAsync(() => {
component.fileName = 'FakeAuditName';
component.format = 'pdf';
let blob = createFakePdfBlob();
spyOn(service, 'fetchTaskAuditPdfById').and.returnValue(of(blob));
spyOn(component, 'onAuditClick').and.callThrough();
fixture.detectChanges();
let button = fixture.nativeElement.querySelector('#auditButton');
fixture.whenStable().then(() => {
fixture.detectChanges();
expect(component.onAuditClick).toHaveBeenCalledWith({ format: 'pdf', value: blob, fileName: 'FakeAuditName' });
});
button.click();
}));
it('should fetch the json info when the format is json', fakeAsync(() => {
component.fileName = 'FakeAuditName';
component.format = 'json';
component.download = true;
const auditJson = { taskId: '77', taskName: '<NAME>', assignee: '<NAME>', formData: [], selectedOutcome: null, comments: [] };
spyOn(service, 'fetchTaskAuditJsonById').and.returnValue(of(auditJson));
spyOn(component, 'onAuditClick').and.callThrough();
fixture.detectChanges();
let button = fixture.nativeElement.querySelector('#auditButton');
fixture.whenStable().then(() => {
fixture.detectChanges();
expect(component.onAuditClick).toHaveBeenCalledWith({ format: 'json', value: auditJson, fileName: 'FakeAuditName' });
});
button.click();
}));
it('should fetch the pdf Blob as default when the format is UNKNOW', fakeAsync(() => {
component.fileName = 'FakeAuditName';
component.format = 'fakeFormat';
let blob = createFakePdfBlob();
spyOn(service, 'fetchTaskAuditPdfById').and.returnValue(of(blob));
spyOn(component, 'onAuditClick').and.callThrough();
fixture.detectChanges();
let button = fixture.nativeElement.querySelector('#auditButton');
fixture.whenStable().then(() => {
fixture.detectChanges();
expect(component.onAuditClick).toHaveBeenCalledWith({ format: 'pdf', value: blob, fileName: 'FakeAuditName' });
});
button.click();
}));
});
| 1.328125 | 1 |
src/core/exegesisRunner.ts | KrakenTyio/exegesis | 2 | 2040 | import * as http from 'http';
import { Readable } from 'stream';
import { Context as KoaContext } from 'koa';
import { invokeController } from '../controllers/invoke';
import stringToStream from '../utils/stringToStream';
import { ValidationError } from '../errors';
import bufferToStream from '../utils/bufferToStream';
import { isReadable } from '../utils/typeUtils';
import {
ApiInterface,
ExegesisRunner,
HttpResult,
ExegesisContext,
ResponseValidationCallback,
ResolvedOperation,
ExegesisOptions,
ExegesisResponse
} from '../types';
import ExegesisContextImpl from './ExegesisContextImpl';
import PluginsManager from './PluginsManager';
import {IValidationError} from "../types/validation";
import {handleErrorFunction} from "../types/options";
async function handleSecurity(operation: ResolvedOperation, context: ExegesisContext) {
const authenticated = await operation.authenticate(context);
context.security = authenticated;
if(authenticated) {
const matchedSchemes = Object.keys(authenticated);
if(matchedSchemes.length === 1) {
context.user = authenticated[matchedSchemes[0]].user;
}
}
}
function setDefaultContentType(res: ExegesisResponse) {
const body = res.body;
if(res.headers['content-type']) {
// Nothing to do!
} else if(body === undefined || body === null) {
// Do nothing
} else if(body instanceof Buffer) {
res.headers['content-type'] = 'text/plain';
} else if(typeof body === 'string') {
res.headers['content-type'] = 'text/plain';
} else if(isReadable(body)) {
res.headers['content-type'] = 'text/plain';
} else {
res.headers['content-type'] = 'application/json';
}
}
function resultToHttpResponse(
context: ExegesisContext,
result: any
) : HttpResult {
let output: Readable | undefined;
const headers = context.res.headers;
if(result) {
if(result instanceof Buffer) {
output = bufferToStream(result);
} else if(typeof result === 'string') {
output = stringToStream(result);
} else if(isReadable(result)) {
output = result;
} else {
if(!headers['content-type']) {
headers['content-type'] = 'application/json';
}
output = stringToStream(JSON.stringify(result), 'utf-8');
}
}
return {
status: context.res.statusCode,
headers,
body: output
};
}
function handleError(err: Error) {
if(err instanceof ValidationError) {
// TODO: Allow customization of validation error? Or even
// just throw the error instead of turning it into a message?
const jsonError = {
message: "Validation errors",
errors: err.errors.map((error :IValidationError) => {
return {
message: error.message,
location: error.location,
};
})
};
return {
status: err.status,
headers: {"content-type": "application/json"},
body: stringToStream(JSON.stringify(jsonError), 'utf-8')
};
} else if(Number.isInteger((err as any).status)) {
return {
status: (err as any).status,
headers: {"content-type": "application/json"},
body: stringToStream(JSON.stringify({message: err.message}), 'utf-8')
};
} else {
throw err;
}
}
/**
* Returns a `(req, res) => Promise<boolean>` function, which handles incoming
* HTTP requests. The returned function will return true if the request was
* handled, and false otherwise.
*
* @returns runner function.
*/
export default async function generateExegesisRunner<T>(
api: ApiInterface<T>,
options: {
autoHandleHttpErrors: boolean | handleErrorFunction,
plugins: PluginsManager,
onResponseValidationError: ResponseValidationCallback,
validateDefaultResponses: boolean,
originalOptions: ExegesisOptions
}
) : Promise<ExegesisRunner> {
const plugins = options.plugins;
return async function exegesisRunner(
req: http.IncomingMessage,
res: http.ServerResponse,
ctx: KoaContext,
) : Promise<HttpResult | undefined> {
const method = req.method || 'get';
const url = req.url || '/';
let result: HttpResult | undefined;
try {
const resolved = api.resolve(method, url, req.headers);
if(!resolved) {
return result;
}
const context = new ExegesisContextImpl<T>(req, res, resolved.api, options.originalOptions, ctx);
if(!context.isResponseFinished()) {
await plugins.postRouting(context);
}
if(resolved.operation) {
const {operation} = resolved;
context._setOperation(operation);
if(!operation.controllerModule || !operation.controller) {
throw new Error(`No controller found for ${method} ${url}`);
}
await handleSecurity(operation, context);
if(!context.isResponseFinished()) {
await plugins.postSecurity(context);
}
if(!context.isResponseFinished()) {
// Fill in context.params and context.requestBody.
await context.getParams();
await context.getRequestBody();
}
if(!context.isResponseFinished()) {
await invokeController(
operation.controllerModule,
operation.controller,
context
);
}
if(!context.origRes.headersSent) {
// Set _afterController to allow postController() plugins to
// modify the response.
context.res._afterController = true;
await plugins.postController(context);
}
if(!context.origRes.headersSent) {
// Before response validation, if there is a body and no
// content-type has been set, set a reasonable default.
setDefaultContentType(context.res);
if(options.onResponseValidationError) {
const responseValidationResult = resolved.operation.validateResponse(
context.res,
options.validateDefaultResponses
);
try {
if(responseValidationResult.errors && responseValidationResult.errors.length) {
options.onResponseValidationError({
errors: responseValidationResult.errors,
isDefault: responseValidationResult.isDefault,
context
});
}
} catch(err) {
err.status = err.status || 500;
throw err;
}
}
}
if(!context.origRes.headersSent) {
result = resultToHttpResponse(context, context.res.body);
}
}
return result;
} catch (err) {
if(options.autoHandleHttpErrors) {
if (options.autoHandleHttpErrors instanceof Function) {
return options.autoHandleHttpErrors(err);
}
return handleError(err);
} else {
throw err;
}
}
};
}
| 1.515625 | 2 |
src/components/CustomExtensions/link/link.ts | mfoitzik/quasar2-tiptap2 | 8 | 2048 | // eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-nocheck
import {
Mark,
markPasteRule,
mergeAttributes,
} from '@tiptap/core'
import { Plugin, PluginKey } from 'prosemirror-state'
export interface LinkOptions {
/**
* If enabled, links will be opened on click.
*/
openOnClick: boolean,
/**
* Adds a link to the current selection if the pasted content only contains an url.
*/
linkOnPaste: boolean,
/**
* A list of HTML attributes to be rendered.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
HTMLAttributes: Record<string, any>,
}
declare module '@tiptap/core' {
interface Commands<ReturnType> {
link: {
/**
* Set a link mark
*/
setLink: (attributes: { href: string, target?: string, rel?: string }) => ReturnType,
/**
* Toggle a link mark
*/
toggleLink: (attributes: { href: string, target?: string, rel?: string }) => ReturnType,
/**
* Unset a link mark
*/
unsetLink: () => ReturnType,
}
}
}
/**
* A regex that matches any string that contains a link
*/
export const pasteRegex = /https?:\/\/(?:www\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\.[a-zA-Z]{2,}\b(?:[-a-zA-Z0-9@:%._+~#=?!&/]*)(?:[-a-zA-Z0-9@:%._+~#=?!&/]*)/gi
/**
* A regex that matches an url
*/
export const pasteRegexExact = /^https?:\/\/(?:www\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\.[a-zA-Z]{2,}\b(?:[-a-zA-Z0-9@:%._+~#=?!&/]*)(?:[-a-zA-Z0-9@:%._+~#=?!&/]*)$/gi
export const Link = Mark.create<LinkOptions>({
name: 'link',
priority: 1000,
inclusive: false,
defaultOptions: {
openOnClick: true,
linkOnPaste: true,
HTMLAttributes: {
target: '_blank',
rel: undefined
},
},
addAttributes() {
return {
href: {
default: null,
},
target: {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
default: this.options.HTMLAttributes.target,
},
rel: {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
default: undefined,
},
}
},
parseHTML() {
return [
{ tag: 'a[href]' },
]
},
renderHTML({ HTMLAttributes }) {
return ['a', mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0]
},
addCommands() {
return {
setLink: attributes => ({ commands }) => {
return commands.setMark('link', attributes)
},
toggleLink: attributes => ({ commands }) => {
return commands.toggleMark('link', attributes, { extendEmptyMarkRange: true })
},
unsetLink: () => ({ commands }) => {
return commands.unsetMark('link', { extendEmptyMarkRange: true })
},
}
},
addPasteRules() {
return [
markPasteRule(pasteRegex, this.type, match => ({ href: match[0] })),
]
},
addProseMirrorPlugins() {
const plugins = []
if (this.options.openOnClick) {
plugins.push(
new Plugin({
key: new PluginKey('handleClickLink'),
props: {
handleClick: (view, pos, event) => {
const attrs = this.editor.getAttributes('link')
const link = (event.target as HTMLElement)?.closest('a')
if (link && attrs.href) {
window.open(attrs.href, attrs.target)
return true
}
return false
},
},
}),
)
}
if (this.options.linkOnPaste) {
plugins.push(
new Plugin({
key: new PluginKey('handlePasteLink'),
props: {
handlePaste: (view, event, slice) => {
const { state } = view
const { selection } = state
const { empty } = selection
if (empty) {
return false
}
let textContent = ''
slice.content.forEach(node => {
textContent += node.textContent
})
if (!textContent || !textContent.match(pasteRegexExact)) {
return false
}
this.editor.commands.setMark(this.type, {
href: textContent,
})
return true
},
},
}),
)
}
return plugins
},
})
| 1.445313 | 1 |
packages/@essence/essence-constructor-classes/src/StaticPreference/containers/StaticPreferenceContainer.tsx | honyrikS/core-frontend | 2 | 2056 | import * as React from "react";
import {Paper, Grid, Typography, Slider, Switch, Button, TextField} from "@material-ui/core";
import {IClassProps} from "@essence-community/constructor-share/types";
import {getPreference, savePreference} from "@essence-community/constructor-share/utils";
import {useTranslation} from "@essence-community/constructor-share";
import {useStyles} from "./StaticPreferenceContainer.styles";
export const StaticPreferenceContainer: React.FC<IClassProps> = () => {
const classes = useStyles();
const [trans] = useTranslation();
const [form, setForm] = React.useState(getPreference);
const renderPreference = (title: string, setting: React.ReactNode) => (
<Grid item xs>
<Grid container>
<Grid item xs={3}>
{title}
</Grid>
<Grid item xs>
{setting}
</Grid>
</Grid>
</Grid>
);
const handleSave = () => {
savePreference(form);
window.location.reload();
};
return (
<Paper className={classes.root}>
<Grid container direction="column" spacing={2}>
<Grid item>
<Typography variant="h3" component="h3" align="center">
{trans("static:9c97fa4879f144a7b571c4905fa020cc")}
</Typography>
</Grid>
{renderPreference(
trans("static:d39cbeb8128e4f68b201b25291889dd2"),
<Slider
value={form.delayTooltipShow}
min={100}
max={6000}
step={100}
onChange={(event: React.ChangeEvent, value: number) =>
setForm((prevForm) => ({...prevForm, delayTooltipShow: value}))
}
data-qtip={form.delayTooltipShow}
/>,
)}
{renderPreference(
trans("static:a43c94932e3a48c9867ac7b39bb22e60"),
<Slider
value={form.offsetTooltip}
min={0}
max={50}
step={1}
onChange={(event: React.ChangeEvent, value: number) =>
setForm((prevForm) => ({...prevForm, offsetTooltip: value}))
}
data-qtip={form.offsetTooltip}
/>,
)}
{renderPreference(
trans("static:a376942ff8af4ec58eeb18ea5a05e772"),
<Slider
value={form.debounceTooltipTime}
min={8}
max={400}
step={2}
onChange={(event: React.ChangeEvent, value: number) =>
setForm((prevForm) => ({...prevForm, debounceTooltipTime: value}))
}
data-qtip={form.debounceTooltipTime}
/>,
)}
{renderPreference(
trans("static:9a381df0ef4948ebaacb05852324d036"),
<Switch
checked={form.wysiwygCombineFields}
onChange={(event: React.ChangeEvent, value: boolean) =>
setForm((prevForm) => ({...prevForm, wysiwygCombineFields: value}))
}
data-qtip={form.wysiwygCombineFields}
/>,
)}
{renderPreference(
trans("static:c038518f0652435ba9914848f8693454"),
<Switch
checked={form.redirectDebugWindow}
onChange={(event: React.ChangeEvent, value: boolean) =>
setForm((prevForm) => ({...prevForm, redirectDebugWindow: value}))
}
data-qtip={form.redirectDebugWindow}
/>,
)}
{renderPreference(
trans("static:0852f8c548c741d39521833cd739a9f4"),
<Switch
checked={form.experimentalUI}
onChange={(event: React.ChangeEvent, value: boolean) =>
setForm((prevForm) => ({...prevForm, experimentalUI: value}))
}
data-qtip={form.experimentalUI}
/>,
)}
<TextField
label={trans("static:ad56476c04ff4d6091d5e87f5d823a9b")}
value={form.modules}
name="modules"
onChange={(event: React.ChangeEvent<HTMLInputElement>) =>
setForm((prevForm) => ({...prevForm, modules: event.currentTarget.value}))
}
/>
<Grid item>
<Grid container justify="center">
<Grid item>
<Button variant="contained" onClick={handleSave}>
{trans("static:8a930c6b5dd440429c0f0e867ce98316")}
</Button>
</Grid>
</Grid>
</Grid>
</Grid>
</Paper>
);
};
| 1.65625 | 2 |
ui/ninezone/src/ui-ninezone/widget-panels/Panel.tsx | Bernard-Cloutier/imodeljs | 0 | 2064 | /*---------------------------------------------------------------------------------------------
* Copyright (c) Bentley Systems, Incorporated. All rights reserved.
* See LICENSE.md in the project root for license terms and full copyright notice.
*--------------------------------------------------------------------------------------------*/
/** @packageDocumentation
* @module WidgetPanels
*/
import "./Panel.scss";
import classnames from "classnames";
import * as React from "react";
import { DraggedPanelSideContext } from "../base/DragManager";
import { NineZoneDispatchContext } from "../base/NineZone";
import { isHorizontalPanelState, PanelState } from "../base/NineZoneState";
import { PanelWidget } from "../widget/PanelWidget";
import { WidgetTarget } from "../widget/WidgetTarget";
import { WidgetPanelGrip } from "./Grip";
import { PanelTarget } from "./PanelTarget";
import { RectangleProps } from "@bentley/ui-core";
import { assert } from "../base/assert";
/** @internal */
export type TopPanelSide = "top";
/** @internal */
export type BottomPanelSide = "bottom";
/** @internal */
export type LeftPanelSide = "left";
/** @internal */
export type RightPanelSide = "right";
/** @internal */
export type HorizontalPanelSide = TopPanelSide | BottomPanelSide;
/** @internal */
export type VerticalPanelSide = LeftPanelSide | RightPanelSide;
/** @internal future */
export type PanelSide = VerticalPanelSide | HorizontalPanelSide;
/** Properties of [[WidgetPanel]] component.
* @internal
*/
export interface WidgetPanelProps {
panel: PanelState;
spanBottom?: boolean;
spanTop?: boolean;
}
/** Widget panel component is a side panel with multiple widgets.
* @internal
*/
export const WidgetPanel = React.memo<WidgetPanelProps>(function WidgetPanel(props) { // eslint-disable-line @typescript-eslint/naming-convention, no-shadow
return (
<PanelStateContext.Provider value={props.panel}>
<PanelSideContext.Provider value={props.panel.side}>
<PanelPinnedContext.Provider value={props.panel.pinned}>
<PanelSpanContext.Provider value={isHorizontalPanelState(props.panel) ? props.panel.span : undefined}>
<WidgetPanelComponent
panel={props.panel}
spanTop={props.spanTop}
spanBottom={props.spanBottom}
/>
</PanelSpanContext.Provider>
</PanelPinnedContext.Provider>
</PanelSideContext.Provider>
</PanelStateContext.Provider>
);
});
/** @internal */
export interface WidgetPanelComponentProps {
panel: PanelState;
spanBottom?: boolean;
spanTop?: boolean;
}
/** @internal */
export const WidgetPanelComponent = React.memo<WidgetPanelComponentProps>(function WidgetPanelComponent(props) { // eslint-disable-line @typescript-eslint/naming-convention, no-shadow
const draggedPanelSide = React.useContext(DraggedPanelSideContext);
const dispatch = React.useContext(NineZoneDispatchContext);
const captured = draggedPanelSide === props.panel.side;
const { panel } = props;
const horizontalPanel = isHorizontalPanelState(panel) ? panel : undefined;
const [transition, setTransition] = React.useState<"prepared" | "transitioning">();
const [size, setSize] = React.useState<number | undefined>(panel.size);
const firstLayoutEffect = React.useRef(true);
// const lastTransitionTo = React.useRef<number | undefined>(0);
const style = React.useMemo(() => {
if (size === undefined)
return undefined;
const s: React.CSSProperties = {};
if (isHorizontalPanelSide(panel.side)) {
s.height = `${size}px`;
} else {
s.width = `${size}px`;
}
return s;
}, [size, panel.side]);
const contentStyle = React.useMemo(() => {
if (size === undefined)
return undefined;
const s: React.CSSProperties = {};
if (isHorizontalPanelSide(panel.side)) {
s.height = `${panel.size}px`;
} else {
s.width = `${panel.size}px`;
}
return s;
}, [panel.size, panel.side, size]);
const ref = React.useRef<HTMLDivElement>(null);
React.useLayoutEffect(() => {
if (panel.size !== undefined)
return;
const bounds = ref.current?.getBoundingClientRect();
const newSize = isHorizontalPanelSide(panel.side) ? bounds?.height : bounds?.width;
newSize && dispatch({
type: "PANEL_INITIALIZE",
side: panel.side,
size: newSize,
});
});
React.useLayoutEffect(() => {
const newSize = panel.collapsed ? 0 : panel.size;
setTransition(undefined);
setSize(newSize);
}, [panel.collapsed, panel.size])
React.useLayoutEffect(() => {
if (firstLayoutEffect.current)
return;
setTransition("prepared");
}, [panel.collapsed, panel.side]);
React.useLayoutEffect(() => {
const transitionTo = panel.collapsed ? 0 : panel.size;
if (transition === "prepared") {
setTransition("transitioning");
setSize(transitionTo);
return;
}
}, [transition, panel.side, panel.size, panel.collapsed]);
React.useEffect(() => {
firstLayoutEffect.current = false;
}, []);
const getBounds = React.useCallback(() => {
assert(ref.current);
return ref.current.getBoundingClientRect();
}, []);
const widgetPanel = React.useMemo<WidgetPanelContextArgs>(() => {
return {
getBounds,
}
}, [getBounds]);
if (panel.widgets.length === 0)
return (
<PanelTarget />
);
const showTargets = panel.widgets.length < panel.maxWidgetCount;
const className = classnames(
"nz-widgetPanels-panel",
`nz-${panel.side}`,
panel.pinned && "nz-pinned",
horizontalPanel && "nz-horizontal",
panel.collapsed && "nz-collapsed",
captured && "nz-captured",
horizontalPanel?.span && "nz-span",
!horizontalPanel && props.spanTop && "nz-span-top",
!horizontalPanel && props.spanBottom && "nz-span-bottom",
!!transition && "nz-transition",
);
return (
<WidgetPanelContext.Provider value={widgetPanel}>
<div
className={className}
ref={ref}
style={style}
onTransitionEnd={() => {
setTransition(undefined);
}}
>
<div
className="nz-content"
style={contentStyle}
>
{panel.widgets.map((widgetId, index, array) => {
const last = index === array.length - 1;
return (
<React.Fragment key={widgetId}>
{index === 0 && showTargets && <WidgetTarget
position="first"
widgetIndex={0}
/>}
<PanelWidget
widgetId={widgetId}
/>
{showTargets && <WidgetTarget
position={last ? "last" : undefined}
widgetIndex={index + 1}
/>}
</React.Fragment>
);
})}
</div>
{panel.resizable &&
<div className="nz-grip-container">
<WidgetPanelGrip className="nz-grip" />
</div>
}
</div>
</WidgetPanelContext.Provider>
);
});
/** @internal */
export const PanelSideContext = React.createContext<PanelSide | undefined>(undefined); // eslint-disable-line @typescript-eslint/naming-convention
PanelSideContext.displayName = "nz:PanelSideContext";
/** @internal */
export const PanelPinnedContext = React.createContext<boolean>(false); // eslint-disable-line @typescript-eslint/naming-convention
PanelPinnedContext.displayName = "nz:PanelPinnedContext";
/** @internal */
export const PanelSpanContext = React.createContext<boolean | undefined>(undefined); // eslint-disable-line @typescript-eslint/naming-convention
PanelSpanContext.displayName = "nz:PanelStateContext";
/** @internal */
export const PanelStateContext = React.createContext<PanelState | undefined>(undefined); // eslint-disable-line @typescript-eslint/naming-convention
PanelStateContext.displayName = "nz:PanelStateContext";
/** @internal */
export interface WidgetPanelContextArgs {
getBounds(): RectangleProps;
}
/** @internal */
export const WidgetPanelContext = React.createContext<WidgetPanelContextArgs | undefined>(undefined);
WidgetPanelContext.displayName = "nz:WidgetPanelContext";
/** @internal */
export const isHorizontalPanelSide = (side: PanelSide): side is HorizontalPanelSide => {
return side === "top" || side === "bottom";
};
/** @internal */
export const panelSides: [LeftPanelSide, RightPanelSide, TopPanelSide, BottomPanelSide] = [
"left",
"right",
"top",
"bottom",
];
| 1.21875 | 1 |
src/app/public/modules/text-editor/url-modal/text-editor-url-target.ts | blackbaud-conorwright/skyux-text-editor | 0 | 2072 | /**
* @internal
*/
export enum UrlTarget {
None = 0,
NewWindow = 1
}
| 0.173828 | 0 |
config/webpack.config.ts | climbjh/climb-app | 0 | 2080 | import * as path from 'path';
import * as webpack from 'webpack';
import * as webpackDevServer from 'webpack-dev-server';
import * as fs from 'fs';
import lessToJs from 'less-vars-to-js';
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
/** Setup Paths */
const root = path.resolve(__dirname, '..');
const src = path.resolve(root, 'app');
const PATHS = {
root,
src,
index: path.resolve(src, 'index.tsx'),
assets: path.resolve(src, 'assets'),
styles: path.resolve(src, 'styles'),
dist: path.resolve(root, 'dist'),
};
// for ant style overrides
const themeVariables = lessToJs(fs.readFileSync(path.join(PATHS.styles, './ant-theme-vars.less'), 'utf8'));
module.exports = (env: any = {}) => {
const PORT = parseInt(env.port) || 8080;
const resourceName = env.resource || 'app';
const isBuild = !!env.build; // build vs dev-server
const isProd = !!env.prod; // for Prod ENV optimizations
console.log(`Resource Name: ${resourceName} | isBuild: ${isBuild} | isProd: ${isProd}`);
const mode = isProd ? 'production' : 'development';
// add things here to put in the global namespace
const GLOBAL_DEFINES: any = {
'process.env': {
NODE_ENV: JSON.stringify(mode),
},
};
const devServer: webpackDevServer.Configuration = {
historyApiFallback: true,
overlay: true,
port: PORT,
headers: { // enable CORS
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, PATCH, OPTIONS',
'Access-Control-Allow-Headers': 'X-Requested-With, content-type, Authorization',
},
disableHostCheck: true,
};
const config: webpack.Configuration = {
mode,
cache: true,
devtool: isBuild ? 'source-map' : 'source-map',
devServer,
context: PATHS.root,
entry: {
app: [
'babel-polyfill',
PATHS.index,
],
},
output: {
path: PATHS.dist,
filename: '[name].js',
publicPath: (
isBuild ? `/resource/${resourceName}/dist/`
: `https://localhost:${PORT}/` // setup for HMR when hosted with salesforce
),
},
optimization: {
splitChunks: {
cacheGroups: {
commons: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
chunks: 'all',
},
},
},
},
resolve: {
alias: { '@src': PATHS.src },
extensions: ['.ts', '.tsx', '.js', '.jsx', '.json'],
modules: ['src', 'node_modules'],
},
// externals: {
// },
/*** LOADERS ***/
module: {
rules: [
// typescript
{
// Include ts, tsx, js, and jsx files.
test: /\.(ts|js)x?$/,
exclude: /node_modules/,
loader: 'babel-loader',
options: require('./babelrc.json'),
},
// css
{
test: /\.css$/,
include: PATHS.styles,
use: [
{ loader: 'style-loader' },
{ loader: 'css-loader' },
],
},
// antd
{
test: /\.less$/,
use: [
{ loader: 'style-loader' },
{ loader: 'css-loader' },
{
loader: 'less-loader',
options: {
modifyVars: themeVariables,
javascriptEnabled: true,
},
},
],
},
// json
{
test: /\.json$/,
include: [PATHS.src],
use: { loader: 'json-loader' },
},
// images
{
test: /\.(jpg|jpeg|png|gif|svg)$/,
include: [PATHS.assets],
use: {
loader: 'file-loader',
options: {
name: '[path][hash].[ext]',
},
},
},
// fonts
{
test: /\.(woff|woff2|ttf|eot)$/,
include: [
PATHS.assets,
],
use: {
loader: 'file-loader',
options: {
name: 'fonts/[name].[hash].[ext]',
},
},
},
],
},
/*** PLUGIN ***/
plugins: [
...[
new webpack.DefinePlugin(GLOBAL_DEFINES),
],
...(!isBuild ? [
new webpack.NamedModulesPlugin(),
] : []),
...(isProd ? [
// put production optimization plugins here
] : []),
...(env.analyze ? [
new BundleAnalyzerPlugin(),
] : []),
],
};
return config;
}; | 1.289063 | 1 |
src/components/home/HomeNavbar/index.ts | WVAviator/readme-generator | 43 | 2088 | export * from './HomeNavbar'
| -0.322266 | 0 |
pouchdb-mapreduce/pouchdb-mapreduce.d.ts | sguest/DefinitelyTyped | 1 | 2096 | // Type definitions for pouchdb-mapreduce v5.4.4
// Project: https://pouchdb.com/
// Definitions by: <NAME> <https://github.com/AGBrown>, <NAME> <https://github.com/geppy>, <NAME> <https://github.com/fredgalvao>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../pouchdb-core/pouchdb-core.d.ts" />
declare namespace PouchDB {
export interface Database<Content extends Core.Encodable> {
/**
* Cleans up any stale map/reduce indexes.
*
* As design docs are deleted or modified, their associated index
* files(in CouchDB) or companion databases (in local PouchDBs) continue
* to take up space on disk. viewCleanup() removes these unnecessary
* index files.
*/
viewCleanup(callback: PouchDB.Core.Callback<any,void>): void;
viewCleanup(): Promise<void>;
}
}
declare module 'pouchdb-adapter-mapreduce' {
const plugin: PouchDB.Plugin;
export = plugin;
}
| 0.910156 | 1 |
src/shared/components/HTMLHead.tsx | ebi-uniprot/uniprot-website | 0 | 2104 | import { ReactNode } from 'react';
import Helmet from 'react-helmet';
type InputValue = string | number | false | null | undefined;
const isTruthy = (value: InputValue): value is number | string =>
Boolean(value);
type Props = {
title?: InputValue | InputValue[];
children?: ReactNode;
};
const HTMLHead = ({ title, children }: Props) => {
let renderedTitle: string | undefined;
if (title) {
if (Array.isArray(title)) {
renderedTitle = title.filter(isTruthy).join(' | ');
} else {
renderedTitle = `${title}`;
}
}
return (
<Helmet>
{renderedTitle ? <title>{renderedTitle}</title> : null}
{children}
</Helmet>
);
};
export default HTMLHead;
| 1.515625 | 2 |
web/src/apps/Links/index.tsx | manyuanrong/enok-blog | 5 | 2112 | import * as React from "react";
import AppWindow from "../../components/AppWindow";
import "./style.less";
import data from "./data";
export default class LinksApp extends AppWindow {
public state = {
x: 0,
y: 0,
width: 600,
height: 400,
title: "友情链接"
};
public renderContent(): JSX.Element | JSX.Element[] {
return <div className="app-links">
<ul className="links">
{data.filter(item => item.logo).map((link, index) => <li key={index} className="image">
<a href={link.url} target="_blank">
<img src={link.logo} alt={link.title} style={{backgroundColor: link.bgColor}}/>
<span>{link.title}</span>
</a>
</li>)}
</ul>
<ul className="links">
{data.filter(item => !item.logo).map((link, index) => <li key={index} className="text">
<a href={link.url} target="_blank">
<span>{link.title}</span>
</a>
</li>)}
</ul>
</div>;
}
} | 1.242188 | 1 |
packages/hooks/__tests__/use-form-item.spec.ts | oscaralbareda/element-plus | 1 | 2120 | import { h, provide } from 'vue'
import { NOOP } from '@vue/shared'
import { mount } from '@vue/test-utils'
import { ElButton } from '@element-plus/components'
import {
elFormKey,
elFormItemKey,
buttonGroupContextKey,
} from '@element-plus/tokens'
import type {
ElFormContext,
ElFormItemContext,
ButtonGroupContext,
} from '@element-plus/tokens'
const AXIOM = 'Rem is the best girl'
const Component = {
render() {
return h(ElButton, this.$attrs, {
default: () => [AXIOM],
})
},
}
const mountComponent = (setup = NOOP, options = {}) => {
return mount(
{
...Component,
setup,
},
options
)
}
const getButtonVm = (wrapper: ReturnType<typeof mountComponent>) => {
return wrapper.findComponent(ElButton).vm as any as {
buttonSize: string
buttonDisabled: boolean
}
}
describe('use-form-item', () => {
it('should return local value', () => {
const wrapper = mountComponent()
expect(getButtonVm(wrapper).buttonSize).toBe('')
})
it('should return props.size instead of injected.size', () => {
const propSize = 'mini'
const wrapper = mountComponent(
() => {
provide(elFormItemKey, {
size: 'large',
} as ElFormItemContext)
},
{
props: {
size: propSize,
},
}
)
expect(getButtonVm(wrapper).buttonSize).toBe(propSize)
})
it('should return fallback.size instead inject.size', () => {
const fallbackSize = 'mini'
const wrapper = mountComponent(() => {
provide(buttonGroupContextKey, {
size: fallbackSize,
} as ButtonGroupContext)
provide(elFormItemKey, {
size: 'large',
} as ElFormItemContext)
})
expect(getButtonVm(wrapper).buttonSize).toBe(fallbackSize)
})
it('should return formItem.size instead form.size', () => {
const itemSize = 'mini'
const wrapper = mountComponent(() => {
provide(elFormItemKey, {
size: itemSize,
} as ElFormItemContext)
provide(elFormKey, {
size: 'large',
} as ElFormContext)
})
expect(getButtonVm(wrapper).buttonSize).toBe(itemSize)
})
// update this once useGlobalConfig is fixed
// it('should return global config when none is provided', () => {
// const size = 'mini'
// const wrapper = mountComponent(undefined, {
// global: {
// globalProperties: {
// $ELEMENT: {
// size,
// },
// },
// },
// })
// console.log(wrapper.vm.$data)
// expect(getButtonVm(wrapper).buttonSize).toBe(size)
// })
// Add test case for config provider
})
| 1.492188 | 1 |
src/drivers/cms-client.ts | ki-bo/vscode-cmake-tools | 1 | 2128 | import * as child_proc from 'child_process';
import * as net from 'net';
import * as path from 'path';
import * as cache from '@cmt/cache';
import {CMakeGenerator} from '@cmt/kit';
import {createLogger} from '@cmt/logging';
import {fs} from '@cmt/pr';
import * as proc from '@cmt/proc';
import rollbar from '@cmt/rollbar';
import * as util from '@cmt/util';
import * as nls from 'vscode-nls';
nls.config({ messageFormat: nls.MessageFormat.bundle, bundleFormat: nls.BundleFormat.standalone })();
const localize: nls.LocalizeFunc = nls.loadMessageBundle();
const log = createLogger('cms-client');
const ENABLE_CMSERVER_PROTO_DEBUG = false;
const MESSAGE_WRAPPER_RE = /\[== "CMake Server" ==\[([^]*?)\]== "CMake Server" ==\]\s*([^]*)/;
export class StartupError extends global.Error {
constructor(public readonly retc: number) { super(localize('error.starting.cmake-server', 'Error starting up cmake-server')); }
}
export interface ProtocolVersion {
isExperimental: boolean;
major: number;
minor: number;
}
/**
* Summary of the message interfaces:
*
* There are interfaces for every type of message that may be sent to/from cmake
* server. All messages derive from `MessageBase`, which has a single property
* `type` to represent what type of message it is.
*
* Messages which are part of a request/response pair have an additional
* attribute `cookie`. This is described by the `CookiedMessage` interface. All
* messages that are part of a request/response pair derive from this interface.
*
* Each request/response message type is divided into the part describing its
* content separate from protocol attributes, and the part describing its
* protocol attributes.
*
* All reply messages derive from `ReplyMessage`, which defines the one
* attribute `inReplyTo`.
*
* Request content interfaces are named with `<type>Request`, and encapsulate
* the interesting content of the message. The message type corresponding to
* that content is called `<type>Request`. The response content is
* encoded in `<type>Content`, and the message is encoded with `<type>Reply`,
* which inherits from `ReplyMessage` and `<type>Content`.
*/
/**
* The base of all messages. Each message has a `type` property.
*/
export interface MessageBase { type: string; }
/**
* Cookied messages represent some on-going conversation.
*/
export interface CookiedMessage extends MessageBase { cookie: string; }
/**
* Reply messages are solicited by some previous request, which comes with a
* cookie to identify the initiating request.
*/
export interface ReplyMessage extends CookiedMessage { inReplyTo: string; }
/**
* Progress messages are sent regarding some long-running request process before
* the reply is ready.
*/
export interface ProgressMessage extends MessageBase {
type: 'progress';
progressMessage: string;
progressMinimum: number;
progressCurrent: number;
progressMaximum: number;
}
export interface SignalMessage extends MessageBase {
type: 'signal';
name: string;
}
export interface DirtyMessage extends SignalMessage { name: 'dirty'; }
export interface FileChangeMessage {
name: 'fileChange';
path: string;
properties: string[];
}
type SomeSignalMessage = (DirtyMessage|FileChangeMessage);
/**
* The `MessageMessage` is an un-solicited message from cmake with a string to
* display to the user.
*/
export interface MessageMessage extends MessageBase {
type: 'message';
message: string;
title: string;
inReplyTo: string;
}
/**
* The hello message is sent immediately from cmake-server upon startup.
*/
export interface HelloMessage extends MessageBase {
type: 'hello';
supportedProtocolVersions: ProtocolVersion[];
}
/**
* Handshake is sent as the first thing from the client to set up the server
* session. It should contain the chosen protocol version and some setup
* information for the project.
*/
export interface HandshakeParams {
sourceDirectory?: string;
buildDirectory: string;
generator?: string;
extraGenerator?: string;
platform?: string;
toolset?: string;
protocolVersion: {major: number; minor: number;};
}
export interface HandshakeRequest extends CookiedMessage, HandshakeParams { type: 'handshake'; }
export interface HandshakeContent {}
export interface HandshakeReply extends ReplyMessage, HandshakeContent { inReplyTo: 'handshake'; }
/**
* GlobalSettings request gets some static information about the project setup.
*/
export interface GlobalSettingsParams {}
export interface GlobalSettingsRequest extends CookiedMessage, GlobalSettingsParams { type: 'globalSettings'; }
export interface GlobalSettingsContent {
buildDirectory: string;
capabilities: {
generators: {extraGenerators: string[]; name: string; platformSupport: boolean; toolsetSupport: boolean;}[];
serverMode: boolean;
version: {isDirty: boolean; major: number; minor: number; patch: number; string: string; suffix: string;};
};
checkSystemVars: boolean;
extraGenerator: string;
generator: string;
debugOutput: boolean;
sourceDirectory: string;
trace: boolean;
traceExpand: boolean;
warnUninitialized: boolean;
warnUnused: boolean;
warnUnusedCli: boolean;
}
export interface GlobalSettingsReply extends ReplyMessage, GlobalSettingsContent { inReplyTo: 'globalSettings'; }
/**
* setGlobalSettings changes information about the project setup.
*/
export interface SetGlobalSettingsParams {
checkSystemVars?: boolean;
debugOutput?: boolean;
trace?: boolean;
traceExpand?: boolean;
warnUninitialized?: boolean;
warnUnused?: boolean;
warnUnusedCli?: boolean;
}
export interface SetGlobalSettingsRequest extends CookiedMessage, SetGlobalSettingsParams { type: 'setGlobalSettings'; }
export interface SetGlobalSettingsContent {}
export interface SetGlobalSettingsReply extends ReplyMessage, SetGlobalSettingsContent {
inReplyTo: 'setGlobalSettings';
}
/**
* configure will actually do the configuration for the project. Note that
* this should be followed shortly with a 'compute' request.
*/
export interface ConfigureParams { cacheArguments: string[]; }
export interface ConfigureRequest extends CookiedMessage, ConfigureParams { type: 'configure'; }
export interface ConfigureContent {}
export interface ConfigureReply extends ReplyMessage, ConfigureContent { inReplyTo: 'configure'; }
/**
* Compute actually generates the build files from the configure step.
*/
export interface ComputeParams {}
export interface ComputeRequest extends CookiedMessage, ComputeParams { type: 'compute'; }
export interface ComputeContent {}
export interface ComputeReply extends ReplyMessage, ComputeContent { inReplyTo: 'compute'; }
/**
* codemodel gets information about the project, such as targets, files,
* sources,
* configurations, compile options, etc.
*/
export interface CodeModelParams {}
export interface CodeModelRequest extends CookiedMessage, CodeModelParams { type: 'codemodel'; }
export interface CodeModelFileGroup {
language?: string;
compileFlags?: string;
includePath?: {path: string; isSystem?: boolean;}[];
defines?: string[];
sources: string[];
isGenerated: boolean;
}
export type TargetTypeString = ('STATIC_LIBRARY' | 'MODULE_LIBRARY' | 'SHARED_LIBRARY' | 'OBJECT_LIBRARY' | 'EXECUTABLE' | 'UTILITY' | 'INTERFACE_LIBRARY');
export interface CodeModelTarget {
name: string;
type: TargetTypeString;
fullName?: string;
sourceDirectory?: string;
buildDirectory?: string;
artifacts?: string[];
linkerLanguage?: string;
linkLibraries?: string[];
linkFlags?: string[];
linkLanguageFlags?: string[];
frameworkPath?: string;
linkPath?: string;
sysroot?: string;
fileGroups?: CodeModelFileGroup[];
}
export interface CodeModelProject {
name: string;
sourceDirectory: string;
buildDirectory: string;
targets: CodeModelTarget[];
hasInstallRule?: boolean;
}
export interface CodeModelConfiguration {
name: string;
projects: CodeModelProject[];
}
export interface CodeModelContent { configurations: CodeModelConfiguration[]; }
export interface CodeModelReply extends ReplyMessage, CodeModelContent { inReplyTo: 'codemodel'; }
/**
* cmakeInputs will respond with a list of file paths that can alter a
* projects configuration output. Editting these will cause the configuration to
* go out of date.
*/
export interface CMakeInputsParams {}
export interface CMakeInputsRequest extends CookiedMessage, CMakeInputsParams { type: 'cmakeInputs'; }
export interface CMakeInputsContent {
buildFiles: {isCMake: boolean; isTemporary: boolean; sources: string[];}[];
cmakeRootDirectory: string;
sourceDirectory: string;
}
export interface CMakeInputsReply extends ReplyMessage, CMakeInputsContent { inReplyTo: 'cmakeInputs'; }
/**
* The cache request will respond with the contents of the CMake cache.
*/
export interface CacheParams {}
export interface CacheRequest extends CookiedMessage, CacheParams { type: 'cache'; }
export interface CacheContent { cache: CMakeCacheEntry[]; }
export interface CMakeCacheEntry {
key: string;
properties: {ADVANCED: '0'|'1'; HELPSTRING: string};
type: string;
value: string;
}
export interface CacheReply extends ReplyMessage, CacheContent { inReplyTo: 'cache'; }
// Union type that represents any of the request types.
export type SomeRequestMessage
= (HandshakeRequest|GlobalSettingsRequest|SetGlobalSettingsRequest|ConfigureRequest|ComputeRequest|CodeModelRequest|CacheRequest);
// Union type that represents a response type
export type SomeReplyMessage
= (HandshakeReply|GlobalSettingsReply|SetGlobalSettingsReply|ConfigureReply|ComputeReply|CodeModelReply|CacheReply);
export type SomeMessage
= (SomeReplyMessage|SomeRequestMessage|ProgressMessage|ErrorMessage|MessageMessage|HelloMessage|SignalMessage);
/**
* The initial parameters when setting up the CMake client. The client init
* routines will automatically perform the server handshake and set the
* the appropriate settings. This is also where callbacks for progress and
* message handlers are set.
*/
export interface ClientInit {
cmakePath: string;
onMessage: (m: MessageMessage) => Promise<void>;
onOtherOutput(m: string): Promise<void>;
onProgress: (m: ProgressMessage) => Promise<void>;
onDirty: () => Promise<void>;
environment: NodeJS.ProcessEnv;
sourceDir: string;
binaryDir: string;
tmpdir: string;
generator: CMakeGenerator;
}
interface ClientInitPrivate extends ClientInit {
onHello: (m: HelloMessage) => Promise<void>;
onCrash: (retc: number, signal: string) => Promise<void>;
onPipeError(e: Error): Promise<void>;
}
/**
* Error message represent something going wrong.
*/
export interface ErrorMessage extends CookiedMessage {
type: 'error';
errorMessage: string;
inReplyTo: string;
}
export class ServerError extends Error implements ErrorMessage {
type: 'error' = 'error';
constructor(e: ErrorMessage,
public errorMessage = e.errorMessage,
public cookie = e.cookie,
public inReplyTo = e.inReplyTo) {
super(e.errorMessage);
}
toString(): string { return `[cmake-server] ${this.errorMessage}`; }
}
export class BadHomeDirectoryError extends Error {
constructor(readonly cached: string, readonly expecting: string, readonly badCachePath: string) { super(); }
}
interface MessageResolutionCallbacks {
resolve: (a: SomeReplyMessage) => void;
reject: (b: ServerError) => void;
}
export class CMakeServerClient {
private _accInput: string = '';
private readonly _promisesResolvers: Map<string, MessageResolutionCallbacks> = new Map;
private readonly _params: ClientInitPrivate;
// TODO: Refactor init so these init-assertions are not necessary
private _endPromise!: Promise<void>;
private _pipe!: net.Socket;
private readonly _pipeFilePath: string;
private _onMoreData(data: Uint8Array) {
const str = data.toString();
this._accInput += str;
while (1) {
const input = this._accInput;
const mat = MESSAGE_WRAPPER_RE.exec(input);
if (!mat) {
break;
}
if (mat.length !== 3) {
debugger;
throw new global.Error(localize('protocol.error.cmake', 'Protocol error talking to CMake! Got this input: {0}', input));
}
this._accInput = mat[2];
if (ENABLE_CMSERVER_PROTO_DEBUG) {
log.debug(localize('received.message.from.make-server', 'Received message from cmake-server: {0}', mat[1]));
}
const message: SomeMessage = JSON.parse(mat[1]);
this._onMessage(message);
}
}
private _takePromiseForCookie(cookie: string): MessageResolutionCallbacks|undefined {
const item = this._promisesResolvers.get(cookie);
if (!item) {
throw new global.Error(localize('invalid.cookie', 'Invalid cookie: {0}', cookie));
}
this._promisesResolvers.delete(cookie);
return item;
}
private _onMessage(some: SomeMessage): void {
if ('cookie' in some) {
const cookied = some as CookiedMessage;
switch (some.type) {
case 'reply': {
const reply = cookied as SomeReplyMessage;
const pr = this._takePromiseForCookie(cookied.cookie);
if (pr) {
pr.resolve(reply);
} else {
log.error(localize('cookie.not.known.message', 'CMake server cookie "{0}" does not correspond to a known message', cookied.cookie));
}
return;
}
case 'error': {
const err = new ServerError(cookied as ErrorMessage);
const pr = this._takePromiseForCookie(cookied.cookie);
if (pr) {
pr.reject(err);
} else {
log.error(localize('cookie.not.known.message', 'CMake server cookie "{0}" does not correspond to a known message', cookied.cookie));
}
return;
}
case 'progress': {
const prog = cookied as any as ProgressMessage;
this._params.onProgress(prog).catch(e => { log.error(localize('unhandled.error.in', 'Unhandled error in {0}', 'onProgress'), e); });
return;
}
}
}
switch (some.type) {
case 'hello': {
const unlink_pr = fs.exists(this._pipeFilePath).then(async exists => {
if (exists && process.platform !== 'win32') {
await fs.unlink(this._pipeFilePath);
}
});
rollbar.takePromise('Unlink pipe', {pipe: this._pipeFilePath}, unlink_pr);
this._params.onHello(some as HelloMessage).catch(e => { log.error(localize('unhandled.error.in', 'Unhandled error in {0}', 'onHello'), e); });
return;
}
case 'message': {
this._params.onMessage(some as MessageMessage).catch(e => { log.error(localize('unhandled.error.in', 'Unhandled error in {0}', 'onMessage'), e); });
return;
}
case 'signal': {
const sig = some as SomeSignalMessage;
switch (sig.name) {
case 'dirty': {
this._params.onDirty().catch(e => { log.error(localize('unhandled.error.in', 'Unhandled error in {0}', 'onDirty'), e); });
return;
}
case 'fileChange': {
return;
}
}
}
}
debugger;
log.warning(localize('cant.yet.handle.message', 'Can\'t yet handle the {0} messages', some.type));
}
private _sendRequest(type: 'handshake', params: HandshakeParams): Promise<HandshakeContent>;
private _sendRequest(type: 'globalSettings', params?: GlobalSettingsParams): Promise<GlobalSettingsContent>;
private _sendRequest(type: 'setGlobalSettings', params: SetGlobalSettingsParams): Promise<SetGlobalSettingsContent>;
private _sendRequest(type: 'configure', params: ConfigureParams): Promise<ConfigureContent>;
private _sendRequest(type: 'compute', params?: ComputeParams): Promise<ComputeContent>;
private _sendRequest(type: 'codemodel', params?: CodeModelParams): Promise<CodeModelContent>;
private _sendRequest(type: 'cmakeInputs', params?: CMakeInputsParams): Promise<CMakeInputsContent>;
private _sendRequest(type: 'cache', params?: CacheParams): Promise<CacheContent>;
private _sendRequest(type: string, params: any = {}): Promise<any> {
const cookiedMessage = {type, ...params};
const cookie = cookiedMessage.cookie = Math.random().toString();
const promise = new Promise((resolve, reject) => { this._promisesResolvers.set(cookie, {resolve, reject}); });
const jsonMessage = JSON.stringify(cookiedMessage);
if (ENABLE_CMSERVER_PROTO_DEBUG) {
log.debug(localize('sending.message.to.cmake-server', 'Sending message to cmake-server: {0}', jsonMessage));
}
this._pipe.write('\n[== "CMake Server" ==[\n');
this._pipe.write(jsonMessage);
this._pipe.write('\n]== "CMake Server" ==]\n');
return promise;
}
/**
* CMake server requests:
*/
setGlobalSettings(params: SetGlobalSettingsParams): Promise<SetGlobalSettingsContent> {
return this._sendRequest('setGlobalSettings', params);
}
handshake(params: HandshakeParams): Promise<HandshakeContent> {
return this._sendRequest('handshake', params);
}
getCMakeCacheContent(): Promise<CacheContent> {
return this._sendRequest('cache');
}
getGlobalSettings(): Promise<GlobalSettingsContent> {
return this._sendRequest('globalSettings');
}
configure(params: ConfigureParams): Promise<ConfigureContent> {
return this._sendRequest('configure', params);
}
compute(params?: ComputeParams): Promise<ComputeParams> {
return this._sendRequest('compute', params);
}
codemodel(params?: CodeModelParams): Promise<CodeModelContent> {
return this._sendRequest('codemodel', params);
}
cmakeInputs(params?: CMakeInputsParams): Promise<CMakeInputsContent> {
return this._sendRequest('cmakeInputs', params);
}
protected _shutdown = false;
public async shutdown() {
this._shutdown = true;
this._pipe.end();
await this._endPromise;
}
private constructor(params: ClientInitPrivate) {
this._params = params;
let pipe_file = path.join(params.tmpdir, '.cmserver-pipe');
if (process.platform === 'win32') {
pipe_file = '\\\\?\\pipe\\' + pipe_file;
} else {
pipe_file = `/tmp/cmake-server-${Math.random()}`;
}
this._pipeFilePath = pipe_file;
const final_env = util.mergeEnvironment(process.env as proc.EnvironmentVariables,
params.environment as proc.EnvironmentVariables);
const child
= child_proc.spawn(params.cmakePath, ['-E', 'server', '--experimental', `--pipe=${pipe_file}`], {
env: final_env, cwd: params.binaryDir
});
log.debug(localize('started.new.cmake.server.instance', 'Started new CMake Server instance with PID {0}', child.pid));
child.stdout.on('data', data => this._params.onOtherOutput(data.toLocaleString()));
child.stderr.on('data', data => this._params.onOtherOutput(data.toLocaleString()));
setTimeout(() => {
const end_promise = new Promise<void>((resolve, reject) => {
const pipe = this._pipe = net.createConnection(pipe_file);
pipe.on('data', this._onMoreData.bind(this));
pipe.on('error', e => {
pipe.end();
if (!this._shutdown) {
debugger;
rollbar.takePromise(localize('pipe.error.from.cmake-server', 'Pipe error from cmake-server'),
{pipe: pipe_file},
params.onPipeError(e));
reject(e);
} else {
resolve();
}
});
pipe.on('end', () => {
pipe.end();
resolve();
});
});
const exit_promise = new Promise<void>(resolve => { child.on('exit', () => { resolve(); }); });
this._endPromise = Promise.all([end_promise, exit_promise]).then(() => {});
child.on('close', (retc: number, signal: string) => {
if (retc !== 0) {
log.error(localize('connection.terminated.unexpectedly', 'The connection to cmake-server was terminated unexpectedly'));
log.error(localize('cmake-server.exited.with.status', 'cmake-server exited with status {0} ({1})', retc, signal));
params.onCrash(retc, signal).catch(e => { log.error(localize('unhandled.error.in', 'Unhandled error in {0}', 'onCrash'), e); });
}
});
}, 1000);
}
public static async start(params: ClientInit): Promise<CMakeServerClient> {
let resolved = false;
// Ensure the binary directory exists
await fs.mkdir_p(params.binaryDir);
return new Promise<CMakeServerClient>((resolve, reject) => {
const client = new CMakeServerClient({
tmpdir: params.tmpdir,
sourceDir: params.sourceDir,
binaryDir: params.binaryDir,
onMessage: params.onMessage,
onOtherOutput: other => params.onOtherOutput(other),
cmakePath: params.cmakePath,
environment: params.environment,
onProgress: params.onProgress,
onDirty: params.onDirty,
generator: params.generator,
onCrash: async retc => {
if (!resolved) {
reject(new StartupError(retc));
}
},
onPipeError: async e => {
if (!resolved) {
reject(e);
}
},
onHello: async (msg: HelloMessage) => {
// We've gotten the hello message. We need to commense handshake
try {
const hsparams: HandshakeParams
= {buildDirectory: params.binaryDir, protocolVersion: msg.supportedProtocolVersions[0]};
const cache_path = path.join(params.binaryDir, 'CMakeCache.txt');
const have_cache = await fs.exists(cache_path);
if (have_cache) {
// Work-around: CMake Server checks that CMAKE_HOME_DIRECTORY
// in the cmake cache is the same as what we provide when we
// set up the connection. Because CMake may normalize the
// path differently than we would, we should make sure that
// we pass the value that is specified in the cache exactly
// to avoid causing CMake server to spuriously fail.
// While trying to fix issue above CMake broke ability to run
// with an empty sourceDir, so workaround because necessary for
// different CMake versions.
// See
// https://gitlab.kitware.com/cmake/cmake/issues/16948
// https://gitlab.kitware.com/cmake/cmake/issues/16736
const tmpcache = await cache.CMakeCache.fromPath(cache_path);
const src_dir = tmpcache.get('CMAKE_HOME_DIRECTORY');
if (src_dir) {
const cachedDir = src_dir.as<string>();
if (!util.platformPathEquivalent(cachedDir, params.sourceDir)) {
// If src_dir is different, clean configure is required as CMake won't accept it anyways.
throw new BadHomeDirectoryError(cachedDir, params.sourceDir, cache_path);
}
hsparams.sourceDirectory = cachedDir;
}
} else {
// Do clean configure, all parameters are required.
const generator = params.generator;
hsparams.sourceDirectory = params.sourceDir;
hsparams.generator = generator.name;
hsparams.platform = generator.platform;
hsparams.toolset = generator.toolset;
const configureMessage: string = localize('configuring.using.generator',
'Configuring using the "{0}" CMake generator', hsparams.generator);
const extraMessage: string = hsparams.platform || hsparams.toolset ?
localize('with.platform.and.toolset', ' with platform "{0}" and toolset {1}', hsparams.platform, JSON.stringify(hsparams.toolset || {})) :
"";
log.info(configureMessage + extraMessage);
}
await client.handshake(hsparams);
resolved = true;
resolve(client);
} catch (e) {
await client.shutdown();
resolved = true;
reject(e);
}
},
});
});
}
}
| 1.28125 | 1 |
src/main/electron-app/features/disable-hardware-acceleration.injectable.ts | kallisti5/lens | 152 | 2136 | /**
* Copyright (c) OpenLens Authors. All rights reserved.
* Licensed under MIT License. See LICENSE in root directory for more information.
*/
import { getInjectable } from "@ogre-tools/injectable";
import electronAppInjectable from "../electron-app.injectable";
const disableHardwareAccelerationInjectable = getInjectable({
id: "disable-hardware-acceleration",
instantiate: (di) => {
const app = di.inject(electronAppInjectable);
return () => {
app.disableHardwareAcceleration();
};
},
});
export default disableHardwareAccelerationInjectable;
| 0.902344 | 1 |
typeScriptPractices/07-interfaces/CricektCoach.ts | itsraghz/TechNotes | 0 | 2144 | import { Coach } from "./Coach";
export class CricketCoach implements Coach {
getDailyWorkout(): string {
//throw new Error('Method not implemented.');
return "Practice your spin bowling techniques";
}
} | 0.859375 | 1 |
test-suites/test-aave/stable-rate-economy.spec.ts | WaterLoan/waterloan_v2_contract | 0 | 2152 | // import {
// LendingPoolInstance,
// LendingPoolCoreInstance,
// MintableERC20Instance,
// ATokenInstance,
// } from "../utils/typechain-types/truffle-contracts"
// import {
// iATokenBase,
// iAssetsWithoutETH,
// ITestEnvWithoutInstances,
// RateMode,
// } from "../utils/types"
// import {
// APPROVAL_AMOUNT_LENDING_POOL_CORE,
// ETHEREUM_ADDRESS,
// } from "../utils/constants"
// import { testEnvProviderWithoutInstances} from "../utils/truffle/dlp-tests-env"
// import {convertToCurrencyDecimals} from "../utils/misc-utils"
// const expectRevert = require("@openzeppelin/test-helpers").expectRevert
// contract("LendingPool - stable rate economy tests", async ([deployer, ...users]) => {
// let _testEnvProvider: ITestEnvWithoutInstances
// let _lendingPoolInstance: LendingPoolInstance
// let _lendingPoolCoreInstance: LendingPoolCoreInstance
// let _aTokenInstances: iATokenBase<ATokenInstance>
// let _tokenInstances: iAssetsWithoutETH<MintableERC20Instance>
// let _daiAddress: string
// let _depositorAddress: string
// let _borrowerAddress: string
// let _web3: Web3
// before("Initializing LendingPool test variables", async () => {
// console.time('setup-test');
// _testEnvProvider = await testEnvProviderWithoutInstances(
// artifacts,
// [deployer, ...users]
// )
// const {
// getWeb3,
// getAllAssetsInstances,
// getFirstBorrowerAddressOnTests,
// getFirstDepositorAddressOnTests,
// getLendingPoolInstance,
// getLendingPoolCoreInstance,
// getATokenInstances
// } = _testEnvProvider
// const instances = await Promise.all([
// getLendingPoolInstance(),
// getLendingPoolCoreInstance(),
// getATokenInstances(),
// getAllAssetsInstances()
// ])
// _lendingPoolInstance = instances[0]
// _lendingPoolCoreInstance = instances[1]
// _aTokenInstances = instances[2]
// _tokenInstances = instances[3]
// _daiAddress = _tokenInstances.DAI.address
// _depositorAddress = await getFirstDepositorAddressOnTests()
// _borrowerAddress = await getFirstBorrowerAddressOnTests()
// _web3 = await getWeb3()
// console.timeEnd('setup-test');
// })
// it("BORROW - Test user cannot borrow using the same currency as collateral", async () => {
// const {aDAI: aDaiInstance} = _aTokenInstances
// const {DAI: daiInstance} = _tokenInstances
// //mints DAI to depositor
// await daiInstance.mint(await convertToCurrencyDecimals(daiInstance.address, "1000"), {
// from: _depositorAddress,
// })
// //mints DAI to borrower
// await daiInstance.mint(await convertToCurrencyDecimals(daiInstance.address, "1000"), {
// from: _borrowerAddress,
// })
// //approve protocol to access depositor wallet
// await daiInstance.approve(_lendingPoolCoreInstance.address, APPROVAL_AMOUNT_LENDING_POOL_CORE, {
// from: _depositorAddress,
// })
// //approve protocol to access borrower wallet
// await daiInstance.approve(_lendingPoolCoreInstance.address, APPROVAL_AMOUNT_LENDING_POOL_CORE, {
// from: _borrowerAddress,
// })
// const amountDAItoDeposit = await convertToCurrencyDecimals(_daiAddress, "1000")
// //user 1 deposits 1000 DAI
// const txResult = await _lendingPoolInstance.deposit(_daiAddress, amountDAItoDeposit, "0", {
// from: _depositorAddress,
// })
// //user 2 deposits 1000 DAI, tries to borrow. Needs to be reverted as you can't borrow at a stable rate with the same collateral as the currency.
// const amountDAIToDepositBorrower = await convertToCurrencyDecimals(_daiAddress, "1000")
// await _lendingPoolInstance.deposit(_daiAddress, amountDAIToDepositBorrower, "0", {
// from: _borrowerAddress,
// })
// const data: any = await _lendingPoolInstance.getReserveData(_daiAddress)
// //user 2 tries to borrow
// const amountDAIToBorrow = await convertToCurrencyDecimals(_daiAddress, "250")
// //user 2 tries to borrow
// await expectRevert(
// _lendingPoolInstance.borrow(_daiAddress, amountDAIToBorrow, RateMode.Stable, "0", {
// from: _borrowerAddress,
// }),
// "User cannot borrow the selected amount with a stable rate",
// )
// })
// it("BORROW - Test user cannot borrow more than 25% of the liquidity available", async () => {
// const {aDAI: aDaiInstance} = _aTokenInstances
// const {DAI: daiInstance} = _tokenInstances
// //redeem the DAI previously deposited
// const amountADAIToRedeem = await convertToCurrencyDecimals(aDaiInstance.address, "1000")
// await aDaiInstance.redeem(amountADAIToRedeem, {
// from: _borrowerAddress,
// })
// //user 2 deposits 5 ETH tries to borrow. needs to be reverted as you can't borrow more than 25% of the available reserve (250 DAI)
// const amountETHToDeposit = await convertToCurrencyDecimals(ETHEREUM_ADDRESS, "5")
// await _lendingPoolInstance.deposit(ETHEREUM_ADDRESS, amountETHToDeposit, "0", {
// from: _borrowerAddress,
// value: amountETHToDeposit,
// })
// const data: any = await _lendingPoolInstance.getReserveData(_daiAddress)
// const amountDAIToBorrow = await convertToCurrencyDecimals(_daiAddress, "500")
// //user 2 tries to borrow
// await expectRevert(
// _lendingPoolInstance.borrow(_daiAddress, amountDAIToBorrow, RateMode.Stable, "0", {
// from: _borrowerAddress,
// }),
// "User is trying to borrow too much liquidity at a stable rate",
// )
// })
// it("BORROW - Test user can still borrow a currency that he previously deposited as a collateral but he transferred/redeemed", async () => {
// const {aDAI: aDaiInstance} = _aTokenInstances
// const {DAI: daiInstance} = _tokenInstances
// const user = users[2]
// //user deposits 1000 DAI
// await daiInstance.mint(await convertToCurrencyDecimals(daiInstance.address, "1000"), {
// from: user,
// })
// await daiInstance.approve(_lendingPoolCoreInstance.address, APPROVAL_AMOUNT_LENDING_POOL_CORE, {
// from: user,
// })
// const amountDAIToDeposit = await convertToCurrencyDecimals(daiInstance.address, "1000")
// await _lendingPoolInstance.deposit(daiInstance.address, amountDAIToDeposit, "0", {
// from: user,
// })
// //user deposits 5 ETH as collateral
// const amountETHToDeposit = await convertToCurrencyDecimals(ETHEREUM_ADDRESS, "5")
// await _lendingPoolInstance.deposit(ETHEREUM_ADDRESS, amountETHToDeposit, "0", {
// from: user,
// value: amountETHToDeposit,
// })
// //user transfers to another address all the overlying aDAI
// const aDAIBalance = await aDaiInstance.balanceOf(user)
// await aDaiInstance.transfer(users[3], aDAIBalance, {
// from: user,
// })
// //check the underlying balance is 0
// const userData: any = await _lendingPoolInstance.getUserReserveData(daiInstance.address, user)
// expect(userData.currentATokenBalance.toString()).to.be.equal("0")
// //user tries to borrow the DAI at a stable rate using the ETH as collateral
// const amountDAIToBorrow = await convertToCurrencyDecimals(_daiAddress, "100")
// //user tries to borrow. No revert expected
// await _lendingPoolInstance.borrow(_daiAddress, amountDAIToBorrow, RateMode.Stable, "0", {
// from: user,
// })
// })
// })
| 1.46875 | 1 |
x-pack/legacy/plugins/siem/public/components/page/add_to_kql/index.test.tsx | akoloth/kibana | 2 | 2160 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
import { mount, shallow } from 'enzyme';
import toJson from 'enzyme-to-json';
import * as React from 'react';
import { escapeQueryValue } from '../../../lib/keury';
import {
apolloClientObservable,
mockGlobalState,
TestProviders,
mockIndexPattern,
} from '../../../mock';
import { createStore, hostsModel, networkModel, State } from '../../../store';
import { AddToKql } from '.';
describe('AddToKql Component', () => {
const state: State = mockGlobalState;
let store = createStore(state, apolloClientObservable);
beforeEach(() => {
store = createStore(state, apolloClientObservable);
});
test('Rendering', async () => {
const wrapper = shallow(
<TestProviders store={store}>
<AddToKql
indexPattern={mockIndexPattern}
expression={`host.name: ${escapeQueryValue('siem-kibana')}`}
componentFilterType="hosts"
type={hostsModel.HostsType.page}
>
<>{'siem-kibana'}</>
</AddToKql>
</TestProviders>
);
expect(toJson(wrapper)).toMatchSnapshot();
});
test('Rendering tooltip', async () => {
const wrapper = shallow(
<TestProviders store={store}>
<AddToKql
indexPattern={mockIndexPattern}
expression={`host.name: ${escapeQueryValue('siem-kibana')}`}
componentFilterType="hosts"
type={hostsModel.HostsType.page}
>
<>{'siem-kibana'}</>
</AddToKql>
</TestProviders>
);
wrapper.simulate('mouseenter');
wrapper.update();
expect(wrapper.find('[data-test-subj="hover-actions-container"] svg').first()).toBeTruthy();
});
test('Functionality with hosts state', async () => {
const wrapper = mount(
<TestProviders store={store}>
<AddToKql
indexPattern={mockIndexPattern}
expression={`host.name: ${escapeQueryValue('siem-kibana')}`}
componentFilterType="hosts"
type={hostsModel.HostsType.page}
>
<>{'siem-kibana'}</>
</AddToKql>
</TestProviders>
);
wrapper
.simulate('mouseenter')
.find('[data-test-subj="hover-actions-container"] .euiToolTipAnchor svg')
.first()
.simulate('click');
wrapper.update();
expect(store.getState().hosts.page).toEqual({
queries: {
authentications: {
activePage: 0,
limit: 10,
},
hosts: {
activePage: 0,
limit: 10,
direction: 'desc',
sortField: 'lastSeen',
},
events: {
activePage: 0,
limit: 10,
},
uncommonProcesses: {
activePage: 0,
limit: 10,
},
},
filterQuery: {
kuery: {
kind: 'kuery',
expression: 'host.name: siem-kibana',
},
serializedQuery:
'{"bool":{"should":[{"match":{"host.name":"siem-kibana"}}],"minimum_should_match":1}}',
},
filterQueryDraft: {
kind: 'kuery',
expression: 'host.name: siem-kibana',
},
});
});
test('Functionality with network state', async () => {
const wrapper = mount(
<TestProviders store={store}>
<AddToKql
indexPattern={mockIndexPattern}
expression={`host.name: ${escapeQueryValue('siem-kibana')}`}
componentFilterType="network"
type={networkModel.NetworkType.page}
>
<>{'siem-kibana'}</>
</AddToKql>
</TestProviders>
);
wrapper
.simulate('mouseenter')
.find('[data-test-subj="hover-actions-container"] .euiToolTipAnchor svg')
.first()
.simulate('click');
wrapper.update();
expect(store.getState().network.page).toEqual({
queries: {
topNFlow: {
activePage: 0,
limit: 10,
flowDirection: 'uniDirectional',
flowTarget: 'source',
topNFlowSort: {
field: 'bytes',
direction: 'desc',
},
},
dns: {
activePage: 0,
limit: 10,
dnsSortField: {
field: 'queryCount',
direction: 'desc',
},
isPtrIncluded: false,
},
},
filterQuery: {
kuery: {
kind: 'kuery',
expression: 'host.name: siem-kibana',
},
serializedQuery:
'{"bool":{"should":[{"match":{"host.name":"siem-kibana"}}],"minimum_should_match":1}}',
},
filterQueryDraft: {
kind: 'kuery',
expression: 'host.name: siem-kibana',
},
});
});
});
| 1.398438 | 1 |
src/main/webapp/app/layouts/profiles/profile-info.model.ts | Oussama-Goumghar/e-banking-registery | 699 | 2168 | export interface InfoResponse {
git?: any;
build?: any;
activeProfiles?: string[];
'cloud-config-server-configuration-sources'?: Array<any>;
'cloud-config-label'?: string;
}
export class ProfileInfo {
constructor(
public activeProfiles?: string[],
public inProduction?: boolean,
public openAPIEnabled?: boolean,
public cloudConfigServerConfigurationSources?: Array<any>,
public cloudConfigLabel?: string
) {}
}
| 0.839844 | 1 |
src/public_api.ts | lambk/ngAlertbar | 0 | 2176 | /*
* Public API Surface of ng-alertbar
*/
export * from './lib/interface';
export * from './lib/ng-alertbar.component';
export * from './lib/ng-alertbar.module';
export * from './lib/ng-alertbar.service';
| 0.412109 | 0 |
src/components/Comp_05_0498.tsx | FredKSchott/scale-test | 4 | 2184 | // Comp_05_0498
import React from 'react';
import { incModCount } from '../modCount';
const Comp_05_0498: React.FC = () => {
React.useEffect(() => {
incModCount();
}, []);
return <div>
I'm component Comp_05_0498
<div>
</div>
</div>;
};
export default Comp_05_0498;
| 0.851563 | 1 |
Nodejs/Product/Nodejs/Templates/Files/TypeScriptTapeUnitTest/UnitTest.ts | stefb965/nodejstools | 1 | 2192 | import test = require("tape");
test("Test A", function (t) {
t.plan(1);
t.ok(true, "This shouldn't fail");
});
test("Test B", function (t) {
t.plan(2);
t.ok(true, "This shouldn't fail");
t.equal(1, 2, "This should fail");
});
| 1.054688 | 1 |
@types/Gjs/RygelCore-2.6.d.ts | gjsify/ts-for-gjs | 0 | 2200 | /**
* RygelCore-2.6
*/
import type * as Gjs from './Gjs';
import type * as GLib from './GLib-2.0';
import type * as Gee from './Gee-0.8';
import type * as Gio from './Gio-2.0';
import type * as GObject from './GObject-2.0';
import type * as GUPnP from './GUPnP-1.2';
import type * as libxml2 from './libxml2-2.0';
import type * as Soup from './Soup-2.4';
import type * as GSSDP from './GSSDP-1.2';
export enum LogLevel {
INVALID,
ERROR,
CRITICAL,
WARNING,
INFO,
DEFAULT,
DEBUG,
}
export enum ConfigurationEntry {
INTERFACE,
PORT,
TRANSCODING,
ALLOW_UPLOAD,
ALLOW_DELETION,
LOG_LEVELS,
PLUGIN_PATH,
VIDEO_UPLOAD_FOLDER,
MUSIC_UPLOAD_FOLDER,
PICTURE_UPLOAD_FOLDER,
}
export enum SectionEntry {
TITLE,
ENABLED,
}
export enum ConfigurationError {
NO_VALUE_SET,
VALUE_OUT_OF_RANGE,
}
export enum CmdlineConfigError {
VERSION_ONLY,
}
export enum PluginCapabilities {
NONE,
IMAGE_UPLOAD,
VIDEO_UPLOAD,
AUDIO_UPLOAD,
UPLOAD,
TRACK_CHANGES,
CREATE_CONTAINERS,
DIAGNOSTICS,
ENERGY_MANAGEMENT,
}
export function get_pretty_host_name(): string
export interface DBusInterface_ConstructProps extends GObject.Object_ConstructProps {
}
export class DBusInterface {
/* Fields of GObject-2.0.GObject.Object */
g_type_instance: GObject.TypeInstance
/* Methods of RygelCore-2.6.RygelCore.DBusInterface */
shutdown(): void
/* Methods of GObject-2.0.GObject.Object */
bind_property(source_property: string, target: GObject.Object, target_property: string, flags: GObject.BindingFlags): GObject.Binding
bind_property_full(source_property: string, target: GObject.Object, target_property: string, flags: GObject.BindingFlags, transform_to: Function, transform_from: Function): GObject.Binding
force_floating(): void
freeze_notify(): void
get_data(key: string): object | null
get_property(property_name: string, value: any): void
get_qdata(quark: GLib.Quark): object | null
getv(names: string[], values: any[]): void
is_floating(): boolean
notify(property_name: string): void
notify_by_pspec(pspec: GObject.ParamSpec): void
ref(): GObject.Object
ref_sink(): GObject.Object
run_dispose(): void
set_data(key: string, data?: object | null): void
set_property(property_name: string, value: any): void
steal_data(key: string): object | null
steal_qdata(quark: GLib.Quark): object | null
thaw_notify(): void
unref(): void
watch_closure(closure: Function): void
/* Virtual methods of RygelCore-2.6.RygelCore.DBusInterface */
vfunc_shutdown(): void
/* Virtual methods of GObject-2.0.GObject.Object */
vfunc_constructed(): void
vfunc_dispatch_properties_changed(n_pspecs: number, pspecs: GObject.ParamSpec): void
vfunc_dispose(): void
vfunc_finalize(): void
vfunc_get_property(property_id: number, value: any, pspec: GObject.ParamSpec): void
vfunc_notify(pspec: GObject.ParamSpec): void
vfunc_set_property(property_id: number, value: any, pspec: GObject.ParamSpec): void
/* Signals of GObject-2.0.GObject.Object */
connect(sigName: "notify", callback: (($obj: DBusInterface, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify", callback: (($obj: DBusInterface, pspec: GObject.ParamSpec) => void)): number
emit(sigName: "notify", pspec: GObject.ParamSpec): void
connect(sigName: string, callback: any): number
connect_after(sigName: string, callback: any): number
emit(sigName: string, ...args: any[]): void
disconnect(id: number): void
static name: string
constructor (config?: DBusInterface_ConstructProps)
_init (config?: DBusInterface_ConstructProps): void
static $gtype: GObject.Type
}
export interface DBusAclProvider_ConstructProps extends GObject.Object_ConstructProps {
}
export class DBusAclProvider {
/* Fields of GObject-2.0.GObject.Object */
g_type_instance: GObject.TypeInstance
/* Methods of RygelCore-2.6.RygelCore.DBusAclProvider */
is_allowed(device: GLib.HashTable, service: GLib.HashTable, path: string, address: string, agent?: string | null, _callback_?: Gio.AsyncReadyCallback | null): void
is_allowed_finish(_res_: Gio.AsyncResult): boolean
/* Methods of GObject-2.0.GObject.Object */
bind_property(source_property: string, target: GObject.Object, target_property: string, flags: GObject.BindingFlags): GObject.Binding
bind_property_full(source_property: string, target: GObject.Object, target_property: string, flags: GObject.BindingFlags, transform_to: Function, transform_from: Function): GObject.Binding
force_floating(): void
freeze_notify(): void
get_data(key: string): object | null
get_property(property_name: string, value: any): void
get_qdata(quark: GLib.Quark): object | null
getv(names: string[], values: any[]): void
is_floating(): boolean
notify(property_name: string): void
notify_by_pspec(pspec: GObject.ParamSpec): void
ref(): GObject.Object
ref_sink(): GObject.Object
run_dispose(): void
set_data(key: string, data?: object | null): void
set_property(property_name: string, value: any): void
steal_data(key: string): object | null
steal_qdata(quark: GLib.Quark): object | null
thaw_notify(): void
unref(): void
watch_closure(closure: Function): void
/* Virtual methods of RygelCore-2.6.RygelCore.DBusAclProvider */
vfunc_is_allowed(device: GLib.HashTable, service: GLib.HashTable, path: string, address: string, agent?: string | null, _callback_?: Gio.AsyncReadyCallback | null): void
vfunc_is_allowed_finish(_res_: Gio.AsyncResult): boolean
/* Virtual methods of GObject-2.0.GObject.Object */
vfunc_constructed(): void
vfunc_dispatch_properties_changed(n_pspecs: number, pspecs: GObject.ParamSpec): void
vfunc_dispose(): void
vfunc_finalize(): void
vfunc_get_property(property_id: number, value: any, pspec: GObject.ParamSpec): void
vfunc_notify(pspec: GObject.ParamSpec): void
vfunc_set_property(property_id: number, value: any, pspec: GObject.ParamSpec): void
/* Signals of GObject-2.0.GObject.Object */
connect(sigName: "notify", callback: (($obj: DBusAclProvider, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify", callback: (($obj: DBusAclProvider, pspec: GObject.ParamSpec) => void)): number
emit(sigName: "notify", pspec: GObject.ParamSpec): void
connect(sigName: string, callback: any): number
connect_after(sigName: string, callback: any): number
emit(sigName: string, ...args: any[]): void
disconnect(id: number): void
static name: string
constructor (config?: DBusAclProvider_ConstructProps)
_init (config?: DBusAclProvider_ConstructProps): void
static $gtype: GObject.Type
}
export interface Configuration_ConstructProps extends GObject.Object_ConstructProps {
}
export class Configuration {
/* Fields of GObject-2.0.GObject.Object */
g_type_instance: GObject.TypeInstance
/* Methods of RygelCore-2.6.RygelCore.Configuration */
get_interface(): string
get_interfaces(): string[]
get_port(): number
get_transcoding(): boolean
get_allow_upload(): boolean
get_allow_deletion(): boolean
get_log_levels(): string
get_plugin_path(): string
get_engine_path(): string
get_media_engine(): string
get_video_upload_folder(): string | null
get_music_upload_folder(): string | null
get_picture_upload_folder(): string | null
get_enabled(section: string): boolean
get_title(section: string): string
get_string(section: string, key: string): string
get_string_list(section: string, key: string): Gee.ArrayList
get_int(section: string, key: string, min: number, max: number): number
get_int_list(section: string, key: string): Gee.ArrayList
get_bool(section: string, key: string): boolean
/* Methods of GObject-2.0.GObject.Object */
bind_property(source_property: string, target: GObject.Object, target_property: string, flags: GObject.BindingFlags): GObject.Binding
bind_property_full(source_property: string, target: GObject.Object, target_property: string, flags: GObject.BindingFlags, transform_to: Function, transform_from: Function): GObject.Binding
force_floating(): void
freeze_notify(): void
get_data(key: string): object | null
get_property(property_name: string, value: any): void
get_qdata(quark: GLib.Quark): object | null
getv(names: string[], values: any[]): void
is_floating(): boolean
notify(property_name: string): void
notify_by_pspec(pspec: GObject.ParamSpec): void
ref(): GObject.Object
ref_sink(): GObject.Object
run_dispose(): void
set_data(key: string, data?: object | null): void
set_property(property_name: string, value: any): void
steal_data(key: string): object | null
steal_qdata(quark: GLib.Quark): object | null
thaw_notify(): void
unref(): void
watch_closure(closure: Function): void
/* Virtual methods of RygelCore-2.6.RygelCore.Configuration */
vfunc_get_interface(): string
vfunc_get_interfaces(): string[]
vfunc_get_port(): number
vfunc_get_transcoding(): boolean
vfunc_get_allow_upload(): boolean
vfunc_get_allow_deletion(): boolean
vfunc_get_log_levels(): string
vfunc_get_plugin_path(): string
vfunc_get_engine_path(): string
vfunc_get_media_engine(): string
vfunc_get_video_upload_folder(): string | null
vfunc_get_music_upload_folder(): string | null
vfunc_get_picture_upload_folder(): string | null
vfunc_get_enabled(section: string): boolean
vfunc_get_title(section: string): string
vfunc_get_string(section: string, key: string): string
vfunc_get_string_list(section: string, key: string): Gee.ArrayList
vfunc_get_int(section: string, key: string, min: number, max: number): number
vfunc_get_int_list(section: string, key: string): Gee.ArrayList
vfunc_get_bool(section: string, key: string): boolean
/* Virtual methods of GObject-2.0.GObject.Object */
vfunc_constructed(): void
vfunc_dispatch_properties_changed(n_pspecs: number, pspecs: GObject.ParamSpec): void
vfunc_dispose(): void
vfunc_finalize(): void
vfunc_get_property(property_id: number, value: any, pspec: GObject.ParamSpec): void
vfunc_notify(pspec: GObject.ParamSpec): void
vfunc_set_property(property_id: number, value: any, pspec: GObject.ParamSpec): void
/* Signals of RygelCore-2.6.RygelCore.Configuration */
connect(sigName: "configuration-changed", callback: (($obj: Configuration, entry: ConfigurationEntry) => void)): number
connect_after(sigName: "configuration-changed", callback: (($obj: Configuration, entry: ConfigurationEntry) => void)): number
emit(sigName: "configuration-changed", entry: ConfigurationEntry): void
connect(sigName: "section-changed", callback: (($obj: Configuration, section: string, entry: SectionEntry) => void)): number
connect_after(sigName: "section-changed", callback: (($obj: Configuration, section: string, entry: SectionEntry) => void)): number
emit(sigName: "section-changed", section: string, entry: SectionEntry): void
connect(sigName: "setting-changed", callback: (($obj: Configuration, section: string, key: string) => void)): number
connect_after(sigName: "setting-changed", callback: (($obj: Configuration, section: string, key: string) => void)): number
emit(sigName: "setting-changed", section: string, key: string): void
/* Signals of GObject-2.0.GObject.Object */
connect(sigName: "notify", callback: (($obj: Configuration, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify", callback: (($obj: Configuration, pspec: GObject.ParamSpec) => void)): number
emit(sigName: "notify", pspec: GObject.ParamSpec): void
connect(sigName: string, callback: any): number
connect_after(sigName: string, callback: any): number
emit(sigName: string, ...args: any[]): void
disconnect(id: number): void
static name: string
constructor (config?: Configuration_ConstructProps)
_init (config?: Configuration_ConstructProps): void
static $gtype: GObject.Type
}
export interface StateMachine_ConstructProps extends GObject.Object_ConstructProps {
cancellable?: Gio.Cancellable
}
export class StateMachine {
/* Properties of RygelCore-2.6.RygelCore.StateMachine */
cancellable: Gio.Cancellable
/* Fields of GObject-2.0.GObject.Object */
g_type_instance: GObject.TypeInstance
/* Methods of RygelCore-2.6.RygelCore.StateMachine */
run(_callback_?: Gio.AsyncReadyCallback | null): void
run_finish(_res_: Gio.AsyncResult): void
get_cancellable(): Gio.Cancellable
set_cancellable(value: Gio.Cancellable): void
/* Methods of GObject-2.0.GObject.Object */
bind_property(source_property: string, target: GObject.Object, target_property: string, flags: GObject.BindingFlags): GObject.Binding
bind_property_full(source_property: string, target: GObject.Object, target_property: string, flags: GObject.BindingFlags, transform_to: Function, transform_from: Function): GObject.Binding
force_floating(): void
freeze_notify(): void
get_data(key: string): object | null
get_property(property_name: string, value: any): void
get_qdata(quark: GLib.Quark): object | null
getv(names: string[], values: any[]): void
is_floating(): boolean
notify(property_name: string): void
notify_by_pspec(pspec: GObject.ParamSpec): void
ref(): GObject.Object
ref_sink(): GObject.Object
run_dispose(): void
set_data(key: string, data?: object | null): void
set_property(property_name: string, value: any): void
steal_data(key: string): object | null
steal_qdata(quark: GLib.Quark): object | null
thaw_notify(): void
unref(): void
watch_closure(closure: Function): void
/* Virtual methods of RygelCore-2.6.RygelCore.StateMachine */
vfunc_run(_callback_?: Gio.AsyncReadyCallback | null): void
vfunc_run_finish(_res_: Gio.AsyncResult): void
vfunc_get_cancellable(): Gio.Cancellable
vfunc_set_cancellable(value: Gio.Cancellable): void
/* Virtual methods of GObject-2.0.GObject.Object */
vfunc_constructed(): void
vfunc_dispatch_properties_changed(n_pspecs: number, pspecs: GObject.ParamSpec): void
vfunc_dispose(): void
vfunc_finalize(): void
vfunc_get_property(property_id: number, value: any, pspec: GObject.ParamSpec): void
vfunc_notify(pspec: GObject.ParamSpec): void
vfunc_set_property(property_id: number, value: any, pspec: GObject.ParamSpec): void
/* Signals of RygelCore-2.6.RygelCore.StateMachine */
connect(sigName: "completed", callback: (($obj: StateMachine) => void)): number
connect_after(sigName: "completed", callback: (($obj: StateMachine) => void)): number
emit(sigName: "completed"): void
/* Signals of GObject-2.0.GObject.Object */
connect(sigName: "notify", callback: (($obj: StateMachine, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify", callback: (($obj: StateMachine, pspec: GObject.ParamSpec) => void)): number
emit(sigName: "notify", pspec: GObject.ParamSpec): void
connect(sigName: "notify::cancellable", callback: (($obj: StateMachine, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify::cancellable", callback: (($obj: StateMachine, pspec: GObject.ParamSpec) => void)): number
connect(sigName: string, callback: any): number
connect_after(sigName: string, callback: any): number
emit(sigName: string, ...args: any[]): void
disconnect(id: number): void
static name: string
constructor (config?: StateMachine_ConstructProps)
_init (config?: StateMachine_ConstructProps): void
static $gtype: GObject.Type
}
export interface ConnectionManager_ConstructProps extends GUPnP.Service_ConstructProps {
}
export class ConnectionManager {
/* Fields of RygelCore-2.6.RygelCore.ConnectionManager */
sink_protocol_info: string
connection_ids: string
source_protocol_info: string
rcs_id: number
av_transport_id: number
direction: string
/* Fields of GUPnP-1.2.GUPnP.Service */
parent_instance: GUPnP.ServiceInfo
/* Fields of GObject-2.0.GObject.Object */
g_type_instance: GObject.TypeInstance
/* Methods of RygelCore-2.6.RygelCore.ConnectionManager */
get_current_protocol_info(): string
/* Methods of GUPnP-1.2.GUPnP.Service */
freeze_notify(): void
notify_value(variable: string, value: any): void
signals_autoconnect(user_data?: object | null): void
thaw_notify(): void
/* Methods of GUPnP-1.2.GUPnP.ServiceInfo */
get_context(): GUPnP.Context
get_control_url(): string
get_event_subscription_url(): string
get_id(): string
get_introspection_async(callback: GUPnP.ServiceIntrospectionCallback): void
get_introspection_async_full(callback: GUPnP.ServiceIntrospectionCallback, cancellable?: Gio.Cancellable | null): void
get_location(): string
get_scpd_url(): string
get_service_type(): string
get_udn(): string
get_url_base(): Soup.URI
introspect_async(cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback | null): void
introspect_finish(res: Gio.AsyncResult): GUPnP.ServiceIntrospection
/* Methods of GObject-2.0.GObject.Object */
bind_property(source_property: string, target: GObject.Object, target_property: string, flags: GObject.BindingFlags): GObject.Binding
bind_property_full(source_property: string, target: GObject.Object, target_property: string, flags: GObject.BindingFlags, transform_to: Function, transform_from: Function): GObject.Binding
force_floating(): void
get_data(key: string): object | null
get_property(property_name: string, value: any): void
get_qdata(quark: GLib.Quark): object | null
getv(names: string[], values: any[]): void
is_floating(): boolean
notify(property_name: string): void
notify_by_pspec(pspec: GObject.ParamSpec): void
ref(): GObject.Object
ref_sink(): GObject.Object
run_dispose(): void
set_data(key: string, data?: object | null): void
set_property(property_name: string, value: any): void
steal_data(key: string): object | null
steal_qdata(quark: GLib.Quark): object | null
unref(): void
watch_closure(closure: Function): void
/* Virtual methods of RygelCore-2.6.RygelCore.ConnectionManager */
vfunc_get_current_protocol_info(): string
/* Virtual methods of GUPnP-1.2.GUPnP.Service */
vfunc_action_invoked(action: GUPnP.ServiceAction): void
vfunc_query_variable(variable: string, value: any): void
/* Virtual methods of GObject-2.0.GObject.Object */
vfunc_constructed(): void
vfunc_dispatch_properties_changed(n_pspecs: number, pspecs: GObject.ParamSpec): void
vfunc_dispose(): void
vfunc_finalize(): void
vfunc_get_property(property_id: number, value: any, pspec: GObject.ParamSpec): void
vfunc_notify(pspec: GObject.ParamSpec): void
vfunc_set_property(property_id: number, value: any, pspec: GObject.ParamSpec): void
/* Signals of GUPnP-1.2.GUPnP.Service */
connect(sigName: "action-invoked", callback: (($obj: ConnectionManager, action: GUPnP.ServiceAction) => void)): number
connect_after(sigName: "action-invoked", callback: (($obj: ConnectionManager, action: GUPnP.ServiceAction) => void)): number
emit(sigName: "action-invoked", action: GUPnP.ServiceAction): void
connect(sigName: "notify-failed", callback: (($obj: ConnectionManager, callback_url: Soup.URI[], reason: GLib.Error) => void)): number
connect_after(sigName: "notify-failed", callback: (($obj: ConnectionManager, callback_url: Soup.URI[], reason: GLib.Error) => void)): number
emit(sigName: "notify-failed", callback_url: Soup.URI[], reason: GLib.Error): void
connect(sigName: "query-variable", callback: (($obj: ConnectionManager, variable: string, value: any) => void)): number
connect_after(sigName: "query-variable", callback: (($obj: ConnectionManager, variable: string, value: any) => void)): number
emit(sigName: "query-variable", variable: string, value: any): void
/* Signals of GObject-2.0.GObject.Object */
connect(sigName: "notify", callback: (($obj: ConnectionManager, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify", callback: (($obj: ConnectionManager, pspec: GObject.ParamSpec) => void)): number
emit(sigName: "notify", pspec: GObject.ParamSpec): void
connect(sigName: string, callback: any): number
connect_after(sigName: string, callback: any): number
emit(sigName: string, ...args: any[]): void
disconnect(id: number): void
static name: string
constructor (config?: ConnectionManager_ConstructProps)
_init (config?: ConnectionManager_ConstructProps): void
/* Static methods and pseudo-constructors */
static new(): ConnectionManager
static $gtype: GObject.Type
}
export interface BasicManagement_ConstructProps extends GUPnP.Service_ConstructProps {
max_history_size?: number
}
export class BasicManagement {
/* Properties of RygelCore-2.6.RygelCore.BasicManagement */
max_history_size: number
/* Fields of RygelCore-2.6.RygelCore.BasicManagement */
device_status: string
/* Fields of GUPnP-1.2.GUPnP.Service */
parent_instance: GUPnP.ServiceInfo
/* Fields of GObject-2.0.GObject.Object */
g_type_instance: GObject.TypeInstance
/* Methods of RygelCore-2.6.RygelCore.BasicManagement */
get_max_history_size(): number
set_max_history_size(value: number): void
/* Methods of GUPnP-1.2.GUPnP.Service */
freeze_notify(): void
notify_value(variable: string, value: any): void
signals_autoconnect(user_data?: object | null): void
thaw_notify(): void
/* Methods of GUPnP-1.2.GUPnP.ServiceInfo */
get_context(): GUPnP.Context
get_control_url(): string
get_event_subscription_url(): string
get_id(): string
get_introspection_async(callback: GUPnP.ServiceIntrospectionCallback): void
get_introspection_async_full(callback: GUPnP.ServiceIntrospectionCallback, cancellable?: Gio.Cancellable | null): void
get_location(): string
get_scpd_url(): string
get_service_type(): string
get_udn(): string
get_url_base(): Soup.URI
introspect_async(cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback | null): void
introspect_finish(res: Gio.AsyncResult): GUPnP.ServiceIntrospection
/* Methods of GObject-2.0.GObject.Object */
bind_property(source_property: string, target: GObject.Object, target_property: string, flags: GObject.BindingFlags): GObject.Binding
bind_property_full(source_property: string, target: GObject.Object, target_property: string, flags: GObject.BindingFlags, transform_to: Function, transform_from: Function): GObject.Binding
force_floating(): void
get_data(key: string): object | null
get_property(property_name: string, value: any): void
get_qdata(quark: GLib.Quark): object | null
getv(names: string[], values: any[]): void
is_floating(): boolean
notify(property_name: string): void
notify_by_pspec(pspec: GObject.ParamSpec): void
ref(): GObject.Object
ref_sink(): GObject.Object
run_dispose(): void
set_data(key: string, data?: object | null): void
set_property(property_name: string, value: any): void
steal_data(key: string): object | null
steal_qdata(quark: GLib.Quark): object | null
unref(): void
watch_closure(closure: Function): void
/* Virtual methods of GUPnP-1.2.GUPnP.Service */
vfunc_action_invoked(action: GUPnP.ServiceAction): void
vfunc_query_variable(variable: string, value: any): void
/* Virtual methods of GObject-2.0.GObject.Object */
vfunc_constructed(): void
vfunc_dispatch_properties_changed(n_pspecs: number, pspecs: GObject.ParamSpec): void
vfunc_dispose(): void
vfunc_finalize(): void
vfunc_get_property(property_id: number, value: any, pspec: GObject.ParamSpec): void
vfunc_notify(pspec: GObject.ParamSpec): void
vfunc_set_property(property_id: number, value: any, pspec: GObject.ParamSpec): void
/* Signals of GUPnP-1.2.GUPnP.Service */
connect(sigName: "action-invoked", callback: (($obj: BasicManagement, action: GUPnP.ServiceAction) => void)): number
connect_after(sigName: "action-invoked", callback: (($obj: BasicManagement, action: GUPnP.ServiceAction) => void)): number
emit(sigName: "action-invoked", action: GUPnP.ServiceAction): void
connect(sigName: "notify-failed", callback: (($obj: BasicManagement, callback_url: Soup.URI[], reason: GLib.Error) => void)): number
connect_after(sigName: "notify-failed", callback: (($obj: BasicManagement, callback_url: Soup.URI[], reason: GLib.Error) => void)): number
emit(sigName: "notify-failed", callback_url: Soup.URI[], reason: GLib.Error): void
connect(sigName: "query-variable", callback: (($obj: BasicManagement, variable: string, value: any) => void)): number
connect_after(sigName: "query-variable", callback: (($obj: BasicManagement, variable: string, value: any) => void)): number
emit(sigName: "query-variable", variable: string, value: any): void
/* Signals of GObject-2.0.GObject.Object */
connect(sigName: "notify", callback: (($obj: BasicManagement, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify", callback: (($obj: BasicManagement, pspec: GObject.ParamSpec) => void)): number
emit(sigName: "notify", pspec: GObject.ParamSpec): void
connect(sigName: "notify::max-history-size", callback: (($obj: BasicManagement, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify::max-history-size", callback: (($obj: BasicManagement, pspec: GObject.ParamSpec) => void)): number
connect(sigName: string, callback: any): number
connect_after(sigName: string, callback: any): number
emit(sigName: string, ...args: any[]): void
disconnect(id: number): void
static name: string
constructor (config?: BasicManagement_ConstructProps)
_init (config?: BasicManagement_ConstructProps): void
/* Static methods and pseudo-constructors */
static new(): BasicManagement
static $gtype: GObject.Type
}
export interface DescriptionFile_ConstructProps extends GObject.Object_ConstructProps {
}
export class DescriptionFile {
/* Fields of GObject-2.0.GObject.Object */
g_type_instance: GObject.TypeInstance
/* Methods of RygelCore-2.6.RygelCore.DescriptionFile */
set_device_type(device_type: string): void
set_model_description(model_description: string): void
set_model_name(model_name: string): void
set_model_number(model_number: string): void
set_friendly_name(friendly_name: string): void
get_friendly_name(): string
set_udn(udn: string): void
get_udn(): string | null
set_serial_number(serial: string): void
set_dlna_caps(capabilities: PluginCapabilities): void
clear_service_list(): void
add_dlna_doc_element(dlnadoc_xpath: string, dlnadoc_non_xpath: string, dev_cap: string): void
remove_dlna_doc_element(dlnadoc_xpath: string): void
add_service(device_name: string, resource_info: ResourceInfo): void
clear_icon_list(): void
add_icon(device_name: string, icon_info: IconInfo, url: string): void
modify_service_type(old_type: string, new_type: string): void
save(path: string): void
/* Methods of GObject-2.0.GObject.Object */
bind_property(source_property: string, target: GObject.Object, target_property: string, flags: GObject.BindingFlags): GObject.Binding
bind_property_full(source_property: string, target: GObject.Object, target_property: string, flags: GObject.BindingFlags, transform_to: Function, transform_from: Function): GObject.Binding
force_floating(): void
freeze_notify(): void
get_data(key: string): object | null
get_property(property_name: string, value: any): void
get_qdata(quark: GLib.Quark): object | null
getv(names: string[], values: any[]): void
is_floating(): boolean
notify(property_name: string): void
notify_by_pspec(pspec: GObject.ParamSpec): void
ref(): GObject.Object
ref_sink(): GObject.Object
run_dispose(): void
set_data(key: string, data?: object | null): void
set_property(property_name: string, value: any): void
steal_data(key: string): object | null
steal_qdata(quark: GLib.Quark): object | null
thaw_notify(): void
unref(): void
watch_closure(closure: Function): void
/* Virtual methods of GObject-2.0.GObject.Object */
vfunc_constructed(): void
vfunc_dispatch_properties_changed(n_pspecs: number, pspecs: GObject.ParamSpec): void
vfunc_dispose(): void
vfunc_finalize(): void
vfunc_get_property(property_id: number, value: any, pspec: GObject.ParamSpec): void
vfunc_notify(pspec: GObject.ParamSpec): void
vfunc_set_property(property_id: number, value: any, pspec: GObject.ParamSpec): void
/* Signals of GObject-2.0.GObject.Object */
connect(sigName: "notify", callback: (($obj: DescriptionFile, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify", callback: (($obj: DescriptionFile, pspec: GObject.ParamSpec) => void)): number
emit(sigName: "notify", pspec: GObject.ParamSpec): void
connect(sigName: string, callback: any): number
connect_after(sigName: string, callback: any): number
emit(sigName: string, ...args: any[]): void
disconnect(id: number): void
static name: string
constructor (config?: DescriptionFile_ConstructProps)
_init (config?: DescriptionFile_ConstructProps): void
/* Static methods and pseudo-constructors */
static new(template_file: string): DescriptionFile
static from_xml_document(doc: GUPnP.XMLDoc): DescriptionFile
static $gtype: GObject.Type
}
export class DLNAProfile {
/* Fields of RygelCore-2.6.RygelCore.DLNAProfile */
ref_count: number
mime: string
name: string
static name: string
static new(name: string, mime: string): DLNAProfile
constructor(name: string, mime: string)
/* Static methods and pseudo-constructors */
static new(name: string, mime: string): DLNAProfile
static compare_by_name(a: DLNAProfile, b: DLNAProfile): number
}
export interface EnergyManagement_ConstructProps extends GUPnP.Service_ConstructProps {
}
export class EnergyManagement {
/* Fields of GUPnP-1.2.GUPnP.Service */
parent_instance: GUPnP.ServiceInfo
/* Fields of GObject-2.0.GObject.Object */
g_type_instance: GObject.TypeInstance
/* Methods of GUPnP-1.2.GUPnP.Service */
freeze_notify(): void
notify_value(variable: string, value: any): void
signals_autoconnect(user_data?: object | null): void
thaw_notify(): void
/* Methods of GUPnP-1.2.GUPnP.ServiceInfo */
get_context(): GUPnP.Context
get_control_url(): string
get_event_subscription_url(): string
get_id(): string
get_introspection_async(callback: GUPnP.ServiceIntrospectionCallback): void
get_introspection_async_full(callback: GUPnP.ServiceIntrospectionCallback, cancellable?: Gio.Cancellable | null): void
get_location(): string
get_scpd_url(): string
get_service_type(): string
get_udn(): string
get_url_base(): Soup.URI
introspect_async(cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback | null): void
introspect_finish(res: Gio.AsyncResult): GUPnP.ServiceIntrospection
/* Methods of GObject-2.0.GObject.Object */
bind_property(source_property: string, target: GObject.Object, target_property: string, flags: GObject.BindingFlags): GObject.Binding
bind_property_full(source_property: string, target: GObject.Object, target_property: string, flags: GObject.BindingFlags, transform_to: Function, transform_from: Function): GObject.Binding
force_floating(): void
get_data(key: string): object | null
get_property(property_name: string, value: any): void
get_qdata(quark: GLib.Quark): object | null
getv(names: string[], values: any[]): void
is_floating(): boolean
notify(property_name: string): void
notify_by_pspec(pspec: GObject.ParamSpec): void
ref(): GObject.Object
ref_sink(): GObject.Object
run_dispose(): void
set_data(key: string, data?: object | null): void
set_property(property_name: string, value: any): void
steal_data(key: string): object | null
steal_qdata(quark: GLib.Quark): object | null
unref(): void
watch_closure(closure: Function): void
/* Virtual methods of GUPnP-1.2.GUPnP.Service */
vfunc_action_invoked(action: GUPnP.ServiceAction): void
vfunc_query_variable(variable: string, value: any): void
/* Virtual methods of GObject-2.0.GObject.Object */
vfunc_constructed(): void
vfunc_dispatch_properties_changed(n_pspecs: number, pspecs: GObject.ParamSpec): void
vfunc_dispose(): void
vfunc_finalize(): void
vfunc_get_property(property_id: number, value: any, pspec: GObject.ParamSpec): void
vfunc_notify(pspec: GObject.ParamSpec): void
vfunc_set_property(property_id: number, value: any, pspec: GObject.ParamSpec): void
/* Signals of GUPnP-1.2.GUPnP.Service */
connect(sigName: "action-invoked", callback: (($obj: EnergyManagement, action: GUPnP.ServiceAction) => void)): number
connect_after(sigName: "action-invoked", callback: (($obj: EnergyManagement, action: GUPnP.ServiceAction) => void)): number
emit(sigName: "action-invoked", action: GUPnP.ServiceAction): void
connect(sigName: "notify-failed", callback: (($obj: EnergyManagement, callback_url: Soup.URI[], reason: GLib.Error) => void)): number
connect_after(sigName: "notify-failed", callback: (($obj: EnergyManagement, callback_url: Soup.URI[], reason: GLib.Error) => void)): number
emit(sigName: "notify-failed", callback_url: Soup.URI[], reason: GLib.Error): void
connect(sigName: "query-variable", callback: (($obj: EnergyManagement, variable: string, value: any) => void)): number
connect_after(sigName: "query-variable", callback: (($obj: EnergyManagement, variable: string, value: any) => void)): number
emit(sigName: "query-variable", variable: string, value: any): void
/* Signals of GObject-2.0.GObject.Object */
connect(sigName: "notify", callback: (($obj: EnergyManagement, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify", callback: (($obj: EnergyManagement, pspec: GObject.ParamSpec) => void)): number
emit(sigName: "notify", pspec: GObject.ParamSpec): void
connect(sigName: string, callback: any): number
connect_after(sigName: string, callback: any): number
emit(sigName: string, ...args: any[]): void
disconnect(id: number): void
static name: string
constructor (config?: EnergyManagement_ConstructProps)
_init (config?: EnergyManagement_ConstructProps): void
/* Static methods and pseudo-constructors */
static new(): EnergyManagement
static $gtype: GObject.Type
}
export interface RootDevice_ConstructProps extends GUPnP.RootDevice_ConstructProps {
services?: Gee.ArrayList
}
export class RootDevice {
/* Properties of RygelCore-2.6.RygelCore.RootDevice */
services: Gee.ArrayList
/* Properties of GUPnP-1.2.GUPnP.RootDevice */
available: boolean
/* Properties of GUPnP-1.2.GUPnP.DeviceInfo */
element: object
location: string
url_base: Soup.URI
/* Fields of GUPnP-1.2.GUPnP.RootDevice */
parent_instance: GUPnP.Device
/* Fields of GObject-2.0.GObject.Object */
g_type_instance: GObject.TypeInstance
/* Methods of RygelCore-2.6.RygelCore.RootDevice */
get_services(): Gee.ArrayList
/* Methods of GUPnP-1.2.GUPnP.RootDevice */
get_available(): boolean
get_description_dir(): string
get_description_path(): string
get_relative_location(): string
get_ssdp_resource_group(): GSSDP.ResourceGroup
set_available(available: boolean): void
/* Methods of GUPnP-1.2.GUPnP.DeviceInfo */
get_context(): GUPnP.Context
get_description_value(element: string): string
get_device(type: string): GUPnP.DeviceInfo | null
get_device_type(): string
get_friendly_name(): string
get_icon_url(requested_mime_type: string | null, requested_depth: number, requested_width: number, requested_height: number, prefer_bigger: boolean): [ /* returnType */ string, /* mime_type */ string | null, /* depth */ number | null, /* width */ number | null, /* height */ number | null ]
get_location(): string
get_manufacturer(): string
get_manufacturer_url(): string
get_model_description(): string
get_model_name(): string
get_model_number(): string
get_model_url(): string
get_presentation_url(): string
get_resource_factory(): GUPnP.ResourceFactory
get_serial_number(): string
get_service(type: string): GUPnP.ServiceInfo
get_udn(): string
get_upc(): string
get_url_base(): Soup.URI
list_device_types(): string[]
list_devices(): GUPnP.DeviceInfo[]
list_dlna_capabilities(): string[]
list_dlna_device_class_identifier(): string[]
list_service_types(): string[]
list_services(): GUPnP.ServiceInfo[]
/* Methods of GObject-2.0.GObject.Object */
bind_property(source_property: string, target: GObject.Object, target_property: string, flags: GObject.BindingFlags): GObject.Binding
bind_property_full(source_property: string, target: GObject.Object, target_property: string, flags: GObject.BindingFlags, transform_to: Function, transform_from: Function): GObject.Binding
force_floating(): void
freeze_notify(): void
get_data(key: string): object | null
get_property(property_name: string, value: any): void
get_qdata(quark: GLib.Quark): object | null
getv(names: string[], values: any[]): void
is_floating(): boolean
notify(property_name: string): void
notify_by_pspec(pspec: GObject.ParamSpec): void
ref(): GObject.Object
ref_sink(): GObject.Object
run_dispose(): void
set_data(key: string, data?: object | null): void
set_property(property_name: string, value: any): void
steal_data(key: string): object | null
steal_qdata(quark: GLib.Quark): object | null
thaw_notify(): void
unref(): void
watch_closure(closure: Function): void
/* Methods of Gio-2.0.Gio.Initable */
init(cancellable?: Gio.Cancellable | null): boolean
/* Virtual methods of GUPnP-1.2.GUPnP.RootDevice */
vfunc_init(cancellable?: Gio.Cancellable | null): boolean
/* Virtual methods of GObject-2.0.GObject.Object */
vfunc_constructed(): void
vfunc_dispatch_properties_changed(n_pspecs: number, pspecs: GObject.ParamSpec): void
vfunc_dispose(): void
vfunc_finalize(): void
vfunc_get_property(property_id: number, value: any, pspec: GObject.ParamSpec): void
vfunc_notify(pspec: GObject.ParamSpec): void
vfunc_set_property(property_id: number, value: any, pspec: GObject.ParamSpec): void
/* Signals of GObject-2.0.GObject.Object */
connect(sigName: "notify", callback: (($obj: RootDevice, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify", callback: (($obj: RootDevice, pspec: GObject.ParamSpec) => void)): number
emit(sigName: "notify", pspec: GObject.ParamSpec): void
connect(sigName: "notify::services", callback: (($obj: RootDevice, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify::services", callback: (($obj: RootDevice, pspec: GObject.ParamSpec) => void)): number
connect(sigName: "notify::available", callback: (($obj: RootDevice, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify::available", callback: (($obj: RootDevice, pspec: GObject.ParamSpec) => void)): number
connect(sigName: "notify::element", callback: (($obj: RootDevice, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify::element", callback: (($obj: RootDevice, pspec: GObject.ParamSpec) => void)): number
connect(sigName: "notify::location", callback: (($obj: RootDevice, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify::location", callback: (($obj: RootDevice, pspec: GObject.ParamSpec) => void)): number
connect(sigName: "notify::url-base", callback: (($obj: RootDevice, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify::url-base", callback: (($obj: RootDevice, pspec: GObject.ParamSpec) => void)): number
connect(sigName: string, callback: any): number
connect_after(sigName: string, callback: any): number
emit(sigName: string, ...args: any[]): void
disconnect(id: number): void
static name: string
constructor (config?: RootDevice_ConstructProps)
_init (config?: RootDevice_ConstructProps): void
/* Static methods and pseudo-constructors */
static new(context: GUPnP.Context, plugin: Plugin, description_doc: GUPnP.XMLDoc, description_path: string, description_dir: string): RootDevice
static new(context: GUPnP.Context, description_path: string, description_dir: string): RootDevice
static $gtype: GObject.Type
}
export interface RootDeviceFactory_ConstructProps extends GObject.Object_ConstructProps {
context?: GUPnP.Context
}
export class RootDeviceFactory {
/* Fields of GObject-2.0.GObject.Object */
g_type_instance: GObject.TypeInstance
/* Methods of RygelCore-2.6.RygelCore.RootDeviceFactory */
create(plugin: Plugin): RootDevice
get_context(): GUPnP.Context
/* Methods of GObject-2.0.GObject.Object */
bind_property(source_property: string, target: GObject.Object, target_property: string, flags: GObject.BindingFlags): GObject.Binding
bind_property_full(source_property: string, target: GObject.Object, target_property: string, flags: GObject.BindingFlags, transform_to: Function, transform_from: Function): GObject.Binding
force_floating(): void
freeze_notify(): void
get_data(key: string): object | null
get_property(property_name: string, value: any): void
get_qdata(quark: GLib.Quark): object | null
getv(names: string[], values: any[]): void
is_floating(): boolean
notify(property_name: string): void
notify_by_pspec(pspec: GObject.ParamSpec): void
ref(): GObject.Object
ref_sink(): GObject.Object
run_dispose(): void
set_data(key: string, data?: object | null): void
set_property(property_name: string, value: any): void
steal_data(key: string): object | null
steal_qdata(quark: GLib.Quark): object | null
thaw_notify(): void
unref(): void
watch_closure(closure: Function): void
/* Methods of Gio-2.0.Gio.Initable */
init(cancellable?: Gio.Cancellable | null): boolean
/* Virtual methods of RygelCore-2.6.RygelCore.RootDeviceFactory */
vfunc_init(cancellable?: Gio.Cancellable | null): boolean
/* Virtual methods of GObject-2.0.GObject.Object */
vfunc_constructed(): void
vfunc_dispatch_properties_changed(n_pspecs: number, pspecs: GObject.ParamSpec): void
vfunc_dispose(): void
vfunc_finalize(): void
vfunc_get_property(property_id: number, value: any, pspec: GObject.ParamSpec): void
vfunc_notify(pspec: GObject.ParamSpec): void
vfunc_set_property(property_id: number, value: any, pspec: GObject.ParamSpec): void
/* Signals of GObject-2.0.GObject.Object */
connect(sigName: "notify", callback: (($obj: RootDeviceFactory, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify", callback: (($obj: RootDeviceFactory, pspec: GObject.ParamSpec) => void)): number
emit(sigName: "notify", pspec: GObject.ParamSpec): void
connect(sigName: string, callback: any): number
connect_after(sigName: string, callback: any): number
emit(sigName: string, ...args: any[]): void
disconnect(id: number): void
static name: string
constructor (config?: RootDeviceFactory_ConstructProps)
_init (config?: RootDeviceFactory_ConstructProps): void
/* Static methods and pseudo-constructors */
static new(context: GUPnP.Context): RootDeviceFactory
static newv(object_type: GObject.Type, parameters: GObject.Parameter[], cancellable?: Gio.Cancellable | null): GObject.Object
static $gtype: GObject.Type
}
export interface LogHandler_ConstructProps extends GObject.Object_ConstructProps {
}
export class LogHandler {
/* Fields of GObject-2.0.GObject.Object */
g_type_instance: GObject.TypeInstance
/* Methods of GObject-2.0.GObject.Object */
bind_property(source_property: string, target: GObject.Object, target_property: string, flags: GObject.BindingFlags): GObject.Binding
bind_property_full(source_property: string, target: GObject.Object, target_property: string, flags: GObject.BindingFlags, transform_to: Function, transform_from: Function): GObject.Binding
force_floating(): void
freeze_notify(): void
get_data(key: string): object | null
get_property(property_name: string, value: any): void
get_qdata(quark: GLib.Quark): object | null
getv(names: string[], values: any[]): void
is_floating(): boolean
notify(property_name: string): void
notify_by_pspec(pspec: GObject.ParamSpec): void
ref(): GObject.Object
ref_sink(): GObject.Object
run_dispose(): void
set_data(key: string, data?: object | null): void
set_property(property_name: string, value: any): void
steal_data(key: string): object | null
steal_qdata(quark: GLib.Quark): object | null
thaw_notify(): void
unref(): void
watch_closure(closure: Function): void
/* Virtual methods of GObject-2.0.GObject.Object */
vfunc_constructed(): void
vfunc_dispatch_properties_changed(n_pspecs: number, pspecs: GObject.ParamSpec): void
vfunc_dispose(): void
vfunc_finalize(): void
vfunc_get_property(property_id: number, value: any, pspec: GObject.ParamSpec): void
vfunc_notify(pspec: GObject.ParamSpec): void
vfunc_set_property(property_id: number, value: any, pspec: GObject.ParamSpec): void
/* Signals of GObject-2.0.GObject.Object */
connect(sigName: "notify", callback: (($obj: LogHandler, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify", callback: (($obj: LogHandler, pspec: GObject.ParamSpec) => void)): number
emit(sigName: "notify", pspec: GObject.ParamSpec): void
connect(sigName: string, callback: any): number
connect_after(sigName: string, callback: any): number
emit(sigName: string, ...args: any[]): void
disconnect(id: number): void
static name: string
constructor (config?: LogHandler_ConstructProps)
_init (config?: LogHandler_ConstructProps): void
/* Static methods and pseudo-constructors */
static get_default(): LogHandler
static $gtype: GObject.Type
}
export interface MetaConfig_ConstructProps extends GObject.Object_ConstructProps {
}
export class MetaConfig {
/* Fields of GObject-2.0.GObject.Object */
g_type_instance: GObject.TypeInstance
/* Methods of GObject-2.0.GObject.Object */
bind_property(source_property: string, target: GObject.Object, target_property: string, flags: GObject.BindingFlags): GObject.Binding
bind_property_full(source_property: string, target: GObject.Object, target_property: string, flags: GObject.BindingFlags, transform_to: Function, transform_from: Function): GObject.Binding
force_floating(): void
freeze_notify(): void
get_data(key: string): object | null
get_property(property_name: string, value: any): void
get_qdata(quark: GLib.Quark): object | null
getv(names: string[], values: any[]): void
is_floating(): boolean
notify(property_name: string): void
notify_by_pspec(pspec: GObject.ParamSpec): void
ref(): GObject.Object
ref_sink(): GObject.Object
run_dispose(): void
set_data(key: string, data?: object | null): void
set_property(property_name: string, value: any): void
steal_data(key: string): object | null
steal_qdata(quark: GLib.Quark): object | null
thaw_notify(): void
unref(): void
watch_closure(closure: Function): void
/* Methods of RygelCore-2.6.RygelCore.Configuration */
get_interface(): string
get_interfaces(): string[]
get_port(): number
get_transcoding(): boolean
get_allow_upload(): boolean
get_allow_deletion(): boolean
get_log_levels(): string
get_plugin_path(): string
get_engine_path(): string
get_media_engine(): string
get_video_upload_folder(): string | null
get_music_upload_folder(): string | null
get_picture_upload_folder(): string | null
get_enabled(section: string): boolean
get_title(section: string): string
get_string(section: string, key: string): string
get_string_list(section: string, key: string): Gee.ArrayList
get_int(section: string, key: string, min: number, max: number): number
get_int_list(section: string, key: string): Gee.ArrayList
get_bool(section: string, key: string): boolean
/* Virtual methods of RygelCore-2.6.RygelCore.MetaConfig */
vfunc_get_interface(): string
vfunc_get_interfaces(): string[]
vfunc_get_port(): number
vfunc_get_transcoding(): boolean
vfunc_get_allow_upload(): boolean
vfunc_get_allow_deletion(): boolean
vfunc_get_log_levels(): string
vfunc_get_plugin_path(): string
vfunc_get_engine_path(): string
vfunc_get_media_engine(): string
vfunc_get_video_upload_folder(): string | null
vfunc_get_music_upload_folder(): string | null
vfunc_get_picture_upload_folder(): string | null
vfunc_get_enabled(section: string): boolean
vfunc_get_title(section: string): string
vfunc_get_string(section: string, key: string): string
vfunc_get_string_list(section: string, key: string): Gee.ArrayList
vfunc_get_int(section: string, key: string, min: number, max: number): number
vfunc_get_int_list(section: string, key: string): Gee.ArrayList
vfunc_get_bool(section: string, key: string): boolean
/* Virtual methods of GObject-2.0.GObject.Object */
vfunc_constructed(): void
vfunc_dispatch_properties_changed(n_pspecs: number, pspecs: GObject.ParamSpec): void
vfunc_dispose(): void
vfunc_finalize(): void
vfunc_get_property(property_id: number, value: any, pspec: GObject.ParamSpec): void
vfunc_notify(pspec: GObject.ParamSpec): void
vfunc_set_property(property_id: number, value: any, pspec: GObject.ParamSpec): void
/* Signals of GObject-2.0.GObject.Object */
connect(sigName: "notify", callback: (($obj: MetaConfig, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify", callback: (($obj: MetaConfig, pspec: GObject.ParamSpec) => void)): number
emit(sigName: "notify", pspec: GObject.ParamSpec): void
/* Signals of RygelCore-2.6.RygelCore.Configuration */
connect(sigName: "configuration-changed", callback: (($obj: MetaConfig, entry: ConfigurationEntry) => void)): number
connect_after(sigName: "configuration-changed", callback: (($obj: MetaConfig, entry: ConfigurationEntry) => void)): number
emit(sigName: "configuration-changed", entry: ConfigurationEntry): void
connect(sigName: "section-changed", callback: (($obj: MetaConfig, section: string, entry: SectionEntry) => void)): number
connect_after(sigName: "section-changed", callback: (($obj: MetaConfig, section: string, entry: SectionEntry) => void)): number
emit(sigName: "section-changed", section: string, entry: SectionEntry): void
connect(sigName: "setting-changed", callback: (($obj: MetaConfig, section: string, key: string) => void)): number
connect_after(sigName: "setting-changed", callback: (($obj: MetaConfig, section: string, key: string) => void)): number
emit(sigName: "setting-changed", section: string, key: string): void
connect(sigName: string, callback: any): number
connect_after(sigName: string, callback: any): number
emit(sigName: string, ...args: any[]): void
disconnect(id: number): void
static name: string
constructor (config?: MetaConfig_ConstructProps)
_init (config?: MetaConfig_ConstructProps): void
/* Static methods and pseudo-constructors */
static new(): MetaConfig
static get_default(): MetaConfig
static register_configuration(config: Configuration): void
static cleanup(): void
static $gtype: GObject.Type
}
export interface PluginLoader_ConstructProps extends RecursiveModuleLoader_ConstructProps {
}
export class PluginLoader {
/* Properties of RygelCore-2.6.RygelCore.RecursiveModuleLoader */
base_path: string
/* Fields of GObject-2.0.GObject.Object */
g_type_instance: GObject.TypeInstance
/* Methods of RygelCore-2.6.RygelCore.PluginLoader */
plugin_disabled(name: string): boolean
add_plugin(plugin: Plugin): void
get_plugin_by_name(name: string): Plugin | null
list_plugins(): Gee.Collection
/* Methods of RygelCore-2.6.RygelCore.RecursiveModuleLoader */
load_modules(): void
load_modules_sync(cancellable?: Gio.Cancellable | null): void
load_module_from_file(file: Gio.File): boolean
load_module_from_info(info: PluginInformation): boolean
get_base_path(): string
set_base_path(value: string): void
/* Methods of GObject-2.0.GObject.Object */
bind_property(source_property: string, target: GObject.Object, target_property: string, flags: GObject.BindingFlags): GObject.Binding
bind_property_full(source_property: string, target: GObject.Object, target_property: string, flags: GObject.BindingFlags, transform_to: Function, transform_from: Function): GObject.Binding
force_floating(): void
freeze_notify(): void
get_data(key: string): object | null
get_property(property_name: string, value: any): void
get_qdata(quark: GLib.Quark): object | null
getv(names: string[], values: any[]): void
is_floating(): boolean
notify(property_name: string): void
notify_by_pspec(pspec: GObject.ParamSpec): void
ref(): GObject.Object
ref_sink(): GObject.Object
run_dispose(): void
set_data(key: string, data?: object | null): void
set_property(property_name: string, value: any): void
steal_data(key: string): object | null
steal_qdata(quark: GLib.Quark): object | null
thaw_notify(): void
unref(): void
watch_closure(closure: Function): void
/* Virtual methods of RygelCore-2.6.RygelCore.RecursiveModuleLoader */
vfunc_load_module_from_file(file: Gio.File): boolean
vfunc_load_module_from_info(info: PluginInformation): boolean
/* Virtual methods of GObject-2.0.GObject.Object */
vfunc_constructed(): void
vfunc_dispatch_properties_changed(n_pspecs: number, pspecs: GObject.ParamSpec): void
vfunc_dispose(): void
vfunc_finalize(): void
vfunc_get_property(property_id: number, value: any, pspec: GObject.ParamSpec): void
vfunc_notify(pspec: GObject.ParamSpec): void
vfunc_set_property(property_id: number, value: any, pspec: GObject.ParamSpec): void
/* Signals of RygelCore-2.6.RygelCore.PluginLoader */
connect(sigName: "plugin-available", callback: (($obj: PluginLoader, plugin: Plugin) => void)): number
connect_after(sigName: "plugin-available", callback: (($obj: PluginLoader, plugin: Plugin) => void)): number
emit(sigName: "plugin-available", plugin: Plugin): void
/* Signals of GObject-2.0.GObject.Object */
connect(sigName: "notify", callback: (($obj: PluginLoader, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify", callback: (($obj: PluginLoader, pspec: GObject.ParamSpec) => void)): number
emit(sigName: "notify", pspec: GObject.ParamSpec): void
connect(sigName: "notify::base-path", callback: (($obj: PluginLoader, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify::base-path", callback: (($obj: PluginLoader, pspec: GObject.ParamSpec) => void)): number
connect(sigName: string, callback: any): number
connect_after(sigName: string, callback: any): number
emit(sigName: string, ...args: any[]): void
disconnect(id: number): void
static name: string
constructor (config?: PluginLoader_ConstructProps)
_init (config?: PluginLoader_ConstructProps): void
/* Static methods and pseudo-constructors */
static new(): PluginLoader
static $gtype: GObject.Type
}
export interface RecursiveModuleLoader_ConstructProps extends GObject.Object_ConstructProps {
base_path?: string
}
export class RecursiveModuleLoader {
/* Properties of RygelCore-2.6.RygelCore.RecursiveModuleLoader */
base_path: string
/* Fields of GObject-2.0.GObject.Object */
g_type_instance: GObject.TypeInstance
/* Methods of RygelCore-2.6.RygelCore.RecursiveModuleLoader */
load_modules(): void
load_modules_sync(cancellable?: Gio.Cancellable | null): void
load_module_from_file(file: Gio.File): boolean
load_module_from_info(info: PluginInformation): boolean
get_base_path(): string
set_base_path(value: string): void
/* Methods of GObject-2.0.GObject.Object */
bind_property(source_property: string, target: GObject.Object, target_property: string, flags: GObject.BindingFlags): GObject.Binding
bind_property_full(source_property: string, target: GObject.Object, target_property: string, flags: GObject.BindingFlags, transform_to: Function, transform_from: Function): GObject.Binding
force_floating(): void
freeze_notify(): void
get_data(key: string): object | null
get_property(property_name: string, value: any): void
get_qdata(quark: GLib.Quark): object | null
getv(names: string[], values: any[]): void
is_floating(): boolean
notify(property_name: string): void
notify_by_pspec(pspec: GObject.ParamSpec): void
ref(): GObject.Object
ref_sink(): GObject.Object
run_dispose(): void
set_data(key: string, data?: object | null): void
set_property(property_name: string, value: any): void
steal_data(key: string): object | null
steal_qdata(quark: GLib.Quark): object | null
thaw_notify(): void
unref(): void
watch_closure(closure: Function): void
/* Virtual methods of RygelCore-2.6.RygelCore.RecursiveModuleLoader */
vfunc_load_module_from_file(file: Gio.File): boolean
vfunc_load_module_from_info(info: PluginInformation): boolean
/* Virtual methods of GObject-2.0.GObject.Object */
vfunc_constructed(): void
vfunc_dispatch_properties_changed(n_pspecs: number, pspecs: GObject.ParamSpec): void
vfunc_dispose(): void
vfunc_finalize(): void
vfunc_get_property(property_id: number, value: any, pspec: GObject.ParamSpec): void
vfunc_notify(pspec: GObject.ParamSpec): void
vfunc_set_property(property_id: number, value: any, pspec: GObject.ParamSpec): void
/* Signals of GObject-2.0.GObject.Object */
connect(sigName: "notify", callback: (($obj: RecursiveModuleLoader, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify", callback: (($obj: RecursiveModuleLoader, pspec: GObject.ParamSpec) => void)): number
emit(sigName: "notify", pspec: GObject.ParamSpec): void
connect(sigName: "notify::base-path", callback: (($obj: RecursiveModuleLoader, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify::base-path", callback: (($obj: RecursiveModuleLoader, pspec: GObject.ParamSpec) => void)): number
connect(sigName: string, callback: any): number
connect_after(sigName: string, callback: any): number
emit(sigName: string, ...args: any[]): void
disconnect(id: number): void
static name: string
constructor (config?: RecursiveModuleLoader_ConstructProps)
_init (config?: RecursiveModuleLoader_ConstructProps): void
static $gtype: GObject.Type
}
export interface Plugin_ConstructProps extends GUPnP.ResourceFactory_ConstructProps {
capabilities?: PluginCapabilities
name?: string
title?: string
description?: string
desc_path?: string
active?: boolean
resource_infos?: Gee.ArrayList
icon_infos?: Gee.ArrayList
default_icons?: Gee.ArrayList
}
export class Plugin {
/* Properties of RygelCore-2.6.RygelCore.Plugin */
capabilities: PluginCapabilities
title: string
active: boolean
resource_infos: Gee.ArrayList
icon_infos: Gee.ArrayList
default_icons: Gee.ArrayList
/* Fields of GUPnP-1.2.GUPnP.ResourceFactory */
parent_instance: GObject.Object
/* Fields of GObject-2.0.GObject.Object */
g_type_instance: GObject.TypeInstance
/* Methods of RygelCore-2.6.RygelCore.Plugin */
add_resource(resource_info: ResourceInfo): void
add_icon(icon_info: IconInfo): void
apply_hacks(device: RootDevice, description_path: string): void
get_capabilities(): PluginCapabilities
set_capabilities(value: PluginCapabilities): void
get_name(): string
get_title(): string
set_title(value: string): void
get_description(): string
get_desc_path(): string
get_active(): boolean
set_active(value: boolean): void
get_resource_infos(): Gee.ArrayList
get_icon_infos(): Gee.ArrayList
get_default_icons(): Gee.ArrayList
/* Methods of GUPnP-1.2.GUPnP.ResourceFactory */
register_resource_proxy_type(upnp_type: string, type: GObject.Type): void
register_resource_type(upnp_type: string, type: GObject.Type): void
unregister_resource_proxy_type(upnp_type: string): boolean
unregister_resource_type(upnp_type: string): boolean
/* Methods of GObject-2.0.GObject.Object */
bind_property(source_property: string, target: GObject.Object, target_property: string, flags: GObject.BindingFlags): GObject.Binding
bind_property_full(source_property: string, target: GObject.Object, target_property: string, flags: GObject.BindingFlags, transform_to: Function, transform_from: Function): GObject.Binding
force_floating(): void
freeze_notify(): void
get_data(key: string): object | null
get_property(property_name: string, value: any): void
get_qdata(quark: GLib.Quark): object | null
getv(names: string[], values: any[]): void
is_floating(): boolean
notify(property_name: string): void
notify_by_pspec(pspec: GObject.ParamSpec): void
ref(): GObject.Object
ref_sink(): GObject.Object
run_dispose(): void
set_data(key: string, data?: object | null): void
set_property(property_name: string, value: any): void
steal_data(key: string): object | null
steal_qdata(quark: GLib.Quark): object | null
thaw_notify(): void
unref(): void
watch_closure(closure: Function): void
/* Virtual methods of RygelCore-2.6.RygelCore.Plugin */
vfunc_apply_hacks(device: RootDevice, description_path: string): void
/* Virtual methods of GObject-2.0.GObject.Object */
vfunc_constructed(): void
vfunc_dispatch_properties_changed(n_pspecs: number, pspecs: GObject.ParamSpec): void
vfunc_dispose(): void
vfunc_finalize(): void
vfunc_get_property(property_id: number, value: any, pspec: GObject.ParamSpec): void
vfunc_notify(pspec: GObject.ParamSpec): void
vfunc_set_property(property_id: number, value: any, pspec: GObject.ParamSpec): void
/* Signals of GObject-2.0.GObject.Object */
connect(sigName: "notify", callback: (($obj: Plugin, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify", callback: (($obj: Plugin, pspec: GObject.ParamSpec) => void)): number
emit(sigName: "notify", pspec: GObject.ParamSpec): void
connect(sigName: "notify::capabilities", callback: (($obj: Plugin, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify::capabilities", callback: (($obj: Plugin, pspec: GObject.ParamSpec) => void)): number
connect(sigName: "notify::title", callback: (($obj: Plugin, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify::title", callback: (($obj: Plugin, pspec: GObject.ParamSpec) => void)): number
connect(sigName: "notify::active", callback: (($obj: Plugin, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify::active", callback: (($obj: Plugin, pspec: GObject.ParamSpec) => void)): number
connect(sigName: "notify::resource-infos", callback: (($obj: Plugin, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify::resource-infos", callback: (($obj: Plugin, pspec: GObject.ParamSpec) => void)): number
connect(sigName: "notify::icon-infos", callback: (($obj: Plugin, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify::icon-infos", callback: (($obj: Plugin, pspec: GObject.ParamSpec) => void)): number
connect(sigName: "notify::default-icons", callback: (($obj: Plugin, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify::default-icons", callback: (($obj: Plugin, pspec: GObject.ParamSpec) => void)): number
connect(sigName: string, callback: any): number
connect_after(sigName: string, callback: any): number
emit(sigName: string, ...args: any[]): void
disconnect(id: number): void
static name: string
constructor (config?: Plugin_ConstructProps)
_init (config?: Plugin_ConstructProps): void
/* Static methods and pseudo-constructors */
static new(desc_path: string, name: string, title: string | null, description: string | null, capabilities: PluginCapabilities): Plugin
static new(): Plugin
static $gtype: GObject.Type
}
export class ResourceInfo {
/* Fields of RygelCore-2.6.RygelCore.ResourceInfo */
ref_count: number
upnp_type: string
upnp_id: string
description_path: string
type: GObject.Type
static name: string
static new(upnp_id: string, upnp_type: string, description_path: string, type: GObject.Type): ResourceInfo
constructor(upnp_id: string, upnp_type: string, description_path: string, type: GObject.Type)
/* Static methods and pseudo-constructors */
static new(upnp_id: string, upnp_type: string, description_path: string, type: GObject.Type): ResourceInfo
}
export interface MediaDevice_ConstructProps extends GObject.Object_ConstructProps {
plugin?: Plugin
title?: string
capabilities?: PluginCapabilities
}
export class MediaDevice {
/* Properties of RygelCore-2.6.RygelCore.MediaDevice */
plugin: Plugin
/* Fields of GObject-2.0.GObject.Object */
g_type_instance: GObject.TypeInstance
/* Methods of RygelCore-2.6.RygelCore.MediaDevice */
add_interface(iface: string): void
remove_interface(iface: string): void
get_interfaces(): string[]
get_plugin(): Plugin
set_plugin(value: Plugin): void
get_title(): string
get_capabilities(): PluginCapabilities
/* Methods of GObject-2.0.GObject.Object */
bind_property(source_property: string, target: GObject.Object, target_property: string, flags: GObject.BindingFlags): GObject.Binding
bind_property_full(source_property: string, target: GObject.Object, target_property: string, flags: GObject.BindingFlags, transform_to: Function, transform_from: Function): GObject.Binding
force_floating(): void
freeze_notify(): void
get_data(key: string): object | null
get_property(property_name: string, value: any): void
get_qdata(quark: GLib.Quark): object | null
getv(names: string[], values: any[]): void
is_floating(): boolean
notify(property_name: string): void
notify_by_pspec(pspec: GObject.ParamSpec): void
ref(): GObject.Object
ref_sink(): GObject.Object
run_dispose(): void
set_data(key: string, data?: object | null): void
set_property(property_name: string, value: any): void
steal_data(key: string): object | null
steal_qdata(quark: GLib.Quark): object | null
thaw_notify(): void
unref(): void
watch_closure(closure: Function): void
/* Virtual methods of GObject-2.0.GObject.Object */
vfunc_constructed(): void
vfunc_dispatch_properties_changed(n_pspecs: number, pspecs: GObject.ParamSpec): void
vfunc_dispose(): void
vfunc_finalize(): void
vfunc_get_property(property_id: number, value: any, pspec: GObject.ParamSpec): void
vfunc_notify(pspec: GObject.ParamSpec): void
vfunc_set_property(property_id: number, value: any, pspec: GObject.ParamSpec): void
/* Signals of GObject-2.0.GObject.Object */
connect(sigName: "notify", callback: (($obj: MediaDevice, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify", callback: (($obj: MediaDevice, pspec: GObject.ParamSpec) => void)): number
emit(sigName: "notify", pspec: GObject.ParamSpec): void
connect(sigName: "notify::plugin", callback: (($obj: MediaDevice, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify::plugin", callback: (($obj: MediaDevice, pspec: GObject.ParamSpec) => void)): number
connect(sigName: string, callback: any): number
connect_after(sigName: string, callback: any): number
emit(sigName: string, ...args: any[]): void
disconnect(id: number): void
static name: string
constructor (config?: MediaDevice_ConstructProps)
_init (config?: MediaDevice_ConstructProps): void
static $gtype: GObject.Type
}
export interface BaseConfiguration_ConstructProps extends GObject.Object_ConstructProps {
}
export class BaseConfiguration {
/* Fields of GObject-2.0.GObject.Object */
g_type_instance: GObject.TypeInstance
/* Methods of RygelCore-2.6.RygelCore.BaseConfiguration */
get_interface(): string
get_interfaces(): string[]
get_port(): number
get_transcoding(): boolean
get_allow_upload(): boolean
get_allow_deletion(): boolean
get_log_levels(): string
get_plugin_path(): string
get_engine_path(): string
get_media_engine(): string
get_video_upload_folder(): string | null
get_music_upload_folder(): string | null
get_picture_upload_folder(): string | null
get_enabled(section: string): boolean
get_title(section: string): string
get_string(section: string, key: string): string
get_string_list(section: string, key: string): Gee.ArrayList
get_int(section: string, key: string, min: number, max: number): number
get_int_list(section: string, key: string): Gee.ArrayList
get_bool(section: string, key: string): boolean
/* Methods of GObject-2.0.GObject.Object */
bind_property(source_property: string, target: GObject.Object, target_property: string, flags: GObject.BindingFlags): GObject.Binding
bind_property_full(source_property: string, target: GObject.Object, target_property: string, flags: GObject.BindingFlags, transform_to: Function, transform_from: Function): GObject.Binding
force_floating(): void
freeze_notify(): void
get_data(key: string): object | null
get_property(property_name: string, value: any): void
get_qdata(quark: GLib.Quark): object | null
getv(names: string[], values: any[]): void
is_floating(): boolean
notify(property_name: string): void
notify_by_pspec(pspec: GObject.ParamSpec): void
ref(): GObject.Object
ref_sink(): GObject.Object
run_dispose(): void
set_data(key: string, data?: object | null): void
set_property(property_name: string, value: any): void
steal_data(key: string): object | null
steal_qdata(quark: GLib.Quark): object | null
thaw_notify(): void
unref(): void
watch_closure(closure: Function): void
/* Virtual methods of RygelCore-2.6.RygelCore.BaseConfiguration */
vfunc_get_interface(): string
vfunc_get_interfaces(): string[]
vfunc_get_port(): number
vfunc_get_transcoding(): boolean
vfunc_get_allow_upload(): boolean
vfunc_get_allow_deletion(): boolean
vfunc_get_log_levels(): string
vfunc_get_plugin_path(): string
vfunc_get_engine_path(): string
vfunc_get_media_engine(): string
vfunc_get_video_upload_folder(): string | null
vfunc_get_music_upload_folder(): string | null
vfunc_get_picture_upload_folder(): string | null
vfunc_get_enabled(section: string): boolean
vfunc_get_title(section: string): string
vfunc_get_string(section: string, key: string): string
vfunc_get_string_list(section: string, key: string): Gee.ArrayList
vfunc_get_int(section: string, key: string, min: number, max: number): number
vfunc_get_int_list(section: string, key: string): Gee.ArrayList
vfunc_get_bool(section: string, key: string): boolean
/* Virtual methods of GObject-2.0.GObject.Object */
vfunc_constructed(): void
vfunc_dispatch_properties_changed(n_pspecs: number, pspecs: GObject.ParamSpec): void
vfunc_dispose(): void
vfunc_finalize(): void
vfunc_get_property(property_id: number, value: any, pspec: GObject.ParamSpec): void
vfunc_notify(pspec: GObject.ParamSpec): void
vfunc_set_property(property_id: number, value: any, pspec: GObject.ParamSpec): void
/* Signals of GObject-2.0.GObject.Object */
connect(sigName: "notify", callback: (($obj: BaseConfiguration, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify", callback: (($obj: BaseConfiguration, pspec: GObject.ParamSpec) => void)): number
emit(sigName: "notify", pspec: GObject.ParamSpec): void
/* Signals of RygelCore-2.6.RygelCore.Configuration */
connect(sigName: "configuration-changed", callback: (($obj: BaseConfiguration, entry: ConfigurationEntry) => void)): number
connect_after(sigName: "configuration-changed", callback: (($obj: BaseConfiguration, entry: ConfigurationEntry) => void)): number
emit(sigName: "configuration-changed", entry: ConfigurationEntry): void
connect(sigName: "section-changed", callback: (($obj: BaseConfiguration, section: string, entry: SectionEntry) => void)): number
connect_after(sigName: "section-changed", callback: (($obj: BaseConfiguration, section: string, entry: SectionEntry) => void)): number
emit(sigName: "section-changed", section: string, entry: SectionEntry): void
connect(sigName: "setting-changed", callback: (($obj: BaseConfiguration, section: string, key: string) => void)): number
connect_after(sigName: "setting-changed", callback: (($obj: BaseConfiguration, section: string, key: string) => void)): number
emit(sigName: "setting-changed", section: string, key: string): void
connect(sigName: string, callback: any): number
connect_after(sigName: string, callback: any): number
emit(sigName: string, ...args: any[]): void
disconnect(id: number): void
static name: string
constructor (config?: BaseConfiguration_ConstructProps)
_init (config?: BaseConfiguration_ConstructProps): void
/* Static methods and pseudo-constructors */
static new(): BaseConfiguration
static $gtype: GObject.Type
}
export interface CmdlineConfig_ConstructProps extends GObject.Object_ConstructProps {
}
export class CmdlineConfig {
/* Fields of GObject-2.0.GObject.Object */
g_type_instance: GObject.TypeInstance
/* Methods of RygelCore-2.6.RygelCore.CmdlineConfig */
get_config_file(): string
/* Methods of GObject-2.0.GObject.Object */
bind_property(source_property: string, target: GObject.Object, target_property: string, flags: GObject.BindingFlags): GObject.Binding
bind_property_full(source_property: string, target: GObject.Object, target_property: string, flags: GObject.BindingFlags, transform_to: Function, transform_from: Function): GObject.Binding
force_floating(): void
freeze_notify(): void
get_data(key: string): object | null
get_property(property_name: string, value: any): void
get_qdata(quark: GLib.Quark): object | null
getv(names: string[], values: any[]): void
is_floating(): boolean
notify(property_name: string): void
notify_by_pspec(pspec: GObject.ParamSpec): void
ref(): GObject.Object
ref_sink(): GObject.Object
run_dispose(): void
set_data(key: string, data?: object | null): void
set_property(property_name: string, value: any): void
steal_data(key: string): object | null
steal_qdata(quark: GLib.Quark): object | null
thaw_notify(): void
unref(): void
watch_closure(closure: Function): void
/* Methods of RygelCore-2.6.RygelCore.Configuration */
get_interface(): string
get_interfaces(): string[]
get_port(): number
get_transcoding(): boolean
get_allow_upload(): boolean
get_allow_deletion(): boolean
get_log_levels(): string
get_plugin_path(): string
get_engine_path(): string
get_media_engine(): string
get_video_upload_folder(): string | null
get_music_upload_folder(): string | null
get_picture_upload_folder(): string | null
get_enabled(section: string): boolean
get_title(section: string): string
get_string(section: string, key: string): string
get_string_list(section: string, key: string): Gee.ArrayList
get_int(section: string, key: string, min: number, max: number): number
get_int_list(section: string, key: string): Gee.ArrayList
get_bool(section: string, key: string): boolean
/* Virtual methods of RygelCore-2.6.RygelCore.CmdlineConfig */
vfunc_get_interface(): string
vfunc_get_interfaces(): string[]
vfunc_get_port(): number
vfunc_get_transcoding(): boolean
vfunc_get_allow_upload(): boolean
vfunc_get_allow_deletion(): boolean
vfunc_get_log_levels(): string
vfunc_get_plugin_path(): string
vfunc_get_engine_path(): string
vfunc_get_media_engine(): string
vfunc_get_video_upload_folder(): string | null
vfunc_get_music_upload_folder(): string | null
vfunc_get_picture_upload_folder(): string | null
vfunc_get_enabled(section: string): boolean
vfunc_get_title(section: string): string
vfunc_get_string(section: string, key: string): string
vfunc_get_string_list(section: string, key: string): Gee.ArrayList
vfunc_get_int(section: string, key: string, min: number, max: number): number
vfunc_get_int_list(section: string, key: string): Gee.ArrayList
vfunc_get_bool(section: string, key: string): boolean
/* Virtual methods of GObject-2.0.GObject.Object */
vfunc_constructed(): void
vfunc_dispatch_properties_changed(n_pspecs: number, pspecs: GObject.ParamSpec): void
vfunc_dispose(): void
vfunc_finalize(): void
vfunc_get_property(property_id: number, value: any, pspec: GObject.ParamSpec): void
vfunc_notify(pspec: GObject.ParamSpec): void
vfunc_set_property(property_id: number, value: any, pspec: GObject.ParamSpec): void
/* Signals of GObject-2.0.GObject.Object */
connect(sigName: "notify", callback: (($obj: CmdlineConfig, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify", callback: (($obj: CmdlineConfig, pspec: GObject.ParamSpec) => void)): number
emit(sigName: "notify", pspec: GObject.ParamSpec): void
/* Signals of RygelCore-2.6.RygelCore.Configuration */
connect(sigName: "configuration-changed", callback: (($obj: CmdlineConfig, entry: ConfigurationEntry) => void)): number
connect_after(sigName: "configuration-changed", callback: (($obj: CmdlineConfig, entry: ConfigurationEntry) => void)): number
emit(sigName: "configuration-changed", entry: ConfigurationEntry): void
connect(sigName: "section-changed", callback: (($obj: CmdlineConfig, section: string, entry: SectionEntry) => void)): number
connect_after(sigName: "section-changed", callback: (($obj: CmdlineConfig, section: string, entry: SectionEntry) => void)): number
emit(sigName: "section-changed", section: string, entry: SectionEntry): void
connect(sigName: "setting-changed", callback: (($obj: CmdlineConfig, section: string, key: string) => void)): number
connect_after(sigName: "setting-changed", callback: (($obj: CmdlineConfig, section: string, key: string) => void)): number
emit(sigName: "setting-changed", section: string, key: string): void
connect(sigName: string, callback: any): number
connect_after(sigName: string, callback: any): number
emit(sigName: string, ...args: any[]): void
disconnect(id: number): void
static name: string
constructor (config?: CmdlineConfig_ConstructProps)
_init (config?: CmdlineConfig_ConstructProps): void
/* Static methods and pseudo-constructors */
static new(): CmdlineConfig
static get_default(): CmdlineConfig
static parse_args(args: string[]): /* args */ string[]
static $gtype: GObject.Type
}
export interface EnvironmentConfig_ConstructProps extends GObject.Object_ConstructProps {
}
export class EnvironmentConfig {
/* Fields of GObject-2.0.GObject.Object */
g_type_instance: GObject.TypeInstance
/* Methods of GObject-2.0.GObject.Object */
bind_property(source_property: string, target: GObject.Object, target_property: string, flags: GObject.BindingFlags): GObject.Binding
bind_property_full(source_property: string, target: GObject.Object, target_property: string, flags: GObject.BindingFlags, transform_to: Function, transform_from: Function): GObject.Binding
force_floating(): void
freeze_notify(): void
get_data(key: string): object | null
get_property(property_name: string, value: any): void
get_qdata(quark: GLib.Quark): object | null
getv(names: string[], values: any[]): void
is_floating(): boolean
notify(property_name: string): void
notify_by_pspec(pspec: GObject.ParamSpec): void
ref(): GObject.Object
ref_sink(): GObject.Object
run_dispose(): void
set_data(key: string, data?: object | null): void
set_property(property_name: string, value: any): void
steal_data(key: string): object | null
steal_qdata(quark: GLib.Quark): object | null
thaw_notify(): void
unref(): void
watch_closure(closure: Function): void
/* Methods of RygelCore-2.6.RygelCore.Configuration */
get_interface(): string
get_interfaces(): string[]
get_port(): number
get_transcoding(): boolean
get_allow_upload(): boolean
get_allow_deletion(): boolean
get_log_levels(): string
get_plugin_path(): string
get_engine_path(): string
get_media_engine(): string
get_video_upload_folder(): string | null
get_music_upload_folder(): string | null
get_picture_upload_folder(): string | null
get_enabled(section: string): boolean
get_title(section: string): string
get_string(section: string, key: string): string
get_string_list(section: string, key: string): Gee.ArrayList
get_int(section: string, key: string, min: number, max: number): number
get_int_list(section: string, key: string): Gee.ArrayList
get_bool(section: string, key: string): boolean
/* Virtual methods of RygelCore-2.6.RygelCore.EnvironmentConfig */
vfunc_get_interface(): string
vfunc_get_interfaces(): string[]
vfunc_get_port(): number
vfunc_get_transcoding(): boolean
vfunc_get_allow_upload(): boolean
vfunc_get_allow_deletion(): boolean
vfunc_get_log_levels(): string
vfunc_get_plugin_path(): string
vfunc_get_engine_path(): string
vfunc_get_media_engine(): string
vfunc_get_video_upload_folder(): string | null
vfunc_get_music_upload_folder(): string | null
vfunc_get_picture_upload_folder(): string | null
vfunc_get_enabled(section: string): boolean
vfunc_get_title(section: string): string
vfunc_get_string(section: string, key: string): string
vfunc_get_string_list(section: string, key: string): Gee.ArrayList
vfunc_get_int(section: string, key: string, min: number, max: number): number
vfunc_get_int_list(section: string, key: string): Gee.ArrayList
vfunc_get_bool(section: string, key: string): boolean
/* Virtual methods of GObject-2.0.GObject.Object */
vfunc_constructed(): void
vfunc_dispatch_properties_changed(n_pspecs: number, pspecs: GObject.ParamSpec): void
vfunc_dispose(): void
vfunc_finalize(): void
vfunc_get_property(property_id: number, value: any, pspec: GObject.ParamSpec): void
vfunc_notify(pspec: GObject.ParamSpec): void
vfunc_set_property(property_id: number, value: any, pspec: GObject.ParamSpec): void
/* Signals of GObject-2.0.GObject.Object */
connect(sigName: "notify", callback: (($obj: EnvironmentConfig, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify", callback: (($obj: EnvironmentConfig, pspec: GObject.ParamSpec) => void)): number
emit(sigName: "notify", pspec: GObject.ParamSpec): void
/* Signals of RygelCore-2.6.RygelCore.Configuration */
connect(sigName: "configuration-changed", callback: (($obj: EnvironmentConfig, entry: ConfigurationEntry) => void)): number
connect_after(sigName: "configuration-changed", callback: (($obj: EnvironmentConfig, entry: ConfigurationEntry) => void)): number
emit(sigName: "configuration-changed", entry: ConfigurationEntry): void
connect(sigName: "section-changed", callback: (($obj: EnvironmentConfig, section: string, entry: SectionEntry) => void)): number
connect_after(sigName: "section-changed", callback: (($obj: EnvironmentConfig, section: string, entry: SectionEntry) => void)): number
emit(sigName: "section-changed", section: string, entry: SectionEntry): void
connect(sigName: "setting-changed", callback: (($obj: EnvironmentConfig, section: string, key: string) => void)): number
connect_after(sigName: "setting-changed", callback: (($obj: EnvironmentConfig, section: string, key: string) => void)): number
emit(sigName: "setting-changed", section: string, key: string): void
connect(sigName: string, callback: any): number
connect_after(sigName: string, callback: any): number
emit(sigName: string, ...args: any[]): void
disconnect(id: number): void
static name: string
constructor (config?: EnvironmentConfig_ConstructProps)
_init (config?: EnvironmentConfig_ConstructProps): void
/* Static methods and pseudo-constructors */
static new(): EnvironmentConfig
static get_default(): EnvironmentConfig
static $gtype: GObject.Type
}
export interface UserConfig_ConstructProps extends GObject.Object_ConstructProps {
}
export class UserConfig {
/* Fields of RygelCore-2.6.RygelCore.UserConfig */
key_file: GLib.KeyFile
sys_key_file: GLib.KeyFile
key_file_monitor: Gio.FileMonitor
sys_key_file_monitor: Gio.FileMonitor
/* Fields of GObject-2.0.GObject.Object */
g_type_instance: GObject.TypeInstance
/* Methods of GObject-2.0.GObject.Object */
bind_property(source_property: string, target: GObject.Object, target_property: string, flags: GObject.BindingFlags): GObject.Binding
bind_property_full(source_property: string, target: GObject.Object, target_property: string, flags: GObject.BindingFlags, transform_to: Function, transform_from: Function): GObject.Binding
force_floating(): void
freeze_notify(): void
get_data(key: string): object | null
get_property(property_name: string, value: any): void
get_qdata(quark: GLib.Quark): object | null
getv(names: string[], values: any[]): void
is_floating(): boolean
notify(property_name: string): void
notify_by_pspec(pspec: GObject.ParamSpec): void
ref(): GObject.Object
ref_sink(): GObject.Object
run_dispose(): void
set_data(key: string, data?: object | null): void
set_property(property_name: string, value: any): void
steal_data(key: string): object | null
steal_qdata(quark: GLib.Quark): object | null
thaw_notify(): void
unref(): void
watch_closure(closure: Function): void
/* Methods of RygelCore-2.6.RygelCore.Configuration */
get_interface(): string
get_interfaces(): string[]
get_port(): number
get_transcoding(): boolean
get_allow_upload(): boolean
get_allow_deletion(): boolean
get_log_levels(): string
get_plugin_path(): string
get_engine_path(): string
get_media_engine(): string
get_video_upload_folder(): string | null
get_music_upload_folder(): string | null
get_picture_upload_folder(): string | null
get_enabled(section: string): boolean
get_title(section: string): string
get_string(section: string, key: string): string
get_string_list(section: string, key: string): Gee.ArrayList
get_int(section: string, key: string, min: number, max: number): number
get_int_list(section: string, key: string): Gee.ArrayList
get_bool(section: string, key: string): boolean
/* Virtual methods of RygelCore-2.6.RygelCore.UserConfig */
vfunc_get_interface(): string
vfunc_get_interfaces(): string[]
vfunc_get_port(): number
vfunc_get_transcoding(): boolean
vfunc_get_allow_upload(): boolean
vfunc_get_allow_deletion(): boolean
vfunc_get_log_levels(): string
vfunc_get_plugin_path(): string
vfunc_get_engine_path(): string
vfunc_get_media_engine(): string
vfunc_get_video_upload_folder(): string | null
vfunc_get_music_upload_folder(): string | null
vfunc_get_picture_upload_folder(): string | null
vfunc_get_enabled(section: string): boolean
vfunc_get_title(section: string): string
vfunc_get_string(section: string, key: string): string
vfunc_get_string_list(section: string, key: string): Gee.ArrayList
vfunc_get_int(section: string, key: string, min: number, max: number): number
vfunc_get_int_list(section: string, key: string): Gee.ArrayList
vfunc_get_bool(section: string, key: string): boolean
/* Virtual methods of GObject-2.0.GObject.Object */
vfunc_constructed(): void
vfunc_dispatch_properties_changed(n_pspecs: number, pspecs: GObject.ParamSpec): void
vfunc_dispose(): void
vfunc_finalize(): void
vfunc_get_property(property_id: number, value: any, pspec: GObject.ParamSpec): void
vfunc_notify(pspec: GObject.ParamSpec): void
vfunc_set_property(property_id: number, value: any, pspec: GObject.ParamSpec): void
/* Signals of GObject-2.0.GObject.Object */
connect(sigName: "notify", callback: (($obj: UserConfig, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify", callback: (($obj: UserConfig, pspec: GObject.ParamSpec) => void)): number
emit(sigName: "notify", pspec: GObject.ParamSpec): void
/* Signals of RygelCore-2.6.RygelCore.Configuration */
connect(sigName: "configuration-changed", callback: (($obj: UserConfig, entry: ConfigurationEntry) => void)): number
connect_after(sigName: "configuration-changed", callback: (($obj: UserConfig, entry: ConfigurationEntry) => void)): number
emit(sigName: "configuration-changed", entry: ConfigurationEntry): void
connect(sigName: "section-changed", callback: (($obj: UserConfig, section: string, entry: SectionEntry) => void)): number
connect_after(sigName: "section-changed", callback: (($obj: UserConfig, section: string, entry: SectionEntry) => void)): number
emit(sigName: "section-changed", section: string, entry: SectionEntry): void
connect(sigName: "setting-changed", callback: (($obj: UserConfig, section: string, key: string) => void)): number
connect_after(sigName: "setting-changed", callback: (($obj: UserConfig, section: string, key: string) => void)): number
emit(sigName: "setting-changed", section: string, key: string): void
connect(sigName: string, callback: any): number
connect_after(sigName: string, callback: any): number
emit(sigName: string, ...args: any[]): void
disconnect(id: number): void
static name: string
constructor (config?: UserConfig_ConstructProps)
_init (config?: UserConfig_ConstructProps): void
/* Static methods and pseudo-constructors */
static new(local_path: string): UserConfig
static with_paths(local_path: string, system_path: string): UserConfig
static get_default(): UserConfig
static $gtype: GObject.Type
}
export interface V1Hacks_ConstructProps extends GObject.Object_ConstructProps {
device_type?: string
service_types?: string[]
}
export class V1Hacks {
/* Properties of RygelCore-2.6.RygelCore.V1Hacks */
device_type: string
/* Fields of RygelCore-2.6.RygelCore.V1Hacks */
description_path: string
/* Fields of GObject-2.0.GObject.Object */
g_type_instance: GObject.TypeInstance
/* Methods of RygelCore-2.6.RygelCore.V1Hacks */
apply_on_device(device: RootDevice, template_path?: string | null): void
get_device_type(): string
set_device_type(value: string): void
get_service_types(): string[]
/* Methods of GObject-2.0.GObject.Object */
bind_property(source_property: string, target: GObject.Object, target_property: string, flags: GObject.BindingFlags): GObject.Binding
bind_property_full(source_property: string, target: GObject.Object, target_property: string, flags: GObject.BindingFlags, transform_to: Function, transform_from: Function): GObject.Binding
force_floating(): void
freeze_notify(): void
get_data(key: string): object | null
get_property(property_name: string, value: any): void
get_qdata(quark: GLib.Quark): object | null
getv(names: string[], values: any[]): void
is_floating(): boolean
notify(property_name: string): void
notify_by_pspec(pspec: GObject.ParamSpec): void
ref(): GObject.Object
ref_sink(): GObject.Object
run_dispose(): void
set_data(key: string, data?: object | null): void
set_property(property_name: string, value: any): void
steal_data(key: string): object | null
steal_qdata(quark: GLib.Quark): object | null
thaw_notify(): void
unref(): void
watch_closure(closure: Function): void
/* Virtual methods of GObject-2.0.GObject.Object */
vfunc_constructed(): void
vfunc_dispatch_properties_changed(n_pspecs: number, pspecs: GObject.ParamSpec): void
vfunc_dispose(): void
vfunc_finalize(): void
vfunc_get_property(property_id: number, value: any, pspec: GObject.ParamSpec): void
vfunc_notify(pspec: GObject.ParamSpec): void
vfunc_set_property(property_id: number, value: any, pspec: GObject.ParamSpec): void
/* Signals of GObject-2.0.GObject.Object */
connect(sigName: "notify", callback: (($obj: V1Hacks, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify", callback: (($obj: V1Hacks, pspec: GObject.ParamSpec) => void)): number
emit(sigName: "notify", pspec: GObject.ParamSpec): void
connect(sigName: "notify::device-type", callback: (($obj: V1Hacks, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify::device-type", callback: (($obj: V1Hacks, pspec: GObject.ParamSpec) => void)): number
connect(sigName: string, callback: any): number
connect_after(sigName: string, callback: any): number
emit(sigName: string, ...args: any[]): void
disconnect(id: number): void
static name: string
constructor (config?: V1Hacks_ConstructProps)
_init (config?: V1Hacks_ConstructProps): void
/* Static methods and pseudo-constructors */
static new(device_type: string, service_types: string[]): V1Hacks
static $gtype: GObject.Type
}
export class IconInfo {
/* Fields of RygelCore-2.6.RygelCore.IconInfo */
ref_count: number
mime_type: string
uri: string
file_extension: string
size: number
width: number
height: number
depth: number
static name: string
static new(mime_type: string, file_extension: string): IconInfo
constructor(mime_type: string, file_extension: string)
/* Static methods and pseudo-constructors */
static new(mime_type: string, file_extension: string): IconInfo
}
export class XMLUtils {
/* Fields of RygelCore-2.6.RygelCore.XMLUtils */
ref_count: number
static name: string
static new(): XMLUtils
constructor()
/* Static methods and pseudo-constructors */
static new(): XMLUtils
}
export class XMLUtilsIterator {
/* Fields of RygelCore-2.6.RygelCore.XMLUtilsIterator */
ref_count: number
/* Methods of RygelCore-2.6.RygelCore.XMLUtilsIterator */
iterator(): XMLUtilsIterator
next(): boolean
get(): object | null
static name: string
static new(node?: object | null): XMLUtilsIterator
constructor(node?: object | null)
/* Static methods and pseudo-constructors */
static new(node?: object | null): XMLUtilsIterator
}
export class XMLUtilsChildIterator {
/* Fields of RygelCore-2.6.RygelCore.XMLUtilsIterator */
ref_count: number
/* Methods of RygelCore-2.6.RygelCore.XMLUtilsIterator */
iterator(): XMLUtilsIterator
next(): boolean
get(): object | null
static name: string
static new(node?: object | null): XMLUtilsChildIterator
constructor(node?: object | null)
/* Static methods and pseudo-constructors */
static new(node?: object | null): XMLUtilsChildIterator
}
export interface PluginInformation_ConstructProps extends GObject.Object_ConstructProps {
module_path?: string
name?: string
conflicts?: any
module_loaded?: boolean
}
export class PluginInformation {
/* Properties of RygelCore-2.6.RygelCore.PluginInformation */
module_loaded: boolean
/* Fields of GObject-2.0.GObject.Object */
g_type_instance: GObject.TypeInstance
/* Methods of RygelCore-2.6.RygelCore.PluginInformation */
get_module_path(): string
get_name(): string
get_conflicts(): any
get_module_loaded(): boolean
set_module_loaded(value: boolean): void
/* Methods of GObject-2.0.GObject.Object */
bind_property(source_property: string, target: GObject.Object, target_property: string, flags: GObject.BindingFlags): GObject.Binding
bind_property_full(source_property: string, target: GObject.Object, target_property: string, flags: GObject.BindingFlags, transform_to: Function, transform_from: Function): GObject.Binding
force_floating(): void
freeze_notify(): void
get_data(key: string): object | null
get_property(property_name: string, value: any): void
get_qdata(quark: GLib.Quark): object | null
getv(names: string[], values: any[]): void
is_floating(): boolean
notify(property_name: string): void
notify_by_pspec(pspec: GObject.ParamSpec): void
ref(): GObject.Object
ref_sink(): GObject.Object
run_dispose(): void
set_data(key: string, data?: object | null): void
set_property(property_name: string, value: any): void
steal_data(key: string): object | null
steal_qdata(quark: GLib.Quark): object | null
thaw_notify(): void
unref(): void
watch_closure(closure: Function): void
/* Virtual methods of GObject-2.0.GObject.Object */
vfunc_constructed(): void
vfunc_dispatch_properties_changed(n_pspecs: number, pspecs: GObject.ParamSpec): void
vfunc_dispose(): void
vfunc_finalize(): void
vfunc_get_property(property_id: number, value: any, pspec: GObject.ParamSpec): void
vfunc_notify(pspec: GObject.ParamSpec): void
vfunc_set_property(property_id: number, value: any, pspec: GObject.ParamSpec): void
/* Signals of GObject-2.0.GObject.Object */
connect(sigName: "notify", callback: (($obj: PluginInformation, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify", callback: (($obj: PluginInformation, pspec: GObject.ParamSpec) => void)): number
emit(sigName: "notify", pspec: GObject.ParamSpec): void
connect(sigName: "notify::module-loaded", callback: (($obj: PluginInformation, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify::module-loaded", callback: (($obj: PluginInformation, pspec: GObject.ParamSpec) => void)): number
connect(sigName: string, callback: any): number
connect_after(sigName: string, callback: any): number
emit(sigName: string, ...args: any[]): void
disconnect(id: number): void
static name: string
constructor (config?: PluginInformation_ConstructProps)
_init (config?: PluginInformation_ConstructProps): void
/* Static methods and pseudo-constructors */
static new_from_file(file: Gio.File): PluginInformation
static $gtype: GObject.Type
}
export abstract class ConnectionManagerClass {
/* Fields of RygelCore-2.6.RygelCore.ConnectionManagerClass */
get_current_protocol_info: () => string
static name: string
}
export class ConnectionManagerPrivate {
static name: string
}
export abstract class BasicManagementClass {
static name: string
}
export class BasicManagementPrivate {
static name: string
}
export abstract class DescriptionFileClass {
static name: string
}
export class DescriptionFilePrivate {
static name: string
}
export abstract class DLNAProfileClass {
static name: string
}
export class DLNAProfilePrivate {
static name: string
}
export abstract class EnergyManagementClass {
static name: string
}
export class EnergyManagementPrivate {
static name: string
}
export abstract class RootDeviceClass {
static name: string
}
export class RootDevicePrivate {
static name: string
}
export abstract class RootDeviceFactoryClass {
static name: string
}
export class RootDeviceFactoryPrivate {
static name: string
}
export abstract class LogHandlerClass {
static name: string
}
export class LogHandlerPrivate {
static name: string
}
export abstract class MetaConfigClass {
static name: string
}
export class MetaConfigPrivate {
static name: string
}
export abstract class PluginLoaderClass {
static name: string
}
export class PluginLoaderPrivate {
static name: string
}
export abstract class RecursiveModuleLoaderClass {
/* Fields of RygelCore-2.6.RygelCore.RecursiveModuleLoaderClass */
load_module_from_file: (file: Gio.File) => boolean
load_module_from_info: (info: PluginInformation) => boolean
static name: string
}
export class RecursiveModuleLoaderPrivate {
static name: string
}
export abstract class PluginClass {
/* Fields of RygelCore-2.6.RygelCore.PluginClass */
apply_hacks: (device: RootDevice, description_path: string) => void
static name: string
}
export class PluginPrivate {
static name: string
}
export abstract class ResourceInfoClass {
static name: string
}
export class ResourceInfoPrivate {
static name: string
}
export abstract class MediaDeviceClass {
static name: string
}
export class MediaDevicePrivate {
static name: string
}
export abstract class BaseConfigurationClass {
/* Fields of RygelCore-2.6.RygelCore.BaseConfigurationClass */
get_interface: () => string
get_interfaces: () => string[]
get_port: () => number
get_transcoding: () => boolean
get_allow_upload: () => boolean
get_allow_deletion: () => boolean
get_log_levels: () => string
get_plugin_path: () => string
get_engine_path: () => string
get_media_engine: () => string
get_video_upload_folder: () => string | null
get_music_upload_folder: () => string | null
get_picture_upload_folder: () => string | null
get_enabled: (section: string) => boolean
get_title: (section: string) => string
get_string: (section: string, key: string) => string
get_string_list: (section: string, key: string) => Gee.ArrayList
get_int: (section: string, key: string, min: number, max: number) => number
get_int_list: (section: string, key: string) => Gee.ArrayList
get_bool: (section: string, key: string) => boolean
static name: string
}
export class BaseConfigurationPrivate {
static name: string
}
export abstract class CmdlineConfigClass {
static name: string
}
export class CmdlineConfigPrivate {
static name: string
}
export abstract class EnvironmentConfigClass {
static name: string
}
export class EnvironmentConfigPrivate {
static name: string
}
export abstract class UserConfigClass {
static name: string
}
export class UserConfigPrivate {
static name: string
}
export abstract class V1HacksClass {
static name: string
}
export class V1HacksPrivate {
static name: string
}
export abstract class IconInfoClass {
static name: string
}
export class IconInfoPrivate {
static name: string
}
export abstract class XMLUtilsClass {
static name: string
}
export class XMLUtilsPrivate {
static name: string
}
export abstract class XMLUtilsIteratorClass {
static name: string
}
export class XMLUtilsIteratorPrivate {
static name: string
}
export abstract class XMLUtilsChildIteratorClass {
static name: string
}
export class XMLUtilsChildIteratorPrivate {
static name: string
}
export abstract class PluginInformationClass {
static name: string
}
export class PluginInformationPrivate {
static name: string
}
export abstract class DBusInterfaceIface {
/* Fields of RygelCore-2.6.RygelCore.DBusInterfaceIface */
shutdown: () => void
static name: string
}
export abstract class DBusAclProviderIface {
/* Fields of RygelCore-2.6.RygelCore.DBusAclProviderIface */
is_allowed: (device: GLib.HashTable, service: GLib.HashTable, path: string, address: string, agent?: string | null, _callback_?: Gio.AsyncReadyCallback | null) => void
is_allowed_finish: (_res_: Gio.AsyncResult) => boolean
static name: string
}
export abstract class ConfigurationIface {
/* Fields of RygelCore-2.6.RygelCore.ConfigurationIface */
get_interface: () => string
get_interfaces: () => string[]
get_port: () => number
get_transcoding: () => boolean
get_allow_upload: () => boolean
get_allow_deletion: () => boolean
get_log_levels: () => string
get_plugin_path: () => string
get_engine_path: () => string
get_media_engine: () => string
get_video_upload_folder: () => string | null
get_music_upload_folder: () => string | null
get_picture_upload_folder: () => string | null
get_enabled: (section: string) => boolean
get_title: (section: string) => string
get_string: (section: string, key: string) => string
get_string_list: (section: string, key: string) => Gee.ArrayList
get_int: (section: string, key: string, min: number, max: number) => number
get_int_list: (section: string, key: string) => Gee.ArrayList
get_bool: (section: string, key: string) => boolean
static name: string
}
export abstract class StateMachineIface {
/* Fields of RygelCore-2.6.RygelCore.StateMachineIface */
run: (_callback_?: Gio.AsyncReadyCallback | null) => void
run_finish: (_res_: Gio.AsyncResult) => void
get_cancellable: () => Gio.Cancellable
set_cancellable: (value: Gio.Cancellable) => void
static name: string
} | 1.078125 | 1 |
src/components/Main/ScanHome.tsx | yoav85/hamagen-react-native | 0 | 2208 | import React, { useEffect, useRef, useState } from 'react';
import { View, StyleSheet, AppState, AppStateStatus, BackHandler, DeviceEventEmitter } from 'react-native';
import { connect } from 'react-redux';
import NetInfo, { NetInfoState } from '@react-native-community/netinfo';
import { RESULTS } from 'react-native-permissions';
import { bindActionCreators } from 'redux';
import SplashScreen from 'react-native-splash-screen';
import { useFocusEffect } from '@react-navigation/native';
// @ts-ignore
import RNSettings from 'react-native-settings';
import ScanHomeHeader from './ScanHomeHeader';
import NoData from './NoData';
import ExposuresDetected from './ExposuresDetected';
import NoExposures from './NoExposures';
import ExposureInstructions from './ExposureInstructions';
import { toggleWebview } from '../../actions/GeneralActions';
import { dismissExposure, removeValidExposure, setValidExposure } from '../../actions/ExposuresActions';
import { checkPermissions } from '../../services/LocationService';
import { Exposure } from '../../types';
interface Props {
navigation: any,
isRTL: boolean,
strings: any,
locale: 'he'|'en'|'ar'|'am'|'ru',
exposures: Exposure[],
validExposure: Exposure,
firstPoint?: undefined,
setValidExposure(exposure: Exposure): void,
removeValidExposure(): void,
dismissExposure(exposureId: number): void,
toggleWebview(isShow: boolean, usageType: string): void
}
const ScanHome = ({ navigation, isRTL, strings, locale, exposures, validExposure, setValidExposure, removeValidExposure, dismissExposure, toggleWebview, firstPoint }: Props) => {
const appStateStatus = useRef<AppStateStatus>('active');
const [{ hasLocation, hasNetwork, hasGPS }, setIsConnected] = useState({ hasLocation: true, hasNetwork: true, hasGPS: true });
useEffect(() => {
setTimeout(SplashScreen.hide, 3000);
checkConnectionStatusOnLoad();
AppState.addEventListener('change', onAppStateChange);
NetInfo.addEventListener((state: NetInfoState) => {
setIsConnected({ hasLocation, hasNetwork: state.isConnected, hasGPS });
});
DeviceEventEmitter.addListener(RNSettings.GPS_PROVIDER_EVENT, handleGPSProviderEvent);
return () => {
AppState.removeEventListener('change', onAppStateChange);
DeviceEventEmitter.removeListener(RNSettings.GPS_PROVIDER_EVENT, handleGPSProviderEvent);
};
}, []);
useFocusEffect(
React.useCallback(() => {
const onBackPress = () => {
BackHandler.exitApp();
return true;
};
BackHandler.addEventListener('hardwareBackPress', onBackPress);
return () => {
BackHandler.removeEventListener('hardwareBackPress', onBackPress);
};
}, [])
);
const checkConnectionStatusOnLoad = async () => {
const locationPermission = await checkPermissions();
const networkStatus = await NetInfo.fetch();
const GPSStatus = await RNSettings.getSetting(RNSettings.LOCATION_SETTING);
setIsConnected({ hasLocation: locationPermission === RESULTS.GRANTED, hasNetwork: networkStatus.isConnected, hasGPS: GPSStatus === RNSettings.ENABLED });
};
const onAppStateChange = async (state: AppStateStatus) => {
if (state === 'active' && appStateStatus.current !== 'active') {
const locationPermission = await checkPermissions();
const GPSStatus = await RNSettings.getSetting(RNSettings.LOCATION_SETTING);
setIsConnected({ hasLocation: locationPermission === RESULTS.GRANTED, hasNetwork, hasGPS: GPSStatus === RNSettings.ENABLED });
}
appStateStatus.current = state;
};
const handleGPSProviderEvent = (e: any) => {
setIsConnected({ hasLocation, hasNetwork, hasGPS: e[RNSettings.LOCATION_SETTING] === RNSettings.ENABLED });
};
const renderRelevantState = () => {
if (validExposure) {
return (
<ExposureInstructions isRTL={isRTL} strings={strings} locale={locale} exposure={validExposure} removeValidExposure={removeValidExposure} />
);
} if (!hasLocation || !hasNetwork) {
return (
<NoData strings={strings} />
);
} if (exposures.length > 0) {
return (
<ExposuresDetected
isRTL={isRTL}
strings={strings}
exposures={exposures}
onValidExposure={exposure => setValidExposure(exposure)}
dismissExposure={exposureId => dismissExposure(exposureId)}
/>
);
}
return <NoExposures strings={strings} toggleWebview={toggleWebview} firstPoint={firstPoint} />;
};
return (
<View style={styles.container}>
<ScanHomeHeader
isRTL={isRTL}
strings={strings}
isConnected={hasLocation && hasNetwork && hasGPS}
showChangeLanguage
goToExposureHistory={() => navigation.navigate('ExposuresHistory')}
/>
{
renderRelevantState()
}
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff'
}
});
const mapStateToProps = (state: any) => {
const {
locale: { isRTL, strings, locale },
exposures: { exposures, validExposure, firstPoint }
} = state;
return { isRTL, strings, locale, exposures, validExposure, firstPoint };
};
const mapDispatchToProps = (dispatch: any) => {
return bindActionCreators({
setValidExposure,
removeValidExposure,
dismissExposure,
toggleWebview
}, dispatch);
};
export default connect(mapStateToProps, mapDispatchToProps)(ScanHome);
| 1.578125 | 2 |
projects/angular-tabler-icons/icons/svg/refresh.ts | pierreavn/angular-tabler-icons | 4 | 2216 | export const IconRefresh = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
<path stroke="none" d="M0 0h24v24H0z" fill="none"/>
<path d="M20 11a8.1 8.1 0 0 0 -15.5 -2m-.5 -4v4h4" />
<path d="M4 13a8.1 8.1 0 0 0 15.5 2m.5 4v-4h-4" />
</svg>
` | 0.664063 | 1 |
src/components/Avatar/index.tsx | platformbuilders/react-native-elements | 0 | 2224 | import React, { useImperativeHandle, useRef, useState } from 'react';
import { isEmpty } from 'lodash';
import { RNCamera } from 'react-native-camera';
import FastImage, { Source } from 'react-native-fast-image';
import ImagePicker from 'react-native-image-picker';
import { ImageAvatarPlaceholder as defaultAvatar } from '../../assets/images';
import If from '../If';
import { CameraView, UploadIcon, UploadIconWrapper, Wrapper } from './styles';
type Props = {
ref?: any;
image?: string;
showBorder?: boolean;
borderWidth?: number;
borderColor?: string;
displayCamera?: boolean;
size?: number;
onPress?: (x: any) => void;
onUpload?: (x: any) => any;
id?: string;
accessibility: string;
accessibilityLabel?: string;
testID?: string;
};
const Avatar: React.FC<Props> = React.forwardRef(
(
{
id,
image = defaultAvatar,
accessibility = 'Upload de Avatar',
accessibilityLabel,
testID,
size = 50,
onPress,
onUpload,
showBorder = true,
displayCamera = false,
...rest
},
ref,
// eslint-disable-next-line sonarjs/cognitive-complexity
) => {
const [uploadedImage, setUploadedImage] = useState<any>();
const cameraRef = useRef<any>();
const openPicker = (): Promise<void> => {
const options = {
title: 'Selecionar foto',
cancelButtonTitle: 'Cancelar',
takePhotoButtonTitle: 'Tirar foto',
chooseFromLibraryButtonTitle: 'Escolher da galeria',
quality: 0.3,
storageOptions: {
skipBackup: true,
path: 'images',
},
};
return new Promise((resolve) => {
ImagePicker.launchImageLibrary(options as any, (response: any) => {
setUploadedImage(response.uri);
if (onUpload) {
onUpload(response.uri);
}
resolve();
});
});
};
const takePicture = async (): Promise<void> => {
if (cameraRef.current) {
const options = { quality: 0.5, base64: true };
const data = await cameraRef.current.takePictureAsync(options);
setUploadedImage(data);
return data;
}
};
const getUploadImage = (): any => {
return uploadedImage;
};
const clearUploadImage = (): void => {
setUploadedImage('');
};
const getCurrentAvatar = (): Source | any => {
if (uploadedImage) {
return { uri: uploadedImage };
}
if (image && !isEmpty(image)) {
return { uri: image };
}
return defaultAvatar;
};
useImperativeHandle(ref, () => ({
getUploadImage,
clearUploadImage,
takePicture,
openPicker,
}));
return (
<Wrapper
id={id || accessibility}
accessibility={accessibility}
accessibilityLabel={accessibilityLabel || accessibility}
testID={testID || id}
size={size}
onPress={onPress}
disabled={!onPress}
showBorder={showBorder}
{...rest}
>
{displayCamera && !uploadedImage ? (
<CameraView
ref={cameraRef}
size={size}
type={RNCamera.Constants.Type.front}
flashMode={RNCamera.Constants.FlashMode.auto}
androidCameraPermissionOptions={{
title: 'Câmera',
message: 'Precisamos da sua permissão para usar a câmera',
buttonPositive: 'Ok',
buttonNegative: 'Cancelar',
}}
/>
) : (
<FastImage
source={getCurrentAvatar()}
resizeMode={FastImage.resizeMode.cover}
style={{ width: '101%', height: '101%' }}
/>
)}
<If condition={!!displayCamera}>
<UploadIconWrapper size={size}>
<UploadIcon id="" accessibility="" />
</UploadIconWrapper>
</If>
</Wrapper>
);
},
);
Avatar.displayName = 'AvatarComponent';
export default Avatar;
| 1.6875 | 2 |
tests/unit/build-time-render/BuildTimeRenderMiddleware.ts | KaneFreeman/webpack-contrib | 0 | 2232 | import { stub, SinonStub } from 'sinon';
import MockModule from '../../support/MockModule';
const { beforeEach, describe, it } = intern.getInterface('bdd');
const { assert } = intern.getPlugin('chai');
let mockModule: MockModule;
describe('build-time-render middleware', () => {
beforeEach(() => {
mockModule = new MockModule('../../../src/build-time-render/BuildTimeRenderMiddleware', require);
mockModule.dependencies(['./BuildTimeRender']);
});
it('test', () => {
const compiler = {
hooks: {
invalid: {
tap: stub()
}
}
};
const mockRequest = {
accepts() {
return true;
},
url: 'http://localhost/blog'
};
const runPathStub = stub();
const BuildTimeRenderMock: SinonStub = mockModule
.getMock('./BuildTimeRender')
.default.returns({ runPath: runPathStub });
const OnDemandBuildTimeRender = mockModule.getModuleUnderTest().default;
const nextStub = stub();
const onDemandBuildTimeRender = new OnDemandBuildTimeRender({
buildTimeRenderOptions: {
root: 'app',
onDemand: true
},
scope: 'lib',
outputPath: 'path',
jsonpName: 'jsonpFunction',
compiler,
base: 'base',
cacheOptions: {
invalidates: ['blog']
},
entries: ['main']
});
onDemandBuildTimeRender.middleware(mockRequest, {}, nextStub);
assert.isTrue(BuildTimeRenderMock.notCalled);
compiler.hooks.invalid.tap.firstCall.callArg(1);
onDemandBuildTimeRender.middleware(mockRequest, {}, nextStub);
assert.isTrue(BuildTimeRenderMock.calledOnce);
assert.deepEqual(BuildTimeRenderMock.firstCall.args, [
{
basePath: process.cwd(),
baseUrl: 'base',
entries: ['main'],
root: 'app',
onDemand: true,
cacheOptions: {
invalidates: ['blog']
},
scope: 'lib'
}
]);
assert.isTrue(runPathStub.calledOnce);
assert.deepEqual(runPathStub.firstCall.args, [nextStub, 'blog', 'path', 'jsonpFunction']);
onDemandBuildTimeRender.middleware(mockRequest, {}, nextStub);
assert.isTrue(BuildTimeRenderMock.calledOnce);
assert.isTrue(runPathStub.calledOnce);
onDemandBuildTimeRender.middleware(
{
url: 'http://localhost/blog.html',
accepts() {
return false;
}
},
{},
nextStub
);
assert.isTrue(BuildTimeRenderMock.calledOnce);
assert.isTrue(runPathStub.calledOnce);
onDemandBuildTimeRender.middleware({ ...mockRequest, url: 'http://localhost/other.js' }, {}, nextStub);
assert.isTrue(BuildTimeRenderMock.calledOnce);
assert.isTrue(runPathStub.calledOnce);
compiler.hooks.invalid.tap.firstCall.callArg(1);
onDemandBuildTimeRender.middleware(mockRequest, {}, nextStub);
assert.isTrue(BuildTimeRenderMock.calledTwice);
assert.deepEqual(BuildTimeRenderMock.secondCall.args, [
{
basePath: process.cwd(),
baseUrl: 'base',
entries: ['main'],
root: 'app',
onDemand: true,
cacheOptions: {
invalidates: ['blog']
},
scope: 'lib'
}
]);
assert.isTrue(runPathStub.calledTwice);
assert.deepEqual(runPathStub.secondCall.args, [nextStub, 'blog', 'path', 'jsonpFunction']);
});
});
| 1.507813 | 2 |
client/src/interfaces/foodItem.ts | evanstern/food-diary | 1 | 2240 | export interface IFoodItem {
_id: string;
name: string;
calories: number;
quantity: number;
date: Date;
createdAt: Date;
updatedAt: Date;
}
| 0.224609 | 0 |
src/AdminUI/src/app/components/contacts/view-contact-dialog/view-contact-dialog.component.ts | cisagov/con-pca-web | 6 | 2248 | import { Component, OnInit, Inject } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
import {
MatDialogRef,
MAT_DIALOG_DATA,
MatDialog,
} from '@angular/material/dialog';
import { CustomerService } from 'src/app/services/customer.service';
import { SubscriptionService } from 'src/app/services/subscription.service';
import {
ICustomerContact,
CustomerModel,
ContactModel,
} from 'src/app/models/customer.model';
import { SubscriptionModel } from 'src/app/models/subscription.model';
import { AlertComponent } from '../../dialogs/alert/alert.component';
@Component({
selector: 'app-view-contact-dialog',
templateUrl: './view-contact-dialog.component.html',
styleUrls: ['../contacts.component.scss'],
})
export class ViewContactDialogComponent implements OnInit {
form_group = new FormGroup({
first_name: new FormControl(),
last_name: new FormControl(),
title: new FormControl(),
office_phone: new FormControl(),
mobile_phone: new FormControl(),
primary_contact: new FormControl(),
phone: new FormControl(),
email: new FormControl(),
notes: new FormControl(),
active: new FormControl(),
});
contactSubs: SubscriptionModel[];
customer: CustomerModel;
subscription: SubscriptionModel;
initial: ICustomerContact;
data: ICustomerContact;
constructor(
public dialog_ref: MatDialogRef<ViewContactDialogComponent>,
public customer_service: CustomerService,
private subscription_service: SubscriptionService,
public dialog: MatDialog,
@Inject(MAT_DIALOG_DATA) data
) {
this.data = data;
this.initial = Object.assign({}, data);
}
ngOnInit(): void {
this.customer_service
.getCustomer(this.data.customer_id)
.subscribe((data: any) => {
this.customer = data as CustomerModel;
});
}
onSaveExitClick(): void {
const index = this.getContactIndex();
const old_contact = this.customer.contact_list[index];
this.removeContact();
const updated_contact = {
first_name: this.data.first_name,
last_name: this.data.last_name,
title: this.data.title,
office_phone: this.data.office_phone,
mobile_phone: this.data.mobile_phone,
email: this.data.email,
notes: this.data.notes,
active: this.data.active,
};
this.customer.contact_list.push(updated_contact);
this.updateSubsContact(old_contact, updated_contact);
this.saveContacts();
this.dialog_ref.close();
}
onDeleteClick(): void {
// check if there are any sub with contact as primary, if so, dont delete
const index = this.getContactIndex();
this.subscription_service
.getPrimaryContactSubscriptions(
this.customer._id,
this.customer.contact_list[index]
)
.subscribe((subscriptions: any[]) => {
this.contactSubs = subscriptions as SubscriptionModel[];
if (this.contactSubs.length > 0) {
// this contact had subs, dont delete
const invalid = [];
for (const sub in this.contactSubs) {
invalid.push(this.contactSubs[sub].name + ' update');
}
this.dialog.open(AlertComponent, {
data: {
title: 'Cannot Delete Contact',
messageText:
'This Contact is currently the primary contact for the following subscriptions. Please update the subscriptions to a new contact before deletion.',
invalidData: invalid,
},
});
} else {
// free and clear, delete away
this.removeContact();
this.saveContacts();
}
});
this.dialog_ref.close();
}
removeContact(): void {
const index = this.getContactIndex();
if (index > -1) {
this.customer.contact_list.splice(index, 1);
}
}
updateSubsContact(
old_contact: ContactModel,
updated_contact: ContactModel
): void {
// Get all subs of the contact then update
this.subscription_service
.getPrimaryContactSubscriptions(this.customer._id, old_contact)
.subscribe((subscriptions: SubscriptionModel[]) => {
this.contactSubs = subscriptions as SubscriptionModel[];
if (this.contactSubs.length > 0) {
// Check if there are any subs with contact, if so, remove them from the sub.
for (let index in this.contactSubs) {
let contsub: SubscriptionModel = this.contactSubs[index];
this.subscription_service
.changePrimaryContact(contsub._id, updated_contact)
.subscribe();
}
}
});
}
onCancelExitClick(): void {
this.dialog_ref.close();
}
saveContacts(): void {
this.customer_service
.setContacts(this.customer._id, this.customer.contact_list)
.subscribe();
}
getContactIndex(): number {
for (var i = 0; i < this.customer.contact_list.length; i++) {
var contact: ContactModel = this.customer.contact_list[i];
if (
contact.first_name == this.initial.first_name &&
contact.last_name == this.initial.last_name &&
contact.email == this.initial.email &&
contact.notes == this.initial.notes &&
contact.title == this.initial.title
) {
return i;
}
}
}
}
| 1.179688 | 1 |
server/gql/index.ts | sidiousvic/spiders | 0 | 2264 | import { Request } from "express";
import { ApolloServer } from "apollo-server";
import { GraphQLConfig, Models, User } from "@spiders";
async function GraphQLServer(
models: Models,
{ apolloConfig: { schema, auth }, uri, port }: GraphQLConfig
) {
const apolloServer = new ApolloServer({
schema,
async context({ req }: { req: Request }) {
const token = req.headers.authorization;
let authedUser = {} as User;
if (token) {
const { userId } = auth.getUserFromToken(token);
authedUser = await models.User.find({ userId });
}
return { models, authedUser };
},
});
await apolloServer.listen({ port });
console.log(`🧬 Apollo GraphQL server live @ ${uri}`);
}
export { GraphQLServer };
| 1.210938 | 1 |
src/index.ts | aarmora/jordan-scrapes-amazon-prices | 0 | 2272 | import puppeteer, { Browser } from 'puppeteer';
import { getPropertyBySelector, setUpNewPage } from 'puppeteer-helpers';
(async () => {
try {
let browser: Browser;
let ubuntu = false;
let headless = false;
if (process.argv[2] === 'ubuntu' || process.argv[3] === 'ubuntu') {
ubuntu = true;
}
if (process.argv[2] === 'headless' || process.argv[3] === 'headless') {
headless = true;
}
if (ubuntu) {
browser = await puppeteer.launch({ headless: true, args: [`--window-size=${1800},${1200}`, '--no-sandbox', '--disable-setuid-sandbox'] });
}
else {
browser = await puppeteer.launch({ headless: headless, args: [`--window-size=${1800},${1200}`] });
}
const baseUrl = `https://www.amazon.com/dp/`;
// Whatever products you want to scrape
const asins = [ 'B0007L7GMW', 'B0007LHZCS', 'B0007LDX8I'];
for (let asin of asins) {
const url = baseUrl + asin;
const page = await setUpNewPage(browser);
await page.goto(url);
const price = await getPropertyBySelector(page, '#priceblock_ourprice', 'innerHTML');
const vendor = await getPropertyBySelector(page, '#merchant-info a', 'innerHTML');
console.log('price, vendor', price, vendor);
await page.close();
// Update database or price or something else?
}
await browser.close();
}
catch (e) {
console.log('Error in initial');
}
})(); | 1.429688 | 1 |
src/systems/bricks/createBricks.ts | dpoarch/TypeScript-Phaser | 3 | 2280 | import { BrickConfig } from '@config/BrickConfig';
import { BricksWaveConfig } from '@config/BricksWaveConfig';
import { BaseMutableComposite } from '@systems/BaseMutableComposite';
import { BaseBricks } from '@systems/bricks/BaseBricks';
import { Bricks } from '@systems/bricks/Bricks';
import { nextWaveBricks } from '@systems/bricks/nextWaveBricks';
import { Stats } from '@systems/score/Stats';
/**
* Create the bricks.
* @param wave Wave config.
* @param brick Brick config.
*/
export function createBricks(wave: BricksWaveConfig, brick: BrickConfig, stats: Stats): Bricks {
return new BaseBricks(brick, new BaseMutableComposite(nextWaveBricks(wave, 1, brick, [])), stats);
}
| 0.953125 | 1 |
src/ts/markdown/mermaidRender.ts | angleshe/vditor | 21 | 2288 | import {Constants} from "../constants";
import {addScript} from "../util/addScript";
declare const mermaid: {
init(option: { noteMargin: number; }, c: string): void;
};
export const mermaidRender = (element: HTMLElement, className = ".language-mermaid",
cdn = Constants.CDN) => {
if (element.querySelectorAll(className).length === 0) {
return;
}
addScript(`${cdn}/dist/js/mermaid/mermaid.min.js`, "vditorMermaidScript").then(() => {
mermaid.init({noteMargin: 10}, className);
});
};
| 0.988281 | 1 |
server/sn_cc/sn_cc_StandardCredentialsProvider.d.ts | Dman89/servicenow-types | 3 | 2296 | import { sn_cc_SNAPIStandardCredentialsProvider } from "./sn_cc_SNAPIStandardCredentialsProvider";
declare class sn_cc_StandardCredentialsProvider extends sn_cc_SNAPIStandardCredentialsProvider {}
export { sn_cc_StandardCredentialsProvider };
| 0.211914 | 0 |
src/entity.ts | myywlc/lin-micro-frontend | 0 | 2304 | import type { App } from './types';
import { mapMixin } from './mixin';
import { importHtml } from './html-loader';
export enum Status {
NOT_LOADED = 'NOT_LOADED',
LOADING = 'LOADING',
NOT_BOOTSTRAPPED = 'NOT_BOOTSTRAPPED',
BOOTSTRAPPING = 'BOOTSTRAPPING',
NOT_MOUNTED = 'NOT_MOUNTED',
MOUNTING = 'MOUNTING',
MOUNTED = 'MOUNTED',
UPDATING = 'UPDATING',
UPDATED = 'UPDATED',
UNMOUNTING = 'UNMOUNTING'
}
let apps: App[] = [];
export function register(appArray: any[]): void {
appArray.forEach((app: any) => (app.status = Status.NOT_LOADED));
apps = appArray;
hack();
reroute();
}
function reroute(): void {
const { loads, mounts, unmounts } = getAppChanges();
perform();
async function perform(): Promise<void> {
unmounts.map(runUnmount);
loads.map(async (app) => {
app = await runLoad(app);
app = await runBootstrap(app);
return runMount(app);
});
mounts.map(async (app) => {
app = await runBootstrap(app);
return runMount(app);
});
}
}
function getAppChanges(): {
unmounts: App[]
loads: App[]
mounts: App[]
} {
const unmounts: App[] = [];
const loads: App[] = [];
const mounts: App[] = [];
apps.forEach((app: any) => {
const isActive =
typeof app.path === 'function'
? app.path(window.location)
: window.location.pathname === app.path;
switch (app.status) {
case Status.NOT_LOADED:
case Status.LOADING:
isActive && loads.push(app);
break;
case Status.NOT_BOOTSTRAPPED:
case Status.BOOTSTRAPPING:
case Status.NOT_MOUNTED:
isActive && mounts.push(app);
break;
case Status.MOUNTED:
!isActive && unmounts.push(app);
break;
}
});
return { unmounts, loads, mounts };
}
function compose(
fns: ((app: App) => Promise<any>)[],
): (app: App) => Promise<void> {
fns = Array.isArray(fns) ? fns : [fns];
return (app: App): Promise<void> =>
fns.reduce((p, fn) => p.then(() => fn(app)), Promise.resolve());
}
async function runLoad(app: App): Promise<any> {
if (app.loaded) return app.loaded;
app.loaded = Promise.resolve().then(async () => {
app.status = Status.LOADING;
let mixinLife = mapMixin();
app.host = await loadShadowDOM(app);
const { dom, lifecycles } = await importHtml(app);
app.host?.appendChild(dom);
app.status = Status.NOT_BOOTSTRAPPED;
app.bootstrap = compose(mixinLife.bootstrap.concat(lifecycles.bootstrap));
app.mount = compose(mixinLife.mount.concat(lifecycles.mount));
app.unmount = compose(mixinLife.unmount.concat(lifecycles.unmount));
delete app.loaded;
return app;
});
return app.loaded;
}
function loadShadowDOM(app: App): Promise<DocumentFragment> {
// @ts-ignore
return new Promise((resolve, reject) => {
class Berial extends HTMLElement {
constructor() {
super();
resolve(this.attachShadow({ mode: 'open' }));
}
// @ts-ignore
static get tag(): string {
return app.name;
}
}
const hasDef = window.customElements.get(app.name);
if (!hasDef) {
customElements.define(app.name, Berial);
}
});
}
async function runUnmount(app: App): Promise<App> {
if (app.status != Status.MOUNTED) {
return app;
}
app.status = Status.UNMOUNTING;
await app.unmount(app);
app.status = Status.NOT_MOUNTED;
return app;
}
async function runBootstrap(app: App): Promise<App> {
if (app.status !== Status.NOT_BOOTSTRAPPED) {
return app;
}
app.status = Status.BOOTSTRAPPING;
await app.bootstrap(app);
app.status = Status.NOT_MOUNTED;
return app;
}
async function runMount(app: App): Promise<App> {
if (app.status !== Status.NOT_MOUNTED) {
return app;
}
app.status = Status.MOUNTING;
await app.mount(app);
app.status = Status.MOUNTED;
return app;
}
function hack(): void {
window.addEventListener = hackEventListener(window.addEventListener);
window.removeEventListener = hackEventListener(window.removeEventListener);
window.history.pushState = hackHistory(window.history.pushState);
window.history.replaceState = hackHistory(window.history.replaceState);
window.addEventListener('hashchange', reroute);
window.addEventListener('popstate', reroute);
}
const captured = {
hashchange: [],
popstate: [],
} as any;
function hackEventListener(func: any): any {
return function (name: any, fn: any): any {
if (name === 'hashchange' || name === 'popstate') {
if (!captured[name].some((l: any) => l == fn)) {
captured[name].push(fn);
return;
} else {
captured[name] = captured[name].filter((l: any) => l !== fn);
return;
}
}
// @ts-ignore
return func.apply(this, arguments as any);
};
}
function hackHistory(fn: any): () => void {
return function (): void {
const before = window.location.href;
fn.apply(window.history, arguments);
const after = window.location.href;
if (before !== after) {
new PopStateEvent('popstate');
reroute();
}
};
}
| 1.492188 | 1 |
src/app/ui/game.ts | carljohansen/shallow-thought | 0 | 2312 | import { EventEmitter, Output } from '@angular/core';
import * as Chess from '../engine/ChessElements';
import { PlayerBase } from './playerBase';
import { SquareComponent } from './square.component';
export class Game {
@Output() movePlayed: EventEmitter<any> = new EventEmitter();
@Output() progressNotified: EventEmitter<number> = new EventEmitter();
public board: Chess.Board;
public whitePlayer: PlayerBase;
public blackPlayer: PlayerBase;
public moveHistory: Chess.GameMove[];
private isPaused: boolean;
constructor() {
this.isPaused = true;
}
public get activePlayer(): PlayerBase {
return this.board.isWhiteToMove ? this.whitePlayer : this.blackPlayer;
}
public get inactivePlayer(): PlayerBase {
return !this.board.isWhiteToMove ? this.whitePlayer : this.blackPlayer;
}
public dispose(): void {
this.whitePlayer.dispose();
this.blackPlayer.dispose();
this.moveHistory = null;
}
public resume(): void {
if (!this.isPaused) {
throw "Can't resume - game is not paused.";
}
this.isPaused = false;
this.activePlayer.activate(this.board);
}
public onSquareSelected(selectedSquare: SquareComponent) {
this.activePlayer.onSquareSelected(selectedSquare);
}
public static createGame(whitePlayer: PlayerBase, blackPlayer: PlayerBase, board: Chess.Board): Game {
let newGame = new Game();
newGame.whitePlayer = whitePlayer;
newGame.blackPlayer = blackPlayer;
newGame.board = board;
newGame.whitePlayer.move.subscribe(newGame.onMove);
newGame.blackPlayer.move.subscribe(newGame.onMove);
newGame.whitePlayer.progress.subscribe(newGame.onProgressNotified);
newGame.blackPlayer.progress.subscribe(newGame.onProgressNotified);
newGame.moveHistory = [];
return newGame;
}
private onMove = (move: Chess.GameMove) => {
if (!move) {
alert("Game over!");
return;
}
let validatedMove = this.board.isLegalMove(move);
if (!validatedMove) {
alert("That move is not legal..");
this.activePlayer.deactivate();
this.activePlayer.activate(this.board);
return;
}
// Annotate the move with disambiguation information (this improves our move list display).
validatedMove.disambiguationSquare = this.board.getMoveDisambiguationSquare(validatedMove);
this.board = this.board.applyMove(validatedMove);
validatedMove.checkHint = this.board.getCheckState();
this.moveHistory.push(validatedMove);
this.inactivePlayer.deactivate();
this.activePlayer.activate(this.board);
this.movePlayed.emit(true);
}
private onProgressNotified = (progress: number) => {
this.progressNotified.emit(progress);
}
public static createStandardGame(whitePlayer: PlayerBase, blackPlayer: PlayerBase): Game {
const standardBoard = Chess.Board.create([{ square: "a1", piece: Chess.PieceType.Rook },
{ square: "b1", piece: Chess.PieceType.Knight },
{ square: "c1", piece: Chess.PieceType.Bishop },
{ square: "d1", piece: Chess.PieceType.Queen },
{ square: "e1", piece: Chess.PieceType.King },
{ square: "f1", piece: Chess.PieceType.Bishop },
{ square: "g1", piece: Chess.PieceType.Knight },
{ square: "h1", piece: Chess.PieceType.Rook },
{ square: "a2", piece: Chess.PieceType.Pawn },
{ square: "b2", piece: Chess.PieceType.Pawn },
{ square: "c2", piece: Chess.PieceType.Pawn },
{ square: "d2", piece: Chess.PieceType.Pawn },
{ square: "e2", piece: Chess.PieceType.Pawn },
{ square: "f2", piece: Chess.PieceType.Pawn },
{ square: "g2", piece: Chess.PieceType.Pawn },
{ square: "h2", piece: Chess.PieceType.Pawn },
],
[{ square: "a8", piece: Chess.PieceType.Rook },
{ square: "b8", piece: Chess.PieceType.Knight },
{ square: "c8", piece: Chess.PieceType.Bishop },
{ square: "d8", piece: Chess.PieceType.Queen },
{ square: "e8", piece: Chess.PieceType.King },
{ square: "f8", piece: Chess.PieceType.Bishop },
{ square: "g8", piece: Chess.PieceType.Knight },
{ square: "h8", piece: Chess.PieceType.Rook },
{ square: "a7", piece: Chess.PieceType.Pawn },
{ square: "b7", piece: Chess.PieceType.Pawn },
{ square: "c7", piece: Chess.PieceType.Pawn },
{ square: "d7", piece: Chess.PieceType.Pawn },
{ square: "e7", piece: Chess.PieceType.Pawn },
{ square: "f7", piece: Chess.PieceType.Pawn },
{ square: "g7", piece: Chess.PieceType.Pawn },
{ square: "h7", piece: Chess.PieceType.Pawn }],
true, Chess.CastlingPotential.BlackKingside + Chess.CastlingPotential.BlackQueenside + Chess.CastlingPotential.WhiteKingside + Chess.CastlingPotential.WhiteQueenside);
return Game.createGame(whitePlayer, blackPlayer, standardBoard);
}
public static createCustomGame(whitePlayer: PlayerBase, blackPlayer: PlayerBase): Game {
const standardBoard = Chess.Board.create([{ square: "a6", piece: Chess.PieceType.Rook },
{ square: "f7", piece: Chess.PieceType.King },
],
[{ square: "h8", piece: Chess.PieceType.King },
{ square: "h3", piece: Chess.PieceType.Pawn }],
true, Chess.CastlingPotential.BlackKingside + Chess.CastlingPotential.BlackQueenside + Chess.CastlingPotential.WhiteKingside + Chess.CastlingPotential.WhiteQueenside);
return Game.createGame(whitePlayer, blackPlayer, standardBoard);
}
} | 1.625 | 2 |
src/app/shell/components/Footer/Footer.tsx | Levie7/c-lisys | 0 | 2320 | import { memo } from 'react';
export const Footer = memo(() => (
<div className='bg-primary fg-white p-6 ta-center' id='Footer'>
Copyright © 2022 - Lisys. All Right Reserved.
<br />
made with{' '}
<span role='img' aria-label='Heart'>
❤️
</span>{' '}
by Lisys
</div>
));
| 0.832031 | 1 |
tools/ng-packagr.transformers/tasks/write-package-json/index.ts | tamtakoe/ngrid | 225 | 2328 | export * from './write-package-json';
| -0.217773 | 0 |
src/components/SidebarDebug/DebugPropertiesPanel.tsx | FWeinb/moddable-webide | 8 | 2336 | /** @jsx jsx */
import { jsx } from '@emotion/core';
import React from 'react';
import SidebarPanel from '../SidebarPanel';
import { XsbugProperty } from '../../xs/DeviceConnection';
const sortingRegexps = [
/(\[)([0-9]+)(\])/,
/(\(\.)([0-9]+)(\))/,
/(\(\.\.)([0-9]+)(\))/,
/(arg\()([0-9]+)(\))/,
/(var\()([0-9]+)(\))/
];
const sortingZeros = '0000000000';
type ToggleFunction = (value: string) => void;
export type DebugPropertyProps = {
property: XsbugProperty;
toggle: ToggleFunction;
};
const DebugProperty: React.FC<DebugPropertyProps> = ({ property, toggle }) => {
const { name, value, properties } = property;
const isValue = value && value[0] !== '@';
const onClick = isValue ? undefined : () => toggle(value);
return (
<div
onClick={onClick}
css={{
display: 'flex',
flexShrink: 0,
cursor: 'pointer',
':hover': {
color: 'var(--color-text-muted)',
background: 'rgba(255,255,255,0.3)'
}
}}
style={{ cursor: isValue ? 'not-allowed' : 'pointer' }}
>
<span css={{ display: 'inline-block', width: 5 }}>
{!isValue ? (properties === undefined ? '+' : '-') : ''}
</span>
<span
css={{
paddingLeft: '0.5em',
whiteSpace: 'nowrap',
overflow: 'hidden',
textOverflow: 'ellipsis'
}}
>
<span>{name}</span>
<span css={{ color: 'var(--color-text-muted)' }}>
{isValue ? ' = ' + value : ''}
</span>
</span>
</div>
);
};
export type DebugFramePropertiesProps = {
properties: XsbugProperty[];
toggle: ToggleFunction;
depth?: number;
};
const DebugFrameProperties: React.FC<DebugFramePropertiesProps> = ({
properties,
toggle,
depth = 0
}) =>
properties ? (
<div
css={[
{
position: 'relative',
flexGrow: 1,
margin: 0,
padding: 0,
listStyle: 'none'
}
]}
>
{properties
.map(({ name, flags, value, properties }) => {
for (let i = 0; i < sortingRegexps.length; i++) {
let results = sortingRegexps[i].exec(name);
if (results) {
let result = results[2];
name =
results[1] +
sortingZeros.slice(0, -result.length) +
result +
results[3];
break;
}
}
return { name, flags, value, properties };
})
.sort((a, b) => a.name.localeCompare(b.name))
.map(property => {
const properties = property.properties;
return (
<div
key={property.name}
css={{
margin: 0,
padding: `.125em 0 .125em`
}}
style={{
paddingLeft: `${0.5 + depth * 0.2}em`
}}
>
<DebugProperty property={property} toggle={toggle} />
{properties && (
<DebugFrameProperties
properties={properties}
toggle={toggle}
depth={++depth}
/>
)}
</div>
);
})}
</div>
) : (
<div />
);
export type DebugPropertiesPanel = {
title: string;
properties: XsbugProperty[];
toggle: ToggleFunction;
autoOpen?: boolean;
};
const DebugPropertiesPanel: React.FC<DebugPropertiesPanel> = ({
title,
properties,
toggle,
autoOpen
}) => {
return (
<SidebarPanel title={title} autoOpen={autoOpen}>
<DebugFrameProperties properties={properties} toggle={toggle} />
</SidebarPanel>
);
};
export default DebugPropertiesPanel;
| 1.445313 | 1 |
src/Utils/sortProps.ts | ccpu/ts-to-json | 9 | 2344 | import { Definition } from "../Schema/Definition";
import * as deepSortArray from "sort-keys";
export const sortProps = (schema: Definition) => {
if (schema.definitions) {
sortProps(schema.definitions);
}
Object.keys(schema).forEach((key) => {
// eslint-disable-next-line @typescript-eslint/ban-ts-ignore
// @ts-ignore
const obj = schema[key] as Definition;
if (obj) {
if (obj.type === "object" && obj.properties) {
obj.properties = deepSortArray(obj.properties);
sortProps(obj.properties);
if (obj.parameters) {
sortProps(obj.parameters as Definition);
}
} else if (typeof obj === "object") {
sortProps(obj);
}
}
});
return schema;
};
| 0.96875 | 1 |
src/jobs/index.ts | LuanSilveiraSouza/node-pipedrive-bling-api | 1 | 2352 | import { CronJob } from 'cron';
import GetPipedriveDeals from './GetPipedriveDeals';
import DealRepository from '../database/DealRepository';
import PostBlingDeal from './PostBlingDeal';
import { IDeal } from '../types/deal';
const job = new CronJob(
'0 0 */1 * * *',
async () => {
const deals = await GetPipedriveDeals();
await Promise.all(deals.map(async (deal: IDeal) => {
const inserted = await DealRepository.create(deal);
if (inserted) {
await PostBlingDeal(deal);
}
}));
},
null,
true,
'America/Sao_Paulo'
);
export default job;
| 1.023438 | 1 |
src/renderer/FirebaseHelpers.ts | Aisthetic/cookietouch | 2 | 2360 | import * as firebase from "firebase";
export function initialize() {
const config = {
apiKey: "<KEY>",
authDomain: "cookietouch-52c0c.firebaseapp.com",
databaseURL: "https://cookietouch-52c0c.firebaseio.com",
messagingSenderId: "423749577733",
projectId: "cookietouch-52c0c",
storageBucket: "cookietouch-52c0c.appspot.com",
};
return firebase.initializeApp(config);
}
export async function signin(email: string, password: string): Promise<boolean> {
try {
await firebase.auth().signInWithEmailAndPassword(email, password);
return true;
} catch (error) {
return false;
}
}
export async function signout() {
await firebase.auth().signOut();
}
export async function signup(email: string, password: string): Promise<boolean> {
try {
await firebase.auth().createUserWithEmailAndPassword(email, password);
return true;
} catch (error) {
return false;
}
}
export function presence() {
firebase.auth().onAuthStateChanged((user) => {
// Fetch the current user's ID from Firebase Authentication.
const uid = firebase.auth().currentUser.uid;
// Create a reference to this user's specific status node.
// This is where we will store data about being online/offline.
const userStatusDatabaseRef = firebase.database().ref(`/status/${uid}`);
// We'll create two constants which we will write to
// the Realtime database when this device is offline
// or online.
const isOfflineForDatabase = {
last_changed: firebase.database.ServerValue.TIMESTAMP,
state: "offline",
};
const isOnlineForDatabase = {
last_changed: firebase.database.ServerValue.TIMESTAMP,
state: "online",
};
// Create a reference to the special '.info/connected' path in
// Realtime Database. This path returns `true` when connected
// and `false` when disconnected.
firebase.database().ref(".info/connected").on("value", (snapshot) => {
// If we're not currently connected, don't do anything.
if (snapshot.val() === false) {
return;
}
// If we are currently connected, then use the 'onDisconnect()'
// method to add a set which will only trigger once this
// client has disconnected by closing the app,
// losing internet, or any other means.
userStatusDatabaseRef.onDisconnect().set(isOfflineForDatabase).then(() => {
// The promise returned from .onDisconnect().set() will
// resolve as soon as the server acknowledges the onDisconnect()
// request, NOT once we've actually disconnected:
// https://firebase.google.com/docs/reference/js/firebase.database.OnDisconnect
// We can now safely set ourselves as 'online' knowing that the
// server will mark us as offline once we lose connection.
userStatusDatabaseRef.set(isOnlineForDatabase);
});
});
});
}
| 1.882813 | 2 |
src/components/FormSelectionContainer/FormSelectionContainer.tsx | gjj/document-creator-website | 0 | 2368 | import React, { FunctionComponent } from "react";
import { Redirect } from "react-router";
import { useConfigContext } from "../../common/context/config";
import { useFormsContext } from "../../common/context/forms";
import { NavigationBar } from "../NavigationBar";
import { FormSelection } from "./FormSelection";
export const FormSelectionContainer: FunctionComponent = () => {
const { config, setConfig } = useConfigContext();
const { setForms, setActiveFormIndex } = useFormsContext();
const logout = (): void => {
setForms([]);
setActiveFormIndex(undefined);
setConfig(undefined);
};
if (!config) {
return <Redirect to="/" />;
}
return (
<>
<NavigationBar logout={logout} />
<FormSelection config={config} />
</>
);
};
| 1.234375 | 1 |
showcase/src/modules/button.ts | csutorasa/UI-toolkit | 0 | 2376 | import { Component } from '@angular/core';
import { CreateTesterComponentData } from '../source';
@Component(CreateTesterComponentData('button'))
export class ButtonTesterComponent { }
@Component({
selector: 'button-test',
template: `<button>Basic</button>
<button buttonstyle="default">Default</button>
<button buttonstyle="primary">Primary</button>
<button buttonstyle="success">Success</button>
<button buttonstyle="info">Info</button>
<button buttonstyle="warning">Warning</button>
<button buttonstyle="danger">Danger</button>
<button buttonstyle="link">Link</button>`,
})
export class ButtonTestComponent {
} | 1.109375 | 1 |
common/poe.models.ts | mortefos/gear-finder | 5 | 2384 | export interface League {
endAt: string | null;
id: string;
startAt: string | null;
url: string;
}
export enum EquipmentSlotType {
Amulet = "Amulet",
Belt = "Belt",
BodyArmour = "BodyArmour",
Boots = "Boots",
Flask = "Flask",
Gloves = "Gloves",
Helm = "Helm",
MainInventory = "MainInventory",
Offhand = "Offhand",
Offhand2 = "Offhand2",
Ring = "Ring",
Ring2 = "Ring2",
Weapon = "Weapon",
Weapon2 = "Weapon2"
}
export interface CharacterEquipment {
Amulet?: Item;
Belt?: Item;
BodyArmour?: Item;
Boots?: Item;
Flask?: Item[];
Gloves?: Item;
Helm?: Item;
Offhand?: Item;
Offhand2?: Item;
Ring?: Item;
Ring2?: Item;
Weapon?: Item;
Weapon2?: Item;
}
export interface UserInfo {
username: string;
sessionId: string;
}
export interface Sockets {
group: number; // group id
attr: "S" | "I" | "D" | "G"; // S=Strength, I=Intelligence, D=Dexterity, G=white string
}
export interface Character {
name: string;
league: string;
classId: number;
ascendancyClass: number;
class: string;
level: number;
experience: number;
}
export interface Item {
verified: boolean;
w: number; // slot width
h: number; // slot height
ilvl: number; // item level
icon: string; // item picture art
league: string; // Standard / Hardcore /
id: string; // item id, will change if you use currency on it
sockets?: Sockets[]; // See below, array of sockets
name: string; // unique name
typeLine: string; // item base type, mixed with affix name for magic/ rare
identified: boolean;
corrupted: boolean;
lockedToCharacter: boolean; //
note: string;
properties: any[]; // See below
requirements: any[]; // See below
explicitMods: string[];
implicitMods: string[];
enchantMods: string[]; // labyrinth mods
craftedMods: string[]; // master mods
flavourText: string[];
frameType: number; // See below
x: number; // stash position x
y: number; // stash position y
inventoryId: string; // slot
socketedItems: any[]; // See items
additionalProperties: any[]; // See properties
secDescrText: string; // second description text
descrText: string; // description text
artFilename: string; // Divination Card
duplicated: boolean; //
maxStackSize: number; //
nextLevelRequirements: any[]; // See requirements
stackSize: number; //
talismanTier: number; //
utilityMods: string; // array flask utility mods
support: boolean; //
cosmeticMods: string; // array
prophecyDiffText: string; // prophecy difficulty text
prophecyText: string; //
isRelic: boolean; //
category: any[];
}
export interface LeagueData {
id: string;
text: string;
}
export interface Stat {
id: string;
text: string;
type: StatType;
}
export interface Stats {
entries: Stat[];
label: StatType;
}
export enum StatType {
Pseudo = "Pseudo",
Explicit = "Explicit",
Implicit = "Implicit",
Fractured = "Fractured",
Enchant = "Enchant",
Crafted = "Crafted",
Veiled = "Veiled",
Monster = "Monster",
Delve = "Delve"
}
export interface ItemModSearch extends Stat {
value: number;
regex: string;
}
export interface ItemMod {
type: StatType;
text: string;
}
| 1.375 | 1 |
src/core/permission/modules/sys/menu.ts | wsa-wsa/vue3 | 307 | 2392 | export const sysMenu = {
list: 'sys/menu/list',
add: 'sys/menu/add',
update: 'sys/menu/update',
info: 'sys/menu/info',
delete: 'sys/menu/delete',
} as const;
export const deptValues = Object.values(sysMenu);
export type SysMenuPerms = typeof deptValues[number];
export default sysMenu;
| 0.726563 | 1 |
packages/@azure/arm-network/lib/models/networkWatchersMappers.ts | mmacy/azure-sdk-for-js | 0 | 2400 | /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
export {
NetworkWatcher,
Resource,
BaseResource,
ErrorResponse,
ErrorDetails,
TagsObject,
NetworkWatcherListResult,
TopologyParameters,
SubResource,
Topology,
TopologyResource,
TopologyAssociation,
VerificationIPFlowParameters,
VerificationIPFlowResult,
NextHopParameters,
NextHopResult,
SecurityGroupViewParameters,
SecurityGroupViewResult,
SecurityGroupNetworkInterface,
SecurityRuleAssociations,
NetworkInterfaceAssociation,
SecurityRule,
ApplicationSecurityGroup,
SubnetAssociation,
EffectiveNetworkSecurityRule,
TroubleshootingParameters,
TroubleshootingResult,
TroubleshootingDetails,
TroubleshootingRecommendedActions,
QueryTroubleshootingParameters,
FlowLogInformation,
RetentionPolicyParameters,
TrafficAnalyticsProperties,
TrafficAnalyticsConfigurationProperties,
FlowLogStatusParameters,
ConnectivityParameters,
ConnectivitySource,
ConnectivityDestination,
ProtocolConfiguration,
HTTPConfiguration,
HTTPHeader,
ConnectivityInformation,
ConnectivityHop,
ConnectivityIssue,
AzureReachabilityReportParameters,
AzureReachabilityReportLocation,
AzureReachabilityReport,
AzureReachabilityReportItem,
AzureReachabilityReportLatencyInfo,
AvailableProvidersListParameters,
AvailableProvidersList,
AvailableProvidersListCountry,
AvailableProvidersListState,
AvailableProvidersListCity,
NetworkConfigurationDiagnosticParameters,
NetworkConfigurationDiagnosticProfile,
NetworkConfigurationDiagnosticResponse,
NetworkConfigurationDiagnosticResult,
NetworkSecurityGroupResult,
EvaluatedNetworkSecurityGroup,
MatchedRule,
NetworkSecurityRulesEvaluationResult,
NetworkInterfaceTapConfiguration,
VirtualNetworkTap,
NetworkInterfaceIPConfiguration,
ApplicationGatewayBackendAddressPool,
ApplicationGatewayBackendAddress,
BackendAddressPool,
InboundNatRule,
Subnet,
NetworkSecurityGroup,
NetworkInterface,
InterfaceEndpoint,
EndpointService,
NetworkInterfaceDnsSettings,
RouteTable,
Route,
ServiceEndpointPropertiesFormat,
ServiceEndpointPolicy,
ServiceEndpointPolicyDefinition,
IPConfiguration,
PublicIPAddress,
PublicIPAddressSku,
PublicIPAddressDnsSettings,
IpTag,
IPConfigurationProfile,
ResourceNavigationLink,
ServiceAssociationLink,
Delegation,
FrontendIPConfiguration,
ApplicationGatewayBackendHttpSettings,
ApplicationGatewayConnectionDraining,
ApplicationGatewayIPConfiguration,
ApplicationGatewayAuthenticationCertificate,
ApplicationGatewayTrustedRootCertificate,
ApplicationGatewaySslCertificate,
ApplicationGatewayFrontendIPConfiguration,
ApplicationGatewayFrontendPort,
ApplicationGatewayHttpListener,
ApplicationGatewayCustomError,
ApplicationGatewayPathRule,
ApplicationGatewayProbe,
ApplicationGatewayProbeHealthResponseMatch,
ApplicationGatewayRequestRoutingRule,
ApplicationGatewayRedirectConfiguration,
ApplicationGatewayUrlPathMap,
ApplicationGateway,
ApplicationGatewaySku,
ApplicationGatewaySslPolicy,
ApplicationGatewayWebApplicationFirewallConfiguration,
ApplicationGatewayFirewallDisabledRuleGroup,
ApplicationGatewayFirewallExclusion,
ApplicationGatewayAutoscaleConfiguration,
ApplicationGatewayFirewallRuleSet,
ApplicationGatewayFirewallRuleGroup,
ApplicationGatewayFirewallRule,
ApplicationGatewayAvailableSslOptions,
ApplicationGatewaySslPredefinedPolicy,
AzureFirewallIPConfiguration,
AzureFirewallApplicationRuleCollection,
AzureFirewallRCAction,
AzureFirewallApplicationRule,
AzureFirewallApplicationRuleProtocol,
AzureFirewallNatRuleCollection,
AzureFirewallNatRCAction,
AzureFirewallNatRule,
AzureFirewallNetworkRuleCollection,
AzureFirewallNetworkRule,
AzureFirewall,
AzureFirewallFqdnTag,
DdosProtectionPlan,
EndpointServiceResult,
ExpressRouteCircuitAuthorization,
RouteFilterRule,
ExpressRouteCircuitConnection,
ExpressRouteCircuitPeering,
ExpressRouteCircuitPeeringConfig,
ExpressRouteCircuitStats,
RouteFilter,
Ipv6ExpressRouteCircuitPeeringConfig,
ExpressRouteConnectionId,
ExpressRouteCircuit,
ExpressRouteCircuitSku,
ExpressRouteCircuitServiceProviderProperties,
ExpressRouteServiceProvider,
ExpressRouteServiceProviderBandwidthsOffered,
ExpressRouteCrossConnectionPeering,
ExpressRouteCrossConnection,
ExpressRouteCircuitReference,
ExpressRouteConnection,
ExpressRouteCircuitPeeringId,
ExpressRouteGateway,
ExpressRouteGatewayPropertiesAutoScaleConfiguration,
ExpressRouteGatewayPropertiesAutoScaleConfigurationBounds,
VirtualHubId,
ExpressRoutePortsLocation,
ExpressRoutePortsLocationBandwidths,
ExpressRouteLink,
ExpressRoutePort,
LoadBalancingRule,
Probe,
InboundNatPool,
OutboundRule,
LoadBalancer,
LoadBalancerSku,
ContainerNetworkInterfaceConfiguration,
ContainerNetworkInterface,
Container,
ContainerNetworkInterfaceIpConfiguration,
NetworkProfile,
ConnectionMonitorResult,
ConnectionMonitorSource,
ConnectionMonitorDestination,
PublicIPPrefix,
PublicIPPrefixSku,
ReferencedPublicIpAddress,
PatchRouteFilterRule,
PatchRouteFilter,
BgpServiceCommunity,
BGPCommunity,
VirtualNetworkPeering,
AddressSpace,
VirtualNetwork,
DhcpOptions,
VirtualNetworkGatewayIPConfiguration,
VpnClientRootCertificate,
VpnClientRevokedCertificate,
VirtualNetworkGateway,
VirtualNetworkGatewaySku,
VpnClientConfiguration,
IpsecPolicy,
BgpSettings,
LocalNetworkGateway,
VirtualNetworkGatewayConnection,
TunnelConnectionHealth,
ConnectionSharedKey,
VirtualNetworkGatewayConnectionListEntity,
VirtualNetworkConnectionGatewayReference,
P2SVpnServerConfigVpnClientRootCertificate,
P2SVpnServerConfigVpnClientRevokedCertificate,
P2SVpnServerConfigRadiusServerRootCertificate,
P2SVpnServerConfigRadiusClientRootCertificate,
P2SVpnServerConfiguration,
VirtualWAN,
VpnSite,
DeviceProperties,
HubVirtualNetworkConnection,
VirtualHub,
VirtualHubRouteTable,
VirtualHubRoute,
VpnConnection,
VpnGateway,
P2SVpnGateway,
VpnClientConnectionHealth
} from "../models/mappers";
| 0.310547 | 0 |