file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
mod.rs | pub mod spout;
pub mod bolt;
use rustc_serialize::json;
use tokio_core::net::TcpStream;
use tokio_io;
use futures::Future;
use std;
use tokio_uds::UnixStream;
pub struct ComponentConfig{
pub sock_file: String,
pub component_id: String
}
#[derive(Debug)]
#[derive(RustcEncodable, RustcDecodable)]
pub enum Mes... | unimplemented!();
}
pub fn tuple(stream: &str, value: &str) -> Self{
Message::Tuple(stream.to_string(), value.to_string())
}
} | random_line_split | |
index.js | var camelCase = require('camelcase')
var path = require('path')
var tokenizeArgString = require('./lib/tokenize-arg-string')
var util = require('util')
function parse (args, opts) {
if (!opts) opts = {}
// allow a string argument to be passed in rather
// than an argv array.
args = tokenizeArgString(args)
//... | Object.keys(opts.narg || {}).forEach(function (k) {
flags.nargs[k] = opts.narg[k]
})
Object.keys(opts.coerce || {}).forEach(function (k) {
flags.coercions[k] = opts.coerce[k]
})
if (Array.isArray(opts.config) || typeof opts.config === 'string') {
;[].concat(opts.config).filter(Boolean).forEach(f... |
;[].concat(opts.normalize).filter(Boolean).forEach(function (key) {
flags.normalize[key] = true
})
| random_line_split |
index.js | var camelCase = require('camelcase')
var path = require('path')
var tokenizeArgString = require('./lib/tokenize-arg-string')
var util = require('util')
function parse (args, opts) {
if (!opts) opts = {}
// allow a string argument to be passed in rather
// than an argv array.
args = tokenizeArgString(args)
//... |
return {
argv: argv,
error: error,
aliases: flags.aliases,
newAliases: newAliases,
configuration: configuration
}
}
// if any aliases reference each other, we should
// merge them together.
function combineAliases (aliases) {
var aliasArrays = []
var change = true
var combined = {}
/... | {
return num === undefined
} | identifier_body |
index.js | var camelCase = require('camelcase')
var path = require('path')
var tokenizeArgString = require('./lib/tokenize-arg-string')
var util = require('util')
function parse (args, opts) {
if (!opts) opts = {}
// allow a string argument to be passed in rather
// than an argv array.
args = tokenizeArgString(args)
//... | (argv) {
var coerce
Object.keys(argv).forEach(function (key) {
coerce = checkAllAliases(key, flags.coercions)
if (typeof coerce === 'function') {
try {
argv[key] = coerce(argv[key])
} catch (err) {
error = err
}
}
})
}
function applyDefault... | applyCoercions | identifier_name |
AutoFilterRow.tsx | import * as React from 'react';
import * as classNames from 'classnames';
import { FiltersProps} from './QuickGrid.Props';
import { Grid} from 'react-virtualized';
import './QuickGrid.scss';
import { TextField } from '../TextField';
import { ColumnFilter } from './ColumnFilter';
export class AutoFilterRow exte... |
}
setGridReference = (ref) => { this._filtersGrid = ref; };
public render() {
const { headerColumns, width, scrollLeft} = this.props;
return (
<div style={{ width }}>
<Grid
ref={this.setGridReference}
cellRende... | {
this._filtersGrid.recomputeGridSize();
} | conditional_block |
AutoFilterRow.tsx | import * as React from 'react';
import * as classNames from 'classnames';
import { FiltersProps} from './QuickGrid.Props';
import { Grid} from 'react-virtualized';
import './QuickGrid.scss';
import { TextField } from '../TextField';
import { ColumnFilter } from './ColumnFilter';
export class AutoFilterRow exte... | (prevProps: FiltersProps) {
if (prevProps.columnWidths !== this.props.columnWidths) {
this._filtersGrid.recomputeGridSize();
}
}
setGridReference = (ref) => { this._filtersGrid = ref; };
public render() {
const { headerColumns, width, scrollLeft} = this.props;
... | componentDidUpdate | identifier_name |
AutoFilterRow.tsx | import * as React from 'react';
import * as classNames from 'classnames';
import { FiltersProps} from './QuickGrid.Props';
import { Grid} from 'react-virtualized';
import './QuickGrid.scss';
import { TextField } from '../TextField';
import { ColumnFilter } from './ColumnFilter';
export class AutoFilterRow exte... | width={width}
scrollLeft={scrollLeft}
/>
</div>
);
}
getColumnWidth = ({ index }) => {
return this.props.columnWidths[index];
}
filtersCellRender = ({ columnIndex, style }) => {
const column =... | rowCount={1}
| random_line_split |
AutoFilterRow.tsx | import * as React from 'react';
import * as classNames from 'classnames';
import { FiltersProps} from './QuickGrid.Props';
import { Grid} from 'react-virtualized';
import './QuickGrid.scss';
import { TextField } from '../TextField';
import { ColumnFilter } from './ColumnFilter';
export class AutoFilterRow exte... |
setGridReference = (ref) => { this._filtersGrid = ref; };
public render() {
const { headerColumns, width, scrollLeft} = this.props;
return (
<div style={{ width }}>
<Grid
ref={this.setGridReference}
cellRenderer={th... | {
if (prevProps.columnWidths !== this.props.columnWidths) {
this._filtersGrid.recomputeGridSize();
}
} | identifier_body |
EditComponentFactory.tsx | import {FormConfig} from '../../../../models';
import {TextareaInput} from '../inputs/TextareaInput';
import {BasicMathInput} from '../inputs/BasicMathInput';
import {NumericInput} from '../inputs/NumericInput';
import {StringInput} from '../inputs/StringInput';
import {InvoiceLineTypeSelect, ProjectLineTypeSelect} fro... | {
const componentMap = {
// Standard
number: NumericInput,
money: MoneyInput,
text: StringInput,
textarea: TextareaInput,
switch: Switch,
float: FloatInput,
bool: CheckboxInput,
date: DatePicker,
month: MonthPicker,
// Specialized
'basic-math': BasicMathInput,
emai... | identifier_body | |
EditComponentFactory.tsx | import {FormConfig} from '../../../../models';
import {TextareaInput} from '../inputs/TextareaInput';
import {BasicMathInput} from '../inputs/BasicMathInput';
import {NumericInput} from '../inputs/NumericInput';
import {StringInput} from '../inputs/StringInput';
import {InvoiceLineTypeSelect, ProjectLineTypeSelect} fro... | ProjectLineTypeSelect,
InvoiceDateStrategySelect,
PropertiesSelect,
ExtraFields: ExtraFieldsInput,
ClientSelect,
ClientSelectWithCreateModal,
PartnerSelectWithCreateModal,
StringsSelect,
AttachmentsTypeSelect,
ConsultantTypeSelect,
ProjectSelect,
EditProjectClient,
Ed... |
// Custom
InvoiceLineTypeSelect, | random_line_split |
EditComponentFactory.tsx | import {FormConfig} from '../../../../models';
import {TextareaInput} from '../inputs/TextareaInput';
import {BasicMathInput} from '../inputs/BasicMathInput';
import {NumericInput} from '../inputs/NumericInput';
import {StringInput} from '../inputs/StringInput';
import {InvoiceLineTypeSelect, ProjectLineTypeSelect} fro... | (col: FormConfig) {
const componentMap = {
// Standard
number: NumericInput,
money: MoneyInput,
text: StringInput,
textarea: TextareaInput,
switch: Switch,
float: FloatInput,
bool: CheckboxInput,
date: DatePicker,
month: MonthPicker,
// Specialized
'basic-math': BasicM... | getComponent | identifier_name |
Circle.ts | import { VarAD } from "types/ad";
import { ICenter, IFill, INamed, IShape, IStroke } from "types/shapes";
import { IFloatV } from "types/value";
import {
BoolV,
Canvas,
sampleColor,
sampleNoPaint,
sampleVector,
sampleWidth,
sampleZero,
StrV,
} from "./Samplers";
export interface ICircle extends INamed,... | ...properties,
shapeType: "Circle",
}); | ): Circle => ({
...sampleCircle(rng, canvas), | random_line_split |
test.js | const pageIcon = require('./../lib/index');
const helpers = require('./helpers');
const fs = require('fs');
const chai = require('chai');
const path = require('path');
const url = require('url');
const expect = chai.expect;
const {isIconValid, saveToFile} = helpers;
const SITE_URLS = [
'https://www.facebook.com/'... | (ext, callback) {
pageIcon(ICON_TYPE_URL, {ext: ext})
.then(function(icon) {
if (!icon) {
throw `No icon found for url: ${ICON_TYPE_URL}`;
}
return icon;
})
.then(function(icon) {
expect(icon.ext).to.equal(ext, `Should get a ${e... | iconTypeTest | identifier_name |
test.js | const pageIcon = require('./../lib/index');
const helpers = require('./helpers');
const fs = require('fs');
const chai = require('chai');
const path = require('path');
const url = require('url');
const expect = chai.expect;
const {isIconValid, saveToFile} = helpers;
const SITE_URLS = [
'https://www.facebook.com/'... | return icon;
})
.then(function(icon) {
expect(isIconValid(icon)).to.be.true;
return icon;
})
.then(saveToFile)
.then(() => {
... | random_line_split | |
test.js | const pageIcon = require('./../lib/index');
const helpers = require('./helpers');
const fs = require('fs');
const chai = require('chai');
const path = require('path');
const url = require('url');
const expect = chai.expect;
const {isIconValid, saveToFile} = helpers;
const SITE_URLS = [
'https://www.facebook.com/'... |
return icon;
})
.then(function(icon) {
expect(isIconValid(icon)).to.be.true;
done()
})
.catch(done);
});
describe('Specification of preferred icon ext', function () {
it('Type .png', function(done) {
... | {
throw `No icon found for url: ${siteUrl}`;
} | conditional_block |
test.js | const pageIcon = require('./../lib/index');
const helpers = require('./helpers');
const fs = require('fs');
const chai = require('chai');
const path = require('path');
const url = require('url');
const expect = chai.expect;
const {isIconValid, saveToFile} = helpers;
const SITE_URLS = [
'https://www.facebook.com/'... | {
pageIcon(ICON_TYPE_URL, {ext: ext})
.then(function(icon) {
if (!icon) {
throw `No icon found for url: ${ICON_TYPE_URL}`;
}
return icon;
})
.then(function(icon) {
expect(icon.ext).to.equal(ext, `Should get a ${ext} from WhatsAp... | identifier_body | |
exportAnimFBX.py | __author__ = 'sofiaelm'
# version 1.0
"""
"""
from pymel.all import *
import maya.cmds as cmds
# Regex for our scene name structure. Example: genericTurnLeft45A_v013_sm
SCENE_FILE_NAME_REGEX = r'[a-zA-Z]+[0-9]+[A-Z]{1}_v[0-9]{3}_[a-zA-Z]{2}'
# Regex for our top node name structure. Example: genericTurnLeft45A
SCEN... | file_dir = os.path.dirname(cmds.file(q=1, sceneName=1))
export_dir = os.path.join(os.path.dirname(file_dir), "export")
if not os.path.exists(export_dir):
os.mkdir(export_dir)
# Get the full scene name
scene_file_raw = str(cmds.file(q=1, sceneName=1, shortName=1))
# ... | conditional_block | |
exportAnimFBX.py | __author__ = 'sofiaelm'
# version 1.0
"""
"""
from pymel.all import *
import maya.cmds as cmds
# Regex for our scene name structure. Example: genericTurnLeft45A_v013_sm
SCENE_FILE_NAME_REGEX = r'[a-zA-Z]+[0-9]+[A-Z]{1}_v[0-9]{3}_[a-zA-Z]{2}'
# Regex for our top node name structure. Example: genericTurnLeft45A
SCEN... | print selectBND
# Bake anim to bind joints
#cmds.bakeResults(selectBND, t=(startTime, endTime))
# Select bind joints and geometry and export as FBX
select(cl=1)
selectBNDJNTS()
# Make a list of the selection to "Export selection" as FBX
toExport = cmds... | selectBND = cmds.ls(sl=1) | random_line_split |
exportAnimFBX.py | __author__ = 'sofiaelm'
# version 1.0
"""
"""
from pymel.all import *
import maya.cmds as cmds
# Regex for our scene name structure. Example: genericTurnLeft45A_v013_sm
SCENE_FILE_NAME_REGEX = r'[a-zA-Z]+[0-9]+[A-Z]{1}_v[0-9]{3}_[a-zA-Z]{2}'
# Regex for our top node name structure. Example: genericTurnLeft45A
SCEN... | if cmds.objExists("*:geo_grp*") == 0:
cmds.warning(">>>>> No group matches name 'geo_grp' <<<<<")
else:
# if the export folder doesnt exist in the directory then create it.
file_dir = os.path.dirname(cmds.file(q=1, sceneName=1))
export_dir = os.path.join(os.path.dirname(file_dir), "... | identifier_body | |
exportAnimFBX.py | __author__ = 'sofiaelm'
# version 1.0
"""
"""
from pymel.all import *
import maya.cmds as cmds
# Regex for our scene name structure. Example: genericTurnLeft45A_v013_sm
SCENE_FILE_NAME_REGEX = r'[a-zA-Z]+[0-9]+[A-Z]{1}_v[0-9]{3}_[a-zA-Z]{2}'
# Regex for our top node name structure. Example: genericTurnLeft45A
SCEN... | ():
select("*:*_geo", "*:main_bnd*", r=1)
selectBNDJNTS()
# Make a list of the selection
selectBND = cmds.ls(sl=1)
print selectBND
# Bake anim to bind joints
#cmds.bakeResults(selectBND, t=(startTime, endTime))
# Select bind joints and geometry an... | selectBNDJNTS | identifier_name |
revert-file.tsx | /*
* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
* License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details
*/
import { Rendered, Component } from "../../app-framework";
import { Button } from "react-bootstrap";
import { TimeTravelActions } from "./actions";
import { Icon } from "../../... | tends Component<Props> {
public render(): Rendered {
return (
<Button
title={`Revert file to the displayed version (this makes a new version, so nothing is lost)`}
onClick={() => {
if (this.props.version != null)
this.props.actions.revert(this.props.version);
}}... | ertFile ex | identifier_name |
revert-file.tsx | /*
* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
* License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details |
import { Rendered, Component } from "../../app-framework";
import { Button } from "react-bootstrap";
import { TimeTravelActions } from "./actions";
import { Icon } from "../../components";
interface Props {
actions: TimeTravelActions;
version: Date | undefined;
}
export class RevertFile extends Component<Props> ... | */ | random_line_split |
conftest.py | # coding: utf-8
'''Common test fixtures
@author: Jesse Schwartzentruber (:truber)
@license:
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/.
'''
import logging
import os... |
elif repotype == "hg":
cls.hg(result, "init")
return result
@staticmethod
def create_collection_file(data):
# Use a specific temporary directory to upload covmanager files
# This is required as Django now needs a path relative to that fo... | cls.git(result, "init") | conditional_block |
conftest.py | # coding: utf-8
'''Common test fixtures
@author: Jesse Schwartzentruber (:truber)
@license:
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/.
'''
import logging
import os... | (data):
# Use a specific temporary directory to upload covmanager files
# This is required as Django now needs a path relative to that folder in FileField
location = str(tmpdir)
CollectionFile.file.field.storage.location = location
tmp_fd, path = tempfile.mk... | create_collection_file | identifier_name |
conftest.py | # coding: utf-8
'''Common test fixtures
@author: Jesse Schwartzentruber (:truber)
@license:
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/.
'''
import logging
import os... |
@staticmethod
def git(repo, *args):
path = os.getcwd()
try:
os.chdir(repo.location)
return subprocess.check_output(["git"] + list(args)).decode("utf-8")
finally:
os.chdir(path)
@staticmethod
def hg(rep... | coverage = cls.create_collection_file(coverage)
# create client
client, created = Client.objects.get_or_create(name=client)
if created:
LOG.debug("Created Client pk=%d", client.pk)
# create repository
if repository is None:
repo... | identifier_body |
conftest.py | # coding: utf-8
'''Common test fixtures
@author: Jesse Schwartzentruber (:truber)
@license:
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/.
'''
import logging
import os... | have_git = HAVE_GIT
have_hg = HAVE_HG
@classmethod
def create_repository(cls, repotype, name="testrepo"):
location = tempfile.mkdtemp(prefix='testrepo', dir=os.path.dirname(__file__))
request.addfinalizer(lambda: shutil.rmtree(location))
if repotype =... |
@pytest.fixture
def cm(request, settings, tmpdir):
class _result(object): | random_line_split |
directives.js | "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var visitor_1 = require("graphql/language/visitor");
var ts_invariant_1 = require("ts-invariant");
var storeUtils_1 = require("./storeUtils");
function | (field, variables) {
if (field.directives && field.directives.length) {
var directiveObj_1 = {};
field.directives.forEach(function (directive) {
directiveObj_1[directive.name.value] = storeUtils_1.argumentsObjectFromField(directive, variables);
});
return directiveObj_1;
... | getDirectiveInfoFromField | identifier_name |
directives.js | "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var visitor_1 = require("graphql/language/visitor");
var ts_invariant_1 = require("ts-invariant");
var storeUtils_1 = require("./storeUtils");
function getDirectiveInfoFromField(field, variables) {
if (field.directives && field.directives.... |
exports.hasDirectives = hasDirectives;
function hasClientExports(document) {
return (document &&
hasDirectives(['client'], document) &&
hasDirectives(['export'], document));
}
exports.hasClientExports = hasClientExports;
//# sourceMappingURL=directives.js.map | {
return getDirectiveNames(doc).some(function (name) { return names.indexOf(name) > -1; });
} | identifier_body |
directives.js | "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var visitor_1 = require("graphql/language/visitor");
var ts_invariant_1 = require("ts-invariant");
var storeUtils_1 = require("./storeUtils");
function getDirectiveInfoFromField(field, variables) {
if (field.directives && field.directives.... | if (directive.name.value !== 'skip' && directive.name.value !== 'include') {
return;
}
var directiveArguments = directive.arguments || [];
var directiveName = directive.name.value;
ts_invariant_1.invariant(directiveArguments.length === 1, "Incorrect number of argument... | }
var res = true;
selection.directives.forEach(function (directive) { | random_line_split |
directives.js | "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var visitor_1 = require("graphql/language/visitor");
var ts_invariant_1 = require("ts-invariant");
var storeUtils_1 = require("./storeUtils");
function getDirectiveInfoFromField(field, variables) {
if (field.directives && field.directives.... |
if (!evaledValue) {
res = false;
}
});
return res;
}
exports.shouldInclude = shouldInclude;
function getDirectiveNames(doc) {
var names = [];
visitor_1.visit(doc, {
Directive: function (node) {
names.push(node.name.value);
},
});
return na... | {
evaledValue = !evaledValue;
} | conditional_block |
memory-block-cbrw.ts | "use strict";
import MemoryBlockCbw from "./memory-block-cbw";
/**
* MemoryBlock
* @constructor
* @param {object} opt the options.
*/
export default class MemoryBlockCbrw extends MemoryBlockCbw {
/* callback on peek */
// eslint-disable-next-line @typescript-eslint/no-unused-vars
onPeek = (addr:number,... |
}
/**
* Read a byte data.
* @param {number} address an address.
* @returns {number} the value in the memory.
*/
peek(address:number):number {
const value:number = super.peekByte(address);
const override = this.onPeek(address, value);
if (override != null && over... | {
this.onPeek = opt.onPeek;
} | conditional_block |
memory-block-cbrw.ts | "use strict";
import MemoryBlockCbw from "./memory-block-cbw";
/**
* MemoryBlock
* @constructor
* @param {object} opt the options.
*/
export default class MemoryBlockCbrw extends MemoryBlockCbw {
/* callback on peek */
// eslint-disable-next-line @typescript-eslint/no-unused-vars
onPeek = (addr:number,... | (address:number):number {
const value:number = super.peekByte(address);
const override = this.onPeek(address, value);
if (override != null && override !== undefined) {
return override;
}
return value;
}
}
module.exports = MemoryBlockCbrw;
| peek | identifier_name |
memory-block-cbrw.ts | "use strict";
import MemoryBlockCbw from "./memory-block-cbw";
/**
* MemoryBlock
* @constructor
* @param {object} opt the options.
*/
export default class MemoryBlockCbrw extends MemoryBlockCbw {
/* callback on peek */
// eslint-disable-next-line @typescript-eslint/no-unused-vars
onPeek = (addr:number,... |
/**
* Read a byte data.
* @param {number} address an address.
* @returns {number} the value in the memory.
*/
peek(address:number):number {
const value:number = super.peekByte(address);
const override = this.onPeek(address, value);
if (override != null && override !... | {
super(opt);
if(opt.onPeek) {
this.onPeek = opt.onPeek;
}
} | identifier_body |
memory-block-cbrw.ts | "use strict";
import MemoryBlockCbw from "./memory-block-cbw";
/**
* MemoryBlock
* @constructor
* @param {object} opt the options.
*/
export default class MemoryBlockCbrw extends MemoryBlockCbw {
/* callback on peek */
// eslint-disable-next-line @typescript-eslint/no-unused-vars
onPeek = (addr:number,... | module.exports = MemoryBlockCbrw; | random_line_split | |
timestamp_anti_stealing_link_config.py | class TimestampAntiStealingLinkConfig(dict):
def __init__(self, json):
if json is not None:
if 'enabled' in json.keys():
self.enabled = json['enabled']
else: | else:
self.primary_key = None
if 'secondaryKey' in json.keys():
self.secondary_key = json['secondaryKey']
else:
self.secondary_key = None
else:
raise GalaxyFDSClientException("Json data cannot be None")
@property
def enabled(self):
return self['enabled']
@... | self.enabled = None
if 'primaryKey' in json.keys():
self.primary_key = json['primaryKey'] | random_line_split |
timestamp_anti_stealing_link_config.py | class TimestampAntiStealingLinkConfig(dict):
def __init__(self, json):
if json is not None:
if 'enabled' in json.keys():
self.enabled = json['enabled']
else:
self.enabled = None
if 'primaryKey' in json.keys():
|
else:
self.primary_key = None
if 'secondaryKey' in json.keys():
self.secondary_key = json['secondaryKey']
else:
self.secondary_key = None
else:
raise GalaxyFDSClientException("Json data cannot be None")
@property
def enabled(self):
return self['enabled']
... | self.primary_key = json['primaryKey'] | conditional_block |
timestamp_anti_stealing_link_config.py | class TimestampAntiStealingLinkConfig(dict):
def | (self, json):
if json is not None:
if 'enabled' in json.keys():
self.enabled = json['enabled']
else:
self.enabled = None
if 'primaryKey' in json.keys():
self.primary_key = json['primaryKey']
else:
self.primary_key = None
if 'secondaryKey' in json.keys():... | __init__ | identifier_name |
timestamp_anti_stealing_link_config.py | class TimestampAntiStealingLinkConfig(dict):
def __init__(self, json):
if json is not None:
if 'enabled' in json.keys():
self.enabled = json['enabled']
else:
self.enabled = None
if 'primaryKey' in json.keys():
self.primary_key = json['primaryKey']
else:
self... | self['secondaryKey'] = secondary_key | identifier_body | |
trampoline_to_glib.rs | use analysis::conversion_type::ConversionType;
use library;
pub trait TrampolineToGlib {
fn trampoline_to_glib(&self, library: &library::Library) -> String;
}
impl TrampolineToGlib for library::Parameter {
fn trampoline_to_glib(&self, library: &library::Library) -> String |
}
fn to_glib_xxx(transfer: library::Transfer) -> &'static str {
use library::Transfer::*;
match transfer {
None => "/*Not checked*/.to_glib_none().0",
Full => ".to_glib_full()",
Container => "/*Not checked*/.to_glib_container().0",
}
}
| {
use analysis::conversion_type::ConversionType::*;
match ConversionType::of(library, self.typ) {
Direct => String::new(),
Scalar => ".to_glib()".to_owned(),
Pointer => to_glib_xxx(self.transfer).to_owned(),
Unknown => "/*Unknown conversion*/".to_owned(),
... | identifier_body |
trampoline_to_glib.rs | use analysis::conversion_type::ConversionType;
use library;
pub trait TrampolineToGlib {
fn trampoline_to_glib(&self, library: &library::Library) -> String;
}
impl TrampolineToGlib for library::Parameter {
fn trampoline_to_glib(&self, library: &library::Library) -> String {
use analysis::conversion_ty... | None => "/*Not checked*/.to_glib_none().0",
Full => ".to_glib_full()",
Container => "/*Not checked*/.to_glib_container().0",
}
} | fn to_glib_xxx(transfer: library::Transfer) -> &'static str {
use library::Transfer::*;
match transfer { | random_line_split |
trampoline_to_glib.rs | use analysis::conversion_type::ConversionType;
use library;
pub trait TrampolineToGlib {
fn trampoline_to_glib(&self, library: &library::Library) -> String;
}
impl TrampolineToGlib for library::Parameter {
fn trampoline_to_glib(&self, library: &library::Library) -> String {
use analysis::conversion_ty... | (transfer: library::Transfer) -> &'static str {
use library::Transfer::*;
match transfer {
None => "/*Not checked*/.to_glib_none().0",
Full => ".to_glib_full()",
Container => "/*Not checked*/.to_glib_container().0",
}
}
| to_glib_xxx | identifier_name |
gulpfile.js | // Include gulp
import gulp from 'gulp';
import fs from 'fs';
// Include Our Plugins
import eslint from 'gulp-eslint';
import mocha from 'gulp-mocha';
import browserSyncJs from 'browser-sync';
import sassJs from 'gulp-sass';
import sassCompiler from 'sass';
import rename from "gulp-rena... | }))
;
};
const buildJs = function() {
return gulp.src(pkg.directories.theme + '/**/js-src/*.js')
.pipe(eslint())
.pipe(eslint.format())
//.pipe(eslint.failAfterError())
.pipe(rename(function(path){
path.dirname = path.dirname.replace(/js-src/, 'js');
}))
.pipe(uglify({output: {
... | .pipe(mocha({
reporter: 'dot' | random_line_split |
beehive.ts | import {config} from '../config.ts';
import {Util, Location} from './app.ts';
import {Map} from './map.ts';
import {IHiveOptions, Hive} from './hive.ts';
import * as ko from 'knockout';
import * as _ from 'lodash';
export interface IBeehiveOptions {
map: Map;
center: Location;
steps: number;
leaps: number;
}
... |
public toggleActive(fromMap: boolean = false): void {
this.isActive = !this.isActive;
this.mapObject.set('fillOpacity', this.isActive ? 0.3 : 0);
this.options.map.setActiveBeehive(this.isActive ? this : null);
}
public editHives(): void {
this.isEditingHives = !this.isEditingHives;
for (l... | {
this.isActive = false;
if (this.isEditingHives) {
this.editHives();
}
this.mapObject.set('fillOpacity', 0);
} | identifier_body |
beehive.ts | import {config} from '../config.ts';
import {Util, Location} from './app.ts';
import {Map} from './map.ts';
import {IHiveOptions, Hive} from './hive.ts';
import * as ko from 'knockout';
import * as _ from 'lodash';
export interface IBeehiveOptions {
map: Map;
center: Location;
steps: number;
leaps: number;
}
... |
for (let ne = 2; ne < leap; ne++) {
point = getNextPoint(point, 60);
}
}
this.hives(locations);
return this.hives();
}
public resize(steps: number): void {
this.options.steps = steps;
this.options.leaps = Util.getLeapsToCoverRadius(this.coveringRadius, this.options.steps)... | {
point = getNextPoint(point, 0);
} | conditional_block |
beehive.ts | import {config} from '../config.ts';
import {Util, Location} from './app.ts';
import {Map} from './map.ts';
import {IHiveOptions, Hive} from './hive.ts';
import * as ko from 'knockout';
import * as _ from 'lodash';
export interface IBeehiveOptions {
map: Map;
center: Location;
steps: number;
leaps: number;
}
... | this.hives()[i].reset();
}
this.hives([]);
if (dispose) {
this.mapObject = this.options.map.removeMapObject(this.mapObject) as google.maps.Circle;
}
}
private generateHives(): Hive[] {
this.reset();
let locations: Hive[] = [];
let distanceBetweenHiveCenters = Util.distanc... | random_line_split | |
beehive.ts | import {config} from '../config.ts';
import {Util, Location} from './app.ts';
import {Map} from './map.ts';
import {IHiveOptions, Hive} from './hive.ts';
import * as ko from 'knockout';
import * as _ from 'lodash';
export interface IBeehiveOptions {
map: Map;
center: Location;
steps: number;
leaps: number;
}
... | (options: IBeehiveOptions) {
this.options = options;
this.hives = ko.observableArray([]);
this.isEditingHives = false;
this.coveringRadius = Util.getBeehiveRadius(this.options.leaps, this.options.steps);
this.activeHives = ko.computed(() => this.getActiveHives(), this, { deferEvaluation: true });
... | constructor | identifier_name |
video-modal.component.ts | import { Component, ViewChild } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
import { DoctorsListService } from './doctors-list.service';
import { DoctorDetails } from '../shared/database/doctor-details';
/**
* Component for video modal window
* @export
* @class VideoModalComponen... | (private doctorsListService: DoctorsListService, private domSanitizer:DomSanitizer) {
this.videoUrl = this.domSanitizer.bypassSecurityTrustResourceUrl(this.videoUrl);
}
open(size: string) {
this.videoUrl = this.doctorsListService.getVideoUrl();
this.videoModal.open(size);
}
/**... | constructor | identifier_name |
video-modal.component.ts | import { Component, ViewChild } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
import { DoctorsListService } from './doctors-list.service';
import { DoctorDetails } from '../shared/database/doctor-details';
/**
* Component for video modal window
* @export
* @class VideoModalComponen... |
/**
* function to stop playing the video when the modal window is closed
* @memberof VideoModalComponent
*/
close() {
let iframe = document.getElementsByTagName('iframe')[0].contentWindow;
let func = 'pauseVideo'; // to pause the youtube video on closing the modal window
... | {
this.videoUrl = this.doctorsListService.getVideoUrl();
this.videoModal.open(size);
} | identifier_body |
video-modal.component.ts | import { Component, ViewChild } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
import { DoctorsListService } from './doctors-list.service';
import { DoctorDetails } from '../shared/database/doctor-details';
/**
* Component for video modal window
* @export
* @class VideoModalComponen... | <modal-header [show-close]="true" (click)="close()">
</modal-header>
<modal-body>
<div class="embed-responsive embed-responsive-16by9">
<iframe class="embed-responsive-item" [src]="videoUrl" allowfullscreen>
</iframe>
... | @Component({
selector: 'mm-video-modal',
template: `
<!--modal [cssClass]="cssClass" #videoModal-->
<modal #videoModal> | random_line_split |
counts.rs | use needletail::bitkmer::{bitmer_to_bytes, reverse_complement};
use needletail::Sequence;
use crate::sketch_schemes::{KmerCount, SketchParams, SketchScheme};
use needletail::parser::SequenceRecord;
#[derive(Clone)]
pub struct AllCountsSketcher {
counts: Vec<u32>,
total_bases: u64,
k: u8,
}
impl AllCounts... |
fn total_bases_and_kmers(&self) -> (u64, u64) {
(
self.total_bases,
self.counts.iter().map(|x| u64::from(*x)).sum(),
)
}
fn to_vec(&self) -> Vec<KmerCount> {
let mut counts = self.counts.clone();
let mut results = Vec::with_capacity(self.counts.len(... | {
for (_, kmer, _) in seq.normalize(false).bit_kmers(self.k, false) {
self.counts[kmer.0 as usize] = self.counts[kmer.0 as usize].saturating_add(1);
}
} | identifier_body |
counts.rs | use needletail::bitkmer::{bitmer_to_bytes, reverse_complement};
use needletail::Sequence;
use crate::sketch_schemes::{KmerCount, SketchParams, SketchScheme};
use needletail::parser::SequenceRecord;
#[derive(Clone)]
pub struct AllCountsSketcher {
counts: Vec<u32>,
total_bases: u64,
k: u8,
}
impl AllCounts... |
let extra_count = self.counts[reverse_complement((ix, self.k)).0 as usize];
counts[reverse_complement((ix, self.k)).0 as usize] = 0;
count += extra_count;
let new_item = KmerCount {
hash: ix,
kmer: bitmer_to_bytes((ix as u64, self.k)),
... | {
continue;
} | conditional_block |
counts.rs | use needletail::bitkmer::{bitmer_to_bytes, reverse_complement};
use needletail::Sequence;
use crate::sketch_schemes::{KmerCount, SketchParams, SketchScheme};
use needletail::parser::SequenceRecord;
#[derive(Clone)]
pub struct | {
counts: Vec<u32>,
total_bases: u64,
k: u8,
}
impl AllCountsSketcher {
pub fn new(k: u8) -> Self {
// TODO: should we take a size parameter or the like and clip this?
AllCountsSketcher {
counts: vec![0; 4usize.pow(k.into())],
total_bases: 0,
k,
... | AllCountsSketcher | identifier_name |
counts.rs | use needletail::bitkmer::{bitmer_to_bytes, reverse_complement};
use needletail::Sequence;
use crate::sketch_schemes::{KmerCount, SketchParams, SketchScheme};
use needletail::parser::SequenceRecord;
#[derive(Clone)]
pub struct AllCountsSketcher {
counts: Vec<u32>,
total_bases: u64,
k: u8,
}
impl AllCounts... | fn parameters(&self) -> SketchParams {
SketchParams::AllCounts {
kmer_length: self.k,
}
}
} | results
}
| random_line_split |
tkmain.py | #!/usr/bin/python
__author__ = 'Markus Bajones'
__license__ = 'GPL'
__version__ = '1.0.0'
__email__ = 'markus.bajones@gmail.com'
"""
- download ROS key from keyserver and install it
- show settings (mirror/package selection/ROS distro)
- install selected packages
- rosdep update, and init
"""
import ImageTk
import l... | self.install_button.config(bg='green')
self.master.update()
mirror, ros_pkgs, ros_version = self.select_mirror.get(), self.select_pkg.get(), self.select_ros_version.get()
ros_pkgs = '-'.join(['ros', ros_version, ros_pkgs])
catkin =''
if self.select_catkin.get():
... | return
self.message.set('Executing...') | random_line_split |
tkmain.py | #!/usr/bin/python
__author__ = 'Markus Bajones'
__license__ = 'GPL'
__version__ = '1.0.0'
__email__ = 'markus.bajones@gmail.com'
"""
- download ROS key from keyserver and install it
- show settings (mirror/package selection/ROS distro)
- install selected packages
- rosdep update, and init
"""
import ImageTk
import l... | (self):
shell = self.select_shell.get()
content = "".join(['source /opt/ros/', self.select_ros_version.get(), '/setup.', shell])
file = os.path.join(os.environ['HOME'], "".join(['.',shell,'rc']))
try:
if not os.path.exists(file) or not content in open(file).read():
... | write_shell_config | identifier_name |
tkmain.py | #!/usr/bin/python
__author__ = 'Markus Bajones'
__license__ = 'GPL'
__version__ = '1.0.0'
__email__ = 'markus.bajones@gmail.com'
"""
- download ROS key from keyserver and install it
- show settings (mirror/package selection/ROS distro)
- install selected packages
- rosdep update, and init
"""
import ImageTk
import l... |
def write_shell_config(self):
shell = self.select_shell.get()
content = "".join(['source /opt/ros/', self.select_ros_version.get(), '/setup.', shell])
file = os.path.join(os.environ['HOME'], "".join(['.',shell,'rc']))
try:
if not os.path.exists(file) or not content in o... | try:
subprocess.check_call(['/usr/bin/rosdep', 'update'])
self.rosdep_update = True
except subprocess.CalledProcessError as e:
print("rosdep executed with errors. [{err}]".format(err=str(e)))
self.rosdep_update = False | identifier_body |
tkmain.py | #!/usr/bin/python
__author__ = 'Markus Bajones'
__license__ = 'GPL'
__version__ = '1.0.0'
__email__ = 'markus.bajones@gmail.com'
"""
- download ROS key from keyserver and install it
- show settings (mirror/package selection/ROS distro)
- install selected packages
- rosdep update, and init
"""
import ImageTk
import l... |
b = tk.Checkbutton(tab1, text="Include catkin tools?", variable=self.select_catkin)
b.pack(anchor=tk.W)
for text in self.ros_version:
b = tk.Radiobutton(tab2, text=text, variable=self.select_ros_version, value=text)
b.pack(anchor=tk.W)
for text in self.shell:
... | b = tk.Radiobutton(tab1, text=text, variable=self.select_pkg, value=pkg)
b.pack(anchor=tk.W) | conditional_block |
abstract_change_detector.ts | import {isPresent} from 'angular2/src/facade/lang';
import {List, ListWrapper} from 'angular2/src/facade/collection';
import {ChangeDetectorRef} from './change_detector_ref';
import {ChangeDetector} from './interfaces';
import {CHECK_ALWAYS, CHECK_ONCE, CHECKED, DETACHED, ON_PUSH} from './constants';
export class Abst... | (throwOnChange: boolean): void {
var c = this.shadowDomChildren;
for (var i = 0; i < c.length; ++i) {
c[i]._detectChanges(throwOnChange);
}
}
markAsCheckOnce(): void { this.mode = CHECK_ONCE; }
markPathToRootAsCheckOnce(): void {
var c: ChangeDetector = this;
while (isPresent(c) && c.m... | _detectChangesInShadowDomChildren | identifier_name |
abstract_change_detector.ts | import {isPresent} from 'angular2/src/facade/lang';
import {List, ListWrapper} from 'angular2/src/facade/collection';
import {ChangeDetectorRef} from './change_detector_ref';
import {ChangeDetector} from './interfaces';
import {CHECK_ALWAYS, CHECK_ONCE, CHECKED, DETACHED, ON_PUSH} from './constants';
export class Abst... |
}
_detectChangesInShadowDomChildren(throwOnChange: boolean): void {
var c = this.shadowDomChildren;
for (var i = 0; i < c.length; ++i) {
c[i]._detectChanges(throwOnChange);
}
}
markAsCheckOnce(): void { this.mode = CHECK_ONCE; }
markPathToRootAsCheckOnce(): void {
var c: ChangeDetect... | {
c[i]._detectChanges(throwOnChange);
} | conditional_block |
abstract_change_detector.ts | import {isPresent} from 'angular2/src/facade/lang';
import {List, ListWrapper} from 'angular2/src/facade/collection';
import {ChangeDetectorRef} from './change_detector_ref';
import {ChangeDetector} from './interfaces';
import {CHECK_ALWAYS, CHECK_ONCE, CHECKED, DETACHED, ON_PUSH} from './constants';
export class Abst... |
if (throwOnChange === false) this.callOnAllChangesDone();
this._detectChangesInShadowDomChildren(throwOnChange);
if (this.mode === CHECK_ONCE) this.mode = CHECKED;
}
detectChangesInRecords(throwOnChange: boolean): void {}
callOnAllChangesDone(): void {}
_detectChangesInLightDomChildren(throwOnC... | random_line_split | |
abstract_change_detector.ts | import {isPresent} from 'angular2/src/facade/lang';
import {List, ListWrapper} from 'angular2/src/facade/collection';
import {ChangeDetectorRef} from './change_detector_ref';
import {ChangeDetector} from './interfaces';
import {CHECK_ALWAYS, CHECK_ONCE, CHECKED, DETACHED, ON_PUSH} from './constants';
export class Abst... |
detectChanges(): void { this._detectChanges(false); }
checkNoChanges(): void { this._detectChanges(true); }
_detectChanges(throwOnChange: boolean): void {
if (this.mode === DETACHED || this.mode === CHECKED) return;
this.detectChangesInRecords(throwOnChange);
this._detectChangesInLightDomChildre... | { this.parent.removeChild(this); } | identifier_body |
mod.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license | // option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Unordered containers, implemented as hash-tables
mod table;
pub mod map;
pub mod set;
trait Recover<Q: ?Sized> {
type Key;
fn get(&self, key: &Q) -> Option<&Self::Key>;
fn take(&mut self, key: &Q) ->... | // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your | random_line_split |
bezier.rs | // Copyright (C) 2020 Inderjit Gill <email@indy.io>
// This file is part of Seni
// Seni is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any l... | {
let au = uvm.map[0];
let av = uvm.map[1];
let bu = uvm.map[2];
let bv = uvm.map[3];
let cu = uvm.map[4];
let cv = uvm.map[5];
let du = uvm.map[6];
let dv = uvm.map[7];
// modify the width so that the brush textures provide good coverage
//
let line_width_start = width_star... | identifier_body | |
bezier.rs | // Copyright (C) 2020 Inderjit Gill <email@indy.io>
// This file is part of Seni
// Seni is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any l... | let tex_t = 1.0 / tessellation as f32;
// this chunk of code is just to calc the initial verts for prepare_to_add_triangle_strip
// and to get the appropriate render packet
//
let t_val = t_start;
let t_val_next = t_start + (1.0 * unit);
let xs = bezier_point(x0, x1, x2, x3, t_val);
let... | random_line_split | |
bezier.rs | // Copyright (C) 2020 Inderjit Gill <email@indy.io>
// This file is part of Seni
// Seni is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any l... | (
render_list: &mut RenderList,
matrix: &Matrix,
coords: &[f32; 8],
width_start: f32,
width_end: f32,
width_mapping: Easing,
t_start: f32,
t_end: f32,
colour: &Rgb,
tessellation: usize,
uvm: &UvMapping,
) -> Result<()> {
let au = uvm.map[0];
let av = uvm.map[1];
l... | render | identifier_name |
async.js | /**
* model/core/async.js
*/
var asyncModel = models.async = boundModel.extend({
_update: function asyncUpdate() {
var self = this;
// Allow updates that are as new or newer than the last *update* generation.
// This allows rolling updates, where the model may have one or more requests
... |
return undefined;
});
if (!callbackCalledImmediately) {
self.abortCallback = opts && opts.onAbort;
}
},
abortPrevious: function asyncAbortPrevious() {
if (this.abortCallback) {
this.abortCallback();
}
},
priority: BASE_PRIORI... | {
self.updateGeneration = reqGeneration;
self.abortCallback = null;
self.query('', value);
return true;
} | conditional_block |
async.js | /**
* model/core/async.js
*/
var asyncModel = models.async = boundModel.extend({
_update: function asyncUpdate() {
var self = this;
// Allow updates that are as new or newer than the last *update* generation.
// This allows rolling updates, where the model may have one or more requests
... | abortPrevious: function asyncAbortPrevious() {
if (this.abortCallback) {
this.abortCallback();
}
},
priority: BASE_PRIORITY_MODEL_ASYNC
}); | random_line_split | |
fqe_ops_utils.py | # Copyright 2020 Google LLC
# 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... | """Convert the string passed in to the desired symmetry.
Args:
string (str): Input string in the original expression.
Returns:
(str): Output string in the converted format.
"""
new = ""
if any(char.isdigit() for char in string):
work = string.split()
creation = re.... | identifier_body | |
fqe_ops_utils.py | # Copyright 2020 Google LLC
# 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... |
def switch_broken_symmetry(string: str) -> str:
"""Convert the string passed in to the desired symmetry.
Args:
string (str): Input string in the original expression.
Returns:
(str): Output string in the converted format.
"""
new = ""
if any(char.isdigit() for char in string):... | return "tensor" | random_line_split |
fqe_ops_utils.py | # Copyright 2020 Google LLC
# 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... |
assert nani == ncre
return "element"
creation = re.compile(r"^[a-z]\^$")
annihilation = re.compile(r"^[a-z]$")
ncre = 0
nani = 0
for opr in qftops:
if creation.match(opr):
ncre += 1
elif annihilation.match(opr):
nani += 1
else:
... | if creation.match(opr):
ncre += 1
elif annihilation.match(opr):
nani += 1
else:
raise TypeError("Unsupported behavior for {}".format(ops)) | conditional_block |
fqe_ops_utils.py | # Copyright 2020 Google LLC
# 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... | (string: str) -> str:
"""Convert the string passed in to the desired symmetry.
Args:
string (str): Input string in the original expression.
Returns:
(str): Output string in the converted format.
"""
new = ""
if any(char.isdigit() for char in string):
work = string.spli... | switch_broken_symmetry | identifier_name |
error.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::error;
use std::fmt::Display;
use std::fmt::{self};
use std::io;
use std::str;
use std::string;
use std::{self};
use serde::de;
u... | impl error::Error for Error {
fn description(&self) -> &str {
&self.msg
}
}
impl Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(&self.msg)
}
}
impl ser::Error for Error {
fn custom<T: Display>(msg: T) -> Self {
Error::new(msg)
}
}... | msg: msg.to_string(),
}
}
}
| random_line_split |
error.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::error;
use std::fmt::Display;
use std::fmt::{self};
use std::io;
use std::str;
use std::string;
use std::{self};
use serde::de;
u... |
}
impl From<string::FromUtf8Error> for Error {
fn from(err: string::FromUtf8Error) -> Self {
Error::new(err)
}
}
| {
Error::new(err)
} | identifier_body |
error.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::error;
use std::fmt::Display;
use std::fmt::{self};
use std::io;
use std::str;
use std::string;
use std::{self};
use serde::de;
u... | (&self) -> &str {
&self.msg
}
}
impl Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(&self.msg)
}
}
impl ser::Error for Error {
fn custom<T: Display>(msg: T) -> Self {
Error::new(msg)
}
}
impl de::Error for Error {
fn custom<T: Di... | description | identifier_name |
serve-path_spec_large.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { request, runTargetSpec } from '@angular-devkit/architect/testing';
import { from } from 'rxjs';
import { co... | take(1),
).toPromise().then(done, done.fail);
}, 30000);
}); | tap(response => expect(response).toContain('<title>HelloWorldApp</title>')),
concatMap(() => from(request('http://localhost:4200/test/abc/'))),
tap(response => expect(response).toContain('<title>HelloWorldApp</title>')), | random_line_split |
ms.js | /* -*- Mode: Javascript; indent-tabs-mode:nil; js-indent-level: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
/*************************************************************
*
* MathJax/jax/output/SVG/autoload/ms.js
*
* Implements the SVG output for <ms> elements.
*
* ------------------------------------------... | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
MathJax.Hub.Register.StartupHook("SVG Jax Ready",function () {
var VERSION = "2.7.2";
var MML = MathJax.ElementJax.mml,
S... | * 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, | random_line_split |
index.js | import { createSelector } from 'reselect';
import { bindActionCreators, compose } from 'redux';
import { connect } from 'react-redux';
import { reduxForm } from 'redux-form';
import {
requestContact, createContact, deleteContact, invalidate as invalidateContacts,
} from '../../store/modules/contact';
import { request... |
return result;
};
const mapDispatchToProps = dispatch => ({
...bindActionCreators({
requestContact,
getContact,
updateContact,
createContact,
deleteContact,
invalidateContacts,
updateTagCollection,
}, dispatch),
onSubmit: values => Promise.resolve(values),
});
export default comp... | {
dispatch(requestUser());
} | conditional_block |
index.js | import { createSelector } from 'reselect';
import { bindActionCreators, compose } from 'redux';
import { connect } from 'react-redux';
import { reduxForm } from 'redux-form';
import {
requestContact, createContact, deleteContact, invalidate as invalidateContacts,
} from '../../store/modules/contact';
import { request... | requestContact,
getContact,
updateContact,
createContact,
deleteContact,
invalidateContacts,
updateTagCollection,
}, dispatch),
onSubmit: values => Promise.resolve(values),
});
export default compose(
withSearchParams(),
connect(mapStateToProps, mapDispatchToProps),
reduxForm({
... | };
const mapDispatchToProps = dispatch => ({
...bindActionCreators({ | random_line_split |
18.py | #!/usr/bin/env python
# -*- coding: utf-8 -8-
"""
By starting at the top of the triangle below and moving to adjacent numbers
on the row below, the maximum total from top to bottom is 23.
3
7 4
2 4 6
8 5 9 3
That is, 3 + 7 + 4 + 9 = 23.
Find the maximum total from top to bottom of the triangle below:
"""
tri... |
sums[row, column] = s
return s
def main():
values = [[int(j) for j in i.split()] for i in triangle.split('\n') if i]
print(largest_triangle_sum(values))
if __name__ == '__main__':
main()
| left = largest_triangle_sum(values, row + 1, column, sums)
right = largest_triangle_sum(values, row + 1, column + 1, sums)
s += max([left, right]) | conditional_block |
18.py | """
By starting at the top of the triangle below and moving to adjacent numbers
on the row below, the maximum total from top to bottom is 23.
3
7 4
2 4 6
8 5 9 3
That is, 3 + 7 + 4 + 9 = 23.
Find the maximum total from top to bottom of the triangle below:
"""
triangle = """
75
9... | #!/usr/bin/env python
# -*- coding: utf-8 -8-
| random_line_split | |
18.py | #!/usr/bin/env python
# -*- coding: utf-8 -8-
"""
By starting at the top of the triangle below and moving to adjacent numbers
on the row below, the maximum total from top to bottom is 23.
3
7 4
2 4 6
8 5 9 3
That is, 3 + 7 + 4 + 9 = 23.
Find the maximum total from top to bottom of the triangle below:
"""
tri... | ():
values = [[int(j) for j in i.split()] for i in triangle.split('\n') if i]
print(largest_triangle_sum(values))
if __name__ == '__main__':
main()
| main | identifier_name |
18.py | #!/usr/bin/env python
# -*- coding: utf-8 -8-
"""
By starting at the top of the triangle below and moving to adjacent numbers
on the row below, the maximum total from top to bottom is 23.
3
7 4
2 4 6
8 5 9 3
That is, 3 + 7 + 4 + 9 = 23.
Find the maximum total from top to bottom of the triangle below:
"""
tri... |
def main():
values = [[int(j) for j in i.split()] for i in triangle.split('\n') if i]
print(largest_triangle_sum(values))
if __name__ == '__main__':
main()
| if (row, column) in sums:
return sums[row, column]
s = values[row][column]
if row + 1 < len(values):
left = largest_triangle_sum(values, row + 1, column, sums)
right = largest_triangle_sum(values, row + 1, column + 1, sums)
s += max([left, right])
sums[row, column] = s
r... | identifier_body |
scalar2geo.py | import sys
import os
from netCDF4 import Dataset, MFDataset, num2date
import numpy as np
sys.path.append(os.path.join(os.path.dirname(__file__), "../"))
import pyfesom as pf
import joblib
from joblib import Parallel, delayed
import json
from collections import OrderedDict
import click
from mpl_toolkits.basemap import m... |
# Backend is switched to threading for linear and cubic interpolations
# due to problems with memory mapping.
# One have to test threading vs multiprocessing.
if (interp == 'linear') or (interp=='cubic'):
backend = 'threading'
else:
backend = 'multiprocessing'
Parallel(n_jo... | topo = np.ma.masked_where(~mdata.mask, topo_interp) | random_line_split |
scalar2geo.py | import sys
import os
from netCDF4 import Dataset, MFDataset, num2date
import numpy as np
sys.path.append(os.path.join(os.path.dirname(__file__), "../"))
import pyfesom as pf
import joblib
from joblib import Parallel, delayed
import json
from collections import OrderedDict
import click
from mpl_toolkits.basemap import m... | (ifile, opath, variable,
mesh, ind_noempty_all,
ind_empty_all,ind_depth_all, cmore_table,
lonreg2, latreg2, distances, inds, radius_of_influence,
topo, points, interp, qh, timestep, dind, realdepth):
print(ifile)
ext = variable
#ifile = ipath
o... | scalar2geo | identifier_name |
scalar2geo.py | import sys
import os
from netCDF4 import Dataset, MFDataset, num2date
import numpy as np
sys.path.append(os.path.join(os.path.dirname(__file__), "../"))
import pyfesom as pf
import joblib
from joblib import Parallel, delayed
import json
from collections import OrderedDict
import click
from mpl_toolkits.basemap import m... |
def scalar2geo(ifile, opath, variable,
mesh, ind_noempty_all,
ind_empty_all,ind_depth_all, cmore_table,
lonreg2, latreg2, distances, inds, radius_of_influence,
topo, points, interp, qh, timestep, dind, realdepth):
print(ifile)
ext = variable
#ifi... | '''
meshpath - Path to the folder with FESOM1.4 mesh files.
ipath - Path to FESOM1.4 netCDF file or files (with wildcard).
opath - path where the output will be stored.
variable - The netCDF variable to be converted.
'''
print(ipath)
mesh = pf.load_mesh(meshpath, abg=abg, usepickle=... | identifier_body |
scalar2geo.py | import sys
import os
from netCDF4 import Dataset, MFDataset, num2date
import numpy as np
sys.path.append(os.path.join(os.path.dirname(__file__), "../"))
import pyfesom as pf
import joblib
from joblib import Parallel, delayed
import json
from collections import OrderedDict
import click
from mpl_toolkits.basemap import m... |
else:
timesteps = range(timestep, timestep+1)
if True:
temp = fw.createVariable(variable,'d',\
('time','depth_coord','latitude','longitude'), \
fill_value=-9999, zlib=False, complevel=1)
for ttime in timesteps:
... | timesteps = range(fl.variables[variable].shape[0]) | conditional_block |
string-util.ts | export class | {
static _baseTen = [true, true, true, true, true, true, true, true, true, true]
static firstUniqueByCounterSuffix(value: string, values: string[], separatorChar: string = ' ') {
let result = value
const map: { [key: string]: boolean } = {}
values.forEach(v => map[v] = true)
let idx = 1
while... | StringUtil | identifier_name |
string-util.ts | export class StringUtil {
static _baseTen = [true, true, true, true, true, true, true, true, true, true]
static firstUniqueByCounterSuffix(value: string, values: string[], separatorChar: string = ' ') |
/**
* Split a string that ends with a number into its corresponding parts. Useful for name collisions, e.g.
* FooValue, FooValue-1, FooValue-2
* @param value
*/
static withoutNumericSuffix(value: string): { text: string, suffix: number } {
let idx = value.length
const suffixChars = []
for... | {
let result = value
const map: { [key: string]: boolean } = {}
values.forEach(v => map[v] = true)
let idx = 1
while (map[result]) {
result = value + separatorChar + idx++
}
return result
} | identifier_body |
string-util.ts | export class StringUtil {
static _baseTen = [true, true, true, true, true, true, true, true, true, true]
static firstUniqueByCounterSuffix(value: string, values: string[], separatorChar: string = ' ') {
let result = value
const map: { [key: string]: boolean } = {}
values.forEach(v => map[v] = true)
... |
if (suffixChars.length) {
try {
suffixValue = Number.parseInt(suffixChars.join(''))
result = value.substring(0, idx + 1)
} catch (e) {
suffixValue = 1;
}
}
return result + (suffixValue + 1)
}
}
| {
if (StringUtil._baseTen[value.charAt(idx)] !== true) {
break;
}
suffixChars.unshift(value.charAt(idx))
} | conditional_block |
string-util.ts | export class StringUtil {
static _baseTen = [true, true, true, true, true, true, true, true, true, true]
static firstUniqueByCounterSuffix(value: string, values: string[], separatorChar: string = ' ') {
let result = value
const map: { [key: string]: boolean } = {}
values.forEach(v => map[v] = true)
... | let idx = value.length
for (idx; idx--; idx > 0) {
if (StringUtil._baseTen[value.charAt(idx)] !== true) {
break;
}
suffixChars.unshift(value.charAt(idx))
}
if (suffixChars.length) {
try {
suffixValue = Number.parseInt(suffixChars.join(''))
result = value.... |
static incrementCounterSuffix(value: string) {
let result = value
let suffixValue = 1
const suffixChars = [] | random_line_split |
list.js | ;(function(Form) {
/**
* List editor
*
* An array editor. Creates a list of other editor items.
*
* Special options:
* @param {String} [options.schema.itemType] The editor type for each item in the list. Default: 'Text'
* @param {String} [options.schema.confirmDelete] Text to displ... |
return item;
},
/**
* Remove an item from the list
* @param {List.Item} item
*/
removeItem: function(item) {
//Confirm delete
var confirmMsg = this.schema.confirmDelete;
if (confirmMsg && !confirm(confirmMsg)) return;
var index = _.indexOf(this.items, i... | {
_addItem();
item.editor.focus();
} | conditional_block |
list.js | ;(function(Form) {
/**
* List editor
*
* An array editor. Creates a list of other editor items.
*
* Special options:
* @param {String} [options.schema.itemType] The editor type for each item in the list. Default: 'Text'
* @param {String} [options.schema.confirmDelete] Text to displ... | render: function() {
var self = this,
value = this.value || [],
$ = Backbone.$;
//Create main element
var $el = $($.trim(this.template()));
//Store a reference to the list (item container)
this.$list = $el.is('[data-items]') ? $el : $el.find('[data-items]');
... | random_line_split | |
stateManager.ts | ///<reference path="../../typings/tsd.d.ts" />
namespace config.stateManager {
export const namespace = 'config.stateManager';
class StateManagerConfig {
static $inject = ['$stateProvider', '$locationProvider', '$urlRouterProvider', '$compileProvider', 'stateHelperServiceProvider'];
constru... | 'config.siteModules' //include the site modules after stateManager has been configured so all states can be loaded
])
.config(StateManagerConfig);
} |
}
angular.module(namespace, [ | random_line_split |
stateManager.ts | ///<reference path="../../typings/tsd.d.ts" />
namespace config.stateManager {
export const namespace = 'config.stateManager';
class StateManagerConfig {
static $inject = ['$stateProvider', '$locationProvider', '$urlRouterProvider', '$compileProvider', 'stateHelperServiceProvider'];
constru... | ($stateProvider, stateHelperServiceProvider) {
//add base state
$stateProvider
.state('app', {
abstract: true,
})
;
// Loop through each sub-module state and register them
angular.forEach(stateHelperService... | registerStates | identifier_name |
stateManager.ts | ///<reference path="../../typings/tsd.d.ts" />
namespace config.stateManager {
export const namespace = 'config.stateManager';
class StateManagerConfig {
static $inject = ['$stateProvider', '$locationProvider', '$urlRouterProvider', '$compileProvider', 'stateHelperServiceProvider'];
constru... |
private static configureRouter($locationProvider, $urlRouterProvider) {
$locationProvider.html5Mode(!global.Environment.isBrowserStack());
$urlRouterProvider.otherwise(function ($injector, $location) {
var errorService:common.services.error.ErrorService = $injector.get... | {
//add base state
$stateProvider
.state('app', {
abstract: true,
})
;
// Loop through each sub-module state and register them
angular.forEach(stateHelperServiceProvider.getStates(), (state:global.IStateDef... | identifier_body |
background_datastore.rs |
use rand;
use rand::distributions::*;
use structures;
use constants::*;
use GameUpdateArgs;
pub struct BackgroundDatastore<'a>
{
buffer_data: &'a mut [structures::BackgroundInstance; MAX_BK_COUNT],
instance_data: &'a mut [u32; MAX_BK_COUNT]
}
impl <'a> BackgroundDatastore<'a>
{
pub fn new(buffer_data_ref: &'a mut ... |
}
| {
let mut require_appear = appear;
let mut left_range = rand::distributions::Range::new(-14.0f32, 14.0f32);
let mut count_range = rand::distributions::Range::new(2, 10);
let mut scale_range = rand::distributions::Range::new(1.0f32, 3.0f32);
for (i, m) in self.instance_data.iter_mut().enumerate()
{
if *m ... | identifier_body |
background_datastore.rs | use rand;
use rand::distributions::*;
use structures;
use constants::*;
use GameUpdateArgs;
pub struct BackgroundDatastore<'a>
{
buffer_data: &'a mut [structures::BackgroundInstance; MAX_BK_COUNT],
instance_data: &'a mut [u32; MAX_BK_COUNT]
}
impl <'a> BackgroundDatastore<'a>
{ | {
buffer_data: buffer_data_ref,
instance_data: instance_data_ref
}
}
pub fn update(&mut self, update_args: &mut GameUpdateArgs, appear: bool)
{
let mut require_appear = appear;
let mut left_range = rand::distributions::Range::new(-14.0f32, 14.0f32);
let mut count_range = rand::distributions::Range::n... | pub fn new(buffer_data_ref: &'a mut [structures::BackgroundInstance; MAX_BK_COUNT], instance_data_ref: &'a mut [u32; MAX_BK_COUNT]) -> Self
{
BackgroundDatastore | random_line_split |
background_datastore.rs |
use rand;
use rand::distributions::*;
use structures;
use constants::*;
use GameUpdateArgs;
pub struct BackgroundDatastore<'a>
{
buffer_data: &'a mut [structures::BackgroundInstance; MAX_BK_COUNT],
instance_data: &'a mut [u32; MAX_BK_COUNT]
}
impl <'a> BackgroundDatastore<'a>
{
pub fn new(buffer_data_ref: &'a mut ... | (&mut self, update_args: &mut GameUpdateArgs, appear: bool)
{
let mut require_appear = appear;
let mut left_range = rand::distributions::Range::new(-14.0f32, 14.0f32);
let mut count_range = rand::distributions::Range::new(2, 10);
let mut scale_range = rand::distributions::Range::new(1.0f32, 3.0f32);
for (i, ... | update | identifier_name |
background_datastore.rs |
use rand;
use rand::distributions::*;
use structures;
use constants::*;
use GameUpdateArgs;
pub struct BackgroundDatastore<'a>
{
buffer_data: &'a mut [structures::BackgroundInstance; MAX_BK_COUNT],
instance_data: &'a mut [u32; MAX_BK_COUNT]
}
impl <'a> BackgroundDatastore<'a>
{
pub fn new(buffer_data_ref: &'a mut ... |
else
{
self.buffer_data[i].offset[1] += update_args.delta_time * 22.0f32;
*m = if self.buffer_data[i].offset[1] >= 20.0f32 { 0 } else { 1 };
}
}
}
}
| {
// instantiate randomly
if require_appear
{
let scale = scale_range.sample(&mut update_args.randomizer);
*m = 1;
self.buffer_data[i].offset = [left_range.sample(&mut update_args.randomizer), -20.0f32, -20.0f32,
count_range.sample(&mut update_args.randomizer) as f32];
self.buffer_... | conditional_block |
test_django.py | from kaneda.backends import LoggerBackend, ElasticsearchBackend
from kaneda.queues import CeleryQueue
from django_kaneda import settings # NOQA
class TestDjango(object):
def test_django_kaneda_with_backend(self, mocker, django_settings_backend):
mocker.patch('django_kaneda.settings', django_settings_bac... |
def test_django_kaneda_with_queue(self, mocker, django_settings_queue):
mocker.patch('django_kaneda.settings', django_settings_queue)
from django_kaneda import LazyMetrics
metrics = LazyMetrics()
assert isinstance(metrics.queue, CeleryQueue)
result = metrics.gauge('test_gau... | mocker.patch('django_kaneda.settings', django_settings_debug)
from django_kaneda import LazyMetrics
metrics = LazyMetrics()
metrics.gauge('test_gauge', 42)
assert isinstance(metrics.backend, LoggerBackend) | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.