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 |
|---|---|---|---|---|
main.rs | #![allow(unused_variables)]
fn | () {
// Rust let bindings are immutable by default.
let z = 3;
// This will raise a compiler error:
// z += 2; //~ ERROR cannot assign twice to immutable variable `z`
// You must declare a variable mutable explicitly:
let mut x = 3;
// Similarly, references are immutable by default e.g.
// The following lines would raise a compiler error. Even though x is mutable, y is an
// immutable reference.
// let y = &x;
// *y += 2; //~ ERROR cannot borrow `x` as mutable because it is also borrowed as immutable
let y = &mut x;
*y += 2; // Works
// Note that though y is now a mutable reference, y itself is still immutable e.g.
// let mut z = 5;
// y = &mut z; //~ ERROR re-assignment of immutable variable `y`
}
| main | identifier_name |
main.rs | #![allow(unused_variables)]
fn main() {
// Rust let bindings are immutable by default.
let z = 3;
// This will raise a compiler error:
// z += 2; //~ ERROR cannot assign twice to immutable variable `z`
// You must declare a variable mutable explicitly:
let mut x = 3;
// Similarly, references are immutable by default e.g.
// The following lines would raise a compiler error. Even though x is mutable, y is an
// immutable reference.
// let y = &x;
// *y += 2; //~ ERROR cannot borrow `x` as mutable because it is also borrowed as immutable
let y = &mut x;
*y += 2; // Works
// Note that though y is now a mutable reference, y itself is still immutable e.g.
// let mut z = 5;
// y = &mut z; //~ ERROR re-assignment of immutable variable `y` | } | random_line_split | |
main.rs | #![allow(unused_variables)]
fn main() | {
// Rust let bindings are immutable by default.
let z = 3;
// This will raise a compiler error:
// z += 2; //~ ERROR cannot assign twice to immutable variable `z`
// You must declare a variable mutable explicitly:
let mut x = 3;
// Similarly, references are immutable by default e.g.
// The following lines would raise a compiler error. Even though x is mutable, y is an
// immutable reference.
// let y = &x;
// *y += 2; //~ ERROR cannot borrow `x` as mutable because it is also borrowed as immutable
let y = &mut x;
*y += 2; // Works
// Note that though y is now a mutable reference, y itself is still immutable e.g.
// let mut z = 5;
// y = &mut z; //~ ERROR re-assignment of immutable variable `y`
} | identifier_body | |
tabbarrenderer.js | // Copyright 2008 The Closure Library Authors. 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.
/**
* @fileoverview Default renderer for {@link goog.ui.TabBar}s. Based on the
* original {@code TabPane} code.
*
* @author attila@google.com (Attila Bodis)
* @author eae@google.com (Emil A. Eklund)
*/
goog.provide('goog.ui.TabBarRenderer');
goog.require('goog.a11y.aria.Role');
goog.require('goog.object');
goog.require('goog.ui.ContainerRenderer');
/**
* Default renderer for {@link goog.ui.TabBar}s, based on the {@code TabPane}
* code. The tab bar's DOM structure is determined by its orientation and
* location relative to tab contents. For example, a horizontal tab bar
* located above tab contents looks like this:
* <pre>
* <div class="goog-tab-bar goog-tab-bar-horizontal goog-tab-bar-top">
* ...(tabs here)...
* </div>
* </pre>
* @constructor
* @extends {goog.ui.ContainerRenderer}
*/
goog.ui.TabBarRenderer = function() {
goog.ui.ContainerRenderer.call(this, goog.a11y.aria.Role.TAB_LIST);
};
goog.inherits(goog.ui.TabBarRenderer, goog.ui.ContainerRenderer);
goog.addSingletonGetter(goog.ui.TabBarRenderer);
goog.tagUnsealableClass(goog.ui.TabBarRenderer);
/**
* Default CSS class to be applied to the root element of components rendered
* by this renderer.
* @type {string}
*/
goog.ui.TabBarRenderer.CSS_CLASS = goog.getCssName('goog-tab-bar');
/**
* Returns the CSS class name to be applied to the root element of all tab bars
* rendered or decorated using this renderer.
* @return {string} Renderer-specific CSS class name.
* @override
*/
goog.ui.TabBarRenderer.prototype.getCssClass = function() {
return goog.ui.TabBarRenderer.CSS_CLASS;
};
/**
* Sets the tab bar's state based on the given CSS class name, encountered
* during decoration. Overrides the superclass implementation by recognizing
* class names representing tab bar orientation and location.
* @param {goog.ui.Container} tabBar Tab bar to configure.
* @param {string} className CSS class name.
* @param {string} baseClass Base class name used as the root of state-specific
* class names (typically the renderer's own class name).
* @protected
* @override
*/
goog.ui.TabBarRenderer.prototype.setStateFromClassName = function(tabBar,
className, baseClass) {
// Create the class-to-location lookup table on first access.
if (!this.locationByClass_) {
this.createLocationByClassMap_();
}
// If the class name corresponds to a location, update the tab bar's location;
// otherwise let the superclass handle it.
var location = this.locationByClass_[className];
if (location) | else {
goog.ui.TabBarRenderer.superClass_.setStateFromClassName.call(this, tabBar,
className, baseClass);
}
};
/**
* Returns all CSS class names applicable to the tab bar, based on its state.
* Overrides the superclass implementation by appending the location-specific
* class name to the list.
* @param {goog.ui.Container} tabBar Tab bar whose CSS classes are to be
* returned.
* @return {!Array.<string>} Array of CSS class names applicable to the tab bar.
* @override
*/
goog.ui.TabBarRenderer.prototype.getClassNames = function(tabBar) {
var classNames = goog.ui.TabBarRenderer.superClass_.getClassNames.call(this,
tabBar);
// Create the location-to-class lookup table on first access.
if (!this.classByLocation_) {
this.createClassByLocationMap_();
}
// Apped the class name corresponding to the tab bar's location to the list.
classNames.push(this.classByLocation_[tabBar.getLocation()]);
return classNames;
};
/**
* Creates the location-to-class lookup table.
* @private
*/
goog.ui.TabBarRenderer.prototype.createClassByLocationMap_ = function() {
var baseClass = this.getCssClass();
/**
* Map of locations to location-specific structural class names,
* precomputed and cached on first use to minimize object allocations
* and string concatenation.
* @type {Object}
* @private
*/
this.classByLocation_ = goog.object.create(
goog.ui.TabBar.Location.TOP, goog.getCssName(baseClass, 'top'),
goog.ui.TabBar.Location.BOTTOM, goog.getCssName(baseClass, 'bottom'),
goog.ui.TabBar.Location.START, goog.getCssName(baseClass, 'start'),
goog.ui.TabBar.Location.END, goog.getCssName(baseClass, 'end'));
};
/**
* Creates the class-to-location lookup table, used during decoration.
* @private
*/
goog.ui.TabBarRenderer.prototype.createLocationByClassMap_ = function() {
// We need the classByLocation_ map so we can transpose it.
if (!this.classByLocation_) {
this.createClassByLocationMap_();
}
/**
* Map of location-specific structural class names to locations, used during
* element decoration. Precomputed and cached on first use to minimize object
* allocations and string concatenation.
* @type {Object}
* @private
*/
this.locationByClass_ = goog.object.transpose(this.classByLocation_);
};
| {
tabBar.setLocation(location);
} | conditional_block |
tabbarrenderer.js | // Copyright 2008 The Closure Library Authors. 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.
/**
* @fileoverview Default renderer for {@link goog.ui.TabBar}s. Based on the
* original {@code TabPane} code.
*
* @author attila@google.com (Attila Bodis)
* @author eae@google.com (Emil A. Eklund)
*/
goog.provide('goog.ui.TabBarRenderer');
goog.require('goog.a11y.aria.Role');
goog.require('goog.object');
goog.require('goog.ui.ContainerRenderer');
/**
* Default renderer for {@link goog.ui.TabBar}s, based on the {@code TabPane}
* code. The tab bar's DOM structure is determined by its orientation and
* location relative to tab contents. For example, a horizontal tab bar
* located above tab contents looks like this:
* <pre>
* <div class="goog-tab-bar goog-tab-bar-horizontal goog-tab-bar-top">
* ...(tabs here)...
* </div>
* </pre>
* @constructor
* @extends {goog.ui.ContainerRenderer}
*/
goog.ui.TabBarRenderer = function() {
goog.ui.ContainerRenderer.call(this, goog.a11y.aria.Role.TAB_LIST);
};
goog.inherits(goog.ui.TabBarRenderer, goog.ui.ContainerRenderer);
goog.addSingletonGetter(goog.ui.TabBarRenderer);
goog.tagUnsealableClass(goog.ui.TabBarRenderer);
/** | goog.ui.TabBarRenderer.CSS_CLASS = goog.getCssName('goog-tab-bar');
/**
* Returns the CSS class name to be applied to the root element of all tab bars
* rendered or decorated using this renderer.
* @return {string} Renderer-specific CSS class name.
* @override
*/
goog.ui.TabBarRenderer.prototype.getCssClass = function() {
return goog.ui.TabBarRenderer.CSS_CLASS;
};
/**
* Sets the tab bar's state based on the given CSS class name, encountered
* during decoration. Overrides the superclass implementation by recognizing
* class names representing tab bar orientation and location.
* @param {goog.ui.Container} tabBar Tab bar to configure.
* @param {string} className CSS class name.
* @param {string} baseClass Base class name used as the root of state-specific
* class names (typically the renderer's own class name).
* @protected
* @override
*/
goog.ui.TabBarRenderer.prototype.setStateFromClassName = function(tabBar,
className, baseClass) {
// Create the class-to-location lookup table on first access.
if (!this.locationByClass_) {
this.createLocationByClassMap_();
}
// If the class name corresponds to a location, update the tab bar's location;
// otherwise let the superclass handle it.
var location = this.locationByClass_[className];
if (location) {
tabBar.setLocation(location);
} else {
goog.ui.TabBarRenderer.superClass_.setStateFromClassName.call(this, tabBar,
className, baseClass);
}
};
/**
* Returns all CSS class names applicable to the tab bar, based on its state.
* Overrides the superclass implementation by appending the location-specific
* class name to the list.
* @param {goog.ui.Container} tabBar Tab bar whose CSS classes are to be
* returned.
* @return {!Array.<string>} Array of CSS class names applicable to the tab bar.
* @override
*/
goog.ui.TabBarRenderer.prototype.getClassNames = function(tabBar) {
var classNames = goog.ui.TabBarRenderer.superClass_.getClassNames.call(this,
tabBar);
// Create the location-to-class lookup table on first access.
if (!this.classByLocation_) {
this.createClassByLocationMap_();
}
// Apped the class name corresponding to the tab bar's location to the list.
classNames.push(this.classByLocation_[tabBar.getLocation()]);
return classNames;
};
/**
* Creates the location-to-class lookup table.
* @private
*/
goog.ui.TabBarRenderer.prototype.createClassByLocationMap_ = function() {
var baseClass = this.getCssClass();
/**
* Map of locations to location-specific structural class names,
* precomputed and cached on first use to minimize object allocations
* and string concatenation.
* @type {Object}
* @private
*/
this.classByLocation_ = goog.object.create(
goog.ui.TabBar.Location.TOP, goog.getCssName(baseClass, 'top'),
goog.ui.TabBar.Location.BOTTOM, goog.getCssName(baseClass, 'bottom'),
goog.ui.TabBar.Location.START, goog.getCssName(baseClass, 'start'),
goog.ui.TabBar.Location.END, goog.getCssName(baseClass, 'end'));
};
/**
* Creates the class-to-location lookup table, used during decoration.
* @private
*/
goog.ui.TabBarRenderer.prototype.createLocationByClassMap_ = function() {
// We need the classByLocation_ map so we can transpose it.
if (!this.classByLocation_) {
this.createClassByLocationMap_();
}
/**
* Map of location-specific structural class names to locations, used during
* element decoration. Precomputed and cached on first use to minimize object
* allocations and string concatenation.
* @type {Object}
* @private
*/
this.locationByClass_ = goog.object.transpose(this.classByLocation_);
}; | * Default CSS class to be applied to the root element of components rendered
* by this renderer.
* @type {string}
*/ | random_line_split |
user-video-settings.component.ts | import { pick } from 'lodash-es'
import { Subject, Subscription } from 'rxjs'
import { first } from 'rxjs/operators'
import { Component, Input, OnDestroy, OnInit } from '@angular/core'
import { AuthService, Notifier, ServerService, User, UserService } from '@app/core'
import { FormReactive, FormValidatorService } from '@app/shared/shared-forms' | templateUrl: './user-video-settings.component.html',
styleUrls: [ './user-video-settings.component.scss' ]
})
export class UserVideoSettingsComponent extends FormReactive implements OnInit, OnDestroy {
@Input() user: User = null
@Input() reactiveUpdate = false
@Input() notifyOnUpdate = true
@Input() userInformationLoaded: Subject<any>
defaultNSFWPolicy: NSFWPolicyType
formValuesWatcher: Subscription
constructor (
protected formValidatorService: FormValidatorService,
private authService: AuthService,
private notifier: Notifier,
private userService: UserService,
private serverService: ServerService
) {
super()
}
ngOnInit () {
this.buildForm({
nsfwPolicy: null,
p2pEnabled: null,
autoPlayVideo: null,
autoPlayNextVideo: null,
videoLanguages: null
})
this.userInformationLoaded.pipe(first())
.subscribe(
() => {
const serverConfig = this.serverService.getHTMLConfig()
this.defaultNSFWPolicy = serverConfig.instance.defaultNSFWPolicy
this.form.patchValue({
nsfwPolicy: this.user.nsfwPolicy || this.defaultNSFWPolicy,
p2pEnabled: this.user.p2pEnabled,
autoPlayVideo: this.user.autoPlayVideo === true,
autoPlayNextVideo: this.user.autoPlayNextVideo,
videoLanguages: this.user.videoLanguages
})
if (this.reactiveUpdate) this.handleReactiveUpdate()
}
)
}
ngOnDestroy () {
this.formValuesWatcher?.unsubscribe()
}
updateDetails (onlyKeys?: string[]) {
const nsfwPolicy = this.form.value['nsfwPolicy']
const p2pEnabled = this.form.value['p2pEnabled']
const autoPlayVideo = this.form.value['autoPlayVideo']
const autoPlayNextVideo = this.form.value['autoPlayNextVideo']
const videoLanguages = this.form.value['videoLanguages']
if (Array.isArray(videoLanguages)) {
if (videoLanguages.length > 20) {
this.notifier.error($localize`Too many languages are enabled. Please enable them all or stay below 20 enabled languages.`)
return
}
}
let details: UserUpdateMe = {
nsfwPolicy,
p2pEnabled,
autoPlayVideo,
autoPlayNextVideo,
videoLanguages
}
if (videoLanguages) {
details = Object.assign(details, videoLanguages)
}
if (onlyKeys) details = pick(details, onlyKeys)
if (this.authService.isLoggedIn()) {
return this.updateLoggedProfile(details)
}
return this.updateAnonymousProfile(details)
}
private handleReactiveUpdate () {
let oldForm = { ...this.form.value }
this.formValuesWatcher = this.form.valueChanges.subscribe((formValue: any) => {
const updatedKey = Object.keys(formValue)
.find(k => formValue[k] !== oldForm[k])
oldForm = { ...this.form.value }
this.updateDetails([ updatedKey ])
})
}
private updateLoggedProfile (details: UserUpdateMe) {
this.userService.updateMyProfile(details)
.subscribe({
next: () => {
this.authService.refreshUserInformation()
if (this.notifyOnUpdate) this.notifier.success($localize`Video settings updated.`)
},
error: err => this.notifier.error(err.message)
})
}
private updateAnonymousProfile (details: UserUpdateMe) {
this.userService.updateMyAnonymousProfile(details)
if (this.notifyOnUpdate) this.notifier.success($localize`Display/Video settings updated.`)
}
} | import { UserUpdateMe } from '@shared/models'
import { NSFWPolicyType } from '@shared/models/videos/nsfw-policy.type'
@Component({
selector: 'my-user-video-settings', | random_line_split |
user-video-settings.component.ts | import { pick } from 'lodash-es'
import { Subject, Subscription } from 'rxjs'
import { first } from 'rxjs/operators'
import { Component, Input, OnDestroy, OnInit } from '@angular/core'
import { AuthService, Notifier, ServerService, User, UserService } from '@app/core'
import { FormReactive, FormValidatorService } from '@app/shared/shared-forms'
import { UserUpdateMe } from '@shared/models'
import { NSFWPolicyType } from '@shared/models/videos/nsfw-policy.type'
@Component({
selector: 'my-user-video-settings',
templateUrl: './user-video-settings.component.html',
styleUrls: [ './user-video-settings.component.scss' ]
})
export class UserVideoSettingsComponent extends FormReactive implements OnInit, OnDestroy {
@Input() user: User = null
@Input() reactiveUpdate = false
@Input() notifyOnUpdate = true
@Input() userInformationLoaded: Subject<any>
defaultNSFWPolicy: NSFWPolicyType
formValuesWatcher: Subscription
constructor (
protected formValidatorService: FormValidatorService,
private authService: AuthService,
private notifier: Notifier,
private userService: UserService,
private serverService: ServerService
) {
super()
}
ngOnInit () {
this.buildForm({
nsfwPolicy: null,
p2pEnabled: null,
autoPlayVideo: null,
autoPlayNextVideo: null,
videoLanguages: null
})
this.userInformationLoaded.pipe(first())
.subscribe(
() => {
const serverConfig = this.serverService.getHTMLConfig()
this.defaultNSFWPolicy = serverConfig.instance.defaultNSFWPolicy
this.form.patchValue({
nsfwPolicy: this.user.nsfwPolicy || this.defaultNSFWPolicy,
p2pEnabled: this.user.p2pEnabled,
autoPlayVideo: this.user.autoPlayVideo === true,
autoPlayNextVideo: this.user.autoPlayNextVideo,
videoLanguages: this.user.videoLanguages
})
if (this.reactiveUpdate) this.handleReactiveUpdate()
}
)
}
ngOnDestroy () {
this.formValuesWatcher?.unsubscribe()
}
updateDetails (onlyKeys?: string[]) {
const nsfwPolicy = this.form.value['nsfwPolicy']
const p2pEnabled = this.form.value['p2pEnabled']
const autoPlayVideo = this.form.value['autoPlayVideo']
const autoPlayNextVideo = this.form.value['autoPlayNextVideo']
const videoLanguages = this.form.value['videoLanguages']
if (Array.isArray(videoLanguages)) |
let details: UserUpdateMe = {
nsfwPolicy,
p2pEnabled,
autoPlayVideo,
autoPlayNextVideo,
videoLanguages
}
if (videoLanguages) {
details = Object.assign(details, videoLanguages)
}
if (onlyKeys) details = pick(details, onlyKeys)
if (this.authService.isLoggedIn()) {
return this.updateLoggedProfile(details)
}
return this.updateAnonymousProfile(details)
}
private handleReactiveUpdate () {
let oldForm = { ...this.form.value }
this.formValuesWatcher = this.form.valueChanges.subscribe((formValue: any) => {
const updatedKey = Object.keys(formValue)
.find(k => formValue[k] !== oldForm[k])
oldForm = { ...this.form.value }
this.updateDetails([ updatedKey ])
})
}
private updateLoggedProfile (details: UserUpdateMe) {
this.userService.updateMyProfile(details)
.subscribe({
next: () => {
this.authService.refreshUserInformation()
if (this.notifyOnUpdate) this.notifier.success($localize`Video settings updated.`)
},
error: err => this.notifier.error(err.message)
})
}
private updateAnonymousProfile (details: UserUpdateMe) {
this.userService.updateMyAnonymousProfile(details)
if (this.notifyOnUpdate) this.notifier.success($localize`Display/Video settings updated.`)
}
}
| {
if (videoLanguages.length > 20) {
this.notifier.error($localize`Too many languages are enabled. Please enable them all or stay below 20 enabled languages.`)
return
}
} | conditional_block |
user-video-settings.component.ts | import { pick } from 'lodash-es'
import { Subject, Subscription } from 'rxjs'
import { first } from 'rxjs/operators'
import { Component, Input, OnDestroy, OnInit } from '@angular/core'
import { AuthService, Notifier, ServerService, User, UserService } from '@app/core'
import { FormReactive, FormValidatorService } from '@app/shared/shared-forms'
import { UserUpdateMe } from '@shared/models'
import { NSFWPolicyType } from '@shared/models/videos/nsfw-policy.type'
@Component({
selector: 'my-user-video-settings',
templateUrl: './user-video-settings.component.html',
styleUrls: [ './user-video-settings.component.scss' ]
})
export class UserVideoSettingsComponent extends FormReactive implements OnInit, OnDestroy {
@Input() user: User = null
@Input() reactiveUpdate = false
@Input() notifyOnUpdate = true
@Input() userInformationLoaded: Subject<any>
defaultNSFWPolicy: NSFWPolicyType
formValuesWatcher: Subscription
constructor (
protected formValidatorService: FormValidatorService,
private authService: AuthService,
private notifier: Notifier,
private userService: UserService,
private serverService: ServerService
) {
super()
}
ngOnInit () {
this.buildForm({
nsfwPolicy: null,
p2pEnabled: null,
autoPlayVideo: null,
autoPlayNextVideo: null,
videoLanguages: null
})
this.userInformationLoaded.pipe(first())
.subscribe(
() => {
const serverConfig = this.serverService.getHTMLConfig()
this.defaultNSFWPolicy = serverConfig.instance.defaultNSFWPolicy
this.form.patchValue({
nsfwPolicy: this.user.nsfwPolicy || this.defaultNSFWPolicy,
p2pEnabled: this.user.p2pEnabled,
autoPlayVideo: this.user.autoPlayVideo === true,
autoPlayNextVideo: this.user.autoPlayNextVideo,
videoLanguages: this.user.videoLanguages
})
if (this.reactiveUpdate) this.handleReactiveUpdate()
}
)
}
ngOnDestroy () {
this.formValuesWatcher?.unsubscribe()
}
updateDetails (onlyKeys?: string[]) {
const nsfwPolicy = this.form.value['nsfwPolicy']
const p2pEnabled = this.form.value['p2pEnabled']
const autoPlayVideo = this.form.value['autoPlayVideo']
const autoPlayNextVideo = this.form.value['autoPlayNextVideo']
const videoLanguages = this.form.value['videoLanguages']
if (Array.isArray(videoLanguages)) {
if (videoLanguages.length > 20) {
this.notifier.error($localize`Too many languages are enabled. Please enable them all or stay below 20 enabled languages.`)
return
}
}
let details: UserUpdateMe = {
nsfwPolicy,
p2pEnabled,
autoPlayVideo,
autoPlayNextVideo,
videoLanguages
}
if (videoLanguages) {
details = Object.assign(details, videoLanguages)
}
if (onlyKeys) details = pick(details, onlyKeys)
if (this.authService.isLoggedIn()) {
return this.updateLoggedProfile(details)
}
return this.updateAnonymousProfile(details)
}
private handleReactiveUpdate () {
let oldForm = { ...this.form.value }
this.formValuesWatcher = this.form.valueChanges.subscribe((formValue: any) => {
const updatedKey = Object.keys(formValue)
.find(k => formValue[k] !== oldForm[k])
oldForm = { ...this.form.value }
this.updateDetails([ updatedKey ])
})
}
private | (details: UserUpdateMe) {
this.userService.updateMyProfile(details)
.subscribe({
next: () => {
this.authService.refreshUserInformation()
if (this.notifyOnUpdate) this.notifier.success($localize`Video settings updated.`)
},
error: err => this.notifier.error(err.message)
})
}
private updateAnonymousProfile (details: UserUpdateMe) {
this.userService.updateMyAnonymousProfile(details)
if (this.notifyOnUpdate) this.notifier.success($localize`Display/Video settings updated.`)
}
}
| updateLoggedProfile | identifier_name |
user-video-settings.component.ts | import { pick } from 'lodash-es'
import { Subject, Subscription } from 'rxjs'
import { first } from 'rxjs/operators'
import { Component, Input, OnDestroy, OnInit } from '@angular/core'
import { AuthService, Notifier, ServerService, User, UserService } from '@app/core'
import { FormReactive, FormValidatorService } from '@app/shared/shared-forms'
import { UserUpdateMe } from '@shared/models'
import { NSFWPolicyType } from '@shared/models/videos/nsfw-policy.type'
@Component({
selector: 'my-user-video-settings',
templateUrl: './user-video-settings.component.html',
styleUrls: [ './user-video-settings.component.scss' ]
})
export class UserVideoSettingsComponent extends FormReactive implements OnInit, OnDestroy {
@Input() user: User = null
@Input() reactiveUpdate = false
@Input() notifyOnUpdate = true
@Input() userInformationLoaded: Subject<any>
defaultNSFWPolicy: NSFWPolicyType
formValuesWatcher: Subscription
constructor (
protected formValidatorService: FormValidatorService,
private authService: AuthService,
private notifier: Notifier,
private userService: UserService,
private serverService: ServerService
) {
super()
}
ngOnInit () {
this.buildForm({
nsfwPolicy: null,
p2pEnabled: null,
autoPlayVideo: null,
autoPlayNextVideo: null,
videoLanguages: null
})
this.userInformationLoaded.pipe(first())
.subscribe(
() => {
const serverConfig = this.serverService.getHTMLConfig()
this.defaultNSFWPolicy = serverConfig.instance.defaultNSFWPolicy
this.form.patchValue({
nsfwPolicy: this.user.nsfwPolicy || this.defaultNSFWPolicy,
p2pEnabled: this.user.p2pEnabled,
autoPlayVideo: this.user.autoPlayVideo === true,
autoPlayNextVideo: this.user.autoPlayNextVideo,
videoLanguages: this.user.videoLanguages
})
if (this.reactiveUpdate) this.handleReactiveUpdate()
}
)
}
ngOnDestroy () {
this.formValuesWatcher?.unsubscribe()
}
updateDetails (onlyKeys?: string[]) {
const nsfwPolicy = this.form.value['nsfwPolicy']
const p2pEnabled = this.form.value['p2pEnabled']
const autoPlayVideo = this.form.value['autoPlayVideo']
const autoPlayNextVideo = this.form.value['autoPlayNextVideo']
const videoLanguages = this.form.value['videoLanguages']
if (Array.isArray(videoLanguages)) {
if (videoLanguages.length > 20) {
this.notifier.error($localize`Too many languages are enabled. Please enable them all or stay below 20 enabled languages.`)
return
}
}
let details: UserUpdateMe = {
nsfwPolicy,
p2pEnabled,
autoPlayVideo,
autoPlayNextVideo,
videoLanguages
}
if (videoLanguages) {
details = Object.assign(details, videoLanguages)
}
if (onlyKeys) details = pick(details, onlyKeys)
if (this.authService.isLoggedIn()) {
return this.updateLoggedProfile(details)
}
return this.updateAnonymousProfile(details)
}
private handleReactiveUpdate () {
let oldForm = { ...this.form.value }
this.formValuesWatcher = this.form.valueChanges.subscribe((formValue: any) => {
const updatedKey = Object.keys(formValue)
.find(k => formValue[k] !== oldForm[k])
oldForm = { ...this.form.value }
this.updateDetails([ updatedKey ])
})
}
private updateLoggedProfile (details: UserUpdateMe) {
this.userService.updateMyProfile(details)
.subscribe({
next: () => {
this.authService.refreshUserInformation()
if (this.notifyOnUpdate) this.notifier.success($localize`Video settings updated.`)
},
error: err => this.notifier.error(err.message)
})
}
private updateAnonymousProfile (details: UserUpdateMe) |
}
| {
this.userService.updateMyAnonymousProfile(details)
if (this.notifyOnUpdate) this.notifier.success($localize`Display/Video settings updated.`)
} | identifier_body |
ordered.rs | use std::fmt;
use std::collections::VecMap;
use std::collections::vec_map::Entry;
use std::sync::atomic::{AtomicUsize,Ordering};
#[allow(non_camel_case_types)]
#[derive(Copy)]
pub enum Category
{ TOKEN = 0,
RULE = 1,
STATE = 2 }
pub trait Ordered {
fn get_order(&self) -> usize;
}
pub struct Manager {
next_order: VecMap<AtomicUsize>
}
impl Manager {
pub fn new() -> Self {
Manager{next_order: VecMap::with_capacity(3)}
}
pub fn | (&mut self, c: Category) -> usize
{
match self.next_order.entry(c as usize) {
Entry::Vacant(entry) => { entry.insert(AtomicUsize::new(1));
0 },
Entry::Occupied(mut entry) => { let val = entry.get_mut();
val.fetch_add(1, Ordering::SeqCst) }
}
}
}
impl fmt::Debug for Manager {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "ordered::Manager{{}}")
}
}
| next_order | identifier_name |
ordered.rs | use std::fmt;
use std::collections::VecMap;
use std::collections::vec_map::Entry;
use std::sync::atomic::{AtomicUsize,Ordering};
#[allow(non_camel_case_types)]
#[derive(Copy)]
pub enum Category
{ TOKEN = 0,
RULE = 1,
STATE = 2 }
pub trait Ordered {
fn get_order(&self) -> usize;
}
pub struct Manager {
next_order: VecMap<AtomicUsize>
}
impl Manager {
pub fn new() -> Self {
Manager{next_order: VecMap::with_capacity(3)}
}
pub fn next_order(&mut self, c: Category) -> usize
{
match self.next_order.entry(c as usize) {
Entry::Vacant(entry) => { entry.insert(AtomicUsize::new(1));
0 },
Entry::Occupied(mut entry) => { let val = entry.get_mut();
val.fetch_add(1, Ordering::SeqCst) }
}
}
}
impl fmt::Debug for Manager {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "ordered::Manager{{}}")
} | } | random_line_split | |
ordered.rs | use std::fmt;
use std::collections::VecMap;
use std::collections::vec_map::Entry;
use std::sync::atomic::{AtomicUsize,Ordering};
#[allow(non_camel_case_types)]
#[derive(Copy)]
pub enum Category
{ TOKEN = 0,
RULE = 1,
STATE = 2 }
pub trait Ordered {
fn get_order(&self) -> usize;
}
pub struct Manager {
next_order: VecMap<AtomicUsize>
}
impl Manager {
pub fn new() -> Self {
Manager{next_order: VecMap::with_capacity(3)}
}
pub fn next_order(&mut self, c: Category) -> usize
|
}
impl fmt::Debug for Manager {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "ordered::Manager{{}}")
}
}
| {
match self.next_order.entry(c as usize) {
Entry::Vacant(entry) => { entry.insert(AtomicUsize::new(1));
0 },
Entry::Occupied(mut entry) => { let val = entry.get_mut();
val.fetch_add(1, Ordering::SeqCst) }
}
} | identifier_body |
ordered.rs | use std::fmt;
use std::collections::VecMap;
use std::collections::vec_map::Entry;
use std::sync::atomic::{AtomicUsize,Ordering};
#[allow(non_camel_case_types)]
#[derive(Copy)]
pub enum Category
{ TOKEN = 0,
RULE = 1,
STATE = 2 }
pub trait Ordered {
fn get_order(&self) -> usize;
}
pub struct Manager {
next_order: VecMap<AtomicUsize>
}
impl Manager {
pub fn new() -> Self {
Manager{next_order: VecMap::with_capacity(3)}
}
pub fn next_order(&mut self, c: Category) -> usize
{
match self.next_order.entry(c as usize) {
Entry::Vacant(entry) => | ,
Entry::Occupied(mut entry) => { let val = entry.get_mut();
val.fetch_add(1, Ordering::SeqCst) }
}
}
}
impl fmt::Debug for Manager {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "ordered::Manager{{}}")
}
}
| { entry.insert(AtomicUsize::new(1));
0 } | conditional_block |
production.py | # -*- coding: utf-8 -*-
'''
Production Configurations
- Use djangosecure
- Use mailgun to send emails
- Use redis
'''
from __future__ import absolute_import, unicode_literals
from django.utils import six
from .common import * # noqa
# SECRET CONFIGURATION
# ------------------------------------------------------------------------------
# See: https://docs.djangoproject.com/en/dev/ref/settings/#secret-key
# Raises ImproperlyConfigured exception if DJANO_SECRET_KEY not in os.environ
SECRET_KEY = env("DJANGO_SECRET_KEY")
# This ensures that Django will be able to detect a secure connection
# properly on Heroku.
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
# django-secure
# ------------------------------------------------------------------------------
INSTALLED_APPS += ("djangosecure", )
MIDDLEWARE_CLASSES = (
# Make sure djangosecure.middleware.SecurityMiddleware is listed first
'djangosecure.middleware.SecurityMiddleware',
) + MIDDLEWARE_CLASSES
# set this to 60 seconds and then to 518400 when you can prove it works
SECURE_HSTS_SECONDS = 60
SECURE_HSTS_INCLUDE_SUBDOMAINS = env.bool("DJANGO_SECURE_HSTS_INCLUDE_SUBDOMAINS", default=True)
SECURE_FRAME_DENY = env.bool("DJANGO_SECURE_FRAME_DENY", default=True)
SECURE_CONTENT_TYPE_NOSNIFF = env.bool("DJANGO_SECURE_CONTENT_TYPE_NOSNIFF", default=True)
SECURE_BROWSER_XSS_FILTER = True
SESSION_COOKIE_SECURE = False
SESSION_COOKIE_HTTPONLY = True
SECURE_SSL_REDIRECT = env.bool("DJANGO_SECURE_SSL_REDIRECT", default=True)
# SITE CONFIGURATION
# ------------------------------------------------------------------------------
# Hosts/domain names that are valid for this site
# See https://docs.djangoproject.com/en/1.6/ref/settings/#allowed-hosts
ALLOWED_HOSTS = ["*"]
# END SITE CONFIGURATION
# EMAIL
# ------------------------------------------------------------------------------
DEFAULT_FROM_EMAIL = env('DJANGO_DEFAULT_FROM_EMAIL',
default='{{cookiecutter.project_name}} <noreply@{{cookiecutter.domain_name}}>')
EMAIL_BACKEND = 'django_mailgun.MailgunBackend'
MAILGUN_ACCESS_KEY = env('DJANGO_MAILGUN_API_KEY')
MAILGUN_SERVER_NAME = env('DJANGO_MAILGUN_SERVER_NAME')
EMAIL_SUBJECT_PREFIX = env("DJANGO_EMAIL_SUBJECT_PREFIX", default='[{{cookiecutter.project_name}}] ')
SERVER_EMAIL = env('DJANGO_SERVER_EMAIL', default=DEFAULT_FROM_EMAIL)
# TEMPLATE CONFIGURATION
# ------------------------------------------------------------------------------
# See: https://docs.djangoproject.com/en/dev/ref/templates/api/#django.template.loaders.cached.Loader
TEMPLATES[0]['OPTIONS']['loaders'] = [
('django.template.loaders.cached.Loader', [
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
]),
]
# CACHE CONFIGURATION
# ------------------------------------------------------------------------------
CACHES = {
'default': {
'BACKEND': 'redis_cache.RedisCache',
'LOCATION': [
'redis:6379',
],
'OPTIONS': {
'DB': 1,
'PARSER_CLASS': 'redis.connection.HiredisParser',
'CONNECTION_POOL_CLASS': 'redis.BlockingConnectionPool',
'CONNECTION_POOL_CLASS_KWARGS': {
'max_connections': 50,
'timeout': 20,
},
'MAX_CONNECTIONS': 1000,
'PICKLE_VERSION': -1,
},
},
}
# ASSET CONFIGURATION
# ------------------------------------------------------------------------------
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
STATIC_ROOT = '/static'
MEDIA_ROOT = '/media'
STATICFILES_DIRS = (
unicode(APPS_DIR.path("static")),
) | {% endif %}
{% if cookiecutter.use_sentry %}
# SENTRY CONFIGURATION
# ------------------------------------------------------------------------------
RAVEN_CONFIG = {
'dsn': env("SENTRY_URL"),
}
INSTALLED_APPS = INSTALLED_APPS + (
'raven.contrib.django.raven_compat',
)
{% endif %}
# Your production stuff: Below this line define 3rd party library settings |
{% if cookiecutter.use_celery %}
# CELERY BROKER CONFIGURATION
# ------------------------------------------------------------------------------
BROKER_URL = "amqp://guest:guest@rabbitmq:5672//" | random_line_split |
github-label-manager.js | // ==UserScript==
// @name GitHub Label Manager
// @namespace http://github.com/senritsu
// @version 0.1
// @description Enables importing/exporting of repository labels
// @author senritsu
// @require https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.6.15/browser-polyfill.min.js
// @require https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.6.15/browser.min.js
// @match http*://github.com/*/*/labels*
// ==/UserScript==
/* jshint ignore:start */
var inline_src = (<><![CDATA[
/* jshint ignore:end */
/* jshint esnext: true */
/* jshint asi:true */
const find = (selector, context) => (context || document).querySelector(selector)
const findAll = (selector, context) => (context || document).querySelectorAll(selector)
const newLabelButton = find('.labels-list .subnav button.js-details-target')
const importButton = document.createElement('button')
importButton.id = 'import-labels'
importButton.classList.add('btn', 'btn-default', 'right', 'select-menu-button')
importButton.textContent = 'Import '
const exportButton = document.createElement('button')
importButton.id = 'export-labels'
exportButton.classList.add('btn', 'btn-default', 'right')
exportButton.textContent = 'Export'
const author = find('span.author a').textContent
const repository = find('.repohead-details-container strong[itemprop=name] a').textContent
const exportLink = document.createElement('a')
exportLink.style.display = 'none'
exportLink.download = `${author}-${repository}-labels.json`
exportButton.appendChild(exportLink)
const newLabelForm = find('form.new-label')
const importForm = document.createElement('form')
importForm.id = 'label-import-toolbar'
importForm.classList.add('form')
importForm.style.padding = '10px'
importForm.style.marginBottom = '15px'
importForm.style.backgroundColor = '#fafafa'
importForm.style.border = '1px solid #e5e5e5'
importForm.style.display = 'none'
const importInput = document.createElement('input')
importInput.id = 'label-import-file'
importInput.classList.add('form-control', 'right')
importInput.type = 'file'
importForm.appendChild(importInput)
const clearAllDiv = document.createElement('div')
clearAllDiv.classList.add('checkbox', 'right')
clearAllDiv.style.marginTop = '9px'
clearAllDiv.style.marginRight = '15px'
importForm.appendChild(clearAllDiv)
const clearAllLabel = document.createElement('label')
clearAllDiv.appendChild(clearAllLabel)
const clearAllCheckbox = document.createElement('input')
clearAllCheckbox.id = 'clear-labels-before-import'
clearAllCheckbox.type = 'checkbox'
clearAllLabel.appendChild(clearAllCheckbox)
clearAllLabel.appendChild(document.createTextNode(' Clear all existing labels first'))
const clearfix = document.createElement('div')
clearfix.classList.add('clearfix')
importForm.appendChild(clearfix)
console.log($)
if(newLabelButton) {
setup()
}
function setup() {
const parent = newLabelButton.parentNode
parent.insertBefore(importButton, newLabelButton)
parent.insertBefore(exportButton, newLabelButton)
newLabelForm.parentNode.insertBefore(importForm, newLabelForm)
let open = false
importButton.addEventListener('click', (event) => {
open = !open
importForm.style.display = open ? 'block' : 'none'
})
importInput.addEventListener('change', (event) => {
const reader = new FileReader()
reader.onload = (event) => {
const labels = JSON.parse(reader.result)
if(clearAllCheckbox.checked) {
deleteAllLabels()
}
for(const label of labels) {
addLabel(label)
}
}
reader.readAsText(importInput.files[0])
})
exportButton.addEventListener('click', exportLabels)
}
function rgb2hex(rgb) {
const [_, r, g, b] = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/)
const hex = (x) => ("0" + parseInt(x).toString(16)).slice(-2)
return "#" + hex(r) + hex(g) + hex(b)
}
function exportLabels() {
const labels = Array.from(findAll('.labels-list-item .label-link'))
.map((label) => ({
name: find('.label-name', label).textContent,
color: rgb2hex(label.style.backgroundColor)
}))
const data = 'data:text/json;charset=utf8,' + encodeURIComponent(JSON.stringify(labels, null, 2));
exportLink.href = data
exportLink.click()
}
function findLabel(label) {
return Array.from(findAll('.labels-list-item'))
.filter((x) => find('.label-name', x).textContent === label.name)[0]
}
function updateLabel(label, element) {
find('.js-edit-label', element).click()
find('.label-edit-name', element).value = label.name
find('.color-editor-input', element).value = label.color
find('.new-label-actions .btn-primary', element).click()
}
function addLabel(label) {
find('input.label-edit-name', newLabelForm).value = label.name
find('input#edit-label-color-new', newLabelForm).value = label.color
find('button[type=submit]', newLabelForm).click()
}
function deleteLabel(element) |
function deleteAllLabels() {
const labels = Array.from(findAll('.labels-list-item'))
for(const label of labels) {
deleteLabel(label)
}
}
/* jshint ignore:start */
]]></>).toString();
var c = babel.transform(inline_src);
eval(c.code);
/* jshint ignore:end */
| {
find('.labels-list-actions button.js-details-target', element).click()
find('.label-delete button[type=submit]', element).click()
} | identifier_body |
github-label-manager.js | // ==UserScript==
// @name GitHub Label Manager
// @namespace http://github.com/senritsu
// @version 0.1
// @description Enables importing/exporting of repository labels
// @author senritsu
// @require https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.6.15/browser-polyfill.min.js
// @require https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.6.15/browser.min.js
// @match http*://github.com/*/*/labels*
// ==/UserScript==
/* jshint ignore:start */
var inline_src = (<><![CDATA[
/* jshint ignore:end */
/* jshint esnext: true */
/* jshint asi:true */
const find = (selector, context) => (context || document).querySelector(selector)
const findAll = (selector, context) => (context || document).querySelectorAll(selector)
const newLabelButton = find('.labels-list .subnav button.js-details-target')
const importButton = document.createElement('button')
importButton.id = 'import-labels'
importButton.classList.add('btn', 'btn-default', 'right', 'select-menu-button')
importButton.textContent = 'Import '
const exportButton = document.createElement('button')
importButton.id = 'export-labels'
exportButton.classList.add('btn', 'btn-default', 'right')
exportButton.textContent = 'Export'
const author = find('span.author a').textContent
const repository = find('.repohead-details-container strong[itemprop=name] a').textContent
const exportLink = document.createElement('a')
exportLink.style.display = 'none'
exportLink.download = `${author}-${repository}-labels.json`
exportButton.appendChild(exportLink)
const newLabelForm = find('form.new-label')
const importForm = document.createElement('form')
importForm.id = 'label-import-toolbar'
importForm.classList.add('form')
importForm.style.padding = '10px'
importForm.style.marginBottom = '15px'
importForm.style.backgroundColor = '#fafafa'
importForm.style.border = '1px solid #e5e5e5'
importForm.style.display = 'none'
const importInput = document.createElement('input')
importInput.id = 'label-import-file'
importInput.classList.add('form-control', 'right')
importInput.type = 'file'
importForm.appendChild(importInput)
const clearAllDiv = document.createElement('div')
clearAllDiv.classList.add('checkbox', 'right')
clearAllDiv.style.marginTop = '9px'
clearAllDiv.style.marginRight = '15px'
importForm.appendChild(clearAllDiv)
const clearAllLabel = document.createElement('label')
clearAllDiv.appendChild(clearAllLabel)
const clearAllCheckbox = document.createElement('input')
clearAllCheckbox.id = 'clear-labels-before-import'
clearAllCheckbox.type = 'checkbox'
clearAllLabel.appendChild(clearAllCheckbox)
clearAllLabel.appendChild(document.createTextNode(' Clear all existing labels first'))
const clearfix = document.createElement('div')
clearfix.classList.add('clearfix')
importForm.appendChild(clearfix)
console.log($)
if(newLabelButton) {
setup()
}
function setup() {
const parent = newLabelButton.parentNode
parent.insertBefore(importButton, newLabelButton)
parent.insertBefore(exportButton, newLabelButton)
newLabelForm.parentNode.insertBefore(importForm, newLabelForm)
let open = false
importButton.addEventListener('click', (event) => {
open = !open
importForm.style.display = open ? 'block' : 'none'
})
importInput.addEventListener('change', (event) => {
const reader = new FileReader()
reader.onload = (event) => {
const labels = JSON.parse(reader.result)
if(clearAllCheckbox.checked) {
deleteAllLabels() | }
}
reader.readAsText(importInput.files[0])
})
exportButton.addEventListener('click', exportLabels)
}
function rgb2hex(rgb) {
const [_, r, g, b] = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/)
const hex = (x) => ("0" + parseInt(x).toString(16)).slice(-2)
return "#" + hex(r) + hex(g) + hex(b)
}
function exportLabels() {
const labels = Array.from(findAll('.labels-list-item .label-link'))
.map((label) => ({
name: find('.label-name', label).textContent,
color: rgb2hex(label.style.backgroundColor)
}))
const data = 'data:text/json;charset=utf8,' + encodeURIComponent(JSON.stringify(labels, null, 2));
exportLink.href = data
exportLink.click()
}
function findLabel(label) {
return Array.from(findAll('.labels-list-item'))
.filter((x) => find('.label-name', x).textContent === label.name)[0]
}
function updateLabel(label, element) {
find('.js-edit-label', element).click()
find('.label-edit-name', element).value = label.name
find('.color-editor-input', element).value = label.color
find('.new-label-actions .btn-primary', element).click()
}
function addLabel(label) {
find('input.label-edit-name', newLabelForm).value = label.name
find('input#edit-label-color-new', newLabelForm).value = label.color
find('button[type=submit]', newLabelForm).click()
}
function deleteLabel(element) {
find('.labels-list-actions button.js-details-target', element).click()
find('.label-delete button[type=submit]', element).click()
}
function deleteAllLabels() {
const labels = Array.from(findAll('.labels-list-item'))
for(const label of labels) {
deleteLabel(label)
}
}
/* jshint ignore:start */
]]></>).toString();
var c = babel.transform(inline_src);
eval(c.code);
/* jshint ignore:end */ | }
for(const label of labels) {
addLabel(label) | random_line_split |
github-label-manager.js | // ==UserScript==
// @name GitHub Label Manager
// @namespace http://github.com/senritsu
// @version 0.1
// @description Enables importing/exporting of repository labels
// @author senritsu
// @require https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.6.15/browser-polyfill.min.js
// @require https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.6.15/browser.min.js
// @match http*://github.com/*/*/labels*
// ==/UserScript==
/* jshint ignore:start */
var inline_src = (<><![CDATA[
/* jshint ignore:end */
/* jshint esnext: true */
/* jshint asi:true */
const find = (selector, context) => (context || document).querySelector(selector)
const findAll = (selector, context) => (context || document).querySelectorAll(selector)
const newLabelButton = find('.labels-list .subnav button.js-details-target')
const importButton = document.createElement('button')
importButton.id = 'import-labels'
importButton.classList.add('btn', 'btn-default', 'right', 'select-menu-button')
importButton.textContent = 'Import '
const exportButton = document.createElement('button')
importButton.id = 'export-labels'
exportButton.classList.add('btn', 'btn-default', 'right')
exportButton.textContent = 'Export'
const author = find('span.author a').textContent
const repository = find('.repohead-details-container strong[itemprop=name] a').textContent
const exportLink = document.createElement('a')
exportLink.style.display = 'none'
exportLink.download = `${author}-${repository}-labels.json`
exportButton.appendChild(exportLink)
const newLabelForm = find('form.new-label')
const importForm = document.createElement('form')
importForm.id = 'label-import-toolbar'
importForm.classList.add('form')
importForm.style.padding = '10px'
importForm.style.marginBottom = '15px'
importForm.style.backgroundColor = '#fafafa'
importForm.style.border = '1px solid #e5e5e5'
importForm.style.display = 'none'
const importInput = document.createElement('input')
importInput.id = 'label-import-file'
importInput.classList.add('form-control', 'right')
importInput.type = 'file'
importForm.appendChild(importInput)
const clearAllDiv = document.createElement('div')
clearAllDiv.classList.add('checkbox', 'right')
clearAllDiv.style.marginTop = '9px'
clearAllDiv.style.marginRight = '15px'
importForm.appendChild(clearAllDiv)
const clearAllLabel = document.createElement('label')
clearAllDiv.appendChild(clearAllLabel)
const clearAllCheckbox = document.createElement('input')
clearAllCheckbox.id = 'clear-labels-before-import'
clearAllCheckbox.type = 'checkbox'
clearAllLabel.appendChild(clearAllCheckbox)
clearAllLabel.appendChild(document.createTextNode(' Clear all existing labels first'))
const clearfix = document.createElement('div')
clearfix.classList.add('clearfix')
importForm.appendChild(clearfix)
console.log($)
if(newLabelButton) {
setup()
}
function setup() {
const parent = newLabelButton.parentNode
parent.insertBefore(importButton, newLabelButton)
parent.insertBefore(exportButton, newLabelButton)
newLabelForm.parentNode.insertBefore(importForm, newLabelForm)
let open = false
importButton.addEventListener('click', (event) => {
open = !open
importForm.style.display = open ? 'block' : 'none'
})
importInput.addEventListener('change', (event) => {
const reader = new FileReader()
reader.onload = (event) => {
const labels = JSON.parse(reader.result)
if(clearAllCheckbox.checked) {
deleteAllLabels()
}
for(const label of labels) {
addLabel(label)
}
}
reader.readAsText(importInput.files[0])
})
exportButton.addEventListener('click', exportLabels)
}
function rgb2hex(rgb) {
const [_, r, g, b] = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/)
const hex = (x) => ("0" + parseInt(x).toString(16)).slice(-2)
return "#" + hex(r) + hex(g) + hex(b)
}
function exportLabels() {
const labels = Array.from(findAll('.labels-list-item .label-link'))
.map((label) => ({
name: find('.label-name', label).textContent,
color: rgb2hex(label.style.backgroundColor)
}))
const data = 'data:text/json;charset=utf8,' + encodeURIComponent(JSON.stringify(labels, null, 2));
exportLink.href = data
exportLink.click()
}
function findLabel(label) {
return Array.from(findAll('.labels-list-item'))
.filter((x) => find('.label-name', x).textContent === label.name)[0]
}
function | (label, element) {
find('.js-edit-label', element).click()
find('.label-edit-name', element).value = label.name
find('.color-editor-input', element).value = label.color
find('.new-label-actions .btn-primary', element).click()
}
function addLabel(label) {
find('input.label-edit-name', newLabelForm).value = label.name
find('input#edit-label-color-new', newLabelForm).value = label.color
find('button[type=submit]', newLabelForm).click()
}
function deleteLabel(element) {
find('.labels-list-actions button.js-details-target', element).click()
find('.label-delete button[type=submit]', element).click()
}
function deleteAllLabels() {
const labels = Array.from(findAll('.labels-list-item'))
for(const label of labels) {
deleteLabel(label)
}
}
/* jshint ignore:start */
]]></>).toString();
var c = babel.transform(inline_src);
eval(c.code);
/* jshint ignore:end */
| updateLabel | identifier_name |
github-label-manager.js | // ==UserScript==
// @name GitHub Label Manager
// @namespace http://github.com/senritsu
// @version 0.1
// @description Enables importing/exporting of repository labels
// @author senritsu
// @require https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.6.15/browser-polyfill.min.js
// @require https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.6.15/browser.min.js
// @match http*://github.com/*/*/labels*
// ==/UserScript==
/* jshint ignore:start */
var inline_src = (<><![CDATA[
/* jshint ignore:end */
/* jshint esnext: true */
/* jshint asi:true */
const find = (selector, context) => (context || document).querySelector(selector)
const findAll = (selector, context) => (context || document).querySelectorAll(selector)
const newLabelButton = find('.labels-list .subnav button.js-details-target')
const importButton = document.createElement('button')
importButton.id = 'import-labels'
importButton.classList.add('btn', 'btn-default', 'right', 'select-menu-button')
importButton.textContent = 'Import '
const exportButton = document.createElement('button')
importButton.id = 'export-labels'
exportButton.classList.add('btn', 'btn-default', 'right')
exportButton.textContent = 'Export'
const author = find('span.author a').textContent
const repository = find('.repohead-details-container strong[itemprop=name] a').textContent
const exportLink = document.createElement('a')
exportLink.style.display = 'none'
exportLink.download = `${author}-${repository}-labels.json`
exportButton.appendChild(exportLink)
const newLabelForm = find('form.new-label')
const importForm = document.createElement('form')
importForm.id = 'label-import-toolbar'
importForm.classList.add('form')
importForm.style.padding = '10px'
importForm.style.marginBottom = '15px'
importForm.style.backgroundColor = '#fafafa'
importForm.style.border = '1px solid #e5e5e5'
importForm.style.display = 'none'
const importInput = document.createElement('input')
importInput.id = 'label-import-file'
importInput.classList.add('form-control', 'right')
importInput.type = 'file'
importForm.appendChild(importInput)
const clearAllDiv = document.createElement('div')
clearAllDiv.classList.add('checkbox', 'right')
clearAllDiv.style.marginTop = '9px'
clearAllDiv.style.marginRight = '15px'
importForm.appendChild(clearAllDiv)
const clearAllLabel = document.createElement('label')
clearAllDiv.appendChild(clearAllLabel)
const clearAllCheckbox = document.createElement('input')
clearAllCheckbox.id = 'clear-labels-before-import'
clearAllCheckbox.type = 'checkbox'
clearAllLabel.appendChild(clearAllCheckbox)
clearAllLabel.appendChild(document.createTextNode(' Clear all existing labels first'))
const clearfix = document.createElement('div')
clearfix.classList.add('clearfix')
importForm.appendChild(clearfix)
console.log($)
if(newLabelButton) {
setup()
}
function setup() {
const parent = newLabelButton.parentNode
parent.insertBefore(importButton, newLabelButton)
parent.insertBefore(exportButton, newLabelButton)
newLabelForm.parentNode.insertBefore(importForm, newLabelForm)
let open = false
importButton.addEventListener('click', (event) => {
open = !open
importForm.style.display = open ? 'block' : 'none'
})
importInput.addEventListener('change', (event) => {
const reader = new FileReader()
reader.onload = (event) => {
const labels = JSON.parse(reader.result)
if(clearAllCheckbox.checked) |
for(const label of labels) {
addLabel(label)
}
}
reader.readAsText(importInput.files[0])
})
exportButton.addEventListener('click', exportLabels)
}
function rgb2hex(rgb) {
const [_, r, g, b] = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/)
const hex = (x) => ("0" + parseInt(x).toString(16)).slice(-2)
return "#" + hex(r) + hex(g) + hex(b)
}
function exportLabels() {
const labels = Array.from(findAll('.labels-list-item .label-link'))
.map((label) => ({
name: find('.label-name', label).textContent,
color: rgb2hex(label.style.backgroundColor)
}))
const data = 'data:text/json;charset=utf8,' + encodeURIComponent(JSON.stringify(labels, null, 2));
exportLink.href = data
exportLink.click()
}
function findLabel(label) {
return Array.from(findAll('.labels-list-item'))
.filter((x) => find('.label-name', x).textContent === label.name)[0]
}
function updateLabel(label, element) {
find('.js-edit-label', element).click()
find('.label-edit-name', element).value = label.name
find('.color-editor-input', element).value = label.color
find('.new-label-actions .btn-primary', element).click()
}
function addLabel(label) {
find('input.label-edit-name', newLabelForm).value = label.name
find('input#edit-label-color-new', newLabelForm).value = label.color
find('button[type=submit]', newLabelForm).click()
}
function deleteLabel(element) {
find('.labels-list-actions button.js-details-target', element).click()
find('.label-delete button[type=submit]', element).click()
}
function deleteAllLabels() {
const labels = Array.from(findAll('.labels-list-item'))
for(const label of labels) {
deleteLabel(label)
}
}
/* jshint ignore:start */
]]></>).toString();
var c = babel.transform(inline_src);
eval(c.code);
/* jshint ignore:end */
| {
deleteAllLabels()
} | conditional_block |
vn_char.py | import lxml.html as l
import requests
def | (char_id):
url = 'https://vndb.org/c' + str(char_id)
page = requests.get(url)
root = l.fromstring(page.text)
name = root.cssselect('.mainbox h1')[0].text
kanji_name = root.cssselect('.mainbox h2.alttitle')[0].text
img = 'https:' + root.cssselect('.mainbox .charimg img')[0].attrib['src']
gender = root.cssselect('.chardetails table thead tr td abbr')[0].attrib['title']
try:
bloodtype = root.cssselect('.chardetails table thead tr td span')[0].text
except IndexError:
bloodtype = None
table = root.cssselect('.chardetails table')[0]
for row in table:
if row.tag == 'tr':
if len(row) == 2:
try:
key = row[0][0].text
except IndexError:
key = row[0].text
value = None
try:
if row[1][0].tag == 'a':
value = row[1][0].text
else:
value = []
for span in row[1]:
if 'charspoil_1' in span.classes:
tag = 'minor spoiler'
elif 'charspoil_2' in span.classes:
tag = 'spoiler'
elif 'sexual' in span.classes:
tag = 'sexual trait'
else:
tag = None
value.append({'value': span[1].text, 'tag': tag})
except IndexError:
value = row[1].text
if key == 'Visual novels':
value = []
for span in row[1]:
if span.tag == 'span':
value.append(span.text + span[0].text)
desc = root.cssselect('.chardetails table td.chardesc')[0][1].text
character = {
'URL': url,
'Name': name,
'Name_J': kanji_name,
'Image': img,
'Gender': gender,
'Blood_Type': bloodtype,
'Description': desc
}
return character
| key_char_parse | identifier_name |
vn_char.py | import lxml.html as l
import requests
def key_char_parse(char_id):
url = 'https://vndb.org/c' + str(char_id)
page = requests.get(url)
root = l.fromstring(page.text)
name = root.cssselect('.mainbox h1')[0].text
kanji_name = root.cssselect('.mainbox h2.alttitle')[0].text
img = 'https:' + root.cssselect('.mainbox .charimg img')[0].attrib['src']
gender = root.cssselect('.chardetails table thead tr td abbr')[0].attrib['title']
try:
bloodtype = root.cssselect('.chardetails table thead tr td span')[0].text
except IndexError:
bloodtype = None
table = root.cssselect('.chardetails table')[0]
for row in table:
if row.tag == 'tr':
if len(row) == 2:
try:
key = row[0][0].text
except IndexError:
key = row[0].text
value = None
try:
if row[1][0].tag == 'a':
value = row[1][0].text
else:
value = []
for span in row[1]:
|
except IndexError:
value = row[1].text
if key == 'Visual novels':
value = []
for span in row[1]:
if span.tag == 'span':
value.append(span.text + span[0].text)
desc = root.cssselect('.chardetails table td.chardesc')[0][1].text
character = {
'URL': url,
'Name': name,
'Name_J': kanji_name,
'Image': img,
'Gender': gender,
'Blood_Type': bloodtype,
'Description': desc
}
return character
| if 'charspoil_1' in span.classes:
tag = 'minor spoiler'
elif 'charspoil_2' in span.classes:
tag = 'spoiler'
elif 'sexual' in span.classes:
tag = 'sexual trait'
else:
tag = None
value.append({'value': span[1].text, 'tag': tag}) | conditional_block |
vn_char.py | import lxml.html as l
import requests
def key_char_parse(char_id):
url = 'https://vndb.org/c' + str(char_id)
page = requests.get(url)
root = l.fromstring(page.text)
name = root.cssselect('.mainbox h1')[0].text
kanji_name = root.cssselect('.mainbox h2.alttitle')[0].text
img = 'https:' + root.cssselect('.mainbox .charimg img')[0].attrib['src']
gender = root.cssselect('.chardetails table thead tr td abbr')[0].attrib['title']
try:
bloodtype = root.cssselect('.chardetails table thead tr td span')[0].text
except IndexError:
bloodtype = None
table = root.cssselect('.chardetails table')[0]
for row in table:
if row.tag == 'tr':
if len(row) == 2:
try:
key = row[0][0].text
except IndexError:
key = row[0].text
value = None
try:
if row[1][0].tag == 'a':
value = row[1][0].text
else:
value = []
for span in row[1]:
if 'charspoil_1' in span.classes:
tag = 'minor spoiler'
elif 'charspoil_2' in span.classes:
tag = 'spoiler'
elif 'sexual' in span.classes:
tag = 'sexual trait'
else: | value.append({'value': span[1].text, 'tag': tag})
except IndexError:
value = row[1].text
if key == 'Visual novels':
value = []
for span in row[1]:
if span.tag == 'span':
value.append(span.text + span[0].text)
desc = root.cssselect('.chardetails table td.chardesc')[0][1].text
character = {
'URL': url,
'Name': name,
'Name_J': kanji_name,
'Image': img,
'Gender': gender,
'Blood_Type': bloodtype,
'Description': desc
}
return character | tag = None
| random_line_split |
vn_char.py | import lxml.html as l
import requests
def key_char_parse(char_id):
| url = 'https://vndb.org/c' + str(char_id)
page = requests.get(url)
root = l.fromstring(page.text)
name = root.cssselect('.mainbox h1')[0].text
kanji_name = root.cssselect('.mainbox h2.alttitle')[0].text
img = 'https:' + root.cssselect('.mainbox .charimg img')[0].attrib['src']
gender = root.cssselect('.chardetails table thead tr td abbr')[0].attrib['title']
try:
bloodtype = root.cssselect('.chardetails table thead tr td span')[0].text
except IndexError:
bloodtype = None
table = root.cssselect('.chardetails table')[0]
for row in table:
if row.tag == 'tr':
if len(row) == 2:
try:
key = row[0][0].text
except IndexError:
key = row[0].text
value = None
try:
if row[1][0].tag == 'a':
value = row[1][0].text
else:
value = []
for span in row[1]:
if 'charspoil_1' in span.classes:
tag = 'minor spoiler'
elif 'charspoil_2' in span.classes:
tag = 'spoiler'
elif 'sexual' in span.classes:
tag = 'sexual trait'
else:
tag = None
value.append({'value': span[1].text, 'tag': tag})
except IndexError:
value = row[1].text
if key == 'Visual novels':
value = []
for span in row[1]:
if span.tag == 'span':
value.append(span.text + span[0].text)
desc = root.cssselect('.chardetails table td.chardesc')[0][1].text
character = {
'URL': url,
'Name': name,
'Name_J': kanji_name,
'Image': img,
'Gender': gender,
'Blood_Type': bloodtype,
'Description': desc
}
return character | identifier_body | |
frame-source.ts | import path from 'path';
import execa from 'execa';
import {
FFMPEG_EXE,
SCRUB_FRAMES,
SCRUB_HEIGHT,
SCRUB_SPRITE_DIRECTORY,
SCRUB_WIDTH,
} from './constants';
import { FrameReadError } from './errors';
import { IExportOptions } from '.';
export class FrameSource {
writeBuffer = Buffer.allocUnsafe(this.options.width * this.options.height * 4);
readBuffer = Buffer.allocUnsafe(this.options.width * this.options.height * 4);
private byteIndex = 0;
scrubJpg: string;
private ffmpeg: execa.ExecaChildProcess<Buffer | string>;
private onFrameComplete: ((frameRead: boolean) => void) | null;
private finished = false;
private error = false;
currentFrame = 0;
get nFrames() {
return Math.round(this.trimmedDuration * this.options.fps);
}
get trimmedDuration() {
return this.duration - this.startTrim - this.endTrim;
}
constructor(
public readonly sourcePath: string,
public readonly duration: number,
public readonly startTrim: number,
public readonly endTrim: number,
public readonly options: IExportOptions,
) {}
async exportScrubbingSprite() {
const parsed = path.parse(this.sourcePath);
this.scrubJpg = path.join(SCRUB_SPRITE_DIRECTORY, `${parsed.name}-scrub.jpg`);
/* eslint-disable */
const args = [
'-i', this.sourcePath,
'-vf', `scale=${SCRUB_WIDTH}:${SCRUB_HEIGHT},fps=${SCRUB_FRAMES / this.duration},tile=${SCRUB_FRAMES}x1`,
'-frames:v', '1',
'-y',
this.scrubJpg,
];
/* eslint-enable */
await execa(FFMPEG_EXE, args);
}
private startFfmpeg() {
/* eslint-disable */
const args = [
'-ss', this.startTrim.toString(),
'-i', this.sourcePath,
'-t', (this.duration - this.startTrim - this.endTrim).toString(),
'-vf', `fps=${this.options.fps},scale=${this.options.width}:${this.options.height}`,
'-map', 'v:0',
'-vcodec', 'rawvideo',
'-pix_fmt', 'rgba',
'-f', 'image2pipe',
'-'
];
/* eslint-enable */
this.ffmpeg = execa(FFMPEG_EXE, args, {
encoding: null,
buffer: false,
stdin: 'ignore',
stdout: 'pipe',
stderr: process.stderr,
});
this.ffmpeg.on('exit', code => {
console.debug(
`Highlighter Frame Count: Expected: ${this.nFrames} Actual: ${this.currentFrame}`,
);
this.finished = true;
if (code) this.error = true;
// If a frame request is in progress, immediately resolve it
if (this.onFrameComplete) this.onFrameComplete(false);
});
this.ffmpeg.stdout?.on('data', (chunk: Buffer) => {
this.handleChunk(chunk);
});
this.ffmpeg.catch(e => {
// SIGTERM means we canceled, don't log an error
if (e.signal === 'SIGTERM') return;
console.error('ffmpeg:', e);
});
}
/**
* Attempts to read another frame into the readBuffer
* @returns Returns true if a frame was read, otherwise false
*/
readNextFrame(): Promise<boolean> {
return new Promise<boolean>((resolve, reject) => {
if (!this.ffmpeg) this.startFfmpeg();
if (this.onFrameComplete) |
if (this.error) {
throw new FrameReadError(this.sourcePath);
}
// The stream was closed, so resolve that a frame could not be read.
if (this.finished) {
resolve(false);
return;
}
this.onFrameComplete = frameRead => {
this.error ? reject(new FrameReadError(this.sourcePath)) : resolve(frameRead);
};
this.ffmpeg.stdout?.resume();
});
}
end() {
if (this.ffmpeg) this.ffmpeg.kill();
}
private handleChunk(chunk: Buffer) {
const frameByteSize = this.options.width * this.options.height * 4;
// If the chunk is larger than what's needed to fill the rest of the frame buffer,
// only copy enough to fill the buffer.
const bytesToCopy =
this.byteIndex + chunk.length > frameByteSize ? frameByteSize - this.byteIndex : chunk.length;
chunk.copy(this.writeBuffer, this.byteIndex, 0, bytesToCopy);
this.byteIndex += bytesToCopy;
if (this.byteIndex >= frameByteSize) {
this.ffmpeg.stdout?.pause();
this.swapBuffers();
this.currentFrame++;
if (this.onFrameComplete) this.onFrameComplete(true);
this.onFrameComplete = null;
const remainingBytes = chunk.length - bytesToCopy;
if (remainingBytes > 0) {
chunk.copy(this.writeBuffer, this.byteIndex, bytesToCopy);
this.byteIndex += remainingBytes;
}
}
}
/**
* Swaps read and write buffers (front/back buffer)
*/
private swapBuffers() {
const newRead = this.writeBuffer;
this.writeBuffer = this.readBuffer;
this.readBuffer = newRead;
this.byteIndex = 0;
}
}
| {
console.log('Cannot read next frame while frame read is in progress');
resolve(false);
return;
} | conditional_block |
frame-source.ts | import path from 'path';
import execa from 'execa';
import {
FFMPEG_EXE,
SCRUB_FRAMES,
SCRUB_HEIGHT,
SCRUB_SPRITE_DIRECTORY,
SCRUB_WIDTH,
} from './constants';
import { FrameReadError } from './errors';
import { IExportOptions } from '.';
export class FrameSource {
writeBuffer = Buffer.allocUnsafe(this.options.width * this.options.height * 4);
readBuffer = Buffer.allocUnsafe(this.options.width * this.options.height * 4);
private byteIndex = 0;
scrubJpg: string;
private ffmpeg: execa.ExecaChildProcess<Buffer | string>;
private onFrameComplete: ((frameRead: boolean) => void) | null;
private finished = false;
private error = false;
currentFrame = 0;
get nFrames() {
return Math.round(this.trimmedDuration * this.options.fps);
}
get trimmedDuration() {
return this.duration - this.startTrim - this.endTrim;
}
constructor(
public readonly sourcePath: string,
public readonly duration: number,
public readonly startTrim: number,
public readonly endTrim: number,
public readonly options: IExportOptions,
) {}
async exportScrubbingSprite() {
const parsed = path.parse(this.sourcePath);
this.scrubJpg = path.join(SCRUB_SPRITE_DIRECTORY, `${parsed.name}-scrub.jpg`);
/* eslint-disable */
const args = [
'-i', this.sourcePath,
'-vf', `scale=${SCRUB_WIDTH}:${SCRUB_HEIGHT},fps=${SCRUB_FRAMES / this.duration},tile=${SCRUB_FRAMES}x1`,
'-frames:v', '1',
'-y',
this.scrubJpg,
];
/* eslint-enable */
await execa(FFMPEG_EXE, args);
}
private | () {
/* eslint-disable */
const args = [
'-ss', this.startTrim.toString(),
'-i', this.sourcePath,
'-t', (this.duration - this.startTrim - this.endTrim).toString(),
'-vf', `fps=${this.options.fps},scale=${this.options.width}:${this.options.height}`,
'-map', 'v:0',
'-vcodec', 'rawvideo',
'-pix_fmt', 'rgba',
'-f', 'image2pipe',
'-'
];
/* eslint-enable */
this.ffmpeg = execa(FFMPEG_EXE, args, {
encoding: null,
buffer: false,
stdin: 'ignore',
stdout: 'pipe',
stderr: process.stderr,
});
this.ffmpeg.on('exit', code => {
console.debug(
`Highlighter Frame Count: Expected: ${this.nFrames} Actual: ${this.currentFrame}`,
);
this.finished = true;
if (code) this.error = true;
// If a frame request is in progress, immediately resolve it
if (this.onFrameComplete) this.onFrameComplete(false);
});
this.ffmpeg.stdout?.on('data', (chunk: Buffer) => {
this.handleChunk(chunk);
});
this.ffmpeg.catch(e => {
// SIGTERM means we canceled, don't log an error
if (e.signal === 'SIGTERM') return;
console.error('ffmpeg:', e);
});
}
/**
* Attempts to read another frame into the readBuffer
* @returns Returns true if a frame was read, otherwise false
*/
readNextFrame(): Promise<boolean> {
return new Promise<boolean>((resolve, reject) => {
if (!this.ffmpeg) this.startFfmpeg();
if (this.onFrameComplete) {
console.log('Cannot read next frame while frame read is in progress');
resolve(false);
return;
}
if (this.error) {
throw new FrameReadError(this.sourcePath);
}
// The stream was closed, so resolve that a frame could not be read.
if (this.finished) {
resolve(false);
return;
}
this.onFrameComplete = frameRead => {
this.error ? reject(new FrameReadError(this.sourcePath)) : resolve(frameRead);
};
this.ffmpeg.stdout?.resume();
});
}
end() {
if (this.ffmpeg) this.ffmpeg.kill();
}
private handleChunk(chunk: Buffer) {
const frameByteSize = this.options.width * this.options.height * 4;
// If the chunk is larger than what's needed to fill the rest of the frame buffer,
// only copy enough to fill the buffer.
const bytesToCopy =
this.byteIndex + chunk.length > frameByteSize ? frameByteSize - this.byteIndex : chunk.length;
chunk.copy(this.writeBuffer, this.byteIndex, 0, bytesToCopy);
this.byteIndex += bytesToCopy;
if (this.byteIndex >= frameByteSize) {
this.ffmpeg.stdout?.pause();
this.swapBuffers();
this.currentFrame++;
if (this.onFrameComplete) this.onFrameComplete(true);
this.onFrameComplete = null;
const remainingBytes = chunk.length - bytesToCopy;
if (remainingBytes > 0) {
chunk.copy(this.writeBuffer, this.byteIndex, bytesToCopy);
this.byteIndex += remainingBytes;
}
}
}
/**
* Swaps read and write buffers (front/back buffer)
*/
private swapBuffers() {
const newRead = this.writeBuffer;
this.writeBuffer = this.readBuffer;
this.readBuffer = newRead;
this.byteIndex = 0;
}
}
| startFfmpeg | identifier_name |
frame-source.ts | import path from 'path';
import execa from 'execa';
import {
FFMPEG_EXE,
SCRUB_FRAMES,
SCRUB_HEIGHT,
SCRUB_SPRITE_DIRECTORY,
SCRUB_WIDTH,
} from './constants';
import { FrameReadError } from './errors';
import { IExportOptions } from '.';
export class FrameSource {
writeBuffer = Buffer.allocUnsafe(this.options.width * this.options.height * 4);
readBuffer = Buffer.allocUnsafe(this.options.width * this.options.height * 4);
private byteIndex = 0;
scrubJpg: string;
private ffmpeg: execa.ExecaChildProcess<Buffer | string>;
private onFrameComplete: ((frameRead: boolean) => void) | null;
private finished = false;
private error = false;
currentFrame = 0;
get nFrames() {
return Math.round(this.trimmedDuration * this.options.fps);
}
get trimmedDuration() {
return this.duration - this.startTrim - this.endTrim;
}
constructor(
public readonly sourcePath: string,
public readonly duration: number,
public readonly startTrim: number,
public readonly endTrim: number,
public readonly options: IExportOptions,
) {}
async exportScrubbingSprite() |
private startFfmpeg() {
/* eslint-disable */
const args = [
'-ss', this.startTrim.toString(),
'-i', this.sourcePath,
'-t', (this.duration - this.startTrim - this.endTrim).toString(),
'-vf', `fps=${this.options.fps},scale=${this.options.width}:${this.options.height}`,
'-map', 'v:0',
'-vcodec', 'rawvideo',
'-pix_fmt', 'rgba',
'-f', 'image2pipe',
'-'
];
/* eslint-enable */
this.ffmpeg = execa(FFMPEG_EXE, args, {
encoding: null,
buffer: false,
stdin: 'ignore',
stdout: 'pipe',
stderr: process.stderr,
});
this.ffmpeg.on('exit', code => {
console.debug(
`Highlighter Frame Count: Expected: ${this.nFrames} Actual: ${this.currentFrame}`,
);
this.finished = true;
if (code) this.error = true;
// If a frame request is in progress, immediately resolve it
if (this.onFrameComplete) this.onFrameComplete(false);
});
this.ffmpeg.stdout?.on('data', (chunk: Buffer) => {
this.handleChunk(chunk);
});
this.ffmpeg.catch(e => {
// SIGTERM means we canceled, don't log an error
if (e.signal === 'SIGTERM') return;
console.error('ffmpeg:', e);
});
}
/**
* Attempts to read another frame into the readBuffer
* @returns Returns true if a frame was read, otherwise false
*/
readNextFrame(): Promise<boolean> {
return new Promise<boolean>((resolve, reject) => {
if (!this.ffmpeg) this.startFfmpeg();
if (this.onFrameComplete) {
console.log('Cannot read next frame while frame read is in progress');
resolve(false);
return;
}
if (this.error) {
throw new FrameReadError(this.sourcePath);
}
// The stream was closed, so resolve that a frame could not be read.
if (this.finished) {
resolve(false);
return;
}
this.onFrameComplete = frameRead => {
this.error ? reject(new FrameReadError(this.sourcePath)) : resolve(frameRead);
};
this.ffmpeg.stdout?.resume();
});
}
end() {
if (this.ffmpeg) this.ffmpeg.kill();
}
private handleChunk(chunk: Buffer) {
const frameByteSize = this.options.width * this.options.height * 4;
// If the chunk is larger than what's needed to fill the rest of the frame buffer,
// only copy enough to fill the buffer.
const bytesToCopy =
this.byteIndex + chunk.length > frameByteSize ? frameByteSize - this.byteIndex : chunk.length;
chunk.copy(this.writeBuffer, this.byteIndex, 0, bytesToCopy);
this.byteIndex += bytesToCopy;
if (this.byteIndex >= frameByteSize) {
this.ffmpeg.stdout?.pause();
this.swapBuffers();
this.currentFrame++;
if (this.onFrameComplete) this.onFrameComplete(true);
this.onFrameComplete = null;
const remainingBytes = chunk.length - bytesToCopy;
if (remainingBytes > 0) {
chunk.copy(this.writeBuffer, this.byteIndex, bytesToCopy);
this.byteIndex += remainingBytes;
}
}
}
/**
* Swaps read and write buffers (front/back buffer)
*/
private swapBuffers() {
const newRead = this.writeBuffer;
this.writeBuffer = this.readBuffer;
this.readBuffer = newRead;
this.byteIndex = 0;
}
}
| {
const parsed = path.parse(this.sourcePath);
this.scrubJpg = path.join(SCRUB_SPRITE_DIRECTORY, `${parsed.name}-scrub.jpg`);
/* eslint-disable */
const args = [
'-i', this.sourcePath,
'-vf', `scale=${SCRUB_WIDTH}:${SCRUB_HEIGHT},fps=${SCRUB_FRAMES / this.duration},tile=${SCRUB_FRAMES}x1`,
'-frames:v', '1',
'-y',
this.scrubJpg,
];
/* eslint-enable */
await execa(FFMPEG_EXE, args);
} | identifier_body |
frame-source.ts | import path from 'path';
import execa from 'execa';
import {
FFMPEG_EXE,
SCRUB_FRAMES,
SCRUB_HEIGHT,
SCRUB_SPRITE_DIRECTORY,
SCRUB_WIDTH,
} from './constants';
import { FrameReadError } from './errors';
import { IExportOptions } from '.';
export class FrameSource {
writeBuffer = Buffer.allocUnsafe(this.options.width * this.options.height * 4);
readBuffer = Buffer.allocUnsafe(this.options.width * this.options.height * 4);
private byteIndex = 0;
scrubJpg: string;
private ffmpeg: execa.ExecaChildProcess<Buffer | string>;
private onFrameComplete: ((frameRead: boolean) => void) | null;
private finished = false;
private error = false;
currentFrame = 0;
get nFrames() {
return Math.round(this.trimmedDuration * this.options.fps);
}
get trimmedDuration() {
return this.duration - this.startTrim - this.endTrim;
}
constructor(
public readonly sourcePath: string,
public readonly duration: number,
public readonly startTrim: number,
public readonly endTrim: number,
public readonly options: IExportOptions,
) {}
async exportScrubbingSprite() {
const parsed = path.parse(this.sourcePath);
this.scrubJpg = path.join(SCRUB_SPRITE_DIRECTORY, `${parsed.name}-scrub.jpg`);
/* eslint-disable */
const args = [
'-i', this.sourcePath,
'-vf', `scale=${SCRUB_WIDTH}:${SCRUB_HEIGHT},fps=${SCRUB_FRAMES / this.duration},tile=${SCRUB_FRAMES}x1`,
'-frames:v', '1',
'-y',
this.scrubJpg,
];
/* eslint-enable */
await execa(FFMPEG_EXE, args);
}
private startFfmpeg() {
/* eslint-disable */
const args = [
'-ss', this.startTrim.toString(),
'-i', this.sourcePath,
'-t', (this.duration - this.startTrim - this.endTrim).toString(),
'-vf', `fps=${this.options.fps},scale=${this.options.width}:${this.options.height}`,
'-map', 'v:0',
'-vcodec', 'rawvideo',
'-pix_fmt', 'rgba',
'-f', 'image2pipe',
'-'
];
/* eslint-enable */
| this.ffmpeg = execa(FFMPEG_EXE, args, {
encoding: null,
buffer: false,
stdin: 'ignore',
stdout: 'pipe',
stderr: process.stderr,
});
this.ffmpeg.on('exit', code => {
console.debug(
`Highlighter Frame Count: Expected: ${this.nFrames} Actual: ${this.currentFrame}`,
);
this.finished = true;
if (code) this.error = true;
// If a frame request is in progress, immediately resolve it
if (this.onFrameComplete) this.onFrameComplete(false);
});
this.ffmpeg.stdout?.on('data', (chunk: Buffer) => {
this.handleChunk(chunk);
});
this.ffmpeg.catch(e => {
// SIGTERM means we canceled, don't log an error
if (e.signal === 'SIGTERM') return;
console.error('ffmpeg:', e);
});
}
/**
* Attempts to read another frame into the readBuffer
* @returns Returns true if a frame was read, otherwise false
*/
readNextFrame(): Promise<boolean> {
return new Promise<boolean>((resolve, reject) => {
if (!this.ffmpeg) this.startFfmpeg();
if (this.onFrameComplete) {
console.log('Cannot read next frame while frame read is in progress');
resolve(false);
return;
}
if (this.error) {
throw new FrameReadError(this.sourcePath);
}
// The stream was closed, so resolve that a frame could not be read.
if (this.finished) {
resolve(false);
return;
}
this.onFrameComplete = frameRead => {
this.error ? reject(new FrameReadError(this.sourcePath)) : resolve(frameRead);
};
this.ffmpeg.stdout?.resume();
});
}
end() {
if (this.ffmpeg) this.ffmpeg.kill();
}
private handleChunk(chunk: Buffer) {
const frameByteSize = this.options.width * this.options.height * 4;
// If the chunk is larger than what's needed to fill the rest of the frame buffer,
// only copy enough to fill the buffer.
const bytesToCopy =
this.byteIndex + chunk.length > frameByteSize ? frameByteSize - this.byteIndex : chunk.length;
chunk.copy(this.writeBuffer, this.byteIndex, 0, bytesToCopy);
this.byteIndex += bytesToCopy;
if (this.byteIndex >= frameByteSize) {
this.ffmpeg.stdout?.pause();
this.swapBuffers();
this.currentFrame++;
if (this.onFrameComplete) this.onFrameComplete(true);
this.onFrameComplete = null;
const remainingBytes = chunk.length - bytesToCopy;
if (remainingBytes > 0) {
chunk.copy(this.writeBuffer, this.byteIndex, bytesToCopy);
this.byteIndex += remainingBytes;
}
}
}
/**
* Swaps read and write buffers (front/back buffer)
*/
private swapBuffers() {
const newRead = this.writeBuffer;
this.writeBuffer = this.readBuffer;
this.readBuffer = newRead;
this.byteIndex = 0;
}
} | random_line_split | |
js-themes-registry.service.d.ts | import 'rxjs/add/operator/publish';
import { NbJSThemeOptions } from './js-themes/theme.options';
export declare const BUILT_IN_THEMES: NbJSThemeOptions[];
/**
* Js Themes registry - provides access to the JS themes' variables.
* Usually shouldn't be used directly, but through the NbThemeService class methods (getJsTheme).
*/ | constructor(builtInThemes: NbJSThemeOptions[], newThemes?: NbJSThemeOptions[]);
/**
* Registers a new JS theme
* @param config any
* @param themeName string
* @param baseTheme string
*/
register(config: any, themeName: string, baseTheme: string): void;
/**
* Checks whether the theme is registered
* @param themeName
* @returns boolean
*/
has(themeName: string): boolean;
/**
* Return a theme
* @param themeName
* @returns NbJSThemeOptions
*/
get(themeName: string): NbJSThemeOptions;
private combineByNames(newThemes, oldThemes);
private isObject(item);
private mergeDeep(target, ...sources);
} | export declare class NbJSThemesRegistry {
private builtInThemes;
private newThemes;
private themes; | random_line_split |
js-themes-registry.service.d.ts | import 'rxjs/add/operator/publish';
import { NbJSThemeOptions } from './js-themes/theme.options';
export declare const BUILT_IN_THEMES: NbJSThemeOptions[];
/**
* Js Themes registry - provides access to the JS themes' variables.
* Usually shouldn't be used directly, but through the NbThemeService class methods (getJsTheme).
*/
export declare class | {
private builtInThemes;
private newThemes;
private themes;
constructor(builtInThemes: NbJSThemeOptions[], newThemes?: NbJSThemeOptions[]);
/**
* Registers a new JS theme
* @param config any
* @param themeName string
* @param baseTheme string
*/
register(config: any, themeName: string, baseTheme: string): void;
/**
* Checks whether the theme is registered
* @param themeName
* @returns boolean
*/
has(themeName: string): boolean;
/**
* Return a theme
* @param themeName
* @returns NbJSThemeOptions
*/
get(themeName: string): NbJSThemeOptions;
private combineByNames(newThemes, oldThemes);
private isObject(item);
private mergeDeep(target, ...sources);
}
| NbJSThemesRegistry | identifier_name |
imgLiquid.js | /*
jQuery Plugin: imgLiquid v0.9.75 / 19-04-13
jQuery plugin to resize images to fit in a container.
Copyright (c) 2012 Alejandro Emparan (karacas), twitter: @krc_ale
Dual licensed under the MIT and GPL licenses
https://github.com/karacas/imgLiquid
ex:
$(".imgLiquid").imgLiquid({fill:true});
//OPTIONS:
>js
fill: true,
verticalAlign: //'center' //'top' //'bottom'
horizontalAlign: //'center' //'left' //'right'
fadeInTime: 0,
delay: 0, //time to process next image in milliseconds
responsive: false,
responsiveCheckTime: 500, //time to check resize in milliseconds
>js callBakcs
onStart: function(){},
onFinish: function(){},
onItemResize: function(index, container, img){},
onItemStart: function(index, container, img){},
onItemFinish: function(index, container, img){}
>css (set useCssAligns: true) (overwrite js)
text-align: center;
vertical-align : middle;
>hml5 data attr (overwrite all)
data-imgLiquid-fill="true"
data-imgLiquid-horizontalAlign="center"
data-imgLiquid-verticalAlign="center"
data-imgLiquid-fadeInTime="500"
*/
//
;(function($){
$.fn.extend({
imgLiquid: function(options) {
//is ie?
var isIE = /*@cc_on!@*/false;
//Sizes
var totalItems = this.length;
var processedItems = 0;
//Settings - Options
this.defaultOptions = {};
var self = this;
//___________________________________________________________________
var settings = $.extend({
fill: true,
verticalAlign: 'center', // 'top' // 'bottom'
horizontalAlign: 'center', // 'left' // 'right'
fadeInTime: 0,
responsive: false,
responsiveCheckTime: 100, /*time to check div resize, default 10fps > 1000/100*/
delay: 0,
removeBoxBackground: true,
ieFadeInDisabled: true,
useDataHtmlAttr: true,
useCssAligns: false,
imageRendering: 'auto',
hardPixels: false,
checkvisibility: true,
timecheckvisibility : 250,
//CALLBACKS
onStart: null, //no-params
onFinish: null, //no-params
onItemResize: null, //params: (index, container, img )
onItemStart: null, //params: (index, container, img )
onItemFinish: null //params: (index, container, img )
}, this.defaultOptions, options);
//CALLBACK > Start
if (settings.onStart) settings.onStart();
//SAVES NEW SETTINGS
if (self.data('settings') !== undefined) {
var settTmp = $.extend(self.data('settings'));
settTmp = $.extend(options);
self.data('settings', settTmp);
}
//___________________________________________________________________
return this.each(function($i) {
//Obj
var $imgBoxCont = $(this);
var $img = $('img:first', $imgBoxCont);
if (!$img || $img === null || $img.size() ===0){
onError();
return null;
}
if ($img.data('ILprocessed')){
settings = $.extend(self.data('settings'));
process($imgBoxCont, $img, $i);
return;
}
//STATUS
$img.data('ILprocessed', false);
$img.ILerror = false;
//CALLBACK > ItemStart (index, container, img )
if (settings.onItemStart) settings.onItemStart($i , $imgBoxCont , $img);
//Alpha to 0 & removes
$img.fadeTo(0, 0);
$('img:not(:first)', $imgBoxCont).css('display','none');
$img.css({'visibility':'visible', 'max-width':'none', 'max-height':'none', 'width':'auto', 'height':'auto', 'display':'block', 'image-rendering':settings.imageRendering });
$img.removeAttr("width");
$img.removeAttr("height");
//Delay > 1
if (settings.delay <1) settings.delay = 1;
//set OverFlow
$imgBoxCont.css({'overflow':'hidden'});
//SETTINGS OVERWRITE
if (isIE && settings.imageRendering === 'optimizeQuality') $img.css('-ms-interpolation-mode', 'bicubic');
if (settings.useCssAligns) {
var cha = $imgBoxCont.css('text-align');
var cva = $imgBoxCont.css('vertical-align');
if(cha === 'left' || cha === 'center' || cha === 'right') settings.horizontalAlign = cha;
if (cva === 'top' || cva === 'middle' || cva === 'bottom' || cva === 'center') settings.verticalAlign = cva;
}
if (settings.useDataHtmlAttr) {
if ($imgBoxCont.attr('data-imgLiquid-fill') === 'true') settings.fill = true;
if ($imgBoxCont.attr('data-imgLiquid-fill') === 'false' ) settings.fill = false;
if ($imgBoxCont.attr('data-imgLiquid-responsive') === 'true') settings.responsive = true;
if ($imgBoxCont.attr('data-imgLiquid-responsive') === 'false' ) settings.responsive = false;
if ( Number ($imgBoxCont.attr('data-imgLiquid-fadeInTime')) > 0) settings.fadeInTime = Number ($imgBoxCont.attr('data-imgLiquid-fadeInTime'));
var ha = $imgBoxCont.attr('data-imgLiquid-horizontalAlign');
var va = $imgBoxCont.attr('data-imgLiquid-verticalAlign');
if (ha === 'left' || ha === 'center' || ha === 'right') settings.horizontalAlign = ha;
if (va === 'top' || va === 'middle' || va === 'bottom' || va === 'center') settings.verticalAlign = va;
}
//ie no anims > (muere ie, muere!)
if (isIE && settings.ieFadeInDisabled) settings.fadeInTime = 0;
//RESPONSIVE
function checkElementSize(){
setTimeout(checkElementSizeDelay, settings.responsiveCheckTime);
}
function checkElementSizeDelay(){
//UPDATE SETTINGS
settings = $.extend(self.data('settings'));
$imgBoxCont.actualSize = $imgBoxCont.get(0).offsetWidth + ($imgBoxCont.get(0).offsetHeight/100000);
if ($imgBoxCont.actualSize !== $imgBoxCont.sizeOld){
if ($img.data('ILprocessed') && $imgBoxCont.sizeOld !== undefined){
//CALLBACK > onItemResize (index, container, img )
if (settings.onItemResize) settings.onItemResize($i , $imgBoxCont , $img);
//Process again
if (settings.responsive) process($imgBoxCont, $img, $i);
}
}
$imgBoxCont.sizeOld = $imgBoxCont.actualSize;
checkElementSize();
}
if (settings.responsive) settings.hardPixels = true;
if (settings.responsive || settings.onItemResize !== null) checkElementSize();
//SAVE FIRST TIME SETTINGS
self.data('settings', settings);
//LOAD
$img.on('load', onLoad).on('error', onError);
if($img[0].complete)$img.load();
function onLoad(e){
if (!Boolean($img[0].width === 0 && $img[0].height === 0)) {
if (settings.checkvisibility){
checkProcess();
}else{
//DIRECT > OLD VERSION TEST AND DELETE
setTimeout(function() {
process($imgBoxCont, $img, $i);
}, $i * settings.delay);
}
}
if (e) e.preventDefault();
}
function onError(){
$img.ILerror = true;
checkFinish($imgBoxCont, $img, $i);
$imgBoxCont.css('visibility', 'hidden');
}
function checkProcess(){
if ($img.data('ILprocessed')) return;
setTimeout(function() {
if ($imgBoxCont.is(':visible')){
setTimeout(function() {
process($imgBoxCont, $img, $i);
}, $i * settings.delay);
}else{
checkProcess();
}
}, settings.timecheckvisibility);
}
//___________________________________________________________________
function | ($imgBoxCont, $img, $i){
//RESIZE
var w,h;
if ($img.data('owidth') === undefined) $img.data('owidth', $img[0].width);
if ($img.data('oheight') === undefined) $img.data('oheight', $img[0].height);
if (settings.fill === ($imgBoxCont.width() / $imgBoxCont.height()) >= ($img.data('owidth') / $img.data('oheight'))){
w = '100%'; h = 'auto';
if (settings.hardPixels){
w = Math.floor ($imgBoxCont.width());
h = Math.floor ($imgBoxCont.width() * ($img.data('oheight') / $img.data('owidth')));
}
}else{
h = '100%'; w = 'auto';
if (settings.hardPixels){
h = Math.floor ($imgBoxCont.height());
w = Math.floor ($imgBoxCont.height() * ($img.data('owidth') / $img.data('oheight')));
}
}
$img.css({'width':w, 'height':h});
//align X
var ha = settings.horizontalAlign.toLowerCase();
var hdif = $imgBoxCont.width() - $img[0].width;
var margL = 0;
if (ha === 'center' || ha === 'middle')margL = hdif/2;
if (ha === 'right') margL = hdif;
$img.css('margin-left', Math.floor(margL));
//align Y
var va = settings.verticalAlign.toLowerCase();
var vdif = $imgBoxCont.height() - $img[0].height;
var margT = 0;
if (va === 'center' || va === 'middle') margT = vdif/2;
if (va === 'bottom') margT = vdif;
$img.css('margin-top', Math.floor(margT));
//FadeIn
if (!$img.data('ILprocessed')){
if (settings.removeBoxBackground) $imgBoxCont.css('background-image', 'none');
$img.fadeTo(settings.fadeInTime, 1);
$img.data('ILprocessed', true) ;
//CALLBACK > onItemFinish (index, container, img )
if (settings.onItemFinish) settings.onItemFinish($i , $imgBoxCont , $img);
checkFinish($imgBoxCont, $img, $i);
}
}
//___________________________________________________________________
function checkFinish($imgBoxCont, $img, $i){
processedItems ++;
//CALLBACK > onFinish
if (processedItems === totalItems){
if (settings.onFinish) settings.onFinish();
}
}
});
}
});
})(jQuery); | process | identifier_name |
imgLiquid.js | /*
jQuery Plugin: imgLiquid v0.9.75 / 19-04-13
jQuery plugin to resize images to fit in a container.
Copyright (c) 2012 Alejandro Emparan (karacas), twitter: @krc_ale
Dual licensed under the MIT and GPL licenses
https://github.com/karacas/imgLiquid
ex:
$(".imgLiquid").imgLiquid({fill:true});
//OPTIONS:
>js
fill: true,
verticalAlign: //'center' //'top' //'bottom'
horizontalAlign: //'center' //'left' //'right'
fadeInTime: 0,
delay: 0, //time to process next image in milliseconds
responsive: false,
responsiveCheckTime: 500, //time to check resize in milliseconds
>js callBakcs
onStart: function(){},
onFinish: function(){},
onItemResize: function(index, container, img){},
onItemStart: function(index, container, img){},
onItemFinish: function(index, container, img){}
>css (set useCssAligns: true) (overwrite js)
text-align: center;
vertical-align : middle;
>hml5 data attr (overwrite all)
data-imgLiquid-fill="true"
data-imgLiquid-horizontalAlign="center"
data-imgLiquid-verticalAlign="center"
data-imgLiquid-fadeInTime="500"
*/
//
;(function($){
$.fn.extend({
imgLiquid: function(options) {
//is ie?
var isIE = /*@cc_on!@*/false;
//Sizes
var totalItems = this.length;
var processedItems = 0;
//Settings - Options
this.defaultOptions = {};
var self = this;
//___________________________________________________________________
var settings = $.extend({
fill: true,
verticalAlign: 'center', // 'top' // 'bottom'
horizontalAlign: 'center', // 'left' // 'right'
fadeInTime: 0,
responsive: false,
responsiveCheckTime: 100, /*time to check div resize, default 10fps > 1000/100*/
delay: 0,
removeBoxBackground: true,
ieFadeInDisabled: true,
useDataHtmlAttr: true,
useCssAligns: false,
imageRendering: 'auto',
hardPixels: false,
checkvisibility: true,
timecheckvisibility : 250,
//CALLBACKS
onStart: null, //no-params
onFinish: null, //no-params
onItemResize: null, //params: (index, container, img )
onItemStart: null, //params: (index, container, img )
onItemFinish: null //params: (index, container, img )
}, this.defaultOptions, options);
//CALLBACK > Start
if (settings.onStart) settings.onStart();
//SAVES NEW SETTINGS
if (self.data('settings') !== undefined) {
var settTmp = $.extend(self.data('settings'));
settTmp = $.extend(options);
self.data('settings', settTmp);
}
//___________________________________________________________________
return this.each(function($i) {
//Obj
var $imgBoxCont = $(this);
var $img = $('img:first', $imgBoxCont);
if (!$img || $img === null || $img.size() ===0){
onError();
return null;
}
if ($img.data('ILprocessed')){
settings = $.extend(self.data('settings'));
process($imgBoxCont, $img, $i);
return;
}
//STATUS
$img.data('ILprocessed', false);
$img.ILerror = false;
//CALLBACK > ItemStart (index, container, img )
if (settings.onItemStart) settings.onItemStart($i , $imgBoxCont , $img);
//Alpha to 0 & removes
$img.fadeTo(0, 0);
$('img:not(:first)', $imgBoxCont).css('display','none');
$img.css({'visibility':'visible', 'max-width':'none', 'max-height':'none', 'width':'auto', 'height':'auto', 'display':'block', 'image-rendering':settings.imageRendering });
$img.removeAttr("width");
$img.removeAttr("height");
//Delay > 1
if (settings.delay <1) settings.delay = 1;
//set OverFlow
$imgBoxCont.css({'overflow':'hidden'});
//SETTINGS OVERWRITE
if (isIE && settings.imageRendering === 'optimizeQuality') $img.css('-ms-interpolation-mode', 'bicubic');
if (settings.useCssAligns) {
var cha = $imgBoxCont.css('text-align');
var cva = $imgBoxCont.css('vertical-align');
if(cha === 'left' || cha === 'center' || cha === 'right') settings.horizontalAlign = cha;
if (cva === 'top' || cva === 'middle' || cva === 'bottom' || cva === 'center') settings.verticalAlign = cva;
}
if (settings.useDataHtmlAttr) {
if ($imgBoxCont.attr('data-imgLiquid-fill') === 'true') settings.fill = true;
if ($imgBoxCont.attr('data-imgLiquid-fill') === 'false' ) settings.fill = false;
if ($imgBoxCont.attr('data-imgLiquid-responsive') === 'true') settings.responsive = true;
if ($imgBoxCont.attr('data-imgLiquid-responsive') === 'false' ) settings.responsive = false;
if ( Number ($imgBoxCont.attr('data-imgLiquid-fadeInTime')) > 0) settings.fadeInTime = Number ($imgBoxCont.attr('data-imgLiquid-fadeInTime'));
var ha = $imgBoxCont.attr('data-imgLiquid-horizontalAlign');
var va = $imgBoxCont.attr('data-imgLiquid-verticalAlign');
if (ha === 'left' || ha === 'center' || ha === 'right') settings.horizontalAlign = ha;
if (va === 'top' || va === 'middle' || va === 'bottom' || va === 'center') settings.verticalAlign = va;
}
//ie no anims > (muere ie, muere!)
if (isIE && settings.ieFadeInDisabled) settings.fadeInTime = 0;
//RESPONSIVE
function checkElementSize(){
setTimeout(checkElementSizeDelay, settings.responsiveCheckTime);
}
function checkElementSizeDelay() |
if (settings.responsive) settings.hardPixels = true;
if (settings.responsive || settings.onItemResize !== null) checkElementSize();
//SAVE FIRST TIME SETTINGS
self.data('settings', settings);
//LOAD
$img.on('load', onLoad).on('error', onError);
if($img[0].complete)$img.load();
function onLoad(e){
if (!Boolean($img[0].width === 0 && $img[0].height === 0)) {
if (settings.checkvisibility){
checkProcess();
}else{
//DIRECT > OLD VERSION TEST AND DELETE
setTimeout(function() {
process($imgBoxCont, $img, $i);
}, $i * settings.delay);
}
}
if (e) e.preventDefault();
}
function onError(){
$img.ILerror = true;
checkFinish($imgBoxCont, $img, $i);
$imgBoxCont.css('visibility', 'hidden');
}
function checkProcess(){
if ($img.data('ILprocessed')) return;
setTimeout(function() {
if ($imgBoxCont.is(':visible')){
setTimeout(function() {
process($imgBoxCont, $img, $i);
}, $i * settings.delay);
}else{
checkProcess();
}
}, settings.timecheckvisibility);
}
//___________________________________________________________________
function process($imgBoxCont, $img, $i){
//RESIZE
var w,h;
if ($img.data('owidth') === undefined) $img.data('owidth', $img[0].width);
if ($img.data('oheight') === undefined) $img.data('oheight', $img[0].height);
if (settings.fill === ($imgBoxCont.width() / $imgBoxCont.height()) >= ($img.data('owidth') / $img.data('oheight'))){
w = '100%'; h = 'auto';
if (settings.hardPixels){
w = Math.floor ($imgBoxCont.width());
h = Math.floor ($imgBoxCont.width() * ($img.data('oheight') / $img.data('owidth')));
}
}else{
h = '100%'; w = 'auto';
if (settings.hardPixels){
h = Math.floor ($imgBoxCont.height());
w = Math.floor ($imgBoxCont.height() * ($img.data('owidth') / $img.data('oheight')));
}
}
$img.css({'width':w, 'height':h});
//align X
var ha = settings.horizontalAlign.toLowerCase();
var hdif = $imgBoxCont.width() - $img[0].width;
var margL = 0;
if (ha === 'center' || ha === 'middle')margL = hdif/2;
if (ha === 'right') margL = hdif;
$img.css('margin-left', Math.floor(margL));
//align Y
var va = settings.verticalAlign.toLowerCase();
var vdif = $imgBoxCont.height() - $img[0].height;
var margT = 0;
if (va === 'center' || va === 'middle') margT = vdif/2;
if (va === 'bottom') margT = vdif;
$img.css('margin-top', Math.floor(margT));
//FadeIn
if (!$img.data('ILprocessed')){
if (settings.removeBoxBackground) $imgBoxCont.css('background-image', 'none');
$img.fadeTo(settings.fadeInTime, 1);
$img.data('ILprocessed', true) ;
//CALLBACK > onItemFinish (index, container, img )
if (settings.onItemFinish) settings.onItemFinish($i , $imgBoxCont , $img);
checkFinish($imgBoxCont, $img, $i);
}
}
//___________________________________________________________________
function checkFinish($imgBoxCont, $img, $i){
processedItems ++;
//CALLBACK > onFinish
if (processedItems === totalItems){
if (settings.onFinish) settings.onFinish();
}
}
});
}
});
})(jQuery); | {
//UPDATE SETTINGS
settings = $.extend(self.data('settings'));
$imgBoxCont.actualSize = $imgBoxCont.get(0).offsetWidth + ($imgBoxCont.get(0).offsetHeight/100000);
if ($imgBoxCont.actualSize !== $imgBoxCont.sizeOld){
if ($img.data('ILprocessed') && $imgBoxCont.sizeOld !== undefined){
//CALLBACK > onItemResize (index, container, img )
if (settings.onItemResize) settings.onItemResize($i , $imgBoxCont , $img);
//Process again
if (settings.responsive) process($imgBoxCont, $img, $i);
}
}
$imgBoxCont.sizeOld = $imgBoxCont.actualSize;
checkElementSize();
} | identifier_body |
imgLiquid.js | /*
jQuery Plugin: imgLiquid v0.9.75 / 19-04-13
jQuery plugin to resize images to fit in a container.
Copyright (c) 2012 Alejandro Emparan (karacas), twitter: @krc_ale
Dual licensed under the MIT and GPL licenses
https://github.com/karacas/imgLiquid
ex:
$(".imgLiquid").imgLiquid({fill:true});
//OPTIONS:
>js
fill: true,
verticalAlign: //'center' //'top' //'bottom'
horizontalAlign: //'center' //'left' //'right'
fadeInTime: 0,
delay: 0, //time to process next image in milliseconds
responsive: false,
responsiveCheckTime: 500, //time to check resize in milliseconds
>js callBakcs
onStart: function(){},
onFinish: function(){},
onItemResize: function(index, container, img){},
onItemStart: function(index, container, img){},
onItemFinish: function(index, container, img){}
>css (set useCssAligns: true) (overwrite js)
text-align: center;
vertical-align : middle;
>hml5 data attr (overwrite all)
data-imgLiquid-fill="true"
data-imgLiquid-horizontalAlign="center"
data-imgLiquid-verticalAlign="center"
data-imgLiquid-fadeInTime="500"
*/
//
;(function($){
$.fn.extend({
imgLiquid: function(options) {
//is ie?
var isIE = /*@cc_on!@*/false;
//Sizes
var totalItems = this.length;
var processedItems = 0;
//Settings - Options
this.defaultOptions = {};
var self = this;
//___________________________________________________________________
var settings = $.extend({
fill: true,
verticalAlign: 'center', // 'top' // 'bottom'
horizontalAlign: 'center', // 'left' // 'right'
fadeInTime: 0,
responsive: false,
responsiveCheckTime: 100, /*time to check div resize, default 10fps > 1000/100*/
delay: 0,
removeBoxBackground: true,
ieFadeInDisabled: true,
useDataHtmlAttr: true,
useCssAligns: false,
imageRendering: 'auto',
hardPixels: false,
checkvisibility: true,
timecheckvisibility : 250,
//CALLBACKS
onStart: null, //no-params
onFinish: null, //no-params
onItemResize: null, //params: (index, container, img )
onItemStart: null, //params: (index, container, img )
onItemFinish: null //params: (index, container, img )
}, this.defaultOptions, options);
//CALLBACK > Start
if (settings.onStart) settings.onStart();
//SAVES NEW SETTINGS
if (self.data('settings') !== undefined) {
var settTmp = $.extend(self.data('settings'));
settTmp = $.extend(options);
self.data('settings', settTmp);
}
//___________________________________________________________________
return this.each(function($i) {
//Obj
var $imgBoxCont = $(this);
var $img = $('img:first', $imgBoxCont);
if (!$img || $img === null || $img.size() ===0){
onError();
return null;
}
if ($img.data('ILprocessed')){
settings = $.extend(self.data('settings'));
process($imgBoxCont, $img, $i);
return;
}
//STATUS
$img.data('ILprocessed', false);
$img.ILerror = false;
//CALLBACK > ItemStart (index, container, img )
if (settings.onItemStart) settings.onItemStart($i , $imgBoxCont , $img);
//Alpha to 0 & removes
$img.fadeTo(0, 0);
$('img:not(:first)', $imgBoxCont).css('display','none');
$img.css({'visibility':'visible', 'max-width':'none', 'max-height':'none', 'width':'auto', 'height':'auto', 'display':'block', 'image-rendering':settings.imageRendering });
$img.removeAttr("width");
$img.removeAttr("height");
//Delay > 1
if (settings.delay <1) settings.delay = 1;
//set OverFlow
$imgBoxCont.css({'overflow':'hidden'});
//SETTINGS OVERWRITE
if (isIE && settings.imageRendering === 'optimizeQuality') $img.css('-ms-interpolation-mode', 'bicubic');
if (settings.useCssAligns) {
var cha = $imgBoxCont.css('text-align');
var cva = $imgBoxCont.css('vertical-align');
if(cha === 'left' || cha === 'center' || cha === 'right') settings.horizontalAlign = cha;
if (cva === 'top' || cva === 'middle' || cva === 'bottom' || cva === 'center') settings.verticalAlign = cva;
}
if (settings.useDataHtmlAttr) {
if ($imgBoxCont.attr('data-imgLiquid-fill') === 'true') settings.fill = true;
if ($imgBoxCont.attr('data-imgLiquid-fill') === 'false' ) settings.fill = false;
if ($imgBoxCont.attr('data-imgLiquid-responsive') === 'true') settings.responsive = true;
if ($imgBoxCont.attr('data-imgLiquid-responsive') === 'false' ) settings.responsive = false;
if ( Number ($imgBoxCont.attr('data-imgLiquid-fadeInTime')) > 0) settings.fadeInTime = Number ($imgBoxCont.attr('data-imgLiquid-fadeInTime'));
var ha = $imgBoxCont.attr('data-imgLiquid-horizontalAlign');
var va = $imgBoxCont.attr('data-imgLiquid-verticalAlign');
if (ha === 'left' || ha === 'center' || ha === 'right') settings.horizontalAlign = ha;
if (va === 'top' || va === 'middle' || va === 'bottom' || va === 'center') settings.verticalAlign = va;
}
//ie no anims > (muere ie, muere!)
if (isIE && settings.ieFadeInDisabled) settings.fadeInTime = 0;
//RESPONSIVE
function checkElementSize(){
setTimeout(checkElementSizeDelay, settings.responsiveCheckTime);
}
function checkElementSizeDelay(){
//UPDATE SETTINGS
settings = $.extend(self.data('settings'));
$imgBoxCont.actualSize = $imgBoxCont.get(0).offsetWidth + ($imgBoxCont.get(0).offsetHeight/100000);
if ($imgBoxCont.actualSize !== $imgBoxCont.sizeOld){
if ($img.data('ILprocessed') && $imgBoxCont.sizeOld !== undefined){
//CALLBACK > onItemResize (index, container, img )
if (settings.onItemResize) settings.onItemResize($i , $imgBoxCont , $img);
//Process again
if (settings.responsive) process($imgBoxCont, $img, $i);
}
}
$imgBoxCont.sizeOld = $imgBoxCont.actualSize;
checkElementSize();
}
if (settings.responsive) settings.hardPixels = true;
if (settings.responsive || settings.onItemResize !== null) checkElementSize();
//SAVE FIRST TIME SETTINGS
self.data('settings', settings);
//LOAD
$img.on('load', onLoad).on('error', onError);
if($img[0].complete)$img.load();
function onLoad(e){
if (!Boolean($img[0].width === 0 && $img[0].height === 0)) {
if (settings.checkvisibility){
checkProcess();
}else{
//DIRECT > OLD VERSION TEST AND DELETE
| if (e) e.preventDefault();
}
function onError(){
$img.ILerror = true;
checkFinish($imgBoxCont, $img, $i);
$imgBoxCont.css('visibility', 'hidden');
}
function checkProcess(){
if ($img.data('ILprocessed')) return;
setTimeout(function() {
if ($imgBoxCont.is(':visible')){
setTimeout(function() {
process($imgBoxCont, $img, $i);
}, $i * settings.delay);
}else{
checkProcess();
}
}, settings.timecheckvisibility);
}
//___________________________________________________________________
function process($imgBoxCont, $img, $i){
//RESIZE
var w,h;
if ($img.data('owidth') === undefined) $img.data('owidth', $img[0].width);
if ($img.data('oheight') === undefined) $img.data('oheight', $img[0].height);
if (settings.fill === ($imgBoxCont.width() / $imgBoxCont.height()) >= ($img.data('owidth') / $img.data('oheight'))){
w = '100%'; h = 'auto';
if (settings.hardPixels){
w = Math.floor ($imgBoxCont.width());
h = Math.floor ($imgBoxCont.width() * ($img.data('oheight') / $img.data('owidth')));
}
}else{
h = '100%'; w = 'auto';
if (settings.hardPixels){
h = Math.floor ($imgBoxCont.height());
w = Math.floor ($imgBoxCont.height() * ($img.data('owidth') / $img.data('oheight')));
}
}
$img.css({'width':w, 'height':h});
//align X
var ha = settings.horizontalAlign.toLowerCase();
var hdif = $imgBoxCont.width() - $img[0].width;
var margL = 0;
if (ha === 'center' || ha === 'middle')margL = hdif/2;
if (ha === 'right') margL = hdif;
$img.css('margin-left', Math.floor(margL));
//align Y
var va = settings.verticalAlign.toLowerCase();
var vdif = $imgBoxCont.height() - $img[0].height;
var margT = 0;
if (va === 'center' || va === 'middle') margT = vdif/2;
if (va === 'bottom') margT = vdif;
$img.css('margin-top', Math.floor(margT));
//FadeIn
if (!$img.data('ILprocessed')){
if (settings.removeBoxBackground) $imgBoxCont.css('background-image', 'none');
$img.fadeTo(settings.fadeInTime, 1);
$img.data('ILprocessed', true) ;
//CALLBACK > onItemFinish (index, container, img )
if (settings.onItemFinish) settings.onItemFinish($i , $imgBoxCont , $img);
checkFinish($imgBoxCont, $img, $i);
}
}
//___________________________________________________________________
function checkFinish($imgBoxCont, $img, $i){
processedItems ++;
//CALLBACK > onFinish
if (processedItems === totalItems){
if (settings.onFinish) settings.onFinish();
}
}
});
}
});
})(jQuery); | setTimeout(function() {
process($imgBoxCont, $img, $i);
}, $i * settings.delay);
}
}
| random_line_split |
pipeline.js | /**
* grunt/pipeline.js
*
* The order in which your css, javascript, and template files should be
* compiled and linked from your views and static HTML files.
*
* (Note that you can take advantage of Grunt-style wildcard/glob/splat expressions
* for matching multiple files, and the ! prefix for excluding files.)
*/
// Path to public folder
var tmpPath = '.tmp/public/';
// CSS files to inject in order
//
// (if you're using LESS with the built-in default config, you'll want
// to change `assets/styles/importer.less` instead.)
var cssFilesToInject = [
'styles/bootstrap.min.css',
'styles/bootstrap-theme.css'
];
// Client-side javascript files to inject in order
// (uses Grunt-style wildcard/glob/splat expressions)
var jsFilesToInject = [
// Load sails.io before everything else
'js/dependencies/sails.io.js',
'js/dependencies/angular.js',
'js/dependencies/angular-translate.min.js',
'js/dependencies/jquery.min.js',
'js/dependencies/bootstrap.min.js',
'js/dependencies/ui-bootstrap.min.js',
'js/dependencies/ui-bootstrap-tpls.min.js',
'js/dependencies/angular-translate.min.js',
'js/dependencies/smart-table.min.js',
'js/app.js'
// Dependencies like jQuery, or Angular are brought in here
// All of the rest of your client-side js files
// will be injected here in no particular order.
// Use the "exclude" operator to ignore files
// '!js/ignore/these/files/*.js'
];
// Client-side HTML templates are injected using the sources below
// The ordering of these templates shouldn't matter.
// (uses Grunt-style wildcard/glob/splat expressions)
//
// By default, Sails uses JST templates and precompiles them into
// functions for you. If you want to use jade, handlebars, dust, etc.,
// with the linker, no problem-- you'll just want to make sure the precompiled
// templates get spit out to the same file. Be sure and check out `tasks/README.md`
// for information on customizing and installing new tasks. | ];
// Prefix relative paths to source files so they point to the proper locations
// (i.e. where the other Grunt tasks spit them out, or in some cases, where
// they reside in the first place)
module.exports.cssFilesToInject = cssFilesToInject.map(transformPath);
module.exports.jsFilesToInject = jsFilesToInject.map(transformPath);
module.exports.templateFilesToInject = templateFilesToInject.map(transformPath);
// Transform paths relative to the "assets" folder to be relative to the public
// folder, preserving "exclude" operators.
function transformPath(path) {
return (path.substring(0,1) == '!') ? ('!' + tmpPath + path.substring(1)) : (tmpPath + path);
} | var templateFilesToInject = [
'templates/**/*.html' | random_line_split |
pipeline.js | /**
* grunt/pipeline.js
*
* The order in which your css, javascript, and template files should be
* compiled and linked from your views and static HTML files.
*
* (Note that you can take advantage of Grunt-style wildcard/glob/splat expressions
* for matching multiple files, and the ! prefix for excluding files.)
*/
// Path to public folder
var tmpPath = '.tmp/public/';
// CSS files to inject in order
//
// (if you're using LESS with the built-in default config, you'll want
// to change `assets/styles/importer.less` instead.)
var cssFilesToInject = [
'styles/bootstrap.min.css',
'styles/bootstrap-theme.css'
];
// Client-side javascript files to inject in order
// (uses Grunt-style wildcard/glob/splat expressions)
var jsFilesToInject = [
// Load sails.io before everything else
'js/dependencies/sails.io.js',
'js/dependencies/angular.js',
'js/dependencies/angular-translate.min.js',
'js/dependencies/jquery.min.js',
'js/dependencies/bootstrap.min.js',
'js/dependencies/ui-bootstrap.min.js',
'js/dependencies/ui-bootstrap-tpls.min.js',
'js/dependencies/angular-translate.min.js',
'js/dependencies/smart-table.min.js',
'js/app.js'
// Dependencies like jQuery, or Angular are brought in here
// All of the rest of your client-side js files
// will be injected here in no particular order.
// Use the "exclude" operator to ignore files
// '!js/ignore/these/files/*.js'
];
// Client-side HTML templates are injected using the sources below
// The ordering of these templates shouldn't matter.
// (uses Grunt-style wildcard/glob/splat expressions)
//
// By default, Sails uses JST templates and precompiles them into
// functions for you. If you want to use jade, handlebars, dust, etc.,
// with the linker, no problem-- you'll just want to make sure the precompiled
// templates get spit out to the same file. Be sure and check out `tasks/README.md`
// for information on customizing and installing new tasks.
var templateFilesToInject = [
'templates/**/*.html'
];
// Prefix relative paths to source files so they point to the proper locations
// (i.e. where the other Grunt tasks spit them out, or in some cases, where
// they reside in the first place)
module.exports.cssFilesToInject = cssFilesToInject.map(transformPath);
module.exports.jsFilesToInject = jsFilesToInject.map(transformPath);
module.exports.templateFilesToInject = templateFilesToInject.map(transformPath);
// Transform paths relative to the "assets" folder to be relative to the public
// folder, preserving "exclude" operators.
function transformPath(path) | {
return (path.substring(0,1) == '!') ? ('!' + tmpPath + path.substring(1)) : (tmpPath + path);
} | identifier_body | |
pipeline.js | /**
* grunt/pipeline.js
*
* The order in which your css, javascript, and template files should be
* compiled and linked from your views and static HTML files.
*
* (Note that you can take advantage of Grunt-style wildcard/glob/splat expressions
* for matching multiple files, and the ! prefix for excluding files.)
*/
// Path to public folder
var tmpPath = '.tmp/public/';
// CSS files to inject in order
//
// (if you're using LESS with the built-in default config, you'll want
// to change `assets/styles/importer.less` instead.)
var cssFilesToInject = [
'styles/bootstrap.min.css',
'styles/bootstrap-theme.css'
];
// Client-side javascript files to inject in order
// (uses Grunt-style wildcard/glob/splat expressions)
var jsFilesToInject = [
// Load sails.io before everything else
'js/dependencies/sails.io.js',
'js/dependencies/angular.js',
'js/dependencies/angular-translate.min.js',
'js/dependencies/jquery.min.js',
'js/dependencies/bootstrap.min.js',
'js/dependencies/ui-bootstrap.min.js',
'js/dependencies/ui-bootstrap-tpls.min.js',
'js/dependencies/angular-translate.min.js',
'js/dependencies/smart-table.min.js',
'js/app.js'
// Dependencies like jQuery, or Angular are brought in here
// All of the rest of your client-side js files
// will be injected here in no particular order.
// Use the "exclude" operator to ignore files
// '!js/ignore/these/files/*.js'
];
// Client-side HTML templates are injected using the sources below
// The ordering of these templates shouldn't matter.
// (uses Grunt-style wildcard/glob/splat expressions)
//
// By default, Sails uses JST templates and precompiles them into
// functions for you. If you want to use jade, handlebars, dust, etc.,
// with the linker, no problem-- you'll just want to make sure the precompiled
// templates get spit out to the same file. Be sure and check out `tasks/README.md`
// for information on customizing and installing new tasks.
var templateFilesToInject = [
'templates/**/*.html'
];
// Prefix relative paths to source files so they point to the proper locations
// (i.e. where the other Grunt tasks spit them out, or in some cases, where
// they reside in the first place)
module.exports.cssFilesToInject = cssFilesToInject.map(transformPath);
module.exports.jsFilesToInject = jsFilesToInject.map(transformPath);
module.exports.templateFilesToInject = templateFilesToInject.map(transformPath);
// Transform paths relative to the "assets" folder to be relative to the public
// folder, preserving "exclude" operators.
function | (path) {
return (path.substring(0,1) == '!') ? ('!' + tmpPath + path.substring(1)) : (tmpPath + path);
}
| transformPath | identifier_name |
GroupView.js | var GroupView = function(json) {
"use strict";
var template;
if (!json.$t) |
return template;
};
| {
var albums = [];
var a, album_id, i;
for (album_id in json.all_songs_for_sid) {
a = json.all_songs_for_sid[album_id][0].albums[0];
// cut off a circular memory reference quick-like
json.all_songs_for_sid[album_id][0].albums = null;
a.songs = json.all_songs_for_sid[album_id].sort(SongsTableSorting);
for (i = 0; i < a.songs.length; i++) {
a.songs[i].artists = JSON.parse(a.songs[i].artist_parseable);
}
albums.push(a);
}
albums.sort(SongsTableAlbumSort);
template = RWTemplates.detail.group({ "group": json, "albums": albums }, MOBILE ? null : document.createElement("div"));
var j;
for (i = 0; i < albums.length; i++) {
for (j = 0; j < albums[i].songs.length; j++) {
Fave.register(albums[i].songs[j]);
Rating.register(albums[i].songs[j]);
if (albums[i].songs[j].requestable) {
Requests.make_clickable(albums[i].songs[j].$t.title, albums[i].songs[j].id);
}
SongsTableDetail(albums[i].songs[j], ((i == albums.length - 1) && (j > albums[i].songs.length - 4)));
}
}
template._header_text = json.name;
MultiAlbumKeyNav(template, albums);
} | conditional_block |
GroupView.js | var GroupView = function(json) {
"use strict";
var template;
if (!json.$t) {
var albums = [];
var a, album_id, i;
for (album_id in json.all_songs_for_sid) {
a = json.all_songs_for_sid[album_id][0].albums[0];
// cut off a circular memory reference quick-like
json.all_songs_for_sid[album_id][0].albums = null; | albums.push(a);
}
albums.sort(SongsTableAlbumSort);
template = RWTemplates.detail.group({ "group": json, "albums": albums }, MOBILE ? null : document.createElement("div"));
var j;
for (i = 0; i < albums.length; i++) {
for (j = 0; j < albums[i].songs.length; j++) {
Fave.register(albums[i].songs[j]);
Rating.register(albums[i].songs[j]);
if (albums[i].songs[j].requestable) {
Requests.make_clickable(albums[i].songs[j].$t.title, albums[i].songs[j].id);
}
SongsTableDetail(albums[i].songs[j], ((i == albums.length - 1) && (j > albums[i].songs.length - 4)));
}
}
template._header_text = json.name;
MultiAlbumKeyNav(template, albums);
}
return template;
}; | a.songs = json.all_songs_for_sid[album_id].sort(SongsTableSorting);
for (i = 0; i < a.songs.length; i++) {
a.songs[i].artists = JSON.parse(a.songs[i].artist_parseable);
} | random_line_split |
errors.spec.ts | import { expect } from "chai";
import { basename } from "path";
import { coerceAsError, ErrorWithCause } from "df/common/errors/errors";
import { suite, test } from "df/testing";
suite(basename(__filename), () => {
suite("ErrorWithCause", () => {
for (const testCase of [
{ name: "with message", message: "an error was thrown!" },
{ name: "without message" }
]) {
test(`by default, acts the same as Error, ${testCase.name}`, () => {
const errorWithCause = new ErrorWithCause(testCase.message);
const normalError = new Error(testCase.message);
expect(errorWithCause.message).eql(normalError.message);
expect(errorWithCause.stack).eql(
normalError.stack.replace(
/errors\.spec\.ts:\d{1,3}:\d{1,3}/,
errorWithCause.stack.match(/errors\.spec\.ts:\d{1,3}:\d{1,3}/)[0]
)
);
expect(errorWithCause.toString()).eql(normalError.toString());
});
}
test("stack includes cause stack", () => {
const cause = new Error("some other error"); | expect(errorWithCause.stack.endsWith(cause.stack)).eql(true);
});
});
suite("coerceAsError", () => {
test("preserves original error", () => {
const originalError = new ErrorWithCause(new Error("cause"));
const coercedError = coerceAsError(originalError);
expect(coercedError).equals(originalError);
});
test("coerces error like objects", () => {
const originalError = {
message: "message",
stack: "stack",
name: "name"
};
const coercedError = coerceAsError(originalError);
expect(coercedError.message).equals("message");
expect(coercedError.stack).equals("stack");
expect(coercedError.name).equals("name");
});
test("coerces non error types", () => {
const originalError = "string";
const coercedError = coerceAsError(originalError);
expect(coercedError.message).equals("string");
expect(coercedError instanceof Error).equals(true);
});
});
}); | const errorWithCause = new ErrorWithCause("top-level error", cause);
// Full stacktrace should be double the length of a single Error's stacktrace.
expect(errorWithCause.stack.split("\n").length).eql(cause.stack.split("\n").length * 2);
expect(errorWithCause.stack.startsWith("Error: top-level error")).eql(true); | random_line_split |
transitiveExportImports.ts | /// <reference path='fourslash.ts'/>
// @Filename: a.ts
////class [|{| "isWriteAccess": true, "isDefinition": true |}A|] {
| ////}
////export = [|A|];
// @Filename: b.ts
////export import [|{| "isWriteAccess": true, "isDefinition": true |}b|] = require('./a');
// @Filename: c.ts
////import [|{| "isWriteAccess": true, "isDefinition": true |}b|] = require('./b');
////var a = new [|b|]./**/[|b|]();
goTo.marker();
verify.quickInfoExists();
verify.noErrors();
const [a0, a1, b0, c0, c1, c2] = test.ranges();
const aRanges = [a0, a1];
const bRanges = [b0, c2];
const cRanges = [c0, c1];
const bGroup = { definition: "import b = require('./a')", ranges: bRanges }
verify.referenceGroups(aRanges, [
{ definition: "class A", ranges: aRanges },
bGroup
]);
verify.referenceGroups(b0, [bGroup]);
verify.referenceGroups(c2, [{ ...bGroup, definition: "(alias) new b.b(): b.b\nimport b.b = require('./a')"}]);
verify.singleReferenceGroup("import b = require('./b')", cRanges);
verify.rangesAreRenameLocations(aRanges);
verify.rangesAreRenameLocations(bRanges);
verify.rangesAreRenameLocations(cRanges); | random_line_split | |
trends.ts | export default [
"cats",
"dogs",
"birth-control",
"the police",
"teachers",
"babies",
"white people",
"purple people",
"fire fighters",
"hamsters",
"macaroni",
"kangaroos",
"politicians",
"hospitals",
"girlfriends",
"boyfriends",
"exercises",
"eating dinner",
"pool parties",
"scooters", | "skateboards",
"apples",
"oranges",
"hotdogs",
"hamburgers",
"fat people",
"skinny people",
"doors",
"houses",
"cigars",
"marijuanas",
"bands",
"popcorn",
"sodas",
"movies",
"blind people",
"elephants",
"shoes",
"hippies",
"beards",
"eyeballs",
"hands",
"noses",
"farts",
"computers",
"hackers",
"men",
"women",
"actors",
"actresses",
"pencils",
"fries",
"fires",
"lights",
"cities",
"websites",
"hopes",
"dreams",
"subs",
"hamsters",
"keyboards",
"phones",
"moms",
"dads",
"grandparents",
"old people",
"millenials",
"wars",
"christians",
"muslims",
"liberals",
"rednecks",
"neo-nazis",
"snow-flakes",
"ducks",
"colds",
"fevers",
"pancakes",
"boogers",
"white people",
"black people",
"red people",
"green people",
"televisions",
"haters",
"bugs",
"basketballs",
"sweatshirts",
"clothes",
"donuts",
"dinosaurs",
"bosses",
"co-workers",
"snakes",
"fingers",
"coats",
"jellies",
"essays",
"toys",
"marbles",
"grenades",
"bombs",
"guns",
"bicycles",
"tricycles",
"indians",
"paraplegics",
"nurses",
"doctors",
"maids",
"mexican people",
"drinks",
"bananas",
"keys",
"chairs",
"couches",
"lions",
"video games",
"mountains",
"trees",
"plants",
"flowers",
"Tyranosaurus",
"parties",
"birthdays",
"republicans",
"democrats",
"presidents",
"dictators",
]; | random_line_split | |
librarylogger.py | # Copyright 2008-2015 Nokia Solutions and Networks
#
# 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.
"""Implementation of the public test library logging API.
This is exposed via :py:mod:`robot.api.logger`. Implementation must reside
here to avoid cyclic imports.
"""
import sys
import threading
from robot.errors import DataError
from robot.utils import unic, encode_output
from .logger import LOGGER
from .loggerhelper import Message
LOGGING_THREADS = ('MainThread', 'RobotFrameworkTimeoutThread')
def write(msg, level, html=False):
# Callable messages allow lazy logging internally, but we don't want to
# expose this functionality publicly. See the following issue for details:
# http://code.google.com/p/robotframework/issues/detail?id=1505
|
def trace(msg, html=False):
write(msg, 'TRACE', html)
def debug(msg, html=False):
write(msg, 'DEBUG', html)
def info(msg, html=False, also_console=False):
write(msg, 'INFO', html)
if also_console:
console(msg)
def warn(msg, html=False):
write(msg, 'WARN', html)
def error(msg, html=False):
write(msg, 'ERROR', html)
def console(msg, newline=True, stream='stdout'):
msg = unic(msg)
if newline:
msg += '\n'
stream = sys.__stdout__ if stream.lower() != 'stderr' else sys.__stderr__
stream.write(encode_output(msg))
stream.flush()
| if callable(msg):
msg = unic(msg)
if level.upper() not in ('TRACE', 'DEBUG', 'INFO', 'HTML', 'WARN', 'ERROR'):
raise DataError("Invalid log level '%s'." % level)
if threading.currentThread().getName() in LOGGING_THREADS:
LOGGER.log_message(Message(msg, level, html)) | identifier_body |
librarylogger.py | # Copyright 2008-2015 Nokia Solutions and Networks
#
# 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.
"""Implementation of the public test library logging API.
This is exposed via :py:mod:`robot.api.logger`. Implementation must reside
here to avoid cyclic imports.
"""
import sys
import threading
from robot.errors import DataError
from robot.utils import unic, encode_output
from .logger import LOGGER
from .loggerhelper import Message
LOGGING_THREADS = ('MainThread', 'RobotFrameworkTimeoutThread')
def write(msg, level, html=False):
# Callable messages allow lazy logging internally, but we don't want to
# expose this functionality publicly. See the following issue for details:
# http://code.google.com/p/robotframework/issues/detail?id=1505
if callable(msg):
msg = unic(msg)
if level.upper() not in ('TRACE', 'DEBUG', 'INFO', 'HTML', 'WARN', 'ERROR'):
raise DataError("Invalid log level '%s'." % level)
if threading.currentThread().getName() in LOGGING_THREADS:
|
def trace(msg, html=False):
write(msg, 'TRACE', html)
def debug(msg, html=False):
write(msg, 'DEBUG', html)
def info(msg, html=False, also_console=False):
write(msg, 'INFO', html)
if also_console:
console(msg)
def warn(msg, html=False):
write(msg, 'WARN', html)
def error(msg, html=False):
write(msg, 'ERROR', html)
def console(msg, newline=True, stream='stdout'):
msg = unic(msg)
if newline:
msg += '\n'
stream = sys.__stdout__ if stream.lower() != 'stderr' else sys.__stderr__
stream.write(encode_output(msg))
stream.flush()
| LOGGER.log_message(Message(msg, level, html)) | conditional_block |
librarylogger.py | # Copyright 2008-2015 Nokia Solutions and Networks
#
# 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.
"""Implementation of the public test library logging API.
This is exposed via :py:mod:`robot.api.logger`. Implementation must reside
here to avoid cyclic imports.
"""
import sys
import threading
from robot.errors import DataError
from robot.utils import unic, encode_output
from .logger import LOGGER
from .loggerhelper import Message
LOGGING_THREADS = ('MainThread', 'RobotFrameworkTimeoutThread')
| # http://code.google.com/p/robotframework/issues/detail?id=1505
if callable(msg):
msg = unic(msg)
if level.upper() not in ('TRACE', 'DEBUG', 'INFO', 'HTML', 'WARN', 'ERROR'):
raise DataError("Invalid log level '%s'." % level)
if threading.currentThread().getName() in LOGGING_THREADS:
LOGGER.log_message(Message(msg, level, html))
def trace(msg, html=False):
write(msg, 'TRACE', html)
def debug(msg, html=False):
write(msg, 'DEBUG', html)
def info(msg, html=False, also_console=False):
write(msg, 'INFO', html)
if also_console:
console(msg)
def warn(msg, html=False):
write(msg, 'WARN', html)
def error(msg, html=False):
write(msg, 'ERROR', html)
def console(msg, newline=True, stream='stdout'):
msg = unic(msg)
if newline:
msg += '\n'
stream = sys.__stdout__ if stream.lower() != 'stderr' else sys.__stderr__
stream.write(encode_output(msg))
stream.flush() |
def write(msg, level, html=False):
# Callable messages allow lazy logging internally, but we don't want to
# expose this functionality publicly. See the following issue for details: | random_line_split |
librarylogger.py | # Copyright 2008-2015 Nokia Solutions and Networks
#
# 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.
"""Implementation of the public test library logging API.
This is exposed via :py:mod:`robot.api.logger`. Implementation must reside
here to avoid cyclic imports.
"""
import sys
import threading
from robot.errors import DataError
from robot.utils import unic, encode_output
from .logger import LOGGER
from .loggerhelper import Message
LOGGING_THREADS = ('MainThread', 'RobotFrameworkTimeoutThread')
def write(msg, level, html=False):
# Callable messages allow lazy logging internally, but we don't want to
# expose this functionality publicly. See the following issue for details:
# http://code.google.com/p/robotframework/issues/detail?id=1505
if callable(msg):
msg = unic(msg)
if level.upper() not in ('TRACE', 'DEBUG', 'INFO', 'HTML', 'WARN', 'ERROR'):
raise DataError("Invalid log level '%s'." % level)
if threading.currentThread().getName() in LOGGING_THREADS:
LOGGER.log_message(Message(msg, level, html))
def | (msg, html=False):
write(msg, 'TRACE', html)
def debug(msg, html=False):
write(msg, 'DEBUG', html)
def info(msg, html=False, also_console=False):
write(msg, 'INFO', html)
if also_console:
console(msg)
def warn(msg, html=False):
write(msg, 'WARN', html)
def error(msg, html=False):
write(msg, 'ERROR', html)
def console(msg, newline=True, stream='stdout'):
msg = unic(msg)
if newline:
msg += '\n'
stream = sys.__stdout__ if stream.lower() != 'stderr' else sys.__stderr__
stream.write(encode_output(msg))
stream.flush()
| trace | identifier_name |
conditional-compile.rs | // xfail-fast
// Copyright 2012 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.
// Crate use statements
#[cfg(bogus)]
use flippity;
#[cfg(bogus)]
static b: bool = false;
static b: bool = true;
mod rustrt {
#[cfg(bogus)]
extern {
// This symbol doesn't exist and would be a link error if this
// module was translated
pub fn bogus();
}
extern {}
}
#[cfg(bogus)]
type t = int;
type t = bool;
#[cfg(bogus)]
enum tg { foo, }
enum tg { bar, }
#[cfg(bogus)]
struct r {
i: int,
}
#[cfg(bogus)]
fn r(i:int) -> r {
r {
i: i
}
}
struct | {
i: int,
}
fn r(i:int) -> r {
r {
i: i
}
}
#[cfg(bogus)]
mod m {
// This needs to parse but would fail in typeck. Since it's not in
// the current config it should not be typechecked.
pub fn bogus() { return 0; }
}
mod m {
// Submodules have slightly different code paths than the top-level
// module, so let's make sure this jazz works here as well
#[cfg(bogus)]
pub fn f() { }
pub fn f() { }
}
// Since the bogus configuration isn't defined main will just be
// parsed, but nothing further will be done with it
#[cfg(bogus)]
pub fn main() { fail!() }
pub fn main() {
// Exercise some of the configured items in ways that wouldn't be possible
// if they had the bogus definition
assert!((b));
let _x: t = true;
let _y: tg = bar;
test_in_fn_ctxt();
}
fn test_in_fn_ctxt() {
#[cfg(bogus)]
fn f() { fail!() }
fn f() { }
f();
#[cfg(bogus)]
static i: int = 0;
static i: int = 1;
assert_eq!(i, 1);
}
mod test_foreign_items {
pub mod rustrt {
extern {
#[cfg(bogus)]
pub fn write() -> ~str;
pub fn write() -> ~str;
}
}
}
mod test_use_statements {
#[cfg(bogus)]
use flippity_foo;
}
mod test_methods {
struct Foo {
bar: uint
}
impl Fooable for Foo {
#[cfg(bogus)]
fn what(&self) { }
fn what(&self) { }
#[cfg(bogus)]
fn the(&self) { }
fn the(&self) { }
}
trait Fooable {
#[cfg(bogus)]
fn what(&self);
fn what(&self);
#[cfg(bogus)]
fn the(&self);
fn the(&self);
}
}
| r | identifier_name |
conditional-compile.rs | // xfail-fast
// Copyright 2012 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.
// Crate use statements
#[cfg(bogus)]
use flippity;
#[cfg(bogus)]
static b: bool = false;
static b: bool = true;
mod rustrt {
#[cfg(bogus)]
extern {
// This symbol doesn't exist and would be a link error if this
// module was translated
pub fn bogus();
}
extern {}
}
#[cfg(bogus)]
type t = int;
type t = bool;
#[cfg(bogus)]
enum tg { foo, }
enum tg { bar, }
#[cfg(bogus)]
struct r {
i: int,
}
#[cfg(bogus)]
fn r(i:int) -> r {
r {
i: i
}
}
struct r {
i: int,
}
fn r(i:int) -> r {
r {
i: i
}
}
#[cfg(bogus)]
mod m {
// This needs to parse but would fail in typeck. Since it's not in
// the current config it should not be typechecked.
pub fn bogus() { return 0; }
}
mod m {
// Submodules have slightly different code paths than the top-level
// module, so let's make sure this jazz works here as well
#[cfg(bogus)]
pub fn f() { }
pub fn f() { }
}
// Since the bogus configuration isn't defined main will just be
// parsed, but nothing further will be done with it
#[cfg(bogus)]
pub fn main() { fail!() }
pub fn main() {
// Exercise some of the configured items in ways that wouldn't be possible
// if they had the bogus definition
assert!((b));
let _x: t = true;
let _y: tg = bar;
test_in_fn_ctxt();
}
fn test_in_fn_ctxt() {
#[cfg(bogus)]
fn f() { fail!() }
fn f() { }
f();
#[cfg(bogus)]
static i: int = 0;
static i: int = 1;
assert_eq!(i, 1);
}
mod test_foreign_items {
pub mod rustrt {
extern {
#[cfg(bogus)]
pub fn write() -> ~str;
pub fn write() -> ~str;
}
}
}
mod test_use_statements {
#[cfg(bogus)]
use flippity_foo;
}
| impl Fooable for Foo {
#[cfg(bogus)]
fn what(&self) { }
fn what(&self) { }
#[cfg(bogus)]
fn the(&self) { }
fn the(&self) { }
}
trait Fooable {
#[cfg(bogus)]
fn what(&self);
fn what(&self);
#[cfg(bogus)]
fn the(&self);
fn the(&self);
}
} | mod test_methods {
struct Foo {
bar: uint
}
| random_line_split |
conditional-compile.rs | // xfail-fast
// Copyright 2012 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.
// Crate use statements
#[cfg(bogus)]
use flippity;
#[cfg(bogus)]
static b: bool = false;
static b: bool = true;
mod rustrt {
#[cfg(bogus)]
extern {
// This symbol doesn't exist and would be a link error if this
// module was translated
pub fn bogus();
}
extern {}
}
#[cfg(bogus)]
type t = int;
type t = bool;
#[cfg(bogus)]
enum tg { foo, }
enum tg { bar, }
#[cfg(bogus)]
struct r {
i: int,
}
#[cfg(bogus)]
fn r(i:int) -> r {
r {
i: i
}
}
struct r {
i: int,
}
fn r(i:int) -> r {
r {
i: i
}
}
#[cfg(bogus)]
mod m {
// This needs to parse but would fail in typeck. Since it's not in
// the current config it should not be typechecked.
pub fn bogus() { return 0; }
}
mod m {
// Submodules have slightly different code paths than the top-level
// module, so let's make sure this jazz works here as well
#[cfg(bogus)]
pub fn f() { }
pub fn f() { }
}
// Since the bogus configuration isn't defined main will just be
// parsed, but nothing further will be done with it
#[cfg(bogus)]
pub fn main() { fail!() }
pub fn main() {
// Exercise some of the configured items in ways that wouldn't be possible
// if they had the bogus definition
assert!((b));
let _x: t = true;
let _y: tg = bar;
test_in_fn_ctxt();
}
fn test_in_fn_ctxt() {
#[cfg(bogus)]
fn f() { fail!() }
fn f() { }
f();
#[cfg(bogus)]
static i: int = 0;
static i: int = 1;
assert_eq!(i, 1);
}
mod test_foreign_items {
pub mod rustrt {
extern {
#[cfg(bogus)]
pub fn write() -> ~str;
pub fn write() -> ~str;
}
}
}
mod test_use_statements {
#[cfg(bogus)]
use flippity_foo;
}
mod test_methods {
struct Foo {
bar: uint
}
impl Fooable for Foo {
#[cfg(bogus)]
fn what(&self) { }
fn what(&self) |
#[cfg(bogus)]
fn the(&self) { }
fn the(&self) { }
}
trait Fooable {
#[cfg(bogus)]
fn what(&self);
fn what(&self);
#[cfg(bogus)]
fn the(&self);
fn the(&self);
}
}
| { } | identifier_body |
unused_async.rs | use clippy_utils::diagnostics::span_lint_and_help;
use rustc_hir::intravisit::{walk_expr, walk_fn, FnKind, NestedVisitorMap, Visitor};
use rustc_hir::{Body, Expr, ExprKind, FnDecl, FnHeader, HirId, IsAsync, YieldSource};
use rustc_lint::{LateContext, LateLintPass};
use rustc_middle::hir::map::Map;
use rustc_session::{declare_lint_pass, declare_tool_lint};
use rustc_span::Span;
declare_clippy_lint! {
/// ### What it does
/// Checks for functions that are declared `async` but have no `.await`s inside of them.
///
/// ### Why is this bad?
/// Async functions with no async code create overhead, both mentally and computationally.
/// Callers of async methods either need to be calling from an async function themselves or run it on an executor, both of which
/// causes runtime overhead and hassle for the caller.
///
/// ### Example
/// ```rust
/// // Bad
/// async fn get_random_number() -> i64 {
/// 4 // Chosen by fair dice roll. Guaranteed to be random.
/// }
/// let number_future = get_random_number();
///
/// // Good
/// fn get_random_number_improved() -> i64 {
/// 4 // Chosen by fair dice roll. Guaranteed to be random.
/// }
/// let number_future = async { get_random_number_improved() };
/// ```
pub UNUSED_ASYNC,
pedantic,
"finds async functions with no await statements"
}
declare_lint_pass!(UnusedAsync => [UNUSED_ASYNC]);
struct AsyncFnVisitor<'a, 'tcx> {
cx: &'a LateContext<'tcx>,
found_await: bool,
}
impl<'a, 'tcx> Visitor<'tcx> for AsyncFnVisitor<'a, 'tcx> {
type Map = Map<'tcx>;
fn visit_expr(&mut self, ex: &'tcx Expr<'tcx>) {
if let ExprKind::Yield(_, YieldSource::Await { .. }) = ex.kind {
self.found_await = true;
}
walk_expr(self, ex);
}
fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
NestedVisitorMap::OnlyBodies(self.cx.tcx.hir())
}
}
impl<'tcx> LateLintPass<'tcx> for UnusedAsync {
fn | (
&mut self,
cx: &LateContext<'tcx>,
fn_kind: FnKind<'tcx>,
fn_decl: &'tcx FnDecl<'tcx>,
body: &Body<'tcx>,
span: Span,
hir_id: HirId,
) {
if let FnKind::ItemFn(_, _, FnHeader { asyncness, .. }, _) = &fn_kind {
if matches!(asyncness, IsAsync::Async) {
let mut visitor = AsyncFnVisitor { cx, found_await: false };
walk_fn(&mut visitor, fn_kind, fn_decl, body.id(), span, hir_id);
if !visitor.found_await {
span_lint_and_help(
cx,
UNUSED_ASYNC,
span,
"unused `async` for function with no await statements",
None,
"consider removing the `async` from this function",
);
}
}
}
}
}
| check_fn | identifier_name |
unused_async.rs | use clippy_utils::diagnostics::span_lint_and_help;
use rustc_hir::intravisit::{walk_expr, walk_fn, FnKind, NestedVisitorMap, Visitor};
use rustc_hir::{Body, Expr, ExprKind, FnDecl, FnHeader, HirId, IsAsync, YieldSource};
use rustc_lint::{LateContext, LateLintPass};
use rustc_middle::hir::map::Map;
use rustc_session::{declare_lint_pass, declare_tool_lint};
use rustc_span::Span;
declare_clippy_lint! {
/// ### What it does
/// Checks for functions that are declared `async` but have no `.await`s inside of them.
///
/// ### Why is this bad?
/// Async functions with no async code create overhead, both mentally and computationally.
/// Callers of async methods either need to be calling from an async function themselves or run it on an executor, both of which
/// causes runtime overhead and hassle for the caller.
///
/// ### Example
/// ```rust
/// // Bad
/// async fn get_random_number() -> i64 {
/// 4 // Chosen by fair dice roll. Guaranteed to be random.
/// }
/// let number_future = get_random_number();
///
/// // Good
/// fn get_random_number_improved() -> i64 {
/// 4 // Chosen by fair dice roll. Guaranteed to be random.
/// }
/// let number_future = async { get_random_number_improved() };
/// ```
pub UNUSED_ASYNC,
pedantic,
"finds async functions with no await statements"
}
declare_lint_pass!(UnusedAsync => [UNUSED_ASYNC]);
struct AsyncFnVisitor<'a, 'tcx> {
cx: &'a LateContext<'tcx>,
found_await: bool,
}
impl<'a, 'tcx> Visitor<'tcx> for AsyncFnVisitor<'a, 'tcx> {
type Map = Map<'tcx>;
fn visit_expr(&mut self, ex: &'tcx Expr<'tcx>) {
if let ExprKind::Yield(_, YieldSource::Await { .. }) = ex.kind {
self.found_await = true;
}
walk_expr(self, ex);
}
fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
NestedVisitorMap::OnlyBodies(self.cx.tcx.hir())
}
}
impl<'tcx> LateLintPass<'tcx> for UnusedAsync {
fn check_fn(
&mut self,
cx: &LateContext<'tcx>,
fn_kind: FnKind<'tcx>,
fn_decl: &'tcx FnDecl<'tcx>,
body: &Body<'tcx>,
span: Span,
hir_id: HirId,
) {
if let FnKind::ItemFn(_, _, FnHeader { asyncness, .. }, _) = &fn_kind {
if matches!(asyncness, IsAsync::Async) {
let mut visitor = AsyncFnVisitor { cx, found_await: false };
walk_fn(&mut visitor, fn_kind, fn_decl, body.id(), span, hir_id);
if !visitor.found_await {
span_lint_and_help(
cx,
UNUSED_ASYNC,
span,
"unused `async` for function with no await statements",
None,
"consider removing the `async` from this function",
);
}
}
}
} | } | random_line_split | |
unused_async.rs | use clippy_utils::diagnostics::span_lint_and_help;
use rustc_hir::intravisit::{walk_expr, walk_fn, FnKind, NestedVisitorMap, Visitor};
use rustc_hir::{Body, Expr, ExprKind, FnDecl, FnHeader, HirId, IsAsync, YieldSource};
use rustc_lint::{LateContext, LateLintPass};
use rustc_middle::hir::map::Map;
use rustc_session::{declare_lint_pass, declare_tool_lint};
use rustc_span::Span;
declare_clippy_lint! {
/// ### What it does
/// Checks for functions that are declared `async` but have no `.await`s inside of them.
///
/// ### Why is this bad?
/// Async functions with no async code create overhead, both mentally and computationally.
/// Callers of async methods either need to be calling from an async function themselves or run it on an executor, both of which
/// causes runtime overhead and hassle for the caller.
///
/// ### Example
/// ```rust
/// // Bad
/// async fn get_random_number() -> i64 {
/// 4 // Chosen by fair dice roll. Guaranteed to be random.
/// }
/// let number_future = get_random_number();
///
/// // Good
/// fn get_random_number_improved() -> i64 {
/// 4 // Chosen by fair dice roll. Guaranteed to be random.
/// }
/// let number_future = async { get_random_number_improved() };
/// ```
pub UNUSED_ASYNC,
pedantic,
"finds async functions with no await statements"
}
declare_lint_pass!(UnusedAsync => [UNUSED_ASYNC]);
struct AsyncFnVisitor<'a, 'tcx> {
cx: &'a LateContext<'tcx>,
found_await: bool,
}
impl<'a, 'tcx> Visitor<'tcx> for AsyncFnVisitor<'a, 'tcx> {
type Map = Map<'tcx>;
fn visit_expr(&mut self, ex: &'tcx Expr<'tcx>) {
if let ExprKind::Yield(_, YieldSource::Await { .. }) = ex.kind {
self.found_await = true;
}
walk_expr(self, ex);
}
fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
NestedVisitorMap::OnlyBodies(self.cx.tcx.hir())
}
}
impl<'tcx> LateLintPass<'tcx> for UnusedAsync {
fn check_fn(
&mut self,
cx: &LateContext<'tcx>,
fn_kind: FnKind<'tcx>,
fn_decl: &'tcx FnDecl<'tcx>,
body: &Body<'tcx>,
span: Span,
hir_id: HirId,
) {
if let FnKind::ItemFn(_, _, FnHeader { asyncness, .. }, _) = &fn_kind |
}
}
| {
if matches!(asyncness, IsAsync::Async) {
let mut visitor = AsyncFnVisitor { cx, found_await: false };
walk_fn(&mut visitor, fn_kind, fn_decl, body.id(), span, hir_id);
if !visitor.found_await {
span_lint_and_help(
cx,
UNUSED_ASYNC,
span,
"unused `async` for function with no await statements",
None,
"consider removing the `async` from this function",
);
}
}
} | conditional_block |
unused_async.rs | use clippy_utils::diagnostics::span_lint_and_help;
use rustc_hir::intravisit::{walk_expr, walk_fn, FnKind, NestedVisitorMap, Visitor};
use rustc_hir::{Body, Expr, ExprKind, FnDecl, FnHeader, HirId, IsAsync, YieldSource};
use rustc_lint::{LateContext, LateLintPass};
use rustc_middle::hir::map::Map;
use rustc_session::{declare_lint_pass, declare_tool_lint};
use rustc_span::Span;
declare_clippy_lint! {
/// ### What it does
/// Checks for functions that are declared `async` but have no `.await`s inside of them.
///
/// ### Why is this bad?
/// Async functions with no async code create overhead, both mentally and computationally.
/// Callers of async methods either need to be calling from an async function themselves or run it on an executor, both of which
/// causes runtime overhead and hassle for the caller.
///
/// ### Example
/// ```rust
/// // Bad
/// async fn get_random_number() -> i64 {
/// 4 // Chosen by fair dice roll. Guaranteed to be random.
/// }
/// let number_future = get_random_number();
///
/// // Good
/// fn get_random_number_improved() -> i64 {
/// 4 // Chosen by fair dice roll. Guaranteed to be random.
/// }
/// let number_future = async { get_random_number_improved() };
/// ```
pub UNUSED_ASYNC,
pedantic,
"finds async functions with no await statements"
}
declare_lint_pass!(UnusedAsync => [UNUSED_ASYNC]);
struct AsyncFnVisitor<'a, 'tcx> {
cx: &'a LateContext<'tcx>,
found_await: bool,
}
impl<'a, 'tcx> Visitor<'tcx> for AsyncFnVisitor<'a, 'tcx> {
type Map = Map<'tcx>;
fn visit_expr(&mut self, ex: &'tcx Expr<'tcx>) {
if let ExprKind::Yield(_, YieldSource::Await { .. }) = ex.kind {
self.found_await = true;
}
walk_expr(self, ex);
}
fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
NestedVisitorMap::OnlyBodies(self.cx.tcx.hir())
}
}
impl<'tcx> LateLintPass<'tcx> for UnusedAsync {
fn check_fn(
&mut self,
cx: &LateContext<'tcx>,
fn_kind: FnKind<'tcx>,
fn_decl: &'tcx FnDecl<'tcx>,
body: &Body<'tcx>,
span: Span,
hir_id: HirId,
) |
}
| {
if let FnKind::ItemFn(_, _, FnHeader { asyncness, .. }, _) = &fn_kind {
if matches!(asyncness, IsAsync::Async) {
let mut visitor = AsyncFnVisitor { cx, found_await: false };
walk_fn(&mut visitor, fn_kind, fn_decl, body.id(), span, hir_id);
if !visitor.found_await {
span_lint_and_help(
cx,
UNUSED_ASYNC,
span,
"unused `async` for function with no await statements",
None,
"consider removing the `async` from this function",
);
}
}
}
} | identifier_body |
views.py | # This file is part of Indico.
# Copyright (C) 2002 - 2021 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from indico.util.i18n import _
from indico.web.breadcrumbs import render_breadcrumbs
from indico.web.flask.util import url_for
from indico.web.menu import get_menu_item
from indico.web.views import WPDecorated, WPJinjaMixin
class WPAdmin(WPJinjaMixin, WPDecorated):
| """Base class for admin pages."""
def __init__(self, rh, active_menu_item=None, **kwargs):
kwargs['active_menu_item'] = active_menu_item or self.sidemenu_option
WPDecorated.__init__(self, rh, **kwargs)
def _get_breadcrumbs(self):
menu_item = get_menu_item('admin-sidemenu', self._kwargs['active_menu_item'])
items = [(_('Administration'), url_for('core.admin_dashboard'))]
if menu_item:
items.append(menu_item.title)
return render_breadcrumbs(*items)
def _get_body(self, params):
return self._get_page_content(params) | identifier_body | |
views.py | # This file is part of Indico.
# Copyright (C) 2002 - 2021 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from indico.util.i18n import _
from indico.web.breadcrumbs import render_breadcrumbs
from indico.web.flask.util import url_for
from indico.web.menu import get_menu_item
from indico.web.views import WPDecorated, WPJinjaMixin
class WPAdmin(WPJinjaMixin, WPDecorated):
"""Base class for admin pages."""
def __init__(self, rh, active_menu_item=None, **kwargs):
kwargs['active_menu_item'] = active_menu_item or self.sidemenu_option
WPDecorated.__init__(self, rh, **kwargs)
def _get_breadcrumbs(self):
menu_item = get_menu_item('admin-sidemenu', self._kwargs['active_menu_item'])
items = [(_('Administration'), url_for('core.admin_dashboard'))]
if menu_item:
items.append(menu_item.title)
return render_breadcrumbs(*items)
def | (self, params):
return self._get_page_content(params)
| _get_body | identifier_name |
views.py | # This file is part of Indico.
# Copyright (C) 2002 - 2021 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from indico.util.i18n import _
from indico.web.breadcrumbs import render_breadcrumbs
from indico.web.flask.util import url_for
from indico.web.menu import get_menu_item
from indico.web.views import WPDecorated, WPJinjaMixin
class WPAdmin(WPJinjaMixin, WPDecorated):
"""Base class for admin pages."""
def __init__(self, rh, active_menu_item=None, **kwargs):
kwargs['active_menu_item'] = active_menu_item or self.sidemenu_option
WPDecorated.__init__(self, rh, **kwargs)
def _get_breadcrumbs(self):
menu_item = get_menu_item('admin-sidemenu', self._kwargs['active_menu_item'])
items = [(_('Administration'), url_for('core.admin_dashboard'))]
if menu_item:
|
return render_breadcrumbs(*items)
def _get_body(self, params):
return self._get_page_content(params)
| items.append(menu_item.title) | conditional_block |
views.py | # This file is part of Indico. | # Copyright (C) 2002 - 2021 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from indico.util.i18n import _
from indico.web.breadcrumbs import render_breadcrumbs
from indico.web.flask.util import url_for
from indico.web.menu import get_menu_item
from indico.web.views import WPDecorated, WPJinjaMixin
class WPAdmin(WPJinjaMixin, WPDecorated):
"""Base class for admin pages."""
def __init__(self, rh, active_menu_item=None, **kwargs):
kwargs['active_menu_item'] = active_menu_item or self.sidemenu_option
WPDecorated.__init__(self, rh, **kwargs)
def _get_breadcrumbs(self):
menu_item = get_menu_item('admin-sidemenu', self._kwargs['active_menu_item'])
items = [(_('Administration'), url_for('core.admin_dashboard'))]
if menu_item:
items.append(menu_item.title)
return render_breadcrumbs(*items)
def _get_body(self, params):
return self._get_page_content(params) | random_line_split | |
semioticGraph.tsx | import * as React from 'react';
import ContainerDimensions from 'react-container-dimensions';
import BoxPlot from './boxplot';
import Histogram from './histogram';
import { GraphType, IMetricSetPairGraphProps } from '../metricSetPairGraph.service';
import NoValidDataSign from './noValidDataSign';
import TimeSeries from './timeSeries';
import './semioticGraph.less';
export default class SemioticGraph extends React.Component<IMetricSetPairGraphProps> {
private fetchChart = (parentWidth: number) => {
const {
type,
metricSetPair: {
values: { control, experiment },
},
} = this.props;
const chartProps = {
...this.props,
parentWidth,
};
const filterInvalidValues = (data: number[]) => data.filter((v) => typeof v === 'number');
if (filterInvalidValues(control).length === 0 && filterInvalidValues(experiment).length === 0) {
return <NoValidDataSign />;
}
switch (type) {
case GraphType.TimeSeries:
return <TimeSeries {...chartProps} />;
case GraphType.Histogram:
return <Histogram {...chartProps} />;
case GraphType.BoxPlot:
return <BoxPlot {...chartProps} />;
default:
return null;
} | return (
<div className="semiotic-graph">
<ContainerDimensions>{({ width }: { width: number }) => this.fetchChart(width)}</ContainerDimensions>
</div>
);
}
} | };
public render() { | random_line_split |
semioticGraph.tsx | import * as React from 'react';
import ContainerDimensions from 'react-container-dimensions';
import BoxPlot from './boxplot';
import Histogram from './histogram';
import { GraphType, IMetricSetPairGraphProps } from '../metricSetPairGraph.service';
import NoValidDataSign from './noValidDataSign';
import TimeSeries from './timeSeries';
import './semioticGraph.less';
export default class SemioticGraph extends React.Component<IMetricSetPairGraphProps> {
private fetchChart = (parentWidth: number) => {
const {
type,
metricSetPair: {
values: { control, experiment },
},
} = this.props;
const chartProps = {
...this.props,
parentWidth,
};
const filterInvalidValues = (data: number[]) => data.filter((v) => typeof v === 'number');
if (filterInvalidValues(control).length === 0 && filterInvalidValues(experiment).length === 0) {
return <NoValidDataSign />;
}
switch (type) {
case GraphType.TimeSeries:
return <TimeSeries {...chartProps} />;
case GraphType.Histogram:
return <Histogram {...chartProps} />;
case GraphType.BoxPlot:
return <BoxPlot {...chartProps} />;
default:
return null;
}
};
public | () {
return (
<div className="semiotic-graph">
<ContainerDimensions>{({ width }: { width: number }) => this.fetchChart(width)}</ContainerDimensions>
</div>
);
}
}
| render | identifier_name |
semioticGraph.tsx | import * as React from 'react';
import ContainerDimensions from 'react-container-dimensions';
import BoxPlot from './boxplot';
import Histogram from './histogram';
import { GraphType, IMetricSetPairGraphProps } from '../metricSetPairGraph.service';
import NoValidDataSign from './noValidDataSign';
import TimeSeries from './timeSeries';
import './semioticGraph.less';
export default class SemioticGraph extends React.Component<IMetricSetPairGraphProps> {
private fetchChart = (parentWidth: number) => {
const {
type,
metricSetPair: {
values: { control, experiment },
},
} = this.props;
const chartProps = {
...this.props,
parentWidth,
};
const filterInvalidValues = (data: number[]) => data.filter((v) => typeof v === 'number');
if (filterInvalidValues(control).length === 0 && filterInvalidValues(experiment).length === 0) |
switch (type) {
case GraphType.TimeSeries:
return <TimeSeries {...chartProps} />;
case GraphType.Histogram:
return <Histogram {...chartProps} />;
case GraphType.BoxPlot:
return <BoxPlot {...chartProps} />;
default:
return null;
}
};
public render() {
return (
<div className="semiotic-graph">
<ContainerDimensions>{({ width }: { width: number }) => this.fetchChart(width)}</ContainerDimensions>
</div>
);
}
}
| {
return <NoValidDataSign />;
} | conditional_block |
math_improved.py | # We try to improve the previous 'math_operation.py' by reduce the code
# here we introduce a concept named list-comprehensive
# Knowledge points:
# 1. list-comprehensive, the [x for x in a-list]
# 2. dir() function to get the current environment variable names in space.
# 3. "in" check, we never user string.search() in Java, but use "in" to check string existence.
# 4. "eval()" function to run the expression
# still, we expect user to input something
user_input = raw_input("Please input a sequence of numbers, like: 1 2 3.1 2.1 -3 9: \n")
# Split user_inputed numbers into individual numbers, store it in a list.
possible_numbers = user_input.strip().split(" ")
# We user list comprehensive to get rid of "for" loop, reduce code amount.
float_numbers = [float(x) for x in possible_numbers]
# absolute numbers
absolute_numbers = [abs(x) for x in float_numbers]
# rounded numbers, in "int" style
int_numbers = [int(round(x)) for x in float_numbers]
import math
# floored numbers
floored_numbers = [math.floor(x) for x in float_numbers]
# ceilled numbers
ceil_numbers = [math.ceil(x) for x in float_numbers]
# alright, lets try to print smartly about all the numbers we have | env_variables = dir()
for var in env_variables:
if "_numbers" in var:
print var, ":", eval(var) | # use the function "dir()" | random_line_split |
math_improved.py | # We try to improve the previous 'math_operation.py' by reduce the code
# here we introduce a concept named list-comprehensive
# Knowledge points:
# 1. list-comprehensive, the [x for x in a-list]
# 2. dir() function to get the current environment variable names in space.
# 3. "in" check, we never user string.search() in Java, but use "in" to check string existence.
# 4. "eval()" function to run the expression
# still, we expect user to input something
user_input = raw_input("Please input a sequence of numbers, like: 1 2 3.1 2.1 -3 9: \n")
# Split user_inputed numbers into individual numbers, store it in a list.
possible_numbers = user_input.strip().split(" ")
# We user list comprehensive to get rid of "for" loop, reduce code amount.
float_numbers = [float(x) for x in possible_numbers]
# absolute numbers
absolute_numbers = [abs(x) for x in float_numbers]
# rounded numbers, in "int" style
int_numbers = [int(round(x)) for x in float_numbers]
import math
# floored numbers
floored_numbers = [math.floor(x) for x in float_numbers]
# ceilled numbers
ceil_numbers = [math.ceil(x) for x in float_numbers]
# alright, lets try to print smartly about all the numbers we have
# use the function "dir()"
env_variables = dir()
for var in env_variables:
if "_numbers" in var:
| print var, ":", eval(var) | conditional_block | |
dump_dependency_json.py | # Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from __future__ import print_function
import os
import gyp
import gyp.common
import gyp.msvs_emulation
import json
generator_supports_multiple_toolsets = True
generator_wants_static_library_dependencies_adjusted = False
generator_filelist_paths = {
}
generator_default_variables = {
}
for dirname in ['INTERMEDIATE_DIR', 'SHARED_INTERMEDIATE_DIR', 'PRODUCT_DIR',
'LIB_DIR', 'SHARED_LIB_DIR']:
# Some gyp steps fail if these are empty(!).
generator_default_variables[dirname] = 'dir'
for unused in ['RULE_INPUT_PATH', 'RULE_INPUT_ROOT', 'RULE_INPUT_NAME',
'RULE_INPUT_DIRNAME', 'RULE_INPUT_EXT',
'EXECUTABLE_PREFIX', 'EXECUTABLE_SUFFIX',
'STATIC_LIB_PREFIX', 'STATIC_LIB_SUFFIX',
'SHARED_LIB_PREFIX', 'SHARED_LIB_SUFFIX',
'CONFIGURATION_NAME']:
generator_default_variables[unused] = ''
def CalculateVariables(default_variables, params):
generator_flags = params.get('generator_flags', {})
for key, val in generator_flags.items():
default_variables.setdefault(key, val)
default_variables.setdefault('OS', gyp.common.GetFlavor(params))
flavor = gyp.common.GetFlavor(params)
if flavor =='win':
# # Copy additional generator configuration data from VS, which is shared by the Windows Ninja generator.
# import gyp.generator.msvs as msvs_generator
# generator_additional_non_configuration_keys = getattr(msvs_generator, 'generator_additional_non_configuration_keys', [])
# generator_additional_path_sections = getattr(msvs_generator, 'generator_additional_path_sections', [])
gyp.msvs_emulation.CalculateCommonVariables(default_variables, params)
def CalculateGeneratorInputInfo(params):
"""Calculate the generator specific info that gets fed to input (called by
gyp)."""
generator_flags = params.get('generator_flags', {})
if generator_flags.get('adjust_static_libraries', False):
global generator_wants_static_library_dependencies_adjusted
generator_wants_static_library_dependencies_adjusted = True
toplevel = params['options'].toplevel_dir
generator_dir = os.path.relpath(params['options'].generator_output or '.')
# output_dir: relative path from generator_dir to the build directory.
output_dir = generator_flags.get('output_dir', 'out')
qualified_out_dir = os.path.normpath(os.path.join(
toplevel, generator_dir, output_dir, 'gypfiles'))
global generator_filelist_paths
generator_filelist_paths = {
'toplevel': toplevel,
'qualified_out_dir': qualified_out_dir,
}
def GenerateOutput(target_list, target_dicts, _, params):
# Map of target -> list of targets it depends on. |
# Queue of targets to visit.
targets_to_visit = target_list[:]
while len(targets_to_visit) > 0:
target = targets_to_visit.pop()
if target in edges:
continue
edges[target] = []
for dep in target_dicts[target].get('dependencies', []):
edges[target].append(dep)
targets_to_visit.append(dep)
try:
filepath = params['generator_flags']['output_dir']
except KeyError:
filepath = '.'
filename = os.path.join(filepath, 'dump.json')
f = open(filename, 'w')
json.dump(edges, f)
f.close()
print('Wrote json to %s.' % filename) | edges = {} | random_line_split |
dump_dependency_json.py | # Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from __future__ import print_function
import os
import gyp
import gyp.common
import gyp.msvs_emulation
import json
generator_supports_multiple_toolsets = True
generator_wants_static_library_dependencies_adjusted = False
generator_filelist_paths = {
}
generator_default_variables = {
}
for dirname in ['INTERMEDIATE_DIR', 'SHARED_INTERMEDIATE_DIR', 'PRODUCT_DIR',
'LIB_DIR', 'SHARED_LIB_DIR']:
# Some gyp steps fail if these are empty(!).
generator_default_variables[dirname] = 'dir'
for unused in ['RULE_INPUT_PATH', 'RULE_INPUT_ROOT', 'RULE_INPUT_NAME',
'RULE_INPUT_DIRNAME', 'RULE_INPUT_EXT',
'EXECUTABLE_PREFIX', 'EXECUTABLE_SUFFIX',
'STATIC_LIB_PREFIX', 'STATIC_LIB_SUFFIX',
'SHARED_LIB_PREFIX', 'SHARED_LIB_SUFFIX',
'CONFIGURATION_NAME']:
generator_default_variables[unused] = ''
def CalculateVariables(default_variables, params):
generator_flags = params.get('generator_flags', {})
for key, val in generator_flags.items():
default_variables.setdefault(key, val)
default_variables.setdefault('OS', gyp.common.GetFlavor(params))
flavor = gyp.common.GetFlavor(params)
if flavor =='win':
# # Copy additional generator configuration data from VS, which is shared by the Windows Ninja generator.
# import gyp.generator.msvs as msvs_generator
# generator_additional_non_configuration_keys = getattr(msvs_generator, 'generator_additional_non_configuration_keys', [])
# generator_additional_path_sections = getattr(msvs_generator, 'generator_additional_path_sections', [])
gyp.msvs_emulation.CalculateCommonVariables(default_variables, params)
def CalculateGeneratorInputInfo(params):
"""Calculate the generator specific info that gets fed to input (called by
gyp)."""
generator_flags = params.get('generator_flags', {})
if generator_flags.get('adjust_static_libraries', False):
global generator_wants_static_library_dependencies_adjusted
generator_wants_static_library_dependencies_adjusted = True
toplevel = params['options'].toplevel_dir
generator_dir = os.path.relpath(params['options'].generator_output or '.')
# output_dir: relative path from generator_dir to the build directory.
output_dir = generator_flags.get('output_dir', 'out')
qualified_out_dir = os.path.normpath(os.path.join(
toplevel, generator_dir, output_dir, 'gypfiles'))
global generator_filelist_paths
generator_filelist_paths = {
'toplevel': toplevel,
'qualified_out_dir': qualified_out_dir,
}
def | (target_list, target_dicts, _, params):
# Map of target -> list of targets it depends on.
edges = {}
# Queue of targets to visit.
targets_to_visit = target_list[:]
while len(targets_to_visit) > 0:
target = targets_to_visit.pop()
if target in edges:
continue
edges[target] = []
for dep in target_dicts[target].get('dependencies', []):
edges[target].append(dep)
targets_to_visit.append(dep)
try:
filepath = params['generator_flags']['output_dir']
except KeyError:
filepath = '.'
filename = os.path.join(filepath, 'dump.json')
f = open(filename, 'w')
json.dump(edges, f)
f.close()
print('Wrote json to %s.' % filename)
| GenerateOutput | identifier_name |
dump_dependency_json.py | # Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from __future__ import print_function
import os
import gyp
import gyp.common
import gyp.msvs_emulation
import json
generator_supports_multiple_toolsets = True
generator_wants_static_library_dependencies_adjusted = False
generator_filelist_paths = {
}
generator_default_variables = {
}
for dirname in ['INTERMEDIATE_DIR', 'SHARED_INTERMEDIATE_DIR', 'PRODUCT_DIR',
'LIB_DIR', 'SHARED_LIB_DIR']:
# Some gyp steps fail if these are empty(!).
generator_default_variables[dirname] = 'dir'
for unused in ['RULE_INPUT_PATH', 'RULE_INPUT_ROOT', 'RULE_INPUT_NAME',
'RULE_INPUT_DIRNAME', 'RULE_INPUT_EXT',
'EXECUTABLE_PREFIX', 'EXECUTABLE_SUFFIX',
'STATIC_LIB_PREFIX', 'STATIC_LIB_SUFFIX',
'SHARED_LIB_PREFIX', 'SHARED_LIB_SUFFIX',
'CONFIGURATION_NAME']:
generator_default_variables[unused] = ''
def CalculateVariables(default_variables, params):
generator_flags = params.get('generator_flags', {})
for key, val in generator_flags.items():
default_variables.setdefault(key, val)
default_variables.setdefault('OS', gyp.common.GetFlavor(params))
flavor = gyp.common.GetFlavor(params)
if flavor =='win':
# # Copy additional generator configuration data from VS, which is shared by the Windows Ninja generator.
# import gyp.generator.msvs as msvs_generator
# generator_additional_non_configuration_keys = getattr(msvs_generator, 'generator_additional_non_configuration_keys', [])
# generator_additional_path_sections = getattr(msvs_generator, 'generator_additional_path_sections', [])
gyp.msvs_emulation.CalculateCommonVariables(default_variables, params)
def CalculateGeneratorInputInfo(params):
|
def GenerateOutput(target_list, target_dicts, _, params):
# Map of target -> list of targets it depends on.
edges = {}
# Queue of targets to visit.
targets_to_visit = target_list[:]
while len(targets_to_visit) > 0:
target = targets_to_visit.pop()
if target in edges:
continue
edges[target] = []
for dep in target_dicts[target].get('dependencies', []):
edges[target].append(dep)
targets_to_visit.append(dep)
try:
filepath = params['generator_flags']['output_dir']
except KeyError:
filepath = '.'
filename = os.path.join(filepath, 'dump.json')
f = open(filename, 'w')
json.dump(edges, f)
f.close()
print('Wrote json to %s.' % filename)
| """Calculate the generator specific info that gets fed to input (called by
gyp)."""
generator_flags = params.get('generator_flags', {})
if generator_flags.get('adjust_static_libraries', False):
global generator_wants_static_library_dependencies_adjusted
generator_wants_static_library_dependencies_adjusted = True
toplevel = params['options'].toplevel_dir
generator_dir = os.path.relpath(params['options'].generator_output or '.')
# output_dir: relative path from generator_dir to the build directory.
output_dir = generator_flags.get('output_dir', 'out')
qualified_out_dir = os.path.normpath(os.path.join(
toplevel, generator_dir, output_dir, 'gypfiles'))
global generator_filelist_paths
generator_filelist_paths = {
'toplevel': toplevel,
'qualified_out_dir': qualified_out_dir,
} | identifier_body |
dump_dependency_json.py | # Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from __future__ import print_function
import os
import gyp
import gyp.common
import gyp.msvs_emulation
import json
generator_supports_multiple_toolsets = True
generator_wants_static_library_dependencies_adjusted = False
generator_filelist_paths = {
}
generator_default_variables = {
}
for dirname in ['INTERMEDIATE_DIR', 'SHARED_INTERMEDIATE_DIR', 'PRODUCT_DIR',
'LIB_DIR', 'SHARED_LIB_DIR']:
# Some gyp steps fail if these are empty(!).
generator_default_variables[dirname] = 'dir'
for unused in ['RULE_INPUT_PATH', 'RULE_INPUT_ROOT', 'RULE_INPUT_NAME',
'RULE_INPUT_DIRNAME', 'RULE_INPUT_EXT',
'EXECUTABLE_PREFIX', 'EXECUTABLE_SUFFIX',
'STATIC_LIB_PREFIX', 'STATIC_LIB_SUFFIX',
'SHARED_LIB_PREFIX', 'SHARED_LIB_SUFFIX',
'CONFIGURATION_NAME']:
|
def CalculateVariables(default_variables, params):
generator_flags = params.get('generator_flags', {})
for key, val in generator_flags.items():
default_variables.setdefault(key, val)
default_variables.setdefault('OS', gyp.common.GetFlavor(params))
flavor = gyp.common.GetFlavor(params)
if flavor =='win':
# # Copy additional generator configuration data from VS, which is shared by the Windows Ninja generator.
# import gyp.generator.msvs as msvs_generator
# generator_additional_non_configuration_keys = getattr(msvs_generator, 'generator_additional_non_configuration_keys', [])
# generator_additional_path_sections = getattr(msvs_generator, 'generator_additional_path_sections', [])
gyp.msvs_emulation.CalculateCommonVariables(default_variables, params)
def CalculateGeneratorInputInfo(params):
"""Calculate the generator specific info that gets fed to input (called by
gyp)."""
generator_flags = params.get('generator_flags', {})
if generator_flags.get('adjust_static_libraries', False):
global generator_wants_static_library_dependencies_adjusted
generator_wants_static_library_dependencies_adjusted = True
toplevel = params['options'].toplevel_dir
generator_dir = os.path.relpath(params['options'].generator_output or '.')
# output_dir: relative path from generator_dir to the build directory.
output_dir = generator_flags.get('output_dir', 'out')
qualified_out_dir = os.path.normpath(os.path.join(
toplevel, generator_dir, output_dir, 'gypfiles'))
global generator_filelist_paths
generator_filelist_paths = {
'toplevel': toplevel,
'qualified_out_dir': qualified_out_dir,
}
def GenerateOutput(target_list, target_dicts, _, params):
# Map of target -> list of targets it depends on.
edges = {}
# Queue of targets to visit.
targets_to_visit = target_list[:]
while len(targets_to_visit) > 0:
target = targets_to_visit.pop()
if target in edges:
continue
edges[target] = []
for dep in target_dicts[target].get('dependencies', []):
edges[target].append(dep)
targets_to_visit.append(dep)
try:
filepath = params['generator_flags']['output_dir']
except KeyError:
filepath = '.'
filename = os.path.join(filepath, 'dump.json')
f = open(filename, 'w')
json.dump(edges, f)
f.close()
print('Wrote json to %s.' % filename)
| generator_default_variables[unused] = '' | conditional_block |
simpleapi.rs | // Simple API example, ported from http://lua-users.org/wiki/SimpleLuaApiExample
// This is a simple introductory example of how to interface to Lua from Rust.
// The Rust program loads a Lua script file, sets some Lua variables, runs the
// Lua script, and reads back the return value.
| #![allow(non_snake_case)]
extern crate lua;
use std::io::{self, Write};
use std::path::Path;
use std::process;
fn main() {
let mut L = lua::State::new();
L.openlibs(); // Load Lua libraries
// Load the file containing the script we are going to run
let path = Path::new("simpleapi.lua");
match L.loadfile(Some(&path)) {
Ok(_) => (),
Err(_) => {
// If something went wrong, error message is at the top of the stack
let _ = writeln!(&mut io::stderr(),
"Couldn't load file: {}", L.describe(-1));
process::exit(1);
}
}
/*
* Ok, now here we go: We pass data to the lua script on the stack.
* That is, we first have to prepare Lua's virtual stack the way we
* want the script to receive it, then ask Lua to run it.
*/
L.newtable(); // We will pass a table
/*
* To put values into the table, we first push the index, then the
* value, and then call rawset() with the index of the table in the
* stack. Let's see why it's -3: In Lua, the value -1 always refers to
* the top of the stack. When you create the table with newtable(),
* the table gets pushed into the top of the stack. When you push the
* index and then the cell value, the stack looks like:
*
* - [stack bottom] -- table, index, value [top]
*
* So the -1 will refer to the cell value, thus -3 is used to refer to
* the table itself. Note that rawset() pops the last two elements
* of the stack, so that after it has been called, the table is at the
* top of the stack.
*/
for i in 1..6 {
L.pushinteger(i); // Push the table index
L.pushinteger(i*2); // Push the cell value
L.rawset(-3); // Stores the pair in the table
}
// By what name is the script going to reference our table?
L.setglobal("foo");
// Ask Lua to run our little script
match L.pcall(0, lua::MULTRET, 0) {
Ok(()) => (),
Err(_) => {
let _ = writeln!(&mut io::stderr(),
"Failed to run script: {}", L.describe(-1));
process::exit(1);
}
}
// Get the returned value at the to of the stack (index -1)
let sum = L.tonumber(-1);
println!("Script returned: {}", sum);
L.pop(1); // Take the returned value out of the stack
// L's destructor will close the state for us
} | random_line_split | |
simpleapi.rs | // Simple API example, ported from http://lua-users.org/wiki/SimpleLuaApiExample
// This is a simple introductory example of how to interface to Lua from Rust.
// The Rust program loads a Lua script file, sets some Lua variables, runs the
// Lua script, and reads back the return value.
#![allow(non_snake_case)]
extern crate lua;
use std::io::{self, Write};
use std::path::Path;
use std::process;
fn main() | {
let mut L = lua::State::new();
L.openlibs(); // Load Lua libraries
// Load the file containing the script we are going to run
let path = Path::new("simpleapi.lua");
match L.loadfile(Some(&path)) {
Ok(_) => (),
Err(_) => {
// If something went wrong, error message is at the top of the stack
let _ = writeln!(&mut io::stderr(),
"Couldn't load file: {}", L.describe(-1));
process::exit(1);
}
}
/*
* Ok, now here we go: We pass data to the lua script on the stack.
* That is, we first have to prepare Lua's virtual stack the way we
* want the script to receive it, then ask Lua to run it.
*/
L.newtable(); // We will pass a table
/*
* To put values into the table, we first push the index, then the
* value, and then call rawset() with the index of the table in the
* stack. Let's see why it's -3: In Lua, the value -1 always refers to
* the top of the stack. When you create the table with newtable(),
* the table gets pushed into the top of the stack. When you push the
* index and then the cell value, the stack looks like:
*
* - [stack bottom] -- table, index, value [top]
*
* So the -1 will refer to the cell value, thus -3 is used to refer to
* the table itself. Note that rawset() pops the last two elements
* of the stack, so that after it has been called, the table is at the
* top of the stack.
*/
for i in 1..6 {
L.pushinteger(i); // Push the table index
L.pushinteger(i*2); // Push the cell value
L.rawset(-3); // Stores the pair in the table
}
// By what name is the script going to reference our table?
L.setglobal("foo");
// Ask Lua to run our little script
match L.pcall(0, lua::MULTRET, 0) {
Ok(()) => (),
Err(_) => {
let _ = writeln!(&mut io::stderr(),
"Failed to run script: {}", L.describe(-1));
process::exit(1);
}
}
// Get the returned value at the to of the stack (index -1)
let sum = L.tonumber(-1);
println!("Script returned: {}", sum);
L.pop(1); // Take the returned value out of the stack
// L's destructor will close the state for us
} | identifier_body | |
simpleapi.rs | // Simple API example, ported from http://lua-users.org/wiki/SimpleLuaApiExample
// This is a simple introductory example of how to interface to Lua from Rust.
// The Rust program loads a Lua script file, sets some Lua variables, runs the
// Lua script, and reads back the return value.
#![allow(non_snake_case)]
extern crate lua;
use std::io::{self, Write};
use std::path::Path;
use std::process;
fn | () {
let mut L = lua::State::new();
L.openlibs(); // Load Lua libraries
// Load the file containing the script we are going to run
let path = Path::new("simpleapi.lua");
match L.loadfile(Some(&path)) {
Ok(_) => (),
Err(_) => {
// If something went wrong, error message is at the top of the stack
let _ = writeln!(&mut io::stderr(),
"Couldn't load file: {}", L.describe(-1));
process::exit(1);
}
}
/*
* Ok, now here we go: We pass data to the lua script on the stack.
* That is, we first have to prepare Lua's virtual stack the way we
* want the script to receive it, then ask Lua to run it.
*/
L.newtable(); // We will pass a table
/*
* To put values into the table, we first push the index, then the
* value, and then call rawset() with the index of the table in the
* stack. Let's see why it's -3: In Lua, the value -1 always refers to
* the top of the stack. When you create the table with newtable(),
* the table gets pushed into the top of the stack. When you push the
* index and then the cell value, the stack looks like:
*
* - [stack bottom] -- table, index, value [top]
*
* So the -1 will refer to the cell value, thus -3 is used to refer to
* the table itself. Note that rawset() pops the last two elements
* of the stack, so that after it has been called, the table is at the
* top of the stack.
*/
for i in 1..6 {
L.pushinteger(i); // Push the table index
L.pushinteger(i*2); // Push the cell value
L.rawset(-3); // Stores the pair in the table
}
// By what name is the script going to reference our table?
L.setglobal("foo");
// Ask Lua to run our little script
match L.pcall(0, lua::MULTRET, 0) {
Ok(()) => (),
Err(_) => {
let _ = writeln!(&mut io::stderr(),
"Failed to run script: {}", L.describe(-1));
process::exit(1);
}
}
// Get the returned value at the to of the stack (index -1)
let sum = L.tonumber(-1);
println!("Script returned: {}", sum);
L.pop(1); // Take the returned value out of the stack
// L's destructor will close the state for us
}
| main | identifier_name |
keyboardEvent.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as browser from 'vs/base/browser/browser';
import { KeyCode, KeyCodeUtils, KeyMod, SimpleKeybinding } from 'vs/base/common/keyCodes';
import * as platform from 'vs/base/common/platform';
let KEY_CODE_MAP: { [keyCode: number]: KeyCode } = new Array(230);
let INVERSE_KEY_CODE_MAP: KeyCode[] = new Array(KeyCode.MAX_VALUE);
(function () {
for (let i = 0; i < INVERSE_KEY_CODE_MAP.length; i++) {
INVERSE_KEY_CODE_MAP[i] = -1;
}
function define(code: number, keyCode: KeyCode): void {
KEY_CODE_MAP[code] = keyCode;
INVERSE_KEY_CODE_MAP[keyCode] = code;
}
define(3, KeyCode.PauseBreak); // VK_CANCEL 0x03 Control-break processing
define(8, KeyCode.Backspace);
define(9, KeyCode.Tab);
define(13, KeyCode.Enter);
define(16, KeyCode.Shift);
define(17, KeyCode.Ctrl);
define(18, KeyCode.Alt);
define(19, KeyCode.PauseBreak);
define(20, KeyCode.CapsLock);
define(27, KeyCode.Escape);
define(32, KeyCode.Space);
define(33, KeyCode.PageUp);
define(34, KeyCode.PageDown);
define(35, KeyCode.End);
define(36, KeyCode.Home);
define(37, KeyCode.LeftArrow);
define(38, KeyCode.UpArrow);
define(39, KeyCode.RightArrow);
define(40, KeyCode.DownArrow);
define(45, KeyCode.Insert);
define(46, KeyCode.Delete);
define(48, KeyCode.KEY_0);
define(49, KeyCode.KEY_1);
define(50, KeyCode.KEY_2);
define(51, KeyCode.KEY_3);
define(52, KeyCode.KEY_4);
define(53, KeyCode.KEY_5);
define(54, KeyCode.KEY_6);
define(55, KeyCode.KEY_7);
define(56, KeyCode.KEY_8);
define(57, KeyCode.KEY_9);
define(65, KeyCode.KEY_A);
define(66, KeyCode.KEY_B);
define(67, KeyCode.KEY_C);
define(68, KeyCode.KEY_D);
define(69, KeyCode.KEY_E);
define(70, KeyCode.KEY_F);
define(71, KeyCode.KEY_G);
define(72, KeyCode.KEY_H);
define(73, KeyCode.KEY_I);
define(74, KeyCode.KEY_J);
define(75, KeyCode.KEY_K);
define(76, KeyCode.KEY_L);
define(77, KeyCode.KEY_M);
define(78, KeyCode.KEY_N);
define(79, KeyCode.KEY_O);
define(80, KeyCode.KEY_P);
define(81, KeyCode.KEY_Q);
define(82, KeyCode.KEY_R);
define(83, KeyCode.KEY_S);
define(84, KeyCode.KEY_T);
define(85, KeyCode.KEY_U);
define(86, KeyCode.KEY_V);
define(87, KeyCode.KEY_W);
define(88, KeyCode.KEY_X);
define(89, KeyCode.KEY_Y);
define(90, KeyCode.KEY_Z);
define(93, KeyCode.ContextMenu);
define(96, KeyCode.NUMPAD_0);
define(97, KeyCode.NUMPAD_1);
define(98, KeyCode.NUMPAD_2);
define(99, KeyCode.NUMPAD_3);
define(100, KeyCode.NUMPAD_4);
define(101, KeyCode.NUMPAD_5);
define(102, KeyCode.NUMPAD_6);
define(103, KeyCode.NUMPAD_7);
define(104, KeyCode.NUMPAD_8);
define(105, KeyCode.NUMPAD_9);
define(106, KeyCode.NUMPAD_MULTIPLY);
define(107, KeyCode.NUMPAD_ADD);
define(108, KeyCode.NUMPAD_SEPARATOR);
define(109, KeyCode.NUMPAD_SUBTRACT);
define(110, KeyCode.NUMPAD_DECIMAL);
define(111, KeyCode.NUMPAD_DIVIDE);
define(112, KeyCode.F1);
define(113, KeyCode.F2);
define(114, KeyCode.F3);
define(115, KeyCode.F4);
define(116, KeyCode.F5);
define(117, KeyCode.F6);
define(118, KeyCode.F7);
define(119, KeyCode.F8);
define(120, KeyCode.F9);
define(121, KeyCode.F10);
define(122, KeyCode.F11);
define(123, KeyCode.F12);
define(124, KeyCode.F13);
define(125, KeyCode.F14);
define(126, KeyCode.F15);
define(127, KeyCode.F16);
define(128, KeyCode.F17);
define(129, KeyCode.F18);
define(130, KeyCode.F19);
define(144, KeyCode.NumLock);
define(145, KeyCode.ScrollLock);
define(186, KeyCode.US_SEMICOLON);
define(187, KeyCode.US_EQUAL);
define(188, KeyCode.US_COMMA);
define(189, KeyCode.US_MINUS);
define(190, KeyCode.US_DOT);
define(191, KeyCode.US_SLASH);
define(192, KeyCode.US_BACKTICK);
define(193, KeyCode.ABNT_C1);
define(194, KeyCode.ABNT_C2);
define(219, KeyCode.US_OPEN_SQUARE_BRACKET);
define(220, KeyCode.US_BACKSLASH);
define(221, KeyCode.US_CLOSE_SQUARE_BRACKET);
define(222, KeyCode.US_QUOTE);
define(223, KeyCode.OEM_8);
define(226, KeyCode.OEM_102);
/**
* https://lists.w3.org/Archives/Public/www-dom/2010JulSep/att-0182/keyCode-spec.html
* If an Input Method Editor is processing key input and the event is keydown, return 229.
*/
define(229, KeyCode.KEY_IN_COMPOSITION);
if (browser.isFirefox) {
define(59, KeyCode.US_SEMICOLON);
define(107, KeyCode.US_EQUAL);
define(109, KeyCode.US_MINUS);
if (platform.isMacintosh) {
define(224, KeyCode.Meta);
}
} else if (browser.isWebKit) {
define(91, KeyCode.Meta);
if (platform.isMacintosh) {
// the two meta keys in the Mac have different key codes (91 and 93)
define(93, KeyCode.Meta);
} else {
define(92, KeyCode.Meta);
}
}
})();
function extractKeyCode(e: KeyboardEvent): KeyCode {
if (e.charCode) {
// "keypress" events mostly
let char = String.fromCharCode(e.charCode).toUpperCase();
return KeyCodeUtils.fromString(char);
}
return KEY_CODE_MAP[e.keyCode] || KeyCode.Unknown;
}
export function getCodeForKeyCode(keyCode: KeyCode): number {
return INVERSE_KEY_CODE_MAP[keyCode];
}
export interface IKeyboardEvent {
readonly _standardKeyboardEventBrand: true;
readonly browserEvent: KeyboardEvent;
readonly target: HTMLElement;
readonly ctrlKey: boolean;
readonly shiftKey: boolean;
readonly altKey: boolean;
readonly metaKey: boolean;
readonly keyCode: KeyCode;
readonly code: string;
/**
* @internal
*/
toKeybinding(): SimpleKeybinding;
equals(keybinding: number): boolean;
preventDefault(): void;
stopPropagation(): void;
}
const ctrlKeyMod = (platform.isMacintosh ? KeyMod.WinCtrl : KeyMod.CtrlCmd);
const altKeyMod = KeyMod.Alt;
const shiftKeyMod = KeyMod.Shift;
const metaKeyMod = (platform.isMacintosh ? KeyMod.CtrlCmd : KeyMod.WinCtrl);
export function printKeyboardEvent(e: KeyboardEvent): string |
export function printStandardKeyboardEvent(e: StandardKeyboardEvent): string {
let modifiers: string[] = [];
if (e.ctrlKey) {
modifiers.push(`ctrl`);
}
if (e.shiftKey) {
modifiers.push(`shift`);
}
if (e.altKey) {
modifiers.push(`alt`);
}
if (e.metaKey) {
modifiers.push(`meta`);
}
return `modifiers: [${modifiers.join(',')}], code: ${e.code}, keyCode: ${e.keyCode} ('${KeyCodeUtils.toString(e.keyCode)}')`;
}
export class StandardKeyboardEvent implements IKeyboardEvent {
readonly _standardKeyboardEventBrand = true;
public readonly browserEvent: KeyboardEvent;
public readonly target: HTMLElement;
public readonly ctrlKey: boolean;
public readonly shiftKey: boolean;
public readonly altKey: boolean;
public readonly metaKey: boolean;
public readonly keyCode: KeyCode;
public readonly code: string;
private _asKeybinding: number;
private _asRuntimeKeybinding: SimpleKeybinding;
constructor(source: KeyboardEvent) {
let e = source;
this.browserEvent = e;
this.target = <HTMLElement>e.target;
this.ctrlKey = e.ctrlKey;
this.shiftKey = e.shiftKey;
this.altKey = e.altKey;
this.metaKey = e.metaKey;
this.keyCode = extractKeyCode(e);
this.code = e.code;
// console.info(e.type + ": keyCode: " + e.keyCode + ", which: " + e.which + ", charCode: " + e.charCode + ", detail: " + e.detail + " ====> " + this.keyCode + ' -- ' + KeyCode[this.keyCode]);
this.ctrlKey = this.ctrlKey || this.keyCode === KeyCode.Ctrl;
this.altKey = this.altKey || this.keyCode === KeyCode.Alt;
this.shiftKey = this.shiftKey || this.keyCode === KeyCode.Shift;
this.metaKey = this.metaKey || this.keyCode === KeyCode.Meta;
this._asKeybinding = this._computeKeybinding();
this._asRuntimeKeybinding = this._computeRuntimeKeybinding();
// console.log(`code: ${e.code}, keyCode: ${e.keyCode}, key: ${e.key}`);
}
public preventDefault(): void {
if (this.browserEvent && this.browserEvent.preventDefault) {
this.browserEvent.preventDefault();
}
}
public stopPropagation(): void {
if (this.browserEvent && this.browserEvent.stopPropagation) {
this.browserEvent.stopPropagation();
}
}
public toKeybinding(): SimpleKeybinding {
return this._asRuntimeKeybinding;
}
public equals(other: number): boolean {
return this._asKeybinding === other;
}
private _computeKeybinding(): number {
let key = KeyCode.Unknown;
if (this.keyCode !== KeyCode.Ctrl && this.keyCode !== KeyCode.Shift && this.keyCode !== KeyCode.Alt && this.keyCode !== KeyCode.Meta) {
key = this.keyCode;
}
let result = 0;
if (this.ctrlKey) {
result |= ctrlKeyMod;
}
if (this.altKey) {
result |= altKeyMod;
}
if (this.shiftKey) {
result |= shiftKeyMod;
}
if (this.metaKey) {
result |= metaKeyMod;
}
result |= key;
return result;
}
private _computeRuntimeKeybinding(): SimpleKeybinding {
let key = KeyCode.Unknown;
if (this.keyCode !== KeyCode.Ctrl && this.keyCode !== KeyCode.Shift && this.keyCode !== KeyCode.Alt && this.keyCode !== KeyCode.Meta) {
key = this.keyCode;
}
return new SimpleKeybinding(this.ctrlKey, this.shiftKey, this.altKey, this.metaKey, key);
}
}
| {
let modifiers: string[] = [];
if (e.ctrlKey) {
modifiers.push(`ctrl`);
}
if (e.shiftKey) {
modifiers.push(`shift`);
}
if (e.altKey) {
modifiers.push(`alt`);
}
if (e.metaKey) {
modifiers.push(`meta`);
}
return `modifiers: [${modifiers.join(',')}], code: ${e.code}, keyCode: ${e.keyCode}, key: ${e.key}`;
} | identifier_body |
keyboardEvent.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as browser from 'vs/base/browser/browser';
import { KeyCode, KeyCodeUtils, KeyMod, SimpleKeybinding } from 'vs/base/common/keyCodes';
import * as platform from 'vs/base/common/platform';
let KEY_CODE_MAP: { [keyCode: number]: KeyCode } = new Array(230);
let INVERSE_KEY_CODE_MAP: KeyCode[] = new Array(KeyCode.MAX_VALUE);
(function () {
for (let i = 0; i < INVERSE_KEY_CODE_MAP.length; i++) {
INVERSE_KEY_CODE_MAP[i] = -1;
}
function define(code: number, keyCode: KeyCode): void {
KEY_CODE_MAP[code] = keyCode;
INVERSE_KEY_CODE_MAP[keyCode] = code;
}
define(3, KeyCode.PauseBreak); // VK_CANCEL 0x03 Control-break processing
define(8, KeyCode.Backspace);
define(9, KeyCode.Tab);
define(13, KeyCode.Enter);
define(16, KeyCode.Shift);
define(17, KeyCode.Ctrl);
define(18, KeyCode.Alt);
define(19, KeyCode.PauseBreak);
define(20, KeyCode.CapsLock);
define(27, KeyCode.Escape);
define(32, KeyCode.Space);
define(33, KeyCode.PageUp);
define(34, KeyCode.PageDown);
define(35, KeyCode.End);
define(36, KeyCode.Home);
define(37, KeyCode.LeftArrow);
define(38, KeyCode.UpArrow);
define(39, KeyCode.RightArrow);
define(40, KeyCode.DownArrow);
define(45, KeyCode.Insert);
define(46, KeyCode.Delete);
define(48, KeyCode.KEY_0);
define(49, KeyCode.KEY_1);
define(50, KeyCode.KEY_2);
define(51, KeyCode.KEY_3);
define(52, KeyCode.KEY_4);
define(53, KeyCode.KEY_5);
define(54, KeyCode.KEY_6);
define(55, KeyCode.KEY_7);
define(56, KeyCode.KEY_8);
define(57, KeyCode.KEY_9);
define(65, KeyCode.KEY_A);
define(66, KeyCode.KEY_B);
define(67, KeyCode.KEY_C);
define(68, KeyCode.KEY_D);
define(69, KeyCode.KEY_E);
define(70, KeyCode.KEY_F);
define(71, KeyCode.KEY_G);
define(72, KeyCode.KEY_H);
define(73, KeyCode.KEY_I);
define(74, KeyCode.KEY_J);
define(75, KeyCode.KEY_K);
define(76, KeyCode.KEY_L);
define(77, KeyCode.KEY_M);
define(78, KeyCode.KEY_N);
define(79, KeyCode.KEY_O);
define(80, KeyCode.KEY_P);
define(81, KeyCode.KEY_Q);
define(82, KeyCode.KEY_R);
define(83, KeyCode.KEY_S);
define(84, KeyCode.KEY_T);
define(85, KeyCode.KEY_U);
define(86, KeyCode.KEY_V);
define(87, KeyCode.KEY_W);
define(88, KeyCode.KEY_X);
define(89, KeyCode.KEY_Y);
define(90, KeyCode.KEY_Z);
define(93, KeyCode.ContextMenu);
define(96, KeyCode.NUMPAD_0);
define(97, KeyCode.NUMPAD_1);
define(98, KeyCode.NUMPAD_2);
define(99, KeyCode.NUMPAD_3);
define(100, KeyCode.NUMPAD_4);
define(101, KeyCode.NUMPAD_5);
define(102, KeyCode.NUMPAD_6);
define(103, KeyCode.NUMPAD_7);
define(104, KeyCode.NUMPAD_8);
define(105, KeyCode.NUMPAD_9);
define(106, KeyCode.NUMPAD_MULTIPLY);
define(107, KeyCode.NUMPAD_ADD);
define(108, KeyCode.NUMPAD_SEPARATOR);
define(109, KeyCode.NUMPAD_SUBTRACT);
define(110, KeyCode.NUMPAD_DECIMAL);
define(111, KeyCode.NUMPAD_DIVIDE);
define(112, KeyCode.F1);
define(113, KeyCode.F2);
define(114, KeyCode.F3);
define(115, KeyCode.F4);
define(116, KeyCode.F5);
define(117, KeyCode.F6);
define(118, KeyCode.F7);
define(119, KeyCode.F8);
define(120, KeyCode.F9);
define(121, KeyCode.F10);
define(122, KeyCode.F11);
define(123, KeyCode.F12);
define(124, KeyCode.F13);
define(125, KeyCode.F14);
define(126, KeyCode.F15);
define(127, KeyCode.F16);
define(128, KeyCode.F17);
define(129, KeyCode.F18);
define(130, KeyCode.F19);
define(144, KeyCode.NumLock);
define(145, KeyCode.ScrollLock);
define(186, KeyCode.US_SEMICOLON);
define(187, KeyCode.US_EQUAL);
define(188, KeyCode.US_COMMA);
define(189, KeyCode.US_MINUS);
define(190, KeyCode.US_DOT);
define(191, KeyCode.US_SLASH);
define(192, KeyCode.US_BACKTICK);
define(193, KeyCode.ABNT_C1);
define(194, KeyCode.ABNT_C2);
define(219, KeyCode.US_OPEN_SQUARE_BRACKET);
define(220, KeyCode.US_BACKSLASH);
define(221, KeyCode.US_CLOSE_SQUARE_BRACKET);
define(222, KeyCode.US_QUOTE);
define(223, KeyCode.OEM_8);
define(226, KeyCode.OEM_102);
/**
* https://lists.w3.org/Archives/Public/www-dom/2010JulSep/att-0182/keyCode-spec.html
* If an Input Method Editor is processing key input and the event is keydown, return 229.
*/
define(229, KeyCode.KEY_IN_COMPOSITION);
if (browser.isFirefox) {
define(59, KeyCode.US_SEMICOLON);
define(107, KeyCode.US_EQUAL);
define(109, KeyCode.US_MINUS);
if (platform.isMacintosh) {
define(224, KeyCode.Meta);
}
} else if (browser.isWebKit) {
define(91, KeyCode.Meta);
if (platform.isMacintosh) {
// the two meta keys in the Mac have different key codes (91 and 93)
define(93, KeyCode.Meta);
} else {
define(92, KeyCode.Meta);
}
}
})();
function extractKeyCode(e: KeyboardEvent): KeyCode {
if (e.charCode) {
// "keypress" events mostly
let char = String.fromCharCode(e.charCode).toUpperCase();
return KeyCodeUtils.fromString(char);
}
return KEY_CODE_MAP[e.keyCode] || KeyCode.Unknown;
}
export function getCodeForKeyCode(keyCode: KeyCode): number {
return INVERSE_KEY_CODE_MAP[keyCode];
}
export interface IKeyboardEvent {
readonly _standardKeyboardEventBrand: true;
readonly browserEvent: KeyboardEvent;
readonly target: HTMLElement;
readonly ctrlKey: boolean;
readonly shiftKey: boolean;
readonly altKey: boolean;
readonly metaKey: boolean;
readonly keyCode: KeyCode;
readonly code: string;
/**
* @internal
*/
toKeybinding(): SimpleKeybinding;
equals(keybinding: number): boolean;
preventDefault(): void;
stopPropagation(): void;
}
const ctrlKeyMod = (platform.isMacintosh ? KeyMod.WinCtrl : KeyMod.CtrlCmd);
const altKeyMod = KeyMod.Alt;
const shiftKeyMod = KeyMod.Shift;
const metaKeyMod = (platform.isMacintosh ? KeyMod.CtrlCmd : KeyMod.WinCtrl);
export function printKeyboardEvent(e: KeyboardEvent): string {
let modifiers: string[] = [];
if (e.ctrlKey) {
modifiers.push(`ctrl`);
}
if (e.shiftKey) {
modifiers.push(`shift`);
}
if (e.altKey) {
modifiers.push(`alt`);
}
if (e.metaKey) {
modifiers.push(`meta`);
}
return `modifiers: [${modifiers.join(',')}], code: ${e.code}, keyCode: ${e.keyCode}, key: ${e.key}`;
}
export function printStandardKeyboardEvent(e: StandardKeyboardEvent): string {
let modifiers: string[] = [];
if (e.ctrlKey) {
modifiers.push(`ctrl`);
}
if (e.shiftKey) {
modifiers.push(`shift`);
}
if (e.altKey) {
modifiers.push(`alt`);
}
if (e.metaKey) {
modifiers.push(`meta`);
}
return `modifiers: [${modifiers.join(',')}], code: ${e.code}, keyCode: ${e.keyCode} ('${KeyCodeUtils.toString(e.keyCode)}')`;
}
export class | implements IKeyboardEvent {
readonly _standardKeyboardEventBrand = true;
public readonly browserEvent: KeyboardEvent;
public readonly target: HTMLElement;
public readonly ctrlKey: boolean;
public readonly shiftKey: boolean;
public readonly altKey: boolean;
public readonly metaKey: boolean;
public readonly keyCode: KeyCode;
public readonly code: string;
private _asKeybinding: number;
private _asRuntimeKeybinding: SimpleKeybinding;
constructor(source: KeyboardEvent) {
let e = source;
this.browserEvent = e;
this.target = <HTMLElement>e.target;
this.ctrlKey = e.ctrlKey;
this.shiftKey = e.shiftKey;
this.altKey = e.altKey;
this.metaKey = e.metaKey;
this.keyCode = extractKeyCode(e);
this.code = e.code;
// console.info(e.type + ": keyCode: " + e.keyCode + ", which: " + e.which + ", charCode: " + e.charCode + ", detail: " + e.detail + " ====> " + this.keyCode + ' -- ' + KeyCode[this.keyCode]);
this.ctrlKey = this.ctrlKey || this.keyCode === KeyCode.Ctrl;
this.altKey = this.altKey || this.keyCode === KeyCode.Alt;
this.shiftKey = this.shiftKey || this.keyCode === KeyCode.Shift;
this.metaKey = this.metaKey || this.keyCode === KeyCode.Meta;
this._asKeybinding = this._computeKeybinding();
this._asRuntimeKeybinding = this._computeRuntimeKeybinding();
// console.log(`code: ${e.code}, keyCode: ${e.keyCode}, key: ${e.key}`);
}
public preventDefault(): void {
if (this.browserEvent && this.browserEvent.preventDefault) {
this.browserEvent.preventDefault();
}
}
public stopPropagation(): void {
if (this.browserEvent && this.browserEvent.stopPropagation) {
this.browserEvent.stopPropagation();
}
}
public toKeybinding(): SimpleKeybinding {
return this._asRuntimeKeybinding;
}
public equals(other: number): boolean {
return this._asKeybinding === other;
}
private _computeKeybinding(): number {
let key = KeyCode.Unknown;
if (this.keyCode !== KeyCode.Ctrl && this.keyCode !== KeyCode.Shift && this.keyCode !== KeyCode.Alt && this.keyCode !== KeyCode.Meta) {
key = this.keyCode;
}
let result = 0;
if (this.ctrlKey) {
result |= ctrlKeyMod;
}
if (this.altKey) {
result |= altKeyMod;
}
if (this.shiftKey) {
result |= shiftKeyMod;
}
if (this.metaKey) {
result |= metaKeyMod;
}
result |= key;
return result;
}
private _computeRuntimeKeybinding(): SimpleKeybinding {
let key = KeyCode.Unknown;
if (this.keyCode !== KeyCode.Ctrl && this.keyCode !== KeyCode.Shift && this.keyCode !== KeyCode.Alt && this.keyCode !== KeyCode.Meta) {
key = this.keyCode;
}
return new SimpleKeybinding(this.ctrlKey, this.shiftKey, this.altKey, this.metaKey, key);
}
}
| StandardKeyboardEvent | identifier_name |
keyboardEvent.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as browser from 'vs/base/browser/browser';
import { KeyCode, KeyCodeUtils, KeyMod, SimpleKeybinding } from 'vs/base/common/keyCodes';
import * as platform from 'vs/base/common/platform';
let KEY_CODE_MAP: { [keyCode: number]: KeyCode } = new Array(230);
let INVERSE_KEY_CODE_MAP: KeyCode[] = new Array(KeyCode.MAX_VALUE);
(function () {
for (let i = 0; i < INVERSE_KEY_CODE_MAP.length; i++) {
INVERSE_KEY_CODE_MAP[i] = -1;
}
function define(code: number, keyCode: KeyCode): void {
KEY_CODE_MAP[code] = keyCode;
INVERSE_KEY_CODE_MAP[keyCode] = code;
}
define(3, KeyCode.PauseBreak); // VK_CANCEL 0x03 Control-break processing
define(8, KeyCode.Backspace);
define(9, KeyCode.Tab);
define(13, KeyCode.Enter);
define(16, KeyCode.Shift);
define(17, KeyCode.Ctrl);
define(18, KeyCode.Alt);
define(19, KeyCode.PauseBreak);
define(20, KeyCode.CapsLock);
define(27, KeyCode.Escape);
define(32, KeyCode.Space);
define(33, KeyCode.PageUp);
define(34, KeyCode.PageDown);
define(35, KeyCode.End);
define(36, KeyCode.Home);
define(37, KeyCode.LeftArrow);
define(38, KeyCode.UpArrow);
define(39, KeyCode.RightArrow);
define(40, KeyCode.DownArrow);
define(45, KeyCode.Insert);
define(46, KeyCode.Delete);
define(48, KeyCode.KEY_0);
define(49, KeyCode.KEY_1);
define(50, KeyCode.KEY_2);
define(51, KeyCode.KEY_3);
define(52, KeyCode.KEY_4);
define(53, KeyCode.KEY_5);
define(54, KeyCode.KEY_6);
define(55, KeyCode.KEY_7);
define(56, KeyCode.KEY_8);
define(57, KeyCode.KEY_9);
define(65, KeyCode.KEY_A);
define(66, KeyCode.KEY_B);
define(67, KeyCode.KEY_C);
define(68, KeyCode.KEY_D);
define(69, KeyCode.KEY_E);
define(70, KeyCode.KEY_F);
define(71, KeyCode.KEY_G);
define(72, KeyCode.KEY_H);
define(73, KeyCode.KEY_I);
define(74, KeyCode.KEY_J);
define(75, KeyCode.KEY_K);
define(76, KeyCode.KEY_L);
define(77, KeyCode.KEY_M);
define(78, KeyCode.KEY_N);
define(79, KeyCode.KEY_O);
define(80, KeyCode.KEY_P);
define(81, KeyCode.KEY_Q);
define(82, KeyCode.KEY_R);
define(83, KeyCode.KEY_S);
define(84, KeyCode.KEY_T);
define(85, KeyCode.KEY_U);
define(86, KeyCode.KEY_V);
define(87, KeyCode.KEY_W);
define(88, KeyCode.KEY_X);
define(89, KeyCode.KEY_Y);
define(90, KeyCode.KEY_Z);
define(93, KeyCode.ContextMenu);
define(96, KeyCode.NUMPAD_0);
define(97, KeyCode.NUMPAD_1);
define(98, KeyCode.NUMPAD_2);
define(99, KeyCode.NUMPAD_3);
define(100, KeyCode.NUMPAD_4);
define(101, KeyCode.NUMPAD_5);
define(102, KeyCode.NUMPAD_6);
define(103, KeyCode.NUMPAD_7);
define(104, KeyCode.NUMPAD_8);
define(105, KeyCode.NUMPAD_9);
define(106, KeyCode.NUMPAD_MULTIPLY);
define(107, KeyCode.NUMPAD_ADD);
define(108, KeyCode.NUMPAD_SEPARATOR);
define(109, KeyCode.NUMPAD_SUBTRACT);
define(110, KeyCode.NUMPAD_DECIMAL);
define(111, KeyCode.NUMPAD_DIVIDE);
define(112, KeyCode.F1);
define(113, KeyCode.F2);
define(114, KeyCode.F3);
define(115, KeyCode.F4);
define(116, KeyCode.F5);
define(117, KeyCode.F6);
define(118, KeyCode.F7);
define(119, KeyCode.F8);
define(120, KeyCode.F9);
define(121, KeyCode.F10);
define(122, KeyCode.F11);
define(123, KeyCode.F12);
define(124, KeyCode.F13);
define(125, KeyCode.F14);
define(126, KeyCode.F15);
define(127, KeyCode.F16);
define(128, KeyCode.F17);
define(129, KeyCode.F18);
define(130, KeyCode.F19);
define(144, KeyCode.NumLock);
define(145, KeyCode.ScrollLock);
define(186, KeyCode.US_SEMICOLON);
define(187, KeyCode.US_EQUAL);
define(188, KeyCode.US_COMMA);
define(189, KeyCode.US_MINUS);
define(190, KeyCode.US_DOT);
define(191, KeyCode.US_SLASH);
define(192, KeyCode.US_BACKTICK);
define(193, KeyCode.ABNT_C1);
define(194, KeyCode.ABNT_C2);
define(219, KeyCode.US_OPEN_SQUARE_BRACKET);
define(220, KeyCode.US_BACKSLASH);
define(221, KeyCode.US_CLOSE_SQUARE_BRACKET);
define(222, KeyCode.US_QUOTE);
define(223, KeyCode.OEM_8);
define(226, KeyCode.OEM_102);
/**
* https://lists.w3.org/Archives/Public/www-dom/2010JulSep/att-0182/keyCode-spec.html
* If an Input Method Editor is processing key input and the event is keydown, return 229.
*/
define(229, KeyCode.KEY_IN_COMPOSITION);
if (browser.isFirefox) {
define(59, KeyCode.US_SEMICOLON);
define(107, KeyCode.US_EQUAL);
define(109, KeyCode.US_MINUS);
if (platform.isMacintosh) {
define(224, KeyCode.Meta);
}
} else if (browser.isWebKit) {
define(91, KeyCode.Meta);
if (platform.isMacintosh) {
// the two meta keys in the Mac have different key codes (91 and 93)
define(93, KeyCode.Meta);
} else {
define(92, KeyCode.Meta);
}
}
})();
function extractKeyCode(e: KeyboardEvent): KeyCode {
if (e.charCode) {
// "keypress" events mostly
let char = String.fromCharCode(e.charCode).toUpperCase();
return KeyCodeUtils.fromString(char);
}
return KEY_CODE_MAP[e.keyCode] || KeyCode.Unknown;
}
export function getCodeForKeyCode(keyCode: KeyCode): number {
return INVERSE_KEY_CODE_MAP[keyCode];
}
export interface IKeyboardEvent {
readonly _standardKeyboardEventBrand: true;
readonly browserEvent: KeyboardEvent;
readonly target: HTMLElement;
readonly ctrlKey: boolean;
readonly shiftKey: boolean;
readonly altKey: boolean;
readonly metaKey: boolean;
readonly keyCode: KeyCode;
readonly code: string;
/**
* @internal
*/
toKeybinding(): SimpleKeybinding;
equals(keybinding: number): boolean;
preventDefault(): void; |
const ctrlKeyMod = (platform.isMacintosh ? KeyMod.WinCtrl : KeyMod.CtrlCmd);
const altKeyMod = KeyMod.Alt;
const shiftKeyMod = KeyMod.Shift;
const metaKeyMod = (platform.isMacintosh ? KeyMod.CtrlCmd : KeyMod.WinCtrl);
export function printKeyboardEvent(e: KeyboardEvent): string {
let modifiers: string[] = [];
if (e.ctrlKey) {
modifiers.push(`ctrl`);
}
if (e.shiftKey) {
modifiers.push(`shift`);
}
if (e.altKey) {
modifiers.push(`alt`);
}
if (e.metaKey) {
modifiers.push(`meta`);
}
return `modifiers: [${modifiers.join(',')}], code: ${e.code}, keyCode: ${e.keyCode}, key: ${e.key}`;
}
export function printStandardKeyboardEvent(e: StandardKeyboardEvent): string {
let modifiers: string[] = [];
if (e.ctrlKey) {
modifiers.push(`ctrl`);
}
if (e.shiftKey) {
modifiers.push(`shift`);
}
if (e.altKey) {
modifiers.push(`alt`);
}
if (e.metaKey) {
modifiers.push(`meta`);
}
return `modifiers: [${modifiers.join(',')}], code: ${e.code}, keyCode: ${e.keyCode} ('${KeyCodeUtils.toString(e.keyCode)}')`;
}
export class StandardKeyboardEvent implements IKeyboardEvent {
readonly _standardKeyboardEventBrand = true;
public readonly browserEvent: KeyboardEvent;
public readonly target: HTMLElement;
public readonly ctrlKey: boolean;
public readonly shiftKey: boolean;
public readonly altKey: boolean;
public readonly metaKey: boolean;
public readonly keyCode: KeyCode;
public readonly code: string;
private _asKeybinding: number;
private _asRuntimeKeybinding: SimpleKeybinding;
constructor(source: KeyboardEvent) {
let e = source;
this.browserEvent = e;
this.target = <HTMLElement>e.target;
this.ctrlKey = e.ctrlKey;
this.shiftKey = e.shiftKey;
this.altKey = e.altKey;
this.metaKey = e.metaKey;
this.keyCode = extractKeyCode(e);
this.code = e.code;
// console.info(e.type + ": keyCode: " + e.keyCode + ", which: " + e.which + ", charCode: " + e.charCode + ", detail: " + e.detail + " ====> " + this.keyCode + ' -- ' + KeyCode[this.keyCode]);
this.ctrlKey = this.ctrlKey || this.keyCode === KeyCode.Ctrl;
this.altKey = this.altKey || this.keyCode === KeyCode.Alt;
this.shiftKey = this.shiftKey || this.keyCode === KeyCode.Shift;
this.metaKey = this.metaKey || this.keyCode === KeyCode.Meta;
this._asKeybinding = this._computeKeybinding();
this._asRuntimeKeybinding = this._computeRuntimeKeybinding();
// console.log(`code: ${e.code}, keyCode: ${e.keyCode}, key: ${e.key}`);
}
public preventDefault(): void {
if (this.browserEvent && this.browserEvent.preventDefault) {
this.browserEvent.preventDefault();
}
}
public stopPropagation(): void {
if (this.browserEvent && this.browserEvent.stopPropagation) {
this.browserEvent.stopPropagation();
}
}
public toKeybinding(): SimpleKeybinding {
return this._asRuntimeKeybinding;
}
public equals(other: number): boolean {
return this._asKeybinding === other;
}
private _computeKeybinding(): number {
let key = KeyCode.Unknown;
if (this.keyCode !== KeyCode.Ctrl && this.keyCode !== KeyCode.Shift && this.keyCode !== KeyCode.Alt && this.keyCode !== KeyCode.Meta) {
key = this.keyCode;
}
let result = 0;
if (this.ctrlKey) {
result |= ctrlKeyMod;
}
if (this.altKey) {
result |= altKeyMod;
}
if (this.shiftKey) {
result |= shiftKeyMod;
}
if (this.metaKey) {
result |= metaKeyMod;
}
result |= key;
return result;
}
private _computeRuntimeKeybinding(): SimpleKeybinding {
let key = KeyCode.Unknown;
if (this.keyCode !== KeyCode.Ctrl && this.keyCode !== KeyCode.Shift && this.keyCode !== KeyCode.Alt && this.keyCode !== KeyCode.Meta) {
key = this.keyCode;
}
return new SimpleKeybinding(this.ctrlKey, this.shiftKey, this.altKey, this.metaKey, key);
}
} | stopPropagation(): void;
} | random_line_split |
compiler.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {COMPILER_OPTIONS, Compiler, CompilerFactory, CompilerOptions, Inject, Injectable, Optional, PLATFORM_INITIALIZER, PlatformRef, Provider, ReflectiveInjector, TRANSLATIONS, TRANSLATIONS_FORMAT, Type, ViewEncapsulation, createPlatformFactory, isDevMode, platformCore} from '@angular/core';
import {CompilerConfig} from './config';
import {DirectiveNormalizer} from './directive_normalizer';
import {DirectiveResolver} from './directive_resolver';
import {DirectiveWrapperCompiler} from './directive_wrapper_compiler';
import {Lexer} from './expression_parser/lexer';
import {Parser} from './expression_parser/parser';
import * as i18n from './i18n/index';
import {CompileMetadataResolver} from './metadata_resolver';
import {HtmlParser} from './ml_parser/html_parser';
import {NgModuleCompiler} from './ng_module_compiler';
import {NgModuleResolver} from './ng_module_resolver';
import {PipeResolver} from './pipe_resolver';
import {Console, ReflectionCapabilities, Reflector, ReflectorReader, reflector} from './private_import_core';
import {ResourceLoader} from './resource_loader';
import {RuntimeCompiler} from './runtime_compiler';
import {DomElementSchemaRegistry} from './schema/dom_element_schema_registry';
import {ElementSchemaRegistry} from './schema/element_schema_registry';
import {StyleCompiler} from './style_compiler';
import {TemplateParser} from './template_parser/template_parser';
import {DEFAULT_PACKAGE_URL_PROVIDER, UrlResolver} from './url_resolver';
import {ViewCompiler} from './view_compiler/view_compiler';
const _NO_RESOURCE_LOADER: ResourceLoader = {
get(url: string): Promise<string>{
throw new Error(
`No ResourceLoader implementation has been provided. Can't read the url "${url}"`);}
};
/**
* A set of providers that provide `RuntimeCompiler` and its dependencies to use for
* template compilation.
*/
export const COMPILER_PROVIDERS: Array<any|Type<any>|{[k: string]: any}|any[]> = [
{provide: Reflector, useValue: reflector},
{provide: ReflectorReader, useExisting: Reflector},
{provide: ResourceLoader, useValue: _NO_RESOURCE_LOADER},
Console,
Lexer,
Parser,
HtmlParser,
{
provide: i18n.I18NHtmlParser,
useFactory: (parser: HtmlParser, translations: string, format: string) =>
new i18n.I18NHtmlParser(parser, translations, format),
deps: [
HtmlParser,
[new Optional(), new Inject(TRANSLATIONS)],
[new Optional(), new Inject(TRANSLATIONS_FORMAT)],
]
},
TemplateParser,
DirectiveNormalizer,
CompileMetadataResolver,
DEFAULT_PACKAGE_URL_PROVIDER,
StyleCompiler,
ViewCompiler,
NgModuleCompiler,
DirectiveWrapperCompiler,
{provide: CompilerConfig, useValue: new CompilerConfig()},
RuntimeCompiler,
{provide: Compiler, useExisting: RuntimeCompiler},
DomElementSchemaRegistry,
{provide: ElementSchemaRegistry, useExisting: DomElementSchemaRegistry},
UrlResolver,
DirectiveResolver,
PipeResolver,
NgModuleResolver
];
@Injectable()
export class RuntimeCompilerFactory implements CompilerFactory {
private _defaultOptions: CompilerOptions[];
constructor(@Inject(COMPILER_OPTIONS) defaultOptions: CompilerOptions[]) {
this._defaultOptions = [<CompilerOptions>{
useDebug: isDevMode(),
useJit: true,
defaultEncapsulation: ViewEncapsulation.Emulated
}].concat(defaultOptions);
}
createCompiler(options: CompilerOptions[] = []): Compiler {
const mergedOptions = _mergeOptions(this._defaultOptions.concat(options));
const injector = ReflectiveInjector.resolveAndCreate([
COMPILER_PROVIDERS, {
provide: CompilerConfig,
useFactory: () => {
return new CompilerConfig({
// let explicit values from the compiler options overwrite options
// from the app providers. E.g. important for the testing platform.
genDebugInfo: mergedOptions.useDebug,
// let explicit values from the compiler options overwrite options
// from the app providers
useJit: mergedOptions.useJit,
// let explicit values from the compiler options overwrite options
// from the app providers
defaultEncapsulation: mergedOptions.defaultEncapsulation,
logBindingUpdate: mergedOptions.useDebug
});
},
deps: []
},
mergedOptions.providers
]);
return injector.get(Compiler);
}
}
function | () {
reflector.reflectionCapabilities = new ReflectionCapabilities();
}
/**
* A platform that included corePlatform and the compiler.
*
* @experimental
*/
export const platformCoreDynamic = createPlatformFactory(platformCore, 'coreDynamic', [
{provide: COMPILER_OPTIONS, useValue: {}, multi: true},
{provide: CompilerFactory, useClass: RuntimeCompilerFactory},
{provide: PLATFORM_INITIALIZER, useValue: _initReflector, multi: true},
]);
function _mergeOptions(optionsArr: CompilerOptions[]): CompilerOptions {
return {
useDebug: _lastDefined(optionsArr.map(options => options.useDebug)),
useJit: _lastDefined(optionsArr.map(options => options.useJit)),
defaultEncapsulation: _lastDefined(optionsArr.map(options => options.defaultEncapsulation)),
providers: _mergeArrays(optionsArr.map(options => options.providers))
};
}
function _lastDefined<T>(args: T[]): T {
for (var i = args.length - 1; i >= 0; i--) {
if (args[i] !== undefined) {
return args[i];
}
}
return undefined;
}
function _mergeArrays(parts: any[][]): any[] {
let result: any[] = [];
parts.forEach((part) => part && result.push(...part));
return result;
}
| _initReflector | identifier_name |
compiler.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {COMPILER_OPTIONS, Compiler, CompilerFactory, CompilerOptions, Inject, Injectable, Optional, PLATFORM_INITIALIZER, PlatformRef, Provider, ReflectiveInjector, TRANSLATIONS, TRANSLATIONS_FORMAT, Type, ViewEncapsulation, createPlatformFactory, isDevMode, platformCore} from '@angular/core';
import {CompilerConfig} from './config';
import {DirectiveNormalizer} from './directive_normalizer';
import {DirectiveResolver} from './directive_resolver';
import {DirectiveWrapperCompiler} from './directive_wrapper_compiler';
import {Lexer} from './expression_parser/lexer';
import {Parser} from './expression_parser/parser';
import * as i18n from './i18n/index';
import {CompileMetadataResolver} from './metadata_resolver';
import {HtmlParser} from './ml_parser/html_parser';
import {NgModuleCompiler} from './ng_module_compiler';
import {NgModuleResolver} from './ng_module_resolver';
import {PipeResolver} from './pipe_resolver';
import {Console, ReflectionCapabilities, Reflector, ReflectorReader, reflector} from './private_import_core';
import {ResourceLoader} from './resource_loader';
import {RuntimeCompiler} from './runtime_compiler';
import {DomElementSchemaRegistry} from './schema/dom_element_schema_registry';
import {ElementSchemaRegistry} from './schema/element_schema_registry';
import {StyleCompiler} from './style_compiler';
import {TemplateParser} from './template_parser/template_parser';
import {DEFAULT_PACKAGE_URL_PROVIDER, UrlResolver} from './url_resolver';
import {ViewCompiler} from './view_compiler/view_compiler';
const _NO_RESOURCE_LOADER: ResourceLoader = {
get(url: string): Promise<string>{
throw new Error(
`No ResourceLoader implementation has been provided. Can't read the url "${url}"`);}
};
/**
* A set of providers that provide `RuntimeCompiler` and its dependencies to use for
* template compilation. | */
export const COMPILER_PROVIDERS: Array<any|Type<any>|{[k: string]: any}|any[]> = [
{provide: Reflector, useValue: reflector},
{provide: ReflectorReader, useExisting: Reflector},
{provide: ResourceLoader, useValue: _NO_RESOURCE_LOADER},
Console,
Lexer,
Parser,
HtmlParser,
{
provide: i18n.I18NHtmlParser,
useFactory: (parser: HtmlParser, translations: string, format: string) =>
new i18n.I18NHtmlParser(parser, translations, format),
deps: [
HtmlParser,
[new Optional(), new Inject(TRANSLATIONS)],
[new Optional(), new Inject(TRANSLATIONS_FORMAT)],
]
},
TemplateParser,
DirectiveNormalizer,
CompileMetadataResolver,
DEFAULT_PACKAGE_URL_PROVIDER,
StyleCompiler,
ViewCompiler,
NgModuleCompiler,
DirectiveWrapperCompiler,
{provide: CompilerConfig, useValue: new CompilerConfig()},
RuntimeCompiler,
{provide: Compiler, useExisting: RuntimeCompiler},
DomElementSchemaRegistry,
{provide: ElementSchemaRegistry, useExisting: DomElementSchemaRegistry},
UrlResolver,
DirectiveResolver,
PipeResolver,
NgModuleResolver
];
@Injectable()
export class RuntimeCompilerFactory implements CompilerFactory {
private _defaultOptions: CompilerOptions[];
constructor(@Inject(COMPILER_OPTIONS) defaultOptions: CompilerOptions[]) {
this._defaultOptions = [<CompilerOptions>{
useDebug: isDevMode(),
useJit: true,
defaultEncapsulation: ViewEncapsulation.Emulated
}].concat(defaultOptions);
}
createCompiler(options: CompilerOptions[] = []): Compiler {
const mergedOptions = _mergeOptions(this._defaultOptions.concat(options));
const injector = ReflectiveInjector.resolveAndCreate([
COMPILER_PROVIDERS, {
provide: CompilerConfig,
useFactory: () => {
return new CompilerConfig({
// let explicit values from the compiler options overwrite options
// from the app providers. E.g. important for the testing platform.
genDebugInfo: mergedOptions.useDebug,
// let explicit values from the compiler options overwrite options
// from the app providers
useJit: mergedOptions.useJit,
// let explicit values from the compiler options overwrite options
// from the app providers
defaultEncapsulation: mergedOptions.defaultEncapsulation,
logBindingUpdate: mergedOptions.useDebug
});
},
deps: []
},
mergedOptions.providers
]);
return injector.get(Compiler);
}
}
function _initReflector() {
reflector.reflectionCapabilities = new ReflectionCapabilities();
}
/**
* A platform that included corePlatform and the compiler.
*
* @experimental
*/
export const platformCoreDynamic = createPlatformFactory(platformCore, 'coreDynamic', [
{provide: COMPILER_OPTIONS, useValue: {}, multi: true},
{provide: CompilerFactory, useClass: RuntimeCompilerFactory},
{provide: PLATFORM_INITIALIZER, useValue: _initReflector, multi: true},
]);
function _mergeOptions(optionsArr: CompilerOptions[]): CompilerOptions {
return {
useDebug: _lastDefined(optionsArr.map(options => options.useDebug)),
useJit: _lastDefined(optionsArr.map(options => options.useJit)),
defaultEncapsulation: _lastDefined(optionsArr.map(options => options.defaultEncapsulation)),
providers: _mergeArrays(optionsArr.map(options => options.providers))
};
}
function _lastDefined<T>(args: T[]): T {
for (var i = args.length - 1; i >= 0; i--) {
if (args[i] !== undefined) {
return args[i];
}
}
return undefined;
}
function _mergeArrays(parts: any[][]): any[] {
let result: any[] = [];
parts.forEach((part) => part && result.push(...part));
return result;
} | random_line_split | |
compiler.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {COMPILER_OPTIONS, Compiler, CompilerFactory, CompilerOptions, Inject, Injectable, Optional, PLATFORM_INITIALIZER, PlatformRef, Provider, ReflectiveInjector, TRANSLATIONS, TRANSLATIONS_FORMAT, Type, ViewEncapsulation, createPlatformFactory, isDevMode, platformCore} from '@angular/core';
import {CompilerConfig} from './config';
import {DirectiveNormalizer} from './directive_normalizer';
import {DirectiveResolver} from './directive_resolver';
import {DirectiveWrapperCompiler} from './directive_wrapper_compiler';
import {Lexer} from './expression_parser/lexer';
import {Parser} from './expression_parser/parser';
import * as i18n from './i18n/index';
import {CompileMetadataResolver} from './metadata_resolver';
import {HtmlParser} from './ml_parser/html_parser';
import {NgModuleCompiler} from './ng_module_compiler';
import {NgModuleResolver} from './ng_module_resolver';
import {PipeResolver} from './pipe_resolver';
import {Console, ReflectionCapabilities, Reflector, ReflectorReader, reflector} from './private_import_core';
import {ResourceLoader} from './resource_loader';
import {RuntimeCompiler} from './runtime_compiler';
import {DomElementSchemaRegistry} from './schema/dom_element_schema_registry';
import {ElementSchemaRegistry} from './schema/element_schema_registry';
import {StyleCompiler} from './style_compiler';
import {TemplateParser} from './template_parser/template_parser';
import {DEFAULT_PACKAGE_URL_PROVIDER, UrlResolver} from './url_resolver';
import {ViewCompiler} from './view_compiler/view_compiler';
const _NO_RESOURCE_LOADER: ResourceLoader = {
get(url: string): Promise<string>{
throw new Error(
`No ResourceLoader implementation has been provided. Can't read the url "${url}"`);}
};
/**
* A set of providers that provide `RuntimeCompiler` and its dependencies to use for
* template compilation.
*/
export const COMPILER_PROVIDERS: Array<any|Type<any>|{[k: string]: any}|any[]> = [
{provide: Reflector, useValue: reflector},
{provide: ReflectorReader, useExisting: Reflector},
{provide: ResourceLoader, useValue: _NO_RESOURCE_LOADER},
Console,
Lexer,
Parser,
HtmlParser,
{
provide: i18n.I18NHtmlParser,
useFactory: (parser: HtmlParser, translations: string, format: string) =>
new i18n.I18NHtmlParser(parser, translations, format),
deps: [
HtmlParser,
[new Optional(), new Inject(TRANSLATIONS)],
[new Optional(), new Inject(TRANSLATIONS_FORMAT)],
]
},
TemplateParser,
DirectiveNormalizer,
CompileMetadataResolver,
DEFAULT_PACKAGE_URL_PROVIDER,
StyleCompiler,
ViewCompiler,
NgModuleCompiler,
DirectiveWrapperCompiler,
{provide: CompilerConfig, useValue: new CompilerConfig()},
RuntimeCompiler,
{provide: Compiler, useExisting: RuntimeCompiler},
DomElementSchemaRegistry,
{provide: ElementSchemaRegistry, useExisting: DomElementSchemaRegistry},
UrlResolver,
DirectiveResolver,
PipeResolver,
NgModuleResolver
];
@Injectable()
export class RuntimeCompilerFactory implements CompilerFactory {
private _defaultOptions: CompilerOptions[];
constructor(@Inject(COMPILER_OPTIONS) defaultOptions: CompilerOptions[]) {
this._defaultOptions = [<CompilerOptions>{
useDebug: isDevMode(),
useJit: true,
defaultEncapsulation: ViewEncapsulation.Emulated
}].concat(defaultOptions);
}
createCompiler(options: CompilerOptions[] = []): Compiler {
const mergedOptions = _mergeOptions(this._defaultOptions.concat(options));
const injector = ReflectiveInjector.resolveAndCreate([
COMPILER_PROVIDERS, {
provide: CompilerConfig,
useFactory: () => {
return new CompilerConfig({
// let explicit values from the compiler options overwrite options
// from the app providers. E.g. important for the testing platform.
genDebugInfo: mergedOptions.useDebug,
// let explicit values from the compiler options overwrite options
// from the app providers
useJit: mergedOptions.useJit,
// let explicit values from the compiler options overwrite options
// from the app providers
defaultEncapsulation: mergedOptions.defaultEncapsulation,
logBindingUpdate: mergedOptions.useDebug
});
},
deps: []
},
mergedOptions.providers
]);
return injector.get(Compiler);
}
}
function _initReflector() {
reflector.reflectionCapabilities = new ReflectionCapabilities();
}
/**
* A platform that included corePlatform and the compiler.
*
* @experimental
*/
export const platformCoreDynamic = createPlatformFactory(platformCore, 'coreDynamic', [
{provide: COMPILER_OPTIONS, useValue: {}, multi: true},
{provide: CompilerFactory, useClass: RuntimeCompilerFactory},
{provide: PLATFORM_INITIALIZER, useValue: _initReflector, multi: true},
]);
function _mergeOptions(optionsArr: CompilerOptions[]): CompilerOptions |
function _lastDefined<T>(args: T[]): T {
for (var i = args.length - 1; i >= 0; i--) {
if (args[i] !== undefined) {
return args[i];
}
}
return undefined;
}
function _mergeArrays(parts: any[][]): any[] {
let result: any[] = [];
parts.forEach((part) => part && result.push(...part));
return result;
}
| {
return {
useDebug: _lastDefined(optionsArr.map(options => options.useDebug)),
useJit: _lastDefined(optionsArr.map(options => options.useJit)),
defaultEncapsulation: _lastDefined(optionsArr.map(options => options.defaultEncapsulation)),
providers: _mergeArrays(optionsArr.map(options => options.providers))
};
} | identifier_body |
compiler.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {COMPILER_OPTIONS, Compiler, CompilerFactory, CompilerOptions, Inject, Injectable, Optional, PLATFORM_INITIALIZER, PlatformRef, Provider, ReflectiveInjector, TRANSLATIONS, TRANSLATIONS_FORMAT, Type, ViewEncapsulation, createPlatformFactory, isDevMode, platformCore} from '@angular/core';
import {CompilerConfig} from './config';
import {DirectiveNormalizer} from './directive_normalizer';
import {DirectiveResolver} from './directive_resolver';
import {DirectiveWrapperCompiler} from './directive_wrapper_compiler';
import {Lexer} from './expression_parser/lexer';
import {Parser} from './expression_parser/parser';
import * as i18n from './i18n/index';
import {CompileMetadataResolver} from './metadata_resolver';
import {HtmlParser} from './ml_parser/html_parser';
import {NgModuleCompiler} from './ng_module_compiler';
import {NgModuleResolver} from './ng_module_resolver';
import {PipeResolver} from './pipe_resolver';
import {Console, ReflectionCapabilities, Reflector, ReflectorReader, reflector} from './private_import_core';
import {ResourceLoader} from './resource_loader';
import {RuntimeCompiler} from './runtime_compiler';
import {DomElementSchemaRegistry} from './schema/dom_element_schema_registry';
import {ElementSchemaRegistry} from './schema/element_schema_registry';
import {StyleCompiler} from './style_compiler';
import {TemplateParser} from './template_parser/template_parser';
import {DEFAULT_PACKAGE_URL_PROVIDER, UrlResolver} from './url_resolver';
import {ViewCompiler} from './view_compiler/view_compiler';
const _NO_RESOURCE_LOADER: ResourceLoader = {
get(url: string): Promise<string>{
throw new Error(
`No ResourceLoader implementation has been provided. Can't read the url "${url}"`);}
};
/**
* A set of providers that provide `RuntimeCompiler` and its dependencies to use for
* template compilation.
*/
export const COMPILER_PROVIDERS: Array<any|Type<any>|{[k: string]: any}|any[]> = [
{provide: Reflector, useValue: reflector},
{provide: ReflectorReader, useExisting: Reflector},
{provide: ResourceLoader, useValue: _NO_RESOURCE_LOADER},
Console,
Lexer,
Parser,
HtmlParser,
{
provide: i18n.I18NHtmlParser,
useFactory: (parser: HtmlParser, translations: string, format: string) =>
new i18n.I18NHtmlParser(parser, translations, format),
deps: [
HtmlParser,
[new Optional(), new Inject(TRANSLATIONS)],
[new Optional(), new Inject(TRANSLATIONS_FORMAT)],
]
},
TemplateParser,
DirectiveNormalizer,
CompileMetadataResolver,
DEFAULT_PACKAGE_URL_PROVIDER,
StyleCompiler,
ViewCompiler,
NgModuleCompiler,
DirectiveWrapperCompiler,
{provide: CompilerConfig, useValue: new CompilerConfig()},
RuntimeCompiler,
{provide: Compiler, useExisting: RuntimeCompiler},
DomElementSchemaRegistry,
{provide: ElementSchemaRegistry, useExisting: DomElementSchemaRegistry},
UrlResolver,
DirectiveResolver,
PipeResolver,
NgModuleResolver
];
@Injectable()
export class RuntimeCompilerFactory implements CompilerFactory {
private _defaultOptions: CompilerOptions[];
constructor(@Inject(COMPILER_OPTIONS) defaultOptions: CompilerOptions[]) {
this._defaultOptions = [<CompilerOptions>{
useDebug: isDevMode(),
useJit: true,
defaultEncapsulation: ViewEncapsulation.Emulated
}].concat(defaultOptions);
}
createCompiler(options: CompilerOptions[] = []): Compiler {
const mergedOptions = _mergeOptions(this._defaultOptions.concat(options));
const injector = ReflectiveInjector.resolveAndCreate([
COMPILER_PROVIDERS, {
provide: CompilerConfig,
useFactory: () => {
return new CompilerConfig({
// let explicit values from the compiler options overwrite options
// from the app providers. E.g. important for the testing platform.
genDebugInfo: mergedOptions.useDebug,
// let explicit values from the compiler options overwrite options
// from the app providers
useJit: mergedOptions.useJit,
// let explicit values from the compiler options overwrite options
// from the app providers
defaultEncapsulation: mergedOptions.defaultEncapsulation,
logBindingUpdate: mergedOptions.useDebug
});
},
deps: []
},
mergedOptions.providers
]);
return injector.get(Compiler);
}
}
function _initReflector() {
reflector.reflectionCapabilities = new ReflectionCapabilities();
}
/**
* A platform that included corePlatform and the compiler.
*
* @experimental
*/
export const platformCoreDynamic = createPlatformFactory(platformCore, 'coreDynamic', [
{provide: COMPILER_OPTIONS, useValue: {}, multi: true},
{provide: CompilerFactory, useClass: RuntimeCompilerFactory},
{provide: PLATFORM_INITIALIZER, useValue: _initReflector, multi: true},
]);
function _mergeOptions(optionsArr: CompilerOptions[]): CompilerOptions {
return {
useDebug: _lastDefined(optionsArr.map(options => options.useDebug)),
useJit: _lastDefined(optionsArr.map(options => options.useJit)),
defaultEncapsulation: _lastDefined(optionsArr.map(options => options.defaultEncapsulation)),
providers: _mergeArrays(optionsArr.map(options => options.providers))
};
}
function _lastDefined<T>(args: T[]): T {
for (var i = args.length - 1; i >= 0; i--) {
if (args[i] !== undefined) |
}
return undefined;
}
function _mergeArrays(parts: any[][]): any[] {
let result: any[] = [];
parts.forEach((part) => part && result.push(...part));
return result;
}
| {
return args[i];
} | conditional_block |
route-list.rs | extern crate neli;
use std::error::Error;
use std::net::IpAddr;
use neli::consts::*;
use neli::err::NlError;
use neli::nl::Nlmsghdr;
use neli::rtnl::*;
use neli::socket::*;
fn parse_route_table(rtm: Nlmsghdr<Rtm, Rtmsg>) |
/// This sample is a simple imitation of the `ip route` command, to demonstrate interaction
/// with the rtnetlink subsystem.
fn main() -> Result<(), Box<dyn Error>> {
let mut socket = NlSocket::connect(NlFamily::Route, None, None, true).unwrap();
let rtmsg = Rtmsg {
rtm_family: RtAddrFamily::Inet,
rtm_dst_len: 0,
rtm_src_len: 0,
rtm_tos: 0,
rtm_table: RtTable::Unspec,
rtm_protocol: Rtprot::Unspec,
rtm_scope: RtScope::Universe,
rtm_type: Rtn::Unspec,
rtm_flags: vec![],
rtattrs: Rtattrs::empty(),
};
let nlhdr = {
let len = None;
let nl_type = Rtm::Getroute;
let flags = vec![NlmF::Request, NlmF::Dump];
let seq = None;
let pid = None;
let payload = rtmsg;
Nlmsghdr::new(len, nl_type, flags, seq, pid, payload)
};
socket.send_nl(nlhdr).unwrap();
// Provisionally deserialize as a Nlmsg first.
let nl = socket.recv_nl::<Rtm, Rtmsg>(None)?;
let multi_msg = nl.nl_flags.contains(&NlmF::Multi);
parse_route_table(nl);
if multi_msg {
while let Ok(nl) = socket.recv_nl::<u16, Rtmsg>(None) {
match Nlmsg::from(nl.nl_type) {
Nlmsg::Done => return Ok(()),
Nlmsg::Error => return Err(Box::new(NlError::new("rtnetlink error."))),
_ => {
let rtm = Nlmsghdr {
nl_len: nl.nl_len,
nl_type: Rtm::from(nl.nl_type),
nl_flags: nl.nl_flags,
nl_seq: nl.nl_seq,
nl_pid: nl.nl_pid,
nl_payload: nl.nl_payload,
};
// Some other message type, so let's try to deserialize as a Rtm.
parse_route_table(rtm)
}
}
}
}
Ok(())
}
| {
// This sample is only interested in the main table.
if rtm.nl_payload.rtm_table == RtTable::Main {
let mut src = None;
let mut dst = None;
let mut gateway = None;
for attr in rtm.nl_payload.rtattrs.iter() {
fn to_addr(b: &[u8]) -> Option<IpAddr> {
use std::convert::TryFrom;
if let Ok(tup) = <&[u8; 4]>::try_from(b) {
Some(IpAddr::from(*tup))
} else if let Ok(tup) = <&[u8; 16]>::try_from(b) {
Some(IpAddr::from(*tup))
} else {
None
}
}
match attr.rta_type {
Rta::Dst => dst = to_addr(&attr.rta_payload),
Rta::Prefsrc => src = to_addr(&attr.rta_payload),
Rta::Gateway => gateway = to_addr(&attr.rta_payload),
_ => (),
}
}
if let Some(dst) = dst {
print!("{}/{} ", dst, rtm.nl_payload.rtm_dst_len);
} else {
print!("default ");
if let Some(gateway) = gateway {
print!("via {} ", gateway);
}
}
if rtm.nl_payload.rtm_scope != RtScope::Universe {
print!(
" proto {:?} scope {:?} ",
rtm.nl_payload.rtm_protocol, rtm.nl_payload.rtm_scope
)
}
if let Some(src) = src {
print!(" src {} ", src);
}
println!();
}
} | identifier_body |
route-list.rs | extern crate neli;
use std::error::Error;
use std::net::IpAddr;
use neli::consts::*;
use neli::err::NlError;
use neli::nl::Nlmsghdr;
use neli::rtnl::*;
use neli::socket::*;
fn parse_route_table(rtm: Nlmsghdr<Rtm, Rtmsg>) {
// This sample is only interested in the main table.
if rtm.nl_payload.rtm_table == RtTable::Main {
let mut src = None;
let mut dst = None;
let mut gateway = None;
for attr in rtm.nl_payload.rtattrs.iter() {
fn to_addr(b: &[u8]) -> Option<IpAddr> {
use std::convert::TryFrom;
if let Ok(tup) = <&[u8; 4]>::try_from(b) {
Some(IpAddr::from(*tup))
} else if let Ok(tup) = <&[u8; 16]>::try_from(b) {
Some(IpAddr::from(*tup))
} else {
None
}
}
match attr.rta_type {
Rta::Dst => dst = to_addr(&attr.rta_payload),
Rta::Prefsrc => src = to_addr(&attr.rta_payload),
Rta::Gateway => gateway = to_addr(&attr.rta_payload),
_ => (),
}
}
if let Some(dst) = dst {
print!("{}/{} ", dst, rtm.nl_payload.rtm_dst_len);
} else {
print!("default ");
if let Some(gateway) = gateway {
print!("via {} ", gateway);
}
}
if rtm.nl_payload.rtm_scope != RtScope::Universe {
print!(
" proto {:?} scope {:?} ",
rtm.nl_payload.rtm_protocol, rtm.nl_payload.rtm_scope
)
}
if let Some(src) = src {
print!(" src {} ", src);
}
println!();
}
}
/// This sample is a simple imitation of the `ip route` command, to demonstrate interaction
/// with the rtnetlink subsystem.
fn | () -> Result<(), Box<dyn Error>> {
let mut socket = NlSocket::connect(NlFamily::Route, None, None, true).unwrap();
let rtmsg = Rtmsg {
rtm_family: RtAddrFamily::Inet,
rtm_dst_len: 0,
rtm_src_len: 0,
rtm_tos: 0,
rtm_table: RtTable::Unspec,
rtm_protocol: Rtprot::Unspec,
rtm_scope: RtScope::Universe,
rtm_type: Rtn::Unspec,
rtm_flags: vec![],
rtattrs: Rtattrs::empty(),
};
let nlhdr = {
let len = None;
let nl_type = Rtm::Getroute;
let flags = vec![NlmF::Request, NlmF::Dump];
let seq = None;
let pid = None;
let payload = rtmsg;
Nlmsghdr::new(len, nl_type, flags, seq, pid, payload)
};
socket.send_nl(nlhdr).unwrap();
// Provisionally deserialize as a Nlmsg first.
let nl = socket.recv_nl::<Rtm, Rtmsg>(None)?;
let multi_msg = nl.nl_flags.contains(&NlmF::Multi);
parse_route_table(nl);
if multi_msg {
while let Ok(nl) = socket.recv_nl::<u16, Rtmsg>(None) {
match Nlmsg::from(nl.nl_type) {
Nlmsg::Done => return Ok(()),
Nlmsg::Error => return Err(Box::new(NlError::new("rtnetlink error."))),
_ => {
let rtm = Nlmsghdr {
nl_len: nl.nl_len,
nl_type: Rtm::from(nl.nl_type),
nl_flags: nl.nl_flags,
nl_seq: nl.nl_seq,
nl_pid: nl.nl_pid,
nl_payload: nl.nl_payload,
};
// Some other message type, so let's try to deserialize as a Rtm.
parse_route_table(rtm)
}
}
}
}
Ok(())
}
| main | identifier_name |
route-list.rs | extern crate neli;
use std::error::Error;
use std::net::IpAddr;
use neli::consts::*;
use neli::err::NlError;
use neli::nl::Nlmsghdr;
use neli::rtnl::*;
use neli::socket::*;
fn parse_route_table(rtm: Nlmsghdr<Rtm, Rtmsg>) {
// This sample is only interested in the main table.
if rtm.nl_payload.rtm_table == RtTable::Main {
let mut src = None;
let mut dst = None;
let mut gateway = None;
for attr in rtm.nl_payload.rtattrs.iter() {
fn to_addr(b: &[u8]) -> Option<IpAddr> {
use std::convert::TryFrom;
if let Ok(tup) = <&[u8; 4]>::try_from(b) {
Some(IpAddr::from(*tup))
} else if let Ok(tup) = <&[u8; 16]>::try_from(b) {
Some(IpAddr::from(*tup))
} else {
None
}
}
match attr.rta_type {
Rta::Dst => dst = to_addr(&attr.rta_payload),
Rta::Prefsrc => src = to_addr(&attr.rta_payload),
Rta::Gateway => gateway = to_addr(&attr.rta_payload),
_ => (),
}
}
if let Some(dst) = dst {
print!("{}/{} ", dst, rtm.nl_payload.rtm_dst_len);
} else {
print!("default ");
if let Some(gateway) = gateway {
print!("via {} ", gateway);
}
}
if rtm.nl_payload.rtm_scope != RtScope::Universe {
print!(
" proto {:?} scope {:?} ",
rtm.nl_payload.rtm_protocol, rtm.nl_payload.rtm_scope
)
}
if let Some(src) = src {
print!(" src {} ", src);
}
println!();
}
}
/// This sample is a simple imitation of the `ip route` command, to demonstrate interaction
/// with the rtnetlink subsystem.
fn main() -> Result<(), Box<dyn Error>> {
let mut socket = NlSocket::connect(NlFamily::Route, None, None, true).unwrap();
let rtmsg = Rtmsg {
rtm_family: RtAddrFamily::Inet,
rtm_dst_len: 0,
rtm_src_len: 0,
rtm_tos: 0,
rtm_table: RtTable::Unspec,
rtm_protocol: Rtprot::Unspec,
rtm_scope: RtScope::Universe,
rtm_type: Rtn::Unspec,
rtm_flags: vec![],
rtattrs: Rtattrs::empty(),
};
let nlhdr = {
let len = None;
let nl_type = Rtm::Getroute;
let flags = vec![NlmF::Request, NlmF::Dump];
let seq = None;
let pid = None;
let payload = rtmsg;
Nlmsghdr::new(len, nl_type, flags, seq, pid, payload)
};
socket.send_nl(nlhdr).unwrap();
// Provisionally deserialize as a Nlmsg first.
let nl = socket.recv_nl::<Rtm, Rtmsg>(None)?;
let multi_msg = nl.nl_flags.contains(&NlmF::Multi);
parse_route_table(nl);
if multi_msg {
while let Ok(nl) = socket.recv_nl::<u16, Rtmsg>(None) {
match Nlmsg::from(nl.nl_type) {
Nlmsg::Done => return Ok(()),
Nlmsg::Error => return Err(Box::new(NlError::new("rtnetlink error."))),
_ => {
let rtm = Nlmsghdr {
nl_len: nl.nl_len,
nl_type: Rtm::from(nl.nl_type),
nl_flags: nl.nl_flags,
nl_seq: nl.nl_seq,
nl_pid: nl.nl_pid, | }
}
}
}
Ok(())
} | nl_payload: nl.nl_payload,
};
// Some other message type, so let's try to deserialize as a Rtm.
parse_route_table(rtm) | random_line_split |
handlebars.items-stored.js | (function() {
var template = Handlebars.template, templates = Handlebars.templates = Handlebars.templates || {}; | templates['items-stored'] = template({"1":function(container,depth0,helpers,partials,data) {
var helper, alias1=depth0 != null ? depth0 : {}, alias2=helpers.helperMissing, alias3="function", alias4=container.escapeExpression;
return "<tr>\n <td><i class=\"icon-"
+ alias4(((helper = (helper = helpers.smiling || (depth0 != null ? depth0.smiling : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"smiling","hash":{},"data":data}) : helper)))
+ "\"></i></td>\n <td>\n <div class=\"table-results-imc\">"
+ alias4(((helper = (helper = helpers.imc || (depth0 != null ? depth0.imc : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"imc","hash":{},"data":data}) : helper)))
+ "</div>\n </td>\n <td>\n <div class=\"table-results-info\">\n <div class=\"table-results-name\">"
+ alias4(((helper = (helper = helpers.name || (depth0 != null ? depth0.name : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"name","hash":{},"data":data}) : helper)))
+ "</div>\n <div class=\"table-results-data\">"
+ alias4(((helper = (helper = helpers.date || (depth0 != null ? depth0.date : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"date","hash":{},"data":data}) : helper)))
+ "</div>\n <div class=\"table-results-time\">"
+ alias4(((helper = (helper = helpers.hours || (depth0 != null ? depth0.hours : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"hours","hash":{},"data":data}) : helper)))
+ "</div>\n </div>\n </td>\n</tr>\n";
},"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) {
var stack1;
return ((stack1 = helpers.each.call(depth0 != null ? depth0 : {},depth0,{"name":"each","hash":{},"fn":container.program(1, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : "");
},"useData":true});
})(); | random_line_split | |
rte.py | # coding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..compat import compat_HTTPError
from ..utils import (
float_or_none,
parse_iso8601,
str_or_none,
try_get,
unescapeHTML,
url_or_none,
ExtractorError,
)
class RteBaseIE(InfoExtractor):
def _real_extract(self, url):
item_id = self._match_id(url)
info_dict = {}
formats = []
ENDPOINTS = (
'https://feeds.rasset.ie/rteavgen/player/playlist?type=iptv&format=json&showId=',
'http://www.rte.ie/rteavgen/getplaylist/?type=web&format=json&id=',
)
for num, ep_url in enumerate(ENDPOINTS, start=1):
try:
data = self._download_json(ep_url + item_id, item_id)
except ExtractorError as ee:
if num < len(ENDPOINTS) or formats:
continue
if isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 404:
error_info = self._parse_json(ee.cause.read().decode(), item_id, fatal=False)
if error_info:
raise ExtractorError(
'%s said: %s' % (self.IE_NAME, error_info['message']),
expected=True)
raise
# NB the string values in the JSON are stored using XML escaping(!)
show = try_get(data, lambda x: x['shows'][0], dict)
if not show:
continue
if not info_dict:
title = unescapeHTML(show['title'])
description = unescapeHTML(show.get('description'))
thumbnail = show.get('thumbnail')
duration = float_or_none(show.get('duration'), 1000)
timestamp = parse_iso8601(show.get('published'))
info_dict = {
'id': item_id,
'title': title,
'description': description,
'thumbnail': thumbnail,
'timestamp': timestamp,
'duration': duration,
}
mg = try_get(show, lambda x: x['media:group'][0], dict)
if not mg:
continue
if mg.get('url'):
m = re.match(r'(?P<url>rtmpe?://[^/]+)/(?P<app>.+)/(?P<playpath>mp4:.*)', mg['url'])
if m:
|
if mg.get('hls_server') and mg.get('hls_url'):
formats.extend(self._extract_m3u8_formats(
mg['hls_server'] + mg['hls_url'], item_id, 'mp4',
entry_protocol='m3u8_native', m3u8_id='hls', fatal=False))
if mg.get('hds_server') and mg.get('hds_url'):
formats.extend(self._extract_f4m_formats(
mg['hds_server'] + mg['hds_url'], item_id,
f4m_id='hds', fatal=False))
mg_rte_server = str_or_none(mg.get('rte:server'))
mg_url = str_or_none(mg.get('url'))
if mg_rte_server and mg_url:
hds_url = url_or_none(mg_rte_server + mg_url)
if hds_url:
formats.extend(self._extract_f4m_formats(
hds_url, item_id, f4m_id='hds', fatal=False))
self._sort_formats(formats)
info_dict['formats'] = formats
return info_dict
class RteIE(RteBaseIE):
IE_NAME = 'rte'
IE_DESC = 'Raidió Teilifís Éireann TV'
_VALID_URL = r'https?://(?:www\.)?rte\.ie/player/[^/]{2,3}/show/[^/]+/(?P<id>[0-9]+)'
_TEST = {
'url': 'http://www.rte.ie/player/ie/show/iwitness-862/10478715/',
'md5': '4a76eb3396d98f697e6e8110563d2604',
'info_dict': {
'id': '10478715',
'ext': 'mp4',
'title': 'iWitness',
'thumbnail': r're:^https?://.*\.jpg$',
'description': 'The spirit of Ireland, one voice and one minute at a time.',
'duration': 60.046,
'upload_date': '20151012',
'timestamp': 1444694160,
},
}
class RteRadioIE(RteBaseIE):
IE_NAME = 'rte:radio'
IE_DESC = 'Raidió Teilifís Éireann radio'
# Radioplayer URLs have two distinct specifier formats,
# the old format #!rii=<channel_id>:<id>:<playable_item_id>:<date>:
# the new format #!rii=b<channel_id>_<id>_<playable_item_id>_<date>_
# where the IDs are int/empty, the date is DD-MM-YYYY, and the specifier may be truncated.
# An <id> uniquely defines an individual recording, and is the only part we require.
_VALID_URL = r'https?://(?:www\.)?rte\.ie/radio/utils/radioplayer/rteradioweb\.html#!rii=(?:b?[0-9]*)(?:%3A|:|%5F|_)(?P<id>[0-9]+)'
_TESTS = [{
# Old-style player URL; HLS and RTMPE formats
'url': 'http://www.rte.ie/radio/utils/radioplayer/rteradioweb.html#!rii=16:10507902:2414:27-12-2015:',
'md5': 'c79ccb2c195998440065456b69760411',
'info_dict': {
'id': '10507902',
'ext': 'mp4',
'title': 'Gloria',
'thumbnail': r're:^https?://.*\.jpg$',
'description': 'md5:9ce124a7fb41559ec68f06387cabddf0',
'timestamp': 1451203200,
'upload_date': '20151227',
'duration': 7230.0,
},
}, {
# New-style player URL; RTMPE formats only
'url': 'http://rte.ie/radio/utils/radioplayer/rteradioweb.html#!rii=b16_3250678_8861_06-04-2012_',
'info_dict': {
'id': '3250678',
'ext': 'flv',
'title': 'The Lyric Concert with Paul Herriott',
'thumbnail': r're:^https?://.*\.jpg$',
'description': '',
'timestamp': 1333742400,
'upload_date': '20120406',
'duration': 7199.016,
},
'params': {
# rtmp download
'skip_download': True,
},
}]
| m = m.groupdict()
formats.append({
'url': m['url'] + '/' + m['app'],
'app': m['app'],
'play_path': m['playpath'],
'player_url': url,
'ext': 'flv',
'format_id': 'rtmp',
}) | conditional_block |
rte.py | # coding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..compat import compat_HTTPError
from ..utils import (
float_or_none,
parse_iso8601,
str_or_none,
try_get,
unescapeHTML,
url_or_none,
ExtractorError,
)
class RteBaseIE(InfoExtractor):
def _real_extract(self, url):
item_id = self._match_id(url)
info_dict = {}
formats = []
ENDPOINTS = (
'https://feeds.rasset.ie/rteavgen/player/playlist?type=iptv&format=json&showId=',
'http://www.rte.ie/rteavgen/getplaylist/?type=web&format=json&id=',
)
for num, ep_url in enumerate(ENDPOINTS, start=1):
try:
data = self._download_json(ep_url + item_id, item_id)
except ExtractorError as ee:
if num < len(ENDPOINTS) or formats:
continue
if isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 404:
error_info = self._parse_json(ee.cause.read().decode(), item_id, fatal=False)
if error_info:
raise ExtractorError(
'%s said: %s' % (self.IE_NAME, error_info['message']),
expected=True)
raise
# NB the string values in the JSON are stored using XML escaping(!)
show = try_get(data, lambda x: x['shows'][0], dict)
if not show:
continue
| if not info_dict:
title = unescapeHTML(show['title'])
description = unescapeHTML(show.get('description'))
thumbnail = show.get('thumbnail')
duration = float_or_none(show.get('duration'), 1000)
timestamp = parse_iso8601(show.get('published'))
info_dict = {
'id': item_id,
'title': title,
'description': description,
'thumbnail': thumbnail,
'timestamp': timestamp,
'duration': duration,
}
mg = try_get(show, lambda x: x['media:group'][0], dict)
if not mg:
continue
if mg.get('url'):
m = re.match(r'(?P<url>rtmpe?://[^/]+)/(?P<app>.+)/(?P<playpath>mp4:.*)', mg['url'])
if m:
m = m.groupdict()
formats.append({
'url': m['url'] + '/' + m['app'],
'app': m['app'],
'play_path': m['playpath'],
'player_url': url,
'ext': 'flv',
'format_id': 'rtmp',
})
if mg.get('hls_server') and mg.get('hls_url'):
formats.extend(self._extract_m3u8_formats(
mg['hls_server'] + mg['hls_url'], item_id, 'mp4',
entry_protocol='m3u8_native', m3u8_id='hls', fatal=False))
if mg.get('hds_server') and mg.get('hds_url'):
formats.extend(self._extract_f4m_formats(
mg['hds_server'] + mg['hds_url'], item_id,
f4m_id='hds', fatal=False))
mg_rte_server = str_or_none(mg.get('rte:server'))
mg_url = str_or_none(mg.get('url'))
if mg_rte_server and mg_url:
hds_url = url_or_none(mg_rte_server + mg_url)
if hds_url:
formats.extend(self._extract_f4m_formats(
hds_url, item_id, f4m_id='hds', fatal=False))
self._sort_formats(formats)
info_dict['formats'] = formats
return info_dict
class RteIE(RteBaseIE):
IE_NAME = 'rte'
IE_DESC = 'Raidió Teilifís Éireann TV'
_VALID_URL = r'https?://(?:www\.)?rte\.ie/player/[^/]{2,3}/show/[^/]+/(?P<id>[0-9]+)'
_TEST = {
'url': 'http://www.rte.ie/player/ie/show/iwitness-862/10478715/',
'md5': '4a76eb3396d98f697e6e8110563d2604',
'info_dict': {
'id': '10478715',
'ext': 'mp4',
'title': 'iWitness',
'thumbnail': r're:^https?://.*\.jpg$',
'description': 'The spirit of Ireland, one voice and one minute at a time.',
'duration': 60.046,
'upload_date': '20151012',
'timestamp': 1444694160,
},
}
class RteRadioIE(RteBaseIE):
IE_NAME = 'rte:radio'
IE_DESC = 'Raidió Teilifís Éireann radio'
# Radioplayer URLs have two distinct specifier formats,
# the old format #!rii=<channel_id>:<id>:<playable_item_id>:<date>:
# the new format #!rii=b<channel_id>_<id>_<playable_item_id>_<date>_
# where the IDs are int/empty, the date is DD-MM-YYYY, and the specifier may be truncated.
# An <id> uniquely defines an individual recording, and is the only part we require.
_VALID_URL = r'https?://(?:www\.)?rte\.ie/radio/utils/radioplayer/rteradioweb\.html#!rii=(?:b?[0-9]*)(?:%3A|:|%5F|_)(?P<id>[0-9]+)'
_TESTS = [{
# Old-style player URL; HLS and RTMPE formats
'url': 'http://www.rte.ie/radio/utils/radioplayer/rteradioweb.html#!rii=16:10507902:2414:27-12-2015:',
'md5': 'c79ccb2c195998440065456b69760411',
'info_dict': {
'id': '10507902',
'ext': 'mp4',
'title': 'Gloria',
'thumbnail': r're:^https?://.*\.jpg$',
'description': 'md5:9ce124a7fb41559ec68f06387cabddf0',
'timestamp': 1451203200,
'upload_date': '20151227',
'duration': 7230.0,
},
}, {
# New-style player URL; RTMPE formats only
'url': 'http://rte.ie/radio/utils/radioplayer/rteradioweb.html#!rii=b16_3250678_8861_06-04-2012_',
'info_dict': {
'id': '3250678',
'ext': 'flv',
'title': 'The Lyric Concert with Paul Herriott',
'thumbnail': r're:^https?://.*\.jpg$',
'description': '',
'timestamp': 1333742400,
'upload_date': '20120406',
'duration': 7199.016,
},
'params': {
# rtmp download
'skip_download': True,
},
}] | random_line_split | |
rte.py | # coding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..compat import compat_HTTPError
from ..utils import (
float_or_none,
parse_iso8601,
str_or_none,
try_get,
unescapeHTML,
url_or_none,
ExtractorError,
)
class RteBaseIE(InfoExtractor):
def _real_extract(self, url):
item_id = self._match_id(url)
info_dict = {}
formats = []
ENDPOINTS = (
'https://feeds.rasset.ie/rteavgen/player/playlist?type=iptv&format=json&showId=',
'http://www.rte.ie/rteavgen/getplaylist/?type=web&format=json&id=',
)
for num, ep_url in enumerate(ENDPOINTS, start=1):
try:
data = self._download_json(ep_url + item_id, item_id)
except ExtractorError as ee:
if num < len(ENDPOINTS) or formats:
continue
if isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 404:
error_info = self._parse_json(ee.cause.read().decode(), item_id, fatal=False)
if error_info:
raise ExtractorError(
'%s said: %s' % (self.IE_NAME, error_info['message']),
expected=True)
raise
# NB the string values in the JSON are stored using XML escaping(!)
show = try_get(data, lambda x: x['shows'][0], dict)
if not show:
continue
if not info_dict:
title = unescapeHTML(show['title'])
description = unescapeHTML(show.get('description'))
thumbnail = show.get('thumbnail')
duration = float_or_none(show.get('duration'), 1000)
timestamp = parse_iso8601(show.get('published'))
info_dict = {
'id': item_id,
'title': title,
'description': description,
'thumbnail': thumbnail,
'timestamp': timestamp,
'duration': duration,
}
mg = try_get(show, lambda x: x['media:group'][0], dict)
if not mg:
continue
if mg.get('url'):
m = re.match(r'(?P<url>rtmpe?://[^/]+)/(?P<app>.+)/(?P<playpath>mp4:.*)', mg['url'])
if m:
m = m.groupdict()
formats.append({
'url': m['url'] + '/' + m['app'],
'app': m['app'],
'play_path': m['playpath'],
'player_url': url,
'ext': 'flv',
'format_id': 'rtmp',
})
if mg.get('hls_server') and mg.get('hls_url'):
formats.extend(self._extract_m3u8_formats(
mg['hls_server'] + mg['hls_url'], item_id, 'mp4',
entry_protocol='m3u8_native', m3u8_id='hls', fatal=False))
if mg.get('hds_server') and mg.get('hds_url'):
formats.extend(self._extract_f4m_formats(
mg['hds_server'] + mg['hds_url'], item_id,
f4m_id='hds', fatal=False))
mg_rte_server = str_or_none(mg.get('rte:server'))
mg_url = str_or_none(mg.get('url'))
if mg_rte_server and mg_url:
hds_url = url_or_none(mg_rte_server + mg_url)
if hds_url:
formats.extend(self._extract_f4m_formats(
hds_url, item_id, f4m_id='hds', fatal=False))
self._sort_formats(formats)
info_dict['formats'] = formats
return info_dict
class RteIE(RteBaseIE):
IE_NAME = 'rte'
IE_DESC = 'Raidió Teilifís Éireann TV'
_VALID_URL = r'https?://(?:www\.)?rte\.ie/player/[^/]{2,3}/show/[^/]+/(?P<id>[0-9]+)'
_TEST = {
'url': 'http://www.rte.ie/player/ie/show/iwitness-862/10478715/',
'md5': '4a76eb3396d98f697e6e8110563d2604',
'info_dict': {
'id': '10478715',
'ext': 'mp4',
'title': 'iWitness',
'thumbnail': r're:^https?://.*\.jpg$',
'description': 'The spirit of Ireland, one voice and one minute at a time.',
'duration': 60.046,
'upload_date': '20151012',
'timestamp': 1444694160,
},
}
class RteRadioIE(RteBaseIE):
IE_ | NAME = 'rte:radio'
IE_DESC = 'Raidió Teilifís Éireann radio'
# Radioplayer URLs have two distinct specifier formats,
# the old format #!rii=<channel_id>:<id>:<playable_item_id>:<date>:
# the new format #!rii=b<channel_id>_<id>_<playable_item_id>_<date>_
# where the IDs are int/empty, the date is DD-MM-YYYY, and the specifier may be truncated.
# An <id> uniquely defines an individual recording, and is the only part we require.
_VALID_URL = r'https?://(?:www\.)?rte\.ie/radio/utils/radioplayer/rteradioweb\.html#!rii=(?:b?[0-9]*)(?:%3A|:|%5F|_)(?P<id>[0-9]+)'
_TESTS = [{
# Old-style player URL; HLS and RTMPE formats
'url': 'http://www.rte.ie/radio/utils/radioplayer/rteradioweb.html#!rii=16:10507902:2414:27-12-2015:',
'md5': 'c79ccb2c195998440065456b69760411',
'info_dict': {
'id': '10507902',
'ext': 'mp4',
'title': 'Gloria',
'thumbnail': r're:^https?://.*\.jpg$',
'description': 'md5:9ce124a7fb41559ec68f06387cabddf0',
'timestamp': 1451203200,
'upload_date': '20151227',
'duration': 7230.0,
},
}, {
# New-style player URL; RTMPE formats only
'url': 'http://rte.ie/radio/utils/radioplayer/rteradioweb.html#!rii=b16_3250678_8861_06-04-2012_',
'info_dict': {
'id': '3250678',
'ext': 'flv',
'title': 'The Lyric Concert with Paul Herriott',
'thumbnail': r're:^https?://.*\.jpg$',
'description': '',
'timestamp': 1333742400,
'upload_date': '20120406',
'duration': 7199.016,
},
'params': {
# rtmp download
'skip_download': True,
},
}]
| identifier_body | |
rte.py | # coding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..compat import compat_HTTPError
from ..utils import (
float_or_none,
parse_iso8601,
str_or_none,
try_get,
unescapeHTML,
url_or_none,
ExtractorError,
)
class | (InfoExtractor):
def _real_extract(self, url):
item_id = self._match_id(url)
info_dict = {}
formats = []
ENDPOINTS = (
'https://feeds.rasset.ie/rteavgen/player/playlist?type=iptv&format=json&showId=',
'http://www.rte.ie/rteavgen/getplaylist/?type=web&format=json&id=',
)
for num, ep_url in enumerate(ENDPOINTS, start=1):
try:
data = self._download_json(ep_url + item_id, item_id)
except ExtractorError as ee:
if num < len(ENDPOINTS) or formats:
continue
if isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 404:
error_info = self._parse_json(ee.cause.read().decode(), item_id, fatal=False)
if error_info:
raise ExtractorError(
'%s said: %s' % (self.IE_NAME, error_info['message']),
expected=True)
raise
# NB the string values in the JSON are stored using XML escaping(!)
show = try_get(data, lambda x: x['shows'][0], dict)
if not show:
continue
if not info_dict:
title = unescapeHTML(show['title'])
description = unescapeHTML(show.get('description'))
thumbnail = show.get('thumbnail')
duration = float_or_none(show.get('duration'), 1000)
timestamp = parse_iso8601(show.get('published'))
info_dict = {
'id': item_id,
'title': title,
'description': description,
'thumbnail': thumbnail,
'timestamp': timestamp,
'duration': duration,
}
mg = try_get(show, lambda x: x['media:group'][0], dict)
if not mg:
continue
if mg.get('url'):
m = re.match(r'(?P<url>rtmpe?://[^/]+)/(?P<app>.+)/(?P<playpath>mp4:.*)', mg['url'])
if m:
m = m.groupdict()
formats.append({
'url': m['url'] + '/' + m['app'],
'app': m['app'],
'play_path': m['playpath'],
'player_url': url,
'ext': 'flv',
'format_id': 'rtmp',
})
if mg.get('hls_server') and mg.get('hls_url'):
formats.extend(self._extract_m3u8_formats(
mg['hls_server'] + mg['hls_url'], item_id, 'mp4',
entry_protocol='m3u8_native', m3u8_id='hls', fatal=False))
if mg.get('hds_server') and mg.get('hds_url'):
formats.extend(self._extract_f4m_formats(
mg['hds_server'] + mg['hds_url'], item_id,
f4m_id='hds', fatal=False))
mg_rte_server = str_or_none(mg.get('rte:server'))
mg_url = str_or_none(mg.get('url'))
if mg_rte_server and mg_url:
hds_url = url_or_none(mg_rte_server + mg_url)
if hds_url:
formats.extend(self._extract_f4m_formats(
hds_url, item_id, f4m_id='hds', fatal=False))
self._sort_formats(formats)
info_dict['formats'] = formats
return info_dict
class RteIE(RteBaseIE):
IE_NAME = 'rte'
IE_DESC = 'Raidió Teilifís Éireann TV'
_VALID_URL = r'https?://(?:www\.)?rte\.ie/player/[^/]{2,3}/show/[^/]+/(?P<id>[0-9]+)'
_TEST = {
'url': 'http://www.rte.ie/player/ie/show/iwitness-862/10478715/',
'md5': '4a76eb3396d98f697e6e8110563d2604',
'info_dict': {
'id': '10478715',
'ext': 'mp4',
'title': 'iWitness',
'thumbnail': r're:^https?://.*\.jpg$',
'description': 'The spirit of Ireland, one voice and one minute at a time.',
'duration': 60.046,
'upload_date': '20151012',
'timestamp': 1444694160,
},
}
class RteRadioIE(RteBaseIE):
IE_NAME = 'rte:radio'
IE_DESC = 'Raidió Teilifís Éireann radio'
# Radioplayer URLs have two distinct specifier formats,
# the old format #!rii=<channel_id>:<id>:<playable_item_id>:<date>:
# the new format #!rii=b<channel_id>_<id>_<playable_item_id>_<date>_
# where the IDs are int/empty, the date is DD-MM-YYYY, and the specifier may be truncated.
# An <id> uniquely defines an individual recording, and is the only part we require.
_VALID_URL = r'https?://(?:www\.)?rte\.ie/radio/utils/radioplayer/rteradioweb\.html#!rii=(?:b?[0-9]*)(?:%3A|:|%5F|_)(?P<id>[0-9]+)'
_TESTS = [{
# Old-style player URL; HLS and RTMPE formats
'url': 'http://www.rte.ie/radio/utils/radioplayer/rteradioweb.html#!rii=16:10507902:2414:27-12-2015:',
'md5': 'c79ccb2c195998440065456b69760411',
'info_dict': {
'id': '10507902',
'ext': 'mp4',
'title': 'Gloria',
'thumbnail': r're:^https?://.*\.jpg$',
'description': 'md5:9ce124a7fb41559ec68f06387cabddf0',
'timestamp': 1451203200,
'upload_date': '20151227',
'duration': 7230.0,
},
}, {
# New-style player URL; RTMPE formats only
'url': 'http://rte.ie/radio/utils/radioplayer/rteradioweb.html#!rii=b16_3250678_8861_06-04-2012_',
'info_dict': {
'id': '3250678',
'ext': 'flv',
'title': 'The Lyric Concert with Paul Herriott',
'thumbnail': r're:^https?://.*\.jpg$',
'description': '',
'timestamp': 1333742400,
'upload_date': '20120406',
'duration': 7199.016,
},
'params': {
# rtmp download
'skip_download': True,
},
}]
| RteBaseIE | identifier_name |
proto.rs |
use bytes::{BufMut, BytesMut};
use futures::Future;
use std::{io, str};
use std::net::SocketAddr;
use tokio_core::net::TcpStream;
use tokio_core::reactor::Handle;
use tokio_io::{AsyncRead, AsyncWrite};
use tokio_io::codec::{Decoder, Encoder, Framed};
use tokio_proto::TcpClient;
use tokio_proto::multiplex::{ClientProto, ClientService, RequestId};
use tokio_service::Service;
use unterflow_protocol::TransportMessage;
use unterflow_protocol::frame::DataFrameHeader;
use unterflow_protocol::io::{FromBytes, HasBlockLength, ToBytes};
pub struct MultiplexedClient {
inner: ClientService<TcpStream, MultiplexedProto>,
}
impl MultiplexedClient {
pub fn connect(
addr: &SocketAddr,
handle: &Handle,
) -> Box<Future<Item = MultiplexedClient, Error = io::Error>> {
Box::new(TcpClient::new(MultiplexedProto).connect(addr, handle).map(
|service| MultiplexedClient { inner: service },
))
}
}
impl Service for MultiplexedClient {
type Request = TransportMessage;
type Response = TransportMessage;
type Error = io::Error;
type Future = Box<Future<Item = Self::Response, Error = Self::Error>>;
fn call(&self, request: Self::Request) -> Self::Future {
Box::new(self.inner.call(request))
}
}
struct MultiplexedCodec {
header: Option<DataFrameHeader>,
}
impl MultiplexedCodec {
fn decode_frame(
&mut self,
header: DataFrameHeader,
buffer: &mut BytesMut,
) -> Result<Option<(RequestId, TransportMessage)>, io::Error> {
let frame_length = header.aligned_length() - DataFrameHeader::block_length() as usize;
if buffer.len() < frame_length {
self.header = Some(header);
Ok(None)
} else {
let frame = buffer.split_to(frame_length);
let mut reader = io::Cursor::new(frame);
let frame = TransportMessage::read(header, &mut reader)?;
let request_id = match frame {
TransportMessage::RequestResponse(ref r) => r.request_header.request_id,
r => {
return Err(io::Error::new(
io::ErrorKind::Other,
format!("Expected request response message but got {:?}", r),
))
}
};
Ok(Some((request_id as RequestId, frame)))
}
}
}
impl Decoder for MultiplexedCodec {
type Item = (RequestId, TransportMessage);
type Error = io::Error;
fn decode(&mut self, buffer: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
if let Some(header) = self.header.take() {
self.decode_frame(header, buffer)
} else {
let header_length = DataFrameHeader::block_length() as usize;
if buffer.len() < header_length {
Ok(None)
} else {
let header = buffer.split_to(header_length);
let mut reader = io::Cursor::new(header);
let header = DataFrameHeader::from_bytes(&mut reader)?;
self.decode_frame(header, buffer)
}
}
}
}
impl Encoder for MultiplexedCodec {
type Item = (RequestId, TransportMessage);
type Error = io::Error;
fn encode(&mut self, request: Self::Item, buffer: &mut BytesMut) -> Result<(), io::Error> {
let (request_id, mut request) = request;
match request {
TransportMessage::RequestResponse(ref mut r) => {
r.request_header.request_id = request_id;
}
r => {
return Err(io::Error::new(
io::ErrorKind::Other,
format!("Expected request response message but got {:?}", r),
))
}
};
let length = request.length();
if buffer.remaining_mut() < length {
buffer.reserve(length);
}
let mut writer = buffer.writer();
request.to_bytes(&mut writer)
}
}
struct MultiplexedProto;
impl<T: AsyncRead + AsyncWrite + 'static> ClientProto<T> for MultiplexedProto {
type Request = TransportMessage;
type Response = TransportMessage;
type Transport = Framed<T, MultiplexedCodec>;
type BindTransport = Result<Self::Transport, io::Error>;
fn bind_transport(&self, io: T) -> Self::BindTransport |
}
| {
Ok(io.framed(MultiplexedCodec { header: None }))
} | identifier_body |
proto.rs |
use bytes::{BufMut, BytesMut};
use futures::Future;
use std::{io, str};
use std::net::SocketAddr;
use tokio_core::net::TcpStream;
use tokio_core::reactor::Handle;
use tokio_io::{AsyncRead, AsyncWrite};
use tokio_io::codec::{Decoder, Encoder, Framed};
use tokio_proto::TcpClient;
use tokio_proto::multiplex::{ClientProto, ClientService, RequestId};
use tokio_service::Service;
use unterflow_protocol::TransportMessage;
use unterflow_protocol::frame::DataFrameHeader;
use unterflow_protocol::io::{FromBytes, HasBlockLength, ToBytes};
pub struct MultiplexedClient {
inner: ClientService<TcpStream, MultiplexedProto>,
}
impl MultiplexedClient {
pub fn connect(
addr: &SocketAddr,
handle: &Handle,
) -> Box<Future<Item = MultiplexedClient, Error = io::Error>> {
Box::new(TcpClient::new(MultiplexedProto).connect(addr, handle).map(
|service| MultiplexedClient { inner: service },
))
}
}
impl Service for MultiplexedClient {
type Request = TransportMessage;
type Response = TransportMessage;
type Error = io::Error;
type Future = Box<Future<Item = Self::Response, Error = Self::Error>>;
fn call(&self, request: Self::Request) -> Self::Future {
Box::new(self.inner.call(request))
}
}
struct MultiplexedCodec {
header: Option<DataFrameHeader>,
}
impl MultiplexedCodec {
fn decode_frame(
&mut self,
header: DataFrameHeader,
buffer: &mut BytesMut,
) -> Result<Option<(RequestId, TransportMessage)>, io::Error> {
let frame_length = header.aligned_length() - DataFrameHeader::block_length() as usize;
if buffer.len() < frame_length {
self.header = Some(header);
Ok(None)
} else {
let frame = buffer.split_to(frame_length);
let mut reader = io::Cursor::new(frame);
let frame = TransportMessage::read(header, &mut reader)?;
let request_id = match frame {
TransportMessage::RequestResponse(ref r) => r.request_header.request_id,
r => {
return Err(io::Error::new(
io::ErrorKind::Other,
format!("Expected request response message but got {:?}", r),
))
}
};
Ok(Some((request_id as RequestId, frame)))
}
}
}
impl Decoder for MultiplexedCodec {
type Item = (RequestId, TransportMessage);
type Error = io::Error;
fn decode(&mut self, buffer: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
if let Some(header) = self.header.take() {
self.decode_frame(header, buffer)
} else {
let header_length = DataFrameHeader::block_length() as usize;
if buffer.len() < header_length | else {
let header = buffer.split_to(header_length);
let mut reader = io::Cursor::new(header);
let header = DataFrameHeader::from_bytes(&mut reader)?;
self.decode_frame(header, buffer)
}
}
}
}
impl Encoder for MultiplexedCodec {
type Item = (RequestId, TransportMessage);
type Error = io::Error;
fn encode(&mut self, request: Self::Item, buffer: &mut BytesMut) -> Result<(), io::Error> {
let (request_id, mut request) = request;
match request {
TransportMessage::RequestResponse(ref mut r) => {
r.request_header.request_id = request_id;
}
r => {
return Err(io::Error::new(
io::ErrorKind::Other,
format!("Expected request response message but got {:?}", r),
))
}
};
let length = request.length();
if buffer.remaining_mut() < length {
buffer.reserve(length);
}
let mut writer = buffer.writer();
request.to_bytes(&mut writer)
}
}
struct MultiplexedProto;
impl<T: AsyncRead + AsyncWrite + 'static> ClientProto<T> for MultiplexedProto {
type Request = TransportMessage;
type Response = TransportMessage;
type Transport = Framed<T, MultiplexedCodec>;
type BindTransport = Result<Self::Transport, io::Error>;
fn bind_transport(&self, io: T) -> Self::BindTransport {
Ok(io.framed(MultiplexedCodec { header: None }))
}
}
| {
Ok(None)
} | conditional_block |
proto.rs | use bytes::{BufMut, BytesMut};
use futures::Future;
use std::{io, str};
use std::net::SocketAddr;
use tokio_core::net::TcpStream;
use tokio_core::reactor::Handle;
use tokio_io::{AsyncRead, AsyncWrite};
use tokio_io::codec::{Decoder, Encoder, Framed};
use tokio_proto::TcpClient;
use tokio_proto::multiplex::{ClientProto, ClientService, RequestId};
use tokio_service::Service;
use unterflow_protocol::TransportMessage;
use unterflow_protocol::frame::DataFrameHeader;
use unterflow_protocol::io::{FromBytes, HasBlockLength, ToBytes};
pub struct MultiplexedClient {
inner: ClientService<TcpStream, MultiplexedProto>,
}
impl MultiplexedClient {
pub fn connect(
addr: &SocketAddr,
handle: &Handle,
) -> Box<Future<Item = MultiplexedClient, Error = io::Error>> {
Box::new(TcpClient::new(MultiplexedProto).connect(addr, handle).map(
|service| MultiplexedClient { inner: service },
))
}
}
impl Service for MultiplexedClient {
type Request = TransportMessage;
type Response = TransportMessage;
type Error = io::Error;
type Future = Box<Future<Item = Self::Response, Error = Self::Error>>;
fn call(&self, request: Self::Request) -> Self::Future {
Box::new(self.inner.call(request))
}
}
struct MultiplexedCodec {
header: Option<DataFrameHeader>,
}
impl MultiplexedCodec {
fn decode_frame(
&mut self,
header: DataFrameHeader,
buffer: &mut BytesMut,
) -> Result<Option<(RequestId, TransportMessage)>, io::Error> {
let frame_length = header.aligned_length() - DataFrameHeader::block_length() as usize;
if buffer.len() < frame_length {
self.header = Some(header);
Ok(None)
} else {
let frame = buffer.split_to(frame_length);
let mut reader = io::Cursor::new(frame);
let frame = TransportMessage::read(header, &mut reader)?;
let request_id = match frame {
TransportMessage::RequestResponse(ref r) => r.request_header.request_id,
r => {
return Err(io::Error::new(
io::ErrorKind::Other,
format!("Expected request response message but got {:?}", r),
))
}
};
Ok(Some((request_id as RequestId, frame)))
}
}
}
impl Decoder for MultiplexedCodec {
type Item = (RequestId, TransportMessage);
type Error = io::Error;
fn decode(&mut self, buffer: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
if let Some(header) = self.header.take() {
self.decode_frame(header, buffer)
} else {
let header_length = DataFrameHeader::block_length() as usize;
if buffer.len() < header_length {
Ok(None)
} else {
let header = buffer.split_to(header_length);
let mut reader = io::Cursor::new(header);
let header = DataFrameHeader::from_bytes(&mut reader)?;
self.decode_frame(header, buffer)
}
}
}
}
impl Encoder for MultiplexedCodec {
type Item = (RequestId, TransportMessage);
type Error = io::Error;
fn encode(&mut self, request: Self::Item, buffer: &mut BytesMut) -> Result<(), io::Error> {
let (request_id, mut request) = request;
match request {
TransportMessage::RequestResponse(ref mut r) => {
r.request_header.request_id = request_id;
}
r => {
return Err(io::Error::new(
io::ErrorKind::Other,
format!("Expected request response message but got {:?}", r),
))
}
};
let length = request.length();
if buffer.remaining_mut() < length {
buffer.reserve(length);
}
let mut writer = buffer.writer();
request.to_bytes(&mut writer)
}
}
struct MultiplexedProto;
impl<T: AsyncRead + AsyncWrite + 'static> ClientProto<T> for MultiplexedProto {
type Request = TransportMessage;
type Response = TransportMessage; |
fn bind_transport(&self, io: T) -> Self::BindTransport {
Ok(io.framed(MultiplexedCodec { header: None }))
}
} | type Transport = Framed<T, MultiplexedCodec>;
type BindTransport = Result<Self::Transport, io::Error>; | random_line_split |
proto.rs |
use bytes::{BufMut, BytesMut};
use futures::Future;
use std::{io, str};
use std::net::SocketAddr;
use tokio_core::net::TcpStream;
use tokio_core::reactor::Handle;
use tokio_io::{AsyncRead, AsyncWrite};
use tokio_io::codec::{Decoder, Encoder, Framed};
use tokio_proto::TcpClient;
use tokio_proto::multiplex::{ClientProto, ClientService, RequestId};
use tokio_service::Service;
use unterflow_protocol::TransportMessage;
use unterflow_protocol::frame::DataFrameHeader;
use unterflow_protocol::io::{FromBytes, HasBlockLength, ToBytes};
pub struct | {
inner: ClientService<TcpStream, MultiplexedProto>,
}
impl MultiplexedClient {
pub fn connect(
addr: &SocketAddr,
handle: &Handle,
) -> Box<Future<Item = MultiplexedClient, Error = io::Error>> {
Box::new(TcpClient::new(MultiplexedProto).connect(addr, handle).map(
|service| MultiplexedClient { inner: service },
))
}
}
impl Service for MultiplexedClient {
type Request = TransportMessage;
type Response = TransportMessage;
type Error = io::Error;
type Future = Box<Future<Item = Self::Response, Error = Self::Error>>;
fn call(&self, request: Self::Request) -> Self::Future {
Box::new(self.inner.call(request))
}
}
struct MultiplexedCodec {
header: Option<DataFrameHeader>,
}
impl MultiplexedCodec {
fn decode_frame(
&mut self,
header: DataFrameHeader,
buffer: &mut BytesMut,
) -> Result<Option<(RequestId, TransportMessage)>, io::Error> {
let frame_length = header.aligned_length() - DataFrameHeader::block_length() as usize;
if buffer.len() < frame_length {
self.header = Some(header);
Ok(None)
} else {
let frame = buffer.split_to(frame_length);
let mut reader = io::Cursor::new(frame);
let frame = TransportMessage::read(header, &mut reader)?;
let request_id = match frame {
TransportMessage::RequestResponse(ref r) => r.request_header.request_id,
r => {
return Err(io::Error::new(
io::ErrorKind::Other,
format!("Expected request response message but got {:?}", r),
))
}
};
Ok(Some((request_id as RequestId, frame)))
}
}
}
impl Decoder for MultiplexedCodec {
type Item = (RequestId, TransportMessage);
type Error = io::Error;
fn decode(&mut self, buffer: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
if let Some(header) = self.header.take() {
self.decode_frame(header, buffer)
} else {
let header_length = DataFrameHeader::block_length() as usize;
if buffer.len() < header_length {
Ok(None)
} else {
let header = buffer.split_to(header_length);
let mut reader = io::Cursor::new(header);
let header = DataFrameHeader::from_bytes(&mut reader)?;
self.decode_frame(header, buffer)
}
}
}
}
impl Encoder for MultiplexedCodec {
type Item = (RequestId, TransportMessage);
type Error = io::Error;
fn encode(&mut self, request: Self::Item, buffer: &mut BytesMut) -> Result<(), io::Error> {
let (request_id, mut request) = request;
match request {
TransportMessage::RequestResponse(ref mut r) => {
r.request_header.request_id = request_id;
}
r => {
return Err(io::Error::new(
io::ErrorKind::Other,
format!("Expected request response message but got {:?}", r),
))
}
};
let length = request.length();
if buffer.remaining_mut() < length {
buffer.reserve(length);
}
let mut writer = buffer.writer();
request.to_bytes(&mut writer)
}
}
struct MultiplexedProto;
impl<T: AsyncRead + AsyncWrite + 'static> ClientProto<T> for MultiplexedProto {
type Request = TransportMessage;
type Response = TransportMessage;
type Transport = Framed<T, MultiplexedCodec>;
type BindTransport = Result<Self::Transport, io::Error>;
fn bind_transport(&self, io: T) -> Self::BindTransport {
Ok(io.framed(MultiplexedCodec { header: None }))
}
}
| MultiplexedClient | identifier_name |
conf.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# feeluown documentation build configuration file, created by
# sphinx-quickstart on Fri Oct 2 20:55:54 2015.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys
import os
import shlex
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, os.path.abspath('../../src'))
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.viewcode',
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = 'feeluown'
copyright = '2015, cosven'
author = 'cosven'
# The version info for the project you're documenting, acts as replacement for | #
# The short X.Y version.
version = '1.0'
# The full version, including alpha/beta/rc tags.
release = '4.0'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = 'cn'
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = []
# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'alabaster'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#html_extra_path = []
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Language to be used for generating the HTML full-text search index.
# Sphinx supports the following languages:
# 'da', 'de', 'en', 'es', 'fi', 'fr', 'h', 'it', 'ja'
# 'nl', 'no', 'pt', 'ro', 'r', 'sv', 'tr'
#html_search_language = 'en'
# A dictionary with options for the search language support, empty by default.
# Now only 'ja' uses this config value
#html_search_options = {'type': 'default'}
# The name of a javascript file (relative to the configuration directory) that
# implements a search results scorer. If empty, the default will be used.
#html_search_scorer = 'scorer.js'
# Output file base name for HTML help builder.
htmlhelp_basename = 'feeluowndoc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
# Latex figure (float) alignment
#'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'feeluown.tex', 'feeluown Documentation',
'cosven', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'feeluown', 'feeluown Documentation',
[author], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'feeluown', 'feeluown Documentation',
author, 'feeluown', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False | # |version| and |release|, also used in various other places throughout the
# built documents. | random_line_split |
create_profile.py | #!/usr/local/bin/python2.7
# encoding: utf-8
from __future__ import division
from argparse import ArgumentParser
import logging
import sys
from expertfinding import ExpertFinding
from collections import Counter
def main():
'''Command line options.'''
parser = ArgumentParser()
parser.add_argument("-n", "--names", required=True, action="store", nargs="+", help="Names of people to profile")
parser.add_argument("-s", "--storage_db", required=True, action="store", help="Storage DB file")
args = parser.parse_args()
exf = ExpertFinding(args.storage_db, False)
for name in args.names:
a_id = exf.author_id(name)[0]
print a_id, exf.name(a_id), exf.institution(a_id)
for entity, freq, iaf, ef_iaf, max_rho, years in exf.ef_iaf(a_id)[:50]:
years_freq = ", ".join("{}{}".format(y, "(x{})".format(freq) if freq > 1 else "") for y, freq in sorted(Counter(years).items(), key=lambda p: p[0])) | print u"{} freq={:.1%} importance={:.2f} entity_rarity={:.2f} max_rho={:.3f} years={}".format(entity, freq, ef_iaf*100, iaf, max_rho, years_freq)
print
return 0
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO)
sys.exit(main()) | random_line_split | |
create_profile.py | #!/usr/local/bin/python2.7
# encoding: utf-8
from __future__ import division
from argparse import ArgumentParser
import logging
import sys
from expertfinding import ExpertFinding
from collections import Counter
def | ():
'''Command line options.'''
parser = ArgumentParser()
parser.add_argument("-n", "--names", required=True, action="store", nargs="+", help="Names of people to profile")
parser.add_argument("-s", "--storage_db", required=True, action="store", help="Storage DB file")
args = parser.parse_args()
exf = ExpertFinding(args.storage_db, False)
for name in args.names:
a_id = exf.author_id(name)[0]
print a_id, exf.name(a_id), exf.institution(a_id)
for entity, freq, iaf, ef_iaf, max_rho, years in exf.ef_iaf(a_id)[:50]:
years_freq = ", ".join("{}{}".format(y, "(x{})".format(freq) if freq > 1 else "") for y, freq in sorted(Counter(years).items(), key=lambda p: p[0]))
print u"{} freq={:.1%} importance={:.2f} entity_rarity={:.2f} max_rho={:.3f} years={}".format(entity, freq, ef_iaf*100, iaf, max_rho, years_freq)
print
return 0
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO)
sys.exit(main())
| main | identifier_name |
create_profile.py | #!/usr/local/bin/python2.7
# encoding: utf-8
from __future__ import division
from argparse import ArgumentParser
import logging
import sys
from expertfinding import ExpertFinding
from collections import Counter
def main():
|
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO)
sys.exit(main())
| '''Command line options.'''
parser = ArgumentParser()
parser.add_argument("-n", "--names", required=True, action="store", nargs="+", help="Names of people to profile")
parser.add_argument("-s", "--storage_db", required=True, action="store", help="Storage DB file")
args = parser.parse_args()
exf = ExpertFinding(args.storage_db, False)
for name in args.names:
a_id = exf.author_id(name)[0]
print a_id, exf.name(a_id), exf.institution(a_id)
for entity, freq, iaf, ef_iaf, max_rho, years in exf.ef_iaf(a_id)[:50]:
years_freq = ", ".join("{}{}".format(y, "(x{})".format(freq) if freq > 1 else "") for y, freq in sorted(Counter(years).items(), key=lambda p: p[0]))
print u"{} freq={:.1%} importance={:.2f} entity_rarity={:.2f} max_rho={:.3f} years={}".format(entity, freq, ef_iaf*100, iaf, max_rho, years_freq)
print
return 0 | identifier_body |
create_profile.py | #!/usr/local/bin/python2.7
# encoding: utf-8
from __future__ import division
from argparse import ArgumentParser
import logging
import sys
from expertfinding import ExpertFinding
from collections import Counter
def main():
'''Command line options.'''
parser = ArgumentParser()
parser.add_argument("-n", "--names", required=True, action="store", nargs="+", help="Names of people to profile")
parser.add_argument("-s", "--storage_db", required=True, action="store", help="Storage DB file")
args = parser.parse_args()
exf = ExpertFinding(args.storage_db, False)
for name in args.names:
a_id = exf.author_id(name)[0]
print a_id, exf.name(a_id), exf.institution(a_id)
for entity, freq, iaf, ef_iaf, max_rho, years in exf.ef_iaf(a_id)[:50]:
|
print
return 0
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO)
sys.exit(main())
| years_freq = ", ".join("{}{}".format(y, "(x{})".format(freq) if freq > 1 else "") for y, freq in sorted(Counter(years).items(), key=lambda p: p[0]))
print u"{} freq={:.1%} importance={:.2f} entity_rarity={:.2f} max_rho={:.3f} years={}".format(entity, freq, ef_iaf*100, iaf, max_rho, years_freq) | conditional_block |
OperatorEncodeEvent.ts | import * as events from 'events';
import { inject, injectable } from 'inversify';
import ILogger from '../ILogger';
import ILoggerModel from '../ILoggerModel';
import IOperatorEncodeEvent, { OperatorFinishEncodeInfo } from './IOperatorEncodeEvent';
@injectable()
class OperatorEncodeEvent implements IOperatorEncodeEvent {
private log: ILogger;
private emitter: events.EventEmitter = new events.EventEmitter();
constructor(@inject('ILoggerModel') logger: ILoggerModel) |
/**
* エンコード完了イベント発行
* @param info: OperatorFinishEncodeInfo
*/
public emitFinishEncode(info: OperatorFinishEncodeInfo): void {
this.emitter.emit(OperatorEncodeEvent.FINISH_ENCODE_EVENT, info);
}
/**
* エンコード完了イベント登録
* @param callback: (info: OperatorFinishEncodeInfo) => void
*/
public setFinishEncode(callback: (info: OperatorFinishEncodeInfo) => void): void {
this.emitter.on(OperatorEncodeEvent.FINISH_ENCODE_EVENT, async (info: OperatorFinishEncodeInfo) => {
try {
await callback(info);
} catch (err: any) {
this.log.system.error(err);
}
});
}
}
namespace OperatorEncodeEvent {
export const FINISH_ENCODE_EVENT = 'finishEncodeEvent';
}
export default OperatorEncodeEvent;
| {
this.log = logger.getLogger();
} | identifier_body |
OperatorEncodeEvent.ts | import * as events from 'events';
import { inject, injectable } from 'inversify';
import ILogger from '../ILogger';
import ILoggerModel from '../ILoggerModel';
import IOperatorEncodeEvent, { OperatorFinishEncodeInfo } from './IOperatorEncodeEvent';
@injectable()
class OperatorEncodeEvent implements IOperatorEncodeEvent {
private log: ILogger;
private emitter: events.EventEmitter = new events.EventEmitter();
constructor(@inject('ILoggerModel') logger: ILoggerModel) {
this.log = logger.getLogger();
}
/**
* エンコード完了イベント発行
* @param info: OperatorFinishEncodeInfo
*/
public emitFinishEncode(info: OperatorFinishEncodeInfo): void {
this.emitter.emit(OperatorEncodeEvent.FINISH_ENCODE_EVENT, info);
}
/**
* エンコード完了イベント登録
* @param callback: (info: OperatorFinishEncodeInfo) => void
*/
public setFinishEncode(callback: (info: OperatorFinishEncodeInfo) => void): void {
this.emitter.on(OperatorEncodeEvent.FINISH_ENCODE_EVENT, async (info: OperatorFinishEncodeInfo) => {
try {
await callback(info);
} catch (err: any) {
this.log.system.error(err); |
namespace OperatorEncodeEvent {
export const FINISH_ENCODE_EVENT = 'finishEncodeEvent';
}
export default OperatorEncodeEvent; | }
});
}
} | random_line_split |
OperatorEncodeEvent.ts | import * as events from 'events';
import { inject, injectable } from 'inversify';
import ILogger from '../ILogger';
import ILoggerModel from '../ILoggerModel';
import IOperatorEncodeEvent, { OperatorFinishEncodeInfo } from './IOperatorEncodeEvent';
@injectable()
class OperatorEncodeEvent implements IOperatorEncodeEvent {
private log: ILogger;
private emitter: events.EventEmitter = new events.EventEmitter();
constructor(@inject('ILoggerModel') logger: ILoggerModel) {
this.log = logger.getLogger();
}
/**
* エンコード完了イベント発行
* @param info: OperatorFinishEncodeInfo
*/
public emitFinishEncode(info: OperatorFinishEncodeInfo): void {
this.emitter.emit(OperatorEncodeEvent.FINISH_ENCODE_EVENT, info);
}
/**
* エンコード完了イベント登録
* @param callback: (info: OperatorFinishEncodeInfo) => void
*/
public setFinishEncode(callback: (info: OperatorFinishEncod | : void {
this.emitter.on(OperatorEncodeEvent.FINISH_ENCODE_EVENT, async (info: OperatorFinishEncodeInfo) => {
try {
await callback(info);
} catch (err: any) {
this.log.system.error(err);
}
});
}
}
namespace OperatorEncodeEvent {
export const FINISH_ENCODE_EVENT = 'finishEncodeEvent';
}
export default OperatorEncodeEvent;
| eInfo) => void) | identifier_name |
webSocketMiddleware.ts | import {
REQUEST_COMPLETED, WEB_SOCKET_CONNECT,
WEB_SOCKET_SEND
} from '../connectionConstants';
import * as ReconnectingWebsocket from 'reconnecting-websocket';
import {Dispatch, Middleware} from 'redux';
import {authConnected, error} from "../connectionActions";
import {Item} from "../../graph/interfaces/item";
import {
liveReceive,
searchReceive,
setSearchTotal
} from "../../search/searchActions";
import {requestCompleted} from "../connectionActions";
import { receiveFieldMapping } from "../../fields/fieldsActions";
import {LIVE_RECEIVE, SEARCH_RECEIVE} from "../../search/searchConstants";
import {INITIAL_STATE_RECEIVE} from "../../datasources/datasourcesConstants";
import {receiveInitialState} from "../../datasources/datasourcesActions";
import Timer = NodeJS.Timer;
import { getResponses } from './mockServer';
import { FieldMapping } from '../../fields/interfaces/fieldMapping';
import { receiveWorkspaceDescriptions } from '../../ui/uiActions';
let opened: Promise<ReconnectingWebsocket>;
export const webSocketMiddleware: Middleware = ({dispatch}) => next => action => {
switch (action.type) {
case WEB_SOCKET_CONNECT: {
const backendUri: string = action.payload.backendUri;
console.log('Connecting to backend on ', backendUri);
opened = new Promise(resolve => {
const socket = new ReconnectingWebsocket(backendUri);
socket.onopen = event => {onOpen(dispatch); resolve(socket)};
socket.onmessage = event => onMessage(event, dispatch);
socket.onclose = event => onClose(event, dispatch);
socket.onerror = event => onClose(event, dispatch);
});
break;
}
case WEB_SOCKET_SEND: {
const payload: string = JSON.stringify(action.payload);
console.log('Send', action.payload);
let mockedResponses;
if (process.env.MOCK_SERVER) {
mockedResponses = getResponses(action.payload) as MessageEvent[];
}
if (mockedResponses) {
mockedResponses.forEach(response => {
console.log('Mocking server response', response);
onMessage(response, dispatch);
});
} else {
opened.then(socket => socket.send(payload));
}
break;
}
}
return next(action);
};
function onOpen(dispatch: Dispatch<any>) {
dispatch(authConnected(true, null));
dispatch(receiveWorkspaceDescriptions([
{
id: '1',
title: 'Research',
version: 7
},
{
id: '2',
title: 'Malware',
version: 7
}
]));
}
function onMessage(event: MessageEvent, dispatch: Dispatch<any>) {
const data = JSON.parse(event.data);
console.log('Receive', data.type);
switch (data.type) {
case SEARCH_RECEIVE: {
if (typeof data.total_count === 'number') {
dispatch(setSearchTotal(data['request-id'], data.total_count));
}
debounceItems(
data.results,
data.mapping,
data['request-id'],
dispatch,
false,
data.datasource
);
break;
}
case LIVE_RECEIVE: {
debounceItems(
data.graphs,
data.mapping,
data.datasource,
dispatch,
true,
data.datasource
);
break;
}
case INITIAL_STATE_RECEIVE:
dispatch(receiveInitialState({
datasources: data.datasources,
enrichers: data.enrichers,
version: data.version |
case REQUEST_COMPLETED:
dispatch(requestCompleted(data['request-id']));
break;
case 'ERROR':
console.error(data);
dispatch(error(data.message, data['request-id']));
}
}
function onClose(event: CloseEvent, dispatch: Dispatch<any>) {
let reason = getCloseMessage(event);
dispatch(authConnected(false, reason));
}
function getCloseMessage(event: CloseEvent): string {
switch (event.code) {
case 1000:
return 'Normal closure, meaning that the purpose for which the connection was established has been fulfilled.';
case 1001:
return 'An endpoint is \'going away\', such as a server going down or a browser having navigated away from a page.';
case 1002:
return 'An endpoint is terminating the connection due to a protocol error';
case 1003:
return 'An endpoint is terminating the connection because it has received a type of data it cannot accept (e.g., an endpoint that understands only text data MAY send this if it receives a binary message).';
case 1004:
return 'Reserved. The specific meaning might be defined in the future.';
case 1005:
return 'No status code was actually present.';
case 1006:
return 'The connection was closed abnormally, e.g., without sending or receiving a Close control frame';
case 1007:
return 'An endpoint is terminating the connection because it has received data within a message that was not consistent with the type of the message (e.g., non-UTF-8 [http://tools.ietf.org/html/rfc3629] data within a text message).';
case 1008:
return 'An endpoint is terminating the connection because it has received a message that \'violates its policy\'. This reason is given either if there is no other sutible reason, or if there is a need to hide specific details about the policy.';
case 1009:
return 'An endpoint is terminating the connection because it has received a message that is too big for it to process.';
case 1010: // Note that this status code is not used by the server, because it can fail the WebSocket handshake instead:
return 'An endpoint (client) is terminating the connection because it has expected the server to negotiate one or more extension, but the server didn\'t return them in the response message of the WebSocket handshake. <br /> Specifically, the extensions that are needed are: ' + event.reason;
case 1011:
return 'A server is terminating the connection because it encountered an unexpected condition that prevented it from fulfilling the request.';
case 1015:
return 'The connection was closed due to a failure to perform a TLS handshake (e.g., the server certificate can\'t be verified).';
default:
return 'Unknown reason';
}
}
interface ItemsTimeout {
/**
* Resets every time we receive new results, so that we bundle results that
* are received in quick succession of each other.
*
* When the timeout completes, results are dispatched.
*
*/
bundleTimeout: Timer;
/**
* Does not reset when we receive new results. Used for solving the problem
* of the above timeout: imagine that we keep on getting results quickly
* forever -> the above timeout would never complete.
*
* When the timeout completes, results are dispatched.
*
*/
maxTimeout: Timer;
}
const debouncedItems: {
[requestId: string]: Item[]
} = {};
let debouncedFields: FieldMapping = {};
const debounceTimeouts: {
[requestId: string]: ItemsTimeout
} = {};
const timeoutMs = 500;
const maxTimeoutMs = 2000;
/**
* Sometimes we receive many items from the server in quick succession of
* each other. This is not good, because then we would need to calculate the
* graph for each time we receive it (so multiple times per second).
*
* Instead, we wait for 500ms and bundle all of the items together.
*
* @param newItems
* @param fields
* @param requestId
* @param dispatch
* @param isLive
* @param datasourceId
*/
function debounceItems(newItems: Item[], fields: FieldMapping, requestId: string, dispatch: Dispatch<any>, isLive: boolean, datasourceId: string) {
if (fields) {
Object.keys(fields).forEach(datasource => {
if (!debouncedFields[datasource]) {
debouncedFields[datasource] = {};
}
Object.keys(fields[datasource]).forEach(field => {
const type: string = fields[datasource][field];
debouncedFields[datasource][field] = type;
});
});
}
if (newItems === null) {
return;
}
newItems.forEach(item => {
item.datasourceId = datasourceId
});
let results = debouncedItems[requestId] || [];
for (let i = 0; i < newItems.length; i++ ) {
let result = newItems[i];
let index = results.findIndex((item) => item.id === result.id);
if (index === -1) {
results.push(result);
continue;
}
// already exists, update count
results[index].count = result.count;
}
debouncedItems[requestId] = results;
const searchTimeout: any = debounceTimeouts[requestId] || {};
const timeoutFinished = () => {
clearTimeout(searchTimeout.bundleTimeout);
clearTimeout(searchTimeout.maxTimeout);
dispatch(receiveFieldMapping(debouncedFields));
debouncedFields = {};
if (isLive) {
dispatch(liveReceive(debouncedItems[requestId], datasourceId));
} else {
dispatch(searchReceive(debouncedItems[requestId], requestId));
}
delete debouncedItems[requestId];
};
// Dispatch when we haven't received any new items for 500 ms.
clearTimeout(searchTimeout.bundleTimeout);
searchTimeout.bundleTimeout = setTimeout(timeoutFinished, timeoutMs);
// Only set the max timeout if it wasn't set already. It does not get
// cleared when new items are received.
if (!searchTimeout.maxTimeout) {
// Dispatch also when the max timeout is finished
searchTimeout.maxTimeout = setTimeout(timeoutFinished, maxTimeoutMs);
}
debounceTimeouts[requestId] = searchTimeout;
} | }));
break; | random_line_split |
webSocketMiddleware.ts | import {
REQUEST_COMPLETED, WEB_SOCKET_CONNECT,
WEB_SOCKET_SEND
} from '../connectionConstants';
import * as ReconnectingWebsocket from 'reconnecting-websocket';
import {Dispatch, Middleware} from 'redux';
import {authConnected, error} from "../connectionActions";
import {Item} from "../../graph/interfaces/item";
import {
liveReceive,
searchReceive,
setSearchTotal
} from "../../search/searchActions";
import {requestCompleted} from "../connectionActions";
import { receiveFieldMapping } from "../../fields/fieldsActions";
import {LIVE_RECEIVE, SEARCH_RECEIVE} from "../../search/searchConstants";
import {INITIAL_STATE_RECEIVE} from "../../datasources/datasourcesConstants";
import {receiveInitialState} from "../../datasources/datasourcesActions";
import Timer = NodeJS.Timer;
import { getResponses } from './mockServer';
import { FieldMapping } from '../../fields/interfaces/fieldMapping';
import { receiveWorkspaceDescriptions } from '../../ui/uiActions';
let opened: Promise<ReconnectingWebsocket>;
export const webSocketMiddleware: Middleware = ({dispatch}) => next => action => {
switch (action.type) {
case WEB_SOCKET_CONNECT: {
const backendUri: string = action.payload.backendUri;
console.log('Connecting to backend on ', backendUri);
opened = new Promise(resolve => {
const socket = new ReconnectingWebsocket(backendUri);
socket.onopen = event => {onOpen(dispatch); resolve(socket)};
socket.onmessage = event => onMessage(event, dispatch);
socket.onclose = event => onClose(event, dispatch);
socket.onerror = event => onClose(event, dispatch);
});
break;
}
case WEB_SOCKET_SEND: {
const payload: string = JSON.stringify(action.payload);
console.log('Send', action.payload);
let mockedResponses;
if (process.env.MOCK_SERVER) {
mockedResponses = getResponses(action.payload) as MessageEvent[];
}
if (mockedResponses) {
mockedResponses.forEach(response => {
console.log('Mocking server response', response);
onMessage(response, dispatch);
});
} else {
opened.then(socket => socket.send(payload));
}
break;
}
}
return next(action);
};
function onOpen(dispatch: Dispatch<any>) {
dispatch(authConnected(true, null));
dispatch(receiveWorkspaceDescriptions([
{
id: '1',
title: 'Research',
version: 7
},
{
id: '2',
title: 'Malware',
version: 7
}
]));
}
function onMessage(event: MessageEvent, dispatch: Dispatch<any>) {
const data = JSON.parse(event.data);
console.log('Receive', data.type);
switch (data.type) {
case SEARCH_RECEIVE: {
if (typeof data.total_count === 'number') {
dispatch(setSearchTotal(data['request-id'], data.total_count));
}
debounceItems(
data.results,
data.mapping,
data['request-id'],
dispatch,
false,
data.datasource
);
break;
}
case LIVE_RECEIVE: {
debounceItems(
data.graphs,
data.mapping,
data.datasource,
dispatch,
true,
data.datasource
);
break;
}
case INITIAL_STATE_RECEIVE:
dispatch(receiveInitialState({
datasources: data.datasources,
enrichers: data.enrichers,
version: data.version
}));
break;
case REQUEST_COMPLETED:
dispatch(requestCompleted(data['request-id']));
break;
case 'ERROR':
console.error(data);
dispatch(error(data.message, data['request-id']));
}
}
function onClose(event: CloseEvent, dispatch: Dispatch<any>) {
let reason = getCloseMessage(event);
dispatch(authConnected(false, reason));
}
function getCloseMessage(event: CloseEvent): string {
switch (event.code) {
case 1000:
return 'Normal closure, meaning that the purpose for which the connection was established has been fulfilled.';
case 1001:
return 'An endpoint is \'going away\', such as a server going down or a browser having navigated away from a page.';
case 1002:
return 'An endpoint is terminating the connection due to a protocol error';
case 1003:
return 'An endpoint is terminating the connection because it has received a type of data it cannot accept (e.g., an endpoint that understands only text data MAY send this if it receives a binary message).';
case 1004:
return 'Reserved. The specific meaning might be defined in the future.';
case 1005:
return 'No status code was actually present.';
case 1006:
return 'The connection was closed abnormally, e.g., without sending or receiving a Close control frame';
case 1007:
return 'An endpoint is terminating the connection because it has received data within a message that was not consistent with the type of the message (e.g., non-UTF-8 [http://tools.ietf.org/html/rfc3629] data within a text message).';
case 1008:
return 'An endpoint is terminating the connection because it has received a message that \'violates its policy\'. This reason is given either if there is no other sutible reason, or if there is a need to hide specific details about the policy.';
case 1009:
return 'An endpoint is terminating the connection because it has received a message that is too big for it to process.';
case 1010: // Note that this status code is not used by the server, because it can fail the WebSocket handshake instead:
return 'An endpoint (client) is terminating the connection because it has expected the server to negotiate one or more extension, but the server didn\'t return them in the response message of the WebSocket handshake. <br /> Specifically, the extensions that are needed are: ' + event.reason;
case 1011:
return 'A server is terminating the connection because it encountered an unexpected condition that prevented it from fulfilling the request.';
case 1015:
return 'The connection was closed due to a failure to perform a TLS handshake (e.g., the server certificate can\'t be verified).';
default:
return 'Unknown reason';
}
}
interface ItemsTimeout {
/**
* Resets every time we receive new results, so that we bundle results that
* are received in quick succession of each other.
*
* When the timeout completes, results are dispatched.
*
*/
bundleTimeout: Timer;
/**
* Does not reset when we receive new results. Used for solving the problem
* of the above timeout: imagine that we keep on getting results quickly
* forever -> the above timeout would never complete.
*
* When the timeout completes, results are dispatched.
*
*/
maxTimeout: Timer;
}
const debouncedItems: {
[requestId: string]: Item[]
} = {};
let debouncedFields: FieldMapping = {};
const debounceTimeouts: {
[requestId: string]: ItemsTimeout
} = {};
const timeoutMs = 500;
const maxTimeoutMs = 2000;
/**
* Sometimes we receive many items from the server in quick succession of
* each other. This is not good, because then we would need to calculate the
* graph for each time we receive it (so multiple times per second).
*
* Instead, we wait for 500ms and bundle all of the items together.
*
* @param newItems
* @param fields
* @param requestId
* @param dispatch
* @param isLive
* @param datasourceId
*/
function debounceItems(newItems: Item[], fields: FieldMapping, requestId: string, dispatch: Dispatch<any>, isLive: boolean, datasourceId: string) | {
if (fields) {
Object.keys(fields).forEach(datasource => {
if (!debouncedFields[datasource]) {
debouncedFields[datasource] = {};
}
Object.keys(fields[datasource]).forEach(field => {
const type: string = fields[datasource][field];
debouncedFields[datasource][field] = type;
});
});
}
if (newItems === null) {
return;
}
newItems.forEach(item => {
item.datasourceId = datasourceId
});
let results = debouncedItems[requestId] || [];
for (let i = 0; i < newItems.length; i++ ) {
let result = newItems[i];
let index = results.findIndex((item) => item.id === result.id);
if (index === -1) {
results.push(result);
continue;
}
// already exists, update count
results[index].count = result.count;
}
debouncedItems[requestId] = results;
const searchTimeout: any = debounceTimeouts[requestId] || {};
const timeoutFinished = () => {
clearTimeout(searchTimeout.bundleTimeout);
clearTimeout(searchTimeout.maxTimeout);
dispatch(receiveFieldMapping(debouncedFields));
debouncedFields = {};
if (isLive) {
dispatch(liveReceive(debouncedItems[requestId], datasourceId));
} else {
dispatch(searchReceive(debouncedItems[requestId], requestId));
}
delete debouncedItems[requestId];
};
// Dispatch when we haven't received any new items for 500 ms.
clearTimeout(searchTimeout.bundleTimeout);
searchTimeout.bundleTimeout = setTimeout(timeoutFinished, timeoutMs);
// Only set the max timeout if it wasn't set already. It does not get
// cleared when new items are received.
if (!searchTimeout.maxTimeout) {
// Dispatch also when the max timeout is finished
searchTimeout.maxTimeout = setTimeout(timeoutFinished, maxTimeoutMs);
}
debounceTimeouts[requestId] = searchTimeout;
} | identifier_body | |
webSocketMiddleware.ts | import {
REQUEST_COMPLETED, WEB_SOCKET_CONNECT,
WEB_SOCKET_SEND
} from '../connectionConstants';
import * as ReconnectingWebsocket from 'reconnecting-websocket';
import {Dispatch, Middleware} from 'redux';
import {authConnected, error} from "../connectionActions";
import {Item} from "../../graph/interfaces/item";
import {
liveReceive,
searchReceive,
setSearchTotal
} from "../../search/searchActions";
import {requestCompleted} from "../connectionActions";
import { receiveFieldMapping } from "../../fields/fieldsActions";
import {LIVE_RECEIVE, SEARCH_RECEIVE} from "../../search/searchConstants";
import {INITIAL_STATE_RECEIVE} from "../../datasources/datasourcesConstants";
import {receiveInitialState} from "../../datasources/datasourcesActions";
import Timer = NodeJS.Timer;
import { getResponses } from './mockServer';
import { FieldMapping } from '../../fields/interfaces/fieldMapping';
import { receiveWorkspaceDescriptions } from '../../ui/uiActions';
let opened: Promise<ReconnectingWebsocket>;
export const webSocketMiddleware: Middleware = ({dispatch}) => next => action => {
switch (action.type) {
case WEB_SOCKET_CONNECT: {
const backendUri: string = action.payload.backendUri;
console.log('Connecting to backend on ', backendUri);
opened = new Promise(resolve => {
const socket = new ReconnectingWebsocket(backendUri);
socket.onopen = event => {onOpen(dispatch); resolve(socket)};
socket.onmessage = event => onMessage(event, dispatch);
socket.onclose = event => onClose(event, dispatch);
socket.onerror = event => onClose(event, dispatch);
});
break;
}
case WEB_SOCKET_SEND: {
const payload: string = JSON.stringify(action.payload);
console.log('Send', action.payload);
let mockedResponses;
if (process.env.MOCK_SERVER) {
mockedResponses = getResponses(action.payload) as MessageEvent[];
}
if (mockedResponses) {
mockedResponses.forEach(response => {
console.log('Mocking server response', response);
onMessage(response, dispatch);
});
} else {
opened.then(socket => socket.send(payload));
}
break;
}
}
return next(action);
};
function | (dispatch: Dispatch<any>) {
dispatch(authConnected(true, null));
dispatch(receiveWorkspaceDescriptions([
{
id: '1',
title: 'Research',
version: 7
},
{
id: '2',
title: 'Malware',
version: 7
}
]));
}
function onMessage(event: MessageEvent, dispatch: Dispatch<any>) {
const data = JSON.parse(event.data);
console.log('Receive', data.type);
switch (data.type) {
case SEARCH_RECEIVE: {
if (typeof data.total_count === 'number') {
dispatch(setSearchTotal(data['request-id'], data.total_count));
}
debounceItems(
data.results,
data.mapping,
data['request-id'],
dispatch,
false,
data.datasource
);
break;
}
case LIVE_RECEIVE: {
debounceItems(
data.graphs,
data.mapping,
data.datasource,
dispatch,
true,
data.datasource
);
break;
}
case INITIAL_STATE_RECEIVE:
dispatch(receiveInitialState({
datasources: data.datasources,
enrichers: data.enrichers,
version: data.version
}));
break;
case REQUEST_COMPLETED:
dispatch(requestCompleted(data['request-id']));
break;
case 'ERROR':
console.error(data);
dispatch(error(data.message, data['request-id']));
}
}
function onClose(event: CloseEvent, dispatch: Dispatch<any>) {
let reason = getCloseMessage(event);
dispatch(authConnected(false, reason));
}
function getCloseMessage(event: CloseEvent): string {
switch (event.code) {
case 1000:
return 'Normal closure, meaning that the purpose for which the connection was established has been fulfilled.';
case 1001:
return 'An endpoint is \'going away\', such as a server going down or a browser having navigated away from a page.';
case 1002:
return 'An endpoint is terminating the connection due to a protocol error';
case 1003:
return 'An endpoint is terminating the connection because it has received a type of data it cannot accept (e.g., an endpoint that understands only text data MAY send this if it receives a binary message).';
case 1004:
return 'Reserved. The specific meaning might be defined in the future.';
case 1005:
return 'No status code was actually present.';
case 1006:
return 'The connection was closed abnormally, e.g., without sending or receiving a Close control frame';
case 1007:
return 'An endpoint is terminating the connection because it has received data within a message that was not consistent with the type of the message (e.g., non-UTF-8 [http://tools.ietf.org/html/rfc3629] data within a text message).';
case 1008:
return 'An endpoint is terminating the connection because it has received a message that \'violates its policy\'. This reason is given either if there is no other sutible reason, or if there is a need to hide specific details about the policy.';
case 1009:
return 'An endpoint is terminating the connection because it has received a message that is too big for it to process.';
case 1010: // Note that this status code is not used by the server, because it can fail the WebSocket handshake instead:
return 'An endpoint (client) is terminating the connection because it has expected the server to negotiate one or more extension, but the server didn\'t return them in the response message of the WebSocket handshake. <br /> Specifically, the extensions that are needed are: ' + event.reason;
case 1011:
return 'A server is terminating the connection because it encountered an unexpected condition that prevented it from fulfilling the request.';
case 1015:
return 'The connection was closed due to a failure to perform a TLS handshake (e.g., the server certificate can\'t be verified).';
default:
return 'Unknown reason';
}
}
interface ItemsTimeout {
/**
* Resets every time we receive new results, so that we bundle results that
* are received in quick succession of each other.
*
* When the timeout completes, results are dispatched.
*
*/
bundleTimeout: Timer;
/**
* Does not reset when we receive new results. Used for solving the problem
* of the above timeout: imagine that we keep on getting results quickly
* forever -> the above timeout would never complete.
*
* When the timeout completes, results are dispatched.
*
*/
maxTimeout: Timer;
}
const debouncedItems: {
[requestId: string]: Item[]
} = {};
let debouncedFields: FieldMapping = {};
const debounceTimeouts: {
[requestId: string]: ItemsTimeout
} = {};
const timeoutMs = 500;
const maxTimeoutMs = 2000;
/**
* Sometimes we receive many items from the server in quick succession of
* each other. This is not good, because then we would need to calculate the
* graph for each time we receive it (so multiple times per second).
*
* Instead, we wait for 500ms and bundle all of the items together.
*
* @param newItems
* @param fields
* @param requestId
* @param dispatch
* @param isLive
* @param datasourceId
*/
function debounceItems(newItems: Item[], fields: FieldMapping, requestId: string, dispatch: Dispatch<any>, isLive: boolean, datasourceId: string) {
if (fields) {
Object.keys(fields).forEach(datasource => {
if (!debouncedFields[datasource]) {
debouncedFields[datasource] = {};
}
Object.keys(fields[datasource]).forEach(field => {
const type: string = fields[datasource][field];
debouncedFields[datasource][field] = type;
});
});
}
if (newItems === null) {
return;
}
newItems.forEach(item => {
item.datasourceId = datasourceId
});
let results = debouncedItems[requestId] || [];
for (let i = 0; i < newItems.length; i++ ) {
let result = newItems[i];
let index = results.findIndex((item) => item.id === result.id);
if (index === -1) {
results.push(result);
continue;
}
// already exists, update count
results[index].count = result.count;
}
debouncedItems[requestId] = results;
const searchTimeout: any = debounceTimeouts[requestId] || {};
const timeoutFinished = () => {
clearTimeout(searchTimeout.bundleTimeout);
clearTimeout(searchTimeout.maxTimeout);
dispatch(receiveFieldMapping(debouncedFields));
debouncedFields = {};
if (isLive) {
dispatch(liveReceive(debouncedItems[requestId], datasourceId));
} else {
dispatch(searchReceive(debouncedItems[requestId], requestId));
}
delete debouncedItems[requestId];
};
// Dispatch when we haven't received any new items for 500 ms.
clearTimeout(searchTimeout.bundleTimeout);
searchTimeout.bundleTimeout = setTimeout(timeoutFinished, timeoutMs);
// Only set the max timeout if it wasn't set already. It does not get
// cleared when new items are received.
if (!searchTimeout.maxTimeout) {
// Dispatch also when the max timeout is finished
searchTimeout.maxTimeout = setTimeout(timeoutFinished, maxTimeoutMs);
}
debounceTimeouts[requestId] = searchTimeout;
} | onOpen | identifier_name |
FlagView.js | 'use strict';
angular.module('cbt')
.directive('flagView', function(){
return {
restrict: 'E',
template: '{{title}}'+
'<a class="led" ng-repeat="led in values track by $index" ng-class="{\'active\':values[$index]}" title="{{info[title.toLowerCase()][$index]}}"></a>',
link: function (scope, elem, attrs) {
scope.values = Array(8);
scope.$watch('value',function(newValue,oldValue) {
for(var i=0; i<8; i++)
scope.values[i] = !!(newValue & (0x01 << 7-i));
});
},
controller: function($scope){
// Description Library
$scope.info = {
error:[
'RX1OVR: Receive Buffer 1 Overflow Flag bit',
'TXBO: Bus-Off Error Flag bit',
'TXBO: Bus-Off Error Flag bit',
'TXEP: Transmit Error-Passive Flag bit',
'RXEP: Receive Error-Passive Flag bit',
'TXWAR: Transmit Error Warning Flag bit',
'RXWAR: Receive Error Warning Flag bit',
'EWARN: Error Warning Flag bit',
],
// Datasheet pg 58
control:[
'',
'',
'',
'',
'',
'',
'',
''
],
status:[
'CANINTF.RX0IF',
'CANINTFL.RX1IF',
'TXB0CNTRL.TXREQ',
'CANINTF.TX0IF',
'TXB1CNTRL.TXREQ',
'CANINTF.TX1IF',
'TXB2CNTRL.TXREQ',
'CANINTF.TX2IF'
]
}
},
scope: {
title: "@",
value: "@"
} |
}); | } | random_line_split |
ManifestRDFUtils.py | #!/usr/bin/python
#
# Coypyright (C) 2010, University of Oxford
#
# Licensed under the MIT License. You may obtain a copy of the License at:
#
# http://www.opensource.org/licenses/mit-license.php
#
# 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.
#
# $Id: $
"""
Support functions for creating, reading, writing and updating manifest RDF file.
"""
__author__ = "Bhavana Ananda"
__version__ = "0.1"
import logging, os, rdflib
from os.path import isdir
from rdflib import URIRef, Namespace, BNode
from rdflib.namespace import RDF
from rdflib.graph import Graph
from rdflib.plugins.memory import Memory
from rdflib import Literal
Logger = logging.getLogger("MaifestRDFUtils")
oxds = URIRef("http://vocab.ox.ac.uk/dataset/schema#")
oxdsGroupingUri = URIRef(oxds+"Grouping")
def bindNamespaces(rdfGraph, namespaceDict):
# Bind namespaces
for key in namespaceDict:
keyValue = namespaceDict[key]
Logger.debug(key+":"+keyValue)
rdfGraph.bind( key, keyValue , override=True)
# rdfGraph.bind("dcterms", dcterms, override=True)
# rdfGraph.bind("oxds", oxds, override=True)
# URIRef(dcterms+elementList[index])
return rdfGraph
def readManifestFile(manifestPath):
"""
Read from the manifest file.
manifestPath manifest file path
"""
# Read from the manifest.rdf file into an RDF Graph
rdfGraph = Graph()
rdfGraph.parse(manifestPath)
return rdfGraph
def writeToManifestFile(manifestPath, namespaceDict, elementUriList,elementValueList):
"""
Write to the manifest file.
manifestPath manifest file path
elementUriList Element Uri List to be written into the manifest files
elementValueList Element Values List to be written into the manifest files
"""
# Create an empty RDF Graph
rdfGraph = Graph()
subject = BNode()
rdfGraph = bindNamespaces(rdfGraph, namespaceDict)
# Write to the RDF Graph
rdfGraph.add((subject, RDF.type, oxdsGroupingUri))
for index in range(len(elementUriList)):
rdfGraph.add((subject,elementUriList[index], Literal(elementValueList[index])))
# Serialise it to a manifest.rdf file
saveToManifestFile(rdfGraph, manifestPath)
return rdfGraph
def updateManifestFile(manifestPath, elementUriList, elementValueList):
"""
Update the manifest file.
manifestPath manifest file path
elementUriList Element Uri List whose values need to be to be updated in the manifest files
elementValueList Element Values List to be updated into the manifest files
"""
# Read the manifest file and update the title and the description
rdfGraph = readManifestFile(manifestPath)
subject = rdfGraph.value(None,RDF.type, oxdsGroupingUri)
if subject == None :
subject = BNode()
for index in range(len(elementUriList)):
rdfGraph.set((subject, elementUriList[index], Literal(elementValueList[index])))
saveToManifestFile(rdfGraph,manifestPath)
return rdfGraph
def saveToManifestFile(rdfGraph, manifestPath):
"""
Save the RDF Graph into a manifest file.
rdfGraph RDF Graph to be serialised into the manifest file
manifestPath manifest file path
"""
# Serialise the RDf Graph into manifest.rdf file
rdfGraph.serialize(destination=manifestPath, format='pretty-xml')
return
def compareRDFGraphs(graphA, graphB, elementUriListToCompare=[]):
"""
Compare two RDG graphs
graphA RDF Graph of Graph A
graphB RDF Graph of Graph B
graphsEqual Return True if the two graphs are equal or false otherwise
"""
def graphContains(graph, statement):
(s,p,o) = statement
if isinstance(s, BNode): s = None
if isinstance(p, BNode): p = None
if isinstance(o, BNode): o = None
return (s,p,o) in graph
graphsEqual = True
for statement in graphA:
if not graphContains(graphB, statement) : |
for statement in graphB:
if not graphContains(graphA, statement) : return False
subjectA = graphA.value(None,RDF.type, oxdsGroupingUri)
subjectB = graphB.value(None,RDF.type, oxdsGroupingUri)
for elementUri in elementUriListToCompare :
if graphA.value(subjectA,elementUri,None)!=graphB.value(subjectB,elementUri,None) :
graphsEqual = False
return graphsEqual
def getElementValuesFromManifest(rdfGraph,elementUriList):
"""
Get element values of the element list supplied from the RDF graph
rdfGraph RDF Graph
elementUriList Element Uri List whose values need to be to be extracted from the manifest files
"""
elementValueList = []
subject = rdfGraph.value(None, RDF.type, oxdsGroupingUri)
for elementUri in elementUriList:
elementValueList.append(rdfGraph.value(subject,elementUri,None))
Logger.debug("Element Uri List =" + repr(elementUriList))
Logger.debug("Element Value List =" + repr(elementValueList))
return elementValueList
def getDictionaryFromManifest(manifestPath, elementUriList):
"""
Gets the dictionary of Field-Values from the manifest RDF
manifestPath path of the manifest file
elementList Element Names List whose values need to be to be updated in the manifest files
"""
file = None
elementValueList = []
elementList = []
dict = {}
json = ""
Logger.debug(manifestPath)
if manifestPath != None and ifFileExists(manifestPath):
rdfGraph = readManifestFile(manifestPath)
elementValueList = getElementValuesFromManifest(rdfGraph, elementUriList)
# Logger.debug("Element URi List =" + repr(elementUriList))
# Logger.debug("Element Value List =" + repr(elementValueList))
for index in range(len(elementUriList)):
Logger.debug("Index = " + repr(index))
elementUri = elementUriList[index]
position = elementUri.rfind("/") +1
elementList.append(elementUri[position:])
Logger.debug("substring = " + elementUri[position:])
if elementValueList!=[]:
dict = createDictionary(elementList, elementValueList)
return dict
def ifFileExists(filePath):
"""
Cheks if the file exists; returns True/False
filePath File Path
"""
return os.path.isfile(filePath)
def createDictionary(keyList, valueList):
"""
Creates and returns a dictionary from the keyList and valueList supplied
keyUriList List of key uris
valueList List of values
"""
dict = {}
for index in range(len(keyList)):
dict[keyList[index]] = valueList[index]
# Logger.debug(" Key Uri List = "+ repr(keyUriList))
# Logger.debug(" Key value list = "+ repr(valueList))
return dict
| return False | conditional_block |
ManifestRDFUtils.py | #!/usr/bin/python
#
# Coypyright (C) 2010, University of Oxford
#
# Licensed under the MIT License. You may obtain a copy of the License at:
#
# http://www.opensource.org/licenses/mit-license.php
#
# 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.
#
# $Id: $
"""
Support functions for creating, reading, writing and updating manifest RDF file.
"""
__author__ = "Bhavana Ananda"
__version__ = "0.1"
import logging, os, rdflib
from os.path import isdir
from rdflib import URIRef, Namespace, BNode
from rdflib.namespace import RDF
from rdflib.graph import Graph
from rdflib.plugins.memory import Memory
from rdflib import Literal
Logger = logging.getLogger("MaifestRDFUtils")
oxds = URIRef("http://vocab.ox.ac.uk/dataset/schema#")
oxdsGroupingUri = URIRef(oxds+"Grouping")
def bindNamespaces(rdfGraph, namespaceDict):
# Bind namespaces
for key in namespaceDict:
keyValue = namespaceDict[key]
Logger.debug(key+":"+keyValue)
rdfGraph.bind( key, keyValue , override=True)
# rdfGraph.bind("dcterms", dcterms, override=True)
# rdfGraph.bind("oxds", oxds, override=True)
# URIRef(dcterms+elementList[index])
return rdfGraph
def readManifestFile(manifestPath):
"""
Read from the manifest file.
manifestPath manifest file path
"""
# Read from the manifest.rdf file into an RDF Graph
rdfGraph = Graph()
rdfGraph.parse(manifestPath)
return rdfGraph
def writeToManifestFile(manifestPath, namespaceDict, elementUriList,elementValueList):
"""
Write to the manifest file.
manifestPath manifest file path
elementUriList Element Uri List to be written into the manifest files
elementValueList Element Values List to be written into the manifest files
"""
# Create an empty RDF Graph
rdfGraph = Graph()
subject = BNode()
rdfGraph = bindNamespaces(rdfGraph, namespaceDict)
# Write to the RDF Graph
rdfGraph.add((subject, RDF.type, oxdsGroupingUri))
for index in range(len(elementUriList)):
rdfGraph.add((subject,elementUriList[index], Literal(elementValueList[index])))
# Serialise it to a manifest.rdf file
saveToManifestFile(rdfGraph, manifestPath)
return rdfGraph
def updateManifestFile(manifestPath, elementUriList, elementValueList):
"""
Update the manifest file.
manifestPath manifest file path
elementUriList Element Uri List whose values need to be to be updated in the manifest files
elementValueList Element Values List to be updated into the manifest files
"""
| if subject == None :
subject = BNode()
for index in range(len(elementUriList)):
rdfGraph.set((subject, elementUriList[index], Literal(elementValueList[index])))
saveToManifestFile(rdfGraph,manifestPath)
return rdfGraph
def saveToManifestFile(rdfGraph, manifestPath):
"""
Save the RDF Graph into a manifest file.
rdfGraph RDF Graph to be serialised into the manifest file
manifestPath manifest file path
"""
# Serialise the RDf Graph into manifest.rdf file
rdfGraph.serialize(destination=manifestPath, format='pretty-xml')
return
def compareRDFGraphs(graphA, graphB, elementUriListToCompare=[]):
"""
Compare two RDG graphs
graphA RDF Graph of Graph A
graphB RDF Graph of Graph B
graphsEqual Return True if the two graphs are equal or false otherwise
"""
def graphContains(graph, statement):
(s,p,o) = statement
if isinstance(s, BNode): s = None
if isinstance(p, BNode): p = None
if isinstance(o, BNode): o = None
return (s,p,o) in graph
graphsEqual = True
for statement in graphA:
if not graphContains(graphB, statement) : return False
for statement in graphB:
if not graphContains(graphA, statement) : return False
subjectA = graphA.value(None,RDF.type, oxdsGroupingUri)
subjectB = graphB.value(None,RDF.type, oxdsGroupingUri)
for elementUri in elementUriListToCompare :
if graphA.value(subjectA,elementUri,None)!=graphB.value(subjectB,elementUri,None) :
graphsEqual = False
return graphsEqual
def getElementValuesFromManifest(rdfGraph,elementUriList):
"""
Get element values of the element list supplied from the RDF graph
rdfGraph RDF Graph
elementUriList Element Uri List whose values need to be to be extracted from the manifest files
"""
elementValueList = []
subject = rdfGraph.value(None, RDF.type, oxdsGroupingUri)
for elementUri in elementUriList:
elementValueList.append(rdfGraph.value(subject,elementUri,None))
Logger.debug("Element Uri List =" + repr(elementUriList))
Logger.debug("Element Value List =" + repr(elementValueList))
return elementValueList
def getDictionaryFromManifest(manifestPath, elementUriList):
"""
Gets the dictionary of Field-Values from the manifest RDF
manifestPath path of the manifest file
elementList Element Names List whose values need to be to be updated in the manifest files
"""
file = None
elementValueList = []
elementList = []
dict = {}
json = ""
Logger.debug(manifestPath)
if manifestPath != None and ifFileExists(manifestPath):
rdfGraph = readManifestFile(manifestPath)
elementValueList = getElementValuesFromManifest(rdfGraph, elementUriList)
# Logger.debug("Element URi List =" + repr(elementUriList))
# Logger.debug("Element Value List =" + repr(elementValueList))
for index in range(len(elementUriList)):
Logger.debug("Index = " + repr(index))
elementUri = elementUriList[index]
position = elementUri.rfind("/") +1
elementList.append(elementUri[position:])
Logger.debug("substring = " + elementUri[position:])
if elementValueList!=[]:
dict = createDictionary(elementList, elementValueList)
return dict
def ifFileExists(filePath):
"""
Cheks if the file exists; returns True/False
filePath File Path
"""
return os.path.isfile(filePath)
def createDictionary(keyList, valueList):
"""
Creates and returns a dictionary from the keyList and valueList supplied
keyUriList List of key uris
valueList List of values
"""
dict = {}
for index in range(len(keyList)):
dict[keyList[index]] = valueList[index]
# Logger.debug(" Key Uri List = "+ repr(keyUriList))
# Logger.debug(" Key value list = "+ repr(valueList))
return dict | # Read the manifest file and update the title and the description
rdfGraph = readManifestFile(manifestPath)
subject = rdfGraph.value(None,RDF.type, oxdsGroupingUri) | random_line_split |
ManifestRDFUtils.py | #!/usr/bin/python
#
# Coypyright (C) 2010, University of Oxford
#
# Licensed under the MIT License. You may obtain a copy of the License at:
#
# http://www.opensource.org/licenses/mit-license.php
#
# 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.
#
# $Id: $
"""
Support functions for creating, reading, writing and updating manifest RDF file.
"""
__author__ = "Bhavana Ananda"
__version__ = "0.1"
import logging, os, rdflib
from os.path import isdir
from rdflib import URIRef, Namespace, BNode
from rdflib.namespace import RDF
from rdflib.graph import Graph
from rdflib.plugins.memory import Memory
from rdflib import Literal
Logger = logging.getLogger("MaifestRDFUtils")
oxds = URIRef("http://vocab.ox.ac.uk/dataset/schema#")
oxdsGroupingUri = URIRef(oxds+"Grouping")
def bindNamespaces(rdfGraph, namespaceDict):
# Bind namespaces
for key in namespaceDict:
keyValue = namespaceDict[key]
Logger.debug(key+":"+keyValue)
rdfGraph.bind( key, keyValue , override=True)
# rdfGraph.bind("dcterms", dcterms, override=True)
# rdfGraph.bind("oxds", oxds, override=True)
# URIRef(dcterms+elementList[index])
return rdfGraph
def readManifestFile(manifestPath):
"""
Read from the manifest file.
manifestPath manifest file path
"""
# Read from the manifest.rdf file into an RDF Graph
rdfGraph = Graph()
rdfGraph.parse(manifestPath)
return rdfGraph
def writeToManifestFile(manifestPath, namespaceDict, elementUriList,elementValueList):
"""
Write to the manifest file.
manifestPath manifest file path
elementUriList Element Uri List to be written into the manifest files
elementValueList Element Values List to be written into the manifest files
"""
# Create an empty RDF Graph
rdfGraph = Graph()
subject = BNode()
rdfGraph = bindNamespaces(rdfGraph, namespaceDict)
# Write to the RDF Graph
rdfGraph.add((subject, RDF.type, oxdsGroupingUri))
for index in range(len(elementUriList)):
rdfGraph.add((subject,elementUriList[index], Literal(elementValueList[index])))
# Serialise it to a manifest.rdf file
saveToManifestFile(rdfGraph, manifestPath)
return rdfGraph
def updateManifestFile(manifestPath, elementUriList, elementValueList):
"""
Update the manifest file.
manifestPath manifest file path
elementUriList Element Uri List whose values need to be to be updated in the manifest files
elementValueList Element Values List to be updated into the manifest files
"""
# Read the manifest file and update the title and the description
rdfGraph = readManifestFile(manifestPath)
subject = rdfGraph.value(None,RDF.type, oxdsGroupingUri)
if subject == None :
subject = BNode()
for index in range(len(elementUriList)):
rdfGraph.set((subject, elementUriList[index], Literal(elementValueList[index])))
saveToManifestFile(rdfGraph,manifestPath)
return rdfGraph
def saveToManifestFile(rdfGraph, manifestPath):
"""
Save the RDF Graph into a manifest file.
rdfGraph RDF Graph to be serialised into the manifest file
manifestPath manifest file path
"""
# Serialise the RDf Graph into manifest.rdf file
rdfGraph.serialize(destination=manifestPath, format='pretty-xml')
return
def compareRDFGraphs(graphA, graphB, elementUriListToCompare=[]):
"""
Compare two RDG graphs
graphA RDF Graph of Graph A
graphB RDF Graph of Graph B
graphsEqual Return True if the two graphs are equal or false otherwise
"""
def graphContains(graph, statement):
(s,p,o) = statement
if isinstance(s, BNode): s = None
if isinstance(p, BNode): p = None
if isinstance(o, BNode): o = None
return (s,p,o) in graph
graphsEqual = True
for statement in graphA:
if not graphContains(graphB, statement) : return False
for statement in graphB:
if not graphContains(graphA, statement) : return False
subjectA = graphA.value(None,RDF.type, oxdsGroupingUri)
subjectB = graphB.value(None,RDF.type, oxdsGroupingUri)
for elementUri in elementUriListToCompare :
if graphA.value(subjectA,elementUri,None)!=graphB.value(subjectB,elementUri,None) :
graphsEqual = False
return graphsEqual
def getElementValuesFromManifest(rdfGraph,elementUriList):
"""
Get element values of the element list supplied from the RDF graph
rdfGraph RDF Graph
elementUriList Element Uri List whose values need to be to be extracted from the manifest files
"""
elementValueList = []
subject = rdfGraph.value(None, RDF.type, oxdsGroupingUri)
for elementUri in elementUriList:
elementValueList.append(rdfGraph.value(subject,elementUri,None))
Logger.debug("Element Uri List =" + repr(elementUriList))
Logger.debug("Element Value List =" + repr(elementValueList))
return elementValueList
def | (manifestPath, elementUriList):
"""
Gets the dictionary of Field-Values from the manifest RDF
manifestPath path of the manifest file
elementList Element Names List whose values need to be to be updated in the manifest files
"""
file = None
elementValueList = []
elementList = []
dict = {}
json = ""
Logger.debug(manifestPath)
if manifestPath != None and ifFileExists(manifestPath):
rdfGraph = readManifestFile(manifestPath)
elementValueList = getElementValuesFromManifest(rdfGraph, elementUriList)
# Logger.debug("Element URi List =" + repr(elementUriList))
# Logger.debug("Element Value List =" + repr(elementValueList))
for index in range(len(elementUriList)):
Logger.debug("Index = " + repr(index))
elementUri = elementUriList[index]
position = elementUri.rfind("/") +1
elementList.append(elementUri[position:])
Logger.debug("substring = " + elementUri[position:])
if elementValueList!=[]:
dict = createDictionary(elementList, elementValueList)
return dict
def ifFileExists(filePath):
"""
Cheks if the file exists; returns True/False
filePath File Path
"""
return os.path.isfile(filePath)
def createDictionary(keyList, valueList):
"""
Creates and returns a dictionary from the keyList and valueList supplied
keyUriList List of key uris
valueList List of values
"""
dict = {}
for index in range(len(keyList)):
dict[keyList[index]] = valueList[index]
# Logger.debug(" Key Uri List = "+ repr(keyUriList))
# Logger.debug(" Key value list = "+ repr(valueList))
return dict
| getDictionaryFromManifest | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.