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
Snackbar.js
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { fetchIP } from '../../actions/fetchIP'; import { Snackbar } from 'react-toolbox'; import theme from './Snackbar.css'; class SnackbarComponent extends Component { constructor(props) {...
this.props.fetchIP(); }; componentWillReceiveProps(props) { this.setState({ active: props.error, message: props.message }); } componentDidMount() { this._isMounted = true; } componentWillUnmount() { this._isMounted = false; } render() { return ( <section>...
{ this.setState({active: false}); }
conditional_block
Snackbar.js
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { fetchIP } from '../../actions/fetchIP'; import { Snackbar } from 'react-toolbox'; import theme from './Snackbar.css'; class SnackbarComponent extends Component { constructor(props) {...
this.setState({ active: props.error, message: props.message }); } componentDidMount() { this._isMounted = true; } componentWillUnmount() { this._isMounted = false; } render() { return ( <section> <Snackbar theme={theme} action=...
componentWillReceiveProps(props) {
random_line_split
Snackbar.js
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { fetchIP } from '../../actions/fetchIP'; import { Snackbar } from 'react-toolbox'; import theme from './Snackbar.css'; class SnackbarComponent extends Component { constructor(props) {...
export default connect(mapStateToProps, mapDispatchToProps)(SnackbarComponent);
{ return { weather }; }
identifier_body
__init__.py
# Copyright (C) 2015 by Clearcode <http://clearcode.cc> # and associates (see AUTHORS). # This file is part of matchbox. # matchbox 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 ...
# along with matchbox. If not, see <http://www.gnu.org/licenses/>. """Main matchbox module.""" from matchbox.box import MatchBox from matchbox.index import MatchIndex __version__ = "1.1.1" __all__ = ("MatchBox", "MatchIndex")
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # You should have received a copy of the GNU Lesser General Public License
random_line_split
types.d.ts
* Copyright (c) 2018 Choko (choko@curioswitch.org) * * 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, including without limitation the rights * to use, copy, modify,...
/* * MIT License *
random_line_split
match-value-binding-in-guard-3291.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
foo(None, true); foo(None, false); }
random_line_split
match-value-binding-in-guard-3291.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(x: Option<Box<int>>, b: bool) -> int { match x { None => { 1 } Some(ref x) if b => { *x.clone() } Some(_) => { 0 } } } pub fn main() { foo(Some(box 22), true); foo(Some(box 22), false); foo(None, true); foo(None, false); }
foo
identifier_name
match-value-binding-in-guard-3291.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
pub fn main() { foo(Some(box 22), true); foo(Some(box 22), false); foo(None, true); foo(None, false); }
{ match x { None => { 1 } Some(ref x) if b => { *x.clone() } Some(_) => { 0 } } }
identifier_body
controllers.js
(function () { 'use strict'; angular.module('app.controllers', []) .controller('MapCtrl', MapCtrl) .controller('SitesCtrl', SitesCtrl) .controller('SiteDetailCtrl', SiteDetailCtrl) .controller('ConfigCtrl', ConfigCtrl); MapCtrl.$inject = ['$scope', '$ionicLoading', 'uiGmapGoogleMapApi', '$timeout...
($scope, RESTService) { RESTService.all('sites', null, function (response) { $scope.sites = response.results; }); } function SiteDetailCtrl($scope, $stateParams, Chats) { $scope.chat = Chats.get($stateParams.chatId); } function ConfigCtrl($scope) { $scope.settings = { enableFrien...
SitesCtrl
identifier_name
controllers.js
(function () { 'use strict'; angular.module('app.controllers', []) .controller('MapCtrl', MapCtrl) .controller('SitesCtrl', SitesCtrl) .controller('SiteDetailCtrl', SiteDetailCtrl) .controller('ConfigCtrl', ConfigCtrl); MapCtrl.$inject = ['$scope', '$ionicLoading', 'uiGmapGoogleMapApi', '$timeout...
function find_photo() { var options = { quality: 100, destinationType: Camera.DestinationType.DATA_URL, sourceType: Camera.PictureSourceType.PHOTOLIBRARY, allowEdit: true, encodingType: Camera.EncodingType.JPEG, //targetWidth: 100, //targetHeight: 100,...
{ var options = { title: 'que quieres hacer?', buttonLabels: ['Tomar una foto', 'Escoger una foto'], addCancelButtonWithLabel: 'Cancelar', androidEnableCancelButton: true, winphoneEnableCancelButton: true }; $cordovaActionSheet.show(options) .then(funct...
identifier_body
controllers.js
(function () { 'use strict'; angular.module('app.controllers', []) .controller('MapCtrl', MapCtrl) .controller('SitesCtrl', SitesCtrl) .controller('SiteDetailCtrl', SiteDetailCtrl) .controller('ConfigCtrl', ConfigCtrl); MapCtrl.$inject = ['$scope', '$ionicLoading', 'uiGmapGoogleMapApi', '$timeout...
$scope.sites.latitude = position.coords.latitude; $scope.sites.longitude = position.coords.longitude; $scope.map = { center: { latitude: position.coords.latitude, longitude: position.coords.longitude }, zoom: 16 }; // Make info window for mark...
longitude: -79.3745125 } }; } // TODO add marker on current location
random_line_split
systemjs.config.js
/* Copyright 2017 Mozilla Foundation * * 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...
(babel) { return { visitor: { Identifier(path, state) { if (path.node.name === "__non_webpack_require__") { path.replaceWith(babel.types.identifier("require")); } }, }, }; } SystemJS.config({ packages: { "": { defaultExtension: "...
babelPluginReplaceNonWebPackRequire
identifier_name
systemjs.config.js
/* Copyright 2017 Mozilla Foundation * * 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...
, }, }; } SystemJS.config({ packages: { "": { defaultExtension: "js", }, }, paths: { pdfjs: new URL("src", baseLocation).href, "pdfjs-web": new URL("web", baseLocation).href, "pdfjs-test": new URL("test", baseLocation).href, "pdfjs-lib": new URL("sr...
{ if (path.node.name === "__non_webpack_require__") { path.replaceWith(babel.types.identifier("require")); } }
identifier_body
systemjs.config.js
/* Copyright 2017 Mozilla Foundation * * 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...
} else { throw new Error("Cannot configure SystemJS"); } var PluginBabelPath = "node_modules/systemjs-plugin-babel/plugin-babel.js"; var SystemJSPluginBabelPath = "node_modules/systemjs-plugin-babel/systemjs-babel-browser.js"; var PluginBabelCachePath = "external/systemjs/plugin-babel-cached.js"; ...
{ baseLocation = new URL("..", baseLocation); }
conditional_block
systemjs.config.js
/* Copyright 2017 Mozilla Foundation * * 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...
SystemJS.config({ packages: { "": { defaultExtension: "js", }, }, paths: { pdfjs: new URL("src", baseLocation).href, "pdfjs-web": new URL("web", baseLocation).href, "pdfjs-test": new URL("test", baseLocation).href, "pdfjs-lib": new URL("src/pdf", baseLocation)....
}
random_line_split
latex.py
"""LaTeX Exporter class""" # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. import os from traitlets import Unicode, default from traitlets.config import Config from nbconvert.filters.highlight import Highlight2Latex from nbconvert.filters.filter_links import reso...
(self): for x in super(LatexExporter, self).default_filters(): yield x yield ('resolve_references', resolve_references) @property def default_config(self): c = Config({ 'NbConvertBase': { 'display_data_priority' : ['text/latex', 'application/pdf'...
default_filters
identifier_name
latex.py
"""LaTeX Exporter class""" # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. import os from traitlets import Unicode, default from traitlets.config import Config from nbconvert.filters.highlight import Highlight2Latex from nbconvert.filters.filter_links import reso...
yield ('resolve_references', resolve_references) @property def default_config(self): c = Config({ 'NbConvertBase': { 'display_data_priority' : ['text/latex', 'application/pdf', 'image/png', 'image/jpeg', 'image/svg+xml', 'text/markdown', 'text/plain'] ...
yield x
conditional_block
latex.py
"""LaTeX Exporter class""" # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. import os from traitlets import Unicode, default from traitlets.config import Config
class LatexExporter(TemplateExporter): """ Exports to a Latex template. Inherit from this class if your template is LaTeX based and you need custom tranformers/filters. Inherit from it if you are writing your own HTML template and need custom tranformers/filters. If you don't need custom tranf...
from nbconvert.filters.highlight import Highlight2Latex from nbconvert.filters.filter_links import resolve_references from .templateexporter import TemplateExporter
random_line_split
latex.py
"""LaTeX Exporter class""" # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. import os from traitlets import Unicode, default from traitlets.config import Config from nbconvert.filters.highlight import Highlight2Latex from nbconvert.filters.filter_links import reso...
# Latex constants @default('default_template_path') def _default_template_path_default(self): return os.path.join("..", "templates", "latex") @default('template_skeleton_path') def _template_skeleton_path_default(self): return os.path.join("..", "templates", "latex", "skeleton") ...
return 'article.tplx'
identifier_body
tags.ts
/** * @license * Copyright 2016-2020 Balena Ltd. * * 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 ...
extends Command { public static description = stripIndent` List all tags for a fleet, device or release. List all tags and their values for the specified fleet, device or release. ${applicationIdInfo.split('\n').join('\n\t\t')} `; public static examples = [ '$ balena tags --fleet MyFleet', '$ balena ta...
TagsCmd
identifier_name
tags.ts
/** * @license * Copyright 2016-2020 Balena Ltd. * * 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 ...
'$ balena tags --device 7cf02a6', '$ balena tags --release 1234', '$ balena tags --release b376b0e544e9429483b656490e5b9443b4349bd6', ]; public static usage = 'tags'; public static flags: flags.Input<FlagsDef> = { ...(isV13() ? {} : { application: { ...cf.application, exclusive: ['ap...
'$ balena tags -f myorg/myfleet',
random_line_split
tags.ts
/** * @license * Copyright 2016-2020 Balena Ltd. * * 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 ...
const { getTypedApplicationIdentifier } = await import('../utils/sdk'); tags = await balena.models.application.tags.getAllByApplication( await getTypedApplicationIdentifier(balena, options.application), ); } if (options.device) { tags = await balena.models.device.tags.getAllByDevice( tryAsIntege...
{ const { flags: options } = this.parse<FlagsDef, {}>(TagsCmd); if ((options.application || options.app) && process.stderr.isTTY) { console.error(warnify(appToFleetFlagMsg)); } options.application ||= options.app || options.fleet; const balena = getBalenaSdk(); // Check user has specified one of appli...
identifier_body
tags.ts
/** * @license * Copyright 2016-2020 Balena Ltd. * * 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 ...
options.application ||= options.app || options.fleet; const balena = getBalenaSdk(); // Check user has specified one of application/device/release if (!options.application && !options.device && !options.release) { throw new ExpectedError(this.missingResourceMessage); } const { tryAsInteger } = await ...
{ console.error(warnify(appToFleetFlagMsg)); }
conditional_block
Energy.tsx
import React from 'react'; import Analyzer from 'parser/core/Analyzer'; import { ThresholdStyle, When } from 'parser/core/ParseResults'; import SPELLS from 'common/SPELLS'; import { SpellLink } from 'interface'; import resourceSuggest from 'parser/shared/modules/resources/resourcetracker/ResourceSuggest'; import { Ene...
(when: When) { resourceSuggest(when, this.energyTracker, { spell: SPELLS.SYMBOLS_OF_DEATH, minor: 0.10, avg: 0.20, major: 0.50, extraSuggestion: <>Try to spend energy before using <SpellLink id={SPELLS.SYMBOLS_OF_DEATH.id} />, but do not delay it to avoid waste! </>, }); resou...
suggestions
identifier_name
Energy.tsx
import React from 'react'; import Analyzer from 'parser/core/Analyzer'; import { ThresholdStyle, When } from 'parser/core/ParseResults'; import SPELLS from 'common/SPELLS'; import { SpellLink } from 'interface'; import resourceSuggest from 'parser/shared/modules/resources/resourcetracker/ResourceSuggest'; import { Ene...
suggestions(when: When) { resourceSuggest(when, this.energyTracker, { spell: SPELLS.SYMBOLS_OF_DEATH, minor: 0.10, avg: 0.20, major: 0.50, extraSuggestion: <>Try to spend energy before using <SpellLink id={SPELLS.SYMBOLS_OF_DEATH.id} />, but do not delay it to avoid waste! </>, ...
{ return { actual: (this.energyTracker.wasted + this.energyCapTracker.missedRegen) / (this.energyTracker.generated + this.energyCapTracker.naturalRegen), isGreaterThan: { minor: 0.033, average: 0.066, major: 0.1, }, style: ThresholdStyle.PERCENTAGE, }; }
identifier_body
Energy.tsx
import React from 'react'; import Analyzer from 'parser/core/Analyzer'; import { ThresholdStyle, When } from 'parser/core/ParseResults'; import SPELLS from 'common/SPELLS'; import { SpellLink } from 'interface'; import resourceSuggest from 'parser/shared/modules/resources/resourcetracker/ResourceSuggest'; import { Ene...
suggestions(when: When) { resourceSuggest(when, this.energyTracker, { spell: SPELLS.SYMBOLS_OF_DEATH, minor: 0.10, avg: 0.20, major: 0.50, extraSuggestion: <>Try to spend energy before using <SpellLink id={SPELLS.SYMBOLS_OF_DEATH.id} />, but do not delay it to avoid waste! </>, ...
}; }
random_line_split
Edge.ts
import * as Compare from '../dom/Compare'; import * as Awareness from './Awareness'; import * as CursorPosition from './CursorPosition'; import Element from '../node/Element'; import { Node as DomNode } from '@ephox/dom-globals'; import { Option } from '@ephox/katamari'; // not sure where the "correct" interface is de...
type DescentFn = (element: Element<DomNode>) => Option<Element<DomNode>>; type AwarenessFn = (element: Element<DomNode>, offset: number) => boolean; const isAtEdge = function (parent: Element<DomNode>, current: Element<DomNode>, currentOffset: number, descent: DescentFn, awareness: AwarenessFn) { return descent(paren...
random_line_split
test_alias.py
import os from cauldron.test import support from cauldron.test.support import scaffolds class TestAlias(scaffolds.ResultsTest): """...""" def test_unknown_command(self): """Should fail if the command is not recognized.""" r = support.run_command('alias fake') self.assertTrue(r.faile...
def test_autocomplete_path(self): """...""" path = os.path.dirname(os.path.realpath(__file__)) result = support.autocomplete('alias add test {}'.format(path)) self.assertIsNotNone(result)
result = support.autocomplete('alias add fake-alias-not-real') self.assertEqual(len(result), 0)
random_line_split
test_alias.py
import os from cauldron.test import support from cauldron.test.support import scaffolds class TestAlias(scaffolds.ResultsTest): """...""" def test_unknown_command(self): """Should fail if the command is not recognized.""" r = support.run_command('alias fake') self.assertTrue(r.faile...
def test_autocomplete_path(self): """...""" path = os.path.dirname(os.path.realpath(__file__)) result = support.autocomplete('alias add test {}'.format(path)) self.assertIsNotNone(result)
"""...""" result = support.autocomplete('alias add fake-alias-not-real') self.assertEqual(len(result), 0)
identifier_body
test_alias.py
import os from cauldron.test import support from cauldron.test.support import scaffolds class TestAlias(scaffolds.ResultsTest): """...""" def test_unknown_command(self): """Should fail if the command is not recognized.""" r = support.run_command('alias fake') self.assertTrue(r.faile...
(self): """...""" p = self.get_temp_path('aliaser') r = support.run_command('alias add test "{}" --temporary'.format(p)) self.assertFalse(r.failed, 'should not have failed') def test_remove(self): """...""" directory = self.get_temp_path('aliaser') path = o...
test_add
identifier_name
store.js
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) // root state object. // each Vuex instance is just a single state tree. const state = { count: 0, thisMonth: 9, hello: { world: "how are you" }, groups: [ { restaurant: '添好運', date:'2016/10/15 (五)'...
; var provider = new firebase.auth.GoogleAuthProvider(); firebase.auth().signInWithPopup(provider); } } // getters are functions // 根據state,不用另外去設定的變數 // computed 算出來的 const getters = { evenOrOdd: state => state.count % 2 === 0 ? 'even' : 'odd' } // A Vuex instance is created by combining th...
ebase)
identifier_name
store.js
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) // root state object. // each Vuex instance is just a single state tree. const state = { count: 0, thisMonth: 9, hello: { world: "how are you" }, groups: [ { restaurant: '添好運', date:'2016/10/15 (五)'...
e, reject) => { setTimeout(() => { commit('increment') resolve() }, 1000) }) }, signIn ({ commit }) { console.log("signIn"); console.log(firebase); var provider = new firebase.auth.GoogleAuthProvider(); firebase.auth...
mit }) { return new Promise((resolv
conditional_block
store.js
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) // root state object. // each Vuex instance is just a single state tree. const state = { count: 0, thisMonth: 9, hello: { world: "how are you" }, groups: [ {
}, { restaurant: '點點心', date:'2016/10/20 (二)', participant: [{name: 'liz cheng', contact: false}, {name: 'Gary Chung', contact: true}, {name: 'Amber ou', contact: false}], remain: 1, note: 'JAVAN 是我的!' }, { restauran...
restaurant: '添好運', date:'2016/10/15 (五)', participant: [{name: 'stacy chen', contact: true}, {name: 'yingray lu', contact: false}, {name: 'pompom huang', contact: false}], remain: 0, note: '報名即將截止,要搶要快!'
random_line_split
store.js
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) // root state object. // each Vuex instance is just a single state tree. const state = { count: 0, thisMonth: 9, hello: { world: "how are you" }, groups: [ { restaurant: '添好運', date:'2016/10/15 (五)'...
nchronous operations. const actions = { increment: ({ commit }) => commit('increment'), decrement: ({ commit }) => commit('decrement'), incrementIfOdd ({ commit, state }) { if ((state.count + 1) % 2 === 0) { commit('increment') } }, incrementAsync ({ commit }) { r...
ffects and can involve // asy
identifier_body
connection.rs
(&self, dur: Option<Duration>) -> RedisResult<()> { self.con.set_read_timeout(dur) } pub fn as_pubsub<'a>(&'a mut self) -> PubSub<'a> { // NOTE: The pubsub flag is intentionally not raised at this time since running commands // within the pubsub state should not try and exit from the pu...
from_pattern
identifier_name
connection.rs
if self.scheme() == "redis" { url_to_tcp_connection_info(self) } else if self.scheme() == "unix" || self.scheme() == "redis+unix" { url_to_unix_connection_info(self) } else { fail!(( ErrorKind::InvalidClientConfig, "URL provided...
_ => fail!(( ErrorKind::ResponseError, "Redis server refused to switch database" )), } } Ok(rv) } /// Implements the "stateless" part of the connection interface that is used by the /// different objects in redis-rs. Primarily it obviously appl...
{}
conditional_block
connection.rs
{ if self.scheme() == "redis" { url_to_tcp_connection_info(self) } else if self.scheme() == "unix" || self.scheme() == "redis+unix" { url_to_unix_connection_info(self) } else { fail!(( ErrorKind::InvalidClientConfig, "URL provi...
Ok(()) } pub fn is_open(&self) -> bool { match *self { ActualConnection::Tcp(TcpConnection { open, .. }) => open, #[cfg(unix)] ActualConnection::Unix(UnixConnection { open, .. }) => open, } } } pub fn connect(connection_info: &ConnectionInfo) -> ...
random_line_split
connection.rs
url_to_unix_connection_info(self) } else { fail!(( ErrorKind::InvalidClientConfig, "URL provided is not a redis URL" )); } } } struct TcpConnection { reader: BufReader<TcpStream>, open: bool, } #[cfg(unix)] struct UnixConn...
{ self.con.set_read_timeout(dur) }
identifier_body
Test_pt.ts
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE TS> <TS> <context> <name>TestGui::UnitTest</name> <message> <source>FreeCAD UnitTest</source> <translation>Teste de unidade do FreeCAD</translation> </message> <message> <source>Failures and errors</source> <translation>Falhas e ...
<source>Copyright (c) Werner Mayer FreeCAD UnitTest is part of FreeCAD and supports writing Unit Tests for own modules.</source> <translation>Copyright (c) Werner Mayer O teste de unidade do FreeCAD é parte do FreeCAD e suporta o desenvolvimento de testes de unidade para módulos próprios.</translation> ...
<message> <source>About FreeCAD UnitTest</source> <translation>Sobre o teste de unidade do FreeCAD</translation> </message> <message>
random_line_split
cluster.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
except exceptions.SkipResult: pass if no_files_found: raise exceptions.FileNotFoundForTaskException( "None of the tasks in {} contain the files in list {}".format( ",".join([task["id"] for task in task_list]), ",".join(file_list) ) ...
no_files_found = False yield result
conditional_block
cluster.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
(task_list, file_list, max_workers): no_files_found = True async def process(task_fname): task, fname = task_fname try: fobj = await task.file(fname) except exceptions.SlaveDoesNotExist: if task is None: print(f"(Unknown Task):{fname} (Slave no lo...
get_files_for_tasks
identifier_name
cluster.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
futures = [asyncio.ensure_future(process(element)) for element in elements] if futures: for result in asyncio.as_completed(futures): try: result = await result if result: no_files_found = False yield result ...
no_files_found = True async def process(task_fname): task, fname = task_fname try: fobj = await task.file(fname) except exceptions.SlaveDoesNotExist: if task is None: print(f"(Unknown Task):{fname} (Slave no longer exists)") else: ...
identifier_body
cluster.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
if no_files_found: raise exceptions.FileNotFoundForTaskException( "None of the tasks in {} contain the files in list {}".format( ",".join([task["id"] for task in task_list]), ",".join(file_list) ) )
no_files_found = False yield result except exceptions.SkipResult: pass
random_line_split
JobSpecSelectorComponent.tsx
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you ...
private get selectedSpec() { return this.props.specs.find(spec => spec.id === this.props.selectedSpecId); } }
{ const newSpecId = e.currentTarget.value; this.props.onSelectedSpecIdChanged(newSpecId); }
identifier_body
JobSpecSelectorComponent.tsx
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you ...
{this.selectedSpec.description} </div> </div> ); } private onChangedSelectedSpec(e: FormEvent<HTMLSelectElement>): void { const newSpecId = e.currentTarget.value; this.props.onSelectedSpecIdChanged(newSpecId); } private get select...
random_line_split
JobSpecSelectorComponent.tsx
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you ...
(jobSpecSummary: APIJobSpecSummary, i: number): ReactElement<any> { return ( <option key={i} value={jobSpecSummary.id}> {jobSpecSummary.name} </option> ); } public render(): ReactElement<any> { return ( <div className="ui form"> ...
renderJobSpecSummary
identifier_name
app.affiliatefooter.ts
import {Component, NgModule, ViewChild,ViewContainerRef, ViewEncapsulation} from '@angular/core'; import {FormBuilder, FormGroup, Validators, FormControl} from '@angular/forms'; import {FORM_DIRECTIVES, REACTIVE_FORM_DIRECTIVES} from "@angular/forms/src/directives"; //import {FORM_DIRECTIVES, REACTIVE_FORM_DIRECTIVES} ...
{ // /@ViewChild(Modal) modal; // dealerloginform: FormGroup; myModal :ModalModule; data:any; http:Http; items:any; serverUrl:any; commonservices:AppCommonservices; loginerror:any; constructor(fb: FormBuilder , http:Http ,commonservices: AppCommonservices,userInfo:CookieService...
AppAffiliatefooter
identifier_name
app.affiliatefooter.ts
import {Component, NgModule, ViewChild,ViewContainerRef, ViewEncapsulation} from '@angular/core'; import {FormBuilder, FormGroup, Validators, FormControl} from '@angular/forms'; import {FORM_DIRECTIVES, REACTIVE_FORM_DIRECTIVES} from "@angular/forms/src/directives"; //import {FORM_DIRECTIVES, REACTIVE_FORM_DIRECTIVES} ...
import {AppCommonservices} from '../../services/app.commonservices' import {CookieService} from 'angular2-cookie/core'; @Component({ selector: 'my-app', //template: '<h1>Welcome to my First Angular 2 App </h1>' templateUrl:'app/pages/affiliatefooter/home.html', providers: [AppCommonservices] //di...
import {ModalModule} from "ng2-modal"; import {Headers,Http} from "@angular/http";
random_line_split
app.affiliatefooter.ts
import {Component, NgModule, ViewChild,ViewContainerRef, ViewEncapsulation} from '@angular/core'; import {FormBuilder, FormGroup, Validators, FormControl} from '@angular/forms'; import {FORM_DIRECTIVES, REACTIVE_FORM_DIRECTIVES} from "@angular/forms/src/directives"; //import {FORM_DIRECTIVES, REACTIVE_FORM_DIRECTIVES} ...
}
{ }
identifier_body
_script.py
# Copyright ClusterHQ Inc. See LICENSE file for details. """ Command to start up the Docker plugin. """ from os import umask from stat import S_IRUSR, S_IWUSR, S_IXUSR from twisted.python.usage import Options from twisted.internet.endpoints import serverFromString from twisted.application.internet import StreamServe...
directory_path.chmod(S_IRUSR | S_IWUSR | S_IXUSR) finally: umask(original_umask) def main(self, reactor, options): # Many places in both twisted.web and Klein are unhappy with # listening on Unix socket, e.g. # https://twistedmatrix.com/trac/ticket/5406 "fix...
directory_path.makedirs()
conditional_block
_script.py
# Copyright ClusterHQ Inc. See LICENSE file for details. """ Command to start up the Docker plugin. """ from os import umask from stat import S_IRUSR, S_IWUSR, S_IXUSR from twisted.python.usage import Options from twisted.internet.endpoints import serverFromString from twisted.application.internet import StreamServe...
(self, directory_path): """ Create the parent directory for the Unix socket if it doesn't exist. :param FilePath directory_path: The directory to create. """ original_umask = umask(0) try: if not directory_path.exists(): directory_path.makedir...
_create_listening_directory
identifier_name
_script.py
# Copyright ClusterHQ Inc. See LICENSE file for details. """ Command to start up the Docker plugin. """ from os import umask from stat import S_IRUSR, S_IWUSR, S_IXUSR from twisted.python.usage import Options from twisted.internet.endpoints import serverFromString from twisted.application.internet import StreamServe...
@flocker_standard_options class DockerPluginOptions(Options): """ Command-line options for the Docker plugin. """ optParameters = [ ["rest-api-port", "p", REST_API_PORT, "Port to connect to for control service REST API."], ["agent-config", "c", "/etc/flocker/agent.yml", ...
random_line_split
_script.py
# Copyright ClusterHQ Inc. See LICENSE file for details. """ Command to start up the Docker plugin. """ from os import umask from stat import S_IRUSR, S_IWUSR, S_IXUSR from twisted.python.usage import Options from twisted.internet.endpoints import serverFromString from twisted.application.internet import StreamServe...
return main_for_service(reactor, service) def docker_plugin_main(): """ Script entry point that runs the Docker plugin. """ return FlockerScriptRunner(script=DockerPluginScript(), options=DockerPluginOptions()).main()
UNIXAddress.port = 0 # We can use /etc/flocker/agent.yml and /etc/flocker/node.crt to load # some information we need: agent_config = get_configuration(options) control_host = agent_config['control-service']['hostname'] node_id = agent_config['node-credential'].uuid cer...
identifier_body
emitResultTests.ts
import { expect } from "chai"; import { EmitResult } from "../../../compiler"; import { Project } from "../../../Project"; import * as testHelpers from "../../testHelpers";
project.createSourceFile("file1.ts", "const num1 = 1;"); project.createSourceFile("file2.ts", "const num2 = 2;"); const result = await project.emit(); expect(result.compilerObject).to.not.be.undefined; expect(result.getEmitSkipped()).to.be.false; expect(result.getDiagnost...
describe(nameof(EmitResult), () => { it("should get the emit result when there are no errors", async () => { const fileSystem = testHelpers.getFileSystemHostWithFiles([]); const project = new Project({ compilerOptions: { noLib: true, outDir: "dist" }, fileSystem });
random_line_split
package.py
############################################################################## # Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-64...
"""S4 generic functions needed by Bioconductor proteomics packages.""" homepage = "https://bioconductor.org/packages/ProtGenerics/" url = "https://git.bioconductor.org/packages/ProtGenerics" list_url = homepage version('1.8.0', git='https://git.bioconductor.org/packages/ProtGenerics', commit='b2b...
identifier_body
package.py
############################################################################## # Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-64...
homepage = "https://bioconductor.org/packages/ProtGenerics/" url = "https://git.bioconductor.org/packages/ProtGenerics" list_url = homepage version('1.8.0', git='https://git.bioconductor.org/packages/ProtGenerics', commit='b2b3bb0938e20f58fca905f6870de7dbc9dfd7a3') depends_on('r@3.4.0:3.4.9',...
class RProtgenerics(RPackage): """S4 generic functions needed by Bioconductor proteomics packages."""
random_line_split
package.py
############################################################################## # Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-64...
(RPackage): """S4 generic functions needed by Bioconductor proteomics packages.""" homepage = "https://bioconductor.org/packages/ProtGenerics/" url = "https://git.bioconductor.org/packages/ProtGenerics" list_url = homepage version('1.8.0', git='https://git.bioconductor.org/packages/ProtGeneri...
RProtgenerics
identifier_name
ike.rs
ikev2_header: IkeV2Header, } impl IkeHeaderWrapper { pub fn
() -> IkeHeaderWrapper { IkeHeaderWrapper { spi_initiator: String::new(), spi_responder: String::new(), maj_ver: 0, min_ver: 0, msg_id: 0, flags: 0, ikev1_transforms: Vec::new(), ikev2_transforms: Vec::new(), ...
new
identifier_name
ike.rs
ikev2_header: IkeV2Header, } impl IkeHeaderWrapper { pub fn new() -> IkeHeaderWrapper { IkeHeaderWrapper { spi_initiator: String::new(), spi_responder: String::new(), maj_ver: 0, min_ver: 0, msg_id: 0, flags: 0, ikev1_tran...
else if isakmp_header.maj_ver == 2 { if isakmp_header.min_ver != 0 { SCLogDebug!( "ipsec_probe: could be ipsec, but with unsupported/invalid version {}.{}", isakmp_header.maj_ver, isakmp_header.min_ver ...
{ if isakmp_header.resp_spi == 0 && direction != Direction::ToServer { unsafe { *rdir = Direction::ToServer.into(); } } return true; }
conditional_block
ike.rs
, }, } } } #[derive(Default)] pub struct IkePayloadWrapper { pub ikev1_payload_types: Option<HashSet<u8>>, pub ikev2_payload_types: Vec<IkePayloadType>, } pub struct IKETransaction { tx_id: u64, pub ike_version: u8, pub hdr: IkeHeaderWrapper, pub payload_types: IkePayl...
{ let state = cast_pointer!(state, IKEState); return state.tx_id; }
identifier_body
ike.rs
rem; if isakmp_header.maj_ver != 1 && isakmp_header.maj_ver != 2 { SCLogDebug!("Unsupported ISAKMP major_version"); return AppLayerResult::err(); } if isakmp_header.maj_ver == 1 { handle_ikev1(self, current, i...
}; let ip_proto_str = CString::new("udp").unwrap();
random_line_split
player_reinforce_rnn_2.py
from players.player import player from auxiliar.aux_plot import * import random from collections import deque import sys sys.path.append('..') import tensorblock as tb import numpy as np import tensorflow as tf # PLAYER REINFORCE RNN class player_reinforce_rnn_2(player): # __INIT__ def __init__(self): ...
self.experiences = deque()
# Reset Batch
random_line_split
player_reinforce_rnn_2.py
from players.player import player from auxiliar.aux_plot import * import random from collections import deque import sys sys.path.append('..') import tensorblock as tb import numpy as np import tensorflow as tf # PLAYER REINFORCE RNN class player_reinforce_rnn_2(player): # __INIT__ def __init__(self): ...
actions[i] = self.experiences[ i + self.NUM_FRAMES - 1][2] rewards[i] = self.experiences[ i + self.NUM_FRAMES - 1][3] dones[i] = self.experiences[ i + self.NUM_FRAMES - 1][4] # Calculate Discounted Reward running_add = 0 discou...
prev_states[i,j,:,:] = self.experiences[ i + j ][0] curr_states[i,j,:,:] = self.experiences[ i + j ][1]
conditional_block
player_reinforce_rnn_2.py
from players.player import player from auxiliar.aux_plot import * import random from collections import deque import sys sys.path.append('..') import tensorblock as tb import numpy as np import tensorflow as tf # PLAYER REINFORCE RNN class player_reinforce_rnn_2(player): # __INIT__ def __init__(self): ...
# PREPARE NETWORK def operations(self): # Action Placeholders self.brain.addInput( shape = [ None , self.num_actions ] , name = 'Actions' ) self.brain.addInput( shape = [ None ] , name = 'Target' ) # Operations self.brain.addOperation( function ...
size = len( self.experiences ) if size < self.NUM_FRAMES: return self.create_random_action() states = np.zeros( (self.NUM_FRAMES , self.obsv_shape[0], self.obsv_shape[1] ) ) for i , j in enumerate( range( size - self.NUM_FRAMES , size ) ): states[i] = self.experiences...
identifier_body
player_reinforce_rnn_2.py
from players.player import player from auxiliar.aux_plot import * import random from collections import deque import sys sys.path.append('..') import tensorblock as tb import numpy as np import tensorflow as tf # PLAYER REINFORCE RNN class player_reinforce_rnn_2(player): # __INIT__ def
(self): player.__init__(self) self.experiences = deque() # CHOOSE NEXT ACTION def act(self, state): return self.calculate(state) # CALCULATE NETWORK def calculate(self, state): size = len( self.experiences ) if size < self.NUM_FRAMES: return self...
__init__
identifier_name
net.rs
::io::net::tcp::{TcpStream, TcpListener, TcpAcceptor}; use std::mem::{mod, transmute, transmute_copy}; use std::raw::{mod, TraitObject}; use uany::UncheckedBoxAnyDowncast; use openssl::ssl::{Ssl, SslStream, SslContext, VerifyCallback}; use openssl::ssl::SslVerifyMode::SslVerifyPeer; use openssl::ssl::SslMethod::Sslv23...
} impl BoxAny for Box<NetworkStream + Send> { fn downcast<T: 'static>(self) -> Result<Box<T>, Box<NetworkStream + Send>> { if self.is::<T>() { Ok(unsafe { self.downcast_unchecked() }) } else { Err(self) } } } /// A `NetworkListener` for `HttpStream`s. pub struc...
{ if self.is::<T>() { unsafe { // Get the raw representation of the trait object let to: TraitObject = transmute_copy(&self); // Extract the data pointer Some(transmute(to.data)) } } else { None }...
identifier_body
net.rs
std::io::net::tcp::{TcpStream, TcpListener, TcpAcceptor}; use std::mem::{mod, transmute, transmute_copy}; use std::raw::{mod, TraitObject}; use uany::UncheckedBoxAnyDowncast; use openssl::ssl::{Ssl, SslStream, SslContext, VerifyCallback}; use openssl::ssl::SslVerifyMode::SslVerifyPeer; use openssl::ssl::SslMethod::Ss...
(&mut self) -> IoResult<()> { (**self).flush() } } impl<'a> Reader for &'a mut NetworkStream { #[inline] fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> { (**self).read(buf) } } impl<'a> Writer for &'a mut NetworkStream { #[inline] fn write(&mut self, msg: &[u8]) -> IoResult<()> { (**self).write(...
flush
identifier_name
net.rs
std::io::net::tcp::{TcpStream, TcpListener, TcpAcceptor}; use std::mem::{mod, transmute, transmute_copy}; use std::raw::{mod, TraitObject}; use uany::UncheckedBoxAnyDowncast; use openssl::ssl::{Ssl, SslStream, SslContext, VerifyCallback}; use openssl::ssl::SslVerifyMode::SslVerifyPeer; use openssl::ssl::SslMethod::Ss...
impl Clone for Box<NetworkStream + Send> { #[inline] fn clone(&self) -> Box<NetworkStream + Send> { self.clone_box() } } impl Reader for Box<NetworkStream + Send> { #[inline] fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> { (**self).read(buf) } } impl Writer for Box<NetworkStream + Send> { ...
}
random_line_split
op.rs
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you ...
{ pub base: ExprNode, pub name: TString, pub op_type: FuncType, pub description: TString, pub arguments: Array<AttrFieldInfo>, pub attrs_type_key: TString, pub attrs_type_index: u32, pub num_inputs: i32, pub support_level: i32, }
OpNode
identifier_name
op.rs
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you ...
pub name: TString, pub op_type: FuncType, pub description: TString, pub arguments: Array<AttrFieldInfo>, pub attrs_type_key: TString, pub attrs_type_index: u32, pub num_inputs: i32, pub support_level: i32, }
#[type_key = "Op"] pub struct OpNode { pub base: ExprNode,
random_line_split
local_cli_wrapper.py
""" return framework.OnSessionInitResponse( framework.OnSessionInitAction.PROCEED) def on_run_start(self, request): """Overrides on-run-start callback. Invoke the CLI to let user choose what action to take: `run` / `invoke_stepper`. Args: request: An instance of `OnSessionI...
_register_this_run_info
identifier_name
local_cli_wrapper.py
times", type=int, default=1, help="How many Session.run() calls to proceed with.") ap.add_argument( "-n", "--no_debug", dest="no_debug", action="store_true", help="Run through without debug tensor watching.") ap.add_argument( "-f", ...
output = debugger_cli_common.RichTextLines([]) if self._run_call_count == 1: output.extend(cli_shared.get_tfdbg_logo()) output.extend(self._run_info) if (not self._is_run_start and debugger_cli_common.MAIN_MENU_KEY in output.annotations): menu = output.annotations[debugger_cli_common.M...
identifier_body
local_cli_wrapper.py
activated by the "-f" flag of the "run" command. # _run_through_times: keeps track of how many times the wrapper needs to # run through without stopping at the run-end CLI. It is activated by the # "-t" option of the "run" command. # _skip_debug: keeps track of whether the current run should be e...
self._prep_cli_for_run_end(debug_dump, request.tf_error, passed_filter) self._run_start_response = self._launch_cli() # Clean up the dump generated by this run. self._remove_dump_root() else: # No debug information to show following a non-debug run() call. self._run_start_res...
if not debug_dump.find( self._tensor_filters[self._active_tensor_filter], first_n=1): # No dumped tensor passes the filter in this run. Clean up the dump # directory and move on. self._remove_dump_root() return framework.OnRunEndResponse() else: # So...
conditional_block
local_cli_wrapper.py
be launched to ask # the user. This is the case, e.g., right before the first run starts. self._active_tensor_filter = None self._run_through_times = 1 self._skip_debug = False self._run_start_response = None self._is_run_start = True self._ui_type = ui_type def _initialize_argparsers...
random_line_split
start.rs
// STD Dependencies ----------------------------------------------------------- use std::fmt; // Discord Dependencies ------------------------------------------------------- use discord::model::{ChannelId, ServerId}; // Internal Dependencies ------------------------------------------------------ use ::bot::{Bot, Bo...
} actions } } impl fmt::Display for Action { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "[Action] [StartRecording] Server #{}", self.server_id ) } }
{ // Notify all users in the current voice channel for member in server.channel_voice_members(&self.voice_channel_id) { actions.push(MessageActions::Send::user_private( member.id, format!( "N...
conditional_block
start.rs
// STD Dependencies ----------------------------------------------------------- use std::fmt; // Discord Dependencies ------------------------------------------------------- use discord::model::{ChannelId, ServerId}; // Internal Dependencies ------------------------------------------------------ use ::bot::{Bot, Bo...
} impl ActionHandler for Action { fn run(&mut self, bot: &mut Bot, _: &BotConfig, queue: &mut EventQueue) -> ActionGroup { let mut actions: Vec<Box<ActionHandler>> = Vec::new(); if let Some(server) = bot.get_server(&self.server_id) { info!("{} Starting audio recording...", self); ...
{ Box::new(Action { server_id: server_id, voice_channel_id: voice_channel_id }) }
identifier_body
start.rs
// STD Dependencies ----------------------------------------------------------- use std::fmt; // Discord Dependencies ------------------------------------------------------- use discord::model::{ChannelId, ServerId}; // Internal Dependencies ------------------------------------------------------ use ::bot::{Bot, Bo...
f, "[Action] [StartRecording] Server #{}", self.server_id ) } }
impl fmt::Display for Action { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(
random_line_split
start.rs
// STD Dependencies ----------------------------------------------------------- use std::fmt; // Discord Dependencies ------------------------------------------------------- use discord::model::{ChannelId, ServerId}; // Internal Dependencies ------------------------------------------------------ use ::bot::{Bot, Bo...
{ server_id: ServerId, voice_channel_id: ChannelId, } impl Action { pub fn new( server_id: ServerId, voice_channel_id: ChannelId ) -> Box<Action> { Box::new(Action { server_id: server_id, voice_channel_id: voice_channel_id }) } } impl Actio...
Action
identifier_name
dashboard.routes.ts
import { Routes } from '@angular/router'; import { LoggedInGuard } from '../common/session/logged-in.guard'; import { DashboardPage } from './dashboard.page'; import { DashboardListPage } from './dashboard-list.page'; import { DashletSettingsPage } from './dashlet-settings.page'; export const dashboardRoutesConfig:...
pathMatch: 'full', component: DashboardPage, canActivate: [LoggedInGuard], data: { title: 'Dashboard' } }, { path: 'manage/dashboards', pathMatch: 'full', component: DashboardListPage, canActivate: [LoggedInGuard], data: { ...
}, { path: 'dashboard/:id',
random_line_split
prism-python.js
Prism.languages.python = { 'comment': { pattern: /(^|[^\\])#.*/, lookbehind: true }, 'string-interpolation': { pattern: /(?:f|rf|fr)(?:("""|''')[\s\S]*?\1|("|')(?:\\.|(?!\2)[^\\\r\n])*\2)/i, greedy: true, inside: { 'interpolation': { // "{" <expression> <optional "!s", "!r", or "!a"> <optional ":" f...
greedy: true }, 'function': { pattern: /((?:^|\s)def[ \t]+)[a-zA-Z_]\w*(?=\s*\()/g, lookbehind: true }, 'class-name': { pattern: /(\bclass\s+)\w+/i, lookbehind: true }, 'decorator': { pattern: /(^\s*)@\w+(?:\.\w+)*/im, lookbehind: true, alias: ['annotation', 'punctuation'], inside: { 'punctua...
pattern: /(?:[rub]|rb|br)?("|')(?:\\.|(?!\1)[^\\\r\n])*\1/i,
random_line_split
betaserialization.py
""" extend TiddlyWiki serialization to optionally use beta or externalized releases and add the UniversalBackstage. activated via "twrelease=beta" URL parameter or ServerSettings, see build_config_var """ import logging from tiddlyweb.util import read_utf8_file from tiddlywebwiki.serialization import Serialization...
return WikiSerialization.list_tiddlers(self, tiddlers) def _get_wiki(self): beta = external = False release = self.environ.get('tiddlyweb.query', {}).get( 'twrelease', [False])[0] externalize = self.environ.get('tiddlyweb.query', {}).get( 'external',...
""" Subclass of the standard TiddlyWiki serialization to allow choosing beta or externalized versions of the base empty.html in which the tiddlers will be servered. Also, if the TiddlyWiki is not being downloaded, add the UniversalBackstage by injecting a script tag. """ def list_tiddlers(...
identifier_body
betaserialization.py
""" extend TiddlyWiki serialization to optionally use beta or externalized releases and add the UniversalBackstage. activated via "twrelease=beta" URL parameter or ServerSettings, see build_config_var """ import logging from tiddlyweb.util import read_utf8_file from tiddlywebwiki.serialization import Serialization...
wiki = None if beta or external: config_var = build_config_var(beta, external) LOGGER.debug('looking for %s', config_var) base_wiki_file = self.environ.get('tiddlyweb.config', {}).get(config_var, '') if base_wiki_file: ...
external = False
conditional_block
betaserialization.py
""" extend TiddlyWiki serialization to optionally use beta or externalized releases and add the UniversalBackstage. activated via "twrelease=beta" URL parameter or ServerSettings, see build_config_var """ import logging from tiddlyweb.util import read_utf8_file from tiddlywebwiki.serialization import Serialization...
download = self.environ.get('tiddlyweb.query', {}).get( 'download', [False])[0] if release == 'beta': beta = True if externalize: external = True # If somebody is downloading, don't allow them to # externalize. if download: ...
release = self.environ.get('tiddlyweb.query', {}).get( 'twrelease', [False])[0] externalize = self.environ.get('tiddlyweb.query', {}).get( 'external', [False])[0]
random_line_split
betaserialization.py
""" extend TiddlyWiki serialization to optionally use beta or externalized releases and add the UniversalBackstage. activated via "twrelease=beta" URL parameter or ServerSettings, see build_config_var """ import logging from tiddlyweb.util import read_utf8_file from tiddlywebwiki.serialization import Serialization...
(beta=False, external=False): """ Create the configuration key which will be used to locate the base tiddlywiki file. """ base = 'base_tiddlywiki' if external: base += '_external' if beta: base += '_beta' return base class Serialization(WikiSerialization): """ S...
build_config_var
identifier_name
designdocinfo-action.test.js
// Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed un...
afterEach(() => { restore(Actions.monitorDesignDoc); }); it('calls monitorDesignDoc on successful fetch', () => { const promise = FauxtonAPI.Deferred(); promise.resolve(); const fakeDesignDocInfo = { fetch: () => { return promise; } }; const s...
const {assert, restore} = testUtils; describe('DesignDocInfo Actions', () => { describe('fetchDesignDocInfo', () => {
random_line_split
channel.tsx
import * as React from 'react' import { selectProductsFromChannel } from 'app/containers/products/productsReducer' import { IState, IChannel } from 'app/interfaces' import ChannelPreview from 'app/components/ChannelPreview' import { RouteProps } from 'react-router' import Product from 'app/containers/product/product' ...
export default connect(mapStateToProps)(Channel)
{ const { channel } = ownProps.match.params const products = selectProductsFromChannel(state, channel) return { products, channel } }
identifier_body
channel.tsx
import * as React from 'react' import { selectProductsFromChannel } from 'app/containers/products/productsReducer' import { IState, IChannel } from 'app/interfaces' import ChannelPreview from 'app/components/ChannelPreview' import { RouteProps } from 'react-router' import Product from 'app/containers/product/product' ...
function mapStateToProps (state: IState, ownProps: any): object { const { channel } = ownProps.match.params const products = selectProductsFromChannel(state, channel) return { products, channel } } export default connect(mapStateToProps)(Channel)
} }
random_line_split
channel.tsx
import * as React from 'react' import { selectProductsFromChannel } from 'app/containers/products/productsReducer' import { IState, IChannel } from 'app/interfaces' import ChannelPreview from 'app/components/ChannelPreview' import { RouteProps } from 'react-router' import Product from 'app/containers/product/product' ...
(state: IState, ownProps: any): object { const { channel } = ownProps.match.params const products = selectProductsFromChannel(state, channel) return { products, channel } } export default connect(mapStateToProps)(Channel)
mapStateToProps
identifier_name
def_build_graph.py
from networkx import DiGraph from networkx.readwrite import json_graph import cantera as ct import numpy as np import json #from src.core.def_tools import * import os __author__ = 'Xiang Gao' """ ---------------------------------------------- construction of the element flux graph ---------------------------------...
return flux_graph except IOError: pass """ -------------------------------- if not, then compute, and save -------------------------------- """ # --------------------------------------------- # check if traced_element is legal if traced_element not in element: raise('traced element ' + traced_elem...
flux_graph = json_graph.node_link_graph(data)
random_line_split
def_build_graph.py
from networkx import DiGraph from networkx.readwrite import json_graph import cantera as ct import numpy as np import json #from src.core.def_tools import * import os __author__ = 'Xiang Gao' """ ---------------------------------------------- construction of the element flux graph ---------------------------------...
# ------------------------------------- # save the graph using json, which is fast, and human-readable data = json_graph.node_link_data(flux_graph) json.dump(data, open(path_save, 'w')) #print 'graph saved as',path_save return flux_graph
n_sum = sum(produced.values()) for target in produced.keys(): for source in consumed.keys(): n_i2j = 1.0 * produced[target] * consumed[source] / n_sum # note that the direction (source-->target) is already assured # therefore we use abs(RR) here dw = float(n_i2j * abs(rr[id_rxn])) try...
conditional_block
def_build_graph.py
from networkx import DiGraph from networkx.readwrite import json_graph import cantera as ct import numpy as np import json #from src.core.def_tools import * import os __author__ = 'Xiang Gao' """ ---------------------------------------------- construction of the element flux graph ---------------------------------...
(soln, raw, traced_element, path_save=None, overwrite=False, i0=0, i1='eq', constV=False): """ :param mechanism: type = dict, keys include "species", "reaction", "element", etc :param raw: type = dict, keys include "mole_fraction", "net_reaction_rate", etc :param traced_element: type = str :...
build_flux_graph
identifier_name
def_build_graph.py
from networkx import DiGraph from networkx.readwrite import json_graph import cantera as ct import numpy as np import json #from src.core.def_tools import * import os __author__ = 'Xiang Gao' """ ---------------------------------------------- construction of the element flux graph ---------------------------------...
try: data = json.load(open(path_save, 'r')) flux_graph = json_graph.node_link_graph(data) return flux_graph except IOError: pass """ -------------------------------- if not, then compute, and save -------------------------------- """ # --------------------------------------------- # check i...
""" :param mechanism: type = dict, keys include "species", "reaction", "element", etc :param raw: type = dict, keys include "mole_fraction", "net_reaction_rate", etc :param traced_element: type = str :param i0: type = int, specifying the starting point of the considered interval ...
identifier_body
GetNextOperationIdCommand.ts
import { RavenCommand } from "../../Http/RavenCommand"; import { ServerNode } from "../../Http/ServerNode"; import { HttpRequestParameters } from "../../Primitives/Http"; import * as stream from "readable-stream"; export class
extends RavenCommand<number> { public get isReadRequest(): boolean { return false; // disable caching } public createRequest(node: ServerNode): HttpRequestParameters { const uri = `${node.url}/databases/${node.database}/operations/next-operation-id`; return { uri }; }...
GetNextOperationIdCommand
identifier_name
GetNextOperationIdCommand.ts
import { RavenCommand } from "../../Http/RavenCommand"; import { ServerNode } from "../../Http/ServerNode"; import { HttpRequestParameters } from "../../Primitives/Http"; import * as stream from "readable-stream"; export class GetNextOperationIdCommand extends RavenCommand<number> { public get isReadReques...
}); return body; } }
this.result = id; }
random_line_split
GetNextOperationIdCommand.ts
import { RavenCommand } from "../../Http/RavenCommand"; import { ServerNode } from "../../Http/ServerNode"; import { HttpRequestParameters } from "../../Primitives/Http"; import * as stream from "readable-stream"; export class GetNextOperationIdCommand extends RavenCommand<number> { public get isReadReques...
public async setResponseAsync(bodyStream: stream.Stream, fromCache: boolean): Promise<string> { let body: string = null; await this._defaultPipeline(_ => body = _).process(bodyStream) .then(results => { const id = results["id"]; if (typeof id !== ...
{ const uri = `${node.url}/databases/${node.database}/operations/next-operation-id`; return { uri }; }
identifier_body
GetNextOperationIdCommand.ts
import { RavenCommand } from "../../Http/RavenCommand"; import { ServerNode } from "../../Http/ServerNode"; import { HttpRequestParameters } from "../../Primitives/Http"; import * as stream from "readable-stream"; export class GetNextOperationIdCommand extends RavenCommand<number> { public get isReadReques...
}); return body; } }
{ this.result = id; }
conditional_block
map_reduce_part2.py
''' SI 618 - HW 4: Map-Reduce Part 2 Uniqname: gracfu ''' from mrjob.job import MRJob from mrjob.step import MRStep import re WORD_RE = re.compile(r"\b[\w']+\b") class MRMostUsedWord(MRJob): def mapper_get_words(self, _, line): for word in WORD_RE.findall(line): yield (word.lower(), 1) def combiner_count_wo...
MRMostUsedWord.run()
conditional_block
map_reduce_part2.py
''' SI 618 - HW 4: Map-Reduce Part 2 Uniqname: gracfu ''' from mrjob.job import MRJob from mrjob.step import MRStep import re WORD_RE = re.compile(r"\b[\w']+\b") class MRMostUsedWord(MRJob): def mapper_get_words(self, _, line): for word in WORD_RE.findall(line): yield (word.lower(), 1) def combiner_count_wo...
MRMostUsedWord.run()
if __name__ == '__main__':
random_line_split
map_reduce_part2.py
''' SI 618 - HW 4: Map-Reduce Part 2 Uniqname: gracfu ''' from mrjob.job import MRJob from mrjob.step import MRStep import re WORD_RE = re.compile(r"\b[\w']+\b") class MRMostUsedWord(MRJob): def mapper_get_words(self, _, line): for word in WORD_RE.findall(line): yield (word.lower(), 1) def
(self, word, counts): yield (word, sum(counts)) def reducer_count_words(self, word, counts): yield None, (sum(counts), word) def reducer_find_max_words(self, _, word_count_pairs): yield max(word_count_pairs) def steps(self): return [ MRStep(mapper = self.mapper_get_words, combiner = self.combiner_...
combiner_count_words
identifier_name
map_reduce_part2.py
''' SI 618 - HW 4: Map-Reduce Part 2 Uniqname: gracfu ''' from mrjob.job import MRJob from mrjob.step import MRStep import re WORD_RE = re.compile(r"\b[\w']+\b") class MRMostUsedWord(MRJob): def mapper_get_words(self, _, line):
def combiner_count_words(self, word, counts): yield (word, sum(counts)) def reducer_count_words(self, word, counts): yield None, (sum(counts), word) def reducer_find_max_words(self, _, word_count_pairs): yield max(word_count_pairs) def steps(self): return [ MRStep(mapper = self.mapper_get_words, ...
for word in WORD_RE.findall(line): yield (word.lower(), 1)
identifier_body