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 |
|---|---|---|---|---|
action.filter.ts | import {Component, Input, OnInit} from '@angular/core';
import {Observable, Subject} from 'rxjs';
import {App, ApplicationType} from '../../shared/model/app.model';
import {RecordService} from '../../shared/api/record.service';
import {RecordActionType} from '../../shared/model/record.model';
@Component({
selector: ... | (): void {
this.recordService.getActionTypes().subscribe((actionTypes: RecordActionType[]) => {
this.actionTypes = actionTypes;
if (this.value === 'all' || this.value === '' || !this.value) {
this.value = null;
} else {
this.val = this.value;
this.pchanges.next(true);
... | ngOnInit | identifier_name |
action.filter.ts | import {Component, Input, OnInit} from '@angular/core';
import {Observable, Subject} from 'rxjs';
import {App, ApplicationType} from '../../shared/model/app.model';
import {RecordService} from '../../shared/api/record.service';
import {RecordActionType} from '../../shared/model/record.model';
@Component({
selector: ... | else {
this.value = this.val as any as RecordActionType;
}
this.pchanges.next(true);
}
accepts(application: App): boolean {
return true;
}
isActive(): boolean {
return this.value !== null && this.value !== 'all' && this.value !== '';
}
}
| {
this.value = null;
} | conditional_block |
action.filter.ts | import {Component, Input, OnInit} from '@angular/core';
import {Observable, Subject} from 'rxjs'; | import {RecordActionType} from '../../shared/model/record.model';
@Component({
selector: 'app-clr-datagrid-action-filter',
template: ` <div>
<clr-radio-wrapper>
<input type="radio" clrRadio (change)="change()" [(ngModel)]="val" value="all" name="options" />
<label>All actions</label>
</clr-radi... | import {App, ApplicationType} from '../../shared/model/app.model';
import {RecordService} from '../../shared/api/record.service'; | random_line_split |
action.filter.ts | import {Component, Input, OnInit} from '@angular/core';
import {Observable, Subject} from 'rxjs';
import {App, ApplicationType} from '../../shared/model/app.model';
import {RecordService} from '../../shared/api/record.service';
import {RecordActionType} from '../../shared/model/record.model';
@Component({
selector: ... |
public get changes(): Observable<any> {
return this.pchanges.asObservable();
}
change(): void {
if (this.val === 'all') {
this.value = null;
} else {
this.value = this.val as any as RecordActionType;
}
this.pchanges.next(true);
}
accepts(application: App): boolean {
ret... | {
this.recordService.getActionTypes().subscribe((actionTypes: RecordActionType[]) => {
this.actionTypes = actionTypes;
if (this.value === 'all' || this.value === '' || !this.value) {
this.value = null;
} else {
this.val = this.value;
this.pchanges.next(true);
}
})... | identifier_body |
symbol_test.js | /*
* Copyright 2016 The Closure Compiler Authors.
*
* 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
* | * 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 Tests for user-defined Symbols.
*/
goog.require('goog.testing.jsunit');
const s1 = Symbol('example');
const s2 ... | * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, | random_line_split |
symbol_test.js | /*
* Copyright 2016 The Closure Compiler Authors.
*
* 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... |
}
function testSymbols() {
const sp = new SymbolProps();
assertEquals('s1', sp[s1]());
assertEquals('s2', sp[s2]());
}
function testArrayIterator() {
// Note: this test cannot pass in IE8 since we can't polyfill
// Array.prototype methods and maintain correct for-in behavior.
if (typeof Object.defineProp... | { return 's2'; } | identifier_body |
symbol_test.js | /*
* Copyright 2016 The Closure Compiler Authors.
*
* 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... | () {
// Note: this test cannot pass in IE8 since we can't polyfill
// Array.prototype methods and maintain correct for-in behavior.
if (typeof Object.defineProperties !== 'function') return;
const iter = [2, 4, 6][Symbol.iterator]();
assertObjectEquals({value: 2, done: false}, iter.next());
assertObjectEqu... | testArrayIterator | identifier_name |
BaseControl.tsx | // Imports
import * as React from "react";
import ValidationManager from "../Validation/ValidationManager"
import ErrorDisplay from "../Validation/ErrorDisplay"
// Importation des règles CSS de bases -> à transformer en styled-components
import "../../../../Common/theming/base.css"
import UpTooltip, { Tooltip } from '... | var hasError = this.checkData(cleanData);
this.setState({ value: cleanData }, () => { this.dispatchOnChange(this.state.value, null, hasError) });
} else {
this.setState({ value: cleanData }, () => { this.dispatchOnChange(this.state.value, null, null); });
}
}
... | var _value = (value !== undefined) ? value : this.state.value;
var cleanData: _BaseType = this.getValue(_value);
if (this._validationManager !== undefined) { | random_line_split |
BaseControl.tsx | // Imports
import * as React from "react";
import ValidationManager from "../Validation/ValidationManager"
import ErrorDisplay from "../Validation/ErrorDisplay"
// Importation des règles CSS de bases -> à transformer en styled-components
import "../../../../Common/theming/base.css"
import UpTooltip, { Tooltip } from '... | ps) {
if (nextProps.value !== undefined && nextProps.onChange === undefined) {
throw new Error(ONCHANGE_MUST_BE_SPECIFIED);
}
}
public componentWillReceiveProps(nextProps) {
var newValue = nextProps.value;
var oldValue = this.state.value;
if (newValue !== und... | Props(nextPro | identifier_name |
BaseControl.tsx | // Imports
import * as React from "react";
import ValidationManager from "../Validation/ValidationManager"
import ErrorDisplay from "../Validation/ErrorDisplay"
// Importation des règles CSS de bases -> à transformer en styled-components
import "../../../../Common/theming/base.css"
import UpTooltip, { Tooltip } from '... | ivate initWithProps() {
if (this.props.value !== undefined)
this.state = { value: this.props.value as any };
}
protected registerValidations() {
this._validationManager = new ValidationManager();
if (this.props.isRequired) {
this._validationManager.addControl(new... | super(props, context);
this.state = {
error: null,
value: this.props.value !== undefined ? this.props.value as any :
this.props.defaultValue !== undefined ? this.props.defaultValue as any
: null
};
this.initWithProps();
this... | identifier_body |
EditRecord.js | /*
添加用户的教育经历
*/
import React, { PropTypes } from 'react';
import { Toast, Msg } from 'react-weui';
import RecordHistory from '../detail/RecordHistory';
import AddRecord from './AddRecord';
import RemoveRecord from './RemoveRecord';
import { connect } from 'react-redux';
import * as actions from '../../../actions/accep... | }
render() {
const { err, data, toast } = this.props;
return err ? <Msg type="warn" title="发生错误" description={JSON.stringify(err.msg)} /> : (
<div>
<RecordHistory data={data} />
<AddRecord {...this.props} />
<RemoveRecord {...this.props} />
<Toast icon="loading" show={... | componentDidMount() {
this.props.init(this.props.acceptorId);
this.context.setTitle('修改受赠记录'); | random_line_split |
EditRecord.js | /*
添加用户的教育经历
*/
import React, { PropTypes } from 'react';
import { Toast, Msg } from 'react-weui';
import RecordHistory from '../detail/RecordHistory';
import AddRecord from './AddRecord';
import RemoveRecord from './RemoveRecord';
import { connect } from 'react-redux';
import * as actions from '../../../actions/accep... | s.init(this.props.acceptorId);
this.context.setTitle('修改受赠记录');
}
render() {
const { err, data, toast } = this.props;
return err ? <Msg type="warn" title="发生错误" description={JSON.stringify(err.msg)} /> : (
<div>
<RecordHistory data={data} />
<AddRecord {...this.props} />
<... | ) {
this.prop | identifier_name |
new-thread.controller.js | (function(){
function newThreadCtrl($location, $state, MessageEditorService){
var vm = this;
vm.getConstants = function(){
return MessageEditorService.pmConstants;
};
vm.newThread = MessageEditorService.getThreadTemplate($location.search().boardId);
vm.returnToBoard = function(){
var boardId... |
vm.isOpen = false;
}
angular.module('zfgc.forum')
.controller('newThreadCtrl', ['$location', '$state', 'MessageEditorService', newThreadCtrl]);
})(); | random_line_split | |
new-thread.controller.js | (function(){
function newThreadCtrl($location, $state, MessageEditorService) |
angular.module('zfgc.forum')
.controller('newThreadCtrl', ['$location', '$state', 'MessageEditorService', newThreadCtrl]);
})(); | {
var vm = this;
vm.getConstants = function(){
return MessageEditorService.pmConstants;
};
vm.newThread = MessageEditorService.getThreadTemplate($location.search().boardId);
vm.returnToBoard = function(){
var boardId = $location.search().boardId;
$state.go('board',{boardId: boardId});
... | identifier_body |
new-thread.controller.js | (function(){
function | ($location, $state, MessageEditorService){
var vm = this;
vm.getConstants = function(){
return MessageEditorService.pmConstants;
};
vm.newThread = MessageEditorService.getThreadTemplate($location.search().boardId);
vm.returnToBoard = function(){
var boardId = $location.search().boardId;
... | newThreadCtrl | identifier_name |
DensifyGeometriesInterval.py | # -*- coding: utf-8 -*-
"""
***************************************************************************
DensifyGeometriesInterval.py by Anita Graser, Dec 2012
based on DensifyGeometries.py
---------------------
Date : October 2012
Copyright : (C) 2012 by Victor Olaya
... |
def prepareAlgorithm(self, parameters, context, feedback):
interval = self.parameterAsDouble(parameters, self.INTERVAL, context)
return True
def processFeature(self, feature, feedback):
if feature.hasGeometry():
new_geometry = feature.geometry().densifyByDistance(float(int... | return self.tr('Densified') | identifier_body |
DensifyGeometriesInterval.py | # -*- coding: utf-8 -*- | DensifyGeometriesInterval.py by Anita Graser, Dec 2012
based on DensifyGeometries.py
---------------------
Date : October 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
*********************************************************... |
"""
*************************************************************************** | random_line_split |
DensifyGeometriesInterval.py | # -*- coding: utf-8 -*-
"""
***************************************************************************
DensifyGeometriesInterval.py by Anita Graser, Dec 2012
based on DensifyGeometries.py
---------------------
Date : October 2012
Copyright : (C) 2012 by Victor Olaya
... |
return feature
| new_geometry = feature.geometry().densifyByDistance(float(interval))
feature.setGeometry(new_geometry) | conditional_block |
DensifyGeometriesInterval.py | # -*- coding: utf-8 -*-
"""
***************************************************************************
DensifyGeometriesInterval.py by Anita Graser, Dec 2012
based on DensifyGeometries.py
---------------------
Date : October 2012
Copyright : (C) 2012 by Victor Olaya
... | (self):
return 'densifygeometriesgivenaninterval'
def displayName(self):
return self.tr('Densify geometries given an interval')
def outputName(self):
return self.tr('Densified')
def prepareAlgorithm(self, parameters, context, feedback):
interval = self.parameterAsDouble(pa... | name | identifier_name |
AbstractMaskSystem.ts | import { System } from '../System';
import type { MaskData } from './MaskData';
import type { Renderer } from '../Renderer';
/**
* System plugin to the renderer to manage masks of certain type
*
* @class
* @extends PIXI.System
* @memberof PIXI.systems
*/
export class AbstractMaskSystem extends System
{
prot... | (): number
{
return this.maskStack.length;
}
/**
* Changes the mask stack that is used by this System.
*
* @param {PIXI.MaskData[]} maskStack - The mask stack
*/
setMaskStack(maskStack: Array<MaskData>): void
{
const { gl } = this.renderer;
const curStack... | getStackLength | identifier_name |
AbstractMaskSystem.ts | import { System } from '../System';
import type { MaskData } from './MaskData';
import type { Renderer } from '../Renderer';
/**
* System plugin to the renderer to manage masks of certain type
*
* @class
* @extends PIXI.System
* @memberof PIXI.systems
*/
export class AbstractMaskSystem extends System
{
prot... |
else
{
gl.enable(this.glConst);
this._useCurrent();
}
}
}
/**
* Setup renderer to use the current mask data.
* @private
*/
protected _useCurrent(): void
{
// OVERWRITE;
}
/**
* Destroys the... | {
gl.disable(this.glConst);
} | conditional_block |
AbstractMaskSystem.ts | import { System } from '../System';
import type { MaskData } from './MaskData';
import type { Renderer } from '../Renderer';
/**
* System plugin to the renderer to manage masks of certain type
*
* @class
* @extends PIXI.System
* @memberof PIXI.systems
*/
export class AbstractMaskSystem extends System
{
prot... |
/**
* Destroys the mask stack.
*
*/
destroy(): void
{
super.destroy();
this.maskStack = null;
}
}
| {
// OVERWRITE;
} | identifier_body |
AbstractMaskSystem.ts | import { System } from '../System';
import type { MaskData } from './MaskData';
import type { Renderer } from '../Renderer';
/**
* System plugin to the renderer to manage masks of certain type
*
* @class
* @extends PIXI.System
* @memberof PIXI.systems
*/
export class AbstractMaskSystem extends System
{
prot... | */
constructor(renderer: Renderer)
{
super(renderer);
/**
* The mask stack
* @member {PIXI.MaskData[]}
*/
this.maskStack = [];
/**
* Constant for gl.enable
* @member {number}
* @private
*/
this.glConst ... | random_line_split | |
mod.rs | mod env;
mod model;
mod uploader;
use async_trait::async_trait;
use http::Uri;
use model::endpoint::Endpoint;
use opentelemetry::sdk::resource::ResourceDetector;
use opentelemetry::sdk::resource::SdkProvidedResourceDetector;
use opentelemetry::sdk::trace::Config;
use opentelemetry::sdk::Resource;
use opentelemetry::{
... |
/// Assign client implementation
pub fn with_http_client<T: HttpClient + 'static>(mut self, client: T) -> Self {
self.client = Some(Box::new(client));
self
}
/// Assign the service name under which to group traces.
pub fn with_service_address(mut self, addr: SocketAddr) -> Self {
... | /// Assign the service name under which to group traces.
pub fn with_service_name<T: Into<String>>(mut self, name: T) -> Self {
self.service_name = Some(name.into());
self
} | random_line_split |
mod.rs | mod env;
mod model;
mod uploader;
use async_trait::async_trait;
use http::Uri;
use model::endpoint::Endpoint;
use opentelemetry::sdk::resource::ResourceDetector;
use opentelemetry::sdk::resource::SdkProvidedResourceDetector;
use opentelemetry::sdk::trace::Config;
use opentelemetry::sdk::Resource;
use opentelemetry::{
... | (local_endpoint: Endpoint, client: Box<dyn HttpClient>, collector_endpoint: Uri) -> Self {
Exporter {
local_endpoint,
uploader: uploader::Uploader::new(client, collector_endpoint),
}
}
}
/// Create a new Zipkin exporter pipeline builder.
pub fn new_pipeline() -> ZipkinPipeli... | new | identifier_name |
mod.rs | mod env;
mod model;
mod uploader;
use async_trait::async_trait;
use http::Uri;
use model::endpoint::Endpoint;
use opentelemetry::sdk::resource::ResourceDetector;
use opentelemetry::sdk::resource::SdkProvidedResourceDetector;
use opentelemetry::sdk::trace::Config;
use opentelemetry::sdk::Resource;
use opentelemetry::{
... | else {
let service_name = SdkProvidedResourceDetector
.detect(Duration::from_secs(0))
.get(semcov::resource::SERVICE_NAME)
.unwrap()
.to_string();
(
Config {
// use a empty resource to prevent Tr... | {
let config = if let Some(mut cfg) = self.trace_config.take() {
cfg.resource = cfg.resource.map(|r| {
let without_service_name = r
.iter()
.filter(|(k, _v)| **k != semcov::resource::SERVICE_NAME)
.ma... | conditional_block |
mod.rs | mod env;
mod model;
mod uploader;
use async_trait::async_trait;
use http::Uri;
use model::endpoint::Endpoint;
use opentelemetry::sdk::resource::ResourceDetector;
use opentelemetry::sdk::resource::SdkProvidedResourceDetector;
use opentelemetry::sdk::trace::Config;
use opentelemetry::sdk::Resource;
use opentelemetry::{
... |
}
/// Create a new Zipkin exporter pipeline builder.
pub fn new_pipeline() -> ZipkinPipelineBuilder {
ZipkinPipelineBuilder::default()
}
/// Builder for `ExporterConfig` struct.
#[derive(Debug)]
pub struct ZipkinPipelineBuilder {
service_name: Option<String>,
service_addr: Option<SocketAddr>,
collect... | {
Exporter {
local_endpoint,
uploader: uploader::Uploader::new(client, collector_endpoint),
}
} | identifier_body |
instance_metadata.rs | //! The Credentials Provider for an AWS Resource's IAM Role.
use async_trait::async_trait;
use hyper::Uri;
use std::time::Duration;
use crate::request::HttpClient;
use crate::{
parse_credentials_from_aws_service, AwsCredentials, CredentialsError, ProvideAwsCredentials,
};
const AWS_CREDENTIALS_PROVIDER_IP: &str ... | (&self) -> Result<AwsCredentials, CredentialsError> {
let role_name = get_role_name(&self.client, self.timeout, &self.metadata_ip_addr)
.await
.map_err(|err| CredentialsError {
message: format!("Could not get credentials from iam: {}", err.to_string()),
})?;
... | credentials | identifier_name |
instance_metadata.rs | //! The Credentials Provider for an AWS Resource's IAM Role.
use async_trait::async_trait;
use hyper::Uri;
use std::time::Duration;
use crate::request::HttpClient;
use crate::{
parse_credentials_from_aws_service, AwsCredentials, CredentialsError, ProvideAwsCredentials,
};
const AWS_CREDENTIALS_PROVIDER_IP: &str ... |
}
/// Gets the role name to get credentials for using the IAM Metadata Service (169.254.169.254).
async fn get_role_name(
client: &HttpClient,
timeout: Duration,
ip_addr: &str,
) -> Result<String, CredentialsError> {
let role_name_address = format!("http://{}/{}/", ip_addr, AWS_CREDENTIALS_PROVIDER_PA... | {
let role_name = get_role_name(&self.client, self.timeout, &self.metadata_ip_addr)
.await
.map_err(|err| CredentialsError {
message: format!("Could not get credentials from iam: {}", err.to_string()),
})?;
let cred_str = get_credentials_from_role(
... | identifier_body |
instance_metadata.rs | //! The Credentials Provider for an AWS Resource's IAM Role.
use async_trait::async_trait;
use hyper::Uri;
use std::time::Duration;
use crate::request::HttpClient;
use crate::{
parse_credentials_from_aws_service, AwsCredentials, CredentialsError, ProvideAwsCredentials,
};
const AWS_CREDENTIALS_PROVIDER_IP: &str ... | self.metadata_ip_addr = format!("{}:{}", ip, port);
}
}
impl Default for InstanceMetadataProvider {
fn default() -> Self {
Self::new()
}
}
#[async_trait]
impl ProvideAwsCredentials for InstanceMetadataProvider {
async fn credentials(&self) -> Result<AwsCredentials, CredentialsError> {
... | self.timeout = timeout;
}
/// Allow overriding host and port of instance metadata service.
pub fn set_ip_addr_with_port(&mut self, ip: &str, port: &str) { | random_line_split |
test_cargo_profiles.rs | use std::env;
use std::path::MAIN_SEPARATOR as SEP;
use support::{project, execs};
use support::{COMPILING, RUNNING};
use hamcrest::assert_that;
fn setup() |
test!(profile_overrides {
let mut p = project("foo");
p = p
.file("Cargo.toml", r#"
[package]
name = "test"
version = "0.0.0"
authors = []
[profile.dev]
opt-level = 1
debug = false
rpath = true
"#... | {
} | identifier_body |
test_cargo_profiles.rs | use std::env;
use std::path::MAIN_SEPARATOR as SEP;
use support::{project, execs};
use support::{COMPILING, RUNNING};
use hamcrest::assert_that;
fn | () {
}
test!(profile_overrides {
let mut p = project("foo");
p = p
.file("Cargo.toml", r#"
[package]
name = "test"
version = "0.0.0"
authors = []
[profile.dev]
opt-level = 1
debug = false
rpath = true
... | setup | identifier_name |
test_cargo_profiles.rs | use std::env;
use std::path::MAIN_SEPARATOR as SEP;
use support::{project, execs};
use support::{COMPILING, RUNNING};
use hamcrest::assert_that;
fn setup() {
}
test!(profile_overrides {
let mut p = project("foo");
p = p
.file("Cargo.toml", r#"
[package]
name = "test"
... | --emit=dep-info,link \
-L dependency={dir}{sep}target{sep}release \
-L dependency={dir}{sep}target{sep}release{sep}deps \
--extern foo={dir}{sep}target{sep}release{sep}deps{sep}\
{prefix}foo-[..]{suffix} \
--extern foo={dir}{sep}target{sep}release{sep}deps{se... | -g \
-C metadata=[..] \
-C extra-filename=-[..] \
--out-dir {dir}{sep}target{sep}release \ | random_line_split |
base.py | # -*- encoding: utf-8 -*-
"""
sleekxmpp.plugins.base
~~~~~~~~~~~~~~~~~~~~~~
This module provides XMPP functionality that
is specific to client connections.
Part of SleekXMPP: The Sleek XMPP Library
:copyright: (c) 2012 Nathanael C. Fritz
:license: MIT, see LICENSE for more details
"""
i... |
for dep in impl.dependencies:
if dep not in PLUGIN_DEPENDENTS:
PLUGIN_DEPENDENTS[dep] = set()
PLUGIN_DEPENDENTS[dep].add(name)
def load_plugin(name, module=None):
"""Find and import a plugin module so that it can be registered.
This function is called to impor... | PLUGIN_DEPENDENTS[name] = set() | conditional_block |
base.py | # -*- encoding: utf-8 -*-
"""
sleekxmpp.plugins.base
~~~~~~~~~~~~~~~~~~~~~~
This module provides XMPP functionality that
is specific to client connections.
Part of SleekXMPP: The Sleek XMPP Library
:copyright: (c) 2012 Nathanael C. Fritz
:license: MIT, see LICENSE for more details
"""
i... | (self, names=None, config=None):
"""Enable all registered plugins.
:param list names: A list of plugin names to enable. If
none are provided, all registered plugins
will be enabled.
:param dict config: A dictionary mapping plugin names to
... | enable_all | identifier_name |
base.py | # -*- encoding: utf-8 -*-
"""
sleekxmpp.plugins.base
~~~~~~~~~~~~~~~~~~~~~~
This module provides XMPP functionality that
is specific to client connections.
Part of SleekXMPP: The Sleek XMPP Library
:copyright: (c) 2012 Nathanael C. Fritz
:license: MIT, see LICENSE for more details
"""
i... |
def disable(self, name, _disabled=None):
"""Disable a plugin, including any dependent upon it.
:param string name: The name of the plugin to disable.
:param set _disabled: Private set used to track the
disabled status of plugins during
... | """Check if a plugin has been registered.
:param string name: The name of the plugin to check.
:return: boolean
"""
return name in PLUGIN_REGISTRY | identifier_body |
base.py | # -*- encoding: utf-8 -*-
"""
sleekxmpp.plugins.base
~~~~~~~~~~~~~~~~~~~~~~
This module provides XMPP functionality that
is specific to client connections.
Part of SleekXMPP: The Sleek XMPP Library
:copyright: (c) 2012 Nathanael C. Fritz
:license: MIT, see LICENSE for more details
"""
i... | """
if _disabled is None:
_disabled = set()
with self._plugin_lock:
if name not in _disabled and name in self._enabled:
_disabled.add(name)
plugin = self._plugins.get(name, None)
if plugin is None:
raise ... | disabled status of plugins during
the cascading process. | random_line_split |
font.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/// Implementation of Quartz (CoreGraphics) fonts.
extern crate core_foundation;
extern crate core_graphics;
exte... |
fn au_from_pt(pt: f64) -> Au {
Au::from_f64_px(pt_to_px(pt))
}
impl FontTable {
pub fn wrap(data: CFData) -> FontTable {
FontTable { data: data }
}
}
impl FontTableMethods for FontTable {
fn buffer(&self) -> &[u8] {
self.data.bytes()
}
}
#[derive(Debug)]
pub struct FontHandle {
... | {
pt / 72. * 96.
} | identifier_body |
font.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/// Implementation of Quartz (CoreGraphics) fonts.
extern crate core_foundation;
extern crate core_graphics;
exte... | (&self) -> String {
self.ctfont.family_name()
}
fn face_name(&self) -> String {
self.ctfont.face_name()
}
fn is_italic(&self) -> bool {
self.ctfont.symbolic_traits().is_italic()
}
fn boldness(&self) -> font_weight::T {
let normalized = self.ctfont.all_traits().... | family_name | identifier_name |
font.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/// Implementation of Quartz (CoreGraphics) fonts.
extern crate core_foundation;
extern crate core_graphics;
exte... |
fn family_name(&self) -> String {
self.ctfont.family_name()
}
fn face_name(&self) -> String {
self.ctfont.face_name()
}
fn is_italic(&self) -> bool {
self.ctfont.symbolic_traits().is_italic()
}
fn boldness(&self) -> font_weight::T {
let normalized = self.c... |
fn template(&self) -> Arc<FontTemplateData> {
self.font_data.clone()
} | random_line_split |
conf.py | # -*- coding: utf-8 -*-
#
# partpy documentation build configuration file, created by
# sphinx-quickstart on Sat Feb 16 18:56:06 2013.
#
# 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 ... | sys.path.insert(0, os.path.abspath('../'))
# -- 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 Sphin... | # documentation root, use os.path.abspath to make it absolute, like shown here. | random_line_split |
logger.js | "use strict";
var levels = require('./levels')
, util = require('util')
, events = require('events')
, DEFAULT_CATEGORY = '[default]';
var logWritesEnabled = true;
/**
* Models a logging event.
* @constructor
* @param {String} categoryName name of category
* @param {Log4js.Level} level level of message
* @param ... | );
function addLevelMethods(level) {
level = levels.toLevel(level);
var levelStrLower = level.toString().toLowerCase();
var levelMethod = levelStrLower.replace(/_([a-z])/g, function(g) { return g[1].toUpperCase(); } );
var isLevelMethod = levelMethod[0].toUpperCase() + levelMethod.slice(1);
Logger.prototyp... |
['Trace','Debug','Info','Warn','Error','Fatal', 'Mark'].forEach(
function(levelString) {
addLevelMethods(levelString);
} | random_line_split |
logger.js | "use strict";
var levels = require('./levels')
, util = require('util')
, events = require('events')
, DEFAULT_CATEGORY = '[default]';
var logWritesEnabled = true;
/**
* Models a logging event.
* @constructor
* @param {String} categoryName name of category
* @param {Log4js.Level} level level of message
* @param ... | (level) {
level = levels.toLevel(level);
var levelStrLower = level.toString().toLowerCase();
var levelMethod = levelStrLower.replace(/_([a-z])/g, function(g) { return g[1].toUpperCase(); } );
var isLevelMethod = levelMethod[0].toUpperCase() + levelMethod.slice(1);
Logger.prototype['is'+isLevelMethod+'Enable... | addLevelMethods | identifier_name |
logger.js | "use strict";
var levels = require('./levels')
, util = require('util')
, events = require('events')
, DEFAULT_CATEGORY = '[default]';
var logWritesEnabled = true;
/**
* Models a logging event.
* @constructor
* @param {String} categoryName name of category
* @param {Log4js.Level} level level of message
* @param ... |
this._log(level, args);
}
};
}
Logger.prototype._log = function(level, data) {
var loggingEvent = new LoggingEvent(this.category, level, data, this);
this.emit('log', loggingEvent);
};
/**
* Disable all log writes.
* @returns {void}
*/
function disableAllLogWrites() {
logWritesEnabled = false;
}... | {
args[i] = arguments[i];
} | conditional_block |
logger.js | "use strict";
var levels = require('./levels')
, util = require('util')
, events = require('events')
, DEFAULT_CATEGORY = '[default]';
var logWritesEnabled = true;
/**
* Models a logging event.
* @constructor
* @param {String} categoryName name of category
* @param {Log4js.Level} level level of message
* @param ... |
Logger.prototype._log = function(level, data) {
var loggingEvent = new LoggingEvent(this.category, level, data, this);
this.emit('log', loggingEvent);
};
/**
* Disable all log writes.
* @returns {void}
*/
function disableAllLogWrites() {
logWritesEnabled = false;
}
/**
* Enable log writes.
* @returns {vo... | {
level = levels.toLevel(level);
var levelStrLower = level.toString().toLowerCase();
var levelMethod = levelStrLower.replace(/_([a-z])/g, function(g) { return g[1].toUpperCase(); } );
var isLevelMethod = levelMethod[0].toUpperCase() + levelMethod.slice(1);
Logger.prototype['is'+isLevelMethod+'Enabled'] = fu... | identifier_body |
merge_java_srcs.py | #!/usr/bin/env python
# Copyright (c) 2014 Intel Corporation. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import optparse
import os
import re
import sys
import shutil
def DoCopy(path, target_path):
if os.path.isfile(path):
package ... |
if __name__ == '__main__':
sys.exit(main()) | random_line_split | |
merge_java_srcs.py | #!/usr/bin/env python
# Copyright (c) 2014 Intel Corporation. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import optparse
import os
import re
import sys
import shutil
def | (path, target_path):
if os.path.isfile(path):
package = ''
package_re = re.compile(
'^package (?P<package>([a-zA-Z0-9_]+.)*[a-zA-Z0-9_]+);$')
for line in open(path).readlines():
match = package_re.match(line)
if match:
package = match.group('package')
break
sub_path... | DoCopy | identifier_name |
merge_java_srcs.py | #!/usr/bin/env python
# Copyright (c) 2014 Intel Corporation. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import optparse
import os
import re
import sys
import shutil
def DoCopy(path, target_path):
if os.path.isfile(path):
package ... |
if invalid_lines:
continue
elif not f.endswith('.java'):
continue
shutil.copy(fpath, target_dirpath)
def main():
parser = optparse.OptionParser()
info = ('The java source dirs to merge.')
parser.add_option('--dirs', help=info)
info = ('The target to place all the sources... | invalid_lines.append(line) | conditional_block |
merge_java_srcs.py | #!/usr/bin/env python
# Copyright (c) 2014 Intel Corporation. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import optparse
import os
import re
import sys
import shutil
def DoCopy(path, target_path):
if os.path.isfile(path):
package ... |
if __name__ == '__main__':
sys.exit(main())
| parser = optparse.OptionParser()
info = ('The java source dirs to merge.')
parser.add_option('--dirs', help=info)
info = ('The target to place all the sources.')
parser.add_option('--target-path', help=info)
options, _ = parser.parse_args()
if os.path.isdir(options.target_path):
shutil.rmtree(options.t... | identifier_body |
shifter.js | /*
* Copyright (c) 2013, Yahoo! Inc. All rights reserved.
* Copyrights licensed under the New BSD License.
* See the accompanying LICENSE file for terms.
*/
/*jslint node: true, nomen: true */
/**
The `express-yui.shifter` extension exposes a set of utilities to build yui modules
from *.js or build.json files.
... |
next(); // kick off the queue process
},
/**
Analyze a build.json file to extract all the important metadata associated with it.
@method _checkBuildFile
@protected
@param {string} file The filesystem path for the build.json file to be analyzed
@return {object} The parsed and aug... | {
var file = queue.shift(),
opts = utils.extend({}, options.opts);
if (file) {
debug('shifting ' + file);
if (options.symlink && self._isLinked(file, options.buildDir)) {
next();
return;
}... | identifier_body |
shifter.js | /*
* Copyright (c) 2013, Yahoo! Inc. All rights reserved.
* Copyrights licensed under the New BSD License.
* See the accompanying LICENSE file for terms.
*/
/*jslint node: true, nomen: true */
/**
The `express-yui.shifter` extension exposes a set of utilities to build yui modules
from *.js or build.json files.
... | self._clearCached(file, options.buildDir);
}
callback(new Error(file + ": shifter compiler error: " + err));
return;
}
next(); // next item in queue to be processed
... | // invalidating the cache entry | random_line_split |
shifter.js | /*
* Copyright (c) 2013, Yahoo! Inc. All rights reserved.
* Copyrights licensed under the New BSD License.
* See the accompanying LICENSE file for terms.
*/
/*jslint node: true, nomen: true */
/**
The `express-yui.shifter` extension exposes a set of utilities to build yui modules
from *.js or build.json files.
... |
}
}
}
}
}
return mod;
},
/**
Analyze a javascript file, if it is a yui module, it extracts all the important metadata
associted with it.
@method _checkYUIModule
@protected
@param {string} file The file... | {
entry[j].condition.test = libpath.join(metas, entry[j].condition.test);
} | conditional_block |
shifter.js | /*
* Copyright (c) 2013, Yahoo! Inc. All rights reserved.
* Copyrights licensed under the New BSD License.
* See the accompanying LICENSE file for terms.
*/
/*jslint node: true, nomen: true */
/**
The `express-yui.shifter` extension exposes a set of utilities to build yui modules
from *.js or build.json files.
... | () {
var file = queue.shift(),
opts = utils.extend({}, options.opts);
if (file) {
debug('shifting ' + file);
if (options.symlink && self._isLinked(file, options.buildDir)) {
next();
return;
... | next | identifier_name |
profile.rs | use crate::{Error, Result};
use chrono::{DateTime, Utc};
use colored::Colorize;
use serde::Deserialize;
use std::fs::File;
use std::io::{self, Read};
use std::path::{Path, PathBuf};
use std::time::SystemTime;
/// Represents a file with a provisioning profile info.
#[derive(Debug, Clone)]
pub struct Profile {
pub p... | () {
let mut profile = Info::empty();
profile.app_identifier = "12345ABCDE.com.exmaple.app".to_owned();
expect!(profile.bundle_id()).to(be_some().value("com.exmaple.app"));
}
#[test]
fn incorrect_bundle_id() {
let mut profile = Info::empty();
profile.app_identifier =... | correct_bundle_id | identifier_name |
profile.rs | use crate::{Error, Result};
use chrono::{DateTime, Utc};
use colored::Colorize;
use serde::Deserialize;
use std::fs::File;
use std::io::{self, Read};
use std::path::{Path, PathBuf};
use std::time::SystemTime;
/// Represents a file with a provisioning profile info.
#[derive(Debug, Clone)]
pub struct Profile {
pub p... | fn wildcard_bundle_id() {
let mut profile = Info::empty();
profile.app_identifier = "12345ABCDE.*".to_owned();
expect!(profile.bundle_id()).to(be_some().value("*"));
}
} | #[test] | random_line_split |
profile.rs | use crate::{Error, Result};
use chrono::{DateTime, Utc};
use colored::Colorize;
use serde::Deserialize;
use std::fs::File;
use std::io::{self, Read};
use std::path::{Path, PathBuf};
use std::time::SystemTime;
/// Represents a file with a provisioning profile info.
#[derive(Debug, Clone)]
pub struct Profile {
pub p... |
}
false
}
/// Returns a bundle id of a profile.
pub fn bundle_id(&self) -> Option<&str> {
self.app_identifier
.find(|ch| ch == '.')
.map(|i| &self.app_identifier[(i + 1)..])
}
/// Returns profile in a text form.
pub fn description(&self, oneline... | {
return true;
} | conditional_block |
navigator.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::NavigatorBinding;
use dom::bindings::js::{JSRef, Temporary};
use dom::bindin... | (&self) -> bool {
false
}
fn AppName(&self) -> DOMString {
"Netscape".to_string() // Like Gecko/Webkit
}
fn AppCodeName(&self) -> DOMString {
"Mozilla".to_string()
}
fn Platform(&self) -> DOMString {
"".to_string()
}
}
impl Reflectable for Navigator {
... | TaintEnabled | identifier_name |
navigator.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::NavigatorBinding;
use dom::bindings::js::{JSRef, Temporary};
use dom::bindin... |
fn Platform(&self) -> DOMString {
"".to_string()
}
}
impl Reflectable for Navigator {
fn reflector<'a>(&'a self) -> &'a Reflector {
&self.reflector_
}
} | "Mozilla".to_string()
} | random_line_split |
chrome_cache.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Tests for the Chrome Cache files parser."""
import unittest
from plaso.parsers import chrome_cache
from tests.parsers import test_lib
class ChromeCacheParserTest(test_lib.ParserTestCase):
"""Tests for the Chrome Cache files parser."""
def testParse(self):
... | 'recovery_warning')
self.assertEqual(number_of_warnings, 0)
events = list(storage_writer.GetEvents())
expected_event_values = {
'data_type': 'chrome:cache:entry',
'date_time': '2014-04-30 16:44:36.226091',
'original_url': (
'https://s.ytimg.com/yts/imgbin/player... | 'extraction_warning')
self.assertEqual(number_of_warnings, 0)
number_of_warnings = storage_writer.GetNumberOfAttributeContainers( | random_line_split |
chrome_cache.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Tests for the Chrome Cache files parser."""
import unittest
from plaso.parsers import chrome_cache
from tests.parsers import test_lib
class ChromeCacheParserTest(test_lib.ParserTestCase):
"""Tests for the Chrome Cache files parser."""
def testParse(self):
|
if __name__ == '__main__':
unittest.main()
| """Tests the Parse function."""
parser = chrome_cache.ChromeCacheParser()
storage_writer = self._ParseFile(['chrome_cache', 'index'], parser)
number_of_events = storage_writer.GetNumberOfAttributeContainers('event')
self.assertEqual(number_of_events, 217)
number_of_warnings = storage_writer.GetNum... | identifier_body |
chrome_cache.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Tests for the Chrome Cache files parser."""
import unittest
from plaso.parsers import chrome_cache
from tests.parsers import test_lib
class ChromeCacheParserTest(test_lib.ParserTestCase):
"""Tests for the Chrome Cache files parser."""
def testParse(self):
... | unittest.main() | conditional_block | |
chrome_cache.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Tests for the Chrome Cache files parser."""
import unittest
from plaso.parsers import chrome_cache
from tests.parsers import test_lib
class ChromeCacheParserTest(test_lib.ParserTestCase):
"""Tests for the Chrome Cache files parser."""
def | (self):
"""Tests the Parse function."""
parser = chrome_cache.ChromeCacheParser()
storage_writer = self._ParseFile(['chrome_cache', 'index'], parser)
number_of_events = storage_writer.GetNumberOfAttributeContainers('event')
self.assertEqual(number_of_events, 217)
number_of_warnings = storage_w... | testParse | identifier_name |
issue-352.ts | import "reflect-metadata";
import {closeTestingConnections, createTestingConnections, reloadTestingDatabases} from "../../utils/test-utils";
import {Connection} from "../../../src/connection/Connection";
import {expect} from "chai";
import {Post} from "./entity/Post";
import {MssqlParameter} from "../../../src/driver/s... |
await connection.manager.save(posts);
const loadedPost = await connection.manager
.createQueryBuilder(Post, "post")
.where("post.id = :id", { id: new MssqlParameter(1.234567789, "float") })
.getOne();
expect(loadedPost).to.exist;
expect(loadedPost!.... | {
const post = new Post();
post.id = i + 0.234567789;
post.title = "hello post";
posts.push(post);
} | conditional_block |
issue-352.ts | import "reflect-metadata";
import {closeTestingConnections, createTestingConnections, reloadTestingDatabases} from "../../utils/test-utils";
import {Connection} from "../../../src/connection/Connection";
import {expect} from "chai";
import {Post} from "./entity/Post";
import {MssqlParameter} from "../../../src/driver/s... | .getOne();
expect(loadedPost).to.exist;
expect(loadedPost!.id).to.be.equal(1.234567789);
})));
}); | const loadedPost = await connection.manager
.createQueryBuilder(Post, "post")
.where("post.id = :id", { id: new MssqlParameter(1.234567789, "float") }) | random_line_split |
listeners.rs | // Copyright 2021 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under The General Public License (GPL), version 3.
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTI... |
SectionInfoMsg::SectionInfoUpdate(update) => {
let correlation_id = update.correlation_id;
error!("MessageId {:?} was interrupted due to infrastructure updates. This will most likely need to be sent again. Update was : {:?}", correlation_id, update);
if let S... | {
trace!("GetSectionResponse::Redirect, reboostrapping with provided peers");
// Disconnect from peer that sent us the redirect, connect to the new elders provided and
// request the section info again.
self.disconnect_from_peers(vec![src]).await?;
... | conditional_block |
listeners.rs | // Copyright 2021 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under The General Public License (GPL), version 3.
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTI... | ClientMsg::Process(msg) => self.handle_client_msg(msg, src).await,
ClientMsg::ProcessingError(error) => {
warn!("Processing error received. {:?}", error);
// TODO: Handle lazy message errors
}... | error!("Error handling network info message: {:?}", error);
}
}
MessageType::Client { msg, .. } => {
match msg { | random_line_split |
listeners.rs | // Copyright 2021 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under The General Public License (GPL), version 3.
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTI... |
}
| {
debug!(
"===> ClientMsg with id {:?} received from {:?}",
msg.id(),
src
);
let queries = self.pending_queries.clone();
let transfers = self.pending_transfers.clone();
let error_sender = self.incoming_err_sender.clone();
let _ = tokio:... | identifier_body |
listeners.rs | // Copyright 2021 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under The General Public License (GPL), version 3.
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTI... | (&self, msg_id: &MessageId) -> Result<(), Error> {
let pending_transfers = self.pending_transfers.clone();
let mut listeners = pending_transfers.write().await;
debug!("Pending transfers at this point: {:?}", listeners);
let _ = listeners
.remove(msg_id)
.ok_or(Err... | remove_pending_transfer_sender | identifier_name |
viewletService.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | return this.extensionViewletsLoaded.then(() => {
if (this.viewletRegistry.getViewlet(id)) {
return this.sidebarPart.openViewlet(id, focus);
}
// Fallback to default viewlet if extension viewlet is still not found (e.g. uninstalled)
return this.sidebarPart.openViewlet(this.getDefaultViewletId(), focus... | }
// Extension viewlets need to be loaded first which can take time | random_line_split |
viewletService.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
// Fallback to default viewlet if extension viewlet is still not found (e.g. uninstalled)
return this.sidebarPart.openViewlet(this.getDefaultViewletId(), focus);
});
}
public getActiveViewlet(): IViewlet {
return this.sidebarPart.getActiveViewlet();
}
public getViewlets(): ViewletDescriptor[] {
cons... | {
return this.sidebarPart.openViewlet(id, focus);
} | conditional_block |
viewletService.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
public getDefaultViewletId(): string {
return this.viewletRegistry.getDefaultViewletId();
}
public getViewlet(id: string): ViewletDescriptor {
return this.getViewlets().filter(viewlet => viewlet.id === id)[0];
}
} | {
return this.viewletRegistry.getViewlets()
.filter(viewlet => !viewlet.extensionId)
.sort((v1, v2) => v1.order - v2.order);
} | identifier_body |
viewletService.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | (id: string, focus?: boolean): TPromise<IViewlet> {
// Built in viewlets do not need to wait for extensions to be loaded
const builtInViewletIds = this.getBuiltInViewlets().map(v => v.id);
const isBuiltInViewlet = builtInViewletIds.indexOf(id) !== -1;
if (isBuiltInViewlet) {
return this.sidebarPart.openView... | openViewlet | identifier_name |
automaton.py | # This file is part of Scapy
# Copyright (C) 2007, 2008, 2009 Arnaud Ebalard
# 2015, 2016, 2017 Maxence Tury
# This program is published under a GPLv2 license
"""
The _TLSAutomaton class provides methods common to both TLS client and server.
"""
import struct
from scapy.automaton import Automaton
from ... |
def raise_on_packet(self, pkt_cls, state, get_next_msg=True):
"""
If the next message to be processed has type 'pkt_cls', raise 'state'.
If there is no message waiting to be processed, we try to get one with
the default 'get_next_msg' parameters.
"""
# Maybe we alre... | p = p.payload
if self.cur_session.tls_version is None or \
self.cur_session.tls_version < 0x0304:
self.buffer_in += p.msg
else:
self.buffer_in += p.inner.msg | conditional_block |
automaton.py | # This file is part of Scapy
# Copyright (C) 2007, 2008, 2009 Arnaud Ebalard
# 2015, 2016, 2017 Maxence Tury
# This program is published under a GPLv2 license
"""
The _TLSAutomaton class provides methods common to both TLS client and server.
"""
import struct
from scapy.automaton import Automaton
from ... | # Retry following TLS scheme. This will cause failure
# for SSLv2 packets with length 0x1{4-7}03.
grablen = 5
else:
# Extract the SSLv2 length.
is_sslv2_msg = True
still_getting_len = ... | still_getting_len = False
elif grablen == 2 and len(self.remain_in) >= 2:
byte0 = struct.unpack("B", self.remain_in[:1])[0]
byte1 = struct.unpack("B", self.remain_in[1:2])[0]
if (byte0 in _tls_type) and (byte1 == 3): | random_line_split |
automaton.py | # This file is part of Scapy
# Copyright (C) 2007, 2008, 2009 Arnaud Ebalard
# 2015, 2016, 2017 Maxence Tury
# This program is published under a GPLv2 license
"""
The _TLSAutomaton class provides methods common to both TLS client and server.
"""
import struct
from scapy.automaton import Automaton
from ... | """
SSLv3 and TLS 1.0-1.2 typically need a 2-RTT handshake:
Client Server
| --------->>> | C1 - ClientHello
| <<<--------- | S1 - ServerHello
| <<<--------- | S1 - Certificate
| <<<--------- | S1 - ServerKeyExchange
| <<<--------- | S1 - ServerHelloDone
... | identifier_body | |
automaton.py | # This file is part of Scapy
# Copyright (C) 2007, 2008, 2009 Arnaud Ebalard
# 2015, 2016, 2017 Maxence Tury
# This program is published under a GPLv2 license
"""
The _TLSAutomaton class provides methods common to both TLS client and server.
"""
import struct
from scapy.automaton import Automaton
from ... | (self, socket_timeout=2, retry=2):
"""
The purpose of the function is to make next message(s) available in
self.buffer_in. If the list is not empty, nothing is done. If not, in
order to fill it, the function uses the data already available in
self.remain_in from a previous call a... | get_next_msg | identifier_name |
iron-doc-nav.d.ts | /**
* DO NOT EDIT
*
* This file was automatically generated by
* https://github.com/Polymer/tools/tree/master/packages/gen-typescript-declarations
* |
import {dom, flush} from '@polymer/polymer/lib/legacy/polymer.dom.js';
import {html} from '@polymer/polymer/lib/utils/html-tag.js';
import {LegacyElementMixin} from '@polymer/polymer/lib/legacy/legacy-element-mixin.js';
interface IronDocNavElement extends LegacyElementMixin, HTMLElement {
descriptor: object|null|... | * To modify these typings, edit the source file(s):
* iron-doc-nav.js
*/
import {Polymer} from '@polymer/polymer/lib/legacy/polymer-fn.js'; | random_line_split |
issue-2502.rs | // 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 |
struct font<'a> {
fontbuf: &'a ~[u8],
}
impl<'a> font<'a> {
pub fn buf(&self) -> &'a ~[u8] {
self.fontbuf
}
}
fn font<'r>(fontbuf: &'r ~[u8]) -> font<'r> {
font {
fontbuf: fontbuf
}
}
pub fn main() { } | // <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. | random_line_split |
issue-2502.rs | // 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 ... | <'a> {
fontbuf: &'a ~[u8],
}
impl<'a> font<'a> {
pub fn buf(&self) -> &'a ~[u8] {
self.fontbuf
}
}
fn font<'r>(fontbuf: &'r ~[u8]) -> font<'r> {
font {
fontbuf: fontbuf
}
}
pub fn main() { }
| font | identifier_name |
issue-2502.rs | // 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 ... |
pub fn main() { }
| {
font {
fontbuf: fontbuf
}
} | identifier_body |
archive.py | # coding=utf-8
"""archive.py - Archive handling (extract/create) for Comix."""
from __future__ import absolute_import
import cStringIO
import os
import re
import sys
import tarfile
import threading
import zipfile
import gtk
try:
from py7zlib import Archive7z
except ImportError:
Archive7z = None # ignore it.... |
if magic2 == 'BOOKMOBI':
return MOBI
except Exception:
print('! Error while reading {}'.format(path))
return None
def get_name(archive_type):
"""Return a text representation of an archive type."""
return {ZIP: _('ZIP archive'),
TAR: _('Tar archive'),
... | return SEVENZIP | conditional_block |
archive.py | # coding=utf-8
"""archive.py - Archive handling (extract/create) for Comix."""
from __future__ import absolute_import
import cStringIO
import os
import re
import sys
import tarfile
import threading
import zipfile
import gtk
try:
from py7zlib import Archive7z
except ImportError:
Archive7z = None # ignore it.... |
def archive_mime_type(path):
"""Return the archive type of <path> or None for non-archives."""
try:
if os.path.isfile(path):
if not os.access(path, os.R_OK):
return None
if zipfile.is_zipfile(path):
return ZIP
fd = open(path, 'rb')
... | """Packer is a threaded class for packing files into ZIP archives.
It would be straight-forward to add support for more archive types,
but basically all other types are less well fitted for this particular
task than ZIP archives are (yes, really).
"""
def __init__(self, image_files, other_files, a... | identifier_body |
archive.py | # coding=utf-8
"""archive.py - Archive handling (extract/create) for Comix."""
from __future__ import absolute_import
import cStringIO
import os
import re
import sys
import tarfile
import threading
import zipfile | except ImportError:
Archive7z = None # ignore it.
from src import mobiunpack
from src import process
from src.image import get_supported_format_extensions_preg
ZIP, RAR, TAR, GZIP, BZIP2, SEVENZIP, MOBI = range(7)
_rar_exec = None
_7z_exec = None
class Extractor(object):
"""Extractor is a threaded class f... |
import gtk
try:
from py7zlib import Archive7z | random_line_split |
archive.py | # coding=utf-8
"""archive.py - Archive handling (extract/create) for Comix."""
from __future__ import absolute_import
import cStringIO
import os
import re
import sys
import tarfile
import threading
import zipfile
import gtk
try:
from py7zlib import Archive7z
except ImportError:
Archive7z = None # ignore it.... | ():
"""Return the name of the RAR file extractor executable, or None if
no such executable is found.
"""
for command in ('unrar', 'rar'):
if process.Process([command]).spawn() is not None:
return command
return None
def _get_7z_exec():
"""Return the name of the RAR file ext... | _get_rar_exec | identifier_name |
winprocess.py | """
Windows Process Control
winprocess.run launches a child process and returns the exit code.
Optionally, it can:
redirect stdin, stdout & stderr to files
run the command as another user
limit the process's running time
control the process window (location, size, window state, desktop)
Works on Windows NT, 20... | (self, mSec=None):
"""
Wait for process to finish or for specified number of
milliseconds to elapse.
"""
if mSec is None:
mSec = win32event.INFINITE
return win32event.WaitForSingleObject(self.hProcess, mSec)
def kill(self, gracePeriod=5000):
"""
... | wait | identifier_name |
winprocess.py | """
Windows Process Control
winprocess.run launches a child process and returns the exit code.
Optionally, it can:
redirect stdin, stdout & stderr to files
run the command as another user
limit the process's running time
control the process window (location, size, window state, desktop)
Works on Windows NT, 20... |
if hStdout is None:
si.hStdOutput = win32api.GetStdHandle(win32api.STD_OUTPUT_HANDLE)
else:
si.hStdOutput = hStdout
if hStderr is None:
si.hStdError = win32api.GetStdHandle(win32api.STD_ERROR_HANDLE)
else:
si.hStdError = hStderr
si... | si.hStdInput = hStdin | conditional_block |
winprocess.py | """
Windows Process Control
winprocess.run launches a child process and returns the exit code.
Optionally, it can:
redirect stdin, stdout & stderr to files
run the command as another user
limit the process's running time
control the process window (location, size, window state, desktop)
Works on Windows NT, 20... | """
Wait for process to finish or for specified number of
milliseconds to elapse.
"""
if mSec is None:
mSec = win32event.INFINITE
return win32event.WaitForSingleObject(self.hProcess, mSec)
def kill(self, gracePeriod=5000):
"""
Kill process... |
def wait(self, mSec=None): | random_line_split |
winprocess.py | """
Windows Process Control
winprocess.run launches a child process and returns the exit code.
Optionally, it can:
redirect stdin, stdout & stderr to files
run the command as another user
limit the process's running time
control the process window (location, size, window state, desktop)
Works on Windows NT, 20... |
def run(cmd, mSec=None, stdin=None, stdout=None, stderr=None, **kw):
"""
Run cmd as a child process and return exit code.
mSec: terminate cmd after specified number of milliseconds
stdin, stdout, stderr:
file objects for child I/O (use hStdin etc. to attach
handles instead o... | """
A Windows process.
"""
def __init__(self, cmd, login=None,
hStdin=None, hStdout=None, hStderr=None,
show=1, xy=None, xySize=None,
desktop=None):
"""
Create a Windows process.
cmd: command to run
login: run as user ... | identifier_body |
aws.py | __metaclass__ = type
import os
from ..util import (
ApplicationError,
display,
is_shippable,
ConfigParser,
)
from . import (
CloudProvider,
CloudEnvironment,
CloudEnvironmentConfig,
)
from ..core_ci import (
AnsibleCoreCI,
)
class AwsCloudProvider(CloudProvider):
"""AWS cloud p... | """AWS plugin for integration tests."""
from __future__ import (absolute_import, division, print_function) | random_line_split | |
aws.py | """AWS plugin for integration tests."""
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
from ..util import (
ApplicationError,
display,
is_shippable,
ConfigParser,
)
from . import (
CloudProvider,
CloudEnvironment,
CloudEnvironmentConfig,
... | (self):
"""
:rtype: AnsibleCoreCI
"""
return AnsibleCoreCI(self.args, 'aws', 'sts', persist=False, stage=self.args.remote_stage, provider=self.args.remote_provider)
class AwsCloudEnvironment(CloudEnvironment):
"""AWS cloud environment plugin. Updates integration test environment af... | _create_ansible_core_ci | identifier_name |
aws.py | """AWS plugin for integration tests."""
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
from ..util import (
ApplicationError,
display,
is_shippable,
ConfigParser,
)
from . import (
CloudProvider,
CloudEnvironment,
CloudEnvironmentConfig,
... |
class AwsCloudEnvironment(CloudEnvironment):
"""AWS cloud environment plugin. Updates integration test environment after delegation."""
def get_environment_config(self):
"""
:rtype: CloudEnvironmentConfig
"""
parser = ConfigParser()
parser.read(self.config_path)
... | """
:rtype: AnsibleCoreCI
"""
return AnsibleCoreCI(self.args, 'aws', 'sts', persist=False, stage=self.args.remote_stage, provider=self.args.remote_provider) | identifier_body |
aws.py | """AWS plugin for integration tests."""
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
from ..util import (
ApplicationError,
display,
is_shippable,
ConfigParser,
)
from . import (
CloudProvider,
CloudEnvironment,
CloudEnvironmentConfig,
... |
self._write_config(config)
def _create_ansible_core_ci(self):
"""
:rtype: AnsibleCoreCI
"""
return AnsibleCoreCI(self.args, 'aws', 'sts', persist=False, stage=self.args.remote_stage, provider=self.args.remote_provider)
class AwsCloudEnvironment(CloudEnvironment):
"""... | credentials = response['aws']['credentials']
values = dict(
ACCESS_KEY=credentials['access_key'],
SECRET_KEY=credentials['secret_key'],
SECURITY_TOKEN=credentials['session_token'],
REGION='us-east-1',
)
display.sensiti... | conditional_block |
jinja_context.py | '''
Created on Jan 16, 2014
@author: sean
'''
from __future__ import absolute_import, division, print_function
import json
import os
from conda.compat import PY3
from .environ import get_dict as get_environ
_setuptools_data = None
def load_setuptools(setup_file='setup.py'):
global _setuptools_data
if _set... | (**kw):
_setuptools_data.update(kw)
import setuptools
#Add current directory to path
import sys
sys.path.append('.')
#Patch setuptools
setuptools_setup = setuptools.setup
setuptools.setup = setup
exec(open(setup_file).read())
setuptoo... | setup | identifier_name |
jinja_context.py | '''
Created on Jan 16, 2014
@author: sean
'''
from __future__ import absolute_import, division, print_function
import json
import os
from conda.compat import PY3
from .environ import get_dict as get_environ
_setuptools_data = None
def load_setuptools(setup_file='setup.py'): | _setuptools_data.update(kw)
import setuptools
#Add current directory to path
import sys
sys.path.append('.')
#Patch setuptools
setuptools_setup = setuptools.setup
setuptools.setup = setup
exec(open(setup_file).read())
setuptools.setup... | global _setuptools_data
if _setuptools_data is None:
_setuptools_data = {}
def setup(**kw): | random_line_split |
jinja_context.py | '''
Created on Jan 16, 2014
@author: sean
'''
from __future__ import absolute_import, division, print_function
import json
import os
from conda.compat import PY3
from .environ import get_dict as get_environ
_setuptools_data = None
def load_setuptools(setup_file='setup.py'):
global _setuptools_data
if _set... |
return _setuptools_data
def load_npm():
# json module expects bytes in Python 2 and str in Python 3.
mode_dict = {'mode': 'r', 'encoding': 'utf-8'} if PY3 else {'mode': 'rb'}
with open('package.json', **mode_dict) as pkg:
return json.load(pkg)
def context_processor():
ctx = get_environ()
... | _setuptools_data = {}
def setup(**kw):
_setuptools_data.update(kw)
import setuptools
#Add current directory to path
import sys
sys.path.append('.')
#Patch setuptools
setuptools_setup = setuptools.setup
setuptools.setup = setup
exec(op... | conditional_block |
jinja_context.py | '''
Created on Jan 16, 2014
@author: sean
'''
from __future__ import absolute_import, division, print_function
import json
import os
from conda.compat import PY3
from .environ import get_dict as get_environ
_setuptools_data = None
def load_setuptools(setup_file='setup.py'):
global _setuptools_data
if _set... |
import setuptools
#Add current directory to path
import sys
sys.path.append('.')
#Patch setuptools
setuptools_setup = setuptools.setup
setuptools.setup = setup
exec(open(setup_file).read())
setuptools.setup = setuptools_setup
del sys.pat... | _setuptools_data.update(kw) | identifier_body |
ipdl-analyze.rs | use std::env;
use std::path::Path;
use std::path::PathBuf;
use std::fs::File;
use std::io::Write;
extern crate tools;
extern crate ipdl_parser;
extern crate getopts;
use getopts::Options;
use tools::file_format::analysis::{read_analysis, read_target, WithLocation, AnalysisTarget, AnalysisKind};
use ipdl_parser::par... | () -> Options {
let mut opts = Options::new();
opts.optmulti("I", "include",
"Additional directory to search for included protocol specifications",
"DIR");
opts.reqopt("d", "outheaders-dir",
"Directory into which C++ headers analysis data is location.",
... | get_options_parser | identifier_name |
ipdl-analyze.rs | use std::env;
use std::path::Path;
use std::path::PathBuf;
use std::fs::File;
use std::io::Write;
extern crate tools;
extern crate ipdl_parser;
extern crate getopts;
use getopts::Options;
use tools::file_format::analysis::{read_analysis, read_target, WithLocation, AnalysisTarget, AnalysisKind};
use ipdl_parser::par... |
fn mangle_nested_name(ns: &[String], protocol: &str, name: &str) -> String {
format!("_ZN{}{}{}E",
ns.iter().map(|id| mangle_simple(&id)).collect::<Vec<_>>().join(""),
mangle_simple(protocol),
mangle_simple(name))
}
fn find_analysis<'a>(analysis: &'a TargetAnalysis, mangled: &... | {
format!("{}{}", s.len(), s)
} | identifier_body |
ipdl-analyze.rs | use std::env;
use std::path::Path;
use std::path::PathBuf;
use std::fs::File;
use std::io::Write;
extern crate tools;
extern crate ipdl_parser;
extern crate getopts;
use getopts::Options;
use tools::file_format::analysis::{read_analysis, read_target, WithLocation, AnalysisTarget, AnalysisKind};
use ipdl_parser::par... | ;
let ctor_suffix = if is_ctor { "Constructor" } else { "" };
let mangled = mangle_nested_name(&protocol.namespaces,
&format!("{}{}", protocol.name.id, send_side),
&format!("{}{}{}", send_prefix, message.name.id, ctor_suffix));
if l... | { "Recv" } | conditional_block |
ipdl-analyze.rs | use std::env;
use std::path::Path;
use std::path::PathBuf;
use std::fs::File;
use std::io::Write;
extern crate tools;
extern crate ipdl_parser;
extern crate getopts;
use getopts::Options;
use tools::file_format::analysis::{read_analysis, read_target, WithLocation, AnalysisTarget, AnalysisKind};
use ipdl_parser::par... | let base_path = Path::new(&base_dir);
let analysis_path = Path::new(&analysis_dir);
let mut file_names = Vec::new();
for f in matches.free {
file_names.push(PathBuf::from(f));
}
let maybe_tus = parser::parse(&include_dirs, file_names);
if maybe_tus.is_none() {
println!("Sp... | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.