file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
subcontractOperationDefinitionForm.component.ts | import { Component, ViewEncapsulation, Input } from '@angular/core';
import { Subscription } from 'rxjs/Subscription';
import { ActivatedRoute, Params, Router } from '@angular/router';
import {
FormGroup,
AbstractControl,
FormBuilder,
Validators
} from '@angular/forms';
import { SharedService } from '../../../../services/shared.service';
import { SubcontractOperationDefinitionService } from '../../subcontractOperationDefinition.service';
import { ItemService } from '../../../item/item.service';
import 'rxjs/add/operator/take';
import { ProductTypeService } from '../../../productType/productType.service';
import { OperationTypeService } from '../../../operationType/operationType.service';
@Component({
selector: 'subcontract-operation-definition-form',
encapsulation: ViewEncapsulation.None,
styleUrls: ['./subcontractOperationDefinitionForm.scss'],
templateUrl: './subcontractOperationDefinitionForm.html'
})
export class SubcontractOperationDefinitionForm {
JSON: any = JSON;
public formGroup: FormGroup;
subcontractOperationDefinition: any = {};
subscription: Subscription;
itemList = [];
item: any;
subcontractOperationDefinitionType: any;
operationType: any;
productType: any;
productTypeList = [];
operationTypeList = [];
constructor(
protected service: SubcontractOperationDefinitionService,
private route: ActivatedRoute,
private router: Router,
fb: FormBuilder,
private itemService: ItemService,
private productTypeService: ProductTypeService,
private operationTypeService: OperationTypeService,
private sharedService: SharedService
) {
this.formGroup = fb.group({
id: '',
description: '',
item: [this.item, Validators.required],
operationType: [this.operationType, Validators.required],
productType: [this.productType, Validators.required]
});
}
getItemList(): void {
this.itemService
.getCombo()
.subscribe(itemList => (this.itemList = itemList));
}
getProductTypeList(): void {
this.productTypeService
.getCombo()
.subscribe(productTypeList => (this.productTypeList = productTypeList));
}
getOperationTypeList(): void {
this.operationTypeService
.getCombo()
.subscribe(
operationTypeList => (this.operationTypeList = operationTypeList)
);
}
ngOnInit(): void {
this.getItemList();
this.getOperationTypeList();
this.getProductTypeList();
this.route.params.subscribe((params: Params) => {
let id = params['id'];
id = id === undefined ? '0' : id;
if (id !== '0') {
this.service
.get(+id)
.take(1)
.subscribe(data => {
this.loadForm(data);
});
}
});
}
refresh(): void {
this.getItemList();
this.getOperationTypeList();
this.getProductTypeList();
}
loadForm(data: any) {
if (data != null) {
this.subcontractOperationDefinition = data;
}
this.formGroup.patchValue(this.subcontractOperationDefinition, {
onlySelf: true
});
this.item = this.subcontractOperationDefinition.item;
}
public onSubmit(values: any, event: Event): void {
event.preventDefault();
console.log(values);
this.service.save(values).subscribe(data => {
this.sharedService.addMessage({
severity: 'info',
summary: 'Success',
detail: 'Operation Success'
});
this.resetForm();
this.router.navigate(['/pages/subcontractOperationDefinition/form/']);
});
}
public resetForm() {
this.formGroup.reset();
}
/*================== ItemFilter ===================*/
filteredItemList: any[];
filterItemList(event) {
let query = event.query.toLowerCase();
this.filteredItemList = [];
for (let i = 0; i < this.itemList.length; i++) {
let item = this.itemList[i];
if (item.display.toLowerCase().indexOf(query) >= 0) {
this.filteredItemList.push(item);
}
}
}
onItemSelect(event: any) {}
/*================== ItemFilter ===================*/
/*================== OperationTypeFilter ===================*/
filteredOperationTypeList: any[];
filterOperationTypeList(event) {
let query = event.query.toLowerCase();
this.filteredOperationTypeList = [];
for (let i = 0; i < this.operationTypeList.length; i++) {
let operationType = this.operationTypeList[i];
if (operationType.display.toLowerCase().indexOf(query) >= 0) {
this.filteredOperationTypeList.push(operationType);
}
}
}
onOperationTypeSelect(event: any) {}
/*================== OperationTypeFilter ===================*/
/*================== ProductTypeFilter ===================*/
filteredProductTypeList: any[];
filterProductTypeList(event) {
let query = event.query.toLowerCase();
this.filteredProductTypeList = [];
for (let i = 0; i < this.productTypeList.length; i++) {
let productType = this.productTypeList[i];
if (productType.display.toLowerCase().indexOf(query) >= 0) {
this.filteredProductTypeList.push(productType);
}
}
}
| (event: any) {}
/*================== ProductTypeFilter ===================*/
}
| onProductTypeSelect | identifier_name |
subcontractOperationDefinitionForm.component.ts | import { Component, ViewEncapsulation, Input } from '@angular/core';
import { Subscription } from 'rxjs/Subscription';
import { ActivatedRoute, Params, Router } from '@angular/router';
import {
FormGroup,
AbstractControl,
FormBuilder,
Validators
} from '@angular/forms';
import { SharedService } from '../../../../services/shared.service';
import { SubcontractOperationDefinitionService } from '../../subcontractOperationDefinition.service';
import { ItemService } from '../../../item/item.service';
import 'rxjs/add/operator/take';
import { ProductTypeService } from '../../../productType/productType.service';
import { OperationTypeService } from '../../../operationType/operationType.service';
@Component({
selector: 'subcontract-operation-definition-form',
encapsulation: ViewEncapsulation.None,
styleUrls: ['./subcontractOperationDefinitionForm.scss'],
templateUrl: './subcontractOperationDefinitionForm.html'
})
export class SubcontractOperationDefinitionForm {
JSON: any = JSON;
public formGroup: FormGroup;
subcontractOperationDefinition: any = {};
subscription: Subscription;
itemList = [];
item: any;
subcontractOperationDefinitionType: any;
operationType: any;
productType: any;
productTypeList = [];
operationTypeList = [];
constructor(
protected service: SubcontractOperationDefinitionService,
private route: ActivatedRoute,
private router: Router,
fb: FormBuilder,
private itemService: ItemService,
private productTypeService: ProductTypeService,
private operationTypeService: OperationTypeService,
private sharedService: SharedService
) {
this.formGroup = fb.group({
id: '',
description: '',
item: [this.item, Validators.required],
operationType: [this.operationType, Validators.required],
productType: [this.productType, Validators.required]
});
}
getItemList(): void |
getProductTypeList(): void {
this.productTypeService
.getCombo()
.subscribe(productTypeList => (this.productTypeList = productTypeList));
}
getOperationTypeList(): void {
this.operationTypeService
.getCombo()
.subscribe(
operationTypeList => (this.operationTypeList = operationTypeList)
);
}
ngOnInit(): void {
this.getItemList();
this.getOperationTypeList();
this.getProductTypeList();
this.route.params.subscribe((params: Params) => {
let id = params['id'];
id = id === undefined ? '0' : id;
if (id !== '0') {
this.service
.get(+id)
.take(1)
.subscribe(data => {
this.loadForm(data);
});
}
});
}
refresh(): void {
this.getItemList();
this.getOperationTypeList();
this.getProductTypeList();
}
loadForm(data: any) {
if (data != null) {
this.subcontractOperationDefinition = data;
}
this.formGroup.patchValue(this.subcontractOperationDefinition, {
onlySelf: true
});
this.item = this.subcontractOperationDefinition.item;
}
public onSubmit(values: any, event: Event): void {
event.preventDefault();
console.log(values);
this.service.save(values).subscribe(data => {
this.sharedService.addMessage({
severity: 'info',
summary: 'Success',
detail: 'Operation Success'
});
this.resetForm();
this.router.navigate(['/pages/subcontractOperationDefinition/form/']);
});
}
public resetForm() {
this.formGroup.reset();
}
/*================== ItemFilter ===================*/
filteredItemList: any[];
filterItemList(event) {
let query = event.query.toLowerCase();
this.filteredItemList = [];
for (let i = 0; i < this.itemList.length; i++) {
let item = this.itemList[i];
if (item.display.toLowerCase().indexOf(query) >= 0) {
this.filteredItemList.push(item);
}
}
}
onItemSelect(event: any) {}
/*================== ItemFilter ===================*/
/*================== OperationTypeFilter ===================*/
filteredOperationTypeList: any[];
filterOperationTypeList(event) {
let query = event.query.toLowerCase();
this.filteredOperationTypeList = [];
for (let i = 0; i < this.operationTypeList.length; i++) {
let operationType = this.operationTypeList[i];
if (operationType.display.toLowerCase().indexOf(query) >= 0) {
this.filteredOperationTypeList.push(operationType);
}
}
}
onOperationTypeSelect(event: any) {}
/*================== OperationTypeFilter ===================*/
/*================== ProductTypeFilter ===================*/
filteredProductTypeList: any[];
filterProductTypeList(event) {
let query = event.query.toLowerCase();
this.filteredProductTypeList = [];
for (let i = 0; i < this.productTypeList.length; i++) {
let productType = this.productTypeList[i];
if (productType.display.toLowerCase().indexOf(query) >= 0) {
this.filteredProductTypeList.push(productType);
}
}
}
onProductTypeSelect(event: any) {}
/*================== ProductTypeFilter ===================*/
}
| {
this.itemService
.getCombo()
.subscribe(itemList => (this.itemList = itemList));
} | identifier_body |
subcontractOperationDefinitionForm.component.ts | import { Component, ViewEncapsulation, Input } from '@angular/core';
import { Subscription } from 'rxjs/Subscription';
import { ActivatedRoute, Params, Router } from '@angular/router';
import {
FormGroup,
AbstractControl,
FormBuilder,
Validators
} from '@angular/forms';
import { SharedService } from '../../../../services/shared.service';
import { SubcontractOperationDefinitionService } from '../../subcontractOperationDefinition.service';
import { ItemService } from '../../../item/item.service';
import 'rxjs/add/operator/take';
import { ProductTypeService } from '../../../productType/productType.service';
import { OperationTypeService } from '../../../operationType/operationType.service';
@Component({
selector: 'subcontract-operation-definition-form',
encapsulation: ViewEncapsulation.None,
styleUrls: ['./subcontractOperationDefinitionForm.scss'],
templateUrl: './subcontractOperationDefinitionForm.html'
})
export class SubcontractOperationDefinitionForm {
JSON: any = JSON;
public formGroup: FormGroup;
subcontractOperationDefinition: any = {};
subscription: Subscription;
itemList = [];
item: any;
subcontractOperationDefinitionType: any;
operationType: any;
productType: any;
productTypeList = [];
operationTypeList = [];
constructor(
protected service: SubcontractOperationDefinitionService,
private route: ActivatedRoute,
private router: Router,
fb: FormBuilder,
private itemService: ItemService,
private productTypeService: ProductTypeService,
private operationTypeService: OperationTypeService,
private sharedService: SharedService
) {
this.formGroup = fb.group({
id: '',
description: '',
item: [this.item, Validators.required],
operationType: [this.operationType, Validators.required],
productType: [this.productType, Validators.required]
});
}
getItemList(): void {
this.itemService
.getCombo()
.subscribe(itemList => (this.itemList = itemList));
}
getProductTypeList(): void {
this.productTypeService
.getCombo()
.subscribe(productTypeList => (this.productTypeList = productTypeList));
}
getOperationTypeList(): void {
this.operationTypeService
.getCombo()
.subscribe(
operationTypeList => (this.operationTypeList = operationTypeList)
);
}
ngOnInit(): void {
this.getItemList();
this.getOperationTypeList();
this.getProductTypeList();
this.route.params.subscribe((params: Params) => {
let id = params['id'];
id = id === undefined ? '0' : id;
if (id !== '0') {
this.service
.get(+id)
.take(1)
.subscribe(data => {
this.loadForm(data);
});
}
});
}
refresh(): void {
this.getItemList();
this.getOperationTypeList();
this.getProductTypeList();
}
loadForm(data: any) {
if (data != null) {
this.subcontractOperationDefinition = data;
}
this.formGroup.patchValue(this.subcontractOperationDefinition, {
onlySelf: true
});
this.item = this.subcontractOperationDefinition.item;
}
public onSubmit(values: any, event: Event): void {
event.preventDefault();
console.log(values);
this.service.save(values).subscribe(data => {
this.sharedService.addMessage({
severity: 'info',
summary: 'Success',
detail: 'Operation Success'
});
this.resetForm();
this.router.navigate(['/pages/subcontractOperationDefinition/form/']);
});
}
public resetForm() {
this.formGroup.reset();
}
/*================== ItemFilter ===================*/ | filteredItemList: any[];
filterItemList(event) {
let query = event.query.toLowerCase();
this.filteredItemList = [];
for (let i = 0; i < this.itemList.length; i++) {
let item = this.itemList[i];
if (item.display.toLowerCase().indexOf(query) >= 0) {
this.filteredItemList.push(item);
}
}
}
onItemSelect(event: any) {}
/*================== ItemFilter ===================*/
/*================== OperationTypeFilter ===================*/
filteredOperationTypeList: any[];
filterOperationTypeList(event) {
let query = event.query.toLowerCase();
this.filteredOperationTypeList = [];
for (let i = 0; i < this.operationTypeList.length; i++) {
let operationType = this.operationTypeList[i];
if (operationType.display.toLowerCase().indexOf(query) >= 0) {
this.filteredOperationTypeList.push(operationType);
}
}
}
onOperationTypeSelect(event: any) {}
/*================== OperationTypeFilter ===================*/
/*================== ProductTypeFilter ===================*/
filteredProductTypeList: any[];
filterProductTypeList(event) {
let query = event.query.toLowerCase();
this.filteredProductTypeList = [];
for (let i = 0; i < this.productTypeList.length; i++) {
let productType = this.productTypeList[i];
if (productType.display.toLowerCase().indexOf(query) >= 0) {
this.filteredProductTypeList.push(productType);
}
}
}
onProductTypeSelect(event: any) {}
/*================== ProductTypeFilter ===================*/
} | random_line_split | |
v1.ts | /**
* Copyright 2015 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* jshint maxlen: false */
import createAPIRequest from '../../lib/apirequest';
/**
* Google Cloud Speech API
*
* Converts audio to text by applying powerful neural network models.
*
* @example
* const google = require('googleapis');
* const speech = google.speech('v1');
*
* @namespace speech
* @type {Function}
* @version v1
* @variation v1
* @param {object=} options Options for Speech
*/
function Speech(options) { // eslint-disable-line
const self = this;
self._options = options || {};
self.operations = {
/**
* speech.operations.cancel
*
* @desc Starts asynchronous cancellation on a long-running operation. The server makes a best effort to cancel the operation, but success is not guaranteed. If the server doesn't support this method, it returns `google.rpc.Code.UNIMPLEMENTED`. Clients can use Operations.GetOperation or other methods to check whether the cancellation succeeded or whether the operation completed despite cancellation. On successful cancellation, the operation is not deleted; instead, it becomes an operation with an Operation.error value with a google.rpc.Status.code of 1, corresponding to `Code.CANCELLED`.
*
* @alias speech.operations.cancel
* @memberOf! speech(v1)
*
* @param {object} params Parameters for request
* @param {string} params.name The name of the operation resource to be cancelled.
* @param {speech(v1).CancelOperationRequest} params.resource Request body data
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
cancel: function (params, options, callback) {
if (typeof options === 'function') {
callback = options; | options = {};
}
options || (options = {});
const rootUrl = options.rootUrl || 'https://speech.googleapis.com/';
const parameters = {
options: Object.assign({
url: (rootUrl + '/v1/operations/{name}:cancel').replace(/([^:]\/)\/+/g, '$1'),
method: 'POST'
}, options),
params: params,
requiredParams: ['name'],
pathParams: ['name'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* speech.operations.delete
*
* @desc Deletes a long-running operation. This method indicates that the client is no longer interested in the operation result. It does not cancel the operation. If the server doesn't support this method, it returns `google.rpc.Code.UNIMPLEMENTED`.
*
* @alias speech.operations.delete
* @memberOf! speech(v1)
*
* @param {object} params Parameters for request
* @param {string} params.name The name of the operation resource to be deleted.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
delete: function (params, options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
options || (options = {});
const rootUrl = options.rootUrl || 'https://speech.googleapis.com/';
const parameters = {
options: Object.assign({
url: (rootUrl + '/v1/operations/{name}').replace(/([^:]\/)\/+/g, '$1'),
method: 'DELETE'
}, options),
params: params,
requiredParams: ['name'],
pathParams: ['name'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* speech.operations.get
*
* @desc Gets the latest state of a long-running operation. Clients can use this method to poll the operation result at intervals as recommended by the API service.
*
* @alias speech.operations.get
* @memberOf! speech(v1)
*
* @param {object} params Parameters for request
* @param {string} params.name The name of the operation resource.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
get: function (params, options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
options || (options = {});
const rootUrl = options.rootUrl || 'https://speech.googleapis.com/';
const parameters = {
options: Object.assign({
url: (rootUrl + '/v1/operations/{name}').replace(/([^:]\/)\/+/g, '$1'),
method: 'GET'
}, options),
params: params,
requiredParams: ['name'],
pathParams: ['name'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* speech.operations.list
*
* @desc Lists operations that match the specified filter in the request. If the server doesn't support this method, it returns `UNIMPLEMENTED`. NOTE: the `name` binding allows API services to override the binding to use different resource name schemes, such as `users/x/operations`. To override the binding, API services can add a binding such as `"/v1/{name=users/x}/operations"` to their service configuration. For backwards compatibility, the default name includes the operations collection id, however overriding users must ensure the name binding is the parent resource, without the operations collection id.
*
* @alias speech.operations.list
* @memberOf! speech(v1)
*
* @param {object} params Parameters for request
* @param {string=} params.filter The standard list filter.
* @param {string=} params.name The name of the operation's parent resource.
* @param {integer=} params.pageSize The standard list page size.
* @param {string=} params.pageToken The standard list page token.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
list: function (params, options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
options || (options = {});
const rootUrl = options.rootUrl || 'https://speech.googleapis.com/';
const parameters = {
options: Object.assign({
url: (rootUrl + '/v1/operations').replace(/([^:]\/)\/+/g, '$1'),
method: 'GET'
}, options),
params: params,
requiredParams: [],
pathParams: [],
context: self
};
return createAPIRequest(parameters, callback);
}
};
self.speech = {
/**
* speech.speech.longrunningrecognize
*
* @desc Performs asynchronous speech recognition: receive results via the google.longrunning.Operations interface. Returns either an `Operation.error` or an `Operation.response` which contains a `LongRunningRecognizeResponse` message.
*
* @alias speech.speech.longrunningrecognize
* @memberOf! speech(v1)
*
* @param {object} params Parameters for request
* @param {speech(v1).LongRunningRecognizeRequest} params.resource Request body data
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
longrunningrecognize: function (params, options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
options || (options = {});
const rootUrl = options.rootUrl || 'https://speech.googleapis.com/';
const parameters = {
options: Object.assign({
url: (rootUrl + '/v1/speech:longrunningrecognize').replace(/([^:]\/)\/+/g, '$1'),
method: 'POST'
}, options),
params: params,
requiredParams: [],
pathParams: [],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* speech.speech.recognize
*
* @desc Performs synchronous speech recognition: receive results after all audio has been sent and processed.
*
* @alias speech.speech.recognize
* @memberOf! speech(v1)
*
* @param {object} params Parameters for request
* @param {speech(v1).RecognizeRequest} params.resource Request body data
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
recognize: function (params, options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
options || (options = {});
const rootUrl = options.rootUrl || 'https://speech.googleapis.com/';
const parameters = {
options: Object.assign({
url: (rootUrl + '/v1/speech:recognize').replace(/([^:]\/)\/+/g, '$1'),
method: 'POST'
}, options),
params: params,
requiredParams: [],
pathParams: [],
context: self
};
return createAPIRequest(parameters, callback);
}
};
}
/**
* @typedef CancelOperationRequest
* @memberOf! speech(v1)
* @type object
*/
/**
* @typedef Empty
* @memberOf! speech(v1)
* @type object
*/
/**
* @typedef ListOperationsResponse
* @memberOf! speech(v1)
* @type object
* @property {string} nextPageToken The standard List next-page token.
* @property {speech(v1).Operation[]} operations A list of operations that matches the specified filter in the request.
*/
/**
* @typedef LongRunningRecognizeRequest
* @memberOf! speech(v1)
* @type object
* @property {speech(v1).RecognitionAudio} audio *Required* The audio data to be recognized.
* @property {speech(v1).RecognitionConfig} config *Required* Provides information to the recognizer that specifies how to
process the request.
*/
/**
* @typedef Operation
* @memberOf! speech(v1)
* @type object
* @property {boolean} done If the value is `false`, it means the operation is still in progress.
If `true`, the operation is completed, and either `error` or `response` is
available.
* @property {speech(v1).Status} error The error result of the operation in case of failure or cancellation.
* @property {object} metadata Service-specific metadata associated with the operation. It typically
contains progress information and common metadata such as create time.
Some services might not provide such metadata. Any method that returns a
long-running operation should document the metadata type, if any.
* @property {string} name The server-assigned name, which is only unique within the same service that
originally returns it. If you use the default HTTP mapping, the
`name` should have the format of `operations/some/unique/name`.
* @property {object} response The normal response of the operation in case of success. If the original
method returns no data on success, such as `Delete`, the response is
`google.protobuf.Empty`. If the original method is standard
`Get`/`Create`/`Update`, the response should be the resource. For other
methods, the response should have the type `XxxResponse`, where `Xxx`
is the original method name. For example, if the original method name
is `TakeSnapshot()`, the inferred response type is
`TakeSnapshotResponse`.
*/
/**
* @typedef RecognitionAudio
* @memberOf! speech(v1)
* @type object
* @property {string} content The audio data bytes encoded as specified in
`RecognitionConfig`. Note: as with all bytes fields, protobuffers use a
pure binary representation, whereas JSON representations use base64.
* @property {string} uri URI that points to a file that contains audio data bytes as specified in
`RecognitionConfig`. Currently, only Google Cloud Storage URIs are
supported, which must be specified in the following format:
`gs://bucket_name/object_name` (other URI formats return
google.rpc.Code.INVALID_ARGUMENT). For more information, see
[Request URIs](https://cloud.google.com/storage/docs/reference-uris).
*/
/**
* @typedef RecognitionConfig
* @memberOf! speech(v1)
* @type object
* @property {boolean} enableWordTimeOffsets *Optional* If `true`, the top result includes a list of words and
the start and end time offsets (timestamps) for those words. If
`false`, no word-level time offset information is returned. The default is
`false`.
* @property {string} encoding *Required* Encoding of audio data sent in all `RecognitionAudio` messages.
* @property {string} languageCode *Required* The language of the supplied audio as a
[BCP-47](https://www.rfc-editor.org/rfc/bcp/bcp47.txt) language tag.
Example: "en-US".
See [Language Support](https://cloud.google.com/speech/docs/languages)
for a list of the currently supported language codes.
* @property {integer} maxAlternatives *Optional* Maximum number of recognition hypotheses to be returned.
Specifically, the maximum number of `SpeechRecognitionAlternative` messages
within each `SpeechRecognitionResult`.
The server may return fewer than `max_alternatives`.
Valid values are `0`-`30`. A value of `0` or `1` will return a maximum of
one. If omitted, will return a maximum of one.
* @property {boolean} profanityFilter *Optional* If set to `true`, the server will attempt to filter out
profanities, replacing all but the initial character in each filtered word
with asterisks, e.g. "f***". If set to `false` or omitted, profanities
won't be filtered out.
* @property {integer} sampleRateHertz *Required* Sample rate in Hertz of the audio data sent in all
`RecognitionAudio` messages. Valid values are: 8000-48000.
16000 is optimal. For best results, set the sampling rate of the audio
source to 16000 Hz. If that's not possible, use the native sample rate of
the audio source (instead of re-sampling).
* @property {speech(v1).SpeechContext[]} speechContexts *Optional* A means to provide context to assist the speech recognition.
*/
/**
* @typedef RecognizeRequest
* @memberOf! speech(v1)
* @type object
* @property {speech(v1).RecognitionAudio} audio *Required* The audio data to be recognized.
* @property {speech(v1).RecognitionConfig} config *Required* Provides information to the recognizer that specifies how to
process the request.
*/
/**
* @typedef RecognizeResponse
* @memberOf! speech(v1)
* @type object
* @property {speech(v1).SpeechRecognitionResult[]} results *Output-only* Sequential list of transcription results corresponding to
sequential portions of audio.
*/
/**
* @typedef SpeechContext
* @memberOf! speech(v1)
* @type object
* @property {string[]} phrases *Optional* A list of strings containing words and phrases "hints" so that
the speech recognition is more likely to recognize them. This can be used
to improve the accuracy for specific words and phrases, for example, if
specific commands are typically spoken by the user. This can also be used
to add additional words to the vocabulary of the recognizer. See
[usage limits](https://cloud.google.com/speech/limits#content).
*/
/**
* @typedef SpeechRecognitionAlternative
* @memberOf! speech(v1)
* @type object
* @property {number} confidence *Output-only* The confidence estimate between 0.0 and 1.0. A higher number
indicates an estimated greater likelihood that the recognized words are
correct. This field is typically provided only for the top hypothesis, and
only for `is_final=true` results. Clients should not rely on the
`confidence` field as it is not guaranteed to be accurate or consistent.
The default of 0.0 is a sentinel value indicating `confidence` was not set.
* @property {string} transcript *Output-only* Transcript text representing the words that the user spoke.
* @property {speech(v1).WordInfo[]} words *Output-only* A list of word-specific information for each recognized word.
*/
/**
* @typedef SpeechRecognitionResult
* @memberOf! speech(v1)
* @type object
* @property {speech(v1).SpeechRecognitionAlternative[]} alternatives *Output-only* May contain one or more recognition hypotheses (up to the
maximum specified in `max_alternatives`).
These alternatives are ordered in terms of accuracy, with the top (first)
alternative being the most probable, as ranked by the recognizer.
*/
/**
* @typedef Status
* @memberOf! speech(v1)
* @type object
* @property {integer} code The status code, which should be an enum value of google.rpc.Code.
* @property {object[]} details A list of messages that carry the error details. There is a common set of
message types for APIs to use.
* @property {string} message A developer-facing error message, which should be in English. Any
user-facing error message should be localized and sent in the
google.rpc.Status.details field, or localized by the client.
*/
/**
* @typedef WordInfo
* @memberOf! speech(v1)
* @type object
* @property {string} endTime *Output-only* Time offset relative to the beginning of the audio,
and corresponding to the end of the spoken word.
This field is only set if `enable_word_time_offsets=true` and only
in the top hypothesis.
This is an experimental feature and the accuracy of the time offset can
vary.
* @property {string} startTime *Output-only* Time offset relative to the beginning of the audio,
and corresponding to the start of the spoken word.
This field is only set if `enable_word_time_offsets=true` and only
in the top hypothesis.
This is an experimental feature and the accuracy of the time offset can
vary.
* @property {string} word *Output-only* The word corresponding to this set of information.
*/
export = Speech; | random_line_split | |
v1.ts | /**
* Copyright 2015 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* jshint maxlen: false */
import createAPIRequest from '../../lib/apirequest';
/**
* Google Cloud Speech API
*
* Converts audio to text by applying powerful neural network models.
*
* @example
* const google = require('googleapis');
* const speech = google.speech('v1');
*
* @namespace speech
* @type {Function}
* @version v1
* @variation v1
* @param {object=} options Options for Speech
*/
function | (options) { // eslint-disable-line
const self = this;
self._options = options || {};
self.operations = {
/**
* speech.operations.cancel
*
* @desc Starts asynchronous cancellation on a long-running operation. The server makes a best effort to cancel the operation, but success is not guaranteed. If the server doesn't support this method, it returns `google.rpc.Code.UNIMPLEMENTED`. Clients can use Operations.GetOperation or other methods to check whether the cancellation succeeded or whether the operation completed despite cancellation. On successful cancellation, the operation is not deleted; instead, it becomes an operation with an Operation.error value with a google.rpc.Status.code of 1, corresponding to `Code.CANCELLED`.
*
* @alias speech.operations.cancel
* @memberOf! speech(v1)
*
* @param {object} params Parameters for request
* @param {string} params.name The name of the operation resource to be cancelled.
* @param {speech(v1).CancelOperationRequest} params.resource Request body data
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
cancel: function (params, options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
options || (options = {});
const rootUrl = options.rootUrl || 'https://speech.googleapis.com/';
const parameters = {
options: Object.assign({
url: (rootUrl + '/v1/operations/{name}:cancel').replace(/([^:]\/)\/+/g, '$1'),
method: 'POST'
}, options),
params: params,
requiredParams: ['name'],
pathParams: ['name'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* speech.operations.delete
*
* @desc Deletes a long-running operation. This method indicates that the client is no longer interested in the operation result. It does not cancel the operation. If the server doesn't support this method, it returns `google.rpc.Code.UNIMPLEMENTED`.
*
* @alias speech.operations.delete
* @memberOf! speech(v1)
*
* @param {object} params Parameters for request
* @param {string} params.name The name of the operation resource to be deleted.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
delete: function (params, options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
options || (options = {});
const rootUrl = options.rootUrl || 'https://speech.googleapis.com/';
const parameters = {
options: Object.assign({
url: (rootUrl + '/v1/operations/{name}').replace(/([^:]\/)\/+/g, '$1'),
method: 'DELETE'
}, options),
params: params,
requiredParams: ['name'],
pathParams: ['name'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* speech.operations.get
*
* @desc Gets the latest state of a long-running operation. Clients can use this method to poll the operation result at intervals as recommended by the API service.
*
* @alias speech.operations.get
* @memberOf! speech(v1)
*
* @param {object} params Parameters for request
* @param {string} params.name The name of the operation resource.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
get: function (params, options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
options || (options = {});
const rootUrl = options.rootUrl || 'https://speech.googleapis.com/';
const parameters = {
options: Object.assign({
url: (rootUrl + '/v1/operations/{name}').replace(/([^:]\/)\/+/g, '$1'),
method: 'GET'
}, options),
params: params,
requiredParams: ['name'],
pathParams: ['name'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* speech.operations.list
*
* @desc Lists operations that match the specified filter in the request. If the server doesn't support this method, it returns `UNIMPLEMENTED`. NOTE: the `name` binding allows API services to override the binding to use different resource name schemes, such as `users/x/operations`. To override the binding, API services can add a binding such as `"/v1/{name=users/x}/operations"` to their service configuration. For backwards compatibility, the default name includes the operations collection id, however overriding users must ensure the name binding is the parent resource, without the operations collection id.
*
* @alias speech.operations.list
* @memberOf! speech(v1)
*
* @param {object} params Parameters for request
* @param {string=} params.filter The standard list filter.
* @param {string=} params.name The name of the operation's parent resource.
* @param {integer=} params.pageSize The standard list page size.
* @param {string=} params.pageToken The standard list page token.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
list: function (params, options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
options || (options = {});
const rootUrl = options.rootUrl || 'https://speech.googleapis.com/';
const parameters = {
options: Object.assign({
url: (rootUrl + '/v1/operations').replace(/([^:]\/)\/+/g, '$1'),
method: 'GET'
}, options),
params: params,
requiredParams: [],
pathParams: [],
context: self
};
return createAPIRequest(parameters, callback);
}
};
self.speech = {
/**
* speech.speech.longrunningrecognize
*
* @desc Performs asynchronous speech recognition: receive results via the google.longrunning.Operations interface. Returns either an `Operation.error` or an `Operation.response` which contains a `LongRunningRecognizeResponse` message.
*
* @alias speech.speech.longrunningrecognize
* @memberOf! speech(v1)
*
* @param {object} params Parameters for request
* @param {speech(v1).LongRunningRecognizeRequest} params.resource Request body data
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
longrunningrecognize: function (params, options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
options || (options = {});
const rootUrl = options.rootUrl || 'https://speech.googleapis.com/';
const parameters = {
options: Object.assign({
url: (rootUrl + '/v1/speech:longrunningrecognize').replace(/([^:]\/)\/+/g, '$1'),
method: 'POST'
}, options),
params: params,
requiredParams: [],
pathParams: [],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* speech.speech.recognize
*
* @desc Performs synchronous speech recognition: receive results after all audio has been sent and processed.
*
* @alias speech.speech.recognize
* @memberOf! speech(v1)
*
* @param {object} params Parameters for request
* @param {speech(v1).RecognizeRequest} params.resource Request body data
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
recognize: function (params, options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
options || (options = {});
const rootUrl = options.rootUrl || 'https://speech.googleapis.com/';
const parameters = {
options: Object.assign({
url: (rootUrl + '/v1/speech:recognize').replace(/([^:]\/)\/+/g, '$1'),
method: 'POST'
}, options),
params: params,
requiredParams: [],
pathParams: [],
context: self
};
return createAPIRequest(parameters, callback);
}
};
}
/**
* @typedef CancelOperationRequest
* @memberOf! speech(v1)
* @type object
*/
/**
* @typedef Empty
* @memberOf! speech(v1)
* @type object
*/
/**
* @typedef ListOperationsResponse
* @memberOf! speech(v1)
* @type object
* @property {string} nextPageToken The standard List next-page token.
* @property {speech(v1).Operation[]} operations A list of operations that matches the specified filter in the request.
*/
/**
* @typedef LongRunningRecognizeRequest
* @memberOf! speech(v1)
* @type object
* @property {speech(v1).RecognitionAudio} audio *Required* The audio data to be recognized.
* @property {speech(v1).RecognitionConfig} config *Required* Provides information to the recognizer that specifies how to
process the request.
*/
/**
* @typedef Operation
* @memberOf! speech(v1)
* @type object
* @property {boolean} done If the value is `false`, it means the operation is still in progress.
If `true`, the operation is completed, and either `error` or `response` is
available.
* @property {speech(v1).Status} error The error result of the operation in case of failure or cancellation.
* @property {object} metadata Service-specific metadata associated with the operation. It typically
contains progress information and common metadata such as create time.
Some services might not provide such metadata. Any method that returns a
long-running operation should document the metadata type, if any.
* @property {string} name The server-assigned name, which is only unique within the same service that
originally returns it. If you use the default HTTP mapping, the
`name` should have the format of `operations/some/unique/name`.
* @property {object} response The normal response of the operation in case of success. If the original
method returns no data on success, such as `Delete`, the response is
`google.protobuf.Empty`. If the original method is standard
`Get`/`Create`/`Update`, the response should be the resource. For other
methods, the response should have the type `XxxResponse`, where `Xxx`
is the original method name. For example, if the original method name
is `TakeSnapshot()`, the inferred response type is
`TakeSnapshotResponse`.
*/
/**
* @typedef RecognitionAudio
* @memberOf! speech(v1)
* @type object
* @property {string} content The audio data bytes encoded as specified in
`RecognitionConfig`. Note: as with all bytes fields, protobuffers use a
pure binary representation, whereas JSON representations use base64.
* @property {string} uri URI that points to a file that contains audio data bytes as specified in
`RecognitionConfig`. Currently, only Google Cloud Storage URIs are
supported, which must be specified in the following format:
`gs://bucket_name/object_name` (other URI formats return
google.rpc.Code.INVALID_ARGUMENT). For more information, see
[Request URIs](https://cloud.google.com/storage/docs/reference-uris).
*/
/**
* @typedef RecognitionConfig
* @memberOf! speech(v1)
* @type object
* @property {boolean} enableWordTimeOffsets *Optional* If `true`, the top result includes a list of words and
the start and end time offsets (timestamps) for those words. If
`false`, no word-level time offset information is returned. The default is
`false`.
* @property {string} encoding *Required* Encoding of audio data sent in all `RecognitionAudio` messages.
* @property {string} languageCode *Required* The language of the supplied audio as a
[BCP-47](https://www.rfc-editor.org/rfc/bcp/bcp47.txt) language tag.
Example: "en-US".
See [Language Support](https://cloud.google.com/speech/docs/languages)
for a list of the currently supported language codes.
* @property {integer} maxAlternatives *Optional* Maximum number of recognition hypotheses to be returned.
Specifically, the maximum number of `SpeechRecognitionAlternative` messages
within each `SpeechRecognitionResult`.
The server may return fewer than `max_alternatives`.
Valid values are `0`-`30`. A value of `0` or `1` will return a maximum of
one. If omitted, will return a maximum of one.
* @property {boolean} profanityFilter *Optional* If set to `true`, the server will attempt to filter out
profanities, replacing all but the initial character in each filtered word
with asterisks, e.g. "f***". If set to `false` or omitted, profanities
won't be filtered out.
* @property {integer} sampleRateHertz *Required* Sample rate in Hertz of the audio data sent in all
`RecognitionAudio` messages. Valid values are: 8000-48000.
16000 is optimal. For best results, set the sampling rate of the audio
source to 16000 Hz. If that's not possible, use the native sample rate of
the audio source (instead of re-sampling).
* @property {speech(v1).SpeechContext[]} speechContexts *Optional* A means to provide context to assist the speech recognition.
*/
/**
* @typedef RecognizeRequest
* @memberOf! speech(v1)
* @type object
* @property {speech(v1).RecognitionAudio} audio *Required* The audio data to be recognized.
* @property {speech(v1).RecognitionConfig} config *Required* Provides information to the recognizer that specifies how to
process the request.
*/
/**
* @typedef RecognizeResponse
* @memberOf! speech(v1)
* @type object
* @property {speech(v1).SpeechRecognitionResult[]} results *Output-only* Sequential list of transcription results corresponding to
sequential portions of audio.
*/
/**
* @typedef SpeechContext
* @memberOf! speech(v1)
* @type object
* @property {string[]} phrases *Optional* A list of strings containing words and phrases "hints" so that
the speech recognition is more likely to recognize them. This can be used
to improve the accuracy for specific words and phrases, for example, if
specific commands are typically spoken by the user. This can also be used
to add additional words to the vocabulary of the recognizer. See
[usage limits](https://cloud.google.com/speech/limits#content).
*/
/**
* @typedef SpeechRecognitionAlternative
* @memberOf! speech(v1)
* @type object
* @property {number} confidence *Output-only* The confidence estimate between 0.0 and 1.0. A higher number
indicates an estimated greater likelihood that the recognized words are
correct. This field is typically provided only for the top hypothesis, and
only for `is_final=true` results. Clients should not rely on the
`confidence` field as it is not guaranteed to be accurate or consistent.
The default of 0.0 is a sentinel value indicating `confidence` was not set.
* @property {string} transcript *Output-only* Transcript text representing the words that the user spoke.
* @property {speech(v1).WordInfo[]} words *Output-only* A list of word-specific information for each recognized word.
*/
/**
* @typedef SpeechRecognitionResult
* @memberOf! speech(v1)
* @type object
* @property {speech(v1).SpeechRecognitionAlternative[]} alternatives *Output-only* May contain one or more recognition hypotheses (up to the
maximum specified in `max_alternatives`).
These alternatives are ordered in terms of accuracy, with the top (first)
alternative being the most probable, as ranked by the recognizer.
*/
/**
* @typedef Status
* @memberOf! speech(v1)
* @type object
* @property {integer} code The status code, which should be an enum value of google.rpc.Code.
* @property {object[]} details A list of messages that carry the error details. There is a common set of
message types for APIs to use.
* @property {string} message A developer-facing error message, which should be in English. Any
user-facing error message should be localized and sent in the
google.rpc.Status.details field, or localized by the client.
*/
/**
* @typedef WordInfo
* @memberOf! speech(v1)
* @type object
* @property {string} endTime *Output-only* Time offset relative to the beginning of the audio,
and corresponding to the end of the spoken word.
This field is only set if `enable_word_time_offsets=true` and only
in the top hypothesis.
This is an experimental feature and the accuracy of the time offset can
vary.
* @property {string} startTime *Output-only* Time offset relative to the beginning of the audio,
and corresponding to the start of the spoken word.
This field is only set if `enable_word_time_offsets=true` and only
in the top hypothesis.
This is an experimental feature and the accuracy of the time offset can
vary.
* @property {string} word *Output-only* The word corresponding to this set of information.
*/
export = Speech;
| Speech | identifier_name |
v1.ts | /**
* Copyright 2015 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* jshint maxlen: false */
import createAPIRequest from '../../lib/apirequest';
/**
* Google Cloud Speech API
*
* Converts audio to text by applying powerful neural network models.
*
* @example
* const google = require('googleapis');
* const speech = google.speech('v1');
*
* @namespace speech
* @type {Function}
* @version v1
* @variation v1
* @param {object=} options Options for Speech
*/
function Speech(options) |
/**
* @typedef CancelOperationRequest
* @memberOf! speech(v1)
* @type object
*/
/**
* @typedef Empty
* @memberOf! speech(v1)
* @type object
*/
/**
* @typedef ListOperationsResponse
* @memberOf! speech(v1)
* @type object
* @property {string} nextPageToken The standard List next-page token.
* @property {speech(v1).Operation[]} operations A list of operations that matches the specified filter in the request.
*/
/**
* @typedef LongRunningRecognizeRequest
* @memberOf! speech(v1)
* @type object
* @property {speech(v1).RecognitionAudio} audio *Required* The audio data to be recognized.
* @property {speech(v1).RecognitionConfig} config *Required* Provides information to the recognizer that specifies how to
process the request.
*/
/**
* @typedef Operation
* @memberOf! speech(v1)
* @type object
* @property {boolean} done If the value is `false`, it means the operation is still in progress.
If `true`, the operation is completed, and either `error` or `response` is
available.
* @property {speech(v1).Status} error The error result of the operation in case of failure or cancellation.
* @property {object} metadata Service-specific metadata associated with the operation. It typically
contains progress information and common metadata such as create time.
Some services might not provide such metadata. Any method that returns a
long-running operation should document the metadata type, if any.
* @property {string} name The server-assigned name, which is only unique within the same service that
originally returns it. If you use the default HTTP mapping, the
`name` should have the format of `operations/some/unique/name`.
* @property {object} response The normal response of the operation in case of success. If the original
method returns no data on success, such as `Delete`, the response is
`google.protobuf.Empty`. If the original method is standard
`Get`/`Create`/`Update`, the response should be the resource. For other
methods, the response should have the type `XxxResponse`, where `Xxx`
is the original method name. For example, if the original method name
is `TakeSnapshot()`, the inferred response type is
`TakeSnapshotResponse`.
*/
/**
* @typedef RecognitionAudio
* @memberOf! speech(v1)
* @type object
* @property {string} content The audio data bytes encoded as specified in
`RecognitionConfig`. Note: as with all bytes fields, protobuffers use a
pure binary representation, whereas JSON representations use base64.
* @property {string} uri URI that points to a file that contains audio data bytes as specified in
`RecognitionConfig`. Currently, only Google Cloud Storage URIs are
supported, which must be specified in the following format:
`gs://bucket_name/object_name` (other URI formats return
google.rpc.Code.INVALID_ARGUMENT). For more information, see
[Request URIs](https://cloud.google.com/storage/docs/reference-uris).
*/
/**
* @typedef RecognitionConfig
* @memberOf! speech(v1)
* @type object
* @property {boolean} enableWordTimeOffsets *Optional* If `true`, the top result includes a list of words and
the start and end time offsets (timestamps) for those words. If
`false`, no word-level time offset information is returned. The default is
`false`.
* @property {string} encoding *Required* Encoding of audio data sent in all `RecognitionAudio` messages.
* @property {string} languageCode *Required* The language of the supplied audio as a
[BCP-47](https://www.rfc-editor.org/rfc/bcp/bcp47.txt) language tag.
Example: "en-US".
See [Language Support](https://cloud.google.com/speech/docs/languages)
for a list of the currently supported language codes.
* @property {integer} maxAlternatives *Optional* Maximum number of recognition hypotheses to be returned.
Specifically, the maximum number of `SpeechRecognitionAlternative` messages
within each `SpeechRecognitionResult`.
The server may return fewer than `max_alternatives`.
Valid values are `0`-`30`. A value of `0` or `1` will return a maximum of
one. If omitted, will return a maximum of one.
* @property {boolean} profanityFilter *Optional* If set to `true`, the server will attempt to filter out
profanities, replacing all but the initial character in each filtered word
with asterisks, e.g. "f***". If set to `false` or omitted, profanities
won't be filtered out.
* @property {integer} sampleRateHertz *Required* Sample rate in Hertz of the audio data sent in all
`RecognitionAudio` messages. Valid values are: 8000-48000.
16000 is optimal. For best results, set the sampling rate of the audio
source to 16000 Hz. If that's not possible, use the native sample rate of
the audio source (instead of re-sampling).
* @property {speech(v1).SpeechContext[]} speechContexts *Optional* A means to provide context to assist the speech recognition.
*/
/**
* @typedef RecognizeRequest
* @memberOf! speech(v1)
* @type object
* @property {speech(v1).RecognitionAudio} audio *Required* The audio data to be recognized.
* @property {speech(v1).RecognitionConfig} config *Required* Provides information to the recognizer that specifies how to
process the request.
*/
/**
* @typedef RecognizeResponse
* @memberOf! speech(v1)
* @type object
* @property {speech(v1).SpeechRecognitionResult[]} results *Output-only* Sequential list of transcription results corresponding to
sequential portions of audio.
*/
/**
* @typedef SpeechContext
* @memberOf! speech(v1)
* @type object
* @property {string[]} phrases *Optional* A list of strings containing words and phrases "hints" so that
the speech recognition is more likely to recognize them. This can be used
to improve the accuracy for specific words and phrases, for example, if
specific commands are typically spoken by the user. This can also be used
to add additional words to the vocabulary of the recognizer. See
[usage limits](https://cloud.google.com/speech/limits#content).
*/
/**
* @typedef SpeechRecognitionAlternative
* @memberOf! speech(v1)
* @type object
* @property {number} confidence *Output-only* The confidence estimate between 0.0 and 1.0. A higher number
indicates an estimated greater likelihood that the recognized words are
correct. This field is typically provided only for the top hypothesis, and
only for `is_final=true` results. Clients should not rely on the
`confidence` field as it is not guaranteed to be accurate or consistent.
The default of 0.0 is a sentinel value indicating `confidence` was not set.
* @property {string} transcript *Output-only* Transcript text representing the words that the user spoke.
* @property {speech(v1).WordInfo[]} words *Output-only* A list of word-specific information for each recognized word.
*/
/**
* @typedef SpeechRecognitionResult
* @memberOf! speech(v1)
* @type object
* @property {speech(v1).SpeechRecognitionAlternative[]} alternatives *Output-only* May contain one or more recognition hypotheses (up to the
maximum specified in `max_alternatives`).
These alternatives are ordered in terms of accuracy, with the top (first)
alternative being the most probable, as ranked by the recognizer.
*/
/**
* @typedef Status
* @memberOf! speech(v1)
* @type object
* @property {integer} code The status code, which should be an enum value of google.rpc.Code.
* @property {object[]} details A list of messages that carry the error details. There is a common set of
message types for APIs to use.
* @property {string} message A developer-facing error message, which should be in English. Any
user-facing error message should be localized and sent in the
google.rpc.Status.details field, or localized by the client.
*/
/**
* @typedef WordInfo
* @memberOf! speech(v1)
* @type object
* @property {string} endTime *Output-only* Time offset relative to the beginning of the audio,
and corresponding to the end of the spoken word.
This field is only set if `enable_word_time_offsets=true` and only
in the top hypothesis.
This is an experimental feature and the accuracy of the time offset can
vary.
* @property {string} startTime *Output-only* Time offset relative to the beginning of the audio,
and corresponding to the start of the spoken word.
This field is only set if `enable_word_time_offsets=true` and only
in the top hypothesis.
This is an experimental feature and the accuracy of the time offset can
vary.
* @property {string} word *Output-only* The word corresponding to this set of information.
*/
export = Speech;
| { // eslint-disable-line
const self = this;
self._options = options || {};
self.operations = {
/**
* speech.operations.cancel
*
* @desc Starts asynchronous cancellation on a long-running operation. The server makes a best effort to cancel the operation, but success is not guaranteed. If the server doesn't support this method, it returns `google.rpc.Code.UNIMPLEMENTED`. Clients can use Operations.GetOperation or other methods to check whether the cancellation succeeded or whether the operation completed despite cancellation. On successful cancellation, the operation is not deleted; instead, it becomes an operation with an Operation.error value with a google.rpc.Status.code of 1, corresponding to `Code.CANCELLED`.
*
* @alias speech.operations.cancel
* @memberOf! speech(v1)
*
* @param {object} params Parameters for request
* @param {string} params.name The name of the operation resource to be cancelled.
* @param {speech(v1).CancelOperationRequest} params.resource Request body data
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
cancel: function (params, options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
options || (options = {});
const rootUrl = options.rootUrl || 'https://speech.googleapis.com/';
const parameters = {
options: Object.assign({
url: (rootUrl + '/v1/operations/{name}:cancel').replace(/([^:]\/)\/+/g, '$1'),
method: 'POST'
}, options),
params: params,
requiredParams: ['name'],
pathParams: ['name'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* speech.operations.delete
*
* @desc Deletes a long-running operation. This method indicates that the client is no longer interested in the operation result. It does not cancel the operation. If the server doesn't support this method, it returns `google.rpc.Code.UNIMPLEMENTED`.
*
* @alias speech.operations.delete
* @memberOf! speech(v1)
*
* @param {object} params Parameters for request
* @param {string} params.name The name of the operation resource to be deleted.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
delete: function (params, options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
options || (options = {});
const rootUrl = options.rootUrl || 'https://speech.googleapis.com/';
const parameters = {
options: Object.assign({
url: (rootUrl + '/v1/operations/{name}').replace(/([^:]\/)\/+/g, '$1'),
method: 'DELETE'
}, options),
params: params,
requiredParams: ['name'],
pathParams: ['name'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* speech.operations.get
*
* @desc Gets the latest state of a long-running operation. Clients can use this method to poll the operation result at intervals as recommended by the API service.
*
* @alias speech.operations.get
* @memberOf! speech(v1)
*
* @param {object} params Parameters for request
* @param {string} params.name The name of the operation resource.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
get: function (params, options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
options || (options = {});
const rootUrl = options.rootUrl || 'https://speech.googleapis.com/';
const parameters = {
options: Object.assign({
url: (rootUrl + '/v1/operations/{name}').replace(/([^:]\/)\/+/g, '$1'),
method: 'GET'
}, options),
params: params,
requiredParams: ['name'],
pathParams: ['name'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* speech.operations.list
*
* @desc Lists operations that match the specified filter in the request. If the server doesn't support this method, it returns `UNIMPLEMENTED`. NOTE: the `name` binding allows API services to override the binding to use different resource name schemes, such as `users/x/operations`. To override the binding, API services can add a binding such as `"/v1/{name=users/x}/operations"` to their service configuration. For backwards compatibility, the default name includes the operations collection id, however overriding users must ensure the name binding is the parent resource, without the operations collection id.
*
* @alias speech.operations.list
* @memberOf! speech(v1)
*
* @param {object} params Parameters for request
* @param {string=} params.filter The standard list filter.
* @param {string=} params.name The name of the operation's parent resource.
* @param {integer=} params.pageSize The standard list page size.
* @param {string=} params.pageToken The standard list page token.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
list: function (params, options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
options || (options = {});
const rootUrl = options.rootUrl || 'https://speech.googleapis.com/';
const parameters = {
options: Object.assign({
url: (rootUrl + '/v1/operations').replace(/([^:]\/)\/+/g, '$1'),
method: 'GET'
}, options),
params: params,
requiredParams: [],
pathParams: [],
context: self
};
return createAPIRequest(parameters, callback);
}
};
self.speech = {
/**
* speech.speech.longrunningrecognize
*
* @desc Performs asynchronous speech recognition: receive results via the google.longrunning.Operations interface. Returns either an `Operation.error` or an `Operation.response` which contains a `LongRunningRecognizeResponse` message.
*
* @alias speech.speech.longrunningrecognize
* @memberOf! speech(v1)
*
* @param {object} params Parameters for request
* @param {speech(v1).LongRunningRecognizeRequest} params.resource Request body data
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
longrunningrecognize: function (params, options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
options || (options = {});
const rootUrl = options.rootUrl || 'https://speech.googleapis.com/';
const parameters = {
options: Object.assign({
url: (rootUrl + '/v1/speech:longrunningrecognize').replace(/([^:]\/)\/+/g, '$1'),
method: 'POST'
}, options),
params: params,
requiredParams: [],
pathParams: [],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* speech.speech.recognize
*
* @desc Performs synchronous speech recognition: receive results after all audio has been sent and processed.
*
* @alias speech.speech.recognize
* @memberOf! speech(v1)
*
* @param {object} params Parameters for request
* @param {speech(v1).RecognizeRequest} params.resource Request body data
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
recognize: function (params, options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
options || (options = {});
const rootUrl = options.rootUrl || 'https://speech.googleapis.com/';
const parameters = {
options: Object.assign({
url: (rootUrl + '/v1/speech:recognize').replace(/([^:]\/)\/+/g, '$1'),
method: 'POST'
}, options),
params: params,
requiredParams: [],
pathParams: [],
context: self
};
return createAPIRequest(parameters, callback);
}
};
} | identifier_body |
v1.ts | /**
* Copyright 2015 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* jshint maxlen: false */
import createAPIRequest from '../../lib/apirequest';
/**
* Google Cloud Speech API
*
* Converts audio to text by applying powerful neural network models.
*
* @example
* const google = require('googleapis');
* const speech = google.speech('v1');
*
* @namespace speech
* @type {Function}
* @version v1
* @variation v1
* @param {object=} options Options for Speech
*/
function Speech(options) { // eslint-disable-line
const self = this;
self._options = options || {};
self.operations = {
/**
* speech.operations.cancel
*
* @desc Starts asynchronous cancellation on a long-running operation. The server makes a best effort to cancel the operation, but success is not guaranteed. If the server doesn't support this method, it returns `google.rpc.Code.UNIMPLEMENTED`. Clients can use Operations.GetOperation or other methods to check whether the cancellation succeeded or whether the operation completed despite cancellation. On successful cancellation, the operation is not deleted; instead, it becomes an operation with an Operation.error value with a google.rpc.Status.code of 1, corresponding to `Code.CANCELLED`.
*
* @alias speech.operations.cancel
* @memberOf! speech(v1)
*
* @param {object} params Parameters for request
* @param {string} params.name The name of the operation resource to be cancelled.
* @param {speech(v1).CancelOperationRequest} params.resource Request body data
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
cancel: function (params, options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
options || (options = {});
const rootUrl = options.rootUrl || 'https://speech.googleapis.com/';
const parameters = {
options: Object.assign({
url: (rootUrl + '/v1/operations/{name}:cancel').replace(/([^:]\/)\/+/g, '$1'),
method: 'POST'
}, options),
params: params,
requiredParams: ['name'],
pathParams: ['name'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* speech.operations.delete
*
* @desc Deletes a long-running operation. This method indicates that the client is no longer interested in the operation result. It does not cancel the operation. If the server doesn't support this method, it returns `google.rpc.Code.UNIMPLEMENTED`.
*
* @alias speech.operations.delete
* @memberOf! speech(v1)
*
* @param {object} params Parameters for request
* @param {string} params.name The name of the operation resource to be deleted.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
delete: function (params, options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
options || (options = {});
const rootUrl = options.rootUrl || 'https://speech.googleapis.com/';
const parameters = {
options: Object.assign({
url: (rootUrl + '/v1/operations/{name}').replace(/([^:]\/)\/+/g, '$1'),
method: 'DELETE'
}, options),
params: params,
requiredParams: ['name'],
pathParams: ['name'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* speech.operations.get
*
* @desc Gets the latest state of a long-running operation. Clients can use this method to poll the operation result at intervals as recommended by the API service.
*
* @alias speech.operations.get
* @memberOf! speech(v1)
*
* @param {object} params Parameters for request
* @param {string} params.name The name of the operation resource.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
get: function (params, options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
options || (options = {});
const rootUrl = options.rootUrl || 'https://speech.googleapis.com/';
const parameters = {
options: Object.assign({
url: (rootUrl + '/v1/operations/{name}').replace(/([^:]\/)\/+/g, '$1'),
method: 'GET'
}, options),
params: params,
requiredParams: ['name'],
pathParams: ['name'],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* speech.operations.list
*
* @desc Lists operations that match the specified filter in the request. If the server doesn't support this method, it returns `UNIMPLEMENTED`. NOTE: the `name` binding allows API services to override the binding to use different resource name schemes, such as `users/x/operations`. To override the binding, API services can add a binding such as `"/v1/{name=users/x}/operations"` to their service configuration. For backwards compatibility, the default name includes the operations collection id, however overriding users must ensure the name binding is the parent resource, without the operations collection id.
*
* @alias speech.operations.list
* @memberOf! speech(v1)
*
* @param {object} params Parameters for request
* @param {string=} params.filter The standard list filter.
* @param {string=} params.name The name of the operation's parent resource.
* @param {integer=} params.pageSize The standard list page size.
* @param {string=} params.pageToken The standard list page token.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
list: function (params, options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
options || (options = {});
const rootUrl = options.rootUrl || 'https://speech.googleapis.com/';
const parameters = {
options: Object.assign({
url: (rootUrl + '/v1/operations').replace(/([^:]\/)\/+/g, '$1'),
method: 'GET'
}, options),
params: params,
requiredParams: [],
pathParams: [],
context: self
};
return createAPIRequest(parameters, callback);
}
};
self.speech = {
/**
* speech.speech.longrunningrecognize
*
* @desc Performs asynchronous speech recognition: receive results via the google.longrunning.Operations interface. Returns either an `Operation.error` or an `Operation.response` which contains a `LongRunningRecognizeResponse` message.
*
* @alias speech.speech.longrunningrecognize
* @memberOf! speech(v1)
*
* @param {object} params Parameters for request
* @param {speech(v1).LongRunningRecognizeRequest} params.resource Request body data
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
longrunningrecognize: function (params, options, callback) {
if (typeof options === 'function') |
options || (options = {});
const rootUrl = options.rootUrl || 'https://speech.googleapis.com/';
const parameters = {
options: Object.assign({
url: (rootUrl + '/v1/speech:longrunningrecognize').replace(/([^:]\/)\/+/g, '$1'),
method: 'POST'
}, options),
params: params,
requiredParams: [],
pathParams: [],
context: self
};
return createAPIRequest(parameters, callback);
},
/**
* speech.speech.recognize
*
* @desc Performs synchronous speech recognition: receive results after all audio has been sent and processed.
*
* @alias speech.speech.recognize
* @memberOf! speech(v1)
*
* @param {object} params Parameters for request
* @param {speech(v1).RecognizeRequest} params.resource Request body data
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
recognize: function (params, options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
options || (options = {});
const rootUrl = options.rootUrl || 'https://speech.googleapis.com/';
const parameters = {
options: Object.assign({
url: (rootUrl + '/v1/speech:recognize').replace(/([^:]\/)\/+/g, '$1'),
method: 'POST'
}, options),
params: params,
requiredParams: [],
pathParams: [],
context: self
};
return createAPIRequest(parameters, callback);
}
};
}
/**
* @typedef CancelOperationRequest
* @memberOf! speech(v1)
* @type object
*/
/**
* @typedef Empty
* @memberOf! speech(v1)
* @type object
*/
/**
* @typedef ListOperationsResponse
* @memberOf! speech(v1)
* @type object
* @property {string} nextPageToken The standard List next-page token.
* @property {speech(v1).Operation[]} operations A list of operations that matches the specified filter in the request.
*/
/**
* @typedef LongRunningRecognizeRequest
* @memberOf! speech(v1)
* @type object
* @property {speech(v1).RecognitionAudio} audio *Required* The audio data to be recognized.
* @property {speech(v1).RecognitionConfig} config *Required* Provides information to the recognizer that specifies how to
process the request.
*/
/**
* @typedef Operation
* @memberOf! speech(v1)
* @type object
* @property {boolean} done If the value is `false`, it means the operation is still in progress.
If `true`, the operation is completed, and either `error` or `response` is
available.
* @property {speech(v1).Status} error The error result of the operation in case of failure or cancellation.
* @property {object} metadata Service-specific metadata associated with the operation. It typically
contains progress information and common metadata such as create time.
Some services might not provide such metadata. Any method that returns a
long-running operation should document the metadata type, if any.
* @property {string} name The server-assigned name, which is only unique within the same service that
originally returns it. If you use the default HTTP mapping, the
`name` should have the format of `operations/some/unique/name`.
* @property {object} response The normal response of the operation in case of success. If the original
method returns no data on success, such as `Delete`, the response is
`google.protobuf.Empty`. If the original method is standard
`Get`/`Create`/`Update`, the response should be the resource. For other
methods, the response should have the type `XxxResponse`, where `Xxx`
is the original method name. For example, if the original method name
is `TakeSnapshot()`, the inferred response type is
`TakeSnapshotResponse`.
*/
/**
* @typedef RecognitionAudio
* @memberOf! speech(v1)
* @type object
* @property {string} content The audio data bytes encoded as specified in
`RecognitionConfig`. Note: as with all bytes fields, protobuffers use a
pure binary representation, whereas JSON representations use base64.
* @property {string} uri URI that points to a file that contains audio data bytes as specified in
`RecognitionConfig`. Currently, only Google Cloud Storage URIs are
supported, which must be specified in the following format:
`gs://bucket_name/object_name` (other URI formats return
google.rpc.Code.INVALID_ARGUMENT). For more information, see
[Request URIs](https://cloud.google.com/storage/docs/reference-uris).
*/
/**
* @typedef RecognitionConfig
* @memberOf! speech(v1)
* @type object
* @property {boolean} enableWordTimeOffsets *Optional* If `true`, the top result includes a list of words and
the start and end time offsets (timestamps) for those words. If
`false`, no word-level time offset information is returned. The default is
`false`.
* @property {string} encoding *Required* Encoding of audio data sent in all `RecognitionAudio` messages.
* @property {string} languageCode *Required* The language of the supplied audio as a
[BCP-47](https://www.rfc-editor.org/rfc/bcp/bcp47.txt) language tag.
Example: "en-US".
See [Language Support](https://cloud.google.com/speech/docs/languages)
for a list of the currently supported language codes.
* @property {integer} maxAlternatives *Optional* Maximum number of recognition hypotheses to be returned.
Specifically, the maximum number of `SpeechRecognitionAlternative` messages
within each `SpeechRecognitionResult`.
The server may return fewer than `max_alternatives`.
Valid values are `0`-`30`. A value of `0` or `1` will return a maximum of
one. If omitted, will return a maximum of one.
* @property {boolean} profanityFilter *Optional* If set to `true`, the server will attempt to filter out
profanities, replacing all but the initial character in each filtered word
with asterisks, e.g. "f***". If set to `false` or omitted, profanities
won't be filtered out.
* @property {integer} sampleRateHertz *Required* Sample rate in Hertz of the audio data sent in all
`RecognitionAudio` messages. Valid values are: 8000-48000.
16000 is optimal. For best results, set the sampling rate of the audio
source to 16000 Hz. If that's not possible, use the native sample rate of
the audio source (instead of re-sampling).
* @property {speech(v1).SpeechContext[]} speechContexts *Optional* A means to provide context to assist the speech recognition.
*/
/**
* @typedef RecognizeRequest
* @memberOf! speech(v1)
* @type object
* @property {speech(v1).RecognitionAudio} audio *Required* The audio data to be recognized.
* @property {speech(v1).RecognitionConfig} config *Required* Provides information to the recognizer that specifies how to
process the request.
*/
/**
* @typedef RecognizeResponse
* @memberOf! speech(v1)
* @type object
* @property {speech(v1).SpeechRecognitionResult[]} results *Output-only* Sequential list of transcription results corresponding to
sequential portions of audio.
*/
/**
* @typedef SpeechContext
* @memberOf! speech(v1)
* @type object
* @property {string[]} phrases *Optional* A list of strings containing words and phrases "hints" so that
the speech recognition is more likely to recognize them. This can be used
to improve the accuracy for specific words and phrases, for example, if
specific commands are typically spoken by the user. This can also be used
to add additional words to the vocabulary of the recognizer. See
[usage limits](https://cloud.google.com/speech/limits#content).
*/
/**
* @typedef SpeechRecognitionAlternative
* @memberOf! speech(v1)
* @type object
* @property {number} confidence *Output-only* The confidence estimate between 0.0 and 1.0. A higher number
indicates an estimated greater likelihood that the recognized words are
correct. This field is typically provided only for the top hypothesis, and
only for `is_final=true` results. Clients should not rely on the
`confidence` field as it is not guaranteed to be accurate or consistent.
The default of 0.0 is a sentinel value indicating `confidence` was not set.
* @property {string} transcript *Output-only* Transcript text representing the words that the user spoke.
* @property {speech(v1).WordInfo[]} words *Output-only* A list of word-specific information for each recognized word.
*/
/**
* @typedef SpeechRecognitionResult
* @memberOf! speech(v1)
* @type object
* @property {speech(v1).SpeechRecognitionAlternative[]} alternatives *Output-only* May contain one or more recognition hypotheses (up to the
maximum specified in `max_alternatives`).
These alternatives are ordered in terms of accuracy, with the top (first)
alternative being the most probable, as ranked by the recognizer.
*/
/**
* @typedef Status
* @memberOf! speech(v1)
* @type object
* @property {integer} code The status code, which should be an enum value of google.rpc.Code.
* @property {object[]} details A list of messages that carry the error details. There is a common set of
message types for APIs to use.
* @property {string} message A developer-facing error message, which should be in English. Any
user-facing error message should be localized and sent in the
google.rpc.Status.details field, or localized by the client.
*/
/**
* @typedef WordInfo
* @memberOf! speech(v1)
* @type object
* @property {string} endTime *Output-only* Time offset relative to the beginning of the audio,
and corresponding to the end of the spoken word.
This field is only set if `enable_word_time_offsets=true` and only
in the top hypothesis.
This is an experimental feature and the accuracy of the time offset can
vary.
* @property {string} startTime *Output-only* Time offset relative to the beginning of the audio,
and corresponding to the start of the spoken word.
This field is only set if `enable_word_time_offsets=true` and only
in the top hypothesis.
This is an experimental feature and the accuracy of the time offset can
vary.
* @property {string} word *Output-only* The word corresponding to this set of information.
*/
export = Speech;
| {
callback = options;
options = {};
} | conditional_block |
aurelia-event-aggregator.d.ts | declare module 'aurelia-event-aggregator' {
import * as LogManager from 'aurelia-logging';
/**
* Represents a disposable subsciption to an EventAggregator event.
*/
export interface Subscription {
dispose(): void;
}
class Handler {
constructor(messageType: any, callback: any);
handle(message: any): any;
}
/**
* Enables loosely coupled publish/subscribe messaging.
*/
export class | {
/**
* Creates an instance of the EventAggregator class.
*/
constructor();
/**
* Publishes a message.
* @param event The event or channel to publish to.
* @param data The data to publish on the channel.
*/
publish(event: string | any, data?: any): void;
/**
* Subscribes to a message channel or message type.
* @param event The event channel or event data type.
* @param callback The callback to be invoked when when the specified message is published.
*/
subscribe(event: string | Function, callback: Function): Subscription;
/**
* Subscribes to a message channel or message type, then disposes the subscription automatically after the first message is received.
* @param event The event channel or event data type.
* @param callback The callback to be invoked when when the specified message is published.
*/
subscribeOnce(event: string | Function, callback: Function): Subscription;
}
/**
* Includes EA functionality into an object instance.
* @param obj The object to mix Event Aggregator functionality into.
*/
export function includeEventsIn(obj: Object): EventAggregator;
/**
* Configures a global EA by merging functionality into the Aurelia instance.
* @param config The Aurelia Framework configuration object used to configure the plugin.
*/
export function configure(config: Object): void;
} | EventAggregator | identifier_name |
aurelia-event-aggregator.d.ts | declare module 'aurelia-event-aggregator' {
import * as LogManager from 'aurelia-logging';
/**
* Represents a disposable subsciption to an EventAggregator event.
*/
export interface Subscription {
dispose(): void;
}
class Handler {
constructor(messageType: any, callback: any);
handle(message: any): any;
}
/**
* Enables loosely coupled publish/subscribe messaging.
*/
export class EventAggregator {
/**
* Creates an instance of the EventAggregator class.
*/
constructor();
/**
* Publishes a message.
* @param event The event or channel to publish to.
* @param data The data to publish on the channel.
*/
publish(event: string | any, data?: any): void;
/**
* Subscribes to a message channel or message type. | * @param callback The callback to be invoked when when the specified message is published.
*/
subscribe(event: string | Function, callback: Function): Subscription;
/**
* Subscribes to a message channel or message type, then disposes the subscription automatically after the first message is received.
* @param event The event channel or event data type.
* @param callback The callback to be invoked when when the specified message is published.
*/
subscribeOnce(event: string | Function, callback: Function): Subscription;
}
/**
* Includes EA functionality into an object instance.
* @param obj The object to mix Event Aggregator functionality into.
*/
export function includeEventsIn(obj: Object): EventAggregator;
/**
* Configures a global EA by merging functionality into the Aurelia instance.
* @param config The Aurelia Framework configuration object used to configure the plugin.
*/
export function configure(config: Object): void;
} | * @param event The event channel or event data type. | random_line_split |
struct_tempest_1_1_abstract_list_delegate_1_1_list_item.js | var struct_tempest_1_1_abstract_list_delegate_1_1_list_item =
[
[ "ListItem", "struct_tempest_1_1_abstract_list_delegate_1_1_list_item.html#a9c11b618acf99ff46e8d3b369e22bbe8", null ],
[ "emitClick", "struct_tempest_1_1_abstract_list_delegate_1_1_list_item.html#a46adebd1adca8d23768023144cbbe32b", null ],
[ "clicked", "struct_tempest_1_1_abstract_list_delegate_1_1_list_item.html#a7a67d04c648280bbdcb2fb8ea370a05b", null ],
[ "id", "struct_tempest_1_1_abstract_list_delegate_1_1_list_item.html#a8d31d29e4a483ee3dfec2aa8324a8452", null ] | ]; | random_line_split | |
windows_base.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use target::TargetOptions;
use std::default::Default;
pub fn opts() -> TargetOptions {
TargetOptions {
// FIXME(#13846) this should be enabled for windows
function_sections: false,
linker: "gcc".to_string(),
dynamic_linking: true,
executables: true,
dll_prefix: "".to_string(),
dll_suffix: ".dll".to_string(),
exe_suffix: ".exe".to_string(),
staticlib_prefix: "".to_string(),
staticlib_suffix: ".lib".to_string(),
morestack: false,
is_like_windows: true,
pre_link_args: vec!(
// And here, we see obscure linker flags #45. On windows, it has been
// found to be necessary to have this flag to compile liblibc.
//
// First a bit of background. On Windows, the file format is not ELF, | // On more recent versions of gcc on mingw, apparently the section name
// is *not* truncated, but rather stored elsewhere in a separate lookup
// table. On older versions of gcc, they apparently always truncated th
// section names (at least in some cases). Truncating the section name
// actually creates "invalid" objects [1] [2], but only for some
// introspection tools, not in terms of whether it can be loaded.
//
// Long story short, passing this flag forces the linker to *not*
// truncate section names (so we can find the metadata section after
// it's compiled). The real kicker is that rust compiled just fine on
// windows for quite a long time *without* this flag, so I have no idea
// why it suddenly started failing for liblibc. Regardless, we
// definitely don't want section name truncation, so we're keeping this
// flag for windows.
//
// [1] - https://sourceware.org/bugzilla/show_bug.cgi?id=13130
// [2] - https://code.google.com/p/go/issues/detail?id=2139
"-Wl,--enable-long-section-names".to_string(),
// Tell GCC to avoid linker plugins, because we are not bundling
// them with Windows installer, and Rust does its own LTO anyways.
"-fno-use-linker-plugin".to_string(),
// Always enable DEP (NX bit) when it is available
"-Wl,--nxcompat".to_string(),
),
.. Default::default()
}
} | // but COFF (at least according to LLVM). COFF doesn't officially allow
// for section names over 8 characters, apparently. Our metadata
// section, ".note.rustc", you'll note is over 8 characters.
// | random_line_split |
windows_base.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use target::TargetOptions;
use std::default::Default;
pub fn | () -> TargetOptions {
TargetOptions {
// FIXME(#13846) this should be enabled for windows
function_sections: false,
linker: "gcc".to_string(),
dynamic_linking: true,
executables: true,
dll_prefix: "".to_string(),
dll_suffix: ".dll".to_string(),
exe_suffix: ".exe".to_string(),
staticlib_prefix: "".to_string(),
staticlib_suffix: ".lib".to_string(),
morestack: false,
is_like_windows: true,
pre_link_args: vec!(
// And here, we see obscure linker flags #45. On windows, it has been
// found to be necessary to have this flag to compile liblibc.
//
// First a bit of background. On Windows, the file format is not ELF,
// but COFF (at least according to LLVM). COFF doesn't officially allow
// for section names over 8 characters, apparently. Our metadata
// section, ".note.rustc", you'll note is over 8 characters.
//
// On more recent versions of gcc on mingw, apparently the section name
// is *not* truncated, but rather stored elsewhere in a separate lookup
// table. On older versions of gcc, they apparently always truncated th
// section names (at least in some cases). Truncating the section name
// actually creates "invalid" objects [1] [2], but only for some
// introspection tools, not in terms of whether it can be loaded.
//
// Long story short, passing this flag forces the linker to *not*
// truncate section names (so we can find the metadata section after
// it's compiled). The real kicker is that rust compiled just fine on
// windows for quite a long time *without* this flag, so I have no idea
// why it suddenly started failing for liblibc. Regardless, we
// definitely don't want section name truncation, so we're keeping this
// flag for windows.
//
// [1] - https://sourceware.org/bugzilla/show_bug.cgi?id=13130
// [2] - https://code.google.com/p/go/issues/detail?id=2139
"-Wl,--enable-long-section-names".to_string(),
// Tell GCC to avoid linker plugins, because we are not bundling
// them with Windows installer, and Rust does its own LTO anyways.
"-fno-use-linker-plugin".to_string(),
// Always enable DEP (NX bit) when it is available
"-Wl,--nxcompat".to_string(),
),
.. Default::default()
}
}
| opts | identifier_name |
windows_base.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use target::TargetOptions;
use std::default::Default;
pub fn opts() -> TargetOptions | {
TargetOptions {
// FIXME(#13846) this should be enabled for windows
function_sections: false,
linker: "gcc".to_string(),
dynamic_linking: true,
executables: true,
dll_prefix: "".to_string(),
dll_suffix: ".dll".to_string(),
exe_suffix: ".exe".to_string(),
staticlib_prefix: "".to_string(),
staticlib_suffix: ".lib".to_string(),
morestack: false,
is_like_windows: true,
pre_link_args: vec!(
// And here, we see obscure linker flags #45. On windows, it has been
// found to be necessary to have this flag to compile liblibc.
//
// First a bit of background. On Windows, the file format is not ELF,
// but COFF (at least according to LLVM). COFF doesn't officially allow
// for section names over 8 characters, apparently. Our metadata
// section, ".note.rustc", you'll note is over 8 characters.
//
// On more recent versions of gcc on mingw, apparently the section name
// is *not* truncated, but rather stored elsewhere in a separate lookup
// table. On older versions of gcc, they apparently always truncated th
// section names (at least in some cases). Truncating the section name
// actually creates "invalid" objects [1] [2], but only for some
// introspection tools, not in terms of whether it can be loaded.
//
// Long story short, passing this flag forces the linker to *not*
// truncate section names (so we can find the metadata section after
// it's compiled). The real kicker is that rust compiled just fine on
// windows for quite a long time *without* this flag, so I have no idea
// why it suddenly started failing for liblibc. Regardless, we
// definitely don't want section name truncation, so we're keeping this
// flag for windows.
//
// [1] - https://sourceware.org/bugzilla/show_bug.cgi?id=13130
// [2] - https://code.google.com/p/go/issues/detail?id=2139
"-Wl,--enable-long-section-names".to_string(),
// Tell GCC to avoid linker plugins, because we are not bundling
// them with Windows installer, and Rust does its own LTO anyways.
"-fno-use-linker-plugin".to_string(),
// Always enable DEP (NX bit) when it is available
"-Wl,--nxcompat".to_string(),
),
.. Default::default()
}
} | identifier_body | |
base-documents-visitor.ts | import { NormalizedScalarsMap } from './types';
import autoBind from 'auto-bind';
import { DEFAULT_SCALARS } from './scalars';
import { DeclarationBlock, DeclarationBlockConfig, getConfigValue, buildScalarsFromConfig } from './utils';
import {
GraphQLSchema,
FragmentDefinitionNode,
OperationDefinitionNode,
VariableDefinitionNode,
OperationTypeNode,
} from 'graphql';
import { SelectionSetToObject } from './selection-set-to-object';
import { OperationVariablesToObject } from './variables-to-object';
import { BaseVisitor } from './base-visitor';
import { ParsedTypesConfig, RawTypesConfig } from './base-types-visitor';
import { pascalCase } from 'change-case-all';
function getRootType(operation: OperationTypeNode, schema: GraphQLSchema) {
switch (operation) {
case 'query':
return schema.getQueryType();
case 'mutation':
return schema.getMutationType();
case 'subscription':
return schema.getSubscriptionType();
}
throw new Error(`Unknown operation type: ${operation}`);
}
export interface ParsedDocumentsConfig extends ParsedTypesConfig {
addTypename: boolean;
preResolveTypes: boolean;
globalNamespace: boolean;
operationResultSuffix: string;
dedupeOperationSuffix: boolean;
omitOperationSuffix: boolean;
namespacedImportName: string | null;
exportFragmentSpreadSubTypes: boolean;
skipTypeNameForRoot: boolean;
experimentalFragmentVariables: boolean;
}
export interface RawDocumentsConfig extends RawTypesConfig {
/**
* @default true
* @description Uses primitive types where possible.
* Set to `false` in order to use `Pick` and take use the types generated by `typescript` plugin.
*
* @exampleMarkdown
* ```yml
* plugins
* config:
* preResolveTypes: false
* ```
*/
preResolveTypes?: boolean;
/**
* @default false
* @description Avoid adding `__typename` for root types. This is ignored when a selection explicitly specifies `__typename`.
*
* @exampleMarkdown
* ```yml
* plugins
* config:
* skipTypeNameForRoot: true
* ```
*/
skipTypeNameForRoot?: boolean;
/**
* @default false
* @description Puts all generated code under `global` namespace. Useful for Stencil integration.
*
* @exampleMarkdown
* ```yml
* plugins
* config:
* globalNamespace: true
* ```
*/
globalNamespace?: boolean;
/**
* @default ""
* @description Adds a suffix to generated operation result type names
*/
operationResultSuffix?: string;
/**
* @default false
* @description Set this configuration to `true` if you wish to make sure to remove duplicate operation name suffix.
*/
dedupeOperationSuffix?: boolean;
/**
* @default false
* @description Set this configuration to `true` if you wish to disable auto add suffix of operation name, like `Query`, `Mutation`, `Subscription`, `Fragment`.
*/
omitOperationSuffix?: boolean;
/**
* @default false
* @description If set to true, it will export the sub-types created in order to make it easier to access fields declared under fragment spread.
*/
exportFragmentSpreadSubTypes?: boolean;
/**
* @default false
* @description If set to true, it will enable support for parsing variables on fragments.
*/
experimentalFragmentVariables?: boolean;
// The following are internal, and used by presets
/**
* @ignore
*/
namespacedImportName?: string;
}
export class BaseDocumentsVisitor<
TRawConfig extends RawDocumentsConfig = RawDocumentsConfig,
TPluginConfig extends ParsedDocumentsConfig = ParsedDocumentsConfig
> extends BaseVisitor<TRawConfig, TPluginConfig> {
protected _unnamedCounter = 1;
protected _variablesTransfomer: OperationVariablesToObject;
protected _selectionSetToObject: SelectionSetToObject;
protected _globalDeclarations: Set<string> = new Set<string>();
constructor(
rawConfig: TRawConfig,
additionalConfig: TPluginConfig,
protected _schema: GraphQLSchema,
defaultScalars: NormalizedScalarsMap = DEFAULT_SCALARS
) {
super(rawConfig, {
exportFragmentSpreadSubTypes: getConfigValue(rawConfig.exportFragmentSpreadSubTypes, false),
enumPrefix: getConfigValue(rawConfig.enumPrefix, true),
preResolveTypes: getConfigValue(rawConfig.preResolveTypes, true),
dedupeOperationSuffix: getConfigValue(rawConfig.dedupeOperationSuffix, false),
omitOperationSuffix: getConfigValue(rawConfig.omitOperationSuffix, false),
skipTypeNameForRoot: getConfigValue(rawConfig.skipTypeNameForRoot, false),
namespacedImportName: getConfigValue(rawConfig.namespacedImportName, null),
experimentalFragmentVariables: getConfigValue(rawConfig.experimentalFragmentVariables, false),
addTypename: !rawConfig.skipTypename,
globalNamespace: !!rawConfig.globalNamespace,
operationResultSuffix: getConfigValue(rawConfig.operationResultSuffix, ''),
scalars: buildScalarsFromConfig(_schema, rawConfig, defaultScalars),
...((additionalConfig || {}) as any),
});
autoBind(this);
this._variablesTransfomer = new OperationVariablesToObject(
this.scalars,
this.convertName,
this.config.namespacedImportName
);
}
public getGlobalDeclarations(noExport = false): string[] {
return Array.from(this._globalDeclarations).map(t => (noExport ? t : `export ${t}`));
}
setSelectionSetHandler(handler: SelectionSetToObject): void {
this._selectionSetToObject = handler;
}
setDeclarationBlockConfig(config: DeclarationBlockConfig): void {
this._declarationBlockConfig = config;
}
setVariablesTransformer(variablesTransfomer: OperationVariablesToObject): void {
this._variablesTransfomer = variablesTransfomer;
}
public get schema(): GraphQLSchema {
return this._schema;
}
public get addTypename(): boolean {
return this._parsedConfig.addTypename;
}
private handleAnonymousOperation(node: OperationDefinitionNode): string {
const name = node.name && node.name.value;
if (name) {
return this.convertName(name, {
useTypesPrefix: false,
useTypesSuffix: false,
});
}
return this.convertName(this._unnamedCounter++ + '', {
prefix: 'Unnamed_',
suffix: '_',
useTypesPrefix: false,
useTypesSuffix: false,
});
}
FragmentDefinition(node: FragmentDefinitionNode): string {
const fragmentRootType = this._schema.getType(node.typeCondition.name.value);
const selectionSet = this._selectionSetToObject.createNext(fragmentRootType, node.selectionSet);
const fragmentSuffix = this.getFragmentSuffix(node);
return [
selectionSet.transformFragmentSelectionSetToTypes(node.name.value, fragmentSuffix, this._declarationBlockConfig),
this.config.experimentalFragmentVariables
? new DeclarationBlock({
...this._declarationBlockConfig,
blockTransformer: t => this.applyVariablesWrapper(t),
})
.export()
.asKind('type')
.withName(
this.convertName(node.name.value, {
suffix: fragmentSuffix + 'Variables',
})
)
.withBlock(this._variablesTransfomer.transform(node.variableDefinitions)).string
: undefined,
]
.filter(r => r)
.join('\n\n');
}
protected applyVariablesWrapper(variablesBlock: string): string {
return variablesBlock;
}
OperationDefinition(node: OperationDefinitionNode): string {
const name = this.handleAnonymousOperation(node);
const operationRootType = getRootType(node.operation, this._schema);
if (!operationRootType) {
throw new Error(`Unable to find root schema type for operation type "${node.operation}"!`);
}
const selectionSet = this._selectionSetToObject.createNext(operationRootType, node.selectionSet);
const visitedOperationVariables = this._variablesTransfomer.transform<VariableDefinitionNode>(
node.variableDefinitions
);
const operationType: string = pascalCase(node.operation);
const operationTypeSuffix = this.getOperationSuffix(name, operationType);
const operationResult = new DeclarationBlock(this._declarationBlockConfig)
.export()
.asKind('type')
.withName(
this.convertName(name, {
suffix: operationTypeSuffix + this._parsedConfig.operationResultSuffix,
})
) | .withContent(selectionSet.transformSelectionSet()).string;
const operationVariables = new DeclarationBlock({
...this._declarationBlockConfig,
blockTransformer: t => this.applyVariablesWrapper(t),
})
.export()
.asKind('type')
.withName(
this.convertName(name, {
suffix: operationTypeSuffix + 'Variables',
})
)
.withBlock(visitedOperationVariables).string;
return [operationVariables, operationResult].filter(r => r).join('\n\n');
}
} | random_line_split | |
base-documents-visitor.ts | import { NormalizedScalarsMap } from './types';
import autoBind from 'auto-bind';
import { DEFAULT_SCALARS } from './scalars';
import { DeclarationBlock, DeclarationBlockConfig, getConfigValue, buildScalarsFromConfig } from './utils';
import {
GraphQLSchema,
FragmentDefinitionNode,
OperationDefinitionNode,
VariableDefinitionNode,
OperationTypeNode,
} from 'graphql';
import { SelectionSetToObject } from './selection-set-to-object';
import { OperationVariablesToObject } from './variables-to-object';
import { BaseVisitor } from './base-visitor';
import { ParsedTypesConfig, RawTypesConfig } from './base-types-visitor';
import { pascalCase } from 'change-case-all';
function getRootType(operation: OperationTypeNode, schema: GraphQLSchema) {
switch (operation) {
case 'query':
return schema.getQueryType();
case 'mutation':
return schema.getMutationType();
case 'subscription':
return schema.getSubscriptionType();
}
throw new Error(`Unknown operation type: ${operation}`);
}
export interface ParsedDocumentsConfig extends ParsedTypesConfig {
addTypename: boolean;
preResolveTypes: boolean;
globalNamespace: boolean;
operationResultSuffix: string;
dedupeOperationSuffix: boolean;
omitOperationSuffix: boolean;
namespacedImportName: string | null;
exportFragmentSpreadSubTypes: boolean;
skipTypeNameForRoot: boolean;
experimentalFragmentVariables: boolean;
}
export interface RawDocumentsConfig extends RawTypesConfig {
/**
* @default true
* @description Uses primitive types where possible.
* Set to `false` in order to use `Pick` and take use the types generated by `typescript` plugin.
*
* @exampleMarkdown
* ```yml
* plugins
* config:
* preResolveTypes: false
* ```
*/
preResolveTypes?: boolean;
/**
* @default false
* @description Avoid adding `__typename` for root types. This is ignored when a selection explicitly specifies `__typename`.
*
* @exampleMarkdown
* ```yml
* plugins
* config:
* skipTypeNameForRoot: true
* ```
*/
skipTypeNameForRoot?: boolean;
/**
* @default false
* @description Puts all generated code under `global` namespace. Useful for Stencil integration.
*
* @exampleMarkdown
* ```yml
* plugins
* config:
* globalNamespace: true
* ```
*/
globalNamespace?: boolean;
/**
* @default ""
* @description Adds a suffix to generated operation result type names
*/
operationResultSuffix?: string;
/**
* @default false
* @description Set this configuration to `true` if you wish to make sure to remove duplicate operation name suffix.
*/
dedupeOperationSuffix?: boolean;
/**
* @default false
* @description Set this configuration to `true` if you wish to disable auto add suffix of operation name, like `Query`, `Mutation`, `Subscription`, `Fragment`.
*/
omitOperationSuffix?: boolean;
/**
* @default false
* @description If set to true, it will export the sub-types created in order to make it easier to access fields declared under fragment spread.
*/
exportFragmentSpreadSubTypes?: boolean;
/**
* @default false
* @description If set to true, it will enable support for parsing variables on fragments.
*/
experimentalFragmentVariables?: boolean;
// The following are internal, and used by presets
/**
* @ignore
*/
namespacedImportName?: string;
}
export class BaseDocumentsVisitor<
TRawConfig extends RawDocumentsConfig = RawDocumentsConfig,
TPluginConfig extends ParsedDocumentsConfig = ParsedDocumentsConfig
> extends BaseVisitor<TRawConfig, TPluginConfig> {
protected _unnamedCounter = 1;
protected _variablesTransfomer: OperationVariablesToObject;
protected _selectionSetToObject: SelectionSetToObject;
protected _globalDeclarations: Set<string> = new Set<string>();
constructor(
rawConfig: TRawConfig,
additionalConfig: TPluginConfig,
protected _schema: GraphQLSchema,
defaultScalars: NormalizedScalarsMap = DEFAULT_SCALARS
) {
super(rawConfig, {
exportFragmentSpreadSubTypes: getConfigValue(rawConfig.exportFragmentSpreadSubTypes, false),
enumPrefix: getConfigValue(rawConfig.enumPrefix, true),
preResolveTypes: getConfigValue(rawConfig.preResolveTypes, true),
dedupeOperationSuffix: getConfigValue(rawConfig.dedupeOperationSuffix, false),
omitOperationSuffix: getConfigValue(rawConfig.omitOperationSuffix, false),
skipTypeNameForRoot: getConfigValue(rawConfig.skipTypeNameForRoot, false),
namespacedImportName: getConfigValue(rawConfig.namespacedImportName, null),
experimentalFragmentVariables: getConfigValue(rawConfig.experimentalFragmentVariables, false),
addTypename: !rawConfig.skipTypename,
globalNamespace: !!rawConfig.globalNamespace,
operationResultSuffix: getConfigValue(rawConfig.operationResultSuffix, ''),
scalars: buildScalarsFromConfig(_schema, rawConfig, defaultScalars),
...((additionalConfig || {}) as any),
});
autoBind(this);
this._variablesTransfomer = new OperationVariablesToObject(
this.scalars,
this.convertName,
this.config.namespacedImportName
);
}
public getGlobalDeclarations(noExport = false): string[] {
return Array.from(this._globalDeclarations).map(t => (noExport ? t : `export ${t}`));
}
setSelectionSetHandler(handler: SelectionSetToObject): void {
this._selectionSetToObject = handler;
}
setDeclarationBlockConfig(config: DeclarationBlockConfig): void {
this._declarationBlockConfig = config;
}
| (variablesTransfomer: OperationVariablesToObject): void {
this._variablesTransfomer = variablesTransfomer;
}
public get schema(): GraphQLSchema {
return this._schema;
}
public get addTypename(): boolean {
return this._parsedConfig.addTypename;
}
private handleAnonymousOperation(node: OperationDefinitionNode): string {
const name = node.name && node.name.value;
if (name) {
return this.convertName(name, {
useTypesPrefix: false,
useTypesSuffix: false,
});
}
return this.convertName(this._unnamedCounter++ + '', {
prefix: 'Unnamed_',
suffix: '_',
useTypesPrefix: false,
useTypesSuffix: false,
});
}
FragmentDefinition(node: FragmentDefinitionNode): string {
const fragmentRootType = this._schema.getType(node.typeCondition.name.value);
const selectionSet = this._selectionSetToObject.createNext(fragmentRootType, node.selectionSet);
const fragmentSuffix = this.getFragmentSuffix(node);
return [
selectionSet.transformFragmentSelectionSetToTypes(node.name.value, fragmentSuffix, this._declarationBlockConfig),
this.config.experimentalFragmentVariables
? new DeclarationBlock({
...this._declarationBlockConfig,
blockTransformer: t => this.applyVariablesWrapper(t),
})
.export()
.asKind('type')
.withName(
this.convertName(node.name.value, {
suffix: fragmentSuffix + 'Variables',
})
)
.withBlock(this._variablesTransfomer.transform(node.variableDefinitions)).string
: undefined,
]
.filter(r => r)
.join('\n\n');
}
protected applyVariablesWrapper(variablesBlock: string): string {
return variablesBlock;
}
OperationDefinition(node: OperationDefinitionNode): string {
const name = this.handleAnonymousOperation(node);
const operationRootType = getRootType(node.operation, this._schema);
if (!operationRootType) {
throw new Error(`Unable to find root schema type for operation type "${node.operation}"!`);
}
const selectionSet = this._selectionSetToObject.createNext(operationRootType, node.selectionSet);
const visitedOperationVariables = this._variablesTransfomer.transform<VariableDefinitionNode>(
node.variableDefinitions
);
const operationType: string = pascalCase(node.operation);
const operationTypeSuffix = this.getOperationSuffix(name, operationType);
const operationResult = new DeclarationBlock(this._declarationBlockConfig)
.export()
.asKind('type')
.withName(
this.convertName(name, {
suffix: operationTypeSuffix + this._parsedConfig.operationResultSuffix,
})
)
.withContent(selectionSet.transformSelectionSet()).string;
const operationVariables = new DeclarationBlock({
...this._declarationBlockConfig,
blockTransformer: t => this.applyVariablesWrapper(t),
})
.export()
.asKind('type')
.withName(
this.convertName(name, {
suffix: operationTypeSuffix + 'Variables',
})
)
.withBlock(visitedOperationVariables).string;
return [operationVariables, operationResult].filter(r => r).join('\n\n');
}
}
| setVariablesTransformer | identifier_name |
base-documents-visitor.ts | import { NormalizedScalarsMap } from './types';
import autoBind from 'auto-bind';
import { DEFAULT_SCALARS } from './scalars';
import { DeclarationBlock, DeclarationBlockConfig, getConfigValue, buildScalarsFromConfig } from './utils';
import {
GraphQLSchema,
FragmentDefinitionNode,
OperationDefinitionNode,
VariableDefinitionNode,
OperationTypeNode,
} from 'graphql';
import { SelectionSetToObject } from './selection-set-to-object';
import { OperationVariablesToObject } from './variables-to-object';
import { BaseVisitor } from './base-visitor';
import { ParsedTypesConfig, RawTypesConfig } from './base-types-visitor';
import { pascalCase } from 'change-case-all';
function getRootType(operation: OperationTypeNode, schema: GraphQLSchema) {
switch (operation) {
case 'query':
return schema.getQueryType();
case 'mutation':
return schema.getMutationType();
case 'subscription':
return schema.getSubscriptionType();
}
throw new Error(`Unknown operation type: ${operation}`);
}
export interface ParsedDocumentsConfig extends ParsedTypesConfig {
addTypename: boolean;
preResolveTypes: boolean;
globalNamespace: boolean;
operationResultSuffix: string;
dedupeOperationSuffix: boolean;
omitOperationSuffix: boolean;
namespacedImportName: string | null;
exportFragmentSpreadSubTypes: boolean;
skipTypeNameForRoot: boolean;
experimentalFragmentVariables: boolean;
}
export interface RawDocumentsConfig extends RawTypesConfig {
/**
* @default true
* @description Uses primitive types where possible.
* Set to `false` in order to use `Pick` and take use the types generated by `typescript` plugin.
*
* @exampleMarkdown
* ```yml
* plugins
* config:
* preResolveTypes: false
* ```
*/
preResolveTypes?: boolean;
/**
* @default false
* @description Avoid adding `__typename` for root types. This is ignored when a selection explicitly specifies `__typename`.
*
* @exampleMarkdown
* ```yml
* plugins
* config:
* skipTypeNameForRoot: true
* ```
*/
skipTypeNameForRoot?: boolean;
/**
* @default false
* @description Puts all generated code under `global` namespace. Useful for Stencil integration.
*
* @exampleMarkdown
* ```yml
* plugins
* config:
* globalNamespace: true
* ```
*/
globalNamespace?: boolean;
/**
* @default ""
* @description Adds a suffix to generated operation result type names
*/
operationResultSuffix?: string;
/**
* @default false
* @description Set this configuration to `true` if you wish to make sure to remove duplicate operation name suffix.
*/
dedupeOperationSuffix?: boolean;
/**
* @default false
* @description Set this configuration to `true` if you wish to disable auto add suffix of operation name, like `Query`, `Mutation`, `Subscription`, `Fragment`.
*/
omitOperationSuffix?: boolean;
/**
* @default false
* @description If set to true, it will export the sub-types created in order to make it easier to access fields declared under fragment spread.
*/
exportFragmentSpreadSubTypes?: boolean;
/**
* @default false
* @description If set to true, it will enable support for parsing variables on fragments.
*/
experimentalFragmentVariables?: boolean;
// The following are internal, and used by presets
/**
* @ignore
*/
namespacedImportName?: string;
}
export class BaseDocumentsVisitor<
TRawConfig extends RawDocumentsConfig = RawDocumentsConfig,
TPluginConfig extends ParsedDocumentsConfig = ParsedDocumentsConfig
> extends BaseVisitor<TRawConfig, TPluginConfig> {
protected _unnamedCounter = 1;
protected _variablesTransfomer: OperationVariablesToObject;
protected _selectionSetToObject: SelectionSetToObject;
protected _globalDeclarations: Set<string> = new Set<string>();
constructor(
rawConfig: TRawConfig,
additionalConfig: TPluginConfig,
protected _schema: GraphQLSchema,
defaultScalars: NormalizedScalarsMap = DEFAULT_SCALARS
) {
super(rawConfig, {
exportFragmentSpreadSubTypes: getConfigValue(rawConfig.exportFragmentSpreadSubTypes, false),
enumPrefix: getConfigValue(rawConfig.enumPrefix, true),
preResolveTypes: getConfigValue(rawConfig.preResolveTypes, true),
dedupeOperationSuffix: getConfigValue(rawConfig.dedupeOperationSuffix, false),
omitOperationSuffix: getConfigValue(rawConfig.omitOperationSuffix, false),
skipTypeNameForRoot: getConfigValue(rawConfig.skipTypeNameForRoot, false),
namespacedImportName: getConfigValue(rawConfig.namespacedImportName, null),
experimentalFragmentVariables: getConfigValue(rawConfig.experimentalFragmentVariables, false),
addTypename: !rawConfig.skipTypename,
globalNamespace: !!rawConfig.globalNamespace,
operationResultSuffix: getConfigValue(rawConfig.operationResultSuffix, ''),
scalars: buildScalarsFromConfig(_schema, rawConfig, defaultScalars),
...((additionalConfig || {}) as any),
});
autoBind(this);
this._variablesTransfomer = new OperationVariablesToObject(
this.scalars,
this.convertName,
this.config.namespacedImportName
);
}
public getGlobalDeclarations(noExport = false): string[] {
return Array.from(this._globalDeclarations).map(t => (noExport ? t : `export ${t}`));
}
setSelectionSetHandler(handler: SelectionSetToObject): void {
this._selectionSetToObject = handler;
}
setDeclarationBlockConfig(config: DeclarationBlockConfig): void {
this._declarationBlockConfig = config;
}
setVariablesTransformer(variablesTransfomer: OperationVariablesToObject): void {
this._variablesTransfomer = variablesTransfomer;
}
public get schema(): GraphQLSchema {
return this._schema;
}
public get addTypename(): boolean {
return this._parsedConfig.addTypename;
}
private handleAnonymousOperation(node: OperationDefinitionNode): string {
const name = node.name && node.name.value;
if (name) {
return this.convertName(name, {
useTypesPrefix: false,
useTypesSuffix: false,
});
}
return this.convertName(this._unnamedCounter++ + '', {
prefix: 'Unnamed_',
suffix: '_',
useTypesPrefix: false,
useTypesSuffix: false,
});
}
FragmentDefinition(node: FragmentDefinitionNode): string |
protected applyVariablesWrapper(variablesBlock: string): string {
return variablesBlock;
}
OperationDefinition(node: OperationDefinitionNode): string {
const name = this.handleAnonymousOperation(node);
const operationRootType = getRootType(node.operation, this._schema);
if (!operationRootType) {
throw new Error(`Unable to find root schema type for operation type "${node.operation}"!`);
}
const selectionSet = this._selectionSetToObject.createNext(operationRootType, node.selectionSet);
const visitedOperationVariables = this._variablesTransfomer.transform<VariableDefinitionNode>(
node.variableDefinitions
);
const operationType: string = pascalCase(node.operation);
const operationTypeSuffix = this.getOperationSuffix(name, operationType);
const operationResult = new DeclarationBlock(this._declarationBlockConfig)
.export()
.asKind('type')
.withName(
this.convertName(name, {
suffix: operationTypeSuffix + this._parsedConfig.operationResultSuffix,
})
)
.withContent(selectionSet.transformSelectionSet()).string;
const operationVariables = new DeclarationBlock({
...this._declarationBlockConfig,
blockTransformer: t => this.applyVariablesWrapper(t),
})
.export()
.asKind('type')
.withName(
this.convertName(name, {
suffix: operationTypeSuffix + 'Variables',
})
)
.withBlock(visitedOperationVariables).string;
return [operationVariables, operationResult].filter(r => r).join('\n\n');
}
}
| {
const fragmentRootType = this._schema.getType(node.typeCondition.name.value);
const selectionSet = this._selectionSetToObject.createNext(fragmentRootType, node.selectionSet);
const fragmentSuffix = this.getFragmentSuffix(node);
return [
selectionSet.transformFragmentSelectionSetToTypes(node.name.value, fragmentSuffix, this._declarationBlockConfig),
this.config.experimentalFragmentVariables
? new DeclarationBlock({
...this._declarationBlockConfig,
blockTransformer: t => this.applyVariablesWrapper(t),
})
.export()
.asKind('type')
.withName(
this.convertName(node.name.value, {
suffix: fragmentSuffix + 'Variables',
})
)
.withBlock(this._variablesTransfomer.transform(node.variableDefinitions)).string
: undefined,
]
.filter(r => r)
.join('\n\n');
} | identifier_body |
base-documents-visitor.ts | import { NormalizedScalarsMap } from './types';
import autoBind from 'auto-bind';
import { DEFAULT_SCALARS } from './scalars';
import { DeclarationBlock, DeclarationBlockConfig, getConfigValue, buildScalarsFromConfig } from './utils';
import {
GraphQLSchema,
FragmentDefinitionNode,
OperationDefinitionNode,
VariableDefinitionNode,
OperationTypeNode,
} from 'graphql';
import { SelectionSetToObject } from './selection-set-to-object';
import { OperationVariablesToObject } from './variables-to-object';
import { BaseVisitor } from './base-visitor';
import { ParsedTypesConfig, RawTypesConfig } from './base-types-visitor';
import { pascalCase } from 'change-case-all';
function getRootType(operation: OperationTypeNode, schema: GraphQLSchema) {
switch (operation) {
case 'query':
return schema.getQueryType();
case 'mutation':
return schema.getMutationType();
case 'subscription':
return schema.getSubscriptionType();
}
throw new Error(`Unknown operation type: ${operation}`);
}
export interface ParsedDocumentsConfig extends ParsedTypesConfig {
addTypename: boolean;
preResolveTypes: boolean;
globalNamespace: boolean;
operationResultSuffix: string;
dedupeOperationSuffix: boolean;
omitOperationSuffix: boolean;
namespacedImportName: string | null;
exportFragmentSpreadSubTypes: boolean;
skipTypeNameForRoot: boolean;
experimentalFragmentVariables: boolean;
}
export interface RawDocumentsConfig extends RawTypesConfig {
/**
* @default true
* @description Uses primitive types where possible.
* Set to `false` in order to use `Pick` and take use the types generated by `typescript` plugin.
*
* @exampleMarkdown
* ```yml
* plugins
* config:
* preResolveTypes: false
* ```
*/
preResolveTypes?: boolean;
/**
* @default false
* @description Avoid adding `__typename` for root types. This is ignored when a selection explicitly specifies `__typename`.
*
* @exampleMarkdown
* ```yml
* plugins
* config:
* skipTypeNameForRoot: true
* ```
*/
skipTypeNameForRoot?: boolean;
/**
* @default false
* @description Puts all generated code under `global` namespace. Useful for Stencil integration.
*
* @exampleMarkdown
* ```yml
* plugins
* config:
* globalNamespace: true
* ```
*/
globalNamespace?: boolean;
/**
* @default ""
* @description Adds a suffix to generated operation result type names
*/
operationResultSuffix?: string;
/**
* @default false
* @description Set this configuration to `true` if you wish to make sure to remove duplicate operation name suffix.
*/
dedupeOperationSuffix?: boolean;
/**
* @default false
* @description Set this configuration to `true` if you wish to disable auto add suffix of operation name, like `Query`, `Mutation`, `Subscription`, `Fragment`.
*/
omitOperationSuffix?: boolean;
/**
* @default false
* @description If set to true, it will export the sub-types created in order to make it easier to access fields declared under fragment spread.
*/
exportFragmentSpreadSubTypes?: boolean;
/**
* @default false
* @description If set to true, it will enable support for parsing variables on fragments.
*/
experimentalFragmentVariables?: boolean;
// The following are internal, and used by presets
/**
* @ignore
*/
namespacedImportName?: string;
}
export class BaseDocumentsVisitor<
TRawConfig extends RawDocumentsConfig = RawDocumentsConfig,
TPluginConfig extends ParsedDocumentsConfig = ParsedDocumentsConfig
> extends BaseVisitor<TRawConfig, TPluginConfig> {
protected _unnamedCounter = 1;
protected _variablesTransfomer: OperationVariablesToObject;
protected _selectionSetToObject: SelectionSetToObject;
protected _globalDeclarations: Set<string> = new Set<string>();
constructor(
rawConfig: TRawConfig,
additionalConfig: TPluginConfig,
protected _schema: GraphQLSchema,
defaultScalars: NormalizedScalarsMap = DEFAULT_SCALARS
) {
super(rawConfig, {
exportFragmentSpreadSubTypes: getConfigValue(rawConfig.exportFragmentSpreadSubTypes, false),
enumPrefix: getConfigValue(rawConfig.enumPrefix, true),
preResolveTypes: getConfigValue(rawConfig.preResolveTypes, true),
dedupeOperationSuffix: getConfigValue(rawConfig.dedupeOperationSuffix, false),
omitOperationSuffix: getConfigValue(rawConfig.omitOperationSuffix, false),
skipTypeNameForRoot: getConfigValue(rawConfig.skipTypeNameForRoot, false),
namespacedImportName: getConfigValue(rawConfig.namespacedImportName, null),
experimentalFragmentVariables: getConfigValue(rawConfig.experimentalFragmentVariables, false),
addTypename: !rawConfig.skipTypename,
globalNamespace: !!rawConfig.globalNamespace,
operationResultSuffix: getConfigValue(rawConfig.operationResultSuffix, ''),
scalars: buildScalarsFromConfig(_schema, rawConfig, defaultScalars),
...((additionalConfig || {}) as any),
});
autoBind(this);
this._variablesTransfomer = new OperationVariablesToObject(
this.scalars,
this.convertName,
this.config.namespacedImportName
);
}
public getGlobalDeclarations(noExport = false): string[] {
return Array.from(this._globalDeclarations).map(t => (noExport ? t : `export ${t}`));
}
setSelectionSetHandler(handler: SelectionSetToObject): void {
this._selectionSetToObject = handler;
}
setDeclarationBlockConfig(config: DeclarationBlockConfig): void {
this._declarationBlockConfig = config;
}
setVariablesTransformer(variablesTransfomer: OperationVariablesToObject): void {
this._variablesTransfomer = variablesTransfomer;
}
public get schema(): GraphQLSchema {
return this._schema;
}
public get addTypename(): boolean {
return this._parsedConfig.addTypename;
}
private handleAnonymousOperation(node: OperationDefinitionNode): string {
const name = node.name && node.name.value;
if (name) |
return this.convertName(this._unnamedCounter++ + '', {
prefix: 'Unnamed_',
suffix: '_',
useTypesPrefix: false,
useTypesSuffix: false,
});
}
FragmentDefinition(node: FragmentDefinitionNode): string {
const fragmentRootType = this._schema.getType(node.typeCondition.name.value);
const selectionSet = this._selectionSetToObject.createNext(fragmentRootType, node.selectionSet);
const fragmentSuffix = this.getFragmentSuffix(node);
return [
selectionSet.transformFragmentSelectionSetToTypes(node.name.value, fragmentSuffix, this._declarationBlockConfig),
this.config.experimentalFragmentVariables
? new DeclarationBlock({
...this._declarationBlockConfig,
blockTransformer: t => this.applyVariablesWrapper(t),
})
.export()
.asKind('type')
.withName(
this.convertName(node.name.value, {
suffix: fragmentSuffix + 'Variables',
})
)
.withBlock(this._variablesTransfomer.transform(node.variableDefinitions)).string
: undefined,
]
.filter(r => r)
.join('\n\n');
}
protected applyVariablesWrapper(variablesBlock: string): string {
return variablesBlock;
}
OperationDefinition(node: OperationDefinitionNode): string {
const name = this.handleAnonymousOperation(node);
const operationRootType = getRootType(node.operation, this._schema);
if (!operationRootType) {
throw new Error(`Unable to find root schema type for operation type "${node.operation}"!`);
}
const selectionSet = this._selectionSetToObject.createNext(operationRootType, node.selectionSet);
const visitedOperationVariables = this._variablesTransfomer.transform<VariableDefinitionNode>(
node.variableDefinitions
);
const operationType: string = pascalCase(node.operation);
const operationTypeSuffix = this.getOperationSuffix(name, operationType);
const operationResult = new DeclarationBlock(this._declarationBlockConfig)
.export()
.asKind('type')
.withName(
this.convertName(name, {
suffix: operationTypeSuffix + this._parsedConfig.operationResultSuffix,
})
)
.withContent(selectionSet.transformSelectionSet()).string;
const operationVariables = new DeclarationBlock({
...this._declarationBlockConfig,
blockTransformer: t => this.applyVariablesWrapper(t),
})
.export()
.asKind('type')
.withName(
this.convertName(name, {
suffix: operationTypeSuffix + 'Variables',
})
)
.withBlock(visitedOperationVariables).string;
return [operationVariables, operationResult].filter(r => r).join('\n\n');
}
}
| {
return this.convertName(name, {
useTypesPrefix: false,
useTypesSuffix: false,
});
} | conditional_block |
home.component.ts | import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { BooksComponent } from '../top-sellers/books.component';
import { BookDetailsComponent } from '../top-sellers/book-details.component';
import { MomentFormatterPipe } from '../common/moment-formatter/moment-formatter.pipe';
import { IBook } from '../top-sellers/books.service';
import { ExternLibsService } from '../common/extern-libs/extern-libs.service';
import { ConfigService } from '../common/config/config.service';
import { SpinnerService } from '../common/spinner/spinner.service';
@Component({
moduleId: module.id,
selector: 'home',
styleUrls: ['home.style.css'],
directives: [
BooksComponent,
BookDetailsComponent
],
pipes: [
MomentFormatterPipe
],
template: `
<span *ngIf="model !== null">
<div class="jumbotron">
<h1>{{ model.config.companyName }}</h1>
<p>Welcome! Checkout our top sellers <a (click)="onTopSellersClick()" class="mouse-hand">here</a>.</p>
</div>
</span>
`
})
export class HomeComponent implements OnInit {
model: any = null
constructor(
private router: Router,
private externLibsService: ExternLibsService,
private configService: ConfigService,
private spinnerService: SpinnerService
){
}
ngOnInit(){
let model: any = {};
model.selectedBook = null;
let moment = this.externLibsService.moment();
model.currentDate = moment();
this.spinnerService.show();
this.configService.getConfig().finally(() => {
this.spinnerService.hide();
}).subscribe((result) => {
model.config = result;
this.model = model;
}, (e) => {
console.log(e);
});
}
onBookSelected(book: IBook){
if(this.model !== null) |
}
onTopSellersClick(){
this.router.navigate(['/top-sellers']);
}
} | {
this.model.selectedBook = book;
} | conditional_block |
home.component.ts | import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { BooksComponent } from '../top-sellers/books.component';
import { BookDetailsComponent } from '../top-sellers/book-details.component';
import { MomentFormatterPipe } from '../common/moment-formatter/moment-formatter.pipe';
import { IBook } from '../top-sellers/books.service';
import { ExternLibsService } from '../common/extern-libs/extern-libs.service';
import { ConfigService } from '../common/config/config.service';
import { SpinnerService } from '../common/spinner/spinner.service';
@Component({
moduleId: module.id,
selector: 'home',
styleUrls: ['home.style.css'],
directives: [
BooksComponent,
BookDetailsComponent
],
pipes: [
MomentFormatterPipe
],
template: `
<span *ngIf="model !== null">
<div class="jumbotron">
<h1>{{ model.config.companyName }}</h1>
<p>Welcome! Checkout our top sellers <a (click)="onTopSellersClick()" class="mouse-hand">here</a>.</p>
</div>
</span>
`
})
export class HomeComponent implements OnInit {
model: any = null
constructor(
private router: Router,
private externLibsService: ExternLibsService,
private configService: ConfigService,
private spinnerService: SpinnerService
){
}
ngOnInit(){
let model: any = {};
model.selectedBook = null;
let moment = this.externLibsService.moment();
model.currentDate = moment();
this.spinnerService.show();
this.configService.getConfig().finally(() => {
this.spinnerService.hide();
}).subscribe((result) => {
model.config = result;
this.model = model;
}, (e) => {
console.log(e);
});
}
onBookSelected(book: IBook){
if(this.model !== null){
this.model.selectedBook = book;
}
}
onTopSellersClick(){
this.router.navigate(['/top-sellers']); | }
} | random_line_split | |
home.component.ts | import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { BooksComponent } from '../top-sellers/books.component';
import { BookDetailsComponent } from '../top-sellers/book-details.component';
import { MomentFormatterPipe } from '../common/moment-formatter/moment-formatter.pipe';
import { IBook } from '../top-sellers/books.service';
import { ExternLibsService } from '../common/extern-libs/extern-libs.service';
import { ConfigService } from '../common/config/config.service';
import { SpinnerService } from '../common/spinner/spinner.service';
@Component({
moduleId: module.id,
selector: 'home',
styleUrls: ['home.style.css'],
directives: [
BooksComponent,
BookDetailsComponent
],
pipes: [
MomentFormatterPipe
],
template: `
<span *ngIf="model !== null">
<div class="jumbotron">
<h1>{{ model.config.companyName }}</h1>
<p>Welcome! Checkout our top sellers <a (click)="onTopSellersClick()" class="mouse-hand">here</a>.</p>
</div>
</span>
`
})
export class HomeComponent implements OnInit {
model: any = null
constructor(
private router: Router,
private externLibsService: ExternLibsService,
private configService: ConfigService,
private spinnerService: SpinnerService
){
}
| (){
let model: any = {};
model.selectedBook = null;
let moment = this.externLibsService.moment();
model.currentDate = moment();
this.spinnerService.show();
this.configService.getConfig().finally(() => {
this.spinnerService.hide();
}).subscribe((result) => {
model.config = result;
this.model = model;
}, (e) => {
console.log(e);
});
}
onBookSelected(book: IBook){
if(this.model !== null){
this.model.selectedBook = book;
}
}
onTopSellersClick(){
this.router.navigate(['/top-sellers']);
}
} | ngOnInit | identifier_name |
util.js | 'use strict';
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const os = require("os");
const fs = require("fs");
const path = require("path");
const request = require("request");
const sax = require("sax");
function checkExistence(command) {
let isWin = process.platform === 'win32';
if (!command) |
for (let dir of process.env.PATH.split(isWin ? ';' : ':')) {
for (let extension of [''].concat(isWin ? ['.exe', '.bat', '.cmd'] : [])) {
try {
fs.accessSync(path.join(dir, command + extension), fs.constants.X_OK);
return true;
}
catch (e) { }
}
}
return false;
}
exports.checkExistence = checkExistence;
function getInfo(packageInfo) {
let platformInfo = packageInfo[process.platform];
let info = (typeof platformInfo !== 'string') ? platformInfo || {} : { source: platformInfo };
return Object.assign({}, packageInfo, info);
}
exports.getInfo = getInfo;
function retrieveLatestVersion(version, outputListener) {
return __awaiter(this, void 0, void 0, function* () {
if (outputListener) {
outputListener('Fetching version number...' + os.EOL);
}
try {
const feed = yield new Promise((resolve) => {
request.get(version.feed, (err, message, body) => resolve(body.toString()));
});
let parser = sax.parser(false, null);
return new Promise((resolve) => {
let matches = [];
parser.ontext = (text) => {
let match = text.match(typeof version.regexp !== 'string'
? version.regexp
: new RegExp(version.regexp));
if (match) {
matches.push(match[1]);
}
};
parser.onend = () => {
resolve(matches.reduce((previous, current) => previous > current ? previous : current));
};
parser.write(feed).end();
});
}
catch (err) {
return '';
}
});
}
exports.retrieveLatestVersion = retrieveLatestVersion;
//# sourceMappingURL=util.js.map | {
return true;
} | conditional_block |
util.js | 'use strict';
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const os = require("os");
const fs = require("fs");
const path = require("path");
const request = require("request");
const sax = require("sax");
function checkExistence(command) {
let isWin = process.platform === 'win32';
if (!command) {
return true;
}
for (let dir of process.env.PATH.split(isWin ? ';' : ':')) {
for (let extension of [''].concat(isWin ? ['.exe', '.bat', '.cmd'] : [])) {
try {
fs.accessSync(path.join(dir, command + extension), fs.constants.X_OK);
return true;
}
catch (e) { }
}
}
return false;
}
exports.checkExistence = checkExistence;
function getInfo(packageInfo) {
let platformInfo = packageInfo[process.platform];
let info = (typeof platformInfo !== 'string') ? platformInfo || {} : { source: platformInfo };
return Object.assign({}, packageInfo, info);
}
exports.getInfo = getInfo;
function retrieveLatestVersion(version, outputListener) {
return __awaiter(this, void 0, void 0, function* () {
if (outputListener) {
outputListener('Fetching version number...' + os.EOL);
}
try {
const feed = yield new Promise((resolve) => {
request.get(version.feed, (err, message, body) => resolve(body.toString()));
});
let parser = sax.parser(false, null);
return new Promise((resolve) => {
let matches = [];
parser.ontext = (text) => {
let match = text.match(typeof version.regexp !== 'string' | };
parser.onend = () => {
resolve(matches.reduce((previous, current) => previous > current ? previous : current));
};
parser.write(feed).end();
});
}
catch (err) {
return '';
}
});
}
exports.retrieveLatestVersion = retrieveLatestVersion;
//# sourceMappingURL=util.js.map | ? version.regexp
: new RegExp(version.regexp));
if (match) {
matches.push(match[1]);
} | random_line_split |
util.js | 'use strict';
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function | (result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const os = require("os");
const fs = require("fs");
const path = require("path");
const request = require("request");
const sax = require("sax");
function checkExistence(command) {
let isWin = process.platform === 'win32';
if (!command) {
return true;
}
for (let dir of process.env.PATH.split(isWin ? ';' : ':')) {
for (let extension of [''].concat(isWin ? ['.exe', '.bat', '.cmd'] : [])) {
try {
fs.accessSync(path.join(dir, command + extension), fs.constants.X_OK);
return true;
}
catch (e) { }
}
}
return false;
}
exports.checkExistence = checkExistence;
function getInfo(packageInfo) {
let platformInfo = packageInfo[process.platform];
let info = (typeof platformInfo !== 'string') ? platformInfo || {} : { source: platformInfo };
return Object.assign({}, packageInfo, info);
}
exports.getInfo = getInfo;
function retrieveLatestVersion(version, outputListener) {
return __awaiter(this, void 0, void 0, function* () {
if (outputListener) {
outputListener('Fetching version number...' + os.EOL);
}
try {
const feed = yield new Promise((resolve) => {
request.get(version.feed, (err, message, body) => resolve(body.toString()));
});
let parser = sax.parser(false, null);
return new Promise((resolve) => {
let matches = [];
parser.ontext = (text) => {
let match = text.match(typeof version.regexp !== 'string'
? version.regexp
: new RegExp(version.regexp));
if (match) {
matches.push(match[1]);
}
};
parser.onend = () => {
resolve(matches.reduce((previous, current) => previous > current ? previous : current));
};
parser.write(feed).end();
});
}
catch (err) {
return '';
}
});
}
exports.retrieveLatestVersion = retrieveLatestVersion;
//# sourceMappingURL=util.js.map | step | identifier_name |
util.js | 'use strict';
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) |
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const os = require("os");
const fs = require("fs");
const path = require("path");
const request = require("request");
const sax = require("sax");
function checkExistence(command) {
let isWin = process.platform === 'win32';
if (!command) {
return true;
}
for (let dir of process.env.PATH.split(isWin ? ';' : ':')) {
for (let extension of [''].concat(isWin ? ['.exe', '.bat', '.cmd'] : [])) {
try {
fs.accessSync(path.join(dir, command + extension), fs.constants.X_OK);
return true;
}
catch (e) { }
}
}
return false;
}
exports.checkExistence = checkExistence;
function getInfo(packageInfo) {
let platformInfo = packageInfo[process.platform];
let info = (typeof platformInfo !== 'string') ? platformInfo || {} : { source: platformInfo };
return Object.assign({}, packageInfo, info);
}
exports.getInfo = getInfo;
function retrieveLatestVersion(version, outputListener) {
return __awaiter(this, void 0, void 0, function* () {
if (outputListener) {
outputListener('Fetching version number...' + os.EOL);
}
try {
const feed = yield new Promise((resolve) => {
request.get(version.feed, (err, message, body) => resolve(body.toString()));
});
let parser = sax.parser(false, null);
return new Promise((resolve) => {
let matches = [];
parser.ontext = (text) => {
let match = text.match(typeof version.regexp !== 'string'
? version.regexp
: new RegExp(version.regexp));
if (match) {
matches.push(match[1]);
}
};
parser.onend = () => {
resolve(matches.reduce((previous, current) => previous > current ? previous : current));
};
parser.write(feed).end();
});
}
catch (err) {
return '';
}
});
}
exports.retrieveLatestVersion = retrieveLatestVersion;
//# sourceMappingURL=util.js.map | { try { step(generator["throw"](value)); } catch (e) { reject(e); } } | identifier_body |
media.js | jQuery(document).ready(function($){
// Use only one frame for all upload fields
var frame = new Array(), media = wp.media;
// add image field
function dtGetImageHtml( data ) {
var template = wp.media.template('dt-post-gallery-item');
return template(data);
}
function fetch_selection( ids, options ) |
$( 'body' ).on( 'click', '.rwmb-image-advanced-upload-mk2', function( e ) {
e.preventDefault();
var $uploadButton = $( this ),
options = {
frame: 'post',
state: 'gallery-library',
button: 'Add image',
class: 'media-frame rwmb-media-frame rwmb-media-frame-mk2'
},
$imageList = $uploadButton.siblings( '.rwmb-images' ),
maxFileUploads = $imageList.data( 'max_file_uploads' ),
msg = 'You may only upload ' + maxFileUploads + ' file',
frame_key = _.random(0, 999999999999999999),
$images = $imageList.find('.rwmb-delete-file'),
ids = new Array();
if ( 1 == maxFileUploads ) {
options.frame = 'select';
options.state = 'library';
}
if ( maxFileUploads > 1 )
msg += 's';
for (var i=0; i<$images.length; i++ ) {
ids[i] = jQuery($images[i]).attr('data-attachment_id');
}
var prefill = fetch_selection( ids, options );
// If the media frame already exists, reopen it.
if ( frame[frame_key] )
{
frame[frame_key].open();
return;
}
// Create the media frame.
frame[frame_key] = wp.media(
{
frame: options.frame,
state: options.state,
library: { type: 'image' },
button: { text: options.button },
className: options['class'],
selection: prefill
});
// Remove all attached 'select' and 'update' events
frame[frame_key].off( 'update select' );
// Handle selection
frame[frame_key].on( 'update select', function(e) {
// Get selections
var uploaded = $imageList.children().length,
selLength, ids = [];
// for gallery
if(typeof e !== 'undefined') {
selection = e;
// for sigle image
} else {
selection = frame[frame_key].state().get('selection');
}
selection = selection.toJSON();
selLength = selection.length;
for ( var i=0; i<selLength; i++ ) {
ids[i] = selection[i].id;
}
if ( maxFileUploads > 0 && ( uploaded + selLength ) > maxFileUploads ) {
if ( uploaded < maxFileUploads )
selection = selection.slice( 0, maxFileUploads - uploaded );
alert( msg );
}
// Attach attachment to field and get HTML
var data = {
action : 'rwmb_attach_media',
post_id : $( '#post_ID' ).val(),
field_id : $imageList.data( 'field_id' ),
attachments_ids : ids,
_ajax_nonce : $uploadButton.data( 'attach_media_nonce' )
};
$.post( ajaxurl, data, function( r ) {
var r = wpAjax.parseAjaxResponse( r, 'ajax-response' );
if ( r.errors ) {
alert( r.responses[0].errors[0].message );
} else {
var tplData = { editTitle: 'Edit', deleteTitle: 'Delete' },
html = '';
for ( var i=0; i<selLength; i++ ) {
var item = selection[i];
html += dtGetImageHtml( jQuery.extend( tplData, {
imgID : item.id,
imgSrc : item.sizes.thumbnail && item.sizes.thumbnail.url ? item.sizes.thumbnail.url : item.url,
editHref: item.editLink
} ) );
}
$imageList.children().remove();
$imageList.removeClass( 'hidden' ).prepend( html );
}
// Hide files button if reach max file uploads
if ( maxFileUploads && $imageList.children().length >= maxFileUploads ) {
$uploadButton.addClass( 'hidden' );
}
}, 'xml' );
} );
// Finally, open the modal
frame[frame_key].open();
} );
}); | {
if ( typeof ids == 'undefined' || ids.length <= 0 ) return;
var id_array = ids,
args = {orderby: "post__in", order: "ASC", type: "image", perPage: -1, post__in: id_array},
attachments = wp.media.query( args ),
selection = new wp.media.model.Selection( attachments.models,
{
props: attachments.props.toJSON(),
multiple: true
});
if ( options.state == 'gallery-library' && !isNaN( parseInt(id_array[0],10)) && id_array.length ) {
options.state = 'gallery-edit';
}
return selection;
} | identifier_body |
media.js | jQuery(document).ready(function($){
// Use only one frame for all upload fields
var frame = new Array(), media = wp.media;
// add image field
function dtGetImageHtml( data ) {
var template = wp.media.template('dt-post-gallery-item');
return template(data);
}
function | ( ids, options ) {
if ( typeof ids == 'undefined' || ids.length <= 0 ) return;
var id_array = ids,
args = {orderby: "post__in", order: "ASC", type: "image", perPage: -1, post__in: id_array},
attachments = wp.media.query( args ),
selection = new wp.media.model.Selection( attachments.models,
{
props: attachments.props.toJSON(),
multiple: true
});
if ( options.state == 'gallery-library' && !isNaN( parseInt(id_array[0],10)) && id_array.length ) {
options.state = 'gallery-edit';
}
return selection;
}
$( 'body' ).on( 'click', '.rwmb-image-advanced-upload-mk2', function( e ) {
e.preventDefault();
var $uploadButton = $( this ),
options = {
frame: 'post',
state: 'gallery-library',
button: 'Add image',
class: 'media-frame rwmb-media-frame rwmb-media-frame-mk2'
},
$imageList = $uploadButton.siblings( '.rwmb-images' ),
maxFileUploads = $imageList.data( 'max_file_uploads' ),
msg = 'You may only upload ' + maxFileUploads + ' file',
frame_key = _.random(0, 999999999999999999),
$images = $imageList.find('.rwmb-delete-file'),
ids = new Array();
if ( 1 == maxFileUploads ) {
options.frame = 'select';
options.state = 'library';
}
if ( maxFileUploads > 1 )
msg += 's';
for (var i=0; i<$images.length; i++ ) {
ids[i] = jQuery($images[i]).attr('data-attachment_id');
}
var prefill = fetch_selection( ids, options );
// If the media frame already exists, reopen it.
if ( frame[frame_key] )
{
frame[frame_key].open();
return;
}
// Create the media frame.
frame[frame_key] = wp.media(
{
frame: options.frame,
state: options.state,
library: { type: 'image' },
button: { text: options.button },
className: options['class'],
selection: prefill
});
// Remove all attached 'select' and 'update' events
frame[frame_key].off( 'update select' );
// Handle selection
frame[frame_key].on( 'update select', function(e) {
// Get selections
var uploaded = $imageList.children().length,
selLength, ids = [];
// for gallery
if(typeof e !== 'undefined') {
selection = e;
// for sigle image
} else {
selection = frame[frame_key].state().get('selection');
}
selection = selection.toJSON();
selLength = selection.length;
for ( var i=0; i<selLength; i++ ) {
ids[i] = selection[i].id;
}
if ( maxFileUploads > 0 && ( uploaded + selLength ) > maxFileUploads ) {
if ( uploaded < maxFileUploads )
selection = selection.slice( 0, maxFileUploads - uploaded );
alert( msg );
}
// Attach attachment to field and get HTML
var data = {
action : 'rwmb_attach_media',
post_id : $( '#post_ID' ).val(),
field_id : $imageList.data( 'field_id' ),
attachments_ids : ids,
_ajax_nonce : $uploadButton.data( 'attach_media_nonce' )
};
$.post( ajaxurl, data, function( r ) {
var r = wpAjax.parseAjaxResponse( r, 'ajax-response' );
if ( r.errors ) {
alert( r.responses[0].errors[0].message );
} else {
var tplData = { editTitle: 'Edit', deleteTitle: 'Delete' },
html = '';
for ( var i=0; i<selLength; i++ ) {
var item = selection[i];
html += dtGetImageHtml( jQuery.extend( tplData, {
imgID : item.id,
imgSrc : item.sizes.thumbnail && item.sizes.thumbnail.url ? item.sizes.thumbnail.url : item.url,
editHref: item.editLink
} ) );
}
$imageList.children().remove();
$imageList.removeClass( 'hidden' ).prepend( html );
}
// Hide files button if reach max file uploads
if ( maxFileUploads && $imageList.children().length >= maxFileUploads ) {
$uploadButton.addClass( 'hidden' );
}
}, 'xml' );
} );
// Finally, open the modal
frame[frame_key].open();
} );
}); | fetch_selection | identifier_name |
media.js | jQuery(document).ready(function($){
// Use only one frame for all upload fields
var frame = new Array(), media = wp.media;
// add image field
function dtGetImageHtml( data ) {
var template = wp.media.template('dt-post-gallery-item');
return template(data);
}
function fetch_selection( ids, options ) {
if ( typeof ids == 'undefined' || ids.length <= 0 ) return;
var id_array = ids,
args = {orderby: "post__in", order: "ASC", type: "image", perPage: -1, post__in: id_array},
attachments = wp.media.query( args ),
selection = new wp.media.model.Selection( attachments.models,
{
props: attachments.props.toJSON(),
multiple: true
});
if ( options.state == 'gallery-library' && !isNaN( parseInt(id_array[0],10)) && id_array.length ) |
return selection;
}
$( 'body' ).on( 'click', '.rwmb-image-advanced-upload-mk2', function( e ) {
e.preventDefault();
var $uploadButton = $( this ),
options = {
frame: 'post',
state: 'gallery-library',
button: 'Add image',
class: 'media-frame rwmb-media-frame rwmb-media-frame-mk2'
},
$imageList = $uploadButton.siblings( '.rwmb-images' ),
maxFileUploads = $imageList.data( 'max_file_uploads' ),
msg = 'You may only upload ' + maxFileUploads + ' file',
frame_key = _.random(0, 999999999999999999),
$images = $imageList.find('.rwmb-delete-file'),
ids = new Array();
if ( 1 == maxFileUploads ) {
options.frame = 'select';
options.state = 'library';
}
if ( maxFileUploads > 1 )
msg += 's';
for (var i=0; i<$images.length; i++ ) {
ids[i] = jQuery($images[i]).attr('data-attachment_id');
}
var prefill = fetch_selection( ids, options );
// If the media frame already exists, reopen it.
if ( frame[frame_key] )
{
frame[frame_key].open();
return;
}
// Create the media frame.
frame[frame_key] = wp.media(
{
frame: options.frame,
state: options.state,
library: { type: 'image' },
button: { text: options.button },
className: options['class'],
selection: prefill
});
// Remove all attached 'select' and 'update' events
frame[frame_key].off( 'update select' );
// Handle selection
frame[frame_key].on( 'update select', function(e) {
// Get selections
var uploaded = $imageList.children().length,
selLength, ids = [];
// for gallery
if(typeof e !== 'undefined') {
selection = e;
// for sigle image
} else {
selection = frame[frame_key].state().get('selection');
}
selection = selection.toJSON();
selLength = selection.length;
for ( var i=0; i<selLength; i++ ) {
ids[i] = selection[i].id;
}
if ( maxFileUploads > 0 && ( uploaded + selLength ) > maxFileUploads ) {
if ( uploaded < maxFileUploads )
selection = selection.slice( 0, maxFileUploads - uploaded );
alert( msg );
}
// Attach attachment to field and get HTML
var data = {
action : 'rwmb_attach_media',
post_id : $( '#post_ID' ).val(),
field_id : $imageList.data( 'field_id' ),
attachments_ids : ids,
_ajax_nonce : $uploadButton.data( 'attach_media_nonce' )
};
$.post( ajaxurl, data, function( r ) {
var r = wpAjax.parseAjaxResponse( r, 'ajax-response' );
if ( r.errors ) {
alert( r.responses[0].errors[0].message );
} else {
var tplData = { editTitle: 'Edit', deleteTitle: 'Delete' },
html = '';
for ( var i=0; i<selLength; i++ ) {
var item = selection[i];
html += dtGetImageHtml( jQuery.extend( tplData, {
imgID : item.id,
imgSrc : item.sizes.thumbnail && item.sizes.thumbnail.url ? item.sizes.thumbnail.url : item.url,
editHref: item.editLink
} ) );
}
$imageList.children().remove();
$imageList.removeClass( 'hidden' ).prepend( html );
}
// Hide files button if reach max file uploads
if ( maxFileUploads && $imageList.children().length >= maxFileUploads ) {
$uploadButton.addClass( 'hidden' );
}
}, 'xml' );
} );
// Finally, open the modal
frame[frame_key].open();
} );
}); | {
options.state = 'gallery-edit';
} | conditional_block |
media.js | jQuery(document).ready(function($){
// Use only one frame for all upload fields
var frame = new Array(), media = wp.media;
// add image field
function dtGetImageHtml( data ) {
var template = wp.media.template('dt-post-gallery-item');
return template(data);
}
function fetch_selection( ids, options ) {
if ( typeof ids == 'undefined' || ids.length <= 0 ) return;
var id_array = ids,
args = {orderby: "post__in", order: "ASC", type: "image", perPage: -1, post__in: id_array},
attachments = wp.media.query( args ),
selection = new wp.media.model.Selection( attachments.models,
{
props: attachments.props.toJSON(),
multiple: true
| return selection;
}
$( 'body' ).on( 'click', '.rwmb-image-advanced-upload-mk2', function( e ) {
e.preventDefault();
var $uploadButton = $( this ),
options = {
frame: 'post',
state: 'gallery-library',
button: 'Add image',
class: 'media-frame rwmb-media-frame rwmb-media-frame-mk2'
},
$imageList = $uploadButton.siblings( '.rwmb-images' ),
maxFileUploads = $imageList.data( 'max_file_uploads' ),
msg = 'You may only upload ' + maxFileUploads + ' file',
frame_key = _.random(0, 999999999999999999),
$images = $imageList.find('.rwmb-delete-file'),
ids = new Array();
if ( 1 == maxFileUploads ) {
options.frame = 'select';
options.state = 'library';
}
if ( maxFileUploads > 1 )
msg += 's';
for (var i=0; i<$images.length; i++ ) {
ids[i] = jQuery($images[i]).attr('data-attachment_id');
}
var prefill = fetch_selection( ids, options );
// If the media frame already exists, reopen it.
if ( frame[frame_key] )
{
frame[frame_key].open();
return;
}
// Create the media frame.
frame[frame_key] = wp.media(
{
frame: options.frame,
state: options.state,
library: { type: 'image' },
button: { text: options.button },
className: options['class'],
selection: prefill
});
// Remove all attached 'select' and 'update' events
frame[frame_key].off( 'update select' );
// Handle selection
frame[frame_key].on( 'update select', function(e) {
// Get selections
var uploaded = $imageList.children().length,
selLength, ids = [];
// for gallery
if(typeof e !== 'undefined') {
selection = e;
// for sigle image
} else {
selection = frame[frame_key].state().get('selection');
}
selection = selection.toJSON();
selLength = selection.length;
for ( var i=0; i<selLength; i++ ) {
ids[i] = selection[i].id;
}
if ( maxFileUploads > 0 && ( uploaded + selLength ) > maxFileUploads ) {
if ( uploaded < maxFileUploads )
selection = selection.slice( 0, maxFileUploads - uploaded );
alert( msg );
}
// Attach attachment to field and get HTML
var data = {
action : 'rwmb_attach_media',
post_id : $( '#post_ID' ).val(),
field_id : $imageList.data( 'field_id' ),
attachments_ids : ids,
_ajax_nonce : $uploadButton.data( 'attach_media_nonce' )
};
$.post( ajaxurl, data, function( r ) {
var r = wpAjax.parseAjaxResponse( r, 'ajax-response' );
if ( r.errors ) {
alert( r.responses[0].errors[0].message );
} else {
var tplData = { editTitle: 'Edit', deleteTitle: 'Delete' },
html = '';
for ( var i=0; i<selLength; i++ ) {
var item = selection[i];
html += dtGetImageHtml( jQuery.extend( tplData, {
imgID : item.id,
imgSrc : item.sizes.thumbnail && item.sizes.thumbnail.url ? item.sizes.thumbnail.url : item.url,
editHref: item.editLink
} ) );
}
$imageList.children().remove();
$imageList.removeClass( 'hidden' ).prepend( html );
}
// Hide files button if reach max file uploads
if ( maxFileUploads && $imageList.children().length >= maxFileUploads ) {
$uploadButton.addClass( 'hidden' );
}
}, 'xml' );
} );
// Finally, open the modal
frame[frame_key].open();
} );
}); | });
if ( options.state == 'gallery-library' && !isNaN( parseInt(id_array[0],10)) && id_array.length ) {
options.state = 'gallery-edit';
}
| random_line_split |
main.rs | extern crate rand;
use std::io;
use std::cmp::Ordering;
use rand::Rng;
fn | () {
println!("Guess the number!");
let secret_number = rand::thread_rng().gen_range(1, 101);
println!("The secret number is: {}", secret_number);
loop {
println!("Please input your guess.");
let mut guess = String::new();
io::stdin().read_line(&mut guess)
.expect("Failed to read line");
println!("You guessed {}", guess);
let guess: u32 = match guess.trim().parse() {
Ok(num) => num,
Err(_) => continue,
};
match guess.cmp(&secret_number) {
Ordering::Less => println!("Too small!"),
Ordering::Greater => println!("Too big!"),
Ordering::Equal => {
println!("You win!");
break;
}
}
}
}
| main | identifier_name |
main.rs | extern crate rand;
use std::io;
use std::cmp::Ordering;
use rand::Rng;
fn main() {
println!("Guess the number!");
let secret_number = rand::thread_rng().gen_range(1, 101);
println!("The secret number is: {}", secret_number);
loop {
println!("Please input your guess."); |
let guess: u32 = match guess.trim().parse() {
Ok(num) => num,
Err(_) => continue,
};
match guess.cmp(&secret_number) {
Ordering::Less => println!("Too small!"),
Ordering::Greater => println!("Too big!"),
Ordering::Equal => {
println!("You win!");
break;
}
}
}
} |
let mut guess = String::new();
io::stdin().read_line(&mut guess)
.expect("Failed to read line");
println!("You guessed {}", guess); | random_line_split |
main.rs | extern crate rand;
use std::io;
use std::cmp::Ordering;
use rand::Rng;
fn main() | {
println!("Guess the number!");
let secret_number = rand::thread_rng().gen_range(1, 101);
println!("The secret number is: {}", secret_number);
loop {
println!("Please input your guess.");
let mut guess = String::new();
io::stdin().read_line(&mut guess)
.expect("Failed to read line");
println!("You guessed {}", guess);
let guess: u32 = match guess.trim().parse() {
Ok(num) => num,
Err(_) => continue,
};
match guess.cmp(&secret_number) {
Ordering::Less => println!("Too small!"),
Ordering::Greater => println!("Too big!"),
Ordering::Equal => {
println!("You win!");
break;
}
}
}
} | identifier_body | |
gesture.ts | import { Options, Data, PointerData, RETURN_FLAG } from './utils';
import { Listener, DefaultListener, ListenerArgs } from './listener';
export interface GestureFactory<
G extends Gesture<O, D, L>,
O extends Options = Options,
D extends Data = Data,
L extends Listener<O, D> = Listener<O, D>
> {
new (listener: L, data: D, target: Element): G;
}
export class Gesture<O extends Options = Options, D extends Data = Data, L extends Listener<O, D> = Listener<O, D>> {
public __POINTERIDS__: number[] = [];
public __REMOVED_POINTERS__: PointerData[] = [];
public startEmitted: boolean = false;
public args: ListenerArgs<D> = {} as ListenerArgs<D>;
constructor(public listener: L, public data: D, public target: Element) {
this.args.data = data;
this.args.target = target;
}
// tslint:disable-next-line:variable-name
public bind(
target: Element,
registerListener: <G extends Gesture<O, D, L>, O extends Options, D extends Data, L extends Listener<O, D>>(
Type: GestureFactory<G, O, D, L>,
element: Element,
listener: Partial<DefaultListener>
) => () => void,
remove: () => void,
evt: Event
): void;
public bind() {}
public unbind(): number {
return RETURN_FLAG.IDLE;
}
public start(args: ListenerArgs<D>): number;
public start() |
public update(args: ListenerArgs<D>): number;
public update() {
return RETURN_FLAG.IDLE;
}
public end(args: ListenerArgs<D>): number;
public end() {
return RETURN_FLAG.IDLE;
}
public cancel(): number {
return this.listener.cancel();
}
public stop(): void {
this.listener.stop();
}
}
| {
return RETURN_FLAG.IDLE;
} | identifier_body |
gesture.ts | import { Options, Data, PointerData, RETURN_FLAG } from './utils';
import { Listener, DefaultListener, ListenerArgs } from './listener';
export interface GestureFactory<
G extends Gesture<O, D, L>,
O extends Options = Options,
D extends Data = Data,
L extends Listener<O, D> = Listener<O, D>
> {
new (listener: L, data: D, target: Element): G;
}
export class Gesture<O extends Options = Options, D extends Data = Data, L extends Listener<O, D> = Listener<O, D>> {
public __POINTERIDS__: number[] = [];
public __REMOVED_POINTERS__: PointerData[] = [];
public startEmitted: boolean = false;
public args: ListenerArgs<D> = {} as ListenerArgs<D>;
constructor(public listener: L, public data: D, public target: Element) {
this.args.data = data;
this.args.target = target;
}
// tslint:disable-next-line:variable-name
public bind(
target: Element,
registerListener: <G extends Gesture<O, D, L>, O extends Options, D extends Data, L extends Listener<O, D>>(
Type: GestureFactory<G, O, D, L>,
element: Element,
listener: Partial<DefaultListener>
) => () => void,
remove: () => void,
evt: Event
): void;
public bind() {}
public unbind(): number {
return RETURN_FLAG.IDLE;
}
public start(args: ListenerArgs<D>): number;
public start() {
return RETURN_FLAG.IDLE;
}
public update(args: ListenerArgs<D>): number;
public update() {
return RETURN_FLAG.IDLE;
}
public end(args: ListenerArgs<D>): number;
public end() {
return RETURN_FLAG.IDLE;
} | public stop(): void {
this.listener.stop();
}
} | public cancel(): number {
return this.listener.cancel();
} | random_line_split |
gesture.ts | import { Options, Data, PointerData, RETURN_FLAG } from './utils';
import { Listener, DefaultListener, ListenerArgs } from './listener';
export interface GestureFactory<
G extends Gesture<O, D, L>,
O extends Options = Options,
D extends Data = Data,
L extends Listener<O, D> = Listener<O, D>
> {
new (listener: L, data: D, target: Element): G;
}
export class Gesture<O extends Options = Options, D extends Data = Data, L extends Listener<O, D> = Listener<O, D>> {
public __POINTERIDS__: number[] = [];
public __REMOVED_POINTERS__: PointerData[] = [];
public startEmitted: boolean = false;
public args: ListenerArgs<D> = {} as ListenerArgs<D>;
constructor(public listener: L, public data: D, public target: Element) {
this.args.data = data;
this.args.target = target;
}
// tslint:disable-next-line:variable-name
public bind(
target: Element,
registerListener: <G extends Gesture<O, D, L>, O extends Options, D extends Data, L extends Listener<O, D>>(
Type: GestureFactory<G, O, D, L>,
element: Element,
listener: Partial<DefaultListener>
) => () => void,
remove: () => void,
evt: Event
): void;
public bind() {}
public unbind(): number {
return RETURN_FLAG.IDLE;
}
public start(args: ListenerArgs<D>): number;
public start() {
return RETURN_FLAG.IDLE;
}
public update(args: ListenerArgs<D>): number;
public update() {
return RETURN_FLAG.IDLE;
}
public end(args: ListenerArgs<D>): number;
public end() {
return RETURN_FLAG.IDLE;
}
public | (): number {
return this.listener.cancel();
}
public stop(): void {
this.listener.stop();
}
}
| cancel | identifier_name |
adduser.component.ts | import { Component, OnInit } from '@angular/core';
import { FormControl, Validators, FormGroup } from '@angular/forms';
import { AdminService } from '../../auth/admin.service';
import { PASSWOERTER_NICHT_GLEICH, PASSWORT_ZU_KURZ } from '../errormessages';
@Component({
selector: 'app-adduser',
templateUrl: './adduser.component.html',
styleUrls: ['./adduser.component.css']
})
export class AdduserComponent implements OnInit {
| email: new FormControl('', Validators.required),
passwort: new FormControl('', Validators.required),
passwortWiederholung: new FormControl('', Validators.required)
});
public errorMessage = '';
public isAdmin: Promise<boolean>;
constructor(private adminService: AdminService) { }
ngOnInit() {
this.isAdmin = this.adminService.isAdmin();
}
computeErrorMesage = () => {
if (this.newUserForm.get('passwort').value.length < 8) {
this.errorMessage = PASSWORT_ZU_KURZ;
return;
}
if (this.newUserForm.get('passwort').value !== this.newUserForm.get('passwortWiederholung').value) {
this.errorMessage = PASSWOERTER_NICHT_GLEICH;
return;
}
this.errorMessage = '';
}
onNewUserSubmit() {
this.computeErrorMesage();
if (this.errorMessage !== '') {
return;
}
if (!this.newUserForm.valid) {
return;
}
this.adminService.addUser(this.newUserForm.get('username').value,
this.newUserForm.get('email').value,
this.newUserForm.get('passwort').value);
this.newUserForm.reset();
}
} | newUserForm = new FormGroup({
username: new FormControl('', Validators.required), | random_line_split |
adduser.component.ts | import { Component, OnInit } from '@angular/core';
import { FormControl, Validators, FormGroup } from '@angular/forms';
import { AdminService } from '../../auth/admin.service';
import { PASSWOERTER_NICHT_GLEICH, PASSWORT_ZU_KURZ } from '../errormessages';
@Component({
selector: 'app-adduser',
templateUrl: './adduser.component.html',
styleUrls: ['./adduser.component.css']
})
export class AdduserComponent implements OnInit {
newUserForm = new FormGroup({
username: new FormControl('', Validators.required),
email: new FormControl('', Validators.required),
passwort: new FormControl('', Validators.required),
passwortWiederholung: new FormControl('', Validators.required)
});
public errorMessage = '';
public isAdmin: Promise<boolean>;
| (private adminService: AdminService) { }
ngOnInit() {
this.isAdmin = this.adminService.isAdmin();
}
computeErrorMesage = () => {
if (this.newUserForm.get('passwort').value.length < 8) {
this.errorMessage = PASSWORT_ZU_KURZ;
return;
}
if (this.newUserForm.get('passwort').value !== this.newUserForm.get('passwortWiederholung').value) {
this.errorMessage = PASSWOERTER_NICHT_GLEICH;
return;
}
this.errorMessage = '';
}
onNewUserSubmit() {
this.computeErrorMesage();
if (this.errorMessage !== '') {
return;
}
if (!this.newUserForm.valid) {
return;
}
this.adminService.addUser(this.newUserForm.get('username').value,
this.newUserForm.get('email').value,
this.newUserForm.get('passwort').value);
this.newUserForm.reset();
}
}
| constructor | identifier_name |
adduser.component.ts | import { Component, OnInit } from '@angular/core';
import { FormControl, Validators, FormGroup } from '@angular/forms';
import { AdminService } from '../../auth/admin.service';
import { PASSWOERTER_NICHT_GLEICH, PASSWORT_ZU_KURZ } from '../errormessages';
@Component({
selector: 'app-adduser',
templateUrl: './adduser.component.html',
styleUrls: ['./adduser.component.css']
})
export class AdduserComponent implements OnInit {
newUserForm = new FormGroup({
username: new FormControl('', Validators.required),
email: new FormControl('', Validators.required),
passwort: new FormControl('', Validators.required),
passwortWiederholung: new FormControl('', Validators.required)
});
public errorMessage = '';
public isAdmin: Promise<boolean>;
constructor(private adminService: AdminService) { }
ngOnInit() {
this.isAdmin = this.adminService.isAdmin();
}
computeErrorMesage = () => {
if (this.newUserForm.get('passwort').value.length < 8) {
this.errorMessage = PASSWORT_ZU_KURZ;
return;
}
if (this.newUserForm.get('passwort').value !== this.newUserForm.get('passwortWiederholung').value) {
this.errorMessage = PASSWOERTER_NICHT_GLEICH;
return;
}
this.errorMessage = '';
}
onNewUserSubmit() {
this.computeErrorMesage();
if (this.errorMessage !== '') |
if (!this.newUserForm.valid) {
return;
}
this.adminService.addUser(this.newUserForm.get('username').value,
this.newUserForm.get('email').value,
this.newUserForm.get('passwort').value);
this.newUserForm.reset();
}
}
| {
return;
} | conditional_block |
helpers.service.ts | import { Injectable } from '@angular/core';
@Injectable()
export class HelpersService {
| () {
}
getBrightness(rgb): number {
let result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})?$/i.exec(rgb);
if (result && result.length > 4 && result[4] != null) {
return 255 - parseInt(result[4], 16);
}
return result ?
0.2126 * parseInt(result[1], 16) +
0.7152 * parseInt(result[2], 16) +
0.0722 * parseInt(result[3], 16) : 0;
}
getBrightnessColor(rgb): string {
let brightness = this.getBrightness(rgb);
if (brightness > 130) {
return '#000000';
}
return '#ffffff';
}
}
| constructor | identifier_name |
helpers.service.ts | import { Injectable } from '@angular/core';
@Injectable()
export class HelpersService {
constructor() {
}
getBrightness(rgb): number {
let result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})?$/i.exec(rgb);
if (result && result.length > 4 && result[4] != null) {
return 255 - parseInt(result[4], 16);
}
return result ?
0.2126 * parseInt(result[1], 16) +
0.7152 * parseInt(result[2], 16) +
0.0722 * parseInt(result[3], 16) : 0;
}
getBrightnessColor(rgb): string |
}
| {
let brightness = this.getBrightness(rgb);
if (brightness > 130) {
return '#000000';
}
return '#ffffff';
} | identifier_body |
helpers.service.ts | import { Injectable } from '@angular/core';
@Injectable()
export class HelpersService {
constructor() {
}
getBrightness(rgb): number {
let result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})?$/i.exec(rgb);
if (result && result.length > 4 && result[4] != null) {
return 255 - parseInt(result[4], 16);
}
return result ?
0.2126 * parseInt(result[1], 16) +
0.7152 * parseInt(result[2], 16) +
0.0722 * parseInt(result[3], 16) : 0;
}
getBrightnessColor(rgb): string {
let brightness = this.getBrightness(rgb);
if (brightness > 130) |
return '#ffffff';
}
}
| {
return '#000000';
} | conditional_block |
helpers.service.ts | import { Injectable } from '@angular/core';
@Injectable()
export class HelpersService {
constructor() {
} | getBrightness(rgb): number {
let result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})?$/i.exec(rgb);
if (result && result.length > 4 && result[4] != null) {
return 255 - parseInt(result[4], 16);
}
return result ?
0.2126 * parseInt(result[1], 16) +
0.7152 * parseInt(result[2], 16) +
0.0722 * parseInt(result[3], 16) : 0;
}
getBrightnessColor(rgb): string {
let brightness = this.getBrightness(rgb);
if (brightness > 130) {
return '#000000';
}
return '#ffffff';
}
} | random_line_split | |
filter.js | /*
* Copyright (c) 2012 Dmitri Melikyan
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to permit
* persons to whom the Software is furnished to do so, subject to the
* following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
* NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
* THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
var nt;
var filterKeys;
var sampleNum;
exports.init = function() {
nt = global.nodetime;
filterKeys = {};
sampleNum = 0;
nt.on('sample', function(sample) {
if(!nt.headless && nt.sessionId) {
collectKeys(undefined, sample, 0);
sampleNum++;
if(sampleNum == 1 || sampleNum == 10) {
sendKeys();
}
}
});
setInterval(function() {
try {
sendKeys();
}
catch(e) {
nt.error(e);
}
}, 60000);
};
var collectKeys = function(key, obj, depth) {
if(depth > 20) return 0;
var isArray = Array.isArray(obj);
for(var prop in obj) {
if(prop.match(/^\_/)) continue;
if(typeof obj[prop] === 'object') {
collectKeys(prop, obj[prop], depth + 1);
}
else {
if(!isArray) {
filterKeys[prop] = true;
}
else {
filterKeys[key] = true;
}
}
}
};
var sendKeys = function() {
var keys = [];
for(var prop in filterKeys) {
keys.push(prop);
}
keys = keys.sort(function(a, b) {
a = a.toLowerCase();
b = b.toLowerCase();
if(a > b) return 1;
if(a < b) return -1;
return 0;
});
if(keys.length > 0) {
nt.agent.send({cmd: 'updateFilterKeys', args: keys});
}
};
var PredicateFilter = function() {
}
exports.PredicateFilter = PredicateFilter;
PredicateFilter.prototype.preparePredicates = function(preds) {
preds.forEach(function(pred) {
try{
pred.valNum = parseFloat(pred.val)
}
catch(err) {
}
try{
if(pred.op === 'match') pred.valRe = new RegExp(pred.val);
if(typeof pred.val === 'string') pred.valLc = pred.val.toLowerCase();
}
catch(err) {
return nt.error(err);
}
});
this.preds = preds;
return true;
}
PredicateFilter.prototype.filter = function(sample) {
var matched = 0;
this.preds.forEach(function(pred) {
matched += walk(pred, sample, 0);
});
return (matched > 0);
};
function | (pred, obj, depth) {
if(depth > 20) return 0;
var matched = 0;
for(var prop in obj) {
var val = obj[prop];
if(val === undefined || val === null) {
continue;
}
else if(typeof val === 'object') {
matched += walk(pred, val, depth + 1);
}
else if((pred.key === '*' || pred.key === prop) && test(pred, val)) {
matched++;
}
if(matched) break;
}
return matched;
}
function test(pred, val) {
var ret = false;
if(typeof val === 'number') {
if(pred.valNum !== NaN) {
if (pred.op === '==') {
ret = (val == pred.valNum);
}
else if (pred.op === '!=') {
ret = (val != pred.valNum);
}
else if (pred.op === '<') {
ret = (val < pred.valNum);
}
else if (pred.op === '>') {
ret = (val > pred.valNum);
}
}
}
else if(typeof val === 'string') {
if(pred.op === 'match' && pred.valRe) {
ret = pred.valRe.exec(val);
}
else if (pred.op === '==') {
ret = (val.toLowerCase() == pred.valLc);
}
else if (pred.op === '!=') {
ret = (val.toLowerCase() != pred.valLc);
}
}
return ret;
}
| walk | identifier_name |
filter.js | /*
* Copyright (c) 2012 Dmitri Melikyan
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to permit
* persons to whom the Software is furnished to do so, subject to the
* following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
* NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
* THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
var nt;
var filterKeys;
var sampleNum;
exports.init = function() {
nt = global.nodetime;
filterKeys = {};
sampleNum = 0;
nt.on('sample', function(sample) {
if(!nt.headless && nt.sessionId) {
collectKeys(undefined, sample, 0);
sampleNum++;
if(sampleNum == 1 || sampleNum == 10) {
sendKeys();
}
}
});
setInterval(function() {
try {
sendKeys();
}
catch(e) {
nt.error(e);
}
}, 60000);
};
var collectKeys = function(key, obj, depth) {
if(depth > 20) return 0; | var isArray = Array.isArray(obj);
for(var prop in obj) {
if(prop.match(/^\_/)) continue;
if(typeof obj[prop] === 'object') {
collectKeys(prop, obj[prop], depth + 1);
}
else {
if(!isArray) {
filterKeys[prop] = true;
}
else {
filterKeys[key] = true;
}
}
}
};
var sendKeys = function() {
var keys = [];
for(var prop in filterKeys) {
keys.push(prop);
}
keys = keys.sort(function(a, b) {
a = a.toLowerCase();
b = b.toLowerCase();
if(a > b) return 1;
if(a < b) return -1;
return 0;
});
if(keys.length > 0) {
nt.agent.send({cmd: 'updateFilterKeys', args: keys});
}
};
var PredicateFilter = function() {
}
exports.PredicateFilter = PredicateFilter;
PredicateFilter.prototype.preparePredicates = function(preds) {
preds.forEach(function(pred) {
try{
pred.valNum = parseFloat(pred.val)
}
catch(err) {
}
try{
if(pred.op === 'match') pred.valRe = new RegExp(pred.val);
if(typeof pred.val === 'string') pred.valLc = pred.val.toLowerCase();
}
catch(err) {
return nt.error(err);
}
});
this.preds = preds;
return true;
}
PredicateFilter.prototype.filter = function(sample) {
var matched = 0;
this.preds.forEach(function(pred) {
matched += walk(pred, sample, 0);
});
return (matched > 0);
};
function walk(pred, obj, depth) {
if(depth > 20) return 0;
var matched = 0;
for(var prop in obj) {
var val = obj[prop];
if(val === undefined || val === null) {
continue;
}
else if(typeof val === 'object') {
matched += walk(pred, val, depth + 1);
}
else if((pred.key === '*' || pred.key === prop) && test(pred, val)) {
matched++;
}
if(matched) break;
}
return matched;
}
function test(pred, val) {
var ret = false;
if(typeof val === 'number') {
if(pred.valNum !== NaN) {
if (pred.op === '==') {
ret = (val == pred.valNum);
}
else if (pred.op === '!=') {
ret = (val != pred.valNum);
}
else if (pred.op === '<') {
ret = (val < pred.valNum);
}
else if (pred.op === '>') {
ret = (val > pred.valNum);
}
}
}
else if(typeof val === 'string') {
if(pred.op === 'match' && pred.valRe) {
ret = pred.valRe.exec(val);
}
else if (pred.op === '==') {
ret = (val.toLowerCase() == pred.valLc);
}
else if (pred.op === '!=') {
ret = (val.toLowerCase() != pred.valLc);
}
}
return ret;
} | random_line_split | |
filter.js | /*
* Copyright (c) 2012 Dmitri Melikyan
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to permit
* persons to whom the Software is furnished to do so, subject to the
* following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
* NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
* THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
var nt;
var filterKeys;
var sampleNum;
exports.init = function() {
nt = global.nodetime;
filterKeys = {};
sampleNum = 0;
nt.on('sample', function(sample) {
if(!nt.headless && nt.sessionId) {
collectKeys(undefined, sample, 0);
sampleNum++;
if(sampleNum == 1 || sampleNum == 10) {
sendKeys();
}
}
});
setInterval(function() {
try {
sendKeys();
}
catch(e) {
nt.error(e);
}
}, 60000);
};
var collectKeys = function(key, obj, depth) {
if(depth > 20) return 0;
var isArray = Array.isArray(obj);
for(var prop in obj) {
if(prop.match(/^\_/)) continue;
if(typeof obj[prop] === 'object') {
collectKeys(prop, obj[prop], depth + 1);
}
else {
if(!isArray) {
filterKeys[prop] = true;
}
else {
filterKeys[key] = true;
}
}
}
};
var sendKeys = function() {
var keys = [];
for(var prop in filterKeys) {
keys.push(prop);
}
keys = keys.sort(function(a, b) {
a = a.toLowerCase();
b = b.toLowerCase();
if(a > b) return 1;
if(a < b) return -1;
return 0;
});
if(keys.length > 0) {
nt.agent.send({cmd: 'updateFilterKeys', args: keys});
}
};
var PredicateFilter = function() {
}
exports.PredicateFilter = PredicateFilter;
PredicateFilter.prototype.preparePredicates = function(preds) {
preds.forEach(function(pred) {
try{
pred.valNum = parseFloat(pred.val)
}
catch(err) {
}
try{
if(pred.op === 'match') pred.valRe = new RegExp(pred.val);
if(typeof pred.val === 'string') pred.valLc = pred.val.toLowerCase();
}
catch(err) {
return nt.error(err);
}
});
this.preds = preds;
return true;
}
PredicateFilter.prototype.filter = function(sample) {
var matched = 0;
this.preds.forEach(function(pred) {
matched += walk(pred, sample, 0);
});
return (matched > 0);
};
function walk(pred, obj, depth) {
if(depth > 20) return 0;
var matched = 0;
for(var prop in obj) {
var val = obj[prop];
if(val === undefined || val === null) {
continue;
}
else if(typeof val === 'object') {
matched += walk(pred, val, depth + 1);
}
else if((pred.key === '*' || pred.key === prop) && test(pred, val)) |
if(matched) break;
}
return matched;
}
function test(pred, val) {
var ret = false;
if(typeof val === 'number') {
if(pred.valNum !== NaN) {
if (pred.op === '==') {
ret = (val == pred.valNum);
}
else if (pred.op === '!=') {
ret = (val != pred.valNum);
}
else if (pred.op === '<') {
ret = (val < pred.valNum);
}
else if (pred.op === '>') {
ret = (val > pred.valNum);
}
}
}
else if(typeof val === 'string') {
if(pred.op === 'match' && pred.valRe) {
ret = pred.valRe.exec(val);
}
else if (pred.op === '==') {
ret = (val.toLowerCase() == pred.valLc);
}
else if (pred.op === '!=') {
ret = (val.toLowerCase() != pred.valLc);
}
}
return ret;
}
| {
matched++;
} | conditional_block |
filter.js | /*
* Copyright (c) 2012 Dmitri Melikyan
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to permit
* persons to whom the Software is furnished to do so, subject to the
* following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
* NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
* THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
var nt;
var filterKeys;
var sampleNum;
exports.init = function() {
nt = global.nodetime;
filterKeys = {};
sampleNum = 0;
nt.on('sample', function(sample) {
if(!nt.headless && nt.sessionId) {
collectKeys(undefined, sample, 0);
sampleNum++;
if(sampleNum == 1 || sampleNum == 10) {
sendKeys();
}
}
});
setInterval(function() {
try {
sendKeys();
}
catch(e) {
nt.error(e);
}
}, 60000);
};
var collectKeys = function(key, obj, depth) {
if(depth > 20) return 0;
var isArray = Array.isArray(obj);
for(var prop in obj) {
if(prop.match(/^\_/)) continue;
if(typeof obj[prop] === 'object') {
collectKeys(prop, obj[prop], depth + 1);
}
else {
if(!isArray) {
filterKeys[prop] = true;
}
else {
filterKeys[key] = true;
}
}
}
};
var sendKeys = function() {
var keys = [];
for(var prop in filterKeys) {
keys.push(prop);
}
keys = keys.sort(function(a, b) {
a = a.toLowerCase();
b = b.toLowerCase();
if(a > b) return 1;
if(a < b) return -1;
return 0;
});
if(keys.length > 0) {
nt.agent.send({cmd: 'updateFilterKeys', args: keys});
}
};
var PredicateFilter = function() {
}
exports.PredicateFilter = PredicateFilter;
PredicateFilter.prototype.preparePredicates = function(preds) {
preds.forEach(function(pred) {
try{
pred.valNum = parseFloat(pred.val)
}
catch(err) {
}
try{
if(pred.op === 'match') pred.valRe = new RegExp(pred.val);
if(typeof pred.val === 'string') pred.valLc = pred.val.toLowerCase();
}
catch(err) {
return nt.error(err);
}
});
this.preds = preds;
return true;
}
PredicateFilter.prototype.filter = function(sample) {
var matched = 0;
this.preds.forEach(function(pred) {
matched += walk(pred, sample, 0);
});
return (matched > 0);
};
function walk(pred, obj, depth) |
function test(pred, val) {
var ret = false;
if(typeof val === 'number') {
if(pred.valNum !== NaN) {
if (pred.op === '==') {
ret = (val == pred.valNum);
}
else if (pred.op === '!=') {
ret = (val != pred.valNum);
}
else if (pred.op === '<') {
ret = (val < pred.valNum);
}
else if (pred.op === '>') {
ret = (val > pred.valNum);
}
}
}
else if(typeof val === 'string') {
if(pred.op === 'match' && pred.valRe) {
ret = pred.valRe.exec(val);
}
else if (pred.op === '==') {
ret = (val.toLowerCase() == pred.valLc);
}
else if (pred.op === '!=') {
ret = (val.toLowerCase() != pred.valLc);
}
}
return ret;
}
| {
if(depth > 20) return 0;
var matched = 0;
for(var prop in obj) {
var val = obj[prop];
if(val === undefined || val === null) {
continue;
}
else if(typeof val === 'object') {
matched += walk(pred, val, depth + 1);
}
else if((pred.key === '*' || pred.key === prop) && test(pred, val)) {
matched++;
}
if(matched) break;
}
return matched;
} | identifier_body |
player.rs | use rd::util::types::*;
use rd::actor::Actor;
pub struct Player {
position: usize,
experience: Experience,
exp_to_level_up: Experience,
level: Level,
hp: Health,
max_hp: Health,
attack: Attack,
}
pub const MAX_LEVEL: Level = 10;
const EXP_PER_LEVEL: Experience = 5;
const HP_PER_LEVEL: Health = 10;
impl Actor for Player {
fn get_level(&self) -> Level {
self.level
}
fn get_max_hp(&self) -> Health {
self.max_hp
}
fn get_hp(&self) -> Health {
self.hp
}
fn get_position(&self) -> MapIndex {
self.position
}
}
impl Player {
pub fn spawn_at(spawn_point: MapIndex) -> Player {
Player {
position: spawn_point,
experience: 0,
exp_to_level_up: EXP_PER_LEVEL,
level: 1,
hp: 10,
max_hp: 10,
attack: 5,
}
}
pub fn move_to(&mut self, tile: MapIndex) {
self.position = tile;
dbg!("Player moved to {}", tile);
}
pub fn | (&self) -> Experience {
self.experience
}
pub fn get_exp_needed_to_level_up(&self) -> Experience {
self.exp_to_level_up
}
pub fn grant_exp(&mut self, exp: Experience) {
self.experience += exp;
dbg!("Granted {} EXP.", exp);
if self.levelled_past_max() {
self.experience -= self.exp_to_level_up;
self.restore_full_hp();
return;
}
while self.experience >= self.exp_to_level_up {
self.level_up();
self.exp_to_level_up += EXP_PER_LEVEL;
}
}
#[cfg(test)]
pub fn damage(&mut self, damage_points: Health) {
self.hp -= damage_points;
}
fn level_up(&mut self) {
self.level += 1;
self.experience -= self.exp_to_level_up;
self.max_hp += HP_PER_LEVEL;
self.attack += 5;
dbg!("LEVEL UP to {}", self.level);
self.restore_full_hp();
}
fn restore_full_hp(&mut self) {
self.hp = self.max_hp;
dbg!("HP fully restored.");
}
fn levelled_past_max(&self) -> bool {
self.level == MAX_LEVEL && self.experience >= self.exp_to_level_up
}
pub fn get_attack(&self) -> Attack {
self.attack
}
} | get_exp | identifier_name |
player.rs | use rd::util::types::*;
use rd::actor::Actor;
pub struct Player {
position: usize,
experience: Experience,
exp_to_level_up: Experience,
level: Level,
hp: Health,
max_hp: Health,
attack: Attack,
}
pub const MAX_LEVEL: Level = 10;
const EXP_PER_LEVEL: Experience = 5;
const HP_PER_LEVEL: Health = 10;
impl Actor for Player {
fn get_level(&self) -> Level {
self.level
}
fn get_max_hp(&self) -> Health {
self.max_hp
}
fn get_hp(&self) -> Health {
self.hp
}
fn get_position(&self) -> MapIndex {
self.position
}
}
impl Player {
pub fn spawn_at(spawn_point: MapIndex) -> Player {
Player {
position: spawn_point,
experience: 0,
exp_to_level_up: EXP_PER_LEVEL,
level: 1,
hp: 10,
max_hp: 10,
attack: 5,
}
}
pub fn move_to(&mut self, tile: MapIndex) {
self.position = tile;
dbg!("Player moved to {}", tile);
}
pub fn get_exp(&self) -> Experience {
self.experience
}
pub fn get_exp_needed_to_level_up(&self) -> Experience {
self.exp_to_level_up
}
pub fn grant_exp(&mut self, exp: Experience) {
self.experience += exp;
dbg!("Granted {} EXP.", exp);
if self.levelled_past_max() |
while self.experience >= self.exp_to_level_up {
self.level_up();
self.exp_to_level_up += EXP_PER_LEVEL;
}
}
#[cfg(test)]
pub fn damage(&mut self, damage_points: Health) {
self.hp -= damage_points;
}
fn level_up(&mut self) {
self.level += 1;
self.experience -= self.exp_to_level_up;
self.max_hp += HP_PER_LEVEL;
self.attack += 5;
dbg!("LEVEL UP to {}", self.level);
self.restore_full_hp();
}
fn restore_full_hp(&mut self) {
self.hp = self.max_hp;
dbg!("HP fully restored.");
}
fn levelled_past_max(&self) -> bool {
self.level == MAX_LEVEL && self.experience >= self.exp_to_level_up
}
pub fn get_attack(&self) -> Attack {
self.attack
}
} | {
self.experience -= self.exp_to_level_up;
self.restore_full_hp();
return;
} | conditional_block |
player.rs | use rd::util::types::*;
use rd::actor::Actor;
pub struct Player {
position: usize,
experience: Experience,
exp_to_level_up: Experience,
level: Level,
hp: Health,
max_hp: Health,
attack: Attack,
}
pub const MAX_LEVEL: Level = 10;
const EXP_PER_LEVEL: Experience = 5;
const HP_PER_LEVEL: Health = 10;
impl Actor for Player {
fn get_level(&self) -> Level {
self.level
}
fn get_max_hp(&self) -> Health {
self.max_hp
}
fn get_hp(&self) -> Health {
self.hp
}
fn get_position(&self) -> MapIndex { | pub fn spawn_at(spawn_point: MapIndex) -> Player {
Player {
position: spawn_point,
experience: 0,
exp_to_level_up: EXP_PER_LEVEL,
level: 1,
hp: 10,
max_hp: 10,
attack: 5,
}
}
pub fn move_to(&mut self, tile: MapIndex) {
self.position = tile;
dbg!("Player moved to {}", tile);
}
pub fn get_exp(&self) -> Experience {
self.experience
}
pub fn get_exp_needed_to_level_up(&self) -> Experience {
self.exp_to_level_up
}
pub fn grant_exp(&mut self, exp: Experience) {
self.experience += exp;
dbg!("Granted {} EXP.", exp);
if self.levelled_past_max() {
self.experience -= self.exp_to_level_up;
self.restore_full_hp();
return;
}
while self.experience >= self.exp_to_level_up {
self.level_up();
self.exp_to_level_up += EXP_PER_LEVEL;
}
}
#[cfg(test)]
pub fn damage(&mut self, damage_points: Health) {
self.hp -= damage_points;
}
fn level_up(&mut self) {
self.level += 1;
self.experience -= self.exp_to_level_up;
self.max_hp += HP_PER_LEVEL;
self.attack += 5;
dbg!("LEVEL UP to {}", self.level);
self.restore_full_hp();
}
fn restore_full_hp(&mut self) {
self.hp = self.max_hp;
dbg!("HP fully restored.");
}
fn levelled_past_max(&self) -> bool {
self.level == MAX_LEVEL && self.experience >= self.exp_to_level_up
}
pub fn get_attack(&self) -> Attack {
self.attack
}
} | self.position
}
}
impl Player { | random_line_split |
player.rs | use rd::util::types::*;
use rd::actor::Actor;
pub struct Player {
position: usize,
experience: Experience,
exp_to_level_up: Experience,
level: Level,
hp: Health,
max_hp: Health,
attack: Attack,
}
pub const MAX_LEVEL: Level = 10;
const EXP_PER_LEVEL: Experience = 5;
const HP_PER_LEVEL: Health = 10;
impl Actor for Player {
fn get_level(&self) -> Level {
self.level
}
fn get_max_hp(&self) -> Health {
self.max_hp
}
fn get_hp(&self) -> Health {
self.hp
}
fn get_position(&self) -> MapIndex {
self.position
}
}
impl Player {
pub fn spawn_at(spawn_point: MapIndex) -> Player {
Player {
position: spawn_point,
experience: 0,
exp_to_level_up: EXP_PER_LEVEL,
level: 1,
hp: 10,
max_hp: 10,
attack: 5,
}
}
pub fn move_to(&mut self, tile: MapIndex) |
pub fn get_exp(&self) -> Experience {
self.experience
}
pub fn get_exp_needed_to_level_up(&self) -> Experience {
self.exp_to_level_up
}
pub fn grant_exp(&mut self, exp: Experience) {
self.experience += exp;
dbg!("Granted {} EXP.", exp);
if self.levelled_past_max() {
self.experience -= self.exp_to_level_up;
self.restore_full_hp();
return;
}
while self.experience >= self.exp_to_level_up {
self.level_up();
self.exp_to_level_up += EXP_PER_LEVEL;
}
}
#[cfg(test)]
pub fn damage(&mut self, damage_points: Health) {
self.hp -= damage_points;
}
fn level_up(&mut self) {
self.level += 1;
self.experience -= self.exp_to_level_up;
self.max_hp += HP_PER_LEVEL;
self.attack += 5;
dbg!("LEVEL UP to {}", self.level);
self.restore_full_hp();
}
fn restore_full_hp(&mut self) {
self.hp = self.max_hp;
dbg!("HP fully restored.");
}
fn levelled_past_max(&self) -> bool {
self.level == MAX_LEVEL && self.experience >= self.exp_to_level_up
}
pub fn get_attack(&self) -> Attack {
self.attack
}
} | {
self.position = tile;
dbg!("Player moved to {}", tile);
} | identifier_body |
BaseStatusBarItemObserver.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { StatusBarItem } from '../vscodeAdapter';
import { BaseEvent } from '../omnisharp/loggingEvents';
export abstract class BaseStatusBarItemObserver {
constructor(private statusBarItem: StatusBarItem) |
public SetAndShowStatusBar(text: string, command: string, color?: string, tooltip?: string) {
this.statusBarItem.text = text;
this.statusBarItem.command = command;
this.statusBarItem.color = color;
this.statusBarItem.tooltip = tooltip;
this.statusBarItem.show();
}
public ResetAndHideStatusBar() {
this.statusBarItem.text = undefined;
this.statusBarItem.command = undefined;
this.statusBarItem.color = undefined;
this.statusBarItem.tooltip = undefined;
this.statusBarItem.hide();
}
abstract post: (event: BaseEvent) => void;
} | {
} | identifier_body |
BaseStatusBarItemObserver.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { StatusBarItem } from '../vscodeAdapter';
import { BaseEvent } from '../omnisharp/loggingEvents';
export abstract class BaseStatusBarItemObserver {
| (private statusBarItem: StatusBarItem) {
}
public SetAndShowStatusBar(text: string, command: string, color?: string, tooltip?: string) {
this.statusBarItem.text = text;
this.statusBarItem.command = command;
this.statusBarItem.color = color;
this.statusBarItem.tooltip = tooltip;
this.statusBarItem.show();
}
public ResetAndHideStatusBar() {
this.statusBarItem.text = undefined;
this.statusBarItem.command = undefined;
this.statusBarItem.color = undefined;
this.statusBarItem.tooltip = undefined;
this.statusBarItem.hide();
}
abstract post: (event: BaseEvent) => void;
} | constructor | identifier_name |
BaseStatusBarItemObserver.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { StatusBarItem } from '../vscodeAdapter';
import { BaseEvent } from '../omnisharp/loggingEvents';
export abstract class BaseStatusBarItemObserver {
constructor(private statusBarItem: StatusBarItem) {
}
public SetAndShowStatusBar(text: string, command: string, color?: string, tooltip?: string) {
this.statusBarItem.text = text;
this.statusBarItem.command = command;
this.statusBarItem.color = color;
this.statusBarItem.tooltip = tooltip;
this.statusBarItem.show();
}
public ResetAndHideStatusBar() {
this.statusBarItem.text = undefined;
this.statusBarItem.command = undefined;
this.statusBarItem.color = undefined;
this.statusBarItem.tooltip = undefined;
this.statusBarItem.hide();
}
abstract post: (event: BaseEvent) => void; | } | random_line_split | |
path.rs | extern crate url;
use url::percent_encoding::percent_decode;
use regex;
use json::{JsonValue, ToJson};
lazy_static! {
pub static ref MATCHER: regex::Regex = regex::Regex::new(r":([a-z][a-z_]*)").unwrap();
}
pub struct Path {
regex: regex::Regex,
pub path: String,
pub params: Vec<String>
}
pub fn normalize<'a>(path: &'a str) -> &'a str {
if path.starts_with("/") {
&path[1..]
} else {
path
}
}
impl Path {
pub fn apply_captures(&self, params: &mut JsonValue, captures: regex::Captures) {
let obj = params.as_object_mut().expect("Params must be object");
for param in self.params.iter() {
obj.insert(
param.clone(),
percent_decode(
captures.name(¶m).unwrap_or("").as_bytes()
).decode_utf8_lossy().to_string().to_json());
}
}
pub fn is_match<'a>(&'a self, path: &'a str) -> Option<regex::Captures> {
self.regex.captures(path)
}
pub fn parse(path: &str, endpoint: bool) -> Result<Path,String> {
let mut regex_body = "^".to_string() + &Path::sub_regex(path);
if endpoint {
regex_body = regex_body + "$";
}
let regex = match regex::Regex::new(®ex_body) {
Ok(re) => re,
Err(err) => return Err(format!("{}", err))
};
let mut params = vec![];
for capture in MATCHER.captures_iter(path) {
params.push(capture.at(1).unwrap_or("").to_string());
}
Ok(Path {
path: path.to_string(),
params: params,
regex: regex
})
}
fn sub_regex(path: &str) -> String {
return MATCHER.replace_all(path, "(?P<$1>[^/?&]+)");
}
}
#[test]
fn it_normalize() {
assert_eq!(normalize("/test"), "test");
assert_eq!(normalize("test"), "test");
}
#[test]
fn sub_regex() {
let res = Path::sub_regex(":user_id/messages/:message_id");
assert_eq!(&res, "(?P<user_id>[^/?&]+)/messages/(?P<message_id>[^/?&]+)")
}
#[test]
fn parse_and_match() {
let path = Path::parse(":user_id/messages/:message_id", true).unwrap();
assert!(match path.is_match("1920/messages/100500") {
Some(captures) => {
captures.name("user_id").unwrap() == "1920" &&
captures.name("message_id").unwrap() == "100500"
}
None => false
});
assert!(match path.is_match("1920/messages/not_match/100500") {
Some(_) => false,
None => true
});
}
#[test]
fn parse_and_match_root() {
let path = Path::parse("", true).unwrap();
assert!(match path.is_match("") {
Some(captures) => captures.at(0).unwrap() == "",
None => false
});
}
#[test]
fn | () {
let path = Path::parse(":id", true).unwrap();
assert!(match path.is_match("550e8400-e29b-41d4-a716-446655440000") {
Some(captures) => captures.name("id").unwrap() == "550e8400-e29b-41d4-a716-446655440000",
None => false
});
} | parse_and_match_single_val | identifier_name |
path.rs | extern crate url;
use url::percent_encoding::percent_decode;
use regex;
use json::{JsonValue, ToJson};
lazy_static! {
pub static ref MATCHER: regex::Regex = regex::Regex::new(r":([a-z][a-z_]*)").unwrap();
}
pub struct Path {
regex: regex::Regex,
pub path: String,
pub params: Vec<String>
}
pub fn normalize<'a>(path: &'a str) -> &'a str {
if path.starts_with("/") {
&path[1..]
} else {
path
}
}
impl Path {
pub fn apply_captures(&self, params: &mut JsonValue, captures: regex::Captures) {
let obj = params.as_object_mut().expect("Params must be object");
for param in self.params.iter() {
obj.insert(
param.clone(),
percent_decode(
captures.name(¶m).unwrap_or("").as_bytes()
).decode_utf8_lossy().to_string().to_json());
}
}
pub fn is_match<'a>(&'a self, path: &'a str) -> Option<regex::Captures> {
self.regex.captures(path)
}
pub fn parse(path: &str, endpoint: bool) -> Result<Path,String> {
let mut regex_body = "^".to_string() + &Path::sub_regex(path);
if endpoint {
regex_body = regex_body + "$";
}
let regex = match regex::Regex::new(®ex_body) {
Ok(re) => re,
Err(err) => return Err(format!("{}", err))
};
let mut params = vec![];
for capture in MATCHER.captures_iter(path) {
params.push(capture.at(1).unwrap_or("").to_string());
}
Ok(Path {
path: path.to_string(),
params: params,
regex: regex
})
}
fn sub_regex(path: &str) -> String {
return MATCHER.replace_all(path, "(?P<$1>[^/?&]+)");
}
}
#[test]
fn it_normalize() {
assert_eq!(normalize("/test"), "test");
assert_eq!(normalize("test"), "test");
}
#[test]
fn sub_regex() {
let res = Path::sub_regex(":user_id/messages/:message_id");
assert_eq!(&res, "(?P<user_id>[^/?&]+)/messages/(?P<message_id>[^/?&]+)")
}
#[test]
fn parse_and_match() {
let path = Path::parse(":user_id/messages/:message_id", true).unwrap();
assert!(match path.is_match("1920/messages/100500") {
Some(captures) => {
captures.name("user_id").unwrap() == "1920" &&
captures.name("message_id").unwrap() == "100500"
}
None => false
});
assert!(match path.is_match("1920/messages/not_match/100500") {
Some(_) => false,
None => true
});
}
#[test]
fn parse_and_match_root() {
let path = Path::parse("", true).unwrap(); | }
#[test]
fn parse_and_match_single_val() {
let path = Path::parse(":id", true).unwrap();
assert!(match path.is_match("550e8400-e29b-41d4-a716-446655440000") {
Some(captures) => captures.name("id").unwrap() == "550e8400-e29b-41d4-a716-446655440000",
None => false
});
} | assert!(match path.is_match("") {
Some(captures) => captures.at(0).unwrap() == "",
None => false
}); | random_line_split |
path.rs | extern crate url;
use url::percent_encoding::percent_decode;
use regex;
use json::{JsonValue, ToJson};
lazy_static! {
pub static ref MATCHER: regex::Regex = regex::Regex::new(r":([a-z][a-z_]*)").unwrap();
}
pub struct Path {
regex: regex::Regex,
pub path: String,
pub params: Vec<String>
}
pub fn normalize<'a>(path: &'a str) -> &'a str {
if path.starts_with("/") {
&path[1..]
} else {
path
}
}
impl Path {
pub fn apply_captures(&self, params: &mut JsonValue, captures: regex::Captures) {
let obj = params.as_object_mut().expect("Params must be object");
for param in self.params.iter() {
obj.insert(
param.clone(),
percent_decode(
captures.name(¶m).unwrap_or("").as_bytes()
).decode_utf8_lossy().to_string().to_json());
}
}
pub fn is_match<'a>(&'a self, path: &'a str) -> Option<regex::Captures> {
self.regex.captures(path)
}
pub fn parse(path: &str, endpoint: bool) -> Result<Path,String> {
let mut regex_body = "^".to_string() + &Path::sub_regex(path);
if endpoint |
let regex = match regex::Regex::new(®ex_body) {
Ok(re) => re,
Err(err) => return Err(format!("{}", err))
};
let mut params = vec![];
for capture in MATCHER.captures_iter(path) {
params.push(capture.at(1).unwrap_or("").to_string());
}
Ok(Path {
path: path.to_string(),
params: params,
regex: regex
})
}
fn sub_regex(path: &str) -> String {
return MATCHER.replace_all(path, "(?P<$1>[^/?&]+)");
}
}
#[test]
fn it_normalize() {
assert_eq!(normalize("/test"), "test");
assert_eq!(normalize("test"), "test");
}
#[test]
fn sub_regex() {
let res = Path::sub_regex(":user_id/messages/:message_id");
assert_eq!(&res, "(?P<user_id>[^/?&]+)/messages/(?P<message_id>[^/?&]+)")
}
#[test]
fn parse_and_match() {
let path = Path::parse(":user_id/messages/:message_id", true).unwrap();
assert!(match path.is_match("1920/messages/100500") {
Some(captures) => {
captures.name("user_id").unwrap() == "1920" &&
captures.name("message_id").unwrap() == "100500"
}
None => false
});
assert!(match path.is_match("1920/messages/not_match/100500") {
Some(_) => false,
None => true
});
}
#[test]
fn parse_and_match_root() {
let path = Path::parse("", true).unwrap();
assert!(match path.is_match("") {
Some(captures) => captures.at(0).unwrap() == "",
None => false
});
}
#[test]
fn parse_and_match_single_val() {
let path = Path::parse(":id", true).unwrap();
assert!(match path.is_match("550e8400-e29b-41d4-a716-446655440000") {
Some(captures) => captures.name("id").unwrap() == "550e8400-e29b-41d4-a716-446655440000",
None => false
});
} | {
regex_body = regex_body + "$";
} | conditional_block |
path.rs | extern crate url;
use url::percent_encoding::percent_decode;
use regex;
use json::{JsonValue, ToJson};
lazy_static! {
pub static ref MATCHER: regex::Regex = regex::Regex::new(r":([a-z][a-z_]*)").unwrap();
}
pub struct Path {
regex: regex::Regex,
pub path: String,
pub params: Vec<String>
}
pub fn normalize<'a>(path: &'a str) -> &'a str {
if path.starts_with("/") {
&path[1..]
} else {
path
}
}
impl Path {
pub fn apply_captures(&self, params: &mut JsonValue, captures: regex::Captures) {
let obj = params.as_object_mut().expect("Params must be object");
for param in self.params.iter() {
obj.insert(
param.clone(),
percent_decode(
captures.name(¶m).unwrap_or("").as_bytes()
).decode_utf8_lossy().to_string().to_json());
}
}
pub fn is_match<'a>(&'a self, path: &'a str) -> Option<regex::Captures> {
self.regex.captures(path)
}
pub fn parse(path: &str, endpoint: bool) -> Result<Path,String> {
let mut regex_body = "^".to_string() + &Path::sub_regex(path);
if endpoint {
regex_body = regex_body + "$";
}
let regex = match regex::Regex::new(®ex_body) {
Ok(re) => re,
Err(err) => return Err(format!("{}", err))
};
let mut params = vec![];
for capture in MATCHER.captures_iter(path) {
params.push(capture.at(1).unwrap_or("").to_string());
}
Ok(Path {
path: path.to_string(),
params: params,
regex: regex
})
}
fn sub_regex(path: &str) -> String {
return MATCHER.replace_all(path, "(?P<$1>[^/?&]+)");
}
}
#[test]
fn it_normalize() {
assert_eq!(normalize("/test"), "test");
assert_eq!(normalize("test"), "test");
}
#[test]
fn sub_regex() {
let res = Path::sub_regex(":user_id/messages/:message_id");
assert_eq!(&res, "(?P<user_id>[^/?&]+)/messages/(?P<message_id>[^/?&]+)")
}
#[test]
fn parse_and_match() |
#[test]
fn parse_and_match_root() {
let path = Path::parse("", true).unwrap();
assert!(match path.is_match("") {
Some(captures) => captures.at(0).unwrap() == "",
None => false
});
}
#[test]
fn parse_and_match_single_val() {
let path = Path::parse(":id", true).unwrap();
assert!(match path.is_match("550e8400-e29b-41d4-a716-446655440000") {
Some(captures) => captures.name("id").unwrap() == "550e8400-e29b-41d4-a716-446655440000",
None => false
});
} | {
let path = Path::parse(":user_id/messages/:message_id", true).unwrap();
assert!(match path.is_match("1920/messages/100500") {
Some(captures) => {
captures.name("user_id").unwrap() == "1920" &&
captures.name("message_id").unwrap() == "100500"
}
None => false
});
assert!(match path.is_match("1920/messages/not_match/100500") {
Some(_) => false,
None => true
});
} | identifier_body |
babylon.multiMaterial.ts | module BABYLON {
export class MultiMaterial extends Material {
public subMaterials = new Array<Material>();
constructor(name: string, scene: Scene) {
| // Properties
public getSubMaterial(index) {
if (index < 0 || index >= this.subMaterials.length) {
return this.getScene().defaultMaterial;
}
return this.subMaterials[index];
}
// Methods
public isReady(mesh?: AbstractMesh): boolean {
for (var index = 0; index < this.subMaterials.length; index++) {
var subMaterial = this.subMaterials[index];
if (subMaterial) {
if (!this.subMaterials[index].isReady(mesh)) {
return false;
}
}
}
return true;
}
public clone(name: string, cloneChildren?: boolean): MultiMaterial {
var newMultiMaterial = new MultiMaterial(name, this.getScene());
for (var index = 0; index < this.subMaterials.length; index++) {
var subMaterial: Material = null;
if (cloneChildren) {
subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
} else {
subMaterial = this.subMaterials[index];
}
newMultiMaterial.subMaterials.push(subMaterial);
}
return newMultiMaterial;
}
public serialize(): any {
var serializationObject: any = {};
serializationObject.name = this.name;
serializationObject.id = this.id;
serializationObject.tags = Tags.GetTags(this);
serializationObject.materials = [];
for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
var subMat = this.subMaterials[matIndex];
if (subMat) {
serializationObject.materials.push(subMat.id);
} else {
serializationObject.materials.push(null);
}
}
return serializationObject;
}
}
} | super(name, scene, true);
scene.multiMaterials.push(this);
}
| identifier_body |
babylon.multiMaterial.ts | module BABYLON {
export class MultiMaterial extends Material {
public subMaterials = new Array<Material>();
constructor(name: string, scene: Scene) {
super(name, scene, true);
scene.multiMaterials.push(this);
}
// Properties
public getSubMaterial(index) {
if (index < 0 || index >= this.subMaterials.length) {
return this.getScene().defaultMaterial;
}
return this.subMaterials[index];
}
// Methods
public isReady(mesh?: AbstractMesh): boolean {
for (var index = 0; index < this.subMaterials.length; index++) {
var subMaterial = this.subMaterials[index];
if (subMaterial) {
if (!this.subMaterials[index].isReady(mesh)) {
return false;
}
}
}
return true;
}
public clone(name: string, cloneChildren?: boolean): MultiMaterial {
var newMultiMaterial = new MultiMaterial(name, this.getScene());
for (var index = 0; index < this.subMaterials.length; index++) {
var subMaterial: Material = null;
if (cloneChildren) {
subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
} else {
subMaterial = this.subMaterials[index];
} |
return newMultiMaterial;
}
public serialize(): any {
var serializationObject: any = {};
serializationObject.name = this.name;
serializationObject.id = this.id;
serializationObject.tags = Tags.GetTags(this);
serializationObject.materials = [];
for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
var subMat = this.subMaterials[matIndex];
if (subMat) {
serializationObject.materials.push(subMat.id);
} else {
serializationObject.materials.push(null);
}
}
return serializationObject;
}
}
} | newMultiMaterial.subMaterials.push(subMaterial);
} | random_line_split |
babylon.multiMaterial.ts | module BABYLON {
export class MultiMaterial extends Material {
public subMaterials = new Array<Material>();
constructor(name: string, scene: Scene) {
super(name, scene, true);
scene.multiMaterials.push(this);
}
// Properties
public getSubMaterial(index) {
if (index < 0 || index >= this.subMaterials.length) {
return this.getScene().defaultMaterial;
}
return this.subMaterials[index];
}
// Methods
public isReady(mesh?: AbstractMesh): boolean {
for (var index = 0; index < this.subMaterials.length; index++) {
var subMaterial = this.subMaterials[index];
if (subMaterial) {
if (!this.subMaterials[index].isReady(mesh)) {
return false;
}
}
}
return true;
}
public clone(name: string, cloneChildren?: boolean): MultiMaterial {
var newMultiMaterial = new MultiMaterial(name, this.getScene());
for (var index = 0; index < this.subMaterials.length; index++) {
var subMaterial: Material = null;
if (cloneChildren) {
subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
} else {
subMaterial = this.subMaterials[index];
}
newMultiMaterial.subMaterials.push(subMaterial);
}
return newMultiMaterial;
}
public se | : any {
var serializationObject: any = {};
serializationObject.name = this.name;
serializationObject.id = this.id;
serializationObject.tags = Tags.GetTags(this);
serializationObject.materials = [];
for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
var subMat = this.subMaterials[matIndex];
if (subMat) {
serializationObject.materials.push(subMat.id);
} else {
serializationObject.materials.push(null);
}
}
return serializationObject;
}
}
} | rialize() | identifier_name |
babylon.multiMaterial.ts | module BABYLON {
export class MultiMaterial extends Material {
public subMaterials = new Array<Material>();
constructor(name: string, scene: Scene) {
super(name, scene, true);
scene.multiMaterials.push(this);
}
// Properties
public getSubMaterial(index) {
if (index < 0 || index >= this.subMaterials.length) {
return this.getScene().defaultMaterial;
}
return this.subMaterials[index];
}
// Methods
public isReady(mesh?: AbstractMesh): boolean {
for (var index = 0; index < this.subMaterials.length; index++) {
var subMaterial = this.subMaterials[index];
if (subMaterial) {
if (!this.subMaterials[index].isReady(mesh)) {
return false;
}
}
}
return true;
}
public clone(name: string, cloneChildren?: boolean): MultiMaterial {
var newMultiMaterial = new MultiMaterial(name, this.getScene());
for (var index = 0; index < this.subMaterials.length; index++) {
var subMaterial: Material = null;
if (cloneChildren) {
subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
} else {
| newMultiMaterial.subMaterials.push(subMaterial);
}
return newMultiMaterial;
}
public serialize(): any {
var serializationObject: any = {};
serializationObject.name = this.name;
serializationObject.id = this.id;
serializationObject.tags = Tags.GetTags(this);
serializationObject.materials = [];
for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
var subMat = this.subMaterials[matIndex];
if (subMat) {
serializationObject.materials.push(subMat.id);
} else {
serializationObject.materials.push(null);
}
}
return serializationObject;
}
}
} | subMaterial = this.subMaterials[index];
}
| conditional_block |
main.js | $(function() {
var FADE_TIME = 150; // 毫秒
var TYPING_TIMER_LENGTH = 400; // 毫秒
var COLORS = [
'black', 'grey', 'green', 'blue',
'yellow', 'pink', 'yellow', 'brown',
'orange', 'chocolate', 'midnightblue', 'lavender'
];
//初始化
var $window = $(window);
var $usernameInput = $('.usernameInput');
var $messages = $('.messages');
var $inputMessage = $('.inputMessage');
var $loginPage = $('.login.page');
var $chatPage = $('.chat.page');
// 建立用户名
var username;
var connected = false;
var typing = false;
var lastTypingTime;
var $currentInput = $usernameInput.focus();
var socket = io();
function addParticipantsMessage (data) {
var message = '';
if (data.numUsers === 1) {
message += "目前有1位参与者";
} else {
message += "目前有 " + data.numUsers + " 位参与者";
}
log(message);
}
// 把输入转换为用户名(trim去掉前后空格)
function setUsername () {
username = cleanInput($usernameInput.val().trim());
// 用户名正确 切换页面
i | Input(message);
if (message && connected) {
$inputMessage.val('');
addChatMessage({
username: username,
message: message
});
// 告诉服务器
socket.emit('new message', message);
}
}
function log (message, options) {
var $el = $('<li>').addClass('log').text(message);
addMessageElement($el, options);
}
// 看不懂!
function addChatMessage (data, options) {
var $typingMessages = getTypingMessages(data);
options = options || {};
if ($typingMessages.length !== 0) {
options.fade = false;
$typingMessages.remove();
}
var $usernameDiv = $('<span class="username"/>')
.text(data.username)
.css('color', getUsernameColor(data.username));
var $messageBodyDiv = $('<span class="messageBody">')
.text(data.message);
var typingClass = data.typing ? 'typing' : '';
var $messageDiv = $('<li class="message"/>')
.data('username', data.username)
.addClass(typingClass)
.append($usernameDiv, $messageBodyDiv);
addMessageElement($messageDiv, options);
}
// 添加正在输入
function addChatTyping (data) {
data.typing = true;
data.message = '正在输入';
addChatMessage(data);
}
//移除正在输入
function removeChatTyping (data) {
getTypingMessages(data).fadeOut(function () {
$(this).remove();
});
}
// 添加消息并且保持页面在底部??
// options.fade - If the element should fade-in (default = true)
// options.prepend - If the element should prepend
// all other messages (default = false)
function addMessageElement (el, options) {
var $el = $(el);
// 我也不是很懂...求指导
if (!options) {
options = {};
}
if (typeof options.fade === 'undefined') {
options.fade = true;
}
if (typeof options.prepend === 'undefined') {
options.prepend = false;
}
// 应用选项
if (options.fade) {
$el.hide().fadeIn(FADE_TIME);
}
if (options.prepend) {
$messages.prepend($el);
} else {
$messages.append($el);
}
$messages[0].scrollTop = $messages[0].scrollHeight;
}
//确保输入不包含html标签之类的东西
function cleanInput (input) {
return $('<div/>').text(input).text();
}
// 更新正在输入事件 查看是否正在输入
function updateTyping () {
if (connected) {
if (!typing) {
typing = true;
socket.emit('typing');
}
lastTypingTime = (new Date()).getTime();
setTimeout(function () {
var typingTimer = (new Date()).getTime();
var timeDiff = typingTimer - lastTypingTime;
if (timeDiff >= TYPING_TIMER_LENGTH && typing) {
socket.emit('stop typing');
typing = false;
}
}, TYPING_TIMER_LENGTH);
}
}
// 获得是否正在输入的消息
function getTypingMessages (data) {
return $('.typing.message').filter(function (i) {
return $(this).data('username') === data.username;
});
}
// 用户名的颜色 使用哈希函数
function getUsernameColor (username) {
// 哈希函数代码
var hash = 7;
for (var i = 0; i < username.length; i++) {
hash = username.charCodeAt(i) + (hash << 5) - hash;
}
// 计算颜色
var index = Math.abs(hash % COLORS.length);
return COLORS[index];
}
// 键盘行为
$window.keydown(function (event) {
// 键盘按下自动聚焦
if (!(event.ctrlKey || event.metaKey || event.altKey)) {
$currentInput.focus();
}
// 按下回车键
if (event.which === 13) {
if (username) {
sendMessage();
socket.emit('stop typing');
typing = false;
} else {
setUsername();
}
}
});
$inputMessage.on('input', function() {
updateTyping();
});
// 鼠标点击行为
// 鼠标点击时聚焦输入框
$loginPage.click(function () {
$currentInput.focus();
});
$inputMessage.click(function () {
$inputMessage.focus();
});
// Socket events
// 登录信息
socket.on('login', function (data) {
connected = true;
var message = "使用socket.io制作 ";
log(message, {
prepend: true
});
addParticipantsMessage(data);
});
// 有新信息更新
socket.on('new message', function (data) {
addChatMessage(data);
});
// 用户加入
socket.on('user joined', function (data) {
log(data.username + ' 加入了');
addParticipantsMessage(data);
});
// 用户离开
socket.on('user left', function (data) {
log(data.username + ' 离开了');
addParticipantsMessage(data);
removeChatTyping(data);
});
// 正在输入
socket.on('typing', function (data) {
addChatTyping(data);
});
// 删除输入信息
socket.on('stop typing', function (data) {
removeChatTyping(data);
});
});
| f (username) {
$loginPage.fadeOut();
$chatPage.show();
$loginPage.off('click');
$currentInput = $inputMessage.focus();
// 用户名提交至服务器
socket.emit('add user', username);
}
}
// 发送聊天信息
function sendMessage () {
var message = $inputMessage.val();
// 防止混入html标签
message = clean | identifier_body |
main.js | $(function() {
var FADE_TIME = 150; // 毫秒
var TYPING_TIMER_LENGTH = 400; // 毫秒
var COLORS = [
'black', 'grey', 'green', 'blue',
'yellow', 'pink', 'yellow', 'brown',
'orange', 'chocolate', 'midnightblue', 'lavender'
];
//初始化
var $window = $(window);
var $usernameInput = $('.usernameInput');
var $messages = $('.messages');
var $inputMessage = $('.inputMessage');
var $loginPage = $('.login.page');
var $chatPage = $('.chat.page');
// 建立用户名
var username;
var connected = false;
var typing = false;
var lastTypingTime;
var $currentInput = $usernameInput.focus();
var socket = io();
function addParticipantsMessage (data) {
var message = '';
if (data.numUsers === 1) {
message += "目前有1位参与者";
} else {
message += "目前有 " + data.numUsers + " 位参与者";
}
log(message);
}
// 把输入转换为用户名(trim去掉前后空格)
function setUsername () {
username = cleanInput($usernameInput.val().trim());
// 用户名正确 切换页面
if (username) {
$loginPage.fadeOut();
$chatPage.show();
$loginPage.off('click');
$currentInput = $inputMessage.focus();
// 用户名提交至服务器
socket.emit('add user', username);
}
}
// 发送聊天信息
function sendMessage () {
var message = $inputMessage.val();
// 防止混入html标签
message = cleanInput(message);
if (message && connected) {
$inputMessage.val('');
addChatMessage({
username: username,
message: message
});
// 告诉服务器
socket.emit('new message', message);
}
}
function log (message, options) {
var $el = $('<li>').addClass('log').text(message);
addMessageElement($el, options);
}
// 看不懂!
function addChatMessage (data, options) {
var $typingMessages = getTypingMessages(data);
options = options || {};
if ($typingMessages.length !== 0) {
options.fade = false;
$typingMessages.remove();
}
var $usernameDiv = $('<span class="username"/>')
.text(data.username)
.css('color', getUsernameColor(data.username));
var $messageBodyDiv = $('<span class="messageBody">')
.text(data.message);
var typingClass = data.typing ? 'typing' : '';
var $messageDiv = $('<li class="message"/>')
.data('username', data.username)
.addClass(typingClass)
.append($usernameDiv, $messageBodyDiv);
addMessageElement($messageDiv, options);
}
// 添加正在输入
function addChatTyping (data) {
data.typing = true;
data.message = '正在输入';
addChatMessage(data);
}
//移除正在输入
function removeChatTyping (data) {
getTypingMessages(data).fadeOut(function () {
$(this).remove();
});
}
// 添加消息并且保持页面在底部??
// options.fade - If the element should fade-in (default = true)
// options.prepend - If the element should prepend
// all other messages (default = false)
function addMessageElement (el, options) {
var $el = $(el);
// 我也不是很懂...求指导
if (!options) {
options = {};
}
if (typeof options.fade === 'undefined') {
options.fade = true;
}
if (typeof options.prepend === 'undefined') {
options.prepend = false;
}
// 应用选项
if (options.fade) {
$el.hide().fadeIn(FADE_TIME);
}
if (options.prepend) {
$messages.prepend($el);
} else {
$messages.append($el);
}
$messages[0].scrollTop = $messages[0].scrollHeight;
}
//确保输入不包含html标签之类的东西
function cleanInput (input) {
return $('<div/>').text(input).text();
}
// 更新正在输入事件 查看是否正在输入
function updateTyping () {
if (connected) {
if (!typing) {
typing = true;
socket.emit('typing');
}
lastTypingTime = (new Date()).getTime() | etTimeout(function () {
var typingTimer = (new Date()).getTime();
var timeDiff = typingTimer - lastTypingTime;
if (timeDiff >= TYPING_TIMER_LENGTH && typing) {
socket.emit('stop typing');
typing = false;
}
}, TYPING_TIMER_LENGTH);
}
}
// 获得是否正在输入的消息
function getTypingMessages (data) {
return $('.typing.message').filter(function (i) {
return $(this).data('username') === data.username;
});
}
// 用户名的颜色 使用哈希函数
function getUsernameColor (username) {
// 哈希函数代码
var hash = 7;
for (var i = 0; i < username.length; i++) {
hash = username.charCodeAt(i) + (hash << 5) - hash;
}
// 计算颜色
var index = Math.abs(hash % COLORS.length);
return COLORS[index];
}
// 键盘行为
$window.keydown(function (event) {
// 键盘按下自动聚焦
if (!(event.ctrlKey || event.metaKey || event.altKey)) {
$currentInput.focus();
}
// 按下回车键
if (event.which === 13) {
if (username) {
sendMessage();
socket.emit('stop typing');
typing = false;
} else {
setUsername();
}
}
});
$inputMessage.on('input', function() {
updateTyping();
});
// 鼠标点击行为
// 鼠标点击时聚焦输入框
$loginPage.click(function () {
$currentInput.focus();
});
$inputMessage.click(function () {
$inputMessage.focus();
});
// Socket events
// 登录信息
socket.on('login', function (data) {
connected = true;
var message = "使用socket.io制作 ";
log(message, {
prepend: true
});
addParticipantsMessage(data);
});
// 有新信息更新
socket.on('new message', function (data) {
addChatMessage(data);
});
// 用户加入
socket.on('user joined', function (data) {
log(data.username + ' 加入了');
addParticipantsMessage(data);
});
// 用户离开
socket.on('user left', function (data) {
log(data.username + ' 离开了');
addParticipantsMessage(data);
removeChatTyping(data);
});
// 正在输入
socket.on('typing', function (data) {
addChatTyping(data);
});
// 删除输入信息
socket.on('stop typing', function (data) {
removeChatTyping(data);
});
});
| ;
s | identifier_name |
main.js | $(function() {
var FADE_TIME = 150; // 毫秒
var TYPING_TIMER_LENGTH = 400; // 毫秒
var COLORS = [
'black', 'grey', 'green', 'blue',
'yellow', 'pink', 'yellow', 'brown',
'orange', 'chocolate', 'midnightblue', 'lavender'
];
//初始化
var $window = $(window);
var $usernameInput = $('.usernameInput');
var $messages = $('.messages');
var $inputMessage = $('.inputMessage');
var $loginPage = $('.login.page');
var $chatPage = $('.chat.page');
// 建立用户名
var username;
var connected = false;
var typing = false;
var lastTypingTime;
var $currentInput = $usernameInput.focus();
var socket = io();
function addParticipantsMessage (data) {
var message = '';
if (data.numUsers === 1) {
message += "目前有1位参与者";
} else {
message += "目前有 " + data.numUsers + " 位参与者";
}
log(message);
}
// 把输入转换为用户名(trim去掉前后空格)
function setUsername () {
username = cleanInput($usernameInput.val().trim());
// 用户名正确 切换页面
if (username) {
$loginPage.fadeOut();
$chatPage.show();
$loginPage.off('click');
$currentInput = $inputMessage.focus();
// 用户名提交至服务器
socket.emit('add user', username);
}
}
// 发送聊天信息
function sendMessage () {
var message = $inputMessage.val();
// 防止混入html标签
message = cleanInput(message);
if (message && connected) {
$inputMessage.val('');
addChatMessage({ | message: message
});
// 告诉服务器
socket.emit('new message', message);
}
}
function log (message, options) {
var $el = $('<li>').addClass('log').text(message);
addMessageElement($el, options);
}
// 看不懂!
function addChatMessage (data, options) {
var $typingMessages = getTypingMessages(data);
options = options || {};
if ($typingMessages.length !== 0) {
options.fade = false;
$typingMessages.remove();
}
var $usernameDiv = $('<span class="username"/>')
.text(data.username)
.css('color', getUsernameColor(data.username));
var $messageBodyDiv = $('<span class="messageBody">')
.text(data.message);
var typingClass = data.typing ? 'typing' : '';
var $messageDiv = $('<li class="message"/>')
.data('username', data.username)
.addClass(typingClass)
.append($usernameDiv, $messageBodyDiv);
addMessageElement($messageDiv, options);
}
// 添加正在输入
function addChatTyping (data) {
data.typing = true;
data.message = '正在输入';
addChatMessage(data);
}
//移除正在输入
function removeChatTyping (data) {
getTypingMessages(data).fadeOut(function () {
$(this).remove();
});
}
// 添加消息并且保持页面在底部??
// options.fade - If the element should fade-in (default = true)
// options.prepend - If the element should prepend
// all other messages (default = false)
function addMessageElement (el, options) {
var $el = $(el);
// 我也不是很懂...求指导
if (!options) {
options = {};
}
if (typeof options.fade === 'undefined') {
options.fade = true;
}
if (typeof options.prepend === 'undefined') {
options.prepend = false;
}
// 应用选项
if (options.fade) {
$el.hide().fadeIn(FADE_TIME);
}
if (options.prepend) {
$messages.prepend($el);
} else {
$messages.append($el);
}
$messages[0].scrollTop = $messages[0].scrollHeight;
}
//确保输入不包含html标签之类的东西
function cleanInput (input) {
return $('<div/>').text(input).text();
}
// 更新正在输入事件 查看是否正在输入
function updateTyping () {
if (connected) {
if (!typing) {
typing = true;
socket.emit('typing');
}
lastTypingTime = (new Date()).getTime();
setTimeout(function () {
var typingTimer = (new Date()).getTime();
var timeDiff = typingTimer - lastTypingTime;
if (timeDiff >= TYPING_TIMER_LENGTH && typing) {
socket.emit('stop typing');
typing = false;
}
}, TYPING_TIMER_LENGTH);
}
}
// 获得是否正在输入的消息
function getTypingMessages (data) {
return $('.typing.message').filter(function (i) {
return $(this).data('username') === data.username;
});
}
// 用户名的颜色 使用哈希函数
function getUsernameColor (username) {
// 哈希函数代码
var hash = 7;
for (var i = 0; i < username.length; i++) {
hash = username.charCodeAt(i) + (hash << 5) - hash;
}
// 计算颜色
var index = Math.abs(hash % COLORS.length);
return COLORS[index];
}
// 键盘行为
$window.keydown(function (event) {
// 键盘按下自动聚焦
if (!(event.ctrlKey || event.metaKey || event.altKey)) {
$currentInput.focus();
}
// 按下回车键
if (event.which === 13) {
if (username) {
sendMessage();
socket.emit('stop typing');
typing = false;
} else {
setUsername();
}
}
});
$inputMessage.on('input', function() {
updateTyping();
});
// 鼠标点击行为
// 鼠标点击时聚焦输入框
$loginPage.click(function () {
$currentInput.focus();
});
$inputMessage.click(function () {
$inputMessage.focus();
});
// Socket events
// 登录信息
socket.on('login', function (data) {
connected = true;
var message = "使用socket.io制作 ";
log(message, {
prepend: true
});
addParticipantsMessage(data);
});
// 有新信息更新
socket.on('new message', function (data) {
addChatMessage(data);
});
// 用户加入
socket.on('user joined', function (data) {
log(data.username + ' 加入了');
addParticipantsMessage(data);
});
// 用户离开
socket.on('user left', function (data) {
log(data.username + ' 离开了');
addParticipantsMessage(data);
removeChatTyping(data);
});
// 正在输入
socket.on('typing', function (data) {
addChatTyping(data);
});
// 删除输入信息
socket.on('stop typing', function (data) {
removeChatTyping(data);
});
}); | username: username, | random_line_split |
main.js | $(function() {
var FADE_TIME = 150; // 毫秒
var TYPING_TIMER_LENGTH = 400; // 毫秒
var COLORS = [
'black', 'grey', 'green', 'blue',
'yellow', 'pink', 'yellow', 'brown',
'orange', 'chocolate', 'midnightblue', 'lavender'
];
//初始化
var $window = $(window);
var $usernameInput = $('.usernameInput');
var $messages = $('.messages');
var $inputMessage = $('.inputMessage');
var $loginPage = $('.login.page');
var $chatPage = $('.chat.page');
// 建立用户名
var username;
var connected = false;
var typing = false;
var lastTypingTime;
var $currentInput = $usernameInput.focus();
var socket = io();
function addParticipantsMessage (data) {
var message = '';
if (data.numUsers === 1) {
message += "目前有1位参与者";
} else {
message += "目前有 " + data.numUsers + " 位参与者";
}
log(message);
}
// 把输入转换为用户名(trim去掉前后空格)
function setUsername () {
username = cleanInput($usernameInput.val().trim());
// 用户名正确 切换页面
if (username) {
$loginPage.fadeOut();
$chatPage.show();
$loginPage.off('click');
$currentInput = $inputMessage.focus();
// 用户名提交至服务器
socket.emit('add user', username);
}
}
// 发送聊天信息
function sendMessage () {
var message = $inputMessage.val();
// 防止混入html标签
message = cleanInput(message);
if (message && connected) {
$inputMessage.val('');
addChatMessage({
username: username,
message: message
});
// 告诉服务器
socket.emit('new message', message);
}
}
function log (message, options) {
var $el = $('<li>').addClass('log').text(message);
addMessageElement($el, options);
}
// 看不懂!
function addChatMessage (data, options) {
var $typingMessages = getTypingMessages(data);
options = options || {};
if ($typingMessages.length !== 0) {
options.fade = false;
$typingMessages.remove();
}
var $usernameDiv = $('<span class="username"/>')
.text(data.username)
.css('color', getUsernameColor(data.username));
var $messageBodyDiv = $('<span class="messageBody">')
.text(data.message);
var typingClass = data.typing ? 'typing' : '';
var $messageDiv = $('<li class="message"/>')
.data('username', data.username)
.addClass(typingClass)
.append($usernameDiv, $messageBodyDiv);
addMessageElement($messageDiv, options);
}
// 添加正在输入
function addChatTyping (data) {
data.typing = true;
data.message = '正在输入';
addChatMessage(data);
}
//移除正在输入
function removeChatTyping (data) {
getTypingMessages(data).fadeOut(function () {
$(this).remove();
});
}
// 添加消息并且保持页面在底部??
// options.fade - If the element should fade-in (default = true)
// options.prepend - If the element should prepend
// all other messages (default = false)
function addMessageElement (el, options) {
var $el = $(el);
// 我也不是很懂...求指导
if (!options) {
options = {};
}
if (typeof options.fade === 'undefined') {
options.fade = true;
}
if (typeof options.prepend === 'undefined') {
options.prepend = false;
}
// 应用选项
if (options.fade) {
| TIME);
}
if (options.prepend) {
$messages.prepend($el);
} else {
$messages.append($el);
}
$messages[0].scrollTop = $messages[0].scrollHeight;
}
//确保输入不包含html标签之类的东西
function cleanInput (input) {
return $('<div/>').text(input).text();
}
// 更新正在输入事件 查看是否正在输入
function updateTyping () {
if (connected) {
if (!typing) {
typing = true;
socket.emit('typing');
}
lastTypingTime = (new Date()).getTime();
setTimeout(function () {
var typingTimer = (new Date()).getTime();
var timeDiff = typingTimer - lastTypingTime;
if (timeDiff >= TYPING_TIMER_LENGTH && typing) {
socket.emit('stop typing');
typing = false;
}
}, TYPING_TIMER_LENGTH);
}
}
// 获得是否正在输入的消息
function getTypingMessages (data) {
return $('.typing.message').filter(function (i) {
return $(this).data('username') === data.username;
});
}
// 用户名的颜色 使用哈希函数
function getUsernameColor (username) {
// 哈希函数代码
var hash = 7;
for (var i = 0; i < username.length; i++) {
hash = username.charCodeAt(i) + (hash << 5) - hash;
}
// 计算颜色
var index = Math.abs(hash % COLORS.length);
return COLORS[index];
}
// 键盘行为
$window.keydown(function (event) {
// 键盘按下自动聚焦
if (!(event.ctrlKey || event.metaKey || event.altKey)) {
$currentInput.focus();
}
// 按下回车键
if (event.which === 13) {
if (username) {
sendMessage();
socket.emit('stop typing');
typing = false;
} else {
setUsername();
}
}
});
$inputMessage.on('input', function() {
updateTyping();
});
// 鼠标点击行为
// 鼠标点击时聚焦输入框
$loginPage.click(function () {
$currentInput.focus();
});
$inputMessage.click(function () {
$inputMessage.focus();
});
// Socket events
// 登录信息
socket.on('login', function (data) {
connected = true;
var message = "使用socket.io制作 ";
log(message, {
prepend: true
});
addParticipantsMessage(data);
});
// 有新信息更新
socket.on('new message', function (data) {
addChatMessage(data);
});
// 用户加入
socket.on('user joined', function (data) {
log(data.username + ' 加入了');
addParticipantsMessage(data);
});
// 用户离开
socket.on('user left', function (data) {
log(data.username + ' 离开了');
addParticipantsMessage(data);
removeChatTyping(data);
});
// 正在输入
socket.on('typing', function (data) {
addChatTyping(data);
});
// 删除输入信息
socket.on('stop typing', function (data) {
removeChatTyping(data);
});
});
| $el.hide().fadeIn(FADE_ | conditional_block |
.happydoc.TkMoleculeDrawer.py | (S'7f2210613c44962221805a1b28aa76d6'
p1
(ihappydoclib.parseinfo.moduleinfo
ModuleInfo
p2
(dp3
S'_namespaces'
p4
((dp5
S'TkDrawer'
p6
(ihappydoclib.parseinfo.classinfo
ClassInfo
p7
(dp8
g4
((dp9
(dp10
tp11
sS'_filename'
p12
S'../python/frowns/Depict/TkMoleculeDrawer.py'
p13
sS'_docstring'
p14
S''
sS'_class_member_info'
p15
(lp16
sS'_name'
p17
g6
sS'_parent'
p18
g2
sS'_comment_info'
p19
(dp20
sS'_base_class_info'
p21
(lp22
S'DrawMolHarness'
p23
aS'TkMixin'
p24
asS'_configuration_values'
p25
(dp26
sS'_class_info'
p27
g9
sS'_function_info'
p28
g10
sS'_comments'
p29
S''
sbsS'TkMixin'
p30
(ihappydoclib.parseinfo.classinfo
ClassInfo
p31
(dp32
g4
((dp33
(dp34
S'pack_forget'
p35
(ihappydoclib.parseinfo.functioninfo
FunctionInfo
p36
(dp37
g4
((dp38
(dp39
tp40
sS'_exception_info'
p41
(dp42
sS'_parameter_names'
p43
(S'self'
p44
tp45
sS'_parameter_info'
p46
(dp47
g44
(NNNtp48
ssg12
g13
sg14
S''
sg17
g35
sg18
g31
sg19
g20
sg25
(dp49
sg27
g38
sg28
g39
sg29
S''
sbsS'_resize'
p50
(ihappydoclib.parseinfo.functioninfo
FunctionInfo
p51
(dp52
g4
((dp53
(dp54
tp55
sg41
(dp56
sg43
(S'self'
p57
S'event'
p58
tp59
sg46
(dp60
g57
(NNNtp61
sg58
(NNNtp62
ssg12
g13
sg14
S'(event) -> resive the drawing to event.height, event.width'
p63
sg17
g50
sg18
g31
sg19
g20
sg25
(dp64
sg27
g53
sg28
g54
sg29
S''
sbsS'_clear'
p65
(ihappydoclib.parseinfo.functioninfo
FunctionInfo
p66
(dp67
g4
((dp68
(dp69
tp70
sg41
(dp71
sg43
(S'self'
p72
tp73
sg46
(dp74
g72
(NNNtp75
ssg12
g13
sg14
S''
sg17
g65
sg18
g31
sg19
g20
sg25
(dp76
sg27
g68
sg28
g69
sg29
S''
sbsS'_init'
p77
(ihappydoclib.parseinfo.functioninfo
FunctionInfo
p78
(dp79
g4
((dp80
(dp81
tp82
sg41
(dp83
sg43
(S'self'
p84
S'master'
p85
S'height'
p86
S'width'
p87
tp88
sg46
(dp89
g87
(NNNtp90
sg84
(NNNtp91
sg85
(NNNtp92
sg86
(NNNtp93
ssg12
g13
sg14
S''
sg17
g77
sg18
g31
sg19
g20
sg25
(dp94
sg27
g80
sg28
g81
sg29
S''
sbsS'postscript'
p95
(ihappydoclib.parseinfo.functioninfo
FunctionInfo
p96
(dp97
g4
((dp98
(dp99
tp100
sg41
(dp101
sg43
(S'self'
p102
S'*a'
p103
S'*kw'
p104
tp105
sg46
(dp106
g102
(NNNtp107
sg104
(NNNtp108
sg103
(NNNtp109
ssg12
g13
sg14
S'return a postscript image of the current molecule arguments\n are sent to the Tkinter canvas postscript method'
p110
sg17
g95
sg18
g31
sg19
g20
sg25
(dp111
sg27
g98
sg28
g99
sg29
S''
sbsS'_drawLine'
p112
(ihappydoclib.parseinfo.functioninfo
FunctionInfo
p113
(dp114
g4
((dp115
(dp116
tp117
sg41
(dp118
sg43
(S'self'
p119
S'x1'
p120
S'y1'
p121
S'x2'
p122
S'y2'
p123
S'color'
p124
tp125
sg46
(dp126
g123
(NNNtp127
sg124
(NNNtp128
sg119
(NNNtp129
sg122
(NNNtp130
sg121
(NNNtp131
sg120
(NNNtp132
ssg12
g13
sg14
S''
sg17
g112
sg18
g31
sg19
g20
sg25
(dp133
sg27
g115
sg28
g116
sg29
S''
sbsS'grid'
p134
(ihappydoclib.parseinfo.functioninfo
FunctionInfo
p135
(dp136
g4
((dp137
(dp138
tp139
sg41
(dp140
sg43
(S'self'
p141
S'*a'
p142
S'*kw'
p143
tp144
sg46 | (NNNtp147
sg142
(NNNtp148
ssg12
g13
sg14
S''
sg17
g134
sg18
g31
sg19
g20
sg25
(dp149
sg27
g137
sg28
g138
sg29
S''
sbsS'_drawOval'
p150
(ihappydoclib.parseinfo.functioninfo
FunctionInfo
p151
(dp152
g4
((dp153
(dp154
tp155
sg41
(dp156
sg43
(S'self'
p157
S'x'
S'y'
S'xh'
p158
S'yh'
p159
tp160
sg46
(dp161
S'y'
(NNNtp162
sS'x'
(NNNtp163
sg157
(NNNtp164
sg158
(NNNtp165
sg159
(NNNtp166
ssg12
g13
sg14
S''
sg17
g150
sg18
g31
sg19
g20
sg25
(dp167
sg27
g153
sg28
g154
sg29
S''
sbsS'_drawText'
p168
(ihappydoclib.parseinfo.functioninfo
FunctionInfo
p169
(dp170
g4
((dp171
(dp172
tp173
sg41
(dp174
sg43
(S'self'
p175
S'text'
p176
S'font'
p177
S'fontsize'
p178
S'x'
S'y'
S'color'
p179
S'bg'
p180
tp181
sg46
(dp182
g180
(I1
S'"white"'
Ntp183
sg179
(NNNtp184
sg176
(NNNtp185
sg175
(NNNtp186
sg178
(NNNtp187
sS'y'
(NNNtp188
sS'x'
(NNNtp189
sg177
(NNNtp190
ssg12
g13
sg14
S''
sg17
g168
sg18
g31
sg19
g20
sg25
(dp191
sg27
g171
sg28
g172
sg29
S''
sbsS'pack'
p192
(ihappydoclib.parseinfo.functioninfo
FunctionInfo
p193
(dp194
g4
((dp195
(dp196
tp197
sg41
(dp198
sg43
(S'self'
p199
S'*a'
p200
S'*kw'
p201
tp202
sg46
(dp203
g199
(NNNtp204
sg201
(NNNtp205
sg200
(NNNtp206
ssg12
g13
sg14
S''
sg17
g192
sg18
g31
sg19
g20
sg25
(dp207
sg27
g195
sg28
g196
sg29
S''
sbstp208
sg12
g13
sg14
S''
sg15
(lp209
sg17
g30
sg18
g2
sg19
g20
sg21
(lp210
sg25
(dp211
sg27
g33
sg28
g34
sg29
S''
sbs(dp212
tp213
sS'_import_info'
p214
(ihappydoclib.parseinfo.imports
ImportInfo
p215
(dp216
S'_named_imports'
p217
(dp218
S'Tkinter'
p219
(lp220
S'*'
asS'MoleculeDrawer'
p221
(lp222
S'DrawMolHarness'
p223
assS'_straight_imports'
p224
(lp225
sbsg12
g13
sg14
S''
sg17
S'TkMoleculeDrawer'
p226
sg18
Nsg19
g20
sg25
(dp227
S'include_comments'
p228
I1
sS'cacheFilePrefix'
p229
S'.happydoc.'
p230
sS'useCache'
p231
I1
sS'docStringFormat'
p232
S'StructuredText'
p233
ssg27
g5
sg28
g212
sg29
S''
sbt. | (dp145
g141
(NNNtp146
sg143 | random_line_split |
censor.py | import re
import json
import urlparse
from holster.enum import Enum
from unidecode import unidecode
from disco.types.base import cached_property
from disco.types.channel import ChannelType
from disco.util.sanitize import S
from disco.api.http import APIException
from rowboat.redis import rdb
from rowboat.util.stats import timed
from rowboat.util.zalgo import ZALGO_RE
from rowboat.plugins import RowboatPlugin as Plugin
from rowboat.types import SlottedModel, Field, ListField, DictField, ChannelField, snowflake, lower
from rowboat.types.plugin import PluginConfig
from rowboat.models.message import Message
from rowboat.plugins.modlog import Actions
from rowboat.constants import INVITE_LINK_RE, URL_RE
CensorReason = Enum(
'INVITE',
'DOMAIN',
'WORD',
'ZALGO',
)
class | (SlottedModel):
filter_zalgo = Field(bool, default=True)
filter_invites = Field(bool, default=True)
invites_guild_whitelist = ListField(snowflake, default=[])
invites_whitelist = ListField(lower, default=[])
invites_blacklist = ListField(lower, default=[])
filter_domains = Field(bool, default=True)
domains_whitelist = ListField(lower, default=[])
domains_blacklist = ListField(lower, default=[])
blocked_words = ListField(lower, default=[])
blocked_tokens = ListField(lower, default=[])
unidecode_tokens = Field(bool, default=False)
channel = Field(snowflake, default=None)
bypass_channel = Field(snowflake, default=None)
@cached_property
def blocked_re(self):
return re.compile(u'({})'.format(u'|'.join(
map(re.escape, self.blocked_tokens) +
map(lambda k: u'\\b{}\\b'.format(re.escape(k)), self.blocked_words)
)), re.I + re.U)
class CensorConfig(PluginConfig):
levels = DictField(int, CensorSubConfig)
channels = DictField(ChannelField, CensorSubConfig)
# It's bad kids!
class Censorship(Exception):
def __init__(self, reason, event, ctx):
self.reason = reason
self.event = event
self.ctx = ctx
self.content = S(event.content, escape_codeblocks=True)
@property
def details(self):
if self.reason is CensorReason.INVITE:
if self.ctx['guild']:
return u'invite `{}` to {}'.format(
self.ctx['invite'],
S(self.ctx['guild']['name'], escape_codeblocks=True)
)
else:
return u'invite `{}`'.format(self.ctx['invite'])
elif self.reason is CensorReason.DOMAIN:
if self.ctx['hit'] == 'whitelist':
return u'domain `{}` is not in whitelist'.format(S(self.ctx['domain'], escape_codeblocks=True))
else:
return u'domain `{}` is in blacklist'.format(S(self.ctx['domain'], escape_codeblocks=True))
elif self.reason is CensorReason.WORD:
return u'found blacklisted words `{}`'.format(
u', '.join([S(i, escape_codeblocks=True) for i in self.ctx['words']]))
elif self.reason is CensorReason.ZALGO:
return u'found zalgo at position `{}` in text'.format(
self.ctx['position']
)
@Plugin.with_config(CensorConfig)
class CensorPlugin(Plugin):
def compute_relevant_configs(self, event, author):
if event.channel_id in event.config.channels:
yield event.config.channels[event.channel.id]
if event.config.levels:
user_level = int(self.bot.plugins.get('CorePlugin').get_level(event.guild, author))
for level, config in event.config.levels.items():
if user_level <= level:
yield config
def get_invite_info(self, code):
if rdb.exists('inv:{}'.format(code)):
return json.loads(rdb.get('inv:{}'.format(code)))
try:
obj = self.client.api.invites_get(code)
except:
return
if obj.channel and obj.channel.type == ChannelType.GROUP_DM:
obj = {
'id': obj.channel.id,
'name': obj.channel.name
}
else:
obj = {
'id': obj.guild.id,
'name': obj.guild.name,
'icon': obj.guild.icon
}
# Cache for 12 hours
rdb.setex('inv:{}'.format(code), json.dumps(obj), 43200)
return obj
@Plugin.listen('MessageUpdate')
def on_message_update(self, event):
try:
msg = Message.get(id=event.id)
except Message.DoesNotExist:
self.log.warning('Not censoring MessageUpdate for id %s, %s, no stored message', event.channel_id, event.id)
return
if not event.content:
return
return self.on_message_create(
event,
author=event.guild.get_member(msg.author_id))
@Plugin.listen('MessageCreate')
def on_message_create(self, event, author=None):
author = author or event.author
if author.id == self.state.me.id:
return
if event.webhook_id:
return
configs = list(self.compute_relevant_configs(event, author))
if not configs:
return
tags = {'guild_id': event.guild.id, 'channel_id': event.channel.id}
with timed('rowboat.plugin.censor.duration', tags=tags):
try:
# TODO: perhaps imap here? how to raise exception then?
for config in configs:
if config.channel:
if event.channel_id != config.channel:
continue
if config.bypass_channel:
if event.channel_id == config.bypass_channel:
continue
if config.filter_zalgo:
self.filter_zalgo(event, config)
if config.filter_invites:
self.filter_invites(event, config)
if config.filter_domains:
self.filter_domains(event, config)
if config.blocked_words or config.blocked_tokens:
self.filter_blocked_words(event, config)
except Censorship as c:
self.call(
'ModLogPlugin.create_debounce',
event,
['MessageDelete'],
message_id=event.message.id,
)
try:
event.delete()
self.call(
'ModLogPlugin.log_action_ext',
Actions.CENSORED,
event.guild.id,
e=event,
c=c)
except APIException:
self.log.exception('Failed to delete censored message: ')
def filter_zalgo(self, event, config):
s = ZALGO_RE.search(event.content)
if s:
raise Censorship(CensorReason.ZALGO, event, ctx={
'position': s.start()
})
def filter_invites(self, event, config):
invites = INVITE_LINK_RE.findall(event.content)
for _, invite in invites:
invite_info = self.get_invite_info(invite)
need_whitelist = (
config.invites_guild_whitelist or
(config.invites_whitelist or not config.invites_blacklist)
)
whitelisted = False
if invite_info and invite_info.get('id') in config.invites_guild_whitelist:
whitelisted = True
if invite.lower() in config.invites_whitelist:
whitelisted = True
if need_whitelist and not whitelisted:
raise Censorship(CensorReason.INVITE, event, ctx={
'hit': 'whitelist',
'invite': invite,
'guild': invite_info,
})
elif config.invites_blacklist and invite.lower() in config.invites_blacklist:
raise Censorship(CensorReason.INVITE, event, ctx={
'hit': 'blacklist',
'invite': invite,
'guild': invite_info,
})
def filter_domains(self, event, config):
urls = URL_RE.findall(INVITE_LINK_RE.sub('', event.content))
for url in urls:
try:
parsed = urlparse.urlparse(url)
except:
continue
if (config.domains_whitelist or not config.domains_blacklist)\
and parsed.netloc.lower() not in config.domains_whitelist:
raise Censorship(CensorReason.DOMAIN, event, ctx={
'hit': 'whitelist',
'url': url,
'domain': parsed.netloc,
})
elif config.domains_blacklist and parsed.netloc.lower() in config.domains_blacklist:
raise Censorship(CensorReason.DOMAIN, event, ctx={
'hit': 'blacklist',
'url': url,
'domain': parsed.netloc
})
def filter_blocked_words(self, event, config):
content = event.content
if config.unidecode_tokens:
content = unidecode(content)
blocked_words = config.blocked_re.findall(content)
if blocked_words:
raise Censorship(CensorReason.WORD, event, ctx={
'words': blocked_words,
})
| CensorSubConfig | identifier_name |
censor.py | import re
import json
import urlparse
from holster.enum import Enum
from unidecode import unidecode
from disco.types.base import cached_property
from disco.types.channel import ChannelType
from disco.util.sanitize import S
from disco.api.http import APIException
from rowboat.redis import rdb
from rowboat.util.stats import timed
from rowboat.util.zalgo import ZALGO_RE
from rowboat.plugins import RowboatPlugin as Plugin
from rowboat.types import SlottedModel, Field, ListField, DictField, ChannelField, snowflake, lower
from rowboat.types.plugin import PluginConfig
from rowboat.models.message import Message
from rowboat.plugins.modlog import Actions
from rowboat.constants import INVITE_LINK_RE, URL_RE
CensorReason = Enum(
'INVITE',
'DOMAIN',
'WORD',
'ZALGO',
)
class CensorSubConfig(SlottedModel):
filter_zalgo = Field(bool, default=True)
filter_invites = Field(bool, default=True)
invites_guild_whitelist = ListField(snowflake, default=[])
invites_whitelist = ListField(lower, default=[])
invites_blacklist = ListField(lower, default=[])
filter_domains = Field(bool, default=True)
domains_whitelist = ListField(lower, default=[])
domains_blacklist = ListField(lower, default=[])
blocked_words = ListField(lower, default=[])
blocked_tokens = ListField(lower, default=[])
unidecode_tokens = Field(bool, default=False)
channel = Field(snowflake, default=None)
bypass_channel = Field(snowflake, default=None)
@cached_property
def blocked_re(self):
return re.compile(u'({})'.format(u'|'.join(
map(re.escape, self.blocked_tokens) +
map(lambda k: u'\\b{}\\b'.format(re.escape(k)), self.blocked_words)
)), re.I + re.U)
class CensorConfig(PluginConfig):
levels = DictField(int, CensorSubConfig)
channels = DictField(ChannelField, CensorSubConfig)
# It's bad kids!
class Censorship(Exception):
def __init__(self, reason, event, ctx):
self.reason = reason
self.event = event
self.ctx = ctx
self.content = S(event.content, escape_codeblocks=True)
@property
def details(self):
if self.reason is CensorReason.INVITE:
if self.ctx['guild']:
return u'invite `{}` to {}'.format(
self.ctx['invite'],
S(self.ctx['guild']['name'], escape_codeblocks=True)
)
else:
return u'invite `{}`'.format(self.ctx['invite'])
elif self.reason is CensorReason.DOMAIN:
if self.ctx['hit'] == 'whitelist':
return u'domain `{}` is not in whitelist'.format(S(self.ctx['domain'], escape_codeblocks=True))
else:
return u'domain `{}` is in blacklist'.format(S(self.ctx['domain'], escape_codeblocks=True))
elif self.reason is CensorReason.WORD:
return u'found blacklisted words `{}`'.format(
u', '.join([S(i, escape_codeblocks=True) for i in self.ctx['words']]))
elif self.reason is CensorReason.ZALGO:
return u'found zalgo at position `{}` in text'.format(
self.ctx['position']
)
@Plugin.with_config(CensorConfig)
class CensorPlugin(Plugin):
def compute_relevant_configs(self, event, author):
if event.channel_id in event.config.channels:
yield event.config.channels[event.channel.id]
if event.config.levels:
user_level = int(self.bot.plugins.get('CorePlugin').get_level(event.guild, author))
for level, config in event.config.levels.items():
if user_level <= level:
yield config
def get_invite_info(self, code):
if rdb.exists('inv:{}'.format(code)):
return json.loads(rdb.get('inv:{}'.format(code)))
try:
obj = self.client.api.invites_get(code)
except:
return
if obj.channel and obj.channel.type == ChannelType.GROUP_DM:
obj = {
'id': obj.channel.id,
'name': obj.channel.name
}
else:
obj = {
'id': obj.guild.id,
'name': obj.guild.name,
'icon': obj.guild.icon
}
# Cache for 12 hours
rdb.setex('inv:{}'.format(code), json.dumps(obj), 43200)
return obj
@Plugin.listen('MessageUpdate')
def on_message_update(self, event):
try:
msg = Message.get(id=event.id)
except Message.DoesNotExist:
self.log.warning('Not censoring MessageUpdate for id %s, %s, no stored message', event.channel_id, event.id)
return
if not event.content:
return
return self.on_message_create(
event,
author=event.guild.get_member(msg.author_id))
@Plugin.listen('MessageCreate')
def on_message_create(self, event, author=None):
author = author or event.author
if author.id == self.state.me.id:
return
if event.webhook_id:
return
configs = list(self.compute_relevant_configs(event, author))
if not configs:
return
tags = {'guild_id': event.guild.id, 'channel_id': event.channel.id}
with timed('rowboat.plugin.censor.duration', tags=tags):
try:
# TODO: perhaps imap here? how to raise exception then?
for config in configs:
if config.channel:
if event.channel_id != config.channel:
|
if config.bypass_channel:
if event.channel_id == config.bypass_channel:
continue
if config.filter_zalgo:
self.filter_zalgo(event, config)
if config.filter_invites:
self.filter_invites(event, config)
if config.filter_domains:
self.filter_domains(event, config)
if config.blocked_words or config.blocked_tokens:
self.filter_blocked_words(event, config)
except Censorship as c:
self.call(
'ModLogPlugin.create_debounce',
event,
['MessageDelete'],
message_id=event.message.id,
)
try:
event.delete()
self.call(
'ModLogPlugin.log_action_ext',
Actions.CENSORED,
event.guild.id,
e=event,
c=c)
except APIException:
self.log.exception('Failed to delete censored message: ')
def filter_zalgo(self, event, config):
s = ZALGO_RE.search(event.content)
if s:
raise Censorship(CensorReason.ZALGO, event, ctx={
'position': s.start()
})
def filter_invites(self, event, config):
invites = INVITE_LINK_RE.findall(event.content)
for _, invite in invites:
invite_info = self.get_invite_info(invite)
need_whitelist = (
config.invites_guild_whitelist or
(config.invites_whitelist or not config.invites_blacklist)
)
whitelisted = False
if invite_info and invite_info.get('id') in config.invites_guild_whitelist:
whitelisted = True
if invite.lower() in config.invites_whitelist:
whitelisted = True
if need_whitelist and not whitelisted:
raise Censorship(CensorReason.INVITE, event, ctx={
'hit': 'whitelist',
'invite': invite,
'guild': invite_info,
})
elif config.invites_blacklist and invite.lower() in config.invites_blacklist:
raise Censorship(CensorReason.INVITE, event, ctx={
'hit': 'blacklist',
'invite': invite,
'guild': invite_info,
})
def filter_domains(self, event, config):
urls = URL_RE.findall(INVITE_LINK_RE.sub('', event.content))
for url in urls:
try:
parsed = urlparse.urlparse(url)
except:
continue
if (config.domains_whitelist or not config.domains_blacklist)\
and parsed.netloc.lower() not in config.domains_whitelist:
raise Censorship(CensorReason.DOMAIN, event, ctx={
'hit': 'whitelist',
'url': url,
'domain': parsed.netloc,
})
elif config.domains_blacklist and parsed.netloc.lower() in config.domains_blacklist:
raise Censorship(CensorReason.DOMAIN, event, ctx={
'hit': 'blacklist',
'url': url,
'domain': parsed.netloc
})
def filter_blocked_words(self, event, config):
content = event.content
if config.unidecode_tokens:
content = unidecode(content)
blocked_words = config.blocked_re.findall(content)
if blocked_words:
raise Censorship(CensorReason.WORD, event, ctx={
'words': blocked_words,
})
| continue | conditional_block |
censor.py | import re
import json
import urlparse
from holster.enum import Enum
from unidecode import unidecode
from disco.types.base import cached_property
from disco.types.channel import ChannelType
from disco.util.sanitize import S
from disco.api.http import APIException
from rowboat.redis import rdb
from rowboat.util.stats import timed
from rowboat.util.zalgo import ZALGO_RE
from rowboat.plugins import RowboatPlugin as Plugin
from rowboat.types import SlottedModel, Field, ListField, DictField, ChannelField, snowflake, lower
from rowboat.types.plugin import PluginConfig
from rowboat.models.message import Message
from rowboat.plugins.modlog import Actions
from rowboat.constants import INVITE_LINK_RE, URL_RE
CensorReason = Enum(
'INVITE',
'DOMAIN',
'WORD',
'ZALGO',
)
class CensorSubConfig(SlottedModel):
filter_zalgo = Field(bool, default=True)
filter_invites = Field(bool, default=True)
invites_guild_whitelist = ListField(snowflake, default=[])
invites_whitelist = ListField(lower, default=[])
invites_blacklist = ListField(lower, default=[])
filter_domains = Field(bool, default=True)
domains_whitelist = ListField(lower, default=[])
domains_blacklist = ListField(lower, default=[])
blocked_words = ListField(lower, default=[])
blocked_tokens = ListField(lower, default=[])
unidecode_tokens = Field(bool, default=False)
channel = Field(snowflake, default=None)
bypass_channel = Field(snowflake, default=None)
@cached_property
def blocked_re(self):
return re.compile(u'({})'.format(u'|'.join(
map(re.escape, self.blocked_tokens) +
map(lambda k: u'\\b{}\\b'.format(re.escape(k)), self.blocked_words)
)), re.I + re.U)
class CensorConfig(PluginConfig):
levels = DictField(int, CensorSubConfig)
channels = DictField(ChannelField, CensorSubConfig)
# It's bad kids!
class Censorship(Exception):
def __init__(self, reason, event, ctx):
self.reason = reason
self.event = event
self.ctx = ctx
self.content = S(event.content, escape_codeblocks=True)
@property
def details(self):
if self.reason is CensorReason.INVITE:
if self.ctx['guild']:
return u'invite `{}` to {}'.format(
self.ctx['invite'],
S(self.ctx['guild']['name'], escape_codeblocks=True)
)
else:
return u'invite `{}`'.format(self.ctx['invite'])
elif self.reason is CensorReason.DOMAIN:
if self.ctx['hit'] == 'whitelist':
return u'domain `{}` is not in whitelist'.format(S(self.ctx['domain'], escape_codeblocks=True))
else:
return u'domain `{}` is in blacklist'.format(S(self.ctx['domain'], escape_codeblocks=True))
elif self.reason is CensorReason.WORD:
return u'found blacklisted words `{}`'.format(
u', '.join([S(i, escape_codeblocks=True) for i in self.ctx['words']]))
elif self.reason is CensorReason.ZALGO:
return u'found zalgo at position `{}` in text'.format(
self.ctx['position']
)
@Plugin.with_config(CensorConfig)
class CensorPlugin(Plugin):
def compute_relevant_configs(self, event, author):
if event.channel_id in event.config.channels:
yield event.config.channels[event.channel.id]
if event.config.levels:
user_level = int(self.bot.plugins.get('CorePlugin').get_level(event.guild, author))
for level, config in event.config.levels.items():
if user_level <= level:
yield config
def get_invite_info(self, code):
if rdb.exists('inv:{}'.format(code)):
return json.loads(rdb.get('inv:{}'.format(code)))
try:
obj = self.client.api.invites_get(code)
except:
return
if obj.channel and obj.channel.type == ChannelType.GROUP_DM:
obj = {
'id': obj.channel.id,
'name': obj.channel.name
}
else:
obj = {
'id': obj.guild.id,
'name': obj.guild.name,
'icon': obj.guild.icon
}
# Cache for 12 hours
rdb.setex('inv:{}'.format(code), json.dumps(obj), 43200)
return obj
@Plugin.listen('MessageUpdate')
def on_message_update(self, event):
try:
msg = Message.get(id=event.id)
except Message.DoesNotExist:
self.log.warning('Not censoring MessageUpdate for id %s, %s, no stored message', event.channel_id, event.id)
return
if not event.content:
return
return self.on_message_create(
event,
author=event.guild.get_member(msg.author_id))
@Plugin.listen('MessageCreate')
def on_message_create(self, event, author=None):
author = author or event.author
if author.id == self.state.me.id:
return
if event.webhook_id:
return
configs = list(self.compute_relevant_configs(event, author))
if not configs:
return
tags = {'guild_id': event.guild.id, 'channel_id': event.channel.id}
with timed('rowboat.plugin.censor.duration', tags=tags):
try:
# TODO: perhaps imap here? how to raise exception then?
for config in configs:
if config.channel:
if event.channel_id != config.channel:
continue
if config.bypass_channel:
if event.channel_id == config.bypass_channel:
continue
if config.filter_zalgo:
self.filter_zalgo(event, config)
if config.filter_invites:
self.filter_invites(event, config)
if config.filter_domains:
self.filter_domains(event, config)
if config.blocked_words or config.blocked_tokens:
self.filter_blocked_words(event, config)
except Censorship as c:
self.call(
'ModLogPlugin.create_debounce',
event,
['MessageDelete'],
message_id=event.message.id,
)
try:
event.delete()
self.call(
'ModLogPlugin.log_action_ext',
Actions.CENSORED,
event.guild.id,
e=event,
c=c)
except APIException:
self.log.exception('Failed to delete censored message: ')
def filter_zalgo(self, event, config):
s = ZALGO_RE.search(event.content)
if s:
raise Censorship(CensorReason.ZALGO, event, ctx={
'position': s.start()
})
def filter_invites(self, event, config):
invites = INVITE_LINK_RE.findall(event.content)
for _, invite in invites: | )
whitelisted = False
if invite_info and invite_info.get('id') in config.invites_guild_whitelist:
whitelisted = True
if invite.lower() in config.invites_whitelist:
whitelisted = True
if need_whitelist and not whitelisted:
raise Censorship(CensorReason.INVITE, event, ctx={
'hit': 'whitelist',
'invite': invite,
'guild': invite_info,
})
elif config.invites_blacklist and invite.lower() in config.invites_blacklist:
raise Censorship(CensorReason.INVITE, event, ctx={
'hit': 'blacklist',
'invite': invite,
'guild': invite_info,
})
def filter_domains(self, event, config):
urls = URL_RE.findall(INVITE_LINK_RE.sub('', event.content))
for url in urls:
try:
parsed = urlparse.urlparse(url)
except:
continue
if (config.domains_whitelist or not config.domains_blacklist)\
and parsed.netloc.lower() not in config.domains_whitelist:
raise Censorship(CensorReason.DOMAIN, event, ctx={
'hit': 'whitelist',
'url': url,
'domain': parsed.netloc,
})
elif config.domains_blacklist and parsed.netloc.lower() in config.domains_blacklist:
raise Censorship(CensorReason.DOMAIN, event, ctx={
'hit': 'blacklist',
'url': url,
'domain': parsed.netloc
})
def filter_blocked_words(self, event, config):
content = event.content
if config.unidecode_tokens:
content = unidecode(content)
blocked_words = config.blocked_re.findall(content)
if blocked_words:
raise Censorship(CensorReason.WORD, event, ctx={
'words': blocked_words,
}) | invite_info = self.get_invite_info(invite)
need_whitelist = (
config.invites_guild_whitelist or
(config.invites_whitelist or not config.invites_blacklist) | random_line_split |
censor.py | import re
import json
import urlparse
from holster.enum import Enum
from unidecode import unidecode
from disco.types.base import cached_property
from disco.types.channel import ChannelType
from disco.util.sanitize import S
from disco.api.http import APIException
from rowboat.redis import rdb
from rowboat.util.stats import timed
from rowboat.util.zalgo import ZALGO_RE
from rowboat.plugins import RowboatPlugin as Plugin
from rowboat.types import SlottedModel, Field, ListField, DictField, ChannelField, snowflake, lower
from rowboat.types.plugin import PluginConfig
from rowboat.models.message import Message
from rowboat.plugins.modlog import Actions
from rowboat.constants import INVITE_LINK_RE, URL_RE
CensorReason = Enum(
'INVITE',
'DOMAIN',
'WORD',
'ZALGO',
)
class CensorSubConfig(SlottedModel):
filter_zalgo = Field(bool, default=True)
filter_invites = Field(bool, default=True)
invites_guild_whitelist = ListField(snowflake, default=[])
invites_whitelist = ListField(lower, default=[])
invites_blacklist = ListField(lower, default=[])
filter_domains = Field(bool, default=True)
domains_whitelist = ListField(lower, default=[])
domains_blacklist = ListField(lower, default=[])
blocked_words = ListField(lower, default=[])
blocked_tokens = ListField(lower, default=[])
unidecode_tokens = Field(bool, default=False)
channel = Field(snowflake, default=None)
bypass_channel = Field(snowflake, default=None)
@cached_property
def blocked_re(self):
return re.compile(u'({})'.format(u'|'.join(
map(re.escape, self.blocked_tokens) +
map(lambda k: u'\\b{}\\b'.format(re.escape(k)), self.blocked_words)
)), re.I + re.U)
class CensorConfig(PluginConfig):
levels = DictField(int, CensorSubConfig)
channels = DictField(ChannelField, CensorSubConfig)
# It's bad kids!
class Censorship(Exception):
def __init__(self, reason, event, ctx):
self.reason = reason
self.event = event
self.ctx = ctx
self.content = S(event.content, escape_codeblocks=True)
@property
def details(self):
if self.reason is CensorReason.INVITE:
if self.ctx['guild']:
return u'invite `{}` to {}'.format(
self.ctx['invite'],
S(self.ctx['guild']['name'], escape_codeblocks=True)
)
else:
return u'invite `{}`'.format(self.ctx['invite'])
elif self.reason is CensorReason.DOMAIN:
if self.ctx['hit'] == 'whitelist':
return u'domain `{}` is not in whitelist'.format(S(self.ctx['domain'], escape_codeblocks=True))
else:
return u'domain `{}` is in blacklist'.format(S(self.ctx['domain'], escape_codeblocks=True))
elif self.reason is CensorReason.WORD:
return u'found blacklisted words `{}`'.format(
u', '.join([S(i, escape_codeblocks=True) for i in self.ctx['words']]))
elif self.reason is CensorReason.ZALGO:
return u'found zalgo at position `{}` in text'.format(
self.ctx['position']
)
@Plugin.with_config(CensorConfig)
class CensorPlugin(Plugin):
def compute_relevant_configs(self, event, author):
|
def get_invite_info(self, code):
if rdb.exists('inv:{}'.format(code)):
return json.loads(rdb.get('inv:{}'.format(code)))
try:
obj = self.client.api.invites_get(code)
except:
return
if obj.channel and obj.channel.type == ChannelType.GROUP_DM:
obj = {
'id': obj.channel.id,
'name': obj.channel.name
}
else:
obj = {
'id': obj.guild.id,
'name': obj.guild.name,
'icon': obj.guild.icon
}
# Cache for 12 hours
rdb.setex('inv:{}'.format(code), json.dumps(obj), 43200)
return obj
@Plugin.listen('MessageUpdate')
def on_message_update(self, event):
try:
msg = Message.get(id=event.id)
except Message.DoesNotExist:
self.log.warning('Not censoring MessageUpdate for id %s, %s, no stored message', event.channel_id, event.id)
return
if not event.content:
return
return self.on_message_create(
event,
author=event.guild.get_member(msg.author_id))
@Plugin.listen('MessageCreate')
def on_message_create(self, event, author=None):
author = author or event.author
if author.id == self.state.me.id:
return
if event.webhook_id:
return
configs = list(self.compute_relevant_configs(event, author))
if not configs:
return
tags = {'guild_id': event.guild.id, 'channel_id': event.channel.id}
with timed('rowboat.plugin.censor.duration', tags=tags):
try:
# TODO: perhaps imap here? how to raise exception then?
for config in configs:
if config.channel:
if event.channel_id != config.channel:
continue
if config.bypass_channel:
if event.channel_id == config.bypass_channel:
continue
if config.filter_zalgo:
self.filter_zalgo(event, config)
if config.filter_invites:
self.filter_invites(event, config)
if config.filter_domains:
self.filter_domains(event, config)
if config.blocked_words or config.blocked_tokens:
self.filter_blocked_words(event, config)
except Censorship as c:
self.call(
'ModLogPlugin.create_debounce',
event,
['MessageDelete'],
message_id=event.message.id,
)
try:
event.delete()
self.call(
'ModLogPlugin.log_action_ext',
Actions.CENSORED,
event.guild.id,
e=event,
c=c)
except APIException:
self.log.exception('Failed to delete censored message: ')
def filter_zalgo(self, event, config):
s = ZALGO_RE.search(event.content)
if s:
raise Censorship(CensorReason.ZALGO, event, ctx={
'position': s.start()
})
def filter_invites(self, event, config):
invites = INVITE_LINK_RE.findall(event.content)
for _, invite in invites:
invite_info = self.get_invite_info(invite)
need_whitelist = (
config.invites_guild_whitelist or
(config.invites_whitelist or not config.invites_blacklist)
)
whitelisted = False
if invite_info and invite_info.get('id') in config.invites_guild_whitelist:
whitelisted = True
if invite.lower() in config.invites_whitelist:
whitelisted = True
if need_whitelist and not whitelisted:
raise Censorship(CensorReason.INVITE, event, ctx={
'hit': 'whitelist',
'invite': invite,
'guild': invite_info,
})
elif config.invites_blacklist and invite.lower() in config.invites_blacklist:
raise Censorship(CensorReason.INVITE, event, ctx={
'hit': 'blacklist',
'invite': invite,
'guild': invite_info,
})
def filter_domains(self, event, config):
urls = URL_RE.findall(INVITE_LINK_RE.sub('', event.content))
for url in urls:
try:
parsed = urlparse.urlparse(url)
except:
continue
if (config.domains_whitelist or not config.domains_blacklist)\
and parsed.netloc.lower() not in config.domains_whitelist:
raise Censorship(CensorReason.DOMAIN, event, ctx={
'hit': 'whitelist',
'url': url,
'domain': parsed.netloc,
})
elif config.domains_blacklist and parsed.netloc.lower() in config.domains_blacklist:
raise Censorship(CensorReason.DOMAIN, event, ctx={
'hit': 'blacklist',
'url': url,
'domain': parsed.netloc
})
def filter_blocked_words(self, event, config):
content = event.content
if config.unidecode_tokens:
content = unidecode(content)
blocked_words = config.blocked_re.findall(content)
if blocked_words:
raise Censorship(CensorReason.WORD, event, ctx={
'words': blocked_words,
})
| if event.channel_id in event.config.channels:
yield event.config.channels[event.channel.id]
if event.config.levels:
user_level = int(self.bot.plugins.get('CorePlugin').get_level(event.guild, author))
for level, config in event.config.levels.items():
if user_level <= level:
yield config | identifier_body |
index.js | /**
*
* SelectMany
*
*/
import React from 'react';
import Select from 'react-select';
import PropTypes from 'prop-types';
import 'react-select/dist/react-select.css';
import { isArray, isNull, isUndefined, get, findIndex } from 'lodash';
import request from 'utils/request';
import templateObject from 'utils/templateObject';
import styles from './styles.scss';
class SelectMany extends React.Component { // eslint-disable-line react/prefer-stateless-function
constructor(props) {
super(props);
this.state = {
isLoading: true,
};
}
getOptions = (query) => {
const params = {
limit: 20,
source: this.props.relation.plugin || 'content-manager',
};
// Set `query` parameter if necessary
if (query) |
// Request URL
const requestUrlSuffix = query && this.props.record.get(this.props.relation.alias) ? this.props.record.get(this.props.relation.alias) : '';
// NOTE: keep this line if we rollback to the old container
// const requestUrlSuffix = query && this.props.record.get(this.props.relation.alias).toJS() ? this.props.record.get(this.props.relation.alias).toJS() : '';
const requestUrl = `/content-manager/explorer/${this.props.relation.model || this.props.relation.collection}/${requestUrlSuffix}`;
// Call our request helper (see 'utils/request')
return request(requestUrl, {
method: 'GET',
params,
})
.then(response => {
const options = isArray(response) ?
response.map(item => ({
value: item,
label: templateObject({ mainField: this.props.relation.displayedAttribute }, item).mainField,
})) :
[{
value: response,
label: response[this.props.relation.displayedAttribute],
}];
return { options };
})
.catch(() => {
strapi.notification.error('content-manager.notification.error.relationship.fetch');
});
}
handleChange = (value) => {
const filteredValue = value.filter((data, index ) => findIndex(value, (o) => o.value.id === data.value.id) === index);
const target = {
name: `record.${this.props.relation.alias}`,
type: 'select',
value: filteredValue,
};
this.props.setRecordAttribute({ target });
// NOTE: keep this line if we rollback to the old container
// this.props.setRecordAttribute(this.props.relation.alias, filteredValue);
}
render() {
const description = this.props.relation.description
? <p>{this.props.relation.description}</p>
: '';
const value = get(this.props.record, this.props.relation.alias);
// NOTE: keep this line if we rollback to the old container
// const value = this.props.record.get(this.props.relation.alias);
/* eslint-disable jsx-a11y/label-has-for */
return (
<div className={`form-group ${styles.selectMany}`}>
<label htmlFor={this.props.relation.alias}>{this.props.relation.alias}</label>
{description}
<Select.Async
onChange={this.handleChange}
loadOptions={this.getOptions}
id={this.props.relation.alias}
multi
value={isNull(value) || isUndefined(value) || value.size === 0 ? null : value.map(item => {
if (item) {
return {
value: get(item, 'value') || item,
label: get(item, 'label') || templateObject({ mainField: this.props.relation.displayedAttribute }, item).mainField || item.value.id,
};
}
})}
/>
</div>
);
/* eslint-disable jsx-a11y/label-has-for */
}
}
SelectMany.propTypes = {
record: PropTypes.oneOfType([
PropTypes.object,
PropTypes.bool,
]).isRequired,
relation: PropTypes.object.isRequired,
setRecordAttribute: PropTypes.func.isRequired,
};
export default SelectMany;
| {
params.query = query;
params.queryAttribute = this.props.relation.displayedAttribute;
} | conditional_block |
index.js | /**
*
* SelectMany
*
*/
import React from 'react';
import Select from 'react-select';
import PropTypes from 'prop-types';
import 'react-select/dist/react-select.css';
import { isArray, isNull, isUndefined, get, findIndex } from 'lodash';
import request from 'utils/request';
import templateObject from 'utils/templateObject';
import styles from './styles.scss';
class SelectMany extends React.Component { // eslint-disable-line react/prefer-stateless-function
| (props) {
super(props);
this.state = {
isLoading: true,
};
}
getOptions = (query) => {
const params = {
limit: 20,
source: this.props.relation.plugin || 'content-manager',
};
// Set `query` parameter if necessary
if (query) {
params.query = query;
params.queryAttribute = this.props.relation.displayedAttribute;
}
// Request URL
const requestUrlSuffix = query && this.props.record.get(this.props.relation.alias) ? this.props.record.get(this.props.relation.alias) : '';
// NOTE: keep this line if we rollback to the old container
// const requestUrlSuffix = query && this.props.record.get(this.props.relation.alias).toJS() ? this.props.record.get(this.props.relation.alias).toJS() : '';
const requestUrl = `/content-manager/explorer/${this.props.relation.model || this.props.relation.collection}/${requestUrlSuffix}`;
// Call our request helper (see 'utils/request')
return request(requestUrl, {
method: 'GET',
params,
})
.then(response => {
const options = isArray(response) ?
response.map(item => ({
value: item,
label: templateObject({ mainField: this.props.relation.displayedAttribute }, item).mainField,
})) :
[{
value: response,
label: response[this.props.relation.displayedAttribute],
}];
return { options };
})
.catch(() => {
strapi.notification.error('content-manager.notification.error.relationship.fetch');
});
}
handleChange = (value) => {
const filteredValue = value.filter((data, index ) => findIndex(value, (o) => o.value.id === data.value.id) === index);
const target = {
name: `record.${this.props.relation.alias}`,
type: 'select',
value: filteredValue,
};
this.props.setRecordAttribute({ target });
// NOTE: keep this line if we rollback to the old container
// this.props.setRecordAttribute(this.props.relation.alias, filteredValue);
}
render() {
const description = this.props.relation.description
? <p>{this.props.relation.description}</p>
: '';
const value = get(this.props.record, this.props.relation.alias);
// NOTE: keep this line if we rollback to the old container
// const value = this.props.record.get(this.props.relation.alias);
/* eslint-disable jsx-a11y/label-has-for */
return (
<div className={`form-group ${styles.selectMany}`}>
<label htmlFor={this.props.relation.alias}>{this.props.relation.alias}</label>
{description}
<Select.Async
onChange={this.handleChange}
loadOptions={this.getOptions}
id={this.props.relation.alias}
multi
value={isNull(value) || isUndefined(value) || value.size === 0 ? null : value.map(item => {
if (item) {
return {
value: get(item, 'value') || item,
label: get(item, 'label') || templateObject({ mainField: this.props.relation.displayedAttribute }, item).mainField || item.value.id,
};
}
})}
/>
</div>
);
/* eslint-disable jsx-a11y/label-has-for */
}
}
SelectMany.propTypes = {
record: PropTypes.oneOfType([
PropTypes.object,
PropTypes.bool,
]).isRequired,
relation: PropTypes.object.isRequired,
setRecordAttribute: PropTypes.func.isRequired,
};
export default SelectMany;
| constructor | identifier_name |
index.js | /**
*
* SelectMany
*
*/
import React from 'react';
import Select from 'react-select';
import PropTypes from 'prop-types';
import 'react-select/dist/react-select.css';
import { isArray, isNull, isUndefined, get, findIndex } from 'lodash';
import request from 'utils/request';
import templateObject from 'utils/templateObject';
import styles from './styles.scss';
class SelectMany extends React.Component { // eslint-disable-line react/prefer-stateless-function
constructor(props) {
super(props);
this.state = {
isLoading: true,
};
}
getOptions = (query) => {
const params = {
limit: 20,
source: this.props.relation.plugin || 'content-manager',
};
// Set `query` parameter if necessary
if (query) {
params.query = query;
params.queryAttribute = this.props.relation.displayedAttribute;
}
// Request URL
const requestUrlSuffix = query && this.props.record.get(this.props.relation.alias) ? this.props.record.get(this.props.relation.alias) : '';
// NOTE: keep this line if we rollback to the old container
// const requestUrlSuffix = query && this.props.record.get(this.props.relation.alias).toJS() ? this.props.record.get(this.props.relation.alias).toJS() : '';
const requestUrl = `/content-manager/explorer/${this.props.relation.model || this.props.relation.collection}/${requestUrlSuffix}`;
// Call our request helper (see 'utils/request')
return request(requestUrl, {
method: 'GET',
params,
})
.then(response => {
const options = isArray(response) ?
response.map(item => ({
value: item,
label: templateObject({ mainField: this.props.relation.displayedAttribute }, item).mainField,
})) :
[{
value: response,
label: response[this.props.relation.displayedAttribute],
}];
return { options };
})
.catch(() => {
strapi.notification.error('content-manager.notification.error.relationship.fetch');
});
}
handleChange = (value) => {
const filteredValue = value.filter((data, index ) => findIndex(value, (o) => o.value.id === data.value.id) === index);
const target = {
name: `record.${this.props.relation.alias}`,
type: 'select',
value: filteredValue,
};
this.props.setRecordAttribute({ target });
// NOTE: keep this line if we rollback to the old container
// this.props.setRecordAttribute(this.props.relation.alias, filteredValue);
}
render() |
}
SelectMany.propTypes = {
record: PropTypes.oneOfType([
PropTypes.object,
PropTypes.bool,
]).isRequired,
relation: PropTypes.object.isRequired,
setRecordAttribute: PropTypes.func.isRequired,
};
export default SelectMany;
| {
const description = this.props.relation.description
? <p>{this.props.relation.description}</p>
: '';
const value = get(this.props.record, this.props.relation.alias);
// NOTE: keep this line if we rollback to the old container
// const value = this.props.record.get(this.props.relation.alias);
/* eslint-disable jsx-a11y/label-has-for */
return (
<div className={`form-group ${styles.selectMany}`}>
<label htmlFor={this.props.relation.alias}>{this.props.relation.alias}</label>
{description}
<Select.Async
onChange={this.handleChange}
loadOptions={this.getOptions}
id={this.props.relation.alias}
multi
value={isNull(value) || isUndefined(value) || value.size === 0 ? null : value.map(item => {
if (item) {
return {
value: get(item, 'value') || item,
label: get(item, 'label') || templateObject({ mainField: this.props.relation.displayedAttribute }, item).mainField || item.value.id,
};
}
})}
/>
</div>
);
/* eslint-disable jsx-a11y/label-has-for */
} | identifier_body |
index.js | /**
*
* SelectMany
*
*/
import React from 'react';
import Select from 'react-select';
import PropTypes from 'prop-types';
import 'react-select/dist/react-select.css';
import { isArray, isNull, isUndefined, get, findIndex } from 'lodash';
import request from 'utils/request';
import templateObject from 'utils/templateObject';
import styles from './styles.scss';
class SelectMany extends React.Component { // eslint-disable-line react/prefer-stateless-function
constructor(props) {
super(props);
this.state = {
isLoading: true,
};
}
getOptions = (query) => {
const params = {
limit: 20,
source: this.props.relation.plugin || 'content-manager',
};
// Set `query` parameter if necessary
if (query) {
params.query = query;
params.queryAttribute = this.props.relation.displayedAttribute;
}
// Request URL
const requestUrlSuffix = query && this.props.record.get(this.props.relation.alias) ? this.props.record.get(this.props.relation.alias) : '';
// NOTE: keep this line if we rollback to the old container
// const requestUrlSuffix = query && this.props.record.get(this.props.relation.alias).toJS() ? this.props.record.get(this.props.relation.alias).toJS() : '';
const requestUrl = `/content-manager/explorer/${this.props.relation.model || this.props.relation.collection}/${requestUrlSuffix}`;
// Call our request helper (see 'utils/request')
return request(requestUrl, {
method: 'GET',
params,
})
.then(response => {
const options = isArray(response) ?
response.map(item => ({
value: item,
label: templateObject({ mainField: this.props.relation.displayedAttribute }, item).mainField,
})) :
[{
value: response,
label: response[this.props.relation.displayedAttribute],
}];
return { options };
})
.catch(() => {
strapi.notification.error('content-manager.notification.error.relationship.fetch');
});
}
handleChange = (value) => {
const filteredValue = value.filter((data, index ) => findIndex(value, (o) => o.value.id === data.value.id) === index);
const target = {
name: `record.${this.props.relation.alias}`,
type: 'select',
value: filteredValue,
};
this.props.setRecordAttribute({ target });
// NOTE: keep this line if we rollback to the old container
// this.props.setRecordAttribute(this.props.relation.alias, filteredValue);
}
render() {
const description = this.props.relation.description
? <p>{this.props.relation.description}</p>
: '';
const value = get(this.props.record, this.props.relation.alias);
// NOTE: keep this line if we rollback to the old container
// const value = this.props.record.get(this.props.relation.alias);
/* eslint-disable jsx-a11y/label-has-for */
return (
<div className={`form-group ${styles.selectMany}`}>
<label htmlFor={this.props.relation.alias}>{this.props.relation.alias}</label>
{description}
<Select.Async
onChange={this.handleChange}
loadOptions={this.getOptions}
id={this.props.relation.alias}
multi
value={isNull(value) || isUndefined(value) || value.size === 0 ? null : value.map(item => {
if (item) {
return {
value: get(item, 'value') || item,
label: get(item, 'label') || templateObject({ mainField: this.props.relation.displayedAttribute }, item).mainField || item.value.id,
}; | </div>
);
/* eslint-disable jsx-a11y/label-has-for */
}
}
SelectMany.propTypes = {
record: PropTypes.oneOfType([
PropTypes.object,
PropTypes.bool,
]).isRequired,
relation: PropTypes.object.isRequired,
setRecordAttribute: PropTypes.func.isRequired,
};
export default SelectMany; | }
})}
/> | random_line_split |
generate.js | var fs = require('fs');
var path = require('path');
var md_parser = require('./md_parser');
var $ = require('./helper');
var rootDir = path.join(__dirname, '../') + path.sep;
var assetsDir = path.join(rootDir, 'assets') + path.sep;
var templateDir = path.join(rootDir, 'template') + path.sep;
//1. 只导出文件nodeppt generate file.md
//2. 导出文件+目录 nodeppt generate ./ --all -o publish
module.exports = function(filepath, outputDir, isAll) {
filepath = fs.realpathSync(filepath);
outputDir = outputDir ? $.getDirPath(outputDir) : $.getDirPath(path.join(process.cwd(), './publish'));
isAll = !!isAll;
if (isAll) {
//1.导出assets
$.copy(assetsDir, outputDir, function(filename, dir, subdir) {
if (!subdir || subdir === 'scss') {
//不复制scss
return false;
}
return true;
});
}
//2.导出复制filepath除根目录下img、css和js等到assets,遇见/*.md就解析
generate(filepath, outputDir);
console.log('生成结束!'.bold.green + require('path').relative('b:/', outputDir).yellow);
};
function parser(content, template) {
try {
var html = md_parser(content, null, null, null, {
generate: true
});
return html;
} catch (e) {
console.log('ERROR: '.bold.red + e.toString());
}
return false;
}
/**
* 生成
* @param {[type]} filepath [description]
* @param {[type]} outputDir [description]
* @return {[type]} [description]
*/
function generate(filepath, outputDir) {
var filename = '';
var templateMd = $.readFile(templateDir + 'markdown.ejs');
var templateList = $.readFile(templateDir + 'list.ejs');
if ($.isDir(filepath, true)) {
//遍历目录生成htm
var indexList = '';
$.copy(filepath, outputDir, function(filename, dir, subdir) {
if (!subdir && /\.(?:md|markdown)$/i.test(filename)) {
var content = $.readFile(path.join(filepath, filename));
var html = parser(content);
if (html) {
var title = html.match(/<title>(.*?)<\/title>/);
if (title[1]) {
title = title[1];
} else {
title = filename;
}
var url = filename.replace(/\.(?:md|markdown)$/i, '.htm');
indexList += '<li><a class="star" href="' + url + '" target="_blank">' + title + '</a> [<a href="' + url + '?_multiscreen=1" target="_blank" title="多窗口打开">多窗口</a>]</li>';
copyLinkToOutput(content, filepath, outputDir);
html = handlerHTML(html);
$.writeFile(path.join(outputDir, filename.replace(/\.(?:md|markdown)$/i, '.htm')), html);
} | //输出index文件
var packageJson = require(rootDir + 'package.json');
var data = {
version: packageJson.version,
site: packageJson.site,
date: Date.now(),
list: indexList,
dir: '/'
};
indexList = $.renderStr(templateList, data);
$.writeFile(path.join(outputDir, 'index.html'), indexList);
} else {
var content;
if ($.exists(filepath)) {
content = $.readFile(filepath);
} else {
return console.log('ERROR: '.bold.red + filepath + ' is not exists!');
}
filename = path.basename(filepath);
copyLinkToOutput(content, filepath, outputDir);
var html = parser(content);
if (html) {
html = handlerHTML(html);
$.writeFile(path.join(outputDir, filename.replace(/\.(?:md|markdown)$/i, '.htm')), html);
}
}
}
//处理绝对路径的url
function handlerHTML(html) {
html = html.replace(/([src|href])=["']\//gi, '$1="./')
.replace("loadJS('/js", "loadJS('./js").replace("dir: '/js/',", "dir: './js/',");
return html;
}
//处理页面相对url,到目标文件夹
function copyLinkToOutput(content, filepath, outputDir) {
//[inline模式](/assets/box-fe-road/img/inline-mode.png)
var files = [];
content.replace(/\[.+?\]\(\s?(.*?)\s?\)/g, function(i, file) {
files.push(file);
}).replace(/href=(['"])(.+?)\1/g, function(i, q, file) {
files.push(file);
});
//解析cover
var json = md_parser.parseCover(content.split(/\[slide.*\]/i)[0]);
if (json.files) {
files = files.concat(json.files.split(/\s?,\s?/));
}
files.filter(function(f) {
return !/^http[s]?:\/\//.test(f);
}).forEach(function(f) {
var topath = path.join(outputDir, f);
var realpath = path.join(path.dirname(filepath), f);
if ($.exists(realpath)) {
var data = fs.readFileSync(String(realpath));
$.writeFile(topath, data);
}
});
} |
return false;
}
return true;
}); | random_line_split |
generate.js | var fs = require('fs');
var path = require('path');
var md_parser = require('./md_parser');
var $ = require('./helper');
var rootDir = path.join(__dirname, '../') + path.sep;
var assetsDir = path.join(rootDir, 'assets') + path.sep;
var templateDir = path.join(rootDir, 'template') + path.sep;
//1. 只导出文件nodeppt generate file.md
//2. 导出文件+目录 nodeppt generate ./ --all -o publish
module.exports = function(filepath, outputDir, isAll) {
filepath = fs.realpathSync(filepath);
outputDir = outputDir ? $.getDirPath(outputDir) : $.getDirPath(path.join(process.cwd(), './publish'));
isAll = !!isAll;
if (isAll) {
//1.导出assets
$.copy(assetsDir, outputDir, function(filename, dir, subdir) {
if (!subdir || subdir === 'scss') {
//不复制scss
return false;
}
return true;
});
}
//2.导出复制filepath除根目录下img、css和js等到assets,遇见/*.md就解析
generate(filepath, outputDir);
console.log('生成结束!'.bold.green + require('path').relative('b:/', outputDir).yellow);
};
function parser(content, template) {
try {
var html = md_parser(content, null, null, null, {
generate: true
});
return html;
} catch (e) {
console.log('ERROR: '.bold.red + e.toString());
}
return false;
}
/**
* 生成
* @param {[type]} filepath [description]
* @param {[type]} outputDir [description]
* @return {[type]} [description]
*/
function generate(filepath, outputDir) {
var filename = '';
var templateMd = $.readFile(templateDir + 'markdown.ejs');
var templateList = $.readFile(templateDir + 'list.ejs');
if ($.isDir(filepath, true)) {
//遍历目录生成htm
var indexList = '';
$.copy(filepath, outputDir, function(filename, dir, subdir) {
if (!subdir && /\.(?:md|markdown)$/i.test(filename)) {
var content = $.readFile(path.join(filepath, filename));
var html = parser(content);
if (html) {
var title = html.match(/<title>(.*?)<\/title>/);
if (title[1]) {
title = title[1];
} else {
title = filename;
}
var url = filename.replace(/\.(?:md|markdown)$/i, '.htm');
indexList += '<li><a class="star" href="' + url + '" target="_blank">' + title + '</a> [<a href="' + url + '?_multiscreen=1" target="_blank" title="多窗口打开">多窗口</a>]</li>';
copyLinkToOutput(content, filepath, outputDir);
html = handlerHTML(html);
$.writeFile(path.join(outputDir, filename.replace(/\.(?:md|markdown)$/i, '.htm')), html);
}
return false;
}
return true;
});
//输出index文件
var packageJson = require(rootDir + 'package.json');
var data = {
version: packageJson.version,
site: packageJson.site,
date: Date.now(),
list: indexList,
dir: '/'
};
indexList = $.renderStr(templateList, data);
$.writeFile(path.join(outputDir, 'index.html'), indexList);
} else {
var content;
if ($.exists(filepath)) {
content = $.readFile(filepath);
} else {
return console.log('ERROR: '.bold.red + filepath + ' is not exists!');
}
filename = path.basename(filepath);
copyLinkToOutput(content, filepath, outputDir);
var html = parser(content);
if (html) {
html = handlerHTML(html);
$.writeFile(path.join(outputDir, filename.replace(/\.(?:md|markdown)$/i, '.htm')), html);
}
}
}
//处理绝对路径的url
function handlerHTML(html) {
html = html.replace(/([src|href])=["']\//gi, '$1="./')
.replace("loadJS('/js", "loadJS('./js").replace("dir: '/js/',", " | )
var files = [];
content.replace(/\[.+?\]\(\s?(.*?)\s?\)/g, function(i, file) {
files.push(file);
}).replace(/href=(['"])(.+?)\1/g, function(i, q, file) {
files.push(file);
});
//解析cover
var json = md_parser.parseCover(content.split(/\[slide.*\]/i)[0]);
if (json.files) {
files = files.concat(json.files.split(/\s?,\s?/));
}
files.filter(function(f) {
return !/^http[s]?:\/\//.test(f);
}).forEach(function(f) {
var topath = path.join(outputDir, f);
var realpath = path.join(path.dirname(filepath), f);
if ($.exists(realpath)) {
var data = fs.readFileSync(String(realpath));
$.writeFile(topath, data);
}
});
}
| dir: './js/',");
return html;
}
//处理页面相对url,到目标文件夹
function copyLinkToOutput(content, filepath, outputDir) {
//[inline模式](/assets/box-fe-road/img/inline-mode.png | identifier_body |
generate.js | var fs = require('fs');
var path = require('path');
var md_parser = require('./md_parser');
var $ = require('./helper');
var rootDir = path.join(__dirname, '../') + path.sep;
var assetsDir = path.join(rootDir, 'assets') + path.sep;
var templateDir = path.join(rootDir, 'template') + path.sep;
//1. 只导出文件nodeppt generate file.md
//2. 导出文件+目录 nodeppt generate ./ --all -o publish
module.exports = function(filepath, outputDir, isAll) {
filepath = fs.realpathSync(filepath);
outputDir = outputDir ? $.getDirPath(outputDir) : $.getDirPath(path.join(process.cwd(), './publish'));
isAll = !!isAll;
if (isAll) {
//1.导出assets
$.copy(assetsDir, outputDir, function(filename, dir, subdir) {
if (!subdir || subdir === 'scss') {
//不复制scss
return false;
}
return true;
});
}
//2.导出复制filepath除根目录下img、css和js等到assets,遇见/*.md就解析
generate(filepath, outputDir);
console.log('生成结束!'.bold.green + require('path').relative('b:/', outputDir).yellow);
};
function parser(content, template) {
try {
var html = md_parser(content, null, null, null, {
generate: true
});
return html;
} catch (e) {
console.log('ERROR: '.bold.red + e.toString());
}
return false;
}
/**
* 生成
* @param {[type]} filepath [description]
* @param {[type]} outputDir [description]
* @return {[type]} [description]
*/
function generate(filepath, outputDir) {
var filename = '';
var templateMd = $.readFile(templateDir + 'markdown.ejs');
var templateList = $.readFile(templateDir + 'list.ejs');
if ($.isDir(filepath, true)) {
//遍历目录生成htm
var indexList = '';
$.copy(filepath, outputDir, function(filename, dir, subdir) {
if (!subdir && /\.(?:md|markdown)$/i.test(filename)) {
var content = $.readFile(path.join(filepath, filename));
var html = parser(content);
if (html) {
var title = html.match(/<title>(.*?)<\/title>/);
if (title[1]) {
title = title[1];
} else {
| url = filename.replace(/\.(?:md|markdown)$/i, '.htm');
indexList += '<li><a class="star" href="' + url + '" target="_blank">' + title + '</a> [<a href="' + url + '?_multiscreen=1" target="_blank" title="多窗口打开">多窗口</a>]</li>';
copyLinkToOutput(content, filepath, outputDir);
html = handlerHTML(html);
$.writeFile(path.join(outputDir, filename.replace(/\.(?:md|markdown)$/i, '.htm')), html);
}
return false;
}
return true;
});
//输出index文件
var packageJson = require(rootDir + 'package.json');
var data = {
version: packageJson.version,
site: packageJson.site,
date: Date.now(),
list: indexList,
dir: '/'
};
indexList = $.renderStr(templateList, data);
$.writeFile(path.join(outputDir, 'index.html'), indexList);
} else {
var content;
if ($.exists(filepath)) {
content = $.readFile(filepath);
} else {
return console.log('ERROR: '.bold.red + filepath + ' is not exists!');
}
filename = path.basename(filepath);
copyLinkToOutput(content, filepath, outputDir);
var html = parser(content);
if (html) {
html = handlerHTML(html);
$.writeFile(path.join(outputDir, filename.replace(/\.(?:md|markdown)$/i, '.htm')), html);
}
}
}
//处理绝对路径的url
function handlerHTML(html) {
html = html.replace(/([src|href])=["']\//gi, '$1="./')
.replace("loadJS('/js", "loadJS('./js").replace("dir: '/js/',", "dir: './js/',");
return html;
}
//处理页面相对url,到目标文件夹
function copyLinkToOutput(content, filepath, outputDir) {
//[inline模式](/assets/box-fe-road/img/inline-mode.png)
var files = [];
content.replace(/\[.+?\]\(\s?(.*?)\s?\)/g, function(i, file) {
files.push(file);
}).replace(/href=(['"])(.+?)\1/g, function(i, q, file) {
files.push(file);
});
//解析cover
var json = md_parser.parseCover(content.split(/\[slide.*\]/i)[0]);
if (json.files) {
files = files.concat(json.files.split(/\s?,\s?/));
}
files.filter(function(f) {
return !/^http[s]?:\/\//.test(f);
}).forEach(function(f) {
var topath = path.join(outputDir, f);
var realpath = path.join(path.dirname(filepath), f);
if ($.exists(realpath)) {
var data = fs.readFileSync(String(realpath));
$.writeFile(topath, data);
}
});
}
| title = filename;
}
var | conditional_block |
generate.js | var fs = require('fs');
var path = require('path');
var md_parser = require('./md_parser');
var $ = require('./helper');
var rootDir = path.join(__dirname, '../') + path.sep;
var assetsDir = path.join(rootDir, 'assets') + path.sep;
var templateDir = path.join(rootDir, 'template') + path.sep;
//1. 只导出文件nodeppt generate file.md
//2. 导出文件+目录 nodeppt generate ./ --all -o publish
module.exports = function(filepath, outputDir, isAll) {
filepath = fs.realpathSync(filepath);
outputDir = outputDir ? $.getDirPath(outputDir) : $.getDirPath(path.join(process.cwd(), './publish'));
isAll = !!isAll;
if (isAll) {
//1.导出assets
$.copy(assetsDir, outputDir, function(filename, dir, subdir) {
if (!subdir || subdir === 'scss') {
//不复制scss
return false;
}
return true;
});
}
//2.导出复制filepath除根目录下img、css和js等到assets,遇见/*.md就解析
generate(filepath, outputDir);
console.log('生成结束!'.bold.green + require('path').relative('b:/', outputDir).yellow);
};
function parser(content, template) {
try {
var html = md_parser(content, null, null, null, {
generate: true
});
return html;
} catch (e) {
console.log('ERROR: '.bold.red + e.toString());
}
return false;
}
/**
* 生成
* @param {[type]} filepath [description]
* @param {[type]} outputDir [description]
* @return {[type]} [description]
*/
function generate(filepath, outputDir) {
var filename = '';
var templateMd = $.readFi | ateDir + 'markdown.ejs');
var templateList = $.readFile(templateDir + 'list.ejs');
if ($.isDir(filepath, true)) {
//遍历目录生成htm
var indexList = '';
$.copy(filepath, outputDir, function(filename, dir, subdir) {
if (!subdir && /\.(?:md|markdown)$/i.test(filename)) {
var content = $.readFile(path.join(filepath, filename));
var html = parser(content);
if (html) {
var title = html.match(/<title>(.*?)<\/title>/);
if (title[1]) {
title = title[1];
} else {
title = filename;
}
var url = filename.replace(/\.(?:md|markdown)$/i, '.htm');
indexList += '<li><a class="star" href="' + url + '" target="_blank">' + title + '</a> [<a href="' + url + '?_multiscreen=1" target="_blank" title="多窗口打开">多窗口</a>]</li>';
copyLinkToOutput(content, filepath, outputDir);
html = handlerHTML(html);
$.writeFile(path.join(outputDir, filename.replace(/\.(?:md|markdown)$/i, '.htm')), html);
}
return false;
}
return true;
});
//输出index文件
var packageJson = require(rootDir + 'package.json');
var data = {
version: packageJson.version,
site: packageJson.site,
date: Date.now(),
list: indexList,
dir: '/'
};
indexList = $.renderStr(templateList, data);
$.writeFile(path.join(outputDir, 'index.html'), indexList);
} else {
var content;
if ($.exists(filepath)) {
content = $.readFile(filepath);
} else {
return console.log('ERROR: '.bold.red + filepath + ' is not exists!');
}
filename = path.basename(filepath);
copyLinkToOutput(content, filepath, outputDir);
var html = parser(content);
if (html) {
html = handlerHTML(html);
$.writeFile(path.join(outputDir, filename.replace(/\.(?:md|markdown)$/i, '.htm')), html);
}
}
}
//处理绝对路径的url
function handlerHTML(html) {
html = html.replace(/([src|href])=["']\//gi, '$1="./')
.replace("loadJS('/js", "loadJS('./js").replace("dir: '/js/',", "dir: './js/',");
return html;
}
//处理页面相对url,到目标文件夹
function copyLinkToOutput(content, filepath, outputDir) {
//[inline模式](/assets/box-fe-road/img/inline-mode.png)
var files = [];
content.replace(/\[.+?\]\(\s?(.*?)\s?\)/g, function(i, file) {
files.push(file);
}).replace(/href=(['"])(.+?)\1/g, function(i, q, file) {
files.push(file);
});
//解析cover
var json = md_parser.parseCover(content.split(/\[slide.*\]/i)[0]);
if (json.files) {
files = files.concat(json.files.split(/\s?,\s?/));
}
files.filter(function(f) {
return !/^http[s]?:\/\//.test(f);
}).forEach(function(f) {
var topath = path.join(outputDir, f);
var realpath = path.join(path.dirname(filepath), f);
if ($.exists(realpath)) {
var data = fs.readFileSync(String(realpath));
$.writeFile(topath, data);
}
});
}
| le(templ | identifier_name |
SimpleLinearReg.py | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 18 09:23:01 2017
@author: zhouhang
"""
import numpy as np
from matplotlib import pyplot as plt | X = np.arange(-5.,9.,0.1)
print X
X=np.random.permutation(X)
print X
b=5.
y=0.5 * X ** 2.0 +3. * X + b + np.random.random(X.shape)* 10.
#plt.scatter(X,y)
#plt.show()
#
X_ = np.mat(X).T
X_ = np.hstack((np.square(X_) , X_))
X_ = np.hstack((X_, np.mat(np.ones(len(X))).T))
A=(X_.T*X_).I*X_.T * np.mat(y).T
y_ = X_ * A
plt.hold(True)
plt.plot(X,y,'r.',fillstyle='none')
plt.plot(X,y_,'bo',fillstyle='none')
plt.show() | random_line_split | |
mod.rs | mod eloop;
pub(crate) use self::eloop::EventLoop;
thread_local!(pub(crate) static CURRENT_LOOP: EventLoop = EventLoop::new().unwrap());
mod gate;
pub use self::gate::Gate;
mod timer;
pub use self::timer::{PeriodicTimer, Timer};
mod wheel;
use self::wheel::Wheel;
mod sleep;
pub use self::sleep::*;
mod timeout;
pub use self::timeout::*;
use futures::Future;
use task::Task;
pub fn run<F>(f: F) -> Result<F::Item, F::Error>
where
F: Future,
{
CURRENT_LOOP.with(|eloop| {
debug!("{} started", eloop);
let res = unsafe { eloop.as_mut() }.run(f);
debug!("{} stopped", eloop);
res
})
}
pub fn spawn(task: Task) | {
CURRENT_LOOP.with(|eloop| unsafe { eloop.as_mut() }.spawn(task))
} | identifier_body | |
mod.rs | mod eloop;
pub(crate) use self::eloop::EventLoop;
thread_local!(pub(crate) static CURRENT_LOOP: EventLoop = EventLoop::new().unwrap());
mod gate;
pub use self::gate::Gate;
mod timer;
pub use self::timer::{PeriodicTimer, Timer};
mod wheel;
use self::wheel::Wheel;
mod sleep;
pub use self::sleep::*;
mod timeout;
pub use self::timeout::*;
use futures::Future;
use task::Task;
pub fn run<F>(f: F) -> Result<F::Item, F::Error>
where
F: Future,
{
CURRENT_LOOP.with(|eloop| {
debug!("{} started", eloop);
let res = unsafe { eloop.as_mut() }.run(f);
debug!("{} stopped", eloop);
res
})
}
| pub fn spawn(task: Task) {
CURRENT_LOOP.with(|eloop| unsafe { eloop.as_mut() }.spawn(task))
} | random_line_split | |
mod.rs | mod eloop;
pub(crate) use self::eloop::EventLoop;
thread_local!(pub(crate) static CURRENT_LOOP: EventLoop = EventLoop::new().unwrap());
mod gate;
pub use self::gate::Gate;
mod timer;
pub use self::timer::{PeriodicTimer, Timer};
mod wheel;
use self::wheel::Wheel;
mod sleep;
pub use self::sleep::*;
mod timeout;
pub use self::timeout::*;
use futures::Future;
use task::Task;
pub fn run<F>(f: F) -> Result<F::Item, F::Error>
where
F: Future,
{
CURRENT_LOOP.with(|eloop| {
debug!("{} started", eloop);
let res = unsafe { eloop.as_mut() }.run(f);
debug!("{} stopped", eloop);
res
})
}
pub fn | (task: Task) {
CURRENT_LOOP.with(|eloop| unsafe { eloop.as_mut() }.spawn(task))
}
| spawn | identifier_name |
question.component.ts | import {Component, OnInit, Input} from '@angular/core';
import { Router } from '@angular/router';
import {Question} from "./question";
import {QuestionService} from "./question.service";
@Component({
templateUrl: '/component/question'
})
export class QuestionComponent implements OnInit {
question: Question;
saved: boolean;
// HACK: we use a dummy array to avoid ngFor looping each time we change our values,
// see this question: http://stackoverflow.com/q/40852107/6320039
dummyArray: Array<number>;
ngOnInit(): void {
this.question = new Question;
this.question.answers = new Array(2);
this.dummyArray = new Array(2);
}
constructor(private questionService: QuestionService) {}; | deleteAnswer(index: number): void {
if (this.question.answers.length > 2)
if (this.question.goodAnswer === index) this.question.goodAnswer = null;
else if (this.question.goodAnswer > index ) this.question.goodAnswer--;
this.question.answers.splice(index, 1);
this.dummyArray.pop();
}
addAnswer(): void {
if (this.question.answers.length < 4) {
this.question.answers.push(null);
this.dummyArray.push(null);
}
}
save(): Promise<Question> {
return this.questionService
.saveQuestion(this.question)
.then(question => {
this.saved = true;
this.question = new Question;
this.question.answers = new Array(2);
this.dummyArray = new Array(2);
return question;
})
.catch(() => this.saved = false);
}
} | random_line_split | |
question.component.ts | import {Component, OnInit, Input} from '@angular/core';
import { Router } from '@angular/router';
import {Question} from "./question";
import {QuestionService} from "./question.service";
@Component({
templateUrl: '/component/question'
})
export class QuestionComponent implements OnInit {
question: Question;
saved: boolean;
// HACK: we use a dummy array to avoid ngFor looping each time we change our values,
// see this question: http://stackoverflow.com/q/40852107/6320039
dummyArray: Array<number>;
ngOnInit(): void {
this.question = new Question;
this.question.answers = new Array(2);
this.dummyArray = new Array(2);
}
constructor(private questionService: QuestionService) {};
deleteAnswer(index: number): void {
if (this.question.answers.length > 2)
if (this.question.goodAnswer === index) this.question.goodAnswer = null;
else if (this.question.goodAnswer > index ) this.question.goodAnswer--;
this.question.answers.splice(index, 1);
this.dummyArray.pop();
}
addAnswer(): void {
if (this.question.answers.length < 4) {
this.question.answers.push(null);
this.dummyArray.push(null);
}
}
| (): Promise<Question> {
return this.questionService
.saveQuestion(this.question)
.then(question => {
this.saved = true;
this.question = new Question;
this.question.answers = new Array(2);
this.dummyArray = new Array(2);
return question;
})
.catch(() => this.saved = false);
}
}
| save | identifier_name |
question.component.ts | import {Component, OnInit, Input} from '@angular/core';
import { Router } from '@angular/router';
import {Question} from "./question";
import {QuestionService} from "./question.service";
@Component({
templateUrl: '/component/question'
})
export class QuestionComponent implements OnInit {
question: Question;
saved: boolean;
// HACK: we use a dummy array to avoid ngFor looping each time we change our values,
// see this question: http://stackoverflow.com/q/40852107/6320039
dummyArray: Array<number>;
ngOnInit(): void |
constructor(private questionService: QuestionService) {};
deleteAnswer(index: number): void {
if (this.question.answers.length > 2)
if (this.question.goodAnswer === index) this.question.goodAnswer = null;
else if (this.question.goodAnswer > index ) this.question.goodAnswer--;
this.question.answers.splice(index, 1);
this.dummyArray.pop();
}
addAnswer(): void {
if (this.question.answers.length < 4) {
this.question.answers.push(null);
this.dummyArray.push(null);
}
}
save(): Promise<Question> {
return this.questionService
.saveQuestion(this.question)
.then(question => {
this.saved = true;
this.question = new Question;
this.question.answers = new Array(2);
this.dummyArray = new Array(2);
return question;
})
.catch(() => this.saved = false);
}
}
| {
this.question = new Question;
this.question.answers = new Array(2);
this.dummyArray = new Array(2);
} | identifier_body |
queue.py | #!/usr/bin/env python
# -*- coding:UTF-8
__author__ = 'shenshijun'
import copy
class Queue(object):
"""
使用Python的list快速实现一个队列
"""
def __init__(self, *arg):
super(Queue, self).__init__()
self.__queue = list(copy.copy(arg))
self.__size = len(self.__queue)
def enter(self, value):
self.__size += 1
self.__queue.append(value)
def exit(self):
if self.__size <= 0:
return None
el | value = self.__queue[0]
self.__size -= 1
del self.__queue[0]
return value
def __len__(self):
return self.__size
def empty(self):
return self.__size <= 0
def __str__(self):
return "".join(["Queue(list=", str(self.__queue), ",size=", str(self.__size)])
| se:
| conditional_block |
queue.py | #!/usr/bin/env python
# -*- coding:UTF-8
__author__ = 'shenshijun'
import copy
class Queue(object):
"""
使用Python的list快速实现一个队列
"""
def __init__(self, *arg):
super(Queue, self).__init__()
self.__queue = list(copy.copy(arg))
self.__size = len(self.__queue)
def enter(self, value):
| self.__size += 1
self.__queue.append(value)
def exit(self):
if self.__size <= 0:
return None
else:
value = self.__queue[0]
self.__size -= 1
del self.__queue[0]
return value
def __len__(self):
return self.__size
def empty(self):
return self.__size <= 0
def __str__(self):
return "".join(["Queue(list=", str(self.__queue), ",size=", str(self.__size)])
| identifier_name | |
queue.py | #!/usr/bin/env python
# -*- coding:UTF-8
__author__ = 'shenshijun'
import copy
class Queue(object):
"""
使用Python的list快速实现一个队列
"""
def __init__(self, *arg):
super(Queue, self).__init__()
self.__queue = list(copy.copy(arg))
self.__size = len(self.__queue)
def enter(self, value):
self.__size += 1
self.__queue.append(value)
def exit(self):
if self.__size <= 0:
return None
else:
value = self.__queue[0]
self.__size -= 1
del self.__queue[0]
return value
def __len__(self):
return self.__size
def empty(self):
return self.__size <= | ):
return "".join(["Queue(list=", str(self.__queue), ",size=", str(self.__size)])
| 0
def __str__(self | identifier_body |
queue.py | #!/usr/bin/env python
# -*- coding:UTF-8
__author__ = 'shenshijun'
import copy
class Queue(object):
""" | def __init__(self, *arg):
super(Queue, self).__init__()
self.__queue = list(copy.copy(arg))
self.__size = len(self.__queue)
def enter(self, value):
self.__size += 1
self.__queue.append(value)
def exit(self):
if self.__size <= 0:
return None
else:
value = self.__queue[0]
self.__size -= 1
del self.__queue[0]
return value
def __len__(self):
return self.__size
def empty(self):
return self.__size <= 0
def __str__(self):
return "".join(["Queue(list=", str(self.__queue), ",size=", str(self.__size)]) | 使用Python的list快速实现一个队列
"""
| random_line_split |
sha2.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! This module implements only the Sha256 function since that is all that is needed for internal
//! use. This implementation is not intended for external use or for any use where security is
//! important.
#![allow(deprecated)] // to_be32
use std::iter::{range_step, repeat};
use std::num::Int;
use std::slice::bytes::{MutableByteVector, copy_memory};
use serialize::hex::ToHex;
/// Write a u32 into a vector, which must be 4 bytes long. The value is written in big-endian
/// format.
fn write_u32_be(dst: &mut[u8], input: u32) {
dst[0] = (input >> 24) as u8;
dst[1] = (input >> 16) as u8;
dst[2] = (input >> 8) as u8;
dst[3] = input as u8;
}
/// Read the value of a vector of bytes as a u32 value in big-endian format.
fn read_u32_be(input: &[u8]) -> u32 {
return
(input[0] as u32) << 24 |
(input[1] as u32) << 16 |
(input[2] as u32) << 8 |
(input[3] as u32);
}
/// Read a vector of bytes into a vector of u32s. The values are read in big-endian format.
fn read_u32v_be(dst: &mut[u32], input: &[u8]) {
assert!(dst.len() * 4 == input.len());
let mut pos = 0u;
for chunk in input.chunks(4) {
dst[pos] = read_u32_be(chunk);
pos += 1;
}
}
trait ToBits {
/// Convert the value in bytes to the number of bits, a tuple where the 1st item is the
/// high-order value and the 2nd item is the low order value.
fn to_bits(self) -> (Self, Self);
}
impl ToBits for u64 {
fn to_bits(self) -> (u64, u64) {
return (self >> 61, self << 3);
}
}
/// Adds the specified number of bytes to the bit count. panic!() if this would cause numeric
/// overflow.
fn add_bytes_to_bits<T: Int + ToBits>(bits: T, bytes: T) -> T {
let (new_high_bits, new_low_bits) = bytes.to_bits();
if new_high_bits > Int::zero() {
panic!("numeric overflow occurred.")
}
match bits.checked_add(new_low_bits) {
Some(x) => return x,
None => panic!("numeric overflow occurred.")
}
}
/// A FixedBuffer, likes its name implies, is a fixed size buffer. When the buffer becomes full, it
/// must be processed. The input() method takes care of processing and then clearing the buffer
/// automatically. However, other methods do not and require the caller to process the buffer. Any
/// method that modifies the buffer directory or provides the caller with bytes that can be modified
/// results in those bytes being marked as used by the buffer.
trait FixedBuffer {
/// Input a vector of bytes. If the buffer becomes full, process it with the provided
/// function and then clear the buffer.
fn input<F>(&mut self, input: &[u8], func: F) where
F: FnMut(&[u8]);
/// Reset the buffer.
fn reset(&mut self);
/// Zero the buffer up until the specified index. The buffer position currently must not be
/// greater than that index.
fn zero_until(&mut self, idx: uint);
/// Get a slice of the buffer of the specified size. There must be at least that many bytes
/// remaining in the buffer.
fn next<'s>(&'s mut self, len: uint) -> &'s mut [u8];
/// Get the current buffer. The buffer must already be full. This clears the buffer as well.
fn full_buffer<'s>(&'s mut self) -> &'s [u8];
/// Get the current position of the buffer.
fn position(&self) -> uint;
/// Get the number of bytes remaining in the buffer until it is full.
fn remaining(&self) -> uint;
/// Get the size of the buffer
fn size(&self) -> uint;
}
/// A FixedBuffer of 64 bytes useful for implementing Sha256 which has a 64 byte blocksize.
struct FixedBuffer64 {
buffer: [u8; 64],
buffer_idx: uint,
}
impl FixedBuffer64 {
/// Create a new FixedBuffer64
fn new() -> FixedBuffer64 {
return FixedBuffer64 {
buffer: [0u8; 64],
buffer_idx: 0
};
}
}
impl FixedBuffer for FixedBuffer64 {
fn input<F>(&mut self, input: &[u8], mut func: F) where
F: FnMut(&[u8]),
{
let mut i = 0;
let size = self.size();
// If there is already data in the buffer, copy as much as we can into it and process
// the data if the buffer becomes full.
if self.buffer_idx != 0 {
let buffer_remaining = size - self.buffer_idx;
if input.len() >= buffer_remaining {
copy_memory(
self.buffer.slice_mut(self.buffer_idx, size),
&input[..buffer_remaining]);
self.buffer_idx = 0;
func(&self.buffer);
i += buffer_remaining;
} else {
copy_memory(
self.buffer.slice_mut(self.buffer_idx, self.buffer_idx + input.len()),
input);
self.buffer_idx += input.len();
return;
}
}
// While we have at least a full buffer size chunk's worth of data, process that data
// without copying it into the buffer
while input.len() - i >= size {
func(&input[i..i + size]);
i += size;
}
// Copy any input data into the buffer. At this point in the method, the amount of
// data left in the input vector will be less than the buffer size and the buffer will
// be empty.
let input_remaining = input.len() - i;
copy_memory(
self.buffer.slice_to_mut(input_remaining),
&input[i..]);
self.buffer_idx += input_remaining;
}
fn reset(&mut self) {
self.buffer_idx = 0;
}
fn zero_until(&mut self, idx: uint) {
assert!(idx >= self.buffer_idx);
self.buffer.slice_mut(self.buffer_idx, idx).set_memory(0);
self.buffer_idx = idx;
}
fn next<'s>(&'s mut self, len: uint) -> &'s mut [u8] {
self.buffer_idx += len;
return self.buffer.slice_mut(self.buffer_idx - len, self.buffer_idx);
}
fn full_buffer<'s>(&'s mut self) -> &'s [u8] {
assert!(self.buffer_idx == 64);
self.buffer_idx = 0;
return &self.buffer[..64];
}
fn position(&self) -> uint { self.buffer_idx }
fn remaining(&self) -> uint { 64 - self.buffer_idx }
fn size(&self) -> uint { 64 }
}
/// The StandardPadding trait adds a method useful for Sha256 to a FixedBuffer struct.
trait StandardPadding {
/// Add padding to the buffer. The buffer must not be full when this method is called and is
/// guaranteed to have exactly rem remaining bytes when it returns. If there are not at least
/// rem bytes available, the buffer will be zero padded, processed, cleared, and then filled
/// with zeros again until only rem bytes are remaining.
fn standard_padding<F>(&mut self, rem: uint, func: F) where F: FnMut(&[u8]);
}
impl <T: FixedBuffer> StandardPadding for T {
fn standard_padding<F>(&mut self, rem: uint, mut func: F) where F: FnMut(&[u8]) {
let size = self.size();
self.next(1)[0] = 128;
if self.remaining() < rem {
self.zero_until(size);
func(self.full_buffer());
}
self.zero_until(size - rem);
}
}
/// The Digest trait specifies an interface common to digest functions, such as SHA-1 and the SHA-2
/// family of digest functions.
pub trait Digest {
/// Provide message data.
///
/// # Arguments
///
/// * input - A vector of message data
fn input(&mut self, input: &[u8]);
/// Retrieve the digest result. This method may be called multiple times.
///
/// # Arguments
///
/// * out - the vector to hold the result. Must be large enough to contain output_bits().
fn result(&mut self, out: &mut [u8]);
/// Reset the digest. This method must be called after result() and before supplying more
/// data.
fn reset(&mut self);
/// Get the output size in bits.
fn output_bits(&self) -> uint;
/// Convenience function that feeds a string into a digest.
///
/// # Arguments
///
/// * `input` The string to feed into the digest
fn input_str(&mut self, input: &str) {
self.input(input.as_bytes());
}
/// Convenience function that retrieves the result of a digest as a
/// newly allocated vec of bytes.
fn result_bytes(&mut self) -> Vec<u8> {
let mut buf: Vec<u8> = repeat(0u8).take((self.output_bits()+7)/8).collect();
self.result(buf.as_mut_slice());
buf
}
/// Convenience function that retrieves the result of a digest as a
/// String in hexadecimal format.
fn result_str(&mut self) -> String {
self.result_bytes().to_hex().to_string()
}
}
// A structure that represents that state of a digest computation for the SHA-2 512 family of digest
// functions
struct Engine256State {
h0: u32,
h1: u32,
h2: u32,
h3: u32,
h4: u32,
h5: u32,
h6: u32,
h7: u32,
}
impl Engine256State {
fn new(h: &[u32; 8]) -> Engine256State {
return Engine256State {
h0: h[0],
h1: h[1],
h2: h[2],
h3: h[3],
h4: h[4],
h5: h[5],
h6: h[6],
h7: h[7]
};
}
fn reset(&mut self, h: &[u32; 8]) {
self.h0 = h[0];
self.h1 = h[1];
self.h2 = h[2];
self.h3 = h[3];
self.h4 = h[4];
self.h5 = h[5];
self.h6 = h[6];
self.h7 = h[7];
}
fn process_block(&mut self, data: &[u8]) {
fn ch(x: u32, y: u32, z: u32) -> u32 {
((x & y) ^ ((!x) & z))
}
fn maj(x: u32, y: u32, z: u32) -> u32 {
((x & y) ^ (x & z) ^ (y & z))
}
fn sum0(x: u32) -> u32 {
((x >> 2) | (x << 30)) ^ ((x >> 13) | (x << 19)) ^ ((x >> 22) | (x << 10))
}
fn sum1(x: u32) -> u32 {
((x >> 6) | (x << 26)) ^ ((x >> 11) | (x << 21)) ^ ((x >> 25) | (x << 7))
}
fn sigma0(x: u32) -> u32 {
((x >> 7) | (x << 25)) ^ ((x >> 18) | (x << 14)) ^ (x >> 3)
}
fn sigma1(x: u32) -> u32 {
((x >> 17) | (x << 15)) ^ ((x >> 19) | (x << 13)) ^ (x >> 10)
}
let mut a = self.h0;
let mut b = self.h1;
let mut c = self.h2;
let mut d = self.h3;
let mut e = self.h4;
let mut f = self.h5;
let mut g = self.h6;
let mut h = self.h7;
let mut w = [0u32; 64];
// Sha-512 and Sha-256 use basically the same calculations which are implemented
// by these macros. Inlining the calculations seems to result in better generated code.
macro_rules! schedule_round { ($t:expr) => (
w[$t] = sigma1(w[$t - 2]) + w[$t - 7] + sigma0(w[$t - 15]) + w[$t - 16];
)
}
macro_rules! sha2_round {
($A:ident, $B:ident, $C:ident, $D:ident,
$E:ident, $F:ident, $G:ident, $H:ident, $K:ident, $t:expr) => (
{
$H += sum1($E) + ch($E, $F, $G) + $K[$t] + w[$t];
$D += $H;
$H += sum0($A) + maj($A, $B, $C);
}
)
}
read_u32v_be(w.slice_mut(0, 16), data);
// Putting the message schedule inside the same loop as the round calculations allows for
// the compiler to generate better code.
for t in range_step(0u, 48, 8) {
schedule_round!(t + 16);
schedule_round!(t + 17);
schedule_round!(t + 18);
schedule_round!(t + 19);
schedule_round!(t + 20);
schedule_round!(t + 21);
schedule_round!(t + 22);
schedule_round!(t + 23);
sha2_round!(a, b, c, d, e, f, g, h, K32, t);
sha2_round!(h, a, b, c, d, e, f, g, K32, t + 1);
sha2_round!(g, h, a, b, c, d, e, f, K32, t + 2);
sha2_round!(f, g, h, a, b, c, d, e, K32, t + 3);
sha2_round!(e, f, g, h, a, b, c, d, K32, t + 4);
sha2_round!(d, e, f, g, h, a, b, c, K32, t + 5);
sha2_round!(c, d, e, f, g, h, a, b, K32, t + 6);
sha2_round!(b, c, d, e, f, g, h, a, K32, t + 7);
}
for t in range_step(48u, 64, 8) {
sha2_round!(a, b, c, d, e, f, g, h, K32, t);
sha2_round!(h, a, b, c, d, e, f, g, K32, t + 1);
sha2_round!(g, h, a, b, c, d, e, f, K32, t + 2);
sha2_round!(f, g, h, a, b, c, d, e, K32, t + 3);
sha2_round!(e, f, g, h, a, b, c, d, K32, t + 4);
sha2_round!(d, e, f, g, h, a, b, c, K32, t + 5);
sha2_round!(c, d, e, f, g, h, a, b, K32, t + 6);
sha2_round!(b, c, d, e, f, g, h, a, K32, t + 7);
}
self.h0 += a;
self.h1 += b;
self.h2 += c;
self.h3 += d;
self.h4 += e;
self.h5 += f;
self.h6 += g;
self.h7 += h;
}
}
static K32: [u32; 64] = [
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
];
// A structure that keeps track of the state of the Sha-256 operation and contains the logic
// necessary to perform the final calculations.
struct Engine256 {
length_bits: u64,
buffer: FixedBuffer64,
state: Engine256State,
finished: bool,
}
impl Engine256 {
fn new(h: &[u32; 8]) -> Engine256 {
return Engine256 {
length_bits: 0,
buffer: FixedBuffer64::new(),
state: Engine256State::new(h),
finished: false
}
}
fn reset(&mut self, h: &[u32; 8]) {
self.length_bits = 0;
self.buffer.reset();
self.state.reset(h);
self.finished = false;
}
fn input(&mut self, input: &[u8]) {
assert!(!self.finished);
// Assumes that input.len() can be converted to u64 without overflow
self.length_bits = add_bytes_to_bits(self.length_bits, input.len() as u64);
let self_state = &mut self.state;
self.buffer.input(input, |input: &[u8]| { self_state.process_block(input) });
}
fn finish(&mut self) {
if self.finished {
return;
}
let self_state = &mut self.state;
self.buffer.standard_padding(8, |input: &[u8]| { self_state.process_block(input) });
write_u32_be(self.buffer.next(4), (self.length_bits >> 32) as u32 );
write_u32_be(self.buffer.next(4), self.length_bits as u32);
self_state.process_block(self.buffer.full_buffer());
self.finished = true;
}
}
/// The SHA-256 hash algorithm
pub struct Sha256 {
engine: Engine256
}
impl Sha256 {
/// Construct a new instance of a SHA-256 digest.
pub fn new() -> Sha256 {
Sha256 {
engine: Engine256::new(&H256)
}
}
}
impl Digest for Sha256 {
fn input(&mut self, d: &[u8]) {
self.engine.input(d);
}
fn result(&mut self, out: &mut [u8]) {
self.engine.finish();
write_u32_be(out.slice_mut(0, 4), self.engine.state.h0);
write_u32_be(out.slice_mut(4, 8), self.engine.state.h1);
write_u32_be(out.slice_mut(8, 12), self.engine.state.h2);
write_u32_be(out.slice_mut(12, 16), self.engine.state.h3);
write_u32_be(out.slice_mut(16, 20), self.engine.state.h4);
write_u32_be(out.slice_mut(20, 24), self.engine.state.h5);
write_u32_be(out.slice_mut(24, 28), self.engine.state.h6);
write_u32_be(out.slice_mut(28, 32), self.engine.state.h7);
}
fn reset(&mut self) {
self.engine.reset(&H256);
}
fn output_bits(&self) -> uint { 256 }
}
static H256: [u32; 8] = [
0x6a09e667,
0xbb67ae85,
0x3c6ef372,
0xa54ff53a,
0x510e527f,
0x9b05688c,
0x1f83d9ab,
0x5be0cd19
];
#[cfg(test)]
mod tests {
extern crate rand;
use self::rand::Rng;
use self::rand::isaac::IsaacRng;
use serialize::hex::FromHex;
use std::iter::repeat;
use std::num::Int;
use super::{Digest, Sha256, FixedBuffer};
// A normal addition - no overflow occurs
#[test]
fn test_add_bytes_to_bits_ok() {
assert!(super::add_bytes_to_bits::<u64>(100, 10) == 180);
}
// A simple failure case - adding 1 to the max value
#[test]
#[should_fail]
fn test_add_bytes_to_bits_overflow() {
super::add_bytes_to_bits::<u64>(Int::max_value(), 1);
}
struct Test {
input: String,
output_str: String,
}
fn test_hash<D: Digest>(sh: &mut D, tests: &[Test]) {
// Test that it works when accepting the message all at once
for t in tests.iter() {
sh.reset();
sh.input_str(t.input.as_slice());
let out_str = sh.result_str();
assert!(out_str == t.output_str);
}
// Test that it works when accepting the message in pieces
for t in tests.iter() {
sh.reset();
let len = t.input.len();
let mut left = len;
while left > 0u {
let take = (left + 1u) / 2u;
sh.input_str(t.input
.slice(len - left, take + len - left));
left = left - take;
}
let out_str = sh.result_str();
assert!(out_str == t.output_str);
}
}
#[test]
fn test_sha256() {
// Examples from wikipedia
let wikipedia_tests = vec!(
Test {
input: "".to_string(),
output_str: "e3b0c44298fc1c149afb\
f4c8996fb92427ae41e4649b934ca495991b7852b855".to_string()
},
Test {
input: "The quick brown fox jumps over the lazy \
dog".to_string(),
output_str: "d7a8fbb307d7809469ca\
9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592".to_string()
},
Test {
input: "The quick brown fox jumps over the lazy \
dog.".to_string(), |
let mut sh = box Sha256::new();
test_hash(&mut *sh, tests.as_slice());
}
/// Feed 1,000,000 'a's into the digest with varying input sizes and check that the result is
/// correct.
fn test_digest_1million_random<D: Digest>(digest: &mut D, blocksize: uint, expected: &str) {
let total_size = 1000000;
let buffer: Vec<u8> = repeat('a' as u8).take(blocksize * 2).collect();
let mut rng = IsaacRng::new_unseeded();
let mut count = 0;
digest.reset();
while count < total_size {
let next: uint = rng.gen_range(0, 2 * blocksize + 1);
let remaining = total_size - count;
let size = if next > remaining { remaining } else { next };
digest.input(buffer.slice_to(size));
count += size;
}
let result_str = digest.result_str();
let result_bytes = digest.result_bytes();
assert_eq!(expected, result_str.as_slice());
let expected_vec: Vec<u8> = expected.from_hex()
.unwrap()
.into_iter()
.collect();
assert_eq!(expected_vec, result_bytes);
}
#[test]
fn test_1million_random_sha256() {
let mut sh = Sha256::new();
test_digest_1million_random(
&mut sh,
64,
"cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0");
}
}
#[cfg(test)]
mod bench {
extern crate test;
use self::test::Bencher;
use super::{Sha256, FixedBuffer, Digest};
#[bench]
pub fn sha256_10(b: &mut Bencher) {
let mut sh = Sha256::new();
let bytes = [1u8; 10];
b.iter(|| {
sh.input(&bytes);
});
b.bytes = bytes.len() as u64;
}
#[bench]
pub fn sha256_1k(b: &mut Bencher) {
let mut sh = Sha256::new();
let bytes = [1u8; 1024];
b.iter(|| {
sh.input(&bytes);
});
b.bytes = bytes.len() as u64;
}
#[bench]
pub fn sha256_64k(b: &mut Bencher) {
let mut sh = Sha256::new();
let bytes = [1u8; 65536];
b.iter(|| {
sh.input(&bytes);
});
b.bytes = bytes.len() as u64;
}
} | output_str: "ef537f25c895bfa78252\
6529a9b63d97aa631564d5d789c2b765448c8635fb6c".to_string()
});
let tests = wikipedia_tests; | random_line_split |
sha2.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! This module implements only the Sha256 function since that is all that is needed for internal
//! use. This implementation is not intended for external use or for any use where security is
//! important.
#![allow(deprecated)] // to_be32
use std::iter::{range_step, repeat};
use std::num::Int;
use std::slice::bytes::{MutableByteVector, copy_memory};
use serialize::hex::ToHex;
/// Write a u32 into a vector, which must be 4 bytes long. The value is written in big-endian
/// format.
fn write_u32_be(dst: &mut[u8], input: u32) {
dst[0] = (input >> 24) as u8;
dst[1] = (input >> 16) as u8;
dst[2] = (input >> 8) as u8;
dst[3] = input as u8;
}
/// Read the value of a vector of bytes as a u32 value in big-endian format.
fn read_u32_be(input: &[u8]) -> u32 {
return
(input[0] as u32) << 24 |
(input[1] as u32) << 16 |
(input[2] as u32) << 8 |
(input[3] as u32);
}
/// Read a vector of bytes into a vector of u32s. The values are read in big-endian format.
fn read_u32v_be(dst: &mut[u32], input: &[u8]) {
assert!(dst.len() * 4 == input.len());
let mut pos = 0u;
for chunk in input.chunks(4) {
dst[pos] = read_u32_be(chunk);
pos += 1;
}
}
trait ToBits {
/// Convert the value in bytes to the number of bits, a tuple where the 1st item is the
/// high-order value and the 2nd item is the low order value.
fn to_bits(self) -> (Self, Self);
}
impl ToBits for u64 {
fn to_bits(self) -> (u64, u64) {
return (self >> 61, self << 3);
}
}
/// Adds the specified number of bytes to the bit count. panic!() if this would cause numeric
/// overflow.
fn add_bytes_to_bits<T: Int + ToBits>(bits: T, bytes: T) -> T {
let (new_high_bits, new_low_bits) = bytes.to_bits();
if new_high_bits > Int::zero() {
panic!("numeric overflow occurred.")
}
match bits.checked_add(new_low_bits) {
Some(x) => return x,
None => panic!("numeric overflow occurred.")
}
}
/// A FixedBuffer, likes its name implies, is a fixed size buffer. When the buffer becomes full, it
/// must be processed. The input() method takes care of processing and then clearing the buffer
/// automatically. However, other methods do not and require the caller to process the buffer. Any
/// method that modifies the buffer directory or provides the caller with bytes that can be modified
/// results in those bytes being marked as used by the buffer.
trait FixedBuffer {
/// Input a vector of bytes. If the buffer becomes full, process it with the provided
/// function and then clear the buffer.
fn input<F>(&mut self, input: &[u8], func: F) where
F: FnMut(&[u8]);
/// Reset the buffer.
fn reset(&mut self);
/// Zero the buffer up until the specified index. The buffer position currently must not be
/// greater than that index.
fn zero_until(&mut self, idx: uint);
/// Get a slice of the buffer of the specified size. There must be at least that many bytes
/// remaining in the buffer.
fn next<'s>(&'s mut self, len: uint) -> &'s mut [u8];
/// Get the current buffer. The buffer must already be full. This clears the buffer as well.
fn full_buffer<'s>(&'s mut self) -> &'s [u8];
/// Get the current position of the buffer.
fn position(&self) -> uint;
/// Get the number of bytes remaining in the buffer until it is full.
fn remaining(&self) -> uint;
/// Get the size of the buffer
fn size(&self) -> uint;
}
/// A FixedBuffer of 64 bytes useful for implementing Sha256 which has a 64 byte blocksize.
struct FixedBuffer64 {
buffer: [u8; 64],
buffer_idx: uint,
}
impl FixedBuffer64 {
/// Create a new FixedBuffer64
fn new() -> FixedBuffer64 {
return FixedBuffer64 {
buffer: [0u8; 64],
buffer_idx: 0
};
}
}
impl FixedBuffer for FixedBuffer64 {
fn input<F>(&mut self, input: &[u8], mut func: F) where
F: FnMut(&[u8]),
{
let mut i = 0;
let size = self.size();
// If there is already data in the buffer, copy as much as we can into it and process
// the data if the buffer becomes full.
if self.buffer_idx != 0 {
let buffer_remaining = size - self.buffer_idx;
if input.len() >= buffer_remaining {
copy_memory(
self.buffer.slice_mut(self.buffer_idx, size),
&input[..buffer_remaining]);
self.buffer_idx = 0;
func(&self.buffer);
i += buffer_remaining;
} else {
copy_memory(
self.buffer.slice_mut(self.buffer_idx, self.buffer_idx + input.len()),
input);
self.buffer_idx += input.len();
return;
}
}
// While we have at least a full buffer size chunk's worth of data, process that data
// without copying it into the buffer
while input.len() - i >= size {
func(&input[i..i + size]);
i += size;
}
// Copy any input data into the buffer. At this point in the method, the amount of
// data left in the input vector will be less than the buffer size and the buffer will
// be empty.
let input_remaining = input.len() - i;
copy_memory(
self.buffer.slice_to_mut(input_remaining),
&input[i..]);
self.buffer_idx += input_remaining;
}
fn reset(&mut self) {
self.buffer_idx = 0;
}
fn zero_until(&mut self, idx: uint) {
assert!(idx >= self.buffer_idx);
self.buffer.slice_mut(self.buffer_idx, idx).set_memory(0);
self.buffer_idx = idx;
}
fn next<'s>(&'s mut self, len: uint) -> &'s mut [u8] {
self.buffer_idx += len;
return self.buffer.slice_mut(self.buffer_idx - len, self.buffer_idx);
}
fn full_buffer<'s>(&'s mut self) -> &'s [u8] {
assert!(self.buffer_idx == 64);
self.buffer_idx = 0;
return &self.buffer[..64];
}
fn position(&self) -> uint { self.buffer_idx }
fn remaining(&self) -> uint { 64 - self.buffer_idx }
fn size(&self) -> uint { 64 }
}
/// The StandardPadding trait adds a method useful for Sha256 to a FixedBuffer struct.
trait StandardPadding {
/// Add padding to the buffer. The buffer must not be full when this method is called and is
/// guaranteed to have exactly rem remaining bytes when it returns. If there are not at least
/// rem bytes available, the buffer will be zero padded, processed, cleared, and then filled
/// with zeros again until only rem bytes are remaining.
fn standard_padding<F>(&mut self, rem: uint, func: F) where F: FnMut(&[u8]);
}
impl <T: FixedBuffer> StandardPadding for T {
fn standard_padding<F>(&mut self, rem: uint, mut func: F) where F: FnMut(&[u8]) {
let size = self.size();
self.next(1)[0] = 128;
if self.remaining() < rem {
self.zero_until(size);
func(self.full_buffer());
}
self.zero_until(size - rem);
}
}
/// The Digest trait specifies an interface common to digest functions, such as SHA-1 and the SHA-2
/// family of digest functions.
pub trait Digest {
/// Provide message data.
///
/// # Arguments
///
/// * input - A vector of message data
fn input(&mut self, input: &[u8]);
/// Retrieve the digest result. This method may be called multiple times.
///
/// # Arguments
///
/// * out - the vector to hold the result. Must be large enough to contain output_bits().
fn result(&mut self, out: &mut [u8]);
/// Reset the digest. This method must be called after result() and before supplying more
/// data.
fn reset(&mut self);
/// Get the output size in bits.
fn output_bits(&self) -> uint;
/// Convenience function that feeds a string into a digest.
///
/// # Arguments
///
/// * `input` The string to feed into the digest
fn input_str(&mut self, input: &str) {
self.input(input.as_bytes());
}
/// Convenience function that retrieves the result of a digest as a
/// newly allocated vec of bytes.
fn result_bytes(&mut self) -> Vec<u8> {
let mut buf: Vec<u8> = repeat(0u8).take((self.output_bits()+7)/8).collect();
self.result(buf.as_mut_slice());
buf
}
/// Convenience function that retrieves the result of a digest as a
/// String in hexadecimal format.
fn result_str(&mut self) -> String {
self.result_bytes().to_hex().to_string()
}
}
// A structure that represents that state of a digest computation for the SHA-2 512 family of digest
// functions
struct Engine256State {
h0: u32,
h1: u32,
h2: u32,
h3: u32,
h4: u32,
h5: u32,
h6: u32,
h7: u32,
}
impl Engine256State {
fn new(h: &[u32; 8]) -> Engine256State {
return Engine256State {
h0: h[0],
h1: h[1],
h2: h[2],
h3: h[3],
h4: h[4],
h5: h[5],
h6: h[6],
h7: h[7]
};
}
fn reset(&mut self, h: &[u32; 8]) {
self.h0 = h[0];
self.h1 = h[1];
self.h2 = h[2];
self.h3 = h[3];
self.h4 = h[4];
self.h5 = h[5];
self.h6 = h[6];
self.h7 = h[7];
}
fn | (&mut self, data: &[u8]) {
fn ch(x: u32, y: u32, z: u32) -> u32 {
((x & y) ^ ((!x) & z))
}
fn maj(x: u32, y: u32, z: u32) -> u32 {
((x & y) ^ (x & z) ^ (y & z))
}
fn sum0(x: u32) -> u32 {
((x >> 2) | (x << 30)) ^ ((x >> 13) | (x << 19)) ^ ((x >> 22) | (x << 10))
}
fn sum1(x: u32) -> u32 {
((x >> 6) | (x << 26)) ^ ((x >> 11) | (x << 21)) ^ ((x >> 25) | (x << 7))
}
fn sigma0(x: u32) -> u32 {
((x >> 7) | (x << 25)) ^ ((x >> 18) | (x << 14)) ^ (x >> 3)
}
fn sigma1(x: u32) -> u32 {
((x >> 17) | (x << 15)) ^ ((x >> 19) | (x << 13)) ^ (x >> 10)
}
let mut a = self.h0;
let mut b = self.h1;
let mut c = self.h2;
let mut d = self.h3;
let mut e = self.h4;
let mut f = self.h5;
let mut g = self.h6;
let mut h = self.h7;
let mut w = [0u32; 64];
// Sha-512 and Sha-256 use basically the same calculations which are implemented
// by these macros. Inlining the calculations seems to result in better generated code.
macro_rules! schedule_round { ($t:expr) => (
w[$t] = sigma1(w[$t - 2]) + w[$t - 7] + sigma0(w[$t - 15]) + w[$t - 16];
)
}
macro_rules! sha2_round {
($A:ident, $B:ident, $C:ident, $D:ident,
$E:ident, $F:ident, $G:ident, $H:ident, $K:ident, $t:expr) => (
{
$H += sum1($E) + ch($E, $F, $G) + $K[$t] + w[$t];
$D += $H;
$H += sum0($A) + maj($A, $B, $C);
}
)
}
read_u32v_be(w.slice_mut(0, 16), data);
// Putting the message schedule inside the same loop as the round calculations allows for
// the compiler to generate better code.
for t in range_step(0u, 48, 8) {
schedule_round!(t + 16);
schedule_round!(t + 17);
schedule_round!(t + 18);
schedule_round!(t + 19);
schedule_round!(t + 20);
schedule_round!(t + 21);
schedule_round!(t + 22);
schedule_round!(t + 23);
sha2_round!(a, b, c, d, e, f, g, h, K32, t);
sha2_round!(h, a, b, c, d, e, f, g, K32, t + 1);
sha2_round!(g, h, a, b, c, d, e, f, K32, t + 2);
sha2_round!(f, g, h, a, b, c, d, e, K32, t + 3);
sha2_round!(e, f, g, h, a, b, c, d, K32, t + 4);
sha2_round!(d, e, f, g, h, a, b, c, K32, t + 5);
sha2_round!(c, d, e, f, g, h, a, b, K32, t + 6);
sha2_round!(b, c, d, e, f, g, h, a, K32, t + 7);
}
for t in range_step(48u, 64, 8) {
sha2_round!(a, b, c, d, e, f, g, h, K32, t);
sha2_round!(h, a, b, c, d, e, f, g, K32, t + 1);
sha2_round!(g, h, a, b, c, d, e, f, K32, t + 2);
sha2_round!(f, g, h, a, b, c, d, e, K32, t + 3);
sha2_round!(e, f, g, h, a, b, c, d, K32, t + 4);
sha2_round!(d, e, f, g, h, a, b, c, K32, t + 5);
sha2_round!(c, d, e, f, g, h, a, b, K32, t + 6);
sha2_round!(b, c, d, e, f, g, h, a, K32, t + 7);
}
self.h0 += a;
self.h1 += b;
self.h2 += c;
self.h3 += d;
self.h4 += e;
self.h5 += f;
self.h6 += g;
self.h7 += h;
}
}
static K32: [u32; 64] = [
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
];
// A structure that keeps track of the state of the Sha-256 operation and contains the logic
// necessary to perform the final calculations.
struct Engine256 {
length_bits: u64,
buffer: FixedBuffer64,
state: Engine256State,
finished: bool,
}
impl Engine256 {
fn new(h: &[u32; 8]) -> Engine256 {
return Engine256 {
length_bits: 0,
buffer: FixedBuffer64::new(),
state: Engine256State::new(h),
finished: false
}
}
fn reset(&mut self, h: &[u32; 8]) {
self.length_bits = 0;
self.buffer.reset();
self.state.reset(h);
self.finished = false;
}
fn input(&mut self, input: &[u8]) {
assert!(!self.finished);
// Assumes that input.len() can be converted to u64 without overflow
self.length_bits = add_bytes_to_bits(self.length_bits, input.len() as u64);
let self_state = &mut self.state;
self.buffer.input(input, |input: &[u8]| { self_state.process_block(input) });
}
fn finish(&mut self) {
if self.finished {
return;
}
let self_state = &mut self.state;
self.buffer.standard_padding(8, |input: &[u8]| { self_state.process_block(input) });
write_u32_be(self.buffer.next(4), (self.length_bits >> 32) as u32 );
write_u32_be(self.buffer.next(4), self.length_bits as u32);
self_state.process_block(self.buffer.full_buffer());
self.finished = true;
}
}
/// The SHA-256 hash algorithm
pub struct Sha256 {
engine: Engine256
}
impl Sha256 {
/// Construct a new instance of a SHA-256 digest.
pub fn new() -> Sha256 {
Sha256 {
engine: Engine256::new(&H256)
}
}
}
impl Digest for Sha256 {
fn input(&mut self, d: &[u8]) {
self.engine.input(d);
}
fn result(&mut self, out: &mut [u8]) {
self.engine.finish();
write_u32_be(out.slice_mut(0, 4), self.engine.state.h0);
write_u32_be(out.slice_mut(4, 8), self.engine.state.h1);
write_u32_be(out.slice_mut(8, 12), self.engine.state.h2);
write_u32_be(out.slice_mut(12, 16), self.engine.state.h3);
write_u32_be(out.slice_mut(16, 20), self.engine.state.h4);
write_u32_be(out.slice_mut(20, 24), self.engine.state.h5);
write_u32_be(out.slice_mut(24, 28), self.engine.state.h6);
write_u32_be(out.slice_mut(28, 32), self.engine.state.h7);
}
fn reset(&mut self) {
self.engine.reset(&H256);
}
fn output_bits(&self) -> uint { 256 }
}
static H256: [u32; 8] = [
0x6a09e667,
0xbb67ae85,
0x3c6ef372,
0xa54ff53a,
0x510e527f,
0x9b05688c,
0x1f83d9ab,
0x5be0cd19
];
#[cfg(test)]
mod tests {
extern crate rand;
use self::rand::Rng;
use self::rand::isaac::IsaacRng;
use serialize::hex::FromHex;
use std::iter::repeat;
use std::num::Int;
use super::{Digest, Sha256, FixedBuffer};
// A normal addition - no overflow occurs
#[test]
fn test_add_bytes_to_bits_ok() {
assert!(super::add_bytes_to_bits::<u64>(100, 10) == 180);
}
// A simple failure case - adding 1 to the max value
#[test]
#[should_fail]
fn test_add_bytes_to_bits_overflow() {
super::add_bytes_to_bits::<u64>(Int::max_value(), 1);
}
struct Test {
input: String,
output_str: String,
}
fn test_hash<D: Digest>(sh: &mut D, tests: &[Test]) {
// Test that it works when accepting the message all at once
for t in tests.iter() {
sh.reset();
sh.input_str(t.input.as_slice());
let out_str = sh.result_str();
assert!(out_str == t.output_str);
}
// Test that it works when accepting the message in pieces
for t in tests.iter() {
sh.reset();
let len = t.input.len();
let mut left = len;
while left > 0u {
let take = (left + 1u) / 2u;
sh.input_str(t.input
.slice(len - left, take + len - left));
left = left - take;
}
let out_str = sh.result_str();
assert!(out_str == t.output_str);
}
}
#[test]
fn test_sha256() {
// Examples from wikipedia
let wikipedia_tests = vec!(
Test {
input: "".to_string(),
output_str: "e3b0c44298fc1c149afb\
f4c8996fb92427ae41e4649b934ca495991b7852b855".to_string()
},
Test {
input: "The quick brown fox jumps over the lazy \
dog".to_string(),
output_str: "d7a8fbb307d7809469ca\
9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592".to_string()
},
Test {
input: "The quick brown fox jumps over the lazy \
dog.".to_string(),
output_str: "ef537f25c895bfa78252\
6529a9b63d97aa631564d5d789c2b765448c8635fb6c".to_string()
});
let tests = wikipedia_tests;
let mut sh = box Sha256::new();
test_hash(&mut *sh, tests.as_slice());
}
/// Feed 1,000,000 'a's into the digest with varying input sizes and check that the result is
/// correct.
fn test_digest_1million_random<D: Digest>(digest: &mut D, blocksize: uint, expected: &str) {
let total_size = 1000000;
let buffer: Vec<u8> = repeat('a' as u8).take(blocksize * 2).collect();
let mut rng = IsaacRng::new_unseeded();
let mut count = 0;
digest.reset();
while count < total_size {
let next: uint = rng.gen_range(0, 2 * blocksize + 1);
let remaining = total_size - count;
let size = if next > remaining { remaining } else { next };
digest.input(buffer.slice_to(size));
count += size;
}
let result_str = digest.result_str();
let result_bytes = digest.result_bytes();
assert_eq!(expected, result_str.as_slice());
let expected_vec: Vec<u8> = expected.from_hex()
.unwrap()
.into_iter()
.collect();
assert_eq!(expected_vec, result_bytes);
}
#[test]
fn test_1million_random_sha256() {
let mut sh = Sha256::new();
test_digest_1million_random(
&mut sh,
64,
"cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0");
}
}
#[cfg(test)]
mod bench {
extern crate test;
use self::test::Bencher;
use super::{Sha256, FixedBuffer, Digest};
#[bench]
pub fn sha256_10(b: &mut Bencher) {
let mut sh = Sha256::new();
let bytes = [1u8; 10];
b.iter(|| {
sh.input(&bytes);
});
b.bytes = bytes.len() as u64;
}
#[bench]
pub fn sha256_1k(b: &mut Bencher) {
let mut sh = Sha256::new();
let bytes = [1u8; 1024];
b.iter(|| {
sh.input(&bytes);
});
b.bytes = bytes.len() as u64;
}
#[bench]
pub fn sha256_64k(b: &mut Bencher) {
let mut sh = Sha256::new();
let bytes = [1u8; 65536];
b.iter(|| {
sh.input(&bytes);
});
b.bytes = bytes.len() as u64;
}
}
| process_block | identifier_name |
show-toggle.tsx | /*
* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
* License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details
*/
/*
Toggle whether or not to show tasks (deleted, done)
*/
import { React, useRef } from "../../app-framework";
import { Icon, Space } from "../../components";
import { TaskActions } from "./actions";
interface Props {
actions: TaskActions;
type: "done" | "deleted";
count: number;
show?: boolean;
}
export const ShowToggle: React.FC<Props> = React.memo(
({ actions, type, count, show }) => {
const last_call_ref = useRef<number>(0);
function render_toggle() {
let name;
if (show) {
name = "check-square-o";
} else {
name = "square-o";
}
return <Icon name={name} />;
}
function toggle_state() {
// avoid accidental double clicks...
const now = new Date().valueOf();
if (now - last_call_ref.current <= 300) {
return;
}
last_call_ref.current = now;
if (show) {
if (type == "done") actions.stop_showing_done();
else if (type == "deleted") actions.stop_showing_deleted();
} else {
| }
const toggle = render_toggle();
if (actions == null) {
// no support for toggling (e.g., history view)
return toggle;
}
const color = count > 0 || show ? "#666" : "#999";
return (
<div onClick={toggle_state} style={{ color }}>
<span style={{ fontSize: "17pt" }}>{toggle}</span>
<Space />
<span>Show {type}</span>
</div>
);
}
);
| if (count === 0) {
// do nothing
return;
}
if (type == "done") actions.show_done();
else if (type == "deleted") actions.show_deleted();
}
| conditional_block |
show-toggle.tsx | /*
* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
* License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details
*/
/*
Toggle whether or not to show tasks (deleted, done)
*/
import { React, useRef } from "../../app-framework";
import { Icon, Space } from "../../components";
import { TaskActions } from "./actions";
interface Props {
actions: TaskActions;
type: "done" | "deleted";
count: number;
show?: boolean;
}
export const ShowToggle: React.FC<Props> = React.memo(
({ actions, type, count, show }) => {
const last_call_ref = useRef<number>(0);
function render_toggle() {
let name;
if (show) {
name = "check-square-o";
} else {
name = "square-o";
}
return <Icon name={name} />;
}
function tog | {
// avoid accidental double clicks...
const now = new Date().valueOf();
if (now - last_call_ref.current <= 300) {
return;
}
last_call_ref.current = now;
if (show) {
if (type == "done") actions.stop_showing_done();
else if (type == "deleted") actions.stop_showing_deleted();
} else {
if (count === 0) {
// do nothing
return;
}
if (type == "done") actions.show_done();
else if (type == "deleted") actions.show_deleted();
}
}
const toggle = render_toggle();
if (actions == null) {
// no support for toggling (e.g., history view)
return toggle;
}
const color = count > 0 || show ? "#666" : "#999";
return (
<div onClick={toggle_state} style={{ color }}>
<span style={{ fontSize: "17pt" }}>{toggle}</span>
<Space />
<span>Show {type}</span>
</div>
);
}
);
| gle_state() | identifier_name |
show-toggle.tsx | /*
* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
* License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details
*/
| */
import { React, useRef } from "../../app-framework";
import { Icon, Space } from "../../components";
import { TaskActions } from "./actions";
interface Props {
actions: TaskActions;
type: "done" | "deleted";
count: number;
show?: boolean;
}
export const ShowToggle: React.FC<Props> = React.memo(
({ actions, type, count, show }) => {
const last_call_ref = useRef<number>(0);
function render_toggle() {
let name;
if (show) {
name = "check-square-o";
} else {
name = "square-o";
}
return <Icon name={name} />;
}
function toggle_state() {
// avoid accidental double clicks...
const now = new Date().valueOf();
if (now - last_call_ref.current <= 300) {
return;
}
last_call_ref.current = now;
if (show) {
if (type == "done") actions.stop_showing_done();
else if (type == "deleted") actions.stop_showing_deleted();
} else {
if (count === 0) {
// do nothing
return;
}
if (type == "done") actions.show_done();
else if (type == "deleted") actions.show_deleted();
}
}
const toggle = render_toggle();
if (actions == null) {
// no support for toggling (e.g., history view)
return toggle;
}
const color = count > 0 || show ? "#666" : "#999";
return (
<div onClick={toggle_state} style={{ color }}>
<span style={{ fontSize: "17pt" }}>{toggle}</span>
<Space />
<span>Show {type}</span>
</div>
);
}
); | /*
Toggle whether or not to show tasks (deleted, done) | random_line_split |
show-toggle.tsx | /*
* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
* License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details
*/
/*
Toggle whether or not to show tasks (deleted, done)
*/
import { React, useRef } from "../../app-framework";
import { Icon, Space } from "../../components";
import { TaskActions } from "./actions";
interface Props {
actions: TaskActions;
type: "done" | "deleted";
count: number;
show?: boolean;
}
export const ShowToggle: React.FC<Props> = React.memo(
({ actions, type, count, show }) => {
const last_call_ref = useRef<number>(0);
function render_toggle() {
| function toggle_state() {
// avoid accidental double clicks...
const now = new Date().valueOf();
if (now - last_call_ref.current <= 300) {
return;
}
last_call_ref.current = now;
if (show) {
if (type == "done") actions.stop_showing_done();
else if (type == "deleted") actions.stop_showing_deleted();
} else {
if (count === 0) {
// do nothing
return;
}
if (type == "done") actions.show_done();
else if (type == "deleted") actions.show_deleted();
}
}
const toggle = render_toggle();
if (actions == null) {
// no support for toggling (e.g., history view)
return toggle;
}
const color = count > 0 || show ? "#666" : "#999";
return (
<div onClick={toggle_state} style={{ color }}>
<span style={{ fontSize: "17pt" }}>{toggle}</span>
<Space />
<span>Show {type}</span>
</div>
);
}
);
| let name;
if (show) {
name = "check-square-o";
} else {
name = "square-o";
}
return <Icon name={name} />;
}
| identifier_body |
webpack.config.js | /*jshint node: true, esnext: true*/
const path = require('path');
const MinifyPlugin = require("babel-minify-webpack-plugin");
module.exports = {
entry: {
NuCore: 'nucore.js',
test: 'test.js',
widgets: 'widgets.js',
},
output: {
filename: '[name].js',
path: path.resolve(__dirname, 'js'),
publicPath: 'js/',
library: '[name]',
libraryTarget: 'var',
},
module: {
rules: [{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
babelrc: true
},
}
}]
},
plugins: [ | alias: {
maquette$: path.resolve(__dirname, 'node_modules/maquette/dist/index.js'),
},
modules: [
path.resolve(__dirname, 'src'),
'node_modules',
]
}
}; | new MinifyPlugin(),
],
resolve: { | random_line_split |
access_control_allow_methods.rs | use method::Method;
header! {
#[doc="`Access-Control-Allow-Methods` header, part of"]
#[doc="[CORS](http://www.w3.org/TR/cors/#access-control-allow-methods-response-header)"]
#[doc=""]
#[doc="The `Access-Control-Allow-Methods` header indicates, as part of the"]
#[doc="response to a preflight request, which methods can be used during the"]
#[doc="actual request."]
#[doc=""]
#[doc="# ABNF"]
#[doc="```plain"]
#[doc="Access-Control-Allow-Methods: \"Access-Control-Allow-Methods\" \":\" #Method"]
#[doc="```"]
#[doc=""] | #[doc="```"]
#[doc="use hyper::header::{Headers, AccessControlAllowMethods};"]
#[doc="use hyper::method::Method;"]
#[doc=""]
#[doc="let mut headers = Headers::new();"]
#[doc="headers.set("]
#[doc=" AccessControlAllowMethods(vec![Method::Get])"]
#[doc=");"]
#[doc="```"]
#[doc="```"]
#[doc="use hyper::header::{Headers, AccessControlAllowMethods};"]
#[doc="use hyper::method::Method;"]
#[doc=""]
#[doc="let mut headers = Headers::new();"]
#[doc="headers.set("]
#[doc=" AccessControlAllowMethods(vec!["]
#[doc=" Method::Get,"]
#[doc=" Method::Post,"]
#[doc=" Method::Patch,"]
#[doc=" Method::Extension(\"COPY\".to_owned()),"]
#[doc=" ])"]
#[doc=");"]
#[doc="```"]
(AccessControlAllowMethods, "Access-Control-Allow-Methods") => (Method)*
test_access_control_allow_methods {
test_header!(test1, vec![b"PUT, DELETE, XMODIFY"]);
}
} | #[doc="# Example values"]
#[doc="* `PUT, DELETE, XMODIFY`"]
#[doc=""]
#[doc="# Examples"] | random_line_split |
script.js | angular.module('listDemo1', ['ngMaterial'])
.config(function($mdIconProvider) {
$mdIconProvider
.iconSet('communication', 'img/icons/sets/communication-icons.svg', 24);
})
.controller('AppCtrl', function($scope) {
var imagePath = 'img/60.jpeg';
$scope.phones = [
{
type: 'Home',
number: '(555) 251-1234',
options: {
icon: 'communication:phone'
}
},
{
type: 'Cell',
number: '(555) 786-9841',
options: {
icon: 'communication:phone',
avatarIcon: true
}
},
{
type: 'Office',
number: '(555) 314-1592',
options: {
face : imagePath
}
},
{
type: 'Offset',
number: '(555) 192-2010',
options: {
offset: true,
actionIcon: 'communication:phone'
}
}
];
$scope.todos = [
{
face : imagePath,
what: 'My quirky, joyful porg',
who: 'Kaguya w/ #qjporg',
when: '3:08PM',
notes: " I was lucky to find a quirky, joyful porg!"
},
{
face : imagePath,
what: 'Brunch this weekend?',
who: 'Min Li Chan',
when: '3:08PM',
notes: " I'll be in your neighborhood doing errands"
},
{
face : imagePath,
what: 'Brunch this weekend?',
who: 'Min Li Chan',
when: '3:08PM',
notes: " I'll be in your neighborhood doing errands"
},
{
face : imagePath, | notes: " I'll be in your neighborhood doing errands"
},
{
face : imagePath,
what: 'Brunch this weekend?',
who: 'Min Li Chan',
when: '3:08PM',
notes: " I'll be in your neighborhood doing errands"
},
];
}); | what: 'Brunch this weekend?',
who: 'Min Li Chan',
when: '3:08PM', | random_line_split |
util.ts | export * from "../../util/formatContext";
export { array } from "../../util";
import { ILocation, isCurrentPackageLocation } from "../../structure";
// Note that react elements are not react fragments; returning bare elements prevents React from auto-assigning keys, so they must be wrapped in an array.
interface ReactFragmentArray extends Array<ReactFragment> { }
interface ReactElementArray extends Array<React.ReactElement<any>> { }
export type ReactFragment = string | null | ReactFragmentArray | ReactElementArray;
export function join(fragments: ReactFragment[], separator: ReactFragment): ReactFragment |
export function locationDnaid(location: ILocation): string {
if (!location)
return '';
else if (isCurrentPackageLocation(location))
return location;
else
return location.i;
}
| {
const last = fragments.length - 1;
return fragments.map<ReactFragment>((x, i) => i === last ? x : [x, separator]);
} | identifier_body |
util.ts | export * from "../../util/formatContext";
export { array } from "../../util";
import { ILocation, isCurrentPackageLocation } from "../../structure";
// Note that react elements are not react fragments; returning bare elements prevents React from auto-assigning keys, so they must be wrapped in an array.
interface ReactFragmentArray extends Array<ReactFragment> { }
interface ReactElementArray extends Array<React.ReactElement<any>> { } | const last = fragments.length - 1;
return fragments.map<ReactFragment>((x, i) => i === last ? x : [x, separator]);
}
export function locationDnaid(location: ILocation): string {
if (!location)
return '';
else if (isCurrentPackageLocation(location))
return location;
else
return location.i;
} | export type ReactFragment = string | null | ReactFragmentArray | ReactElementArray;
export function join(fragments: ReactFragment[], separator: ReactFragment): ReactFragment { | random_line_split |
util.ts | export * from "../../util/formatContext";
export { array } from "../../util";
import { ILocation, isCurrentPackageLocation } from "../../structure";
// Note that react elements are not react fragments; returning bare elements prevents React from auto-assigning keys, so they must be wrapped in an array.
interface ReactFragmentArray extends Array<ReactFragment> { }
interface ReactElementArray extends Array<React.ReactElement<any>> { }
export type ReactFragment = string | null | ReactFragmentArray | ReactElementArray;
export function join(fragments: ReactFragment[], separator: ReactFragment): ReactFragment {
const last = fragments.length - 1;
return fragments.map<ReactFragment>((x, i) => i === last ? x : [x, separator]);
}
export function | (location: ILocation): string {
if (!location)
return '';
else if (isCurrentPackageLocation(location))
return location;
else
return location.i;
}
| locationDnaid | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.