file_name large_stringlengths 4 140 | prefix large_stringlengths 0 12.1k | suffix large_stringlengths 0 12k | middle large_stringlengths 0 7.51k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
max_key.py | # Copyright 2010-present MongoDB, Inc.
#
# 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 wri... |
def __gt__(self, other: Any) -> bool:
return not isinstance(other, MaxKey)
def __repr__(self):
return "MaxKey()"
| return True | identifier_body |
max_key.py | # Copyright 2010-present MongoDB, Inc.
#
# 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 wri... | (self, state: Any) -> None:
pass
def __eq__(self, other: Any) -> bool:
return isinstance(other, MaxKey)
def __hash__(self) -> int:
return hash(self._type_marker)
def __ne__(self, other: Any) -> bool:
return not self == other
def __le__(self, other: Any) -> bool:
... | __setstate__ | identifier_name |
max_key.py | # Copyright 2010-present MongoDB, Inc.
#
# 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 wri... | return "MaxKey()" | random_line_split | |
question-base.ts | import { EventEmitter } from '@angular/core';
import { slugify } from '../utils';
import { BaseConditional } from '../conditionals/condititional-base';
import { BaseCountCondition } from '../count.conditions/cconditions.base';
export class QuestionBase<T> {
defaultValue: T;
id: number;
_key: string;
n... |
}
| {
let obj = {};
if(this.id > 0) {
obj[ 'id' ] = this.id;
}
obj['name'] = this.name;
obj['description'] = this.description;
obj['order'] = this.order;
obj['type'] = this.controlType;
obj['defaultValue'] = this.defaultValue;
obj['hideCond... | identifier_body |
question-base.ts | import { EventEmitter } from '@angular/core';
import { slugify } from '../utils';
import { BaseConditional } from '../conditionals/condititional-base';
import { BaseCountCondition } from '../count.conditions/cconditions.base';
export class QuestionBase<T> {
defaultValue: T;
id: number;
_key: string;
n... | }
get max_point_sum() {
return this._countConditions
.reduce((prev, curr) => prev + curr.point, 0);
}
calc_point_sum(answer) {
return this._countConditions
.filter(t => t.isValid(answer))
.reduce((prev, curr) => prev + curr.point, 0);
}
isHi... | set countConditions(conditions: BaseCountCondition[]) {
this._countConditions = conditions;
this.countConditions_changes.emit(conditions); | random_line_split |
question-base.ts | import { EventEmitter } from '@angular/core';
import { slugify } from '../utils';
import { BaseConditional } from '../conditionals/condititional-base';
import { BaseCountCondition } from '../count.conditions/cconditions.base';
export class QuestionBase<T> {
defaultValue: T;
id: number;
_key: string;
n... |
obj['name'] = this.name;
obj['description'] = this.description;
obj['order'] = this.order;
obj['type'] = this.controlType;
obj['defaultValue'] = this.defaultValue;
obj['hideConditions'] = this._hideConditions.map(t => t.toPlainObject(questions));
obj['countCondit... | {
obj[ 'id' ] = this.id;
} | conditional_block |
question-base.ts | import { EventEmitter } from '@angular/core';
import { slugify } from '../utils';
import { BaseConditional } from '../conditionals/condititional-base';
import { BaseCountCondition } from '../count.conditions/cconditions.base';
export class QuestionBase<T> {
defaultValue: T;
id: number;
_key: string;
n... | (options: {
defaultValue?: T,
id?: number,
key?: string,
name?: string,
description?: string,
order?: number,
controlType?: string,
hideconditions?: BaseConditional[]
} = {}) {
this.id = (options.id || options.id > 0) ? options.id : -1;
... | constructor | identifier_name |
browser_block_autoplay_media_pausedAfterPlay.js | const PAGE_SHOULD_PLAY = "https://example.com/browser/toolkit/content/tests/browser/file_blockMedia_shouldPlay.html";
const PAGE_SHOULD_NOT_PLAY = "https://example.com/browser/toolkit/content/tests/browser/file_blockMedia_shouldNotPlay.html";
var SuspendedType = {
NONE_SUSPENDED : 0,
SUSPENDED_PAUSE ... | (suspendedType) {
var audio = content.document.getElementById("testAudio");
if (!audio) {
ok(false, "Can't get the audio element!");
}
is(audio.computedSuspended, suspendedType,
"The suspeded state of audio is correct.");
}
function check_audio_pause_state(expectPause) {
var audio = content.documen... | check_audio_suspended | identifier_name |
browser_block_autoplay_media_pausedAfterPlay.js | const PAGE_SHOULD_PLAY = "https://example.com/browser/toolkit/content/tests/browser/file_blockMedia_shouldPlay.html";
const PAGE_SHOULD_NOT_PLAY = "https://example.com/browser/toolkit/content/tests/browser/file_blockMedia_shouldNotPlay.html";
var SuspendedType = {
NONE_SUSPENDED : 0,
SUSPENDED_PAUSE ... |
add_task(function* setup_test_preference() {
yield SpecialPowers.pushPrefEnv({"set": [
["media.useAudioChannelService.testing", true],
["media.block-autoplay-until-in-foreground", true]
]});
});
add_task(function* block_autoplay_media() {
info("- open new background tab1, and check tab1's media suspend... | {
var audio = content.document.getElementById("testAudio");
if (!audio) {
ok(false, "Can't get the audio element!");
}
is(audio.paused, expectPause,
"The pause state of audio is corret.")
} | identifier_body |
browser_block_autoplay_media_pausedAfterPlay.js | const PAGE_SHOULD_PLAY = "https://example.com/browser/toolkit/content/tests/browser/file_blockMedia_shouldPlay.html";
const PAGE_SHOULD_NOT_PLAY = "https://example.com/browser/toolkit/content/tests/browser/file_blockMedia_shouldNotPlay.html";
var SuspendedType = {
NONE_SUSPENDED : 0,
SUSPENDED_PAUSE ... | yield SpecialPowers.pushPrefEnv({"set": [
["media.useAudioChannelService.testing", true],
["media.block-autoplay-until-in-foreground", true]
]});
});
add_task(function* block_autoplay_media() {
info("- open new background tab1, and check tab1's media suspend type -");
let tab1 = window.gBrowser.addTab(... | random_line_split | |
browser_block_autoplay_media_pausedAfterPlay.js | const PAGE_SHOULD_PLAY = "https://example.com/browser/toolkit/content/tests/browser/file_blockMedia_shouldPlay.html";
const PAGE_SHOULD_NOT_PLAY = "https://example.com/browser/toolkit/content/tests/browser/file_blockMedia_shouldNotPlay.html";
var SuspendedType = {
NONE_SUSPENDED : 0,
SUSPENDED_PAUSE ... |
is(audio.computedSuspended, suspendedType,
"The suspeded state of audio is correct.");
}
function check_audio_pause_state(expectPause) {
var audio = content.document.getElementById("testAudio");
if (!audio) {
ok(false, "Can't get the audio element!");
}
is(audio.paused, expectPause,
"The paus... | {
ok(false, "Can't get the audio element!");
} | conditional_block |
lib.rs | ) items from the output"),
("unindent-comments", passes::unindent_comments,
"removes excess indentation on comments in order for markdown to like it"),
("collapse-docs", passes::collapse_docs,
"concatenates all document attributes into one document attribute"),
("strip-private", passes::strip_priv... |
pub fn main_args(args: &[String]) -> int {
let matches = match getopts::getopts(args.tail(), opts().as_slice()) {
Ok(m) => m,
Err(err) => {
println!("{}", err);
return 1;
}
};
if matches.opt_present("h") || matches.opt_present("help") {
usage(args[0]... | {
println!("{}",
getopts::usage(format!("{} [options] <input>", argv0).as_slice(),
opts().as_slice()));
} | identifier_body |
lib.rs | ) items from the output"),
("unindent-comments", passes::unindent_comments,
"removes excess indentation on comments in order for markdown to like it"),
("collapse-docs", passes::collapse_docs,
"concatenates all document attributes into one document attribute"),
("strip-private", passes::strip_priv... |
};
info!("going to format");
let started = time::precise_time_ns();
match matches.opt_str("w").as_ref().map(|s| s.as_slice()) {
Some("html") | None => {
match html::render::run(krate, &external_html, output.unwrap_or(Path::new("doc"))) {
Ok(()) => {}
... | {
println!("input error: {}", s);
return 1;
} | conditional_block |
lib.rs | ) items from the output"),
("unindent-comments", passes::unindent_comments,
"removes excess indentation on comments in order for markdown to like it"),
("collapse-docs", passes::collapse_docs,
"concatenates all document attributes into one document attribute"),
("strip-private", passes::strip_priv... | (args: &[String]) -> int {
let matches = match getopts::getopts(args.tail(), opts().as_slice()) {
Ok(m) => m,
Err(err) => {
println!("{}", err);
return 1;
}
};
if matches.opt_present("h") || matches.opt_present("help") {
usage(args[0].as_slice());
... | main_args | identifier_name |
lib.rs | ) items from the output"),
("unindent-comments", passes::unindent_comments,
"removes excess indentation on comments in order for markdown to like it"),
("collapse-docs", passes::collapse_docs,
"concatenates all document attributes into one document attribute"),
("strip-private", passes::strip_priv... | /// and files and then generates the necessary rustdoc output for formatting.
fn acquire_input(input: &str,
matches: &getopts::Matches) -> Result<Output, String> {
match matches.opt_str("r").as_ref().map(|s| s.as_slice()) {
Some("rust") => Ok(rust_input(input, matches)),
Some("json"... |
/// Looks inside the command line arguments to extract the relevant input format | random_line_split |
get-token.ts | /**
* @license
* Copyright 2019 Google Inc.
*
* 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... |
async function completeInstallationRegistration(
appConfig: AppConfig
): Promise<void> {
const { installationEntry, registrationPromise } = await getInstallationEntry(
appConfig
);
if (registrationPromise) {
// A createInstallation request is in progress. Wait until it finishes.
await registratio... | {
const appConfig = extractAppConfig(app);
await completeInstallationRegistration(appConfig);
// At this point we either have a Registered Installation in the DB, or we've
// already thrown an error.
return fetchAuthToken(appConfig);
} | identifier_body |
get-token.ts | /**
* @license
* Copyright 2019 Google Inc.
*
* 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... | (authToken: CompletedAuthToken): boolean {
const now = Date.now();
return (
now < authToken.creationTime ||
authToken.creationTime + authToken.expiresIn < now + TOKEN_EXPIRATION_BUFFER
);
}
/** Returns an updated InstallationEntry with an InProgressAuthToken. */
function makeAuthTokenRequestInProgressEnt... | isAuthTokenExpired | identifier_name |
get-token.ts | /**
* @license
* Copyright 2019 Google Inc.
*
* 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... | CompletedAuthToken,
InProgressAuthToken,
InstallationEntry,
RegisteredInstallationEntry,
RequestStatus
} from '../interfaces/installation-entry';
import { PENDING_TIMEOUT_MS, TOKEN_EXPIRATION_BUFFER } from '../util/constants';
import { ERROR_FACTORY, ErrorCode, isServerError } from '../util/errors';
import { ... | AuthToken, | random_line_split |
get-token.ts | /**
* @license
* Copyright 2019 Google Inc.
*
* 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... |
const oldAuthToken = oldEntry.authToken;
if (hasAuthTokenRequestTimedOut(oldAuthToken)) {
return {
...oldEntry,
authToken: { requestStatus: RequestStatus.NOT_STARTED }
};
}
return oldEntry;
}
);
}
async function fetchAuthTokenFromServer(
appConfig:... | {
throw ERROR_FACTORY.create(ErrorCode.NOT_REGISTERED);
} | conditional_block |
call_interpolate.py | from bundleprocessing import interpolateMetric
import pandas as pd
import nibabel as nib
import argparse
parser = argparse.ArgumentParser() | parser.add_argument('-flip', '--flip', type=bool, required = True)
parser.add_argument('-outTracks', '--outTracks', required = True)
parser.add_argument('-outMetrics', '--outMetrics', required = True)
args = parser.parse_args()
tracks, hdr = nib.trackvis.read(args.templateBundle)
templateBundle = [trk[0] for trk ... | parser.add_argument('-templateBundle', '--templateBundle', required = True)
parser.add_argument('-subjectBundle', '--subjectBundle', required = True)
parser.add_argument('-metric', '--metric', required = True)
parser.add_argument('-numPoints', '--numPoints', type=int, required = True) | random_line_split |
submission-categories.page.ts | import { Component } from '@angular/core';
import { NavController, ModalController } from 'ionic-angular';
import { CategoriesProvider } from './../../providers/georeport';
import { SubmissionCategoriesDetails } from './modal/category-details.page'
@Component({
templateUrl: 'submission-categories.html'
})
export c... |
loadDescription(_category: any) {
let modal = this.modalCtrl.create(SubmissionCategoriesDetails, _category);
modal.present();
}
}
| {
this.categoriesProvider.load()
.then(data => {
// for (let category of data) {
// data.icon = this.iconsProvider.getIcon(category.service_code);
// }
this.categories = data;
}
);
} | identifier_body |
submission-categories.page.ts | import { Component } from '@angular/core';
import { NavController, ModalController } from 'ionic-angular';
import { CategoriesProvider } from './../../providers/georeport';
import { SubmissionCategoriesDetails } from './modal/category-details.page'
@Component({
templateUrl: 'submission-categories.html'
})
export c... |
// for (let category of data) {
// data.icon = this.iconsProvider.getIcon(category.service_code);
// }
this.categories = data;
}
);
}
loadDescription(_category: any) {
let modal = this.modalCtrl.create(SubmissionCategoriesDetails, _category);
modal.present();... | random_line_split | |
submission-categories.page.ts | import { Component } from '@angular/core';
import { NavController, ModalController } from 'ionic-angular';
import { CategoriesProvider } from './../../providers/georeport';
import { SubmissionCategoriesDetails } from './modal/category-details.page'
@Component({
templateUrl: 'submission-categories.html'
})
export c... | () {
this.categoriesProvider.load()
.then(data => {
// for (let category of data) {
// data.icon = this.iconsProvider.getIcon(category.service_code);
// }
this.categories = data;
}
);
}
loadDescription(_category: any) {
let modal = this.modalCtrl.create... | loadCategories | identifier_name |
index.js | import React from 'react';
import { prefixLink } from 'gatsby-helpers';
import DocumentTitle from 'react-document-title';
import Product from '../components/Product';
import Hexagon from '../components/Hexagon';
import ProductFinder from '../components/ProductFinder';
import CatalogueForm from '../components/CatalogueF... | <span className={`bg--${p.color}`}>{p.title}</span>
<Hexagon color={p.color} active={i === this.state.productId}/>
</MediaQuery>
<MediaQuery query='(max-width: 767px)'>
<span className={`bg--${p.color}`}>{p.title}</span>
<Hexagon width={30} strokeWidth... | <a key={i} onClick={this.handleProductClick.bind(this, i)}>
<MediaQuery query='(min-width: 48em)'> | random_line_split |
index.js | import React from 'react';
import { prefixLink } from 'gatsby-helpers';
import DocumentTitle from 'react-document-title';
import Product from '../components/Product';
import Hexagon from '../components/Hexagon';
import ProductFinder from '../components/ProductFinder';
import CatalogueForm from '../components/CatalogueF... |
handleProductClick = (productId) => {
this.setState({ productId: productId, cycle: false });
};
handleStopCycle = () => {
this.setState({ cycle: false });
};
handleCalculate = (productId) => {
const el = document.getElementById('rechner');
this.setState({ prodForCalc: productId });
scr... | {
setInterval(() => {
if (!this.state.cycle) return;
let next = this.state.productId + 1;
if (next > content.products.length - 1) next = 0;
this.setState({ productId: next });
}, 2500);
} | identifier_body |
index.js | import React from 'react';
import { prefixLink } from 'gatsby-helpers';
import DocumentTitle from 'react-document-title';
import Product from '../components/Product';
import Hexagon from '../components/Hexagon';
import ProductFinder from '../components/ProductFinder';
import CatalogueForm from '../components/CatalogueF... | extends React.Component {
constructor(props) {
super(props);
this.state = { productId: 0, value: 10, prodForCalc: null, cycle: true };
}
componentDidMount() {
setInterval(() => {
if (!this.state.cycle) return;
let next = this.state.productId + 1;
if (next > content.products.length... | Index | identifier_name |
data.py | """Breast Cancer Data"""
__docformat__ = 'restructuredtext'
COPYRIGHT = """???"""
TITLE = """Breast Cancer Data"""
SOURCE = """
This is the breast cancer data used in Owen's empirical likelihood. It is taken from
Rice, J.A. Mathematical Statistics and Data Analysis.
http://www.cengage.com/statistics/dis... | ():
data = _get_data()
##### SET THE INDICES #####
#NOTE: None for exog_idx is the complement of endog_idx
return du.process_recarray_pandas(data, endog_idx=0, exog_idx=None,
dtype=float)
def _get_data():
filepath = dirname(abspath(__file__))
##### EDIT THE... | load_pandas | identifier_name |
data.py | """Breast Cancer Data"""
__docformat__ = 'restructuredtext'
COPYRIGHT = """???"""
TITLE = """Breast Cancer Data"""
SOURCE = """
This is the breast cancer data used in Owen's empirical likelihood. It is taken from
Rice, J.A. Mathematical Statistics and Data Analysis.
http://www.cengage.com/statistics/dis... | filepath = dirname(abspath(__file__))
##### EDIT THE FOLLOWING TO POINT TO DatasetName.csv #####
with open(filepath + '/cancer.csv', 'rb') as f:
data = np.recfromtxt(f, delimiter=",", names=True, dtype=float)
return data | identifier_body | |
data.py | """Breast Cancer Data"""
__docformat__ = 'restructuredtext'
COPYRIGHT = """???"""
TITLE = """Breast Cancer Data"""
SOURCE = """
This is the breast cancer data used in Owen's empirical likelihood. It is taken from
Rice, J.A. Mathematical Statistics and Data Analysis.
http://www.cengage.com/statistics/dis... | ##### SET THE INDICES #####
#NOTE: None for exog_idx is the complement of endog_idx
return du.process_recarray_pandas(data, endog_idx=0, exog_idx=None,
dtype=float)
def _get_data():
filepath = dirname(abspath(__file__))
##### EDIT THE FOLLOWING TO POINT TO Data... | #NOTE: None for exog_idx is the complement of endog_idx
return du.process_recarray(data, endog_idx=0, exog_idx=None, dtype=float)
def load_pandas():
data = _get_data() | random_line_split |
startup.py | """
Module for code that should run during LMS startup
"""
# pylint: disable=unused-argument
from django.conf import settings
# Force settings to run so that the python path is modified
settings.INSTALLED_APPS # pylint: disable=pointless-statement
from openedx.core.lib.django_startup import autostartup
import edxm... | )
# Calculate the location of the theme's files
theme_root = settings.ENV_ROOT / "themes" / settings.THEME_NAME
# Include the theme's templates in the template search paths
settings.TEMPLATE_DIRS.insert(0, theme_root / 'templates')
edxmako.paths.add_lookup('main', theme_root / 'templates', pre... | return
assert settings.FEATURES['USE_CUSTOM_THEME']
settings.FAVICON_PATH = 'themes/{name}/images/favicon.ico'.format(
name=settings.THEME_NAME | random_line_split |
startup.py | """
Module for code that should run during LMS startup
"""
# pylint: disable=unused-argument
from django.conf import settings
# Force settings to run so that the python path is modified
settings.INSTALLED_APPS # pylint: disable=pointless-statement
from openedx.core.lib.django_startup import autostartup
import edxm... | if settings.FEATURES.get('ENABLE_THIRD_PARTY_AUTH', False):
enable_third_party_auth()
# Initialize Segment.io analytics module. Flushes first time a message is received and
# every 50 messages thereafter, or if 10 seconds have passed since last flush
if settings.FEATURES.get('SEGMENT_IO_LMS') a... | """
Executed during django startup
"""
# Patch the xml libs.
from safe_lxml import defuse_xml_libs
defuse_xml_libs()
django_utils_translation.patch()
autostartup()
add_mimetypes()
if settings.FEATURES.get('USE_CUSTOM_THEME', False):
enable_theme()
if settings.FEATUR... | identifier_body |
startup.py | """
Module for code that should run during LMS startup
"""
# pylint: disable=unused-argument
from django.conf import settings
# Force settings to run so that the python path is modified
settings.INSTALLED_APPS # pylint: disable=pointless-statement
from openedx.core.lib.django_startup import autostartup
import edxm... | ():
"""
Enable the use of microsites, which are websites that allow
for subdomains for the edX platform, e.g. foo.edx.org
"""
microsites_root = settings.MICROSITE_ROOT_DIR
microsite_config_dict = settings.MICROSITE_CONFIGURATION
for ms_name, ms_config in microsite_config_dict.items():
... | enable_microsites | identifier_name |
startup.py | """
Module for code that should run during LMS startup
"""
# pylint: disable=unused-argument
from django.conf import settings
# Force settings to run so that the python path is modified
settings.INSTALLED_APPS # pylint: disable=pointless-statement
from openedx.core.lib.django_startup import autostartup
import edxm... |
if settings.FEATURES.get('ENABLE_THIRD_PARTY_AUTH', False):
enable_third_party_auth()
# Initialize Segment.io analytics module. Flushes first time a message is received and
# every 50 messages thereafter, or if 10 seconds have passed since last flush
if settings.FEATURES.get('SEGMENT_IO_LMS')... | enable_microsites() | conditional_block |
stateService.ts | = this.stateRegistry.matcher.find(identifier, options.relative);
return new TargetState(identifier, stateDefinition, params, options);
};
/**
* @ngdoc function
* @name ui.router.state.$state#transitionTo
* @methodOf ui.router.state.$state
*
* @description
* Low-level method for transitioning... | {
if (!glob.matches(this.$current.name)) return false;
stateOrName = this.$current.name;
} | conditional_block | |
stateService.ts | (private $view: ViewService,
private $stateParams: StateParams,
private $urlRouter: UrlRouter,
private $transitions: TransitionService,
private stateRegistry: StateRegistry,
private stateProvider: StateProvider) {
bindFunctions(StateService.proto... | constructor | identifier_name | |
stateService.ts | let root = stateRegistry.root();
extend(this, {
params: new StateParams(),
current: root.self,
$current: root,
transition: null
});
}
/**
* Invokes the onInvalid callbacks, in natural order. Each callback's return value is checked in sequence
* until one of them returns a... | private stateProvider: StateProvider) {
bindFunctions(StateService.prototype, this, this);
| random_line_split | |
stateService.ts | state
*
* @param {object=} params A map of the parameters that will be sent to the state,
* will populate $stateParams. Any parameters that are not specified will be inherited from currently
* defined parameters. This allows, for example, going to a sibling state that shares parameters
* specified in a ... | {
options = defaults(options, { relative: this.$current });
let state = this.stateRegistry.matcher.find(stateOrName, options.relative);
if (!isDefined(state)) return undefined;
if (this.$current !== state) return false;
return isDefined(params) && params !== null ? Param.equals(state.parameters(), t... | identifier_body | |
dumper.py | i in l)
def colorful(line, styles):
yield " " # we can already indent here
for (style, text) in line:
yield click.style(text, **styles.get(style, {}))
class Dumper:
def __init__(self, outfile=None):
self.filter: Optional[flowfilter.TFilter] = None
self.outfp: Optional[IO] = ... | msg = strutils.escape_control_characters(f.error.msg)
self.echo(f" << {msg}", bold=True, fg="red")
def match(self, f):
if ctx.options.flow_detail == 0:
return False
if not self.filter:
return True
elif flowfilter.match(self.filter, f):
... |
if f.error: | random_line_split |
dumper.py | i in l)
def colorful(line, styles):
yield " " # we can already indent here
for (style, text) in line:
yield click.style(text, **styles.get(style, {}))
class Dumper:
def __init__(self, outfile=None):
self.filter: Optional[flowfilter.TFilter] = None
self.outfp: Optional[IO] = ... |
def configure(self, updated):
if "dumper_filter" in updated:
if ctx.options.dumper_filter:
self.filter = flowfilter.parse(ctx.options.dumper_filter)
if not self.filter:
raise exceptions.OptionsError(
"Invalid filter ex... | loader.add_option(
"flow_detail", int, 1,
"""
The display detail level for flows in mitmdump: 0 (almost quiet) to 3 (very verbose).
0: shortened request URL, response status code, WebSocket and TCP message notifications.
1: full request URL with response s... | identifier_body |
dumper.py | i in l)
def colorful(line, styles):
yield " " # we can already indent here
for (style, text) in line:
yield click.style(text, **styles.get(style, {}))
class Dumper:
def __init__(self, outfile=None):
self.filter: Optional[flowfilter.TFilter] = None
self.outfp: Optional[IO] = ... |
if ctx.options.flow_detail >= 2:
self.echo("")
def _echo_request_line(self, flow: http.HTTPFlow) -> None:
if flow.client_conn:
client = click.style(
strutils.escape_control_characters(
human.format_address(flow.client_conn.peername)
... | self.echo("(cut off)", ident=4, dim=True) | conditional_block |
dumper.py | i in l)
def colorful(line, styles):
yield " " # we can already indent here
for (style, text) in line:
yield click.style(text, **styles.get(style, {}))
class Dumper:
def __init__(self, outfile=None):
self.filter: Optional[flowfilter.TFilter] = None
self.outfp: Optional[IO] = ... | elf, f):
if self.match(f):
self.echo_flow(f)
def error(self, f):
if self.match(f):
self.echo_flow(f)
def websocket_message(self, f: http.HTTPFlow):
assert f.websocket is not None # satisfy type checker
if self.match(f):
message = f.websocket... | sponse(s | identifier_name |
screen-saver.component.ts | import {Component, OnInit, OnChanges, SimpleChanges, Input} from '@angular/core';
import {ScreenSaverService} from './screen-saver.service';
import {UtilityService} from '../utility/utility.service';
import {OrganizationService} from '../organization/organization.service';
import {MarkerService} from '../organization/m... |
ngOnInit(): any {
this.screenSaverService.fetchSettings();
const options = {
atmosphere: true,
sky: 'assets/screensaver/',
center: [this.screenSaverService.globeSettings.startingLatCoord,
this.screenSaverService.globeSettings.startingLongCoord],
zoom: this.screenSaverService... | {
} | identifier_body |
screen-saver.component.ts | import {Component, OnInit, OnChanges, SimpleChanges, Input} from '@angular/core';
import {ScreenSaverService} from './screen-saver.service';
import {UtilityService} from '../utility/utility.service';
import {OrganizationService} from '../organization/organization.service';
import {MarkerService} from '../organization/m... | this._earth.setHeading(heading);
}
} | private headingAnimation() {
const heading = this.screenSaverService.globeSettings.heading + this.screenSaverService.globeSettings.headingOffset
+ 0.01 * this.screenSaverService.globeSettings.headingMultiplier;
this.screenSaverService.globeSettings.headingOffset = heading - this.screenSaverService.globe... | random_line_split |
screen-saver.component.ts | import {Component, OnInit, OnChanges, SimpleChanges, Input} from '@angular/core';
import {ScreenSaverService} from './screen-saver.service';
import {UtilityService} from '../utility/utility.service';
import {OrganizationService} from '../organization/organization.service';
import {MarkerService} from '../organization/m... |
}
ngOnChanges(changes: SimpleChanges) {
if (this.utilityService.isScreensaver && this._hasInitialized) {
this.launchAnimations();
} else {
this.killAnimations();
}
}
private setup(): void {
this.markerService.addMarkersToGlobe(this._earth, this.orgService.organizations);
this... | {
this.orgService.orgsReadySubject.subscribe(() => {
this.setup();
});
} | conditional_block |
screen-saver.component.ts | import {Component, OnInit, OnChanges, SimpleChanges, Input} from '@angular/core';
import {ScreenSaverService} from './screen-saver.service';
import {UtilityService} from '../utility/utility.service';
import {OrganizationService} from '../organization/organization.service';
import {MarkerService} from '../organization/m... | (changes: SimpleChanges) {
if (this.utilityService.isScreensaver && this._hasInitialized) {
this.launchAnimations();
} else {
this.killAnimations();
}
}
private setup(): void {
this.markerService.addMarkersToGlobe(this._earth, this.orgService.organizations);
this._hasInitialized = ... | ngOnChanges | identifier_name |
0007_auto_20180311_1704.py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2018-03-11 17:04
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class | (migrations.Migration):
dependencies = [
('board', '0006_merge_20180311_1702'),
]
operations = [
migrations.CreateModel(
name='MainPoster',
fields=[
('basepost_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE,... | Migration | identifier_name |
0007_auto_20180311_1704.py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2018-03-11 17:04
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [ | migrations.CreateModel(
name='MainPoster',
fields=[
('basepost_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='board.BasePost')),
('title', models.CharField... | ('board', '0006_merge_20180311_1702'),
]
operations = [ | random_line_split |
0007_auto_20180311_1704.py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2018-03-11 17:04
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
| migrations.AlterModelOptions(
name='boardbanner',
options={'verbose_name': '게시판 배너', 'verbose_name_plural': '게시판 배너(들)'},
),
migrations.AlterField(
model_name='board',
name='role',
field=models.CharField(choices=[('DEFAULT', '기본'), ('PR... | dependencies = [
('board', '0006_merge_20180311_1702'),
]
operations = [
migrations.CreateModel(
name='MainPoster',
fields=[
('basepost_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_ke... | identifier_body |
list.ts | import gql from 'graphql-tag';
const query = gql`
enum PageListStandard {
income
bills
food
general
social
holiday
}
type ListItem {
id: Int!
item: String!
}
type ListItemStandard {
id: Int!
date: Date!
item: String!
category: String!
cost: Int!
shop: ... | cost: Int!
shop: String!
}
extend type Subscription {
listChanged(pages: [PageListStandard!]!): ListSubscription!
receiptCreated: ReceiptCreated!
}
`;
export const listSchema = gql`
${query}
${mutation}
${subscription}
`; | random_line_split | |
EditConfirmationMessageForm.tsx | import { FunctionComponent } from 'react';
import { connect } from 'react-redux';
import { compose } from 'redux';
import { reduxForm } from 'redux-form';
import { FormContainer, SubmitButton, TextField } from '@waldur/form';
import { translate } from '@waldur/i18n';
import { EDIT_CONFIRMATION_MESSAGE_FORM_ID } from '... | ('Edit confirmation message of {offeringName}', {
offeringName: props.offering.name,
})}
footer={
<>
<CloseDialogButton />
<SubmitButton
submitting={props.submitting}
label={translate('Save')}
/>
</>
}
>
<FormConta... | translate | identifier_name |
EditConfirmationMessageForm.tsx | import { FunctionComponent } from 'react';
import { connect } from 'react-redux';
import { compose } from 'redux';
import { reduxForm } from 'redux-form';
import { FormContainer, SubmitButton, TextField } from '@waldur/form';
import { translate } from '@waldur/i18n';
import { EDIT_CONFIRMATION_MESSAGE_FORM_ID } from '... | </ModalDialog>
</form>
);
const mapStateToProps = (_state, ownProps) => ({
initialValues: {
template_confirmation_comment:
ownProps.offering.secret_options.template_confirmation_comment,
},
});
const mapDispatchToProps = (dispatch, ownProps) => ({
submitRequest: (formData) =>
updateConfirmat... | {
<>
<CloseDialogButton />
<SubmitButton
submitting={props.submitting}
label={translate('Save')}
/>
</>
}
>
<FormContainer
submitting={props.submitting}
labelClass="col-sm-2"
controlClass="col-sm-8"
>
... | identifier_body |
EditConfirmationMessageForm.tsx | import { FunctionComponent } from 'react';
import { connect } from 'react-redux';
import { compose } from 'redux';
import { reduxForm } from 'redux-form';
import { FormContainer, SubmitButton, TextField } from '@waldur/form';
import { translate } from '@waldur/i18n';
import { EDIT_CONFIRMATION_MESSAGE_FORM_ID } from '... | const enhance = compose(
connector,
reduxForm<FormData, EditConfirmationMessageFormOwnProps>({
form: EDIT_CONFIRMATION_MESSAGE_FORM_ID,
}),
);
export const EditConfirmationMessageForm = enhance(
PureEditConfirmationMessageForm,
); | ),
});
const connector = connect(mapStateToProps, mapDispatchToProps);
| random_line_split |
constants.py | # Copyright 2013 Mirantis, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... | SESSION_PERSISTENCE_HTTP_COOKIE = 'HTTP_COOKIE'
SESSION_PERSISTENCE_APP_COOKIE = 'APP_COOKIE'
SUPPORTED_SP_TYPES = (SESSION_PERSISTENCE_SOURCE_IP,
SESSION_PERSISTENCE_HTTP_COOKIE,
SESSION_PERSISTENCE_APP_COOKIE)
L7_RULE_TYPE_HOST_NAME = 'HOST_NAME'
L7_RULE_TYPE_PATH = 'PATH'... |
SESSION_PERSISTENCE_SOURCE_IP = 'SOURCE_IP' | random_line_split |
plotter.py | import csv
from util.helper import *
import util.plot_defaults
from matplotlib.ticker import MaxNLocator
from pylab import figure
parser = argparse.ArgumentParser()
parser.add_argument('--file', '-f',
help="data file directory",
required=True,
action="store... |
plt.title('Shrew-attack TCP throughput. Burst = ' + burst)
plt.legend(loc='upper left')
plt.xlabel('seconds')
plt.ylabel("% thoroughput")
plt.grid(True)
plt.savefig("{0}/{1}-result.png".format(args.dir, burst))
plt.close()
| data = read_list(args.file + '/' + tcptype + '-' + burst +'-raw_data.txt')
xs = col(0, data)
ys = col(1, data)
plt.plot(xs, ys, label=tcptype) | conditional_block |
plotter.py | import csv
from util.helper import *
import util.plot_defaults
from matplotlib.ticker import MaxNLocator
from pylab import figure
parser = argparse.ArgumentParser()
parser.add_argument('--file', '-f',
help="data file directory",
required=True,
action="store... | dest="dir")
args = parser.parse_args()
to_plot = []
cong = ['reno', 'cubic', 'vegas']
bursts = ['0.03', '0.05', '0.07', '0.09']
graphfiles = []
for burst in bursts:
for tcptype in cong:
data = read_list(args.file + '/' + tcptype + '-' + burst +'-raw_data.txt')
xs = col(0, data)
ys = col(1,... |
parser.add_argument('-o',
help="Output directory",
required=True,
action="store", | random_line_split |
set_cover_test.rs | mod bit_vector;
mod set_cover;
use set_cover::minimum_set_cover;
#[test]
fn test_disjoint() |
#[test]
fn test_one() {
test(
vec![
vec![0, 1, 2],
vec![0],
vec![1],
vec![2],
],
vec![0],
);
}
#[test]
fn test_two() {
test(
vec![
vec![0, 1],
vec![1, 2],
vec![2, 3],
],
vec... | {
test(
vec![
vec![0],
vec![1],
vec![2],
],
vec![0, 1, 2],
);
} | identifier_body |
set_cover_test.rs | mod bit_vector;
mod set_cover;
use set_cover::minimum_set_cover;
#[test]
fn test_disjoint() {
test(
vec![
vec![0],
vec![1],
vec![2],
],
vec![0, 1, 2],
);
}
#[test]
fn test_one() {
test(
vec![
vec![0, 1, 2],
vec![0... | ],
vec![0, 2],
);
}
fn test(subsets: Vec<Vec<u8>>, expected_cover: Vec<usize>) {
let mut actual_cover = minimum_set_cover(&subsets);
actual_cover.sort();
assert_eq!(expected_cover, actual_cover);
} | test(
vec![
vec![0, 1],
vec![1, 2],
vec![2, 3], | random_line_split |
set_cover_test.rs | mod bit_vector;
mod set_cover;
use set_cover::minimum_set_cover;
#[test]
fn test_disjoint() {
test(
vec![
vec![0],
vec![1],
vec![2],
],
vec![0, 1, 2],
);
}
#[test]
fn | () {
test(
vec![
vec![0, 1, 2],
vec![0],
vec![1],
vec![2],
],
vec![0],
);
}
#[test]
fn test_two() {
test(
vec![
vec![0, 1],
vec![1, 2],
vec![2, 3],
],
vec![0, 2],
);
}
fn... | test_one | identifier_name |
timers.d.ts | declare module 'node:timers' {
export * from 'timers';
}
declare module 'timers' { | function setTimeout(callback: (...args: any[]) => void, ms?: number, ...args: any[]): NodeJS.Timeout;
namespace setTimeout {
function __promisify__(ms: number): Promise<void>;
function __promisify__<T>(ms: number, value: T): Promise<T>;
}
function clearTimeout(timeoutId: NodeJS.Timeout):... | random_line_split | |
setup.py | from setuptools import setup
def setup_package():
# PyPi doesn't accept markdown as HTML output for long_description
# Pypandoc is only required for uploading the metadata to PyPi and not installing it by the user
# Try to covert Mardown to RST file for long_description
| classifiers=[
'Development Status :: 1 - Planning',
'Intended Audience :: Science/Research',
'Intended Audience :: Education',
'License :: OSI Approved :: BSD License',
'Natural Language :: English',
'Programming Language :: Python :: 3',
... | try:
import pypandoc
long_description = pypandoc.convert_file('README.md', 'rst')
# Except ImportError then read in the Markdown file for long_description
except ImportError:
print("warning: pypandoc module not found, could not convert Markdown to RST")
with open('README.md') as... | identifier_body |
setup.py | from setuptools import setup
def setup_package():
# PyPi doesn't accept markdown as HTML output for long_description
# Pypandoc is only required for uploading the metadata to PyPi and not installing it by the user
# Try to covert Mardown to RST file for long_description
try:
import pypandoc
... | # Bundle metadata up
setup(**metadata)
if __name__ == '__main__':
setup_package() | random_line_split | |
setup.py | from setuptools import setup
def setup_package():
# PyPi doesn't accept markdown as HTML output for long_description
# Pypandoc is only required for uploading the metadata to PyPi and not installing it by the user
# Try to covert Mardown to RST file for long_description
try:
import pypandoc
... | setup_package() | conditional_block | |
setup.py | from setuptools import setup
def | ():
# PyPi doesn't accept markdown as HTML output for long_description
# Pypandoc is only required for uploading the metadata to PyPi and not installing it by the user
# Try to covert Mardown to RST file for long_description
try:
import pypandoc
long_description = pypandoc.convert_file(... | setup_package | identifier_name |
cache_restore.rs | use anyhow::Result;
mod common;
use common::cache::*;
use common::common_args::*;
use common::fixture::*;
use common::input_arg::*;
use common::output_option::*;
use common::process::*;
use common::program::*;
use common::target::*;
use common::test_dir::*;
//------------------------------------------
const USAGE: ... | () -> &'a str {
"" // we don't intent to verify error messages of XML parsing
}
}
impl<'a> OutputProgram<'a> for CacheRestore {
fn missing_output_arg() -> &'a str {
msg::MISSING_OUTPUT_ARG
}
}
impl<'a> MetadataWriter<'a> for CacheRestore {
fn file_not_found() -> &'a str {
msg::... | corrupted_input | identifier_name |
cache_restore.rs | use anyhow::Result;
mod common;
use common::cache::*;
use common::common_args::*;
use common::fixture::*;
use common::input_arg::*;
use common::output_option::*;
use common::process::*;
use common::program::*;
use common::target::*;
use common::test_dir::*;
//------------------------------------------
const USAGE: ... | msg::bad_option_hint(option)
}
}
impl<'a> InputProgram<'a> for CacheRestore {
fn mk_valid_input(td: &mut TestDir) -> Result<std::path::PathBuf> {
mk_valid_xml(td)
}
fn file_not_found() -> &'a str {
msg::FILE_NOT_FOUND
}
fn missing_input_arg() -> &'a str {
msg::... | fn arg_type() -> ArgType {
ArgType::IoOptions
}
fn bad_option_hint(option: &str) -> String { | random_line_split |
cache_restore.rs | use anyhow::Result;
mod common;
use common::cache::*;
use common::common_args::*;
use common::fixture::*;
use common::input_arg::*;
use common::output_option::*;
use common::process::*;
use common::program::*;
use common::target::*;
use common::test_dir::*;
//------------------------------------------
const USAGE: ... |
fn cmd<I>(args: I) -> Command
where
I: IntoIterator,
I::Item: Into<std::ffi::OsString>,
{
cache_restore_cmd(args)
}
fn usage() -> &'a str {
USAGE
}
fn arg_type() -> ArgType {
ArgType::IoOptions
}
fn bad_option_hint(option: &str) -> String ... | {
"thin_restore"
} | identifier_body |
no_0647_palindromic_substrings.rs | struct Solution;
impl Solution {
pub fn count_substrings(s: String) -> i32 | #[cfg(test)]
mod tests {
use super::*;
#[test]
fn
test_count_substrings1() {
assert_eq!(Solution::count_substrings("abc".to_string()), 3);
}
#[test]
fn test_count_substrings2() {
assert_eq!(Solution::count_substrings("aaa".to_string()), 6);
}
}
| {
let s = s.as_bytes();
let n = s.len() as i32;
let mut ans = 0;
for i in 0..(2 * n - 1) {
// i 是中心点,包括了空隙,所以还要求出对应的索引。
// [0, 0], [0, 1], [1, 1], [1, 2] ...
let mut l = i / 2;
let mut r = l + i % 2;
// 从中心点向两边扩散。
wh... | identifier_body |
no_0647_palindromic_substrings.rs | struct Solution;
impl Solution {
pub fn count_substrings(s: String) -> i32 {
let s = s.as_bytes();
let n = s.len() as i32;
let mut ans = 0;
for i in 0..(2 * n - 1) {
// i 是中心点,包括了空隙,所以还要求出对应的索引。
// [0, 0], [0, 1], [1, 1], [1, 2] ...
let mut l = i /... | #[test]
fn test_count_substrings1() {
assert_eq!(Solution::count_substrings("abc".to_string()), 3);
}
#[test]
fn test_count_substrings2() {
assert_eq!(Solution::count_substrings("aaa".to_string()), 6);
}
} |
#[cfg(test)]
mod tests {
use super::*;
| random_line_split |
no_0647_palindromic_substrings.rs | struct Solution;
impl Solution {
pub fn | (s: String) -> i32 {
let s = s.as_bytes();
let n = s.len() as i32;
let mut ans = 0;
for i in 0..(2 * n - 1) {
// i 是中心点,包括了空隙,所以还要求出对应的索引。
// [0, 0], [0, 1], [1, 1], [1, 2] ...
let mut l = i / 2;
let mut r = l + i % 2;
// 从中心点向两... | count_substrings | identifier_name |
BioShape.js | .shape = shape;
this.modelIndex = modelIndex;
this.bioPolymer = bioPolymer;
this.isActive = shape.isActive;
this.bsSizeDefault = new JU.BS ();
this.monomerCount = bioPolymer.monomerCount;
if (this.monomerCount > 0) {
this.colixes = Clazz.newShortArray (this.monomerCount, 0);
this.paletteIDs = Clazz.newByteAr... | function (colix, bsSelected) {
for (var i = this.monomerCount; --i >= 0; ) {
var atomIndex = this.leadAtomIndices[i];
if (bsSelected.get (atomIndex)) {
| random_line_split | |
BioShape.js | ers;
});
Clazz.makeConstructor (c$,
function (shape, modelIndex, bioPolymer) {
Clazz.superConstructor (this, J.shapebio.BioShape, []);
this.shape = shape;
this.modelIndex = modelIndex;
this.bioPolymer = bioPolymer;
this.isActive = shape.isActive;
this.bsSizeDefault = new JU.BS ();
this.monomerCount = bioPol... | }, "J.shapebio.BioShapeCollection,~N,JM.BioPolymer");
Clazz.defineMethod (c$, "calcBfactorRange",
function () {
this.bfactorMin = this.bfactorMax = this.monomers[0].getLeadAtom ().getBfactor100 ();
for (var i = this.monomerCount; --i > 0; ) {
var bfactor = this.monomers[i].getLeadAtom ().getBfactor100 ();
if (bf... | {
this.colixes = Clazz.newShortArray (this.monomerCount, 0);
this.paletteIDs = Clazz.newByteArray (this.monomerCount, 0);
this.mads = Clazz.newShortArray (this.monomerCount + 1, 0);
this.monomers = bioPolymer.getGroups ();
this.meshReady = Clazz.newBooleanArray (this.monomerCount, false);
this.meshes = new A... | conditional_block |
CandlestickChartRounded.js | "use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime")... | d: "M8 4c-.55 0-1 .45-1 1v1H6c-.55 0-1 .45-1 1v10c0 .55.45 1 1 1h1v1c0 .55.45 1 1 1s1-.45 1-1v-1h1c.55 0 1-.45 1-1V7c0-.55-.45-1-1-1H9V5c0-.55-.45-1-1-1zm10 4h-1V5c0-.55-.45-1-1-1s-1 .45-1 1v3h-1c-.55 0-1 .45-1 1v5c0 .55.45 1 1 1h1v4c0 .55.45 1 1 1s1-.45 1-1v-4h1c.55 0 1-.45 1-1V9c0-.55-.45-1-1-1z"
}), 'CandlestickCh... | random_line_split | |
dojox.form.FileUploader.d.ts | /// <reference path="Object.d.ts" />
/// <reference path="dijit._Widget.d.ts" />
/// <reference path="dijit._Templated.d.ts" />
/// <reference path="dijit._Contained.d.ts" /> | widgetsInTemplate : bool;
_skipNodeCache : bool;
_earlyTemplatedStartup : bool;
_attachPoints : any;
_attachEvents : any[];
declaredClass : any;
_startupWidgets : Object;
_supportingWidgets : Object;
_templateCache : Object;
_stringRepl (tmpl:any) : any;
_fillContent (source:HTMLElement) : any;
_attachTemplateNodes (ro... | module dojox.form{
export class FileUploader extends dijit._Widget {
templateString : String;
templatePath : String; | random_line_split |
dojox.form.FileUploader.d.ts | /// <reference path="Object.d.ts" />
/// <reference path="dijit._Widget.d.ts" />
/// <reference path="dijit._Templated.d.ts" />
/// <reference path="dijit._Contained.d.ts" />
module dojox.form{
export class | extends dijit._Widget {
templateString : String;
templatePath : String;
widgetsInTemplate : bool;
_skipNodeCache : bool;
_earlyTemplatedStartup : bool;
_attachPoints : any;
_attachEvents : any[];
declaredClass : any;
_startupWidgets : Object;
_supportingWidgets : Object;
_templateCache : Object;
_stringRepl (tmpl:any)... | FileUploader | identifier_name |
lib.rs | // Copyright © 2015, Peter Atashian
// Licensed under the MIT License <LICENSE.md>
//! FFI bindings to winhttp.
#![cfg(windows)]
extern crate winapi;
use winapi::*;
extern "system" {
// pub fn WinHttpAddRequestHeaders();
// pub fn WinHttpAutoProxySvcMain();
// pub fn WinHttpCheckPlatform();
// pub fn Wi... | // pub fn WinHttpWebSocketSend();
// pub fn WinHttpWebSocketShutdown();
// pub fn WinHttpWriteData();
} | random_line_split | |
lib.rs | extern crate semver;
use std::io::prelude::*;
use std::collections::HashMap;
use std::error::Error;
use std::net::SocketAddr;
pub use self::typemap::TypeMap;
mod typemap;
#[derive(PartialEq, Debug, Clone, Copy)]
pub enum Scheme {
Http,
Https
}
#[derive(PartialEq, Debug, Clone, Copy)]
pub enum Host<'a> {
... |
/// The byte-size of the body, if any
fn content_length(&self) -> Option<u64>;
/// The request's headers, as conduit::Headers.
fn headers<'a>(&'a self) -> &'a Headers;
/// A Reader for the body of the request
fn body<'a>(&'a mut self) -> &'a mut Read;
/// A readable map of extensions
... |
/// The remote IP address of the client or the last proxy that
/// sent the request.
fn remote_addr(&self) -> SocketAddr; | random_line_split |
lib.rs | extern crate semver;
use std::io::prelude::*;
use std::collections::HashMap;
use std::error::Error;
use std::net::SocketAddr;
pub use self::typemap::TypeMap;
mod typemap;
#[derive(PartialEq, Debug, Clone, Copy)]
pub enum Scheme {
Http,
Https
}
#[derive(PartialEq, Debug, Clone, Copy)]
pub enum Host<'a> {
... | {
/// The status code as a tuple of the return code and status string
pub status: (u32, &'static str),
/// A Map of the headers
pub headers: HashMap<String, Vec<String>>,
/// A Writer for body of the response
pub body: Box<Read + Send>
}
/// A Handler takes a request and returns a response o... | Response | identifier_name |
constants.d.ts | // Type definitions for ag-grid v13.1.2
// Project: http://www.ag-grid.com/
// Definitions by: Niall Crosby <https://github.com/ag-grid/>
export declare class | {
static STEP_EVERYTHING: number;
static STEP_FILTER: number;
static STEP_SORT: number;
static STEP_MAP: number;
static STEP_AGGREGATE: number;
static STEP_PIVOT: number;
static ROW_BUFFER_SIZE: number;
static LAYOUT_INTERVAL: number;
static EXPORT_TYPE_DRAG_COPY: string;
static... | Constants | identifier_name |
constants.d.ts | // Type definitions for ag-grid v13.1.2
// Project: http://www.ag-grid.com/
// Definitions by: Niall Crosby <https://github.com/ag-grid/>
export declare class Constants {
static STEP_EVERYTHING: number;
static STEP_FILTER: number;
static STEP_SORT: number;
static STEP_MAP: number;
static STEP_AGGREG... | static KEY_TAB: number;
static KEY_ENTER: number;
static KEY_SHIFT: number;
static KEY_ESCAPE: number;
static KEY_SPACE: number;
static KEY_LEFT: number;
static KEY_UP: number;
static KEY_RIGHT: number;
static KEY_DOWN: number;
static KEY_DELETE: number;
static KEY_A: number;... | static KEY_BACKSPACE: number; | random_line_split |
setup.py | #!/usr/bin/python
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | 'google_clock_skew_daemon=google_compute_engine.clock_skew.clock_skew_daemon:main',
'google_instance_setup=google_compute_engine.instance_setup.instance_setup:main',
'google_network_daemon=google_compute_engine.networking.network_daemon:main',
'google_metadata_script_runn... | 'google_accounts_daemon=google_compute_engine.accounts.accounts_daemon:main', | random_line_split |
setup.py | #!/usr/bin/python
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... |
setuptools.setup(
author='Google Compute Engine Team',
author_email='gc-team@google.com',
description='Google Compute Engine',
include_package_data=True,
install_requires=install_requires,
license='Apache Software License',
long_description='Google Compute Engine guest environment.',
n... | install_requires += ['distro'] | conditional_block |
common.js | export async function login(driver, server, t) {
let userEndpointCalled = 0;
let bugEndpointCalled = 0;
server.get("/rest/user/:email", function(req, res) {
userEndpointCalled++;
t.is(req.params.email, "bugzilla@example.com");
res.json({
users: [{
"can_login" : true,
"email" : "bug... | (driver, server, t) {
let menuButton = await driver.elementById("menuButton");
menuButton.click();
let settingsButton = await driver.waitForElementById("settingsButton");
t.true(await settingsButton.isDisplayed());
settingsButton.click();
let logoutButton = await driver.waitForElementById("logoutButton");... | logout | identifier_name |
common.js | export async function login(driver, server, t) {
let userEndpointCalled = 0;
let bugEndpointCalled = 0;
server.get("/rest/user/:email", function(req, res) {
userEndpointCalled++;
t.is(req.params.email, "bugzilla@example.com");
res.json({
users: [{
"can_login" : true,
"email" : "bug... | t.is(bugEndpointCalled, 1);
server._router.stack.splice(-3, 3);
}
export async function logout(driver, server, t) {
let menuButton = await driver.elementById("menuButton");
menuButton.click();
let settingsButton = await driver.waitForElementById("settingsButton");
t.true(await settingsButton.isDisplayed(... | await button.click();
await driver.waitForElementById("menuButton");
t.is(userEndpointCalled, 2); | random_line_split |
common.js | export async function login(driver, server, t) | },
],
"id" : 65095,
"name" : "bugzilla@example.com",
"real_name" : "Example Tester",
"saved_reports" : [],
"saved_searches" : [],
}],
});
});
server.get("/rest/bug", function(req, res) {
bugEndpointCalled++;
t.is(req.query.assigned_to, "bugzilla... | {
let userEndpointCalled = 0;
let bugEndpointCalled = 0;
server.get("/rest/user/:email", function(req, res) {
userEndpointCalled++;
t.is(req.params.email, "bugzilla@example.com");
res.json({
users: [{
"can_login" : true,
"email" : "bugzilla@example.com",
"groups" : [
... | identifier_body |
wtf-app.py | #!/usr/bin/env python
# coding=utf8
from flask import Flask, render_template
from flask.ext.jqueryuibootstrap import JqueryUiBootstrap
from flask.ext.wtf import (
Form,
RecaptchaField,
)
from wtforms import ( | from wtforms.validators import (
Required,
)
app = Flask(__name__)
JqueryUiBootstrap(app)
app.config['SECRET_KEY'] = 'devkey'
app.config['RECAPTCHA_PUBLIC_KEY'] = '6Lfol9cSAAAAADAkodaYl9wvQCwBMr3qGR_PPHcw'
class ExampleForm(Form):
field1 = TextField('First Field', description='This is field one.')
... | TextField,
HiddenField,
ValidationError,
) | random_line_split |
wtf-app.py | #!/usr/bin/env python
# coding=utf8
from flask import Flask, render_template
from flask.ext.jqueryuibootstrap import JqueryUiBootstrap
from flask.ext.wtf import (
Form,
RecaptchaField,
)
from wtforms import (
TextField,
HiddenField,
ValidationError,
)
from wtforms.validators import (
... | (form, field):
raise ValidationError('Always wrong')
@app.route('/', methods=('GET', 'POST',))
def index():
form = ExampleForm()
if form.validate_on_submit():
return "PASSED"
return render_template('example.html', form=form)
if '__main__' == __name__:
app.run(debug=True)
| validate_hidden_field | identifier_name |
wtf-app.py | #!/usr/bin/env python
# coding=utf8
from flask import Flask, render_template
from flask.ext.jqueryuibootstrap import JqueryUiBootstrap
from flask.ext.wtf import (
Form,
RecaptchaField,
)
from wtforms import (
TextField,
HiddenField,
ValidationError,
)
from wtforms.validators import (
... |
if '__main__' == __name__:
app.run(debug=True)
| form = ExampleForm()
if form.validate_on_submit():
return "PASSED"
return render_template('example.html', form=form) | identifier_body |
wtf-app.py | #!/usr/bin/env python
# coding=utf8
from flask import Flask, render_template
from flask.ext.jqueryuibootstrap import JqueryUiBootstrap
from flask.ext.wtf import (
Form,
RecaptchaField,
)
from wtforms import (
TextField,
HiddenField,
ValidationError,
)
from wtforms.validators import (
... |
return render_template('example.html', form=form)
if '__main__' == __name__:
app.run(debug=True)
| return "PASSED" | conditional_block |
beanStub.js | /**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v25.0.1
* @link http://www.ag-grid.com/
* @license MIT
*/
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = ... | this.localEventService.dispatchEvent(event);
}
};
BeanStub.prototype.addManagedListener = function (object, event, listener) {
var _this = this;
if (this.destroyed) {
return;
}
if (object instanceof HTMLElement) {
addSafePassiveEventLis... | window.setTimeout(function () { return _this.dispatchEvent(event); }, 0);
};
BeanStub.prototype.dispatchEvent = function (event) {
if (this.localEventService) { | random_line_split |
beanStub.js | /**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v25.0.1
* @link http://www.ag-grid.com/
* @license MIT
*/
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = ... |
// this was a test constructor niall built, when active, it prints after 5 seconds all beans/components that are
// not destroyed. to use, create a new grid, then api.destroy() before 5 seconds. then anything that gets printed
// points to a bean or component that was not properly disposed of.
// const... | {
var _this = this;
this.destroyFunctions = [];
this.destroyed = false;
// for vue 3 - prevents Vue from trying to make this (and obviously any sub classes) from being reactive
// prevents vue from creating proxies for created objects and prevents identity related issues
... | identifier_body |
beanStub.js | /**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v25.0.1
* @link http://www.ag-grid.com/
* @license MIT
*/
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = ... | () {
var _this = this;
this.destroyFunctions = [];
this.destroyed = false;
// for vue 3 - prevents Vue from trying to make this (and obviously any sub classes) from being reactive
// prevents vue from creating proxies for created objects and prevents identity related issues
... | BeanStub | identifier_name |
cds.js | /**
* Copyright 2014 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applic... |
// @codekit-append 'helper/event-publisher.js'
// @codekit-append 'helper/util.js'
// @codekit-append 'helper/history.js'
// @codekit-append 'helper/analytics.js'
// @codekit-append 'helper/theme.js'
// @codekit-append 'helper/video-embedder.js'
// @codekit-append 'components/button.js'
// @codekit-append 'components... | random_line_split | |
dircolors.rs | source code.
//
extern crate glob;
#[macro_use]
extern crate uucore;
use std::fs::File;
use std::io::{BufRead, BufReader, Write};
use std::borrow::Borrow;
use std::env;
static SYNTAX: &'static str = "[OPTION]... [FILE]";
static SUMMARY: &'static str = "Output commands to set the LS_COLORS environment variable."; ... | fnmatch(&self, pat: &str) -> bool {
pat.parse::<glob::Pattern>().unwrap().matches(self)
}
}
#[derive(PartialEq)]
enum ParseState {
Global,
Matched,
Continue,
Pass,
}
use std::collections::HashMap;
fn parse<T>(lines: T, fmt: OutputFmt, fp: &str) -> Result<String, String>
where T: IntoIt... | if let Some(b) = self.find(char::is_whitespace) {
let key = &self[..b];
if let Some(e) = self[b..].find(|c: char| !c.is_whitespace()) {
(key, &self[b + e..])
} else {
(key, "")
}
} else {
("", "")
}
}
... | identifier_body |
dircolors.rs | source code.
//
extern crate glob;
#[macro_use]
extern crate uucore;
use std::fs::File;
use std::io::{BufRead, BufReader, Write};
use std::borrow::Borrow;
use std::env;
static SYNTAX: &'static str = "[OPTION]... [FILE]";
static SUMMARY: &'static str = "Output commands to set the LS_COLORS environment variable."; ... | println!("{}", INTERNAL_DB);
return 0;
}
let mut out_format = OutputFmt::Unknown;
if matches.opt_present("csh") || matches.opt_present("c-shell") {
out_format = OutputFmt::CShell;
} else if matches.opt_present("sh") || matches.opt_present("bourne-shell") {
out_format = Outp... | {
disp_err!("extra operand ‘{}’\nfile operands cannot be combined with \
--print-database (-p)",
matches.free[0]);
return 1;
}
| conditional_block |
dircolors.rs | this source code.
//
extern crate glob;
#[macro_use]
extern crate uucore;
use std::fs::File;
use std::io::{BufRead, BufReader, Write};
use std::borrow::Borrow;
use std::env;
static SYNTAX: &'static str = "[OPTION]... [FILE]";
static SUMMARY: &'static str = "Output commands to set the LS_COLORS environment variabl... | }
match File::open(matches.free[0].as_str()) {
Ok(f) => {
let fin = BufReader::new(f);
result = parse(fin.lines().filter_map(|l| l.ok()),
out_format,
matches.free[0].as_str())
}
... | } else {
if matches.free.len() > 1 {
disp_err!("extra operand ‘{}’", matches.free[1]);
return 1; | random_line_split |
dircolors.rs | source code.
//
extern crate glob;
#[macro_use]
extern crate uucore;
use std::fs::File;
use std::io::{BufRead, BufReader, Write};
use std::borrow::Borrow;
use std::env;
static SYNTAX: &'static str = "[OPTION]... [FILE]";
static SUMMARY: &'static str = "Output commands to set the LS_COLORS environment variable."; ... | -> &Self {
let mut line = self;
for (n, c) in self.chars().enumerate() {
if c != '#' {
continue;
}
// Ignore if '#' is at the beginning of line
if n == 0 {
line = &self[..0];
break;
}
... | self) | identifier_name |
event_loop.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/. */
//! This module contains the `EventLoop` type, which is the constellation's
//! view of a script thread. When an `... | (&mut self) {
let _ = self.script_chan.send(ConstellationControlMsg::ExitScriptThread);
}
}
impl EventLoop {
/// Create a new event loop from the channel to its script thread.
pub fn new(script_chan: IpcSender<ConstellationControlMsg>) -> Rc<EventLoop> {
Rc::new(EventLoop {
scri... | drop | identifier_name |
event_loop.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/. */
//! This module contains the `EventLoop` type, which is the constellation's
//! view of a script thread. When an `... |
/// Send a message to the event loop.
pub fn send(&self, msg: ConstellationControlMsg) -> Result<(), IOError> {
self.script_chan.send(msg)
}
/// The underlying channel to the script thread.
pub fn sender(&self) -> IpcSender<ConstellationControlMsg> {
self.script_chan.clone()
}... | {
Rc::new(EventLoop {
script_chan: script_chan,
dont_send_or_sync: PhantomData,
})
} | identifier_body |
event_loop.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/. */
//! This module contains the `EventLoop` type, which is the constellation's
//! view of a script thread. When an `... | /// https://html.spec.whatwg.org/multipage/#event-loop
pub struct EventLoop {
script_chan: IpcSender<ConstellationControlMsg>,
dont_send_or_sync: PhantomData<Rc<()>>,
}
impl Drop for EventLoop {
fn drop(&mut self) {
let _ = self.script_chan.send(ConstellationControlMsg::ExitScriptThread);
}
}
... | use std::marker::PhantomData;
use std::rc::Rc;
| random_line_split |
joiner.rs | // Exercise 2.3
// I were better to be eaten to death with a rust than to be scoured to nothing with perpetual motion.
use std::os;
use std::io::File;
fn xor(a: &[u8], b: &[u8]) -> ~[u8] {
let mut ret = ~[];
for i in range(0, a.len()) {
ret.push(a[i] ^ b[i]);
}
ret
}
fn main() | }
}
}
| {
let args: ~[~str] = os::args();
if args.len() != 3 {
println!("Usage: {:s} <inputfile1> <inputfile2>", args[0]);
} else {
let fname1 = &args[1];
let fname2 = &args[2];
let path1 = Path::new(fname1.clone());
let path2 = Path::new(fname2.clone());
let share_f... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.