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
tag.rs
// Copyright 2016 Jeremy Letang. // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to ...
(db: &mut PgConnection, get_id: &str) -> Result<Tag, DieselError> { use diesel::{LoadDsl, FilterDsl, ExpressionMethods}; use db::schemas::tags::dsl::{tags, id}; tags.filter(id.eq(get_id)).first::<Tag>(db) } pub fn get_from_name_and_user_id(db: &mut PgConnection, get_name: &str, get_user_id: &str) -> Result...
get
identifier_name
tag.rs
// Copyright 2016 Jeremy Letang. // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to ...
pub fn get_all(db: &mut PgConnection, ids: &[String]) -> Result<Vec<Tag>, DieselError> { use diesel::{LoadDsl, FilterDsl, ExpressionMethods}; use db::schemas::tags::dsl::{tags, id}; use diesel::pg::expression::dsl::any; tags.filter(id.eq(any(ids))) .load::<Tag>(db) }
random_line_split
ImprovementCardServiceSpec.ts
// Copyright 2019 The Oppia Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by ap...
}); }); }); describe('.fetchCards', function() { // Each individual factory should test their own fetchCards function. describe('from factories which all return empty cards', function() { beforeEach(function() { this.expectedFactories.forEach(function(factory) { spyOn(fac...
random_line_split
run_lighthouse_tests.py
# Copyright 2020 The Oppia Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable ...
elif 'story_editor' in line: os.environ['story_id'] = url_parts[4] elif 'skill_editor' in line: os.environ['skill_id'] = url_parts[4] def run_lighthouse_checks(lighthouse_mode, shard): """Runs the Lighthouse checks through the Lighthouse config. Args: lighthouse_mode: str. Re...
os.environ['topic_id'] = url_parts[4]
conditional_block
run_lighthouse_tests.py
# Copyright 2020 The Oppia Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable ...
(): """Runs puppeteer script to collect dynamic urls.""" puppeteer_path = ( os.path.join('core', 'tests', 'puppeteer', 'lighthouse_setup.js')) bash_command = [common.NODE_BIN_PATH, puppeteer_path] process = subprocess.Popen( bash_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) ...
run_lighthouse_puppeteer_script
identifier_name
run_lighthouse_tests.py
# Copyright 2020 The Oppia Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable ...
def run_lighthouse_checks(lighthouse_mode, shard): """Runs the Lighthouse checks through the Lighthouse config. Args: lighthouse_mode: str. Represents whether the lighthouse checks are in accessibility mode or performance mode. shard: str. Specifies which shard of the tests shoul...
"""Exports the entity ID in the given line to an environment variable, if the line is a URL. Args: line: str. The line to parse and extract the entity ID from. If no recognizable URL is present, nothing is exported to the environment. """ url_parts = line.split('/') ...
identifier_body
run_lighthouse_tests.py
# Copyright 2020 The Oppia Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable ...
stack.enter_context(servers.managed_dev_appserver( APP_YAML_FILENAMES[server_mode], port=GOOGLE_APP_ENGINE_PORT, log_level='critical', skip_sdk_update_check=True)) run_lighthouse_puppeteer_script() run_lighthouse_checks(lighthouse_mode, parsed_arg...
stack.enter_context(servers.managed_firebase_auth_emulator()) stack.enter_context(servers.managed_cloud_datastore_emulator())
random_line_split
serialize.py
# encoding=utf-8 from .types.compound import ( ModelType, EMPTY_LIST, EMPTY_DICT, MultiType ) import collections import itertools ### ### Field ACL's ### class Role(collections.Set): """A Role object can be used to filter specific fields against a sequence. The Role has a set of names and one function ...
def __len__(self): return len(self.fields) def __eq__(self, other): return (self.function.func_name == other.function.func_name and self.fields == other.fields) def __str__(self): return '%s(%s)' % (self.function.func_name, ', '.join("'%s'" % f for f in self...
random_line_split
serialize.py
# encoding=utf-8 from .types.compound import ( ModelType, EMPTY_LIST, EMPTY_DICT, MultiType ) import collections import itertools ### ### Field ACL's ### class Role(collections.Set): """A Role object can be used to filter specific fields against a sequence. The Role has a set of names and one function ...
(o, prefix=None, ignore_none=True): if hasattr(o, "iteritems"): iterator = o.iteritems() else: iterator = enumerate(o) flat_dict = {} for k, v in iterator: if prefix: key = ".".join(map(unicode, (prefix, k))) else: key = k if v == []: ...
flatten_to_dict
identifier_name
serialize.py
# encoding=utf-8 from .types.compound import ( ModelType, EMPTY_LIST, EMPTY_DICT, MultiType ) import collections import itertools ### ### Field ACL's ### class Role(collections.Set): """A Role object can be used to filter specific fields against a sequence. The Role has a set of names and one function ...
def __iter__(self): return iter(self.fields) def __len__(self): return len(self.fields) def __eq__(self, other): return (self.function.func_name == other.function.func_name and self.fields == other.fields) def __str__(self): return '%s(%s)' % (self.functi...
return value in self.fields
identifier_body
serialize.py
# encoding=utf-8 from .types.compound import ( ModelType, EMPTY_LIST, EMPTY_DICT, MultiType ) import collections import itertools ### ### Field ACL's ### class Role(collections.Set): """A Role object can be used to filter specific fields against a sequence. The Role has a set of names and one function ...
return allowed def apply_shape(cls, instance_or_dict, role, field_converter, model_converter, raise_error_on_role=False, include_serializables=True): """ The apply shape function is intended to be a general loop definition that can be used for any form of data shaping, such as applica...
allowed = field.serialize_when_none
conditional_block
main.rs
use std::io; use std::io::Write; use std::f64::consts::PI; // We can use std::f32::consts::PI if using float fn
() { let mut side_1: String = String::new(); let mut side_2: String = String::new(); let mut angle: String = String::new(); print!("Enter first side length: "); io::stdout().flush().unwrap(); io::stdin().read_line(&mut side_1) .expect("Failed to read"); print!("Enter second side le...
main
identifier_name
main.rs
use std::io; use std::io::Write; use std::f64::consts::PI; // We can use std::f32::consts::PI if using float fn main() { let mut side_1: String = String::new(); let mut side_2: String = String::new(); let mut angle: String = String::new(); print!("Enter first side length: "); io::stdout().flush()....
print!("Enter the angle: "); io::stdout().flush().unwrap(); io::stdin().read_line(&mut angle) .expect("Failed to read"); let side_1: f64 = side_1.trim().parse() .expect("Parsing error"); let side_2: f64 = side_2.trim().parse() .expect("Parsing error"); let angle: f64 = ...
io::stdout().flush().unwrap(); io::stdin().read_line(&mut side_2) .expect("Failed to read");
random_line_split
main.rs
use std::io; use std::io::Write; use std::f64::consts::PI; // We can use std::f32::consts::PI if using float fn main()
let side_1: f64 = side_1.trim().parse() .expect("Parsing error"); let side_2: f64 = side_2.trim().parse() .expect("Parsing error"); let angle: f64 = angle.trim().parse() .expect("Parsing error"); // I have to calculate and write the type the pi angle first before "sin" it let...
{ let mut side_1: String = String::new(); let mut side_2: String = String::new(); let mut angle: String = String::new(); print!("Enter first side length: "); io::stdout().flush().unwrap(); io::stdin().read_line(&mut side_1) .expect("Failed to read"); print!("Enter second side lengt...
identifier_body
migration.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # 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...
# TODO(jkoelker) When migrate 0.7.3 is released and nova depends # on that version or higher, this can be removed MIN_PKG_VERSION = dist_version.StrictVersion('0.7.3') if (not hasattr(migrate, '__version__') or dist_version.StrictVersion(migrate.__version__) < MIN_PKG_VERSION): migrate...
url = a[0] engine = migrate_util.construct_engine(url, **kw) try: kw['engine'] = engine return f(*a, **kw) finally: if isinstance(engine, migrate_util.Engine) and engine is not url: migrate_util.log.debug('Disposing SQLAlchemy engine %s', engine) engine.dispos...
identifier_body
migration.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific langu...
# 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 #
random_line_split
migration.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # 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...
(): """Get the path for the migrate repository.""" path = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'migrate_repo') assert os.path.exists(path) global _REPOSITORY if _REPOSITORY is None: _REPOSITORY = Repository(path) return _REPOSITORY
_find_migrate_repo
identifier_name
migration.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # 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...
return _REPOSITORY
_REPOSITORY = Repository(path)
conditional_block
smartHomeV3.js
var express = require('express'); var hsv = require("hsv-rgb"); var fs = require('fs'); var profile = require('../modules/profile'); var milight = require('../modules/milight-controller.js'); var harmony = require('../modules/harmony-controller.js'); var tplink = require('../modules/hs100-controller'); var blinkstick...
response = constructResponse(event, "color", color); } } if(endpoint === 'ikea-led') { var color = event.directive.payload.color; var h = color.hue; var s = Math.floor(color.saturation * 100); var b = Math.floor(color.brightness * 100); var rgb = hsv(h, s, b); led.setColor(rgb...
{ // Set to provided Colour milight.colorHsv([color.hue, color.saturation, color.brightness]); }
conditional_block
smartHomeV3.js
var express = require('express'); var hsv = require("hsv-rgb"); var fs = require('fs'); var profile = require('../modules/profile'); var milight = require('../modules/milight-controller.js'); var harmony = require('../modules/harmony-controller.js'); var tplink = require('../modules/hs100-controller'); var blinkstick...
var response = constructError(event); var endpoint = event.directive.endpoint.endpointId; if(endpoint === 'milights') { milight.setIp(event.directive.endpoint.cookie.ip); if(event.directive.header.name === "SetBrightness") { var brightnessPercentage = event.directive.payload.brightness; mil...
// default to error
random_line_split
h.ts
import createVNode from './create-vnode' import createVText from './create-vtext' import { createVoid } from './create-void' import { Props, VirtualChildren, VirtualNode, isValidElement, EMPTY_CHILDREN, VNode } from 'nerv-shared' import { isString, isArray, isNumber } from 'nerv-utils' function h (type: st...
( childNodes: VirtualNode[], children: VirtualNode | VirtualNode[], type: string ) { if (isString(children) || isNumber(children)) { childNodes.push(createVText(String(children))) } else if (isValidElement(children)) { childNodes.push(children) } else if (isArray(children)) { for (let i = 0; i ...
addChildren
identifier_name
h.ts
import createVNode from './create-vnode' import createVText from './create-vtext' import { createVoid } from './create-void' import { Props, VirtualChildren, VirtualNode, isValidElement, EMPTY_CHILDREN, VNode } from 'nerv-shared' import { isString, isArray, isNumber } from 'nerv-utils' function h (type: st...
props.key, props.namespace, props.owner, props.ref ) as VNode } function addChildren ( childNodes: VirtualNode[], children: VirtualNode | VirtualNode[], type: string ) { if (isString(children) || isNumber(children)) { childNodes.push(createVText(String(children))) } else if (isValidEle...
{ let childNodes if (props.children) { if (!children) { children = props.children } } if (isArray(children)) { childNodes = [] addChildren(childNodes, children as any, type) } else if (isString(children) || isNumber(children)) { children = createVText(String(children)) } else if (!...
identifier_body
h.ts
import createVNode from './create-vnode' import createVText from './create-vtext' import { createVoid } from './create-void' import { Props, VirtualChildren, VirtualNode, isValidElement, EMPTY_CHILDREN, VNode } from 'nerv-shared' import { isString, isArray, isNumber } from 'nerv-utils'
function h (type: string, props: Props, children?: VirtualChildren) { let childNodes if (props.children) { if (!children) { children = props.children } } if (isArray(children)) { childNodes = [] addChildren(childNodes, children as any, type) } else if (isString(children) || isNumber(chil...
random_line_split
string-length.example.ts
import { StringLength } from '../../src/property-decorators'; export class
{ @StringLength({ min: 2 }) minLength: string = 'AB'; @StringLength({ max: 5 }) maxLength: string = 'ABCDE'; @StringLength({ min: 2, max: 5, throwError: true }) wideRange: string; @StringLength({ min: 2, max: 5, allowNulls: true }) wideRange2: string; } let exampleClass = new Stri...
StringLengthExampleClass
identifier_name
string-length.example.ts
import { StringLength } from '../../src/property-decorators'; export class StringLengthExampleClass { @StringLength({ min: 2 }) minLength: string = 'AB'; @StringLength({ max: 5 })
@StringLength({ min: 2, max: 5, throwError: true }) wideRange: string; @StringLength({ min: 2, max: 5, allowNulls: true }) wideRange2: string; } let exampleClass = new StringLengthExampleClass(); exampleClass.minLength = 'ABC'; console.log('\nMinLength after assign "ABC": ', exampleClass.minLength); ...
maxLength: string = 'ABCDE';
random_line_split
log.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version....
pub block_hash: H256, #[serde(rename="blockNumber")] pub block_number: U256, #[serde(rename="transactionHash")] pub transaction_hash: H256, #[serde(rename="transactionIndex")] pub transaction_index: U256, #[serde(rename="logIndex")] pub log_index: U256, } impl From<LocalizedLogEntry> for Log { fn from(e: Loc...
pub struct Log { pub address: Address, pub topics: Vec<H256>, pub data: Bytes, #[serde(rename="blockHash")]
random_line_split
log.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version....
(e: LocalizedLogEntry) -> Log { Log { address: e.entry.address, topics: e.entry.topics, data: Bytes::new(e.entry.data), block_hash: e.block_hash, block_number: From::from(e.block_number), transaction_hash: e.transaction_hash, transaction_index: From::from(e.transaction_index), log_index: From:...
from
identifier_name
ActivityWithRemarks.tsx
import * as React from 'react' import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' import { classes } from '@framework/Globals' import { Lite } from '@framework/Signum.Entities' import { CaseActivityMessage, CaseNotificationEntity, CaseNotificationOperation, CaseActivityEntity, WorkflowActivityEntity, ...
(e: React.MouseEvent<any>) { e.preventDefault(); var fo: FindOptions = { queryName: AlertEntity, filterOptions: [ { token: AlertEntity.token(a => a.target), value: p.data.caseActivity }, { token: AlertEntity.token().entity(e => e.recipient), value: AppContext.currentUser }, ...
handleAlertsClick
identifier_name
ActivityWithRemarks.tsx
import * as React from 'react' import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' import { classes } from '@framework/Globals' import { Lite } from '@framework/Signum.Entities' import { CaseActivityMessage, CaseNotificationEntity, CaseNotificationOperation, CaseActivityEntity, WorkflowActivityEntity, ...
function handleRemarksClick(e: React.MouseEvent<any>) { e.preventDefault(); ValueLineModal.show({ type: { name: "string" }, valueLineType: "TextArea", title: CaseNotificationEntity.nicePropertyName(a => a.remarks), message: CaseActivityMessage.PersonalRemarksForThisNotifica...
{ e.preventDefault(); var fo: FindOptions = { queryName: AlertEntity, filterOptions: [ { token: AlertEntity.token(a => a.target), value: p.data.caseActivity }, { token: AlertEntity.token().entity(e => e.recipient), value: AppContext.currentUser }, { token: AlertEntit...
identifier_body
ActivityWithRemarks.tsx
import * as React from 'react' import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' import { classes } from '@framework/Globals' import { Lite } from '@framework/Signum.Entities' import { CaseActivityMessage, CaseNotificationEntity, CaseNotificationOperation, CaseActivityEntity, WorkflowActivityEntity, ...
title: CaseNotificationEntity.nicePropertyName(a => a.remarks), message: CaseActivityMessage.PersonalRemarksForThisNotification.niceToString(), labelText: undefined, initialValue: remarks, initiallyFocused: true }).then(remarks => { if (remarks === undefined) ret...
e.preventDefault(); ValueLineModal.show({ type: { name: "string" }, valueLineType: "TextArea",
random_line_split
skills.py
import dices class skill(object): """ Contains a skill. calling is done by skill(bases,value,known=True) bases::string : attributes it depends on. (either ABCx2 or ABC+XYZ format) value: value of the skill. If left empty, standard is calculated. study(learned) --> learned is added to the valu...
"Drive": skill("DEX+POW"), "Endurance": skill("CONx2", encaffect=False), "Evade": skill("DEXx2"), "FirstAid": skill("INT+DEX"), "Influence": skill("CHAx2", encaffect=False), "Insight": skill("INT+POW", encaffect=False), "Locale": skill("INTx2", encaffect=False), "Perception": skill("INT+...
"Customs": skill("INTx2", encaffect=False), "Dance": skill("DEX+CHA"), "Deceit": skill("INT+CHA", encaffect=False),
random_line_split
skills.py
import dices class skill(object):
def basevalue(self, inp): self.value = 0 self.value = inp # TODO decide how to do this def study(self, learned): self.value += learned # now the skills as a class is generated # the next step is creating all the skills standardlist = { "Athletics": skill("STR+DEX"), "Boat...
""" Contains a skill. calling is done by skill(bases,value,known=True) bases::string : attributes it depends on. (either ABCx2 or ABC+XYZ format) value: value of the skill. If left empty, standard is calculated. study(learned) --> learned is added to the value of the skill. learn --> teaches th...
identifier_body
skills.py
import dices class skill(object): """ Contains a skill. calling is done by skill(bases,value,known=True) bases::string : attributes it depends on. (either ABCx2 or ABC+XYZ format) value: value of the skill. If left empty, standard is calculated. study(learned) --> learned is added to the valu...
(self, *args): global professionallist for element in args: if element in self: print element, "is already in the learned skills list", \ ", it was not added to protect the value" else: try: self[element] = p...
learn
identifier_name
skills.py
import dices class skill(object): """ Contains a skill. calling is done by skill(bases,value,known=True) bases::string : attributes it depends on. (either ABCx2 or ABC+XYZ format) value: value of the skill. If left empty, standard is calculated. study(learned) --> learned is added to the valu...
def basevalue(self, inp): self.value = 0 self.value = inp # TODO decide how to do this def study(self, learned): self.value += learned # now the skills as a class is generated # the next step is creating all the skills standardlist = { "Athletics": skill("STR+DEX"), "Boat...
self.base[1] = bases[-3:]
conditional_block
setup.py
# # Copyright (c) 2013 Christopher L. Felton # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This p...
def find_packages(): return list(_find_packages(mn.__path__, mn.__name__)) setup(name = "minnesota", version = "0.1pre", description = "collection of HDL cores ", license = "LGPL", platforms = ["Any"], keywords = "DSP HDL M...
yield prefix prefix = prefix + "." for _, name, ispkg in walk_packages(path, prefix, onerror=lambda x: x): if ispkg: yield name
identifier_body
setup.py
# # Copyright (c) 2013 Christopher L. Felton # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This p...
# many pypy installs don't have setuptools (?) def _find_packages(path='.', prefix=''): yield prefix prefix = prefix + "." for _, name, ispkg in walk_packages(path, prefix, onerror=lambda x: ...
import mn
random_line_split
setup.py
# # Copyright (c) 2013 Christopher L. Felton # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This p...
(path='.', prefix=''): yield prefix prefix = prefix + "." for _, name, ispkg in walk_packages(path, prefix, onerror=lambda x: x): if ispkg: yield name ...
_find_packages
identifier_name
setup.py
# # Copyright (c) 2013 Christopher L. Felton # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This p...
def find_packages(): return list(_find_packages(mn.__path__, mn.__name__)) setup(name = "minnesota", version = "0.1pre", description = "collection of HDL cores ", license = "LGPL", platforms = ["Any"], keywords = "DSP HDL M...
if ispkg: yield name
conditional_block
__init__.py
# Copyright (c) 2021, DjaoDjin Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and t...
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. __version__ = '0.6.4-dev'
# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR # OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
random_line_split
nose_suite.py
""" Classes used for defining and running nose test suites """ import os from paver.easy import call_task from pavelib.utils.test import utils as test_utils from pavelib.utils.test.suites import TestSuite from pavelib.utils.envs import Env __test__ = False # do not collect class NoseTestSuite(TestSuite): """ ...
cmd = ( "python -m coverage run --rcfile={root}/.coveragerc " "{cmd0} {cmd_rest}".format( root=self.root, cmd0=cmd0, cmd_rest=cmd_rest, ) ) return cmd @property def tes...
cmd0 = "`which {}`".format(cmd0)
conditional_block
nose_suite.py
""" Classes used for defining and running nose test suites """ import os from paver.easy import call_task from pavelib.utils.test import utils as test_utils from pavelib.utils.test.suites import TestSuite from pavelib.utils.envs import Env __test__ = False # do not collect class NoseTestSuite(TestSuite): """ ...
) ) return self._under_coverage_cmd(cmd) @property def _default_test_id(self): """ If no test id is provided, we need to limit the test runner to the Djangoapps we want to test. Otherwise, it will run tests on all installed packages. We do this by ...
""" TestSuite for lms and cms nosetests """ def __init__(self, *args, **kwargs): super(SystemTestSuite, self).__init__(*args, **kwargs) self.test_id = kwargs.get('test_id', self._default_test_id) self.fasttest = kwargs.get('fasttest', False) def __enter__(self): super(Sy...
identifier_body
nose_suite.py
""" Classes used for defining and running nose test suites """ import os from paver.easy import call_task from pavelib.utils.test import utils as test_utils from pavelib.utils.test.suites import TestSuite from pavelib.utils.envs import Env __test__ = False # do not collect class NoseTestSuite(TestSuite): """ ...
(self): super(SystemTestSuite, self).__enter__() @property def cmd(self): cmd = ( './manage.py {system} test --verbosity={verbosity} ' '{test_id} {test_opts} --traceback --settings=test'.format( system=self.root, verbosity=self.verbosity, ...
__enter__
identifier_name
nose_suite.py
""" Classes used for defining and running nose test suites """ import os from paver.easy import call_task from pavelib.utils.test import utils as test_utils from pavelib.utils.test.suites import TestSuite from pavelib.utils.envs import Env __test__ = False # do not collect class NoseTestSuite(TestSuite): """ ...
def test_options_flags(self): """ Takes the test options and returns the appropriate flags for the command. """ opts = " " # Handle "--failed" as a special case: we want to re-run only # the tests that failed within our Django apps # This sets the --f...
) return cmd @property
random_line_split
uniform-snapshot.ts
import Snapshot from './snapshot'; export default class UniformSnapshot extends Snapshot { private readonly values: Array<number>; constructor(values: Array<number>) { super(); this.values = new Array<number>(...values).sort(); } getValue(quantile: number): number { if (quantile < 0.0 || quantil...
return sum / this.values.length; } getMin(): number { if (this.values.length === 0) { return 0; } return this.values[0]; } getStdDev(): number { if (this.values.length <= 1) { return 0; } const mean = this.getMean(); const sum = this.values.reduce((acc, val) => ...
const sum = this.values.reduce((acc, val) => acc + val, 0);
random_line_split
uniform-snapshot.ts
import Snapshot from './snapshot'; export default class UniformSnapshot extends Snapshot { private readonly values: Array<number>; constructor(values: Array<number>) { super(); this.values = new Array<number>(...values).sort(); } getValue(quantile: number): number { if (quantile < 0.0 || quantil...
return this.values[0]; } getStdDev(): number { if (this.values.length <= 1) { return 0; } const mean = this.getMean(); const sum = this.values.reduce((acc, val) => { const diff = val - mean; return acc + diff * diff; }, 0); const variance = sum / (this.values.len...
{ return 0; }
conditional_block
uniform-snapshot.ts
import Snapshot from './snapshot'; export default class UniformSnapshot extends Snapshot { private readonly values: Array<number>;
(values: Array<number>) { super(); this.values = new Array<number>(...values).sort(); } getValue(quantile: number): number { if (quantile < 0.0 || quantile > 1.0 || isNaN(quantile)) { throw new Error(`${quantile} is not in [0..1]`); } if (this.values.length === 0) { return 0; ...
constructor
identifier_name
uniform-snapshot.ts
import Snapshot from './snapshot'; export default class UniformSnapshot extends Snapshot { private readonly values: Array<number>; constructor(values: Array<number>) { super(); this.values = new Array<number>(...values).sort(); } getValue(quantile: number): number { if (quantile < 0.0 || quantil...
size(): number { return this.values.length; } getMax(): number { if (this.values.length === 0) { return 0; } return this.values[this.values.length - 1]; } getMean(): number { if (this.values.length === 0) { return 0; } const sum = this.values.reduce((acc, val) => ...
{ return new Array<number>(...this.values); }
identifier_body
element_test.rs
use rquery::Document; fn new_document() -> Document { Document::new_from_xml_string(r#" <?xml version="1.0" encoding="UTF-8"?> <main type="simple"> This is some text </main> "#).unwrap() } #[test] fn it_knows_its_tag_name() { let document = new_document(); let element = document.select("main").unwrap(...
let element = document.select("main").unwrap(); assert_eq!(element.text().trim(), "This is some text"); } #[test] fn it_knows_its_node_indices() { let document = new_document(); let element = document.select("main").unwrap(); assert_eq!(element.node_index(), 1); }
let document = new_document();
random_line_split
element_test.rs
use rquery::Document; fn new_document() -> Document { Document::new_from_xml_string(r#" <?xml version="1.0" encoding="UTF-8"?> <main type="simple"> This is some text </main> "#).unwrap() } #[test] fn it_knows_its_tag_name() { let document = new_document(); let element = document.select("main").unwrap(...
() { let document = new_document(); let element = document.select("main").unwrap(); assert_eq!(element.node_index(), 1); }
it_knows_its_node_indices
identifier_name
element_test.rs
use rquery::Document; fn new_document() -> Document { Document::new_from_xml_string(r#" <?xml version="1.0" encoding="UTF-8"?> <main type="simple"> This is some text </main> "#).unwrap() } #[test] fn it_knows_its_tag_name() { let document = new_document(); let element = document.select("main").unwrap(...
#[test] fn it_knows_its_inner_text_contents() { let document = new_document(); let element = document.select("main").unwrap(); assert_eq!(element.text().trim(), "This is some text"); } #[test] fn it_knows_its_node_indices() { let document = new_document(); let element = document.select("ma...
{ let document = new_document(); let element = document.select("main").unwrap(); assert_eq!(element.attr("type").unwrap(), "simple"); }
identifier_body
testBuild.watch.ts
import webpack from 'webpack'; import webpackConfig from '../webpack.config.test'; import colors from 'colors'; colors; process.env.NODE_ENV = 'production'; console.log('Generating minified bundle for production via Webpack. This will take a moment..'.blue); webpack(webpackConfig).watch({},(err, stats) => { if (e...
if (jsonStats.hasWarnings) { console.log('Webpack generated the following warnings: '.yellow); jsonStats.warnings.map(warning => console.log(warning.yellow)); } // console.log(`Webpack stats: ${stats}`); console.log('Your tests has been compiled in production mode and written to /tests. Is\'s ready ...
{ return jsonStats.errors.map(error => console.log(error.red)); }
conditional_block
testBuild.watch.ts
import webpack from 'webpack'; import webpackConfig from '../webpack.config.test'; import colors from 'colors'; colors; process.env.NODE_ENV = 'production'; console.log('Generating minified bundle for production via Webpack. This will take a moment..'.blue); webpack(webpackConfig).watch({},(err, stats) => { if (e...
if (jsonStats.hasWarnings) { console.log('Webpack generated the following warnings: '.yellow); jsonStats.warnings.map(warning => console.log(warning.yellow)); } // console.log(`Webpack stats: ${stats}`); console.log('Your tests has been compiled in production mode and written to /tests. Is\'s ready to...
random_line_split
application_gateway_web_application_firewall_configuration.py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
(self, **kwargs): super(ApplicationGatewayWebApplicationFirewallConfiguration, self).__init__(**kwargs) self.enabled = kwargs.get('enabled', None) self.firewall_mode = kwargs.get('firewall_mode', None) self.rule_set_type = kwargs.get('rule_set_type', None) self.rule_set_version =...
__init__
identifier_name
application_gateway_web_application_firewall_configuration.py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
from msrest.serialization import Model class ApplicationGatewayWebApplicationFirewallConfiguration(Model): """Application gateway web application firewall configuration. All required parameters must be populated in order to send to Azure. :param enabled: Required. Whether the web application firewall i...
# regenerated. # --------------------------------------------------------------------------
random_line_split
application_gateway_web_application_firewall_configuration.py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
super(ApplicationGatewayWebApplicationFirewallConfiguration, self).__init__(**kwargs) self.enabled = kwargs.get('enabled', None) self.firewall_mode = kwargs.get('firewall_mode', None) self.rule_set_type = kwargs.get('rule_set_type', None) self.rule_set_version = kwargs.get('rule_set_vers...
identifier_body
sananmuunnos.py
#!/usr/bin/envpython #-*- coding: utf-8 -*- """ Sananmuunnos: Transforming Finnish spoonerisms made easy (and systematic). """ __author__ = "Tuukka Ojala" __email__ = "tuukka.ojala@gmail.com" __version__ = "2015.0918" __license__ = "MIT" import re #Regular expressions for detecting different types of sananmuunnose...
tion, word1, word2): """Tries transforming word1 and word2 with the given transform function. It tries swapping the words if the transformation fails. This function returnsthe transformed words or false if the transformation failed both ways.""" result = transformation(word1, word2) if not ...
make the given word comply with Finnish vowel harmony. If the first vowel of the word is a front vowel (a, o or u) all the vowels get transformed to their equivalent back vowels (ä, ö, y) and vice versa.""" vowel = _vowel.search(word) if vowel and word[vowel.start()] in ["a","o","u"]: word...
identifier_body
sananmuunnos.py
#!/usr/bin/envpython #-*- coding: utf-8 -*- """ Sananmuunnos: Transforming Finnish spoonerisms made easy (and systematic). """ __author__ = "Tuukka Ojala" __email__ = "tuukka.ojala@gmail.com" __version__ = "2015.0918" __license__ = "MIT" import re #Regular expressions for detecting different types of sananmuunnose...
return (result[1], result[0]) return result def transform(words): """Make a sananmuunnos ("word transformation") out of the given words. This function returns either the created sananmuunnos or None if the transformation failed.""" transformed = None words = words.lower() w...
result = transformation(word2, word1) if result:
random_line_split
sananmuunnos.py
#!/usr/bin/envpython #-*- coding: utf-8 -*- """ Sananmuunnos: Transforming Finnish spoonerisms made easy (and systematic). """ __author__ = "Tuukka Ojala" __email__ = "tuukka.ojala@gmail.com" __version__ = "2015.0918" __license__ = "MIT" import re #Regular expressions for detecting different types of sananmuunnose...
, word2): """Tries transforming word1 and word2 with the given transform function. It tries swapping the words if the transformation fails. This function returnsthe transformed words or false if the transformation failed both ways.""" result = transformation(word1, word2) if not result: ...
word1
identifier_name
sananmuunnos.py
#!/usr/bin/envpython #-*- coding: utf-8 -*- """ Sananmuunnos: Transforming Finnish spoonerisms made easy (and systematic). """ __author__ = "Tuukka Ojala" __email__ = "tuukka.ojala@gmail.com" __version__ = "2015.0918" __license__ = "MIT" import re #Regular expressions for detecting different types of sananmuunnose...
ial_vowel(word1, word2): """Test word1 and word2 against the "initial vowel" rule.""" if _initial_vowel.search(word1): transformed1 = word2[:2] +word1[1:] transformed2 = word1[0] +word2[2:] return (transformed1, transformed2) else: return False def _is_initial_consonant(word...
def _is_init
conditional_block
dependency_viewer.py
# Opus/UrbanSim urban simulation software. # Copyright (C) 2005-2009 University of Washington # See opus_core/LICENSE import os from PyQt4 import QtGui, Qt, QtCore from opus_gui.general_manager.views.ui_dependency_viewer import Ui_DependencyViewer class
(QtGui.QDialog, Ui_DependencyViewer): def __init__(self, parent_window): flags = QtCore.Qt.WindowTitleHint | QtCore.Qt.WindowSystemMenuHint | QtCore.Qt.WindowMaximizeButtonHint QtGui.QDialog.__init__(self, parent_window, flags) self.setupUi(self) self.setModal(True) #TODO: this sho...
DependencyViewer
identifier_name
dependency_viewer.py
# Opus/UrbanSim urban simulation software. # Copyright (C) 2005-2009 University of Washington # See opus_core/LICENSE import os from PyQt4 import QtGui, Qt, QtCore from opus_gui.general_manager.views.ui_dependency_viewer import Ui_DependencyViewer class DependencyViewer(QtGui.QDialog, Ui_DependencyViewer): def _...
def show_error_message(self): self.lbl_error.setVisible(True) self.scrollArea.setVisible(False) def show_graph(self, file_path, name): self.lbl_error.setVisible(False) self.scrollArea.setVisible(True) self.setWindowTitle("Dependency graph of %s" % name) self.im...
flags = QtCore.Qt.WindowTitleHint | QtCore.Qt.WindowSystemMenuHint | QtCore.Qt.WindowMaximizeButtonHint QtGui.QDialog.__init__(self, parent_window, flags) self.setupUi(self) self.setModal(True) #TODO: this shouldn't be necessary, but without it the window is unresponsive
identifier_body
dependency_viewer.py
# Opus/UrbanSim urban simulation software. # Copyright (C) 2005-2009 University of Washington # See opus_core/LICENSE import os from PyQt4 import QtGui, Qt, QtCore from opus_gui.general_manager.views.ui_dependency_viewer import Ui_DependencyViewer class DependencyViewer(QtGui.QDialog, Ui_DependencyViewer): def _...
rect = Qt.QApplication.desktop().screenGeometry(self) self.resize(min(rect.width(), pix.width() + 35), min(rect.height(), pix.height() + 80)) self.update() def on_closeWindow_released(self): self.close() os.remove(self.image_file)
self.label.setPixmap(pix) self.scrollAreaWidgetContents.setMinimumSize(pix.width(), pix.height()) self.label.setMinimumSize(pix.width(), pix.height())
random_line_split
catrank.rs
// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors // Licensed under the MIT License: // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, inc...
}
{ let mut good_count : i32 = 0; let results = response.get_results()?; for result in results.iter() { if result.get_score() > 1001.0 { good_count += 1; } else { break; } } if good_count == expected_good_count { ...
identifier_body
catrank.rs
// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors // Licensed under the MIT License: // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, inc...
let suffix = rng.next_less_than(20) as usize; for _ in 0..suffix { snippet.push_str(WORDS[rng.next_less_than(WORDS.len() as u32) as usize]); } result.set_snippet(&snippet); } good_count } fn handle_request(&self, request: searc...
{ snippet.push_str("dog ") }
conditional_block
catrank.rs
// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors // Licensed under the MIT License: // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, inc...
(&self, request: search_result_list::Reader, response: search_result_list::Builder) -> ::capnp::Result<()> { let mut scored_results: Vec<ScoredResult> = Vec::new(); let results = request.get_results()?; for i in 0..results.len() { let result = results.get(i...
handle_request
identifier_name
catrank.rs
// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors // Licensed under the MIT License: // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, inc...
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. use common::*; use catrank_capnp::*; #[derive(Clone, Copy)] pub struct ScoredResult<'a> { score: f64, result: search_result::Reader<'a> } const URL_PREFIX: &'static str = "http://example.com"; pub struct CatRank; ...
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
random_line_split
mainmenu-handler.ts
specific language governing permissions and // limitations under the License. import { Injectable } from '@angular/core'; import { AddonMessagesProvider } from './messages'; import { CoreMainMenuHandler, CoreMainMenuHandlerToDisplay } from '@core/mainmenu/providers/delegate'; import { CoreCronHandler } from '@provide...
* @return {boolean} True if is a sync process, false otherwise. */ isSync(): boolean { // This is done to use only wifi if using the fallback function. if (this.appProvider.isDesktop()) { // In desktop it is always sync, since it fetches messages to see if there's a new one. ...
} /** * Whether it's a synchronization process or not. *
random_line_split
mainmenu-handler.ts
language governing permissions and // limitations under the License. import { Injectable } from '@angular/core'; import { AddonMessagesProvider } from './messages'; import { CoreMainMenuHandler, CoreMainMenuHandlerToDisplay } from '@core/mainmenu/providers/delegate'; import { CoreCronHandler } from '@providers/cron';...
/** * Execute the process. * Receives the ID of the site affected, undefined for all sites. * * @param {string} [siteId] ID of the site affected, undefined for all sites. * @param {boolean} [force] Wether the execution is forced (manual sync). * @return {Promise<any>} Promis...
{ const totalCount = this.unreadCount + (this.contactRequestsCount || 0); if (totalCount > 0) { this.handler.badge = totalCount + (this.orMore ? '+' : ''); } else { this.handler.badge = ''; } // Update push notifications badge. this.pushNotificati...
identifier_body
mainmenu-handler.ts
language governing permissions and // limitations under the License. import { Injectable } from '@angular/core'; import { AddonMessagesProvider } from './messages'; import { CoreMainMenuHandler, CoreMainMenuHandlerToDisplay } from '@core/mainmenu/providers/delegate'; import { CoreCronHandler } from '@providers/cron';...
(siteId?: string): Promise<any> { return this.sitesProvider.getSite(siteId).then((site) => { if (site.isVersionGreaterEqualThan('3.7')) { // Use get conversations WS to be able to get group conversations messages. return this.messagesProvider.getConversations(undefin...
fetchMessages
identifier_name
listener.py
#!/usr/bin/python # This file is part of pulseaudio-dlna. # pulseaudio-dlna is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # pulsea...
class SSDPListener(SocketServer.UDPServer): def __init__( self, stream_server_address, message_queue, plugins, device_filter=None, device_config=None, renderer_urls=None, disable_ssdp_listener=False): self.disable_ssdp_listener = disable_ssdp_listener self.rend...
return method_header.split(' ')[0]
identifier_body
listener.py
#!/usr/bin/python # This file is part of pulseaudio-dlna. # pulseaudio-dlna is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # pulsea...
device_filter=None, device_config=None, renderer_urls=None, disable_ssdp_listener=False): self.disable_ssdp_listener = disable_ssdp_listener self.renderer_urls = renderer_urls self.renderers_holder = RendererHolder( stream_server_address, message_queue, plugin...
random_line_split
listener.py
#!/usr/bin/python # This file is part of pulseaudio-dlna. # pulseaudio-dlna is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # pulsea...
class ThreadedSSDPListener(SocketServer.ThreadingMixIn, SSDPListener): pass
setproctitle.setproctitle('ssdp_listener') SocketServer.UDPServer.serve_forever(self)
conditional_block
listener.py
#!/usr/bin/python # This file is part of pulseaudio-dlna. # pulseaudio-dlna is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # pulsea...
(self): if not self.disable_ssdp_listener: setproctitle.setproctitle('ssdp_listener') SocketServer.UDPServer.serve_forever(self) class ThreadedSSDPListener(SocketServer.ThreadingMixIn, SSDPListener): pass
run
identifier_name
utils.ts
const WSP = require('../dist/ws') import axios from 'axios' import * as WS from 'ws' const turnOn = async (port: number = 8095) => { await axios.get('http://127.0.0.1:8085/on/' + port) return true } const shutDown = async (port: number = 8095) => { await axios.get('http://127.0.0.1:8085/off/' + port)
const createNew = async (config = {}, port = 8095): Promise<any> => { await turnOn(port) const ws = new WSP(Object.assign({ url: '127.0.0.1:' + port, // log: (...a) => console.log(...a), adapter: (host, protocols) => new (WS as any)(host, protocols) }, config)) return ws } export { createNew, ...
return true }
random_line_split
PointDistribution.js
/** * This module is used to create different point distributions that can be * turned into different tile sets when made into a graph format. There are * various different distributions that can be used to create interesting * tile patterns when turned into a voronoi diagram. * * @class PointDistribution */ ...
} return points; } /** * Creates a poisson, or blue noise distribution of points in a particular * bounding box with a particular average distance between points. This is * done by using poisson disk sampling which tries to create points so that the * distance between neighbors is as close to a fixed num...
{ // Local bbox for the point to generate in const boxPos = new Vector(x - d + m, y - d + m); pointBox = new Rectangle(boxPos, x - m, y - m); points.push(rng.vector(pointBox)); }
conditional_block
PointDistribution.js
/** * This module is used to create different point distributions that can be * turned into different tile sets when made into a graph format. There are * various different distributions that can be used to create interesting * tile patterns when turned into a voronoi diagram. * * @class PointDistribution */ ...
{ throw "Error: Not Implemented"; }
identifier_body
PointDistribution.js
/** * This module is used to create different point distributions that can be * turned into different tile sets when made into a graph format. There are * various different distributions that can be used to create interesting * tile patterns when turned into a voronoi diagram. * * @class PointDistribution */ ...
var N = Math.sqrt(bbox.area / (d * d)); for (let y = 0; y < N; y++) { for (let x = 0; x < N; x++) { points.push(new Vector((0.5 + x) / N * bbox.width, (0.25 + 0.5 * x % 2 + y) / N * bbox.height)); // points.push(new Vector((y % 2) * dx + x * d + dx, y * d + dy)); ...
let points = []; const altitude = Math.sqrt(3) / 2 * d;
random_line_split
PointDistribution.js
/** * This module is used to create different point distributions that can be * turned into different tile sets when made into a graph format. There are * various different distributions that can be used to create interesting * tile patterns when turned into a voronoi diagram. * * @class PointDistribution */ ...
(bbox, d) { throw "Error: Not Implemented"; } /** * Creates a circular distribution of points in a particular bounding box * with a particular average distance between points. * * @summary Not Implemented Yet * * @export * @param {Rectangle} bbox The bounding box to create the points in * @param {number}...
recursiveWang
identifier_name
_x.py
import _plotly_utils.basevalidators class XValidator(_plotly_utils.basevalidators.CompoundValidator): def __init__(self, plotly_name="x", parent_name="isosurface.caps", **kwargs): super(XValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, data_c...
)
**kwargs
random_line_split
_x.py
import _plotly_utils.basevalidators class XValidator(_plotly_utils.basevalidators.CompoundValidator): def __init__(self, plotly_name="x", parent_name="isosurface.caps", **kwargs):
""", ), **kwargs )
super(XValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, data_class_str=kwargs.pop("data_class_str", "X"), data_docs=kwargs.pop( "data_docs", """ fill Sets the fill ratio of the `caps`....
identifier_body
_x.py
import _plotly_utils.basevalidators class XValidator(_plotly_utils.basevalidators.CompoundValidator): def
(self, plotly_name="x", parent_name="isosurface.caps", **kwargs): super(XValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, data_class_str=kwargs.pop("data_class_str", "X"), data_docs=kwargs.pop( "data_docs", ...
__init__
identifier_name
data_loader.py
import torch import torchvision.transforms as transforms import torch.utils.data as data import os import json import pickle import argparse from PIL import Image import numpy as np from utils import Vocabulary class CocoDataset(data.Dataset): def __init__(self, root, anns, vocab, mode='train',transform=None): ...
def collate_fn(data): # sort the data in descending order data.sort(key=lambda x: len(x[1]), reverse=True) images, captions, imgids = zip(*data) # merge images (from tuple of 3D tensor to 4D tensor). images = torch.stack(images, 0) # merge captions (from tuple of 1D tensor to 2D tensor). ...
return len(self.data)
identifier_body
data_loader.py
import torch import torchvision.transforms as transforms import torch.utils.data as data import os import json import pickle import argparse from PIL import Image import numpy as np from utils import Vocabulary class CocoDataset(data.Dataset): def __init__(self, root, anns, vocab, mode='train',transform=None): ...
return images, targets, lengths, imgids def get_loader(opt, mode='train', shuffle=True, num_workers=1, transform=None): coco = CocoDataset(root=opt.root_dir, anns=opt.data_json, vocab=opt.vocab_path, mode=mode, transf...
end = lengths[i] targets[i, :end] = cap[:end]
conditional_block
data_loader.py
import torch import torchvision.transforms as transforms import torch.utils.data as data import os import json import pickle import argparse from PIL import Image import numpy as np from utils import Vocabulary class CocoDataset(data.Dataset): def __init__(self, root, anns, vocab, mode='train',transform=None): ...
data_loader = get_loader(args, transform=transform) total_iter = len(data_loader) for i, (img, target, length) in enumerate(data_loader): print('done')
transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)) ])
random_line_split
data_loader.py
import torch import torchvision.transforms as transforms import torch.utils.data as data import os import json import pickle import argparse from PIL import Image import numpy as np from utils import Vocabulary class CocoDataset(data.Dataset): def __init__(self, root, anns, vocab, mode='train',transform=None): ...
(self, index): data = self.data vocab = self.vocab # load image path = os.path.join(self.root, data[index]['file_path']) img = Image.open(path).convert('RGB') if self.transform is not None: img = self.transform(img) # load caption cap = data...
__getitem__
identifier_name
gulpfile.js
'use strict'; /** * Import plugins */ var gulp = require('gulp'), $ = require('gulp-load-plugins')(), runSequence = require('run-sequence'), argv = require('yargs').argv, del = require('del'); /** * Build vendors dependencies */ gulp.task('vendors', function() { /** * CSS VENDORS */ ...
browsers: ['last 2 versions', 'safari 5', 'ie 8', 'ie 9', 'ff 27', 'opera 12.1'] })) .pipe($.if(!argv.production, $.sourcemaps.write())) .pipe($.if(argv.production, $.minifyCss())) .pipe(gulp.dest('web/assets/css')); }); /** * Build JS * With error reporting on compiling (s...
})) .pipe($.autoprefixer({
random_line_split
gulpfile.js
'use strict'; /** * Import plugins */ var gulp = require('gulp'), $ = require('gulp-load-plugins')(), runSequence = require('run-sequence'), argv = require('yargs').argv, del = require('del'); /** * Build vendors dependencies */ gulp.task('vendors', function() { /** * CSS VENDORS */ ...
})) .pipe($.autoprefixer({ browsers: ['last 2 versions', 'safari 5', 'ie 8', 'ie 9', 'ff 27', 'opera 12.1'] })) .pipe($.if(!argv.production, $.sourcemaps.write())) .pipe($.if(argv.production, $.minifyCss())) .pipe(gulp.dest('web/assets/css')); }); /** * Buil...
{ return 'Message to the notifier: ' + error.message; }
conditional_block
lib.rs
extern crate warc_parser; extern crate nom; mod tests { use std::fs::File; use std::io::prelude::*; use nom::{Err, IResult, Needed}; fn
(sample_name: &str) -> Vec<u8> { let full_path = "sample/".to_string() + sample_name; let mut f = File::open(full_path).unwrap(); let mut s = Vec::new(); f.read_to_end(&mut s).unwrap(); s } use warc_parser; #[test] fn it_parses_a_plethora() { let example...
read_sample_file
identifier_name
lib.rs
extern crate warc_parser; extern crate nom; mod tests { use std::fs::File; use std::io::prelude::*; use nom::{Err, IResult, Needed}; fn read_sample_file(sample_name: &str) -> Vec<u8> { let full_path = "sample/".to_string() + sample_name; let mut f = File::open(full_path).unwrap(); ...
use warc_parser; #[test] fn it_parses_a_plethora() { let examples = read_sample_file("plethora.warc"); let parsed = warc_parser::records(&examples); assert!(parsed.is_ok()); match parsed { Err(_) => assert!(false), Ok((i, records)) => { ...
random_line_split
lib.rs
extern crate warc_parser; extern crate nom; mod tests { use std::fs::File; use std::io::prelude::*; use nom::{Err, IResult, Needed}; fn read_sample_file(sample_name: &str) -> Vec<u8> { let full_path = "sample/".to_string() + sample_name; let mut f = File::open(full_path).unwrap(); ...
}
{ let bbc = read_sample_file("bbc.warc"); let parsed = warc_parser::record(&bbc[..bbc.len() - 10]); assert!(!parsed.is_ok()); match parsed { Err(Err::Incomplete(needed)) => assert_eq!(Needed::Size(10), needed), Err(_) => assert!(false), Ok((_, _)) => a...
identifier_body
ruby_highlight_rules.js
("./text_highlight_rules").TextHighlightRules; // exports is for Haml var constantOtherSymbol = exports.constantOtherSymbol = { token: "constant.other.symbol.ruby", // symbol regex: "[:](?:[A-Za-z_]|[@$](?=[a-zA-Z0-9_]))[a-zA-Z0-9_]*[!=?]?" }; var qString = exports.qString = { toke...
"filter_parameter_logging|match|get|post|resources|redirect|scope|assert_routing|" + "translate|localize|extract_locale_from_tld|caches_page|expire_page|caches_action|expire_action|" + "cache|expire_fragment|expire_cache_for|observe|cache_sweeper|" + "has_many|has_one|bel...
"validates_inclusion_of|validates_numericality_of|validates_with|validates_each|" + "authenticate_or_request_with_http_basic|authenticate_or_request_with_http_digest|" +
random_line_split
ruby_highlight_rules.js
|assert_match|assert_no_match|assert_in_delta|assert_throws|" + "assert_raise|assert_nothing_raised|assert_instance_of|assert_kind_of|assert_respond_to|" + "assert_operator|assert_send|assert_difference|assert_no_difference|assert_recognizes|" + "assert_generates|assert_response|asse...
{ stack.shift(); stack.shift(); this.next = stack[0] || "start"; return "support.class"; }
conditional_block
reservation-helper.js
jQuery(document).ready(function() { jQuery('ul:checkboxList("reservation, reservation_has_user_list")').addFilter(); jQuery.fn.inval = function(options) { var defaults = { attribute: 'id', expr: '' }; var opts = jQuery.extend(defaults, options); var result = $(this).attr(opts.attribute); result ...
startItem.addClass(opts.selectedClass); } }; var mouseUpHandler = function () { jQuery(document).unbind('mouseup', mouseUpHandler); jQuery(document).unbind('keypress', keyPressHandler); items.removeClass(opts.selectionClass); downItem.removeClass(opts.selectedClass); if (dura...
{ startItem = downItem; selectIndexItems(downIndex, targetIndex, downDay); }
conditional_block
reservation-helper.js
jQuery(document).ready(function() { jQuery('ul:checkboxList("reservation, reservation_has_user_list")').addFilter(); jQuery.fn.inval = function(options) { var defaults = { attribute: 'id', expr: '' }; var opts = jQuery.extend(defaults, options); var result = $(this).attr(opts.attribute); result ...
downItem = null; downDay = null; downIndex = null; duration = 0; } } var mouseEnterHandler = function (e) { if (downItem) { var target = jQuery(this); var targetIndex = target.inval({ expr: opts.indexExpr }); startItem.removeClass(opts.selectedClass); if ...
items.removeClass(opts.selectionClass); items.removeClass(opts.selectedClass);
random_line_split
multidoc-manager.js
State to be set * @return {Promise} - Resolves after state and history have been updated */ amp['setState'] = state => { return Services.bindForDocOrNull(shadowRoot).then(bind => { if (!bind) { return Promise.reject('amp-bind is not available in this document'); } ...
{ dev().fine(TAG, '- src script: ', n); const src = n.getAttribute('src'); const isRuntime = src.indexOf('/amp.js') != -1 || src.indexOf('/v0.js') != -1; // Note: Some extensions don't have [custom-element] or // [custom-template] e.g...
conditional_block
multidoc-manager.js
* * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS-IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language go...
random_line_split
multidoc-manager.js
dev().fine(TAG, 'Attach shadow doc as stream'); return this.attachShadowDoc_( hostElement, url, opt_initParams, (amp, shadowRoot, ampdoc) => { // Start streaming. let renderStarted = false; const writer = createShadowDomWriter(this.win); amp['writer'] = write...
removeShadowRoot_
identifier_name
dashboard-hero.component.spec.ts
import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { DebugElement } from '@angular/core'; import { addMatchers } from '../../testing'; import { Hero } from '../model/hero'; import { DashboardHeroComponent } from './dashboard-her...
} // #enddocregion test-host
{ this.selectedHero = hero; }
identifier_body
dashboard-hero.component.spec.ts
import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { DebugElement } from '@angular/core'; import { addMatchers } from '../../testing'; import { Hero } from '../model/hero'; import { DashboardHeroComponent } from './dashboard-her...
it('should display hero name', () => { const expectedPipedName = expectedHero.name.toUpperCase(); expect(heroEl.nativeElement.textContent).toContain(expectedPipedName); }); // #enddocregion name-test // #docregion click-test it('should raise selected event when clicked', () => { let selectedHero:...
// #docregion name-test
random_line_split
dashboard-hero.component.spec.ts
import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { DebugElement } from '@angular/core'; import { addMatchers } from '../../testing'; import { Hero } from '../model/hero'; import { DashboardHeroComponent } from './dashboard-her...
{ hero = new Hero(42, 'Test Name'); selectedHero: Hero; onSelected(hero: Hero) { this.selectedHero = hero; } } // #enddocregion test-host
TestHostComponent
identifier_name