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
_array-copy-within.js
/* */ 'use strict'; var toObject = require("./_to-object"), toIndex = require("./_to-index"), toLength = require("./_to-length"); module.exports = [].copyWithin || function copyWithin(target, start) { var O = toObject(this), len = toLength(O.length),
if (from < to && to < from + count) { inc = -1; from += count - 1; to += count - 1; } while (count-- > 0) { if (from in O) O[to] = O[from]; else delete O[to]; to += inc; from += inc; } return O; };
to = toIndex(target, len), from = toIndex(start, len), end = arguments.length > 2 ? arguments[2] : undefined, count = Math.min((end === undefined ? len : toIndex(end, len)) - from, len - to), inc = 1;
random_line_split
index.js
/** * Module dependencies. */ var express = require('express') , passport = require('passport') , nowww = require('nowww') , log = require('debug')('root:config') , MongoStore = require('connect-mongo')(express) , mandrillMailer = require('lib/mailer').mandrillMailer , resolve = require('path').resolve ...
* Set `testing` only settings */ app.configure('testing', function() { // Log config settigs load log( 'testing settings' ); }); /** * Set `production` only settings */ app.configure('production', function() { // Log config settigs load log( 'production settings' ); /** ...
{ /** * Set `development` only settings */ app.configure('development', function() { // Log config settigs load log( 'development settings' ); /** * Build */ app.use(require('lib/build').middleware); }); /**
identifier_body
index.js
/** * Module dependencies. */ var express = require('express') , passport = require('passport') , nowww = require('nowww') , log = require('debug')('root:config') , MongoStore = require('connect-mongo')(express) , mandrillMailer = require('lib/mailer').mandrillMailer , resolve = require('path').resolve ...
// Log config settigs load log( 'testing settings' ); }); /** * Set `production` only settings */ app.configure('production', function() { // Log config settigs load log( 'production settings' ); /** * Set `nowww` middleware helper */ app.use( nowww() ); /**...
*/ app.configure('testing', function() {
random_line_split
index.js
/** * Module dependencies. */ var express = require('express') , passport = require('passport') , nowww = require('nowww') , log = require('debug')('root:config') , MongoStore = require('connect-mongo')(express) , mandrillMailer = require('lib/mailer').mandrillMailer , resolve = require('path').resolve ...
(app) { /** * Set `development` only settings */ app.configure('development', function() { // Log config settigs load log( 'development settings' ); /** * Build */ app.use(require('lib/build').middleware); }); /** * Set `testing` only settings */ app.configure('te...
Setup
identifier_name
overrides.spec.ts
import Configuration = require('../../../lib/Configuration'); import overrides = require('../../../lib/overrides/all'); import Rule = require('../../../lib/Rule'); import s = require('../../../lib/helpers/string'); import sinonChai = require('../../sinon-chai'); var expect = sinonChai.expect; // ReSharper disable Wr...
repeat: 'r', size: 's' })(config); expect(result).to.deep.equal([ ['background', 'c1 i r s'] ]); }); it('generates no declarations when no options are provided', () => { var result = overrides.background()(config); expect(result).to.be.empty; }); }); describe('clearfix', () => { ...
['background', 'a c1 c2 i o p r s'] ]); result = overrides.background({ clip: 'c1', image: 'i',
random_line_split
lib.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
// along with Parity. If not, see <http://www.gnu.org/licenses/>. //! Efficient large, fixed-size big integers and hashes. #![cfg_attr(asm_available, feature(asm))] extern crate rand; extern crate rustc_serialize; extern crate bigint; extern crate libc; #[macro_use] extern crate heapsize; pub mod hash; /// A prel...
// You should have received a copy of the GNU General Public License
random_line_split
no_pivot_ldl_test.py
# Copyright 2021 The TensorFlow Probability Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
def _randomSymmetricMatrix(self, n, batch_shape, low, high, forcemin=None, seed=42): diag = self._randomDiag(n, batch_shape, low, high, forcemin, seed) unit_tril = self._randomTril(n, batch_shape, seed) return np.einsum('...ij,...j,...kj->...ik', unit_tril, diag, unit_tril) ...
np.random.seed(seed) unit_tril = np.random.standard_normal(batch_shape + [n, n]) unit_tril = np.tril(unit_tril) unit_tril[..., range(n), range(n)] = 1. return unit_tril
identifier_body
no_pivot_ldl_test.py
# Copyright 2021 The TensorFlow Probability Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
test_util.main()
conditional_block
no_pivot_ldl_test.py
# Copyright 2021 The TensorFlow Probability Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
def _randomSymmetricMatrix(self, n, batch_shape, low, high, forcemin=None, seed=42): diag = self._randomDiag(n, batch_shape, low, high, forcemin, seed) unit_tril = self._randomTril(n, batch_shape, seed) return np.einsum('...ij,...j,...kj->...ik', unit_tril, diag, unit_tril) ...
unit_tril = np.tril(unit_tril) unit_tril[..., range(n), range(n)] = 1. return unit_tril
random_line_split
no_pivot_ldl_test.py
# Copyright 2021 The TensorFlow Probability Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
(self): matrix = self._randomSymmetricMatrix(10, [2, 1, 3], 1e-6, 10., seed=42) chol, left = self.evaluate( (tf.linalg.cholesky(matrix), simple_robustified_cholesky(matrix))) self.assertAllClose(chol, left) def testSimpleIndefinite(self): matrix = [[1., 2.], [2., 1.]] left = self...
testSimpleIsCholeskyRandomPD
identifier_name
protocol.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Low-level wire protocol implementation. Currently only supports //! [JSON packets] //! (https://wiki.mozilla.o...
, Err(ref e) if e.kind == EndOfFile => return Err(IoError { kind: EndOfFile, desc: "EOF", detail: None }), _ => return Err(IoError { kind: OtherIoError, desc: "connection error", detail: None }) } } } }
{ let packet_len_str = String::from_utf8(buffer).unwrap(); let packet_len = num::from_str_radix(packet_len_str.as_slice(), 10).unwrap(); let packet_buf = self.read_exact(packet_len).unwrap(); let packet = String::from_utf8(packet_buf).unwra...
conditional_block
protocol.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Low-level wire protocol implementation. Currently only supports //! [JSON packets] //! (https://wiki.mozilla.o...
fn read_json_packet<'a>(&mut self) -> IoResult<Json> { // https://wiki.mozilla.org/Remote_Debugging_Protocol_Stream_Transport // In short, each JSON packet is [ascii length]:[JSON data of given length] let mut buffer = vec!(); loop { let colon = ':' as u8; m...
{ let s = json::encode(obj).unwrap().replace("__type__", "type"); println!("<- {}", s); self.write_str(s.len().to_string().as_slice()).unwrap(); self.write_u8(':' as u8).unwrap(); self.write_str(s.as_slice()).unwrap(); }
identifier_body
protocol.rs
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Low-level wire protocol implementation. Currently only supports //! [JSON packets] //! (https://wiki.mozilla.org/Remote_Debugging_Protocol_Stream_Transport#JSON_Packets). use seria...
random_line_split
protocol.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Low-level wire protocol implementation. Currently only supports //! [JSON packets] //! (https://wiki.mozilla.o...
<'a>(&mut self) -> IoResult<Json> { // https://wiki.mozilla.org/Remote_Debugging_Protocol_Stream_Transport // In short, each JSON packet is [ascii length]:[JSON data of given length] let mut buffer = vec!(); loop { let colon = ':' as u8; match self.read_byte() { ...
read_json_packet
identifier_name
Login.js
import Login from '../components/Login.jsx'; import {useDeps, composeWithTracker, composeAll} from 'mantra-core'; import { connect } from 'react-redux' import { push } from 'react-router-redux'; export const composer = ({context, clearErrors}, onData) => { onData(null, {}); // clearErrors when unmounting the com...
composeWithTracker(composer), useDeps(depsMapper) )(Login);
export default composeAll( connect(mapStateToProps),
random_line_split
async-iterator-iteration.js
'use strict'; // https://github.com/tc39/proposal-iterator-helpers var aCallable = require('../internals/a-callable'); var anObject = require('../internals/an-object'); var getBuiltIn = require('../internals/get-built-in'); var getMethod = require('../internals/get-method'); var MAX_SAFE_INTEGER = 0x1FFFFFFFFFFFFF; v...
} } catch (error) { onError(error); } }, onError); } catch (error2) { onError(error2); } }; loop(); }); }; }; module.exports = { toArray: createMethod(0), forEach: createMethod(1), every: createMethod(2), some: createMethod(3), find: createMetho...
{ target[index++] = value; loop(); }
conditional_block
async-iterator-iteration.js
'use strict'; // https://github.com/tc39/proposal-iterator-helpers var aCallable = require('../internals/a-callable'); var anObject = require('../internals/an-object'); var getBuiltIn = require('../internals/get-built-in'); var getMethod = require('../internals/get-method'); var MAX_SAFE_INTEGER = 0x1FFFFFFFFFFFFF; v...
} } catch (error2) { return reject(error2); } method(argument); }; var onError = function (error) { closeIteration(reject, error); }; var loop = function () { try { if (IS_TO_ARRAY && (index > MAX_SAFE_INTEGER) && MAPPING) { ...
});
random_line_split
buttons.py
import logging from datetime import datetime from .actions import actions from .system_menu.system_menu import system_menu from .library.buttons import library_buttons from .book.buttons import book_buttons from .go_to_page.buttons import go_to_page_buttons from .bookmarks.buttons import bookmarks_buttons from .languag...
'L': actions.close_menu(), }, 'long': { 'R': actions.toggle_help_menu(), '>': actions.next_page(), '<': actions.previous_page(), 'L': actions.close_menu(), 'X': actions.reset_display('start'), }, } } sys_menu = system_m...
'>': actions.next_page(), '<': actions.previous_page(),
random_line_split
buttons.py
import logging from datetime import datetime from .actions import actions from .system_menu.system_menu import system_menu from .library.buttons import library_buttons from .book.buttons import book_buttons from .go_to_page.buttons import go_to_page_buttons from .bookmarks.buttons import bookmarks_buttons from .languag...
try: action = bindings[location][press_type][key] except KeyError: log.debug('no binding for key {}, {} press'.format(key, press_type)) else: await dispatch(action) prev_buttons = {} long_buttons = {} async def check(driver, state, dispatch): # this is a hack for now until w...
location = state['location']
conditional_block
buttons.py
import logging from datetime import datetime from .actions import actions from .system_menu.system_menu import system_menu from .library.buttons import library_buttons from .book.buttons import book_buttons from .go_to_page.buttons import go_to_page_buttons from .bookmarks.buttons import bookmarks_buttons from .languag...
prev_buttons = {} long_buttons = {} async def check(driver, state, dispatch): # this is a hack for now until we change the protocol, we read the buttons # twice so we don't miss the release of short presses for _ in range(2): buttons = driver.get_buttons() for key in buttons: ...
if state['help_menu']['visible']: location = 'help_menu' else: location = state['location'] try: action = bindings[location][press_type][key] except KeyError: log.debug('no binding for key {}, {} press'.format(key, press_type)) else: await dispatch(action)
identifier_body
buttons.py
import logging from datetime import datetime from .actions import actions from .system_menu.system_menu import system_menu from .library.buttons import library_buttons from .book.buttons import book_buttons from .go_to_page.buttons import go_to_page_buttons from .bookmarks.buttons import bookmarks_buttons from .languag...
(driver, state, dispatch): # this is a hack for now until we change the protocol, we read the buttons # twice so we don't miss the release of short presses for _ in range(2): buttons = driver.get_buttons() for key in buttons: up_or_down = buttons[key] if up_or_down ==...
check
identifier_name
html-to-mfm.ts
const parse5 = require('parse5'); export default function(html: string): string { if (html == null) return null; const dom = parse5.parseFragment(html); let text = ''; dom.childNodes.forEach((n: any) => analyze(n)); return text.trim(); function
(node: any) { if (node.nodeName == '#text') return node.value; if (node.childNodes) { return node.childNodes.map((n: any) => getText(n)).join(''); } return ''; } function analyze(node: any) { switch (node.nodeName) { case '#text': text += node.value; break; case 'br': text += '\n'; ...
getText
identifier_name
html-to-mfm.ts
const parse5 = require('parse5'); export default function(html: string): string { if (html == null) return null; const dom = parse5.parseFragment(html); let text = ''; dom.childNodes.forEach((n: any) => analyze(n)); return text.trim(); function getText(node: any) { if (node.nodeName == '#text') return nod...
} else if (part.length == 3) { text += txt; break; } } if (node.childNodes) { node.childNodes.forEach((n: any) => analyze(n)); } break; case 'p': text += '\n\n'; if (node.childNodes) { node.childNodes.forEach((n: any) => analyze(n)); } break; defa...
const href = new URL(node.attrs.find((x: any) => x.name == 'href').value); const acct = txt + '@' + href.hostname; text += acct; break; //#endregion
random_line_split
html-to-mfm.ts
const parse5 = require('parse5'); export default function(html: string): string { if (html == null) return null; const dom = parse5.parseFragment(html); let text = ''; dom.childNodes.forEach((n: any) => analyze(n)); return text.trim(); function getText(node: any) { if (node.nodeName == '#text') return nod...
const acct = txt + '@' + href.hostname; text += acct; break; //#endregion } else if (part.length == 3) { text += txt; break; } } if (node.childNodes) { node.childNodes.forEach((n: any) => analyze(n)); } break; case 'p': text += '\n\n'; if (...
{ switch (node.nodeName) { case '#text': text += node.value; break; case 'br': text += '\n'; break; case 'a': const txt = getText(node); // メンション if (txt.startsWith('@')) { const part = txt.split('@'); if (part.length == 2) { //#region ホスト名部分が省略されているので復元する ...
identifier_body
contours.py
#!/usr/bin/env python ''' This program illustrates the use of findContours and drawContours. The original image is put up along with the image of drawn contours. Usage: contours.py A trackbar is put up which controls the contour level from -3 to 3 ''' # Python 2/3 compatibility from __future__ import print_funct...
black, white = 0, 255 for i in xrange(6): dx = int((i%2)*250 - 30) dy = int((i/2.)*150) if i == 0: for j in xrange(11): angle = (j+5)*np.pi/21 c, s = np.cos(angle), np.sin(angle) x1, y1 = np.int32([dx+100+j*10-80*c, dy+100-90*s...
random_line_split
contours.py
#!/usr/bin/env python ''' This program illustrates the use of findContours and drawContours. The original image is put up along with the image of drawn contours. Usage: contours.py A trackbar is put up which controls the contour level from -3 to 3 ''' # Python 2/3 compatibility from __future__ import print_funct...
cv2.ellipse( img, (dx+150, dy+100), (100,70), 0, 0, 360, white, -1 ) cv2.ellipse( img, (dx+115, dy+70), (30,20), 0, 0, 360, black, -1 ) cv2.ellipse( img, (dx+185, dy+70), (30,20), 0, 0, 360, black, -1 ) cv2.ellipse( img, (dx+115, dy+70), (15,15), 0, 0, 360, white, -1 ) cv2.elli...
for j in xrange(11): angle = (j+5)*np.pi/21 c, s = np.cos(angle), np.sin(angle) x1, y1 = np.int32([dx+100+j*10-80*c, dy+100-90*s]) x2, y2 = np.int32([dx+100+j*10-30*c, dy+100-30*s]) cv2.line(img, (x1, y1), (x2, y2), white)
conditional_block
contours.py
#!/usr/bin/env python ''' This program illustrates the use of findContours and drawContours. The original image is put up along with the image of drawn contours. Usage: contours.py A trackbar is put up which controls the contour level from -3 to 3 ''' # Python 2/3 compatibility from __future__ import print_funct...
(): img = np.zeros((500, 500), np.uint8) black, white = 0, 255 for i in xrange(6): dx = int((i%2)*250 - 30) dy = int((i/2.)*150) if i == 0: for j in xrange(11): angle = (j+5)*np.pi/21 c, s = np.cos(angle), np.sin(angle) x1,...
make_image
identifier_name
contours.py
#!/usr/bin/env python ''' This program illustrates the use of findContours and drawContours. The original image is put up along with the image of drawn contours. Usage: contours.py A trackbar is put up which controls the contour level from -3 to 3 ''' # Python 2/3 compatibility from __future__ import print_funct...
cv2.ellipse( img, (dx+185, dy+70), (5,5), 0, 0, 360, black, -1 ) cv2.ellipse( img, (dx+150, dy+100), (10,5), 0, 0, 360, black, -1 ) cv2.ellipse( img, (dx+150, dy+150), (40,10), 0, 0, 360, black, -1 ) cv2.ellipse( img, (dx+27, dy+100), (20,35), 0, 0, 360, white, -1 ) cv2.ellipse( ...
img = np.zeros((500, 500), np.uint8) black, white = 0, 255 for i in xrange(6): dx = int((i%2)*250 - 30) dy = int((i/2.)*150) if i == 0: for j in xrange(11): angle = (j+5)*np.pi/21 c, s = np.cos(angle), np.sin(angle) x1, y1 = np...
identifier_body
member.js
import { block, insertAfter, clearSelection, prepend, detach, freeSelect } from "../../domUtils"; import { updateGrid } from "../index"; import { addChange } from "../changes"; import { Toast } from "../../toast"; import { getKeywordView } from "./keyword"; import MANIFEST from "./MANIFEST"; import { MEMBER_SECTIONS, g...
({ headerElement, classData, classBlockName, classBlockPropName, classBlockElement, serviceData }) { let isClass = !classBlockName, opened = false, container, controls, savePath = isClass ? [classData["Name"]] : [classData["Name"], classBlockName, classBlock...
enableMember
identifier_name
member.js
import { block, insertAfter, clearSelection, prepend, detach, freeSelect } from "../../domUtils"; import { updateGrid } from "../index"; import { addChange } from "../changes"; import { Toast } from "../../toast"; import { getKeywordView } from "./keyword"; import MANIFEST from "./MANIFEST"; import { MEMBER_SECTIONS, g...
/** * @param classData * @param [classBlockName] * @param [classBlockPropName] * @param {HTMLElement} classBlockElement * @param {*} [serviceData] - Object with additional properties passed through all the members. * @returns {HTMLElement} */ export function getMemberBlock ({ classData, classBlockName, cla...
{ let iconsBlock = block(`div`, `icons`); if (!isClass) iconsBlock.appendChild( block(`div`, `icon ${ memberData["Private"] ? "private" : "public" }`) ); return iconsBlock; }
identifier_body
member.js
import { block, insertAfter, clearSelection, prepend, detach, freeSelect } from "../../domUtils"; import { updateGrid } from "../index"; import { addChange } from "../changes"; import { Toast } from "../../toast"; import { getKeywordView } from "./keyword"; import MANIFEST from "./MANIFEST"; import { MEMBER_SECTIONS, g...
headerElement.classList.toggle("opened"); if (classBlockName === "Methods" || classBlockName === "XDatas") { serviceData[`visualCodeBlocksOpened`] += opened ? 1 : -1; updateGridElement(serviceData[`cardElement`], { width: serviceData[`cardWidth`] = serviceData[`...
{ container.parentNode.removeChild(container); controls.parentNode.removeChild(controls); clearSelection(); }
conditional_block
member.js
import { block, insertAfter, clearSelection, prepend, detach, freeSelect } from "../../domUtils"; import { updateGrid } from "../index"; import { addChange } from "../changes"; import { Toast } from "../../toast"; import { getKeywordView } from "./keyword"; import MANIFEST from "./MANIFEST"; import { MEMBER_SECTIONS, g...
comment.innerHTML.replace(/<br\s*\/?>/, "<br/>\n") ); }); if (data["Description"]) comment.innerHTML = data["Description"]; comment.setAttribute("placeholder", "< Add comment >"); for (let propName in data) { let propManifest = (MANIFEST[isClass ? "Class" : ...
addChange( isClass ? [classData["Name"], "Description"] : [classData["Name"], memberType, classMemberName, "Description"],
random_line_split
mapObjIndexed.js
var assert = require('assert'); var R = require('..'); describe('mapObjIndexed', function() { var times2 = function(x) {return x * 2;}; var addIndexed = function(x, key) {return x + key;}; var squareVowels = function(x, key) { var vowels = ['a', 'e', 'i', 'o', 'u']; return R.contains(key, vowels) ? x *...
assert.deepEqual(R.mapObjIndexed(squareVowels, {a: 8, b: 6, c: 7, d: 5, e: 3, f: 0, g: 9}), {a: 64, b: 6, c: 7, d: 5, e: 9, f: 0, g: 9}); }); it('is curried', function() { var makeSquareVowels = R.mapObjIndexed(squareVowels); assert.deepEqual(makeSquareVowels({a: 8, b: 6, c: 7, d: ...
assert.deepEqual(R.mapObjIndexed(addIndexed, {a: 8, b: 6, c: 7, d: 5, e: 3, f: 0, g: 9}), {a: '8a', b: '6b', c: '7c', d: '5d', e: '3e', f: '0f', g: '9g'}); }); it('passes the entire list as a third parameter to the callback', function() {
random_line_split
JsPackageManager.ts
} from '@storybook/semver'; import { sync as spawnSync } from 'cross-spawn'; import { commandLog } from '../helpers'; import { PackageJson, PackageJsonWithDepsAndDevDeps } from './PackageJson'; import { readPackageJson, writePackageJson } from './PackageJsonHelper'; import storybookPackagesVersions from '../versions.j...
if (commandResult.status
stdio: stdio ?? 'pipe', encoding: 'utf-8', });
random_line_split
JsPackageManager.ts
} from '@storybook/semver'; import { sync as spawnSync } from 'cross-spawn'; import { commandLog } from '../helpers'; import { PackageJson, PackageJsonWithDepsAndDevDeps } from './PackageJson'; import { readPackageJson, writePackageJson } from './PackageJsonHelper'; import storybookPackagesVersions from '../versions.j...
return { ...packageJson, dependencies: { ...packageJson.dependencies }, devDependencies: { ...packageJson.devDependencies }, }; } /** * Add dependencies to a project using `yarn add` or `npm install`. * * @param {Object} options contains `skipInstall`, `packageJson` and `instal...
{ // It will create a new package.json file this.initPackageJson(); // read the newly created package.json file packageJson = readPackageJson() || {}; }
conditional_block
JsPackageManager.ts
} from '@storybook/semver'; import { sync as spawnSync } from 'cross-spawn'; import { commandLog } from '../helpers'; import { PackageJson, PackageJsonWithDepsAndDevDeps } from './PackageJson'; import { readPackageJson, writePackageJson } from './PackageJsonHelper'; import storybookPackagesVersions from '../versions.j...
(command: string, args: string[], stdio?: 'pipe' | 'inherit'): string { const commandResult = spawnSync(command, args, { stdio: stdio ?? 'pipe', encoding: 'utf-8', }); if (commandResult.status
executeCommand
identifier_name
JsPackageManager.ts
} from '@storybook/semver'; import { sync as spawnSync } from 'cross-spawn'; import { commandLog } from '../helpers'; import { PackageJson, PackageJsonWithDepsAndDevDeps } from './PackageJson'; import { readPackageJson, writePackageJson } from './PackageJsonHelper'; import storybookPackagesVersions from '../versions.j...
/** * Return an array of string standing for the latest version of the input packages. * To be able to identify which version goes with which package the order of the input array is keep. * * @param packageNames */ public getVersions(...packageNames: string[]): Promise<string[]> { return Promis...
{ return Promise.all( packages.map(async (pkg) => { const [packageName, packageVersion] = getPackageDetails(pkg); return `${packageName}@${await this.getVersion(packageName, packageVersion)}`; }) ); }
identifier_body
AboutApplyingWhatWeHaveLearnt.js
var _; //globals
var products; beforeEach(function () { products = [ { name: "Sonoma", ingredients: ["artichoke", "sundried tomatoes", "mushrooms"], containsNuts: false }, { name: "Pizza Primavera", ingredients: ["roma", "sundried tomatoes", "goats cheese", "rosemary"], containsNuts: false }, { name: "Sout...
describe("About Applying What We Have Learnt", function() {
random_line_split
AboutApplyingWhatWeHaveLearnt.js
var _; //globals describe("About Applying What We Have Learnt", function() { var products; beforeEach(function () { products = [ { name: "Sonoma", ingredients: ["artichoke", "sundried tomatoes", "mushrooms"], containsNuts: false }, { name: "Pizza Primavera", ingredients: ["roma", "sundried toma...
if (!hasMushrooms) productsICanEat.push(products[i]); } } expect(productsICanEat.length).toBe(1); }); it("given I'm allergic to nuts and hate mushrooms, it should find a pizza I can eat (functional)", function () { var productsICanEat = []; var noNuts = _(products).filter...
{ if (products[i].ingredients[j] === "mushrooms") { hasMushrooms = true; } }
conditional_block
Service.d.ts
import Serverless = require('../index'); declare namespace Service { interface Custom { [key: string]: any; } } declare class Service { custom: Service.Custom; provider: { compiledCloudFormationTemplate: { Resources: { [key: string]: any; }; ...
name: string; stage: string; region: string; runtime?: string | undefined; timeout?: number | undefined; versionFunctions: boolean; }; serverless: Serverless; service: string | null; plugins: string[]; pluginsData: { [key: string]: any }; functions...
};
random_line_split
Service.d.ts
import Serverless = require('../index'); declare namespace Service { interface Custom { [key: string]: any; } } declare class
{ custom: Service.Custom; provider: { compiledCloudFormationTemplate: { Resources: { [key: string]: any; }; Outputs?: { [key: string]: any; } | undefined; }; name: string; stage: string; re...
Service
identifier_name
servicehost.js
import {normalize, resolve} from "path"; import {existsSync, readFileSync} from "fs"; import {sys, ScriptSnapshot, resolveModuleName, getDefaultLibFilePath} from "typescript"; export function createServiceHost(options, filenames, cwd) { const normalizePath = (path) => resolve(normalize(path)); const moduleResoluti...
() { return options; }, getCurrentDirectory() { return cwd; }, getScriptFileNames() { return Object.keys(files); }, getScriptVersion(filename) { const f = files[normalizePath(filename)]; return f ? f.version.toString() : ""; }, getScriptSnapshot(filename) { let f = files[normalizeP...
getCompilationSettings
identifier_name
servicehost.js
import {normalize, resolve} from "path"; import {existsSync, readFileSync} from "fs"; import {sys, ScriptSnapshot, resolveModuleName, getDefaultLibFilePath} from "typescript"; export function createServiceHost(options, filenames, cwd) { const normalizePath = (path) => resolve(normalize(path)); const moduleResoluti...
, getCompilationSettings() { return options; }, getCurrentDirectory() { return cwd; }, getScriptFileNames() { return Object.keys(files); }, getScriptVersion(filename) { const f = files[normalizePath(filename)]; return f ? f.version.toString() : ""; }, getScriptSnapshot(filename) { ...
{ return readFileSync(normalizePath(filename), "utf-8"); }
identifier_body
servicehost.js
import {normalize, resolve} from "path";
export function createServiceHost(options, filenames, cwd) { const normalizePath = (path) => resolve(normalize(path)); const moduleResolutionHost = createModuleResolutionHost(); const files = {}; // normalized filename => {version, snap, text} filenames.forEach(filename => files[normalizePath(filename)] = null);...
import {existsSync, readFileSync} from "fs"; import {sys, ScriptSnapshot, resolveModuleName, getDefaultLibFilePath} from "typescript";
random_line_split
servicehost.js
import {normalize, resolve} from "path"; import {existsSync, readFileSync} from "fs"; import {sys, ScriptSnapshot, resolveModuleName, getDefaultLibFilePath} from "typescript"; export function createServiceHost(options, filenames, cwd) { const normalizePath = (path) => resolve(normalize(path)); const moduleResoluti...
++file.version; file.snap = snap; file.text = text; return file; }, }; } function createModuleResolutionHost() { return { fileExists(filename) { return existsSync(filename); }, readFile(filename) { return readFileSync(filename, "utf-8") }, }; }
{ file = {version: 0}; files[filename] = file; }
conditional_block
main.rs
::fs; use std::fs::File; use std::error::Error; use std::path::{Path, PathBuf}; use std::env; use itertools::Itertools; use std::cell::{Cell, RefCell}; use std::str::FromStr; use gdk::enums::key; use gdk::keyval_to_unicode; use autocomplete::Completion; use engine::DefaultEngine; use engine::Engine; #[macro_export] ma...
}); window.set_border_width(0); window.set_decorated(false); window.show_all(); let column_types = [glib::Type::String]; let completion_store = ListStore::new(&column_types); completion_list.set_model(Some(&completion_store)); completion_list.set_headers_visible(false); append_text...
{ gtk::init().unwrap_or_else(|_| panic!("Failed to initialize GTK.")); debug!("Major: {}, Minor: {}", gtk::get_major_version(), gtk::get_minor_version()); let ui_path = config_directory.join(Path::new("rrun.glade")); let ui_file = get_or_create(&ui_path, include_str!("rrun.glade")) .unwrap_or_el...
identifier_body
main.rs
std::fs; use std::fs::File; use std::error::Error; use std::path::{Path, PathBuf}; use std::env; use itertools::Itertools; use std::cell::{Cell, RefCell}; use std::str::FromStr; use gdk::enums::key; use gdk::keyval_to_unicode; use autocomplete::Completion; use engine::DefaultEngine; use engine::Engine; #[macro_export...
let (ref current_completions, ref selected_completion) = current_and_selected_completions; *selected_completion.borrow_mut() = Some(current_completions.borrow()[selected_number].clone()); } } }); window.connect_key_release_event(move |_, key| { let ke...
let selected_number = usize::from_str(path.to_string().trim()).unwrap();
random_line_split
main.rs
::fs; use std::fs::File; use std::error::Error; use std::path::{Path, PathBuf}; use std::env; use itertools::Itertools; use std::cell::{Cell, RefCell}; use std::str::FromStr; use gdk::enums::key; use gdk::keyval_to_unicode; use autocomplete::Completion; use engine::DefaultEngine; use engine::Engine; #[macro_export] ma...
(config_directory: &Path, engine: DefaultEngine) { gtk::init().unwrap_or_else(|_| panic!("Failed to initialize GTK.")); debug!("Major: {}, Minor: {}", gtk::get_major_version(), gtk::get_minor_version()); let ui_path = config_directory.join(Path::new("rrun.glade")); let ui_file = get_or_create(&ui_path, ...
run_ui
identifier_name
main.rs
::fs; use std::fs::File; use std::error::Error; use std::path::{Path, PathBuf}; use std::env; use itertools::Itertools; use std::cell::{Cell, RefCell}; use std::str::FromStr; use gdk::enums::key; use gdk::keyval_to_unicode; use autocomplete::Completion; use engine::DefaultEngine; use engine::Engine; #[macro_export] ma...
} else { run_ui(&config_directory, engine); } } fn run_ui(config_directory: &Path, engine: DefaultEngine) { gtk::init().unwrap_or_else(|_| panic!("Failed to initialize GTK.")); debug!("Major: {}, Minor: {}", gtk::get_major_version(), gtk::get_minor_version()); let ui_path = config_director...
{ panic!("If you call completions, you need to provide type and query\nIf unsure, run 'rrun completions \ --help'") }
conditional_block
declareFunctionSupport.js
/** * @project : modula * @package : core * @internal : declareFunctionSupport * @type : function * @dependencies : none * * @description : * the support is used to build crossbrowser compatible modula.js functions. * * @example * support.test = support( function() { return true; } ); // result support.test...
return !!fn( div ); // catch if error occured ... } catch( e ) { // and return false return false; // finally ... } finally { // remove div if added to the document div.parentNode && div.parentNode.removeChild( div ); // delete div for memory release div = null; }; } );
// try to ... try { // execute fn with the created div
random_line_split
index.ts
import styled, { createGlobalStyle } from "styled-components"; import { appFont, AppColors, Colors } from "../../util/constants"; export const AppStyle = createGlobalStyle` html, body { font-family: ${appFont}; text-rendering: optimizeLegibility; font-feature-settings: "kern" 1, "dlig" 1, "tnum" 0, "ss01...
flex-direction: column; height: 100vh; top: 0; left: 0; right: 0; bottom: 0; @media print { height: 100vh; } `;
padding: 0; position: absolute; overflow: hidden; width: 100vw; display: flex;
random_line_split
photoimport.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import logging import os import re import sys from io import BytesIO from PIL import Image from triptools import config, DB from triptools.common import Trackpoint, tp_dist, distance, get_names from triptools.exif_support import get_location logging.basicConfig(level=lo...
if __name__ == "__main__": with DB() as db: for filename in get_names(config.get("Photo", "name"), config.get("Photo", "mask")): try: logging.getLogger(__name__).info("Processing %s" % filename) if db.get_photo(filename) and not config.getboolean("Photo", "refr...
"""Return PNG thumbnail as bytes object""" max_x = config.getint("Photo", "thumbwidth") max_y = config.getint("Photo", "thumbheight") im = Image.open(filename) x, y = im.size scale = max(x / max_x, y / max_y) im.thumbnail((int(x/scale), int(y/scale)), Image.ANTIALIAS) buffer = BytesIO() ...
identifier_body
photoimport.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import logging import os
import re import sys from io import BytesIO from PIL import Image from triptools import config, DB from triptools.common import Trackpoint, tp_dist, distance, get_names from triptools.exif_support import get_location logging.basicConfig(level=logging.INFO) def get_thumbnail(filename): """Return PNG thumbnail as ...
random_line_split
photoimport.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import logging import os import re import sys from io import BytesIO from PIL import Image from triptools import config, DB from triptools.common import Trackpoint, tp_dist, distance, get_names from triptools.exif_support import get_location logging.basicConfig(level=lo...
(filename): """Return PNG thumbnail as bytes object""" max_x = config.getint("Photo", "thumbwidth") max_y = config.getint("Photo", "thumbheight") im = Image.open(filename) x, y = im.size scale = max(x / max_x, y / max_y) im.thumbnail((int(x/scale), int(y/scale)), Image.ANTIALIAS) buffer ...
get_thumbnail
identifier_name
photoimport.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import logging import os import re import sys from io import BytesIO from PIL import Image from triptools import config, DB from triptools.common import Trackpoint, tp_dist, distance, get_names from triptools.exif_support import get_location logging.basicConfig(level=lo...
try: logging.getLogger(__name__).info("Processing %s" % filename) if db.get_photo(filename) and not config.getboolean("Photo", "refresh"): logging.getLogger(__name__).info("Photo %s already imported." % filename) continue ...
conditional_block
auth-guard.service.ts
import { Injectable } from '@angular/core'; import { ActivatedRouteSnapshot, RouterStateSnapshot, Router, Route, CanActivate, CanActivateChild, CanLoad } from '@angular/router'; import { AuthService } from './auth.service'; @Injectable() export  class AuthGuard implements CanActivate, CanActivateChild, CanLo...
}
if (this.authService.isLoggedIn()) { return true; } // Retain the attempted URL for redirection this.authService.redirectUrl = url; this.router.navigate(['/login']); return false; }
identifier_body
auth-guard.service.ts
import { Injectable } from '@angular/core'; import { ActivatedRouteSnapshot, RouterStateSnapshot, Router, Route, CanActivate, CanActivateChild, CanLoad } from '@angular/router'; import { AuthService } from './auth.service'; @Injectable() export  class AuthGuard implements CanActivate, CanActivateChild, CanLo...
// Retain the attempted URL for redirection this.authService.redirectUrl = url; this.router.navigate(['/login']); return false; } }
return true; }
conditional_block
auth-guard.service.ts
import { Injectable } from '@angular/core'; import { ActivatedRouteSnapshot, RouterStateSnapshot, Router, Route, CanActivate, CanActivateChild, CanLoad } from '@angular/router'; import { AuthService } from './auth.service';
@Injectable() export  class AuthGuard implements CanActivate, CanActivateChild, CanLoad { constructor(private authService: AuthService, private router: Router) { } canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean { console.log('In canActivate: ' + state....
random_line_split
auth-guard.service.ts
import { Injectable } from '@angular/core'; import { ActivatedRouteSnapshot, RouterStateSnapshot, Router, Route, CanActivate, CanActivateChild, CanLoad } from '@angular/router'; import { AuthService } from './auth.service'; @Injectable() export  class AuthGuard implements CanActivate, CanActivateChild, CanLo...
url: string): boolean { if (this.authService.isLoggedIn()) { return true; } // Retain the attempted URL for redirection this.authService.redirectUrl = url; this.router.navigate(['/login']); return false; } }
heckLoggedIn(
identifier_name
regionmanip.rs
mut wf = Wf { tcx: tcx, stack: stack, out: Vec::new() }; wf.accumulate_from_ty(ty); wf.out } impl<'a, 'tcx> Wf<'a, 'tcx> { fn accumulate_from_ty(&mut self, ty: Ty<'tcx>) { debug!("Wf::accumulate_from_ty(ty={})", ty.repr(self.tcx)); ...
ty::ty_open(_) => { self.tcx.sess.bug( &format!("Unexpected type encountered while doing wf check: {}", ty.repr(self.tcx))[]); } } } fn accumulate_from_rptr(&mut self, ty: Ty<'tcx>, ...
random_line_split
regionmanip.rs
mut wf = Wf { tcx: tcx, stack: stack, out: Vec::new() }; wf.accumulate_from_ty(ty); wf.out } impl<'a, 'tcx> Wf<'a, 'tcx> { fn accumulate_from_ty(&mut self, ty: Ty<'tcx>) { debug!("Wf::accumulate_from_ty(ty={})", ty.repr(self.tcx)); ...
/// Pushes a constraint that `region <= param_ty`, due to `opt_ty` fn push_param_constraint(&mut self, region: ty::Region, opt_ty: Option<Ty<'tcx>>, param_ty: ty::ParamTy) { self.out.push(RegionSubGenericConstraint(...
{ let &(region, opt_ty) = self.stack.last().unwrap(); self.out.push(RegionSubGenericConstraint( opt_ty, region, GenericKind::Projection(projection_ty.clone()))); }
identifier_body
regionmanip.rs
enclosing parameter // environment. An upvar captured by value has the // same type as the original local variable which is // already checked for consistency. If the upvar is // captured by reference it must also outlive the // region b...
accumulate_from_object_ty
identifier_name
Main.py
#!/usr/bin/python # -*- coding: utf-8 -*- ##################################################################### # Frets on Fire X (FoFiX) # # Copyright (C) 2006 Sami Kyöstilä # # 2008 evilynux <evilynux@gmail.com> ...
elf): log.info("Restarting.") self.engine.audio.close() self.restartRequested = True def run(self): # Perhaps this could be implemented in a better way... # Play the intro video if it is present, we have the capability themename = Config.get("coffee", "themename") ...
start(s
identifier_name
Main.py
#!/usr/bin/python # -*- coding: utf-8 -*- ##################################################################### # Frets on Fire X (FoFiX) # # Copyright (C) 2006 Sami Kyöstilä # # 2008 evilynux <evilynux@gmail.com> ...
# # # You should have received a copy of the GNU General Public License # # along with this program; if not, write to the Free Software # # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # # MA 02110-1301, USA. ...
# This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU General Public License for more details. #
random_line_split
Main.py
#!/usr/bin/python # -*- coding: utf-8 -*- ##################################################################### # Frets on Fire X (FoFiX) # # Copyright (C) 2006 Sami Kyöstilä # # 2008 evilynux <evilynux@gmail.com> ...
def restart(self): log.info("Restarting.") self.engine.audio.close() self.restartRequested = True def run(self): # Perhaps this could be implemented in a better way... # Play the intro video if it is present, we have the capability themename = Config.get("coffee"...
' Load the configuration file. ''' if configPath is not None: if configPath.lower() == "reset": # Get os specific location of config file, and remove it. fileName = os.path.join(VFS.getWritableResourcePath(), Version.PROGRAM_UNIXSTYLE_NAME + ".ini") o...
identifier_body
Main.py
#!/usr/bin/python # -*- coding: utf-8 -*- ##################################################################### # Frets on Fire X (FoFiX) # # Copyright (C) 2006 Sami Kyöstilä # # 2008 evilynux <evilynux@gmail.com> ...
# Lysdestic - Change resolution from CLI if self.resolution is not None: Config.set("video", "resolution", self.resolution) # Lysdestic - Alter theme from CLI if self.theme is not None: Config.set("coffee", "themename", self.theme) self.engine = GameEngi...
nfig.set("video", "fullscreen", self.fullscreen)
conditional_block
main.dev.js
/******/ (function(modules) { // webpackBootstrap /******/ // install a JSONP callback for chunk loading /******/ function webpackJsonpCallback(data) { /******/ var chunkIds = data[0]; /******/ var moreModules = data[1]; /******/ var executeModules = data[2]; /******/ /******/ // add "moreModules" to the modu...
(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /*...
__webpack_require__
identifier_name
main.dev.js
/******/ (function(modules) { // webpackBootstrap /******/ // install a JSONP callback for chunk loading /******/ function webpackJsonpCallback(data) { /******/ var chunkIds = data[0]; /******/ var moreModules = data[1]; /******/ var executeModules = data[2]; /******/ /******/ // add "moreModules" to the modu...
/******/ } /******/ installedChunks[chunkId] = 0; /******/ } /******/ for(moduleId in moreModules) { /******/ if(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) { /******/ modules[moduleId] = moreModules[moduleId]; /******/ } /******/ } /******/ if(parentJsonpFunction) parentJsonpFu...
/******/ chunkId = chunkIds[i]; /******/ if(installedChunks[chunkId]) { /******/ resolves.push(installedChunks[chunkId][0]);
random_line_split
main.dev.js
/******/ (function(modules) { // webpackBootstrap /******/ // install a JSONP callback for chunk loading /******/ function webpackJsonpCallback(data) { /******/ var chunkIds = data[0]; /******/ var moreModules = data[1]; /******/ var executeModules = data[2]; /******/ /******/ // add "moreModules" to the modu...
/******/ /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // object to store loaded and loading chunks /******/ // undefined = chunk not loaded, null = chunk preloaded/prefetched /******/ // Promise = chunk loading, 0 = chunk loaded /******/ var installedChunks = { /******/ "p...
{ /******/ var result; /******/ for(var i = 0; i < deferredModules.length; i++) { /******/ var deferredModule = deferredModules[i]; /******/ var fulfilled = true; /******/ for(var j = 1; j < deferredModule.length; j++) { /******/ var depId = deferredModule[j]; /******/ if(installedChunks[depId] !==...
identifier_body
main.dev.js
/******/ (function(modules) { // webpackBootstrap /******/ // install a JSONP callback for chunk loading /******/ function webpackJsonpCallback(data) { /******/ var chunkIds = data[0]; /******/ var moreModules = data[1]; /******/ var executeModules = data[2]; /******/ /******/ // add "moreModules" to the modu...
/******/ if(fulfilled) { /******/ deferredModules.splice(i--, 1); /******/ result = __webpack_require__(__webpack_require__.s = deferredModule[0]); /******/ } /******/ } /******/ return result; /******/ } /******/ /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ ...
{ /******/ var depId = deferredModule[j]; /******/ if(installedChunks[depId] !== 0) fulfilled = false; /******/ }
conditional_block
rectangle.rs
use crate::{ style::Color, widgets::canvas::{Line, Painter, Shape}, }; /// Shape to draw a rectangle from a `Rect` with the given color #[derive(Debug, Clone)] pub struct Rectangle { pub x: f64, pub y: f64, pub width: f64, pub height: f64, pub color: Color, } impl Shape for Rectangle { ...
(&self, painter: &mut Painter) { let lines: [Line; 4] = [ Line { x1: self.x, y1: self.y, x2: self.x, y2: self.y + self.height, color: self.color, }, Line { x1: self.x, ...
draw
identifier_name
rectangle.rs
use crate::{ style::Color, widgets::canvas::{Line, Painter, Shape}, }; /// Shape to draw a rectangle from a `Rect` with the given color #[derive(Debug, Clone)] pub struct Rectangle { pub x: f64, pub y: f64, pub width: f64, pub height: f64, pub color: Color, } impl Shape for Rectangle { ...
y2: self.y + self.height, color: self.color, }, Line { x1: self.x, y1: self.y, x2: self.x + self.width, y2: self.y, color: self.color, }, ]; for line in &li...
{ let lines: [Line; 4] = [ Line { x1: self.x, y1: self.y, x2: self.x, y2: self.y + self.height, color: self.color, }, Line { x1: self.x, y1: self.y + self.height, ...
identifier_body
rectangle.rs
use crate::{ style::Color, widgets::canvas::{Line, Painter, Shape}, }; /// Shape to draw a rectangle from a `Rect` with the given color #[derive(Debug, Clone)] pub struct Rectangle { pub x: f64, pub y: f64, pub width: f64, pub height: f64, pub color: Color, } impl Shape for Rectangle { ...
y2: self.y + self.height, color: self.color, }, Line { x1: self.x, y1: self.y + self.height, x2: self.x + self.width, y2: self.y + self.height, color: self.color, }, ...
let lines: [Line; 4] = [ Line { x1: self.x, y1: self.y, x2: self.x,
random_line_split
helper_functions.py
from base import data_set from base.trait import create_trait from base.species import TheSpecies from utility import hmac from flask import g import logging logger = logging.getLogger(__name__) def get_species_dataset_trait(self, start_vars):
def get_trait_db_obs(self, trait_db_list): if isinstance(trait_db_list, str): trait_db_list = trait_db_list.split(",") self.trait_list = [] for trait in trait_db_list: data, _separator, hmac_string = trait.rpartition(':') data = data.strip() assert hmac_string == hmac.hmac...
if "temp_trait" in list(start_vars.keys()): if start_vars['temp_trait'] == "True": self.dataset = data_set.create_dataset( dataset_name="Temp", dataset_type="Temp", group_name=start_vars['group']) else: self.dataset = data_set.creat...
identifier_body
helper_functions.py
from base import data_set from base.trait import create_trait from base.species import TheSpecies from utility import hmac from flask import g import logging logger = logging.getLogger(__name__) def
(self, start_vars): if "temp_trait" in list(start_vars.keys()): if start_vars['temp_trait'] == "True": self.dataset = data_set.create_dataset( dataset_name="Temp", dataset_type="Temp", group_name=start_vars['group']) else: self....
get_species_dataset_trait
identifier_name
helper_functions.py
from base import data_set from base.trait import create_trait from base.species import TheSpecies from utility import hmac from flask import g import logging logger = logging.getLogger(__name__) def get_species_dataset_trait(self, start_vars): if "temp_trait" in list(start_vars.keys()): if start_vars['...
self.trait_list = [] for trait in trait_db_list: data, _separator, hmac_string = trait.rpartition(':') data = data.strip() assert hmac_string == hmac.hmac_creation(data), "Data tampering?" trait_name, dataset_name = data.split(":")[:2] if dataset_name == "Temp": ...
trait_db_list = trait_db_list.split(",")
conditional_block
helper_functions.py
from base import data_set from base.trait import create_trait from base.species import TheSpecies from utility import hmac from flask import g import logging logger = logging.getLogger(__name__) def get_species_dataset_trait(self, start_vars): if "temp_trait" in list(start_vars.keys()): if start_vars['...
self.dataset = data_set.create_dataset(start_vars['dataset']) else: self.dataset = data_set.create_dataset(start_vars['dataset']) self.species = TheSpecies(dataset=self.dataset) self.this_trait = create_trait(dataset=self.dataset, name=start_vars['trait...
dataset_type="Temp", group_name=start_vars['group']) else:
random_line_split
editable.tsx
import React from "react"; import TextareaAutosize from 'react-textarea-autosize'; import {RiEdit2Line} from "react-icons/ri"; import {RiEraserLine} from "react-icons/ri"; type Props = { onFocus?(value: string): void, onFocusOut?(value: string): void, editingClassName :string, value :string, }; type ...
(event :React.MouseEvent | React.FocusEvent) { if (this.state.isEditing) { if (typeof this.props.onFocusOut === "function") { this.props.onFocusOut(this.state.value); } this.setState({isEditing: false}); } else { if (typeof this.props.onFoc...
handleFocus
identifier_name
editable.tsx
import React from "react"; import TextareaAutosize from 'react-textarea-autosize'; import {RiEdit2Line} from "react-icons/ri"; import {RiEraserLine} from "react-icons/ri"; type Props = { onFocus?(value: string): void, onFocusOut?(value: string): void, editingClassName :string, value :string, }; type ...
} handleFocus(event :React.MouseEvent | React.FocusEvent) { if (this.state.isEditing) { if (typeof this.props.onFocusOut === "function") { this.props.onFocusOut(this.state.value); } this.setState({isEditing: false}); } else { if (...
{ this.setState({ value: nextProps.value }); }
conditional_block
editable.tsx
import React from "react"; import TextareaAutosize from 'react-textarea-autosize'; import {RiEdit2Line} from "react-icons/ri"; import {RiEraserLine} from "react-icons/ri"; type Props = { onFocus?(value: string): void, onFocusOut?(value: string): void, editingClassName :string, value :string, }; type ...
componentWillReceiveProps(nextProps: Props) { // Updating state when editing overwrites user changes in edit field if (!this.state.isEditing) { this.setState({ value: nextProps.value }); } } handleFocus(event :React.MouseEvent | React.FocusEvent) { if (this.sta...
{ super(props); this.state.value = this.props.value; this.handleFocus = this.handleFocus.bind(this); this.handleChange = this.handleChange.bind(this); this.emptyValue = this.emptyValue.bind(this); }
identifier_body
editable.tsx
import React from "react"; import TextareaAutosize from 'react-textarea-autosize'; import {RiEdit2Line} from "react-icons/ri"; import {RiEraserLine} from "react-icons/ri"; type Props = { onFocus?(value: string): void, onFocusOut?(value: string): void, editingClassName :string, value :string, }; type ...
minRows={1} maxRows={3} value={this.state.value} onBlur={this.handleFocus} onClick={this.handleFocus} onChange={this.handleChange} className={`textarea ...
render() { return ( <div className="columns is-mobile is-vcentered inlineedit"> <div className={"column"}> <TextareaAutosize
random_line_split
brython_fourbar1.py
�為線頭 self.Head = self.p2 # 直線的長度屬性 self.length = math.sqrt(math.pow(self.p2.x-self.p1.x, 2)+math.pow(self.p2.y-self.p1.y,2)) # setPP 以指定頭尾座標點來定義直線 def setPP(self, p1, p2): self.p1 = p1 self.p2 = p2 self.Tail = self.p1 self.Head = self.p2 self.leng...
n self.Tail def drawMe(self, g): self.g = g self.g.beginPath() self.g.moveTo(self.p1.x,self.p1.y) self.g.lineTo(self.p2.x,self.p2.y) self.g.stroke() def test(self): return ("this is pure test to Inherit") class Link(Line): def __init__(self, p1, p2): ...
ead 方法 for Line def getHead(self): return self.Head def getTail(self): retur
conditional_block
brython_fourbar1.py
��為線頭 self.Head = self.p2 # 直線的長度屬性 self.length = math.sqrt(math.pow(self.p2.x-self.p1.x, 2)+math.pow(self.p2.y-self.p1.y,2)) # setPP 以指定頭尾座標點來定義直線 def setPP(self, p1, p2): self.p1 = p1 self.p2 = p2 self.Tail = self.p1 self.Head = self.p2 self.len...
# ends Triangle def # 透過三個邊長定義三角形 def setSSS(self, lenp3, lenp1, lenp2): self.lenp3 = lenp3 self.lenp1 = lenp1 self.lenp2 = lenp2 self.ap1 = math.acos(((self.lenp2 * self.lenp2 + self.lenp3 * self.lenp3) - self.lenp1 * self.lenp1) / (2* self.lenp2 * self.lenp3)) self....
random_line_split
brython_fourbar1.py
��為線頭 self.Head = self.p2 # 直線的長度屬性 self.length = math.sqrt(math.pow(self.p2.x-self.p1.x, 2)+math.pow(self.p2.y-self.p1.y,2)) # setPP 以指定頭尾座標點來定義直線 def setPP(self, p1, p2): self.p1 = p1 self.p2 = p2 self.Tail = self.p1 self.Head = self.p2 self.len...
angle def # 透過三個邊長定義三角形 def setSSS(self, lenp3, lenp1, lenp2): self.lenp3 = lenp3 self.lenp1 = lenp1 self.lenp2 = lenp2 self.ap1 = math.acos(((self.lenp2 * self.lenp2 + self.lenp3 * self.lenp3) - self.lenp1 * self.lenp1) / (2* self.lenp2 * self.lenp3)) self.ap2 = math.aco...
line2 = Line(self.p1,self.p3) line3 = Line(self.p2,self.p3) # 繪出三邊線 line1.drawMe(self.g) line2.drawMe(self.g) line3.drawMe(self.g) # ends Tri
identifier_body
brython_fourbar1.py
# 直線組成的第二點, 設為線頭 self.Head = self.p2 # 直線的長度屬性 self.length = math.sqrt(math.pow(self.p2.x-self.p1.x, 2)+math.pow(self.p2.y-self.p1.y,2)) # setPP 以指定頭尾座標點來定義直線 def setPP(self, p1, p2): self.p1 = p1 self.p2 = p2 self.Tail = self.p1 self.Head = self.p2 ...
identifier_name
quickcheck_limbs.rs
extern crate quickcheck; extern crate ramp; extern crate num_bigint; use quickcheck::TestResult; use ramp::ll::limb; use ramp::ll::limb::Limb; use num_bigint::BigUint; #[cfg(feature = "full-quickcheck")] const QUICKCHECK_THOROUGNESS: u64 = 100; #[cfg(not(feature = "full-quickcheck"))] const QUICKCHECK_THOROUGNESS: u6...
fn check_mul(a: usize, b: usize) -> TestResult { let num_prod = b!(a) * b!(b); let (hw, lw) = limb::mul(l!(a), l!(b)); let ramp_prod = b!(hw.0, lw.0); TestResult::from_bool(ramp_prod == num_prod) } fn check_div(hn: usize, ln: usize, d: usize) -> TestResult { let d ...
random_line_split
Loops.py
''' While x is less than 10 it will print x and add 1 to that number, then print it and so on until that condition is false, which is when x equals 10 ''' condition = input('Enter number: ') x = int(condition) print (' ') print ('While loop:') while x <= 10:
while x > 10: print('True') print (x) print('Number is higher than 10') break # otherwise it will print True forever, like this: # uncomment to run and watch: ''' while True: print('infinite') ''' print (' ') print ('For Loop: ') exampleList = [1,6,7,3,6,9,0] print (' ') print ('See code for refe...
print (x) x += 1 # will stop adding 1 when it reaches 11
conditional_block
Loops.py
''' While x is less than 10 it will print x and add 1 to that number, then print it and so on until that condition is false, which is when x equals 10 ''' condition = input('Enter number: ') x = int(condition) print (' ') print ('While loop:') while x <= 10: print (x) x += 1 # will stop adding 1 wh...
print('Number is higher than 10') break # otherwise it will print True forever, like this: # uncomment to run and watch: ''' while True: print('infinite') ''' print (' ') print ('For Loop: ') exampleList = [1,6,7,3,6,9,0] print (' ') print ('See code for reference') print (' ') for thing in exampleList: ...
print (x)
random_line_split
html.js
if(typeof define !== 'function') var define = require('amdefine')(module); define(["require","deep/deep", "./ajax"],function (require, deep, Ajax)
{ deep.store.jqueryajax = deep.store.jqueryajax || {}; deep.store.jqueryajax.HTML = deep.compose.Classes(Ajax, { headers:{ "Accept" : "text/html; charset=utf-8" }, dataType:"html", bodyParser : function(data){ if(typeof data === 'string') return data; ...
random_line_split
notifier.ts
/** * Generic base class for notifiers. * * Copyright (c) 2017 Mark A. Linton * * Use of this source code is governed by the MIT-style license that is * in the LICENSE file or at https://opensource.org/licenses/MIT. * VERSION 0.1.1 README ## notifier The notifier module provides a base class to implement notifi...
(): void { // Default is to do nothing. } protected listeningStopped(): void { // Default is to do nothing. } }
listeningStarted
identifier_name
notifier.ts
/** * Generic base class for notifiers. * * Copyright (c) 2017 Mark A. Linton * * Use of this source code is governed by the MIT-style license that is * in the LICENSE file or at https://opensource.org/licenses/MIT. * VERSION 0.1.1 README ## notifier The notifier module provides a base class to implement notifi...
/** * Remove a listener, returning the removed listener or null * if there was none. */ listenerDel(listener: T): T { const listeners = this.listenersVar for (let i = 0; i < listeners.length; ++i) { if (listeners[i] === listener) { listeners.splice(i,...
{ this.listenersVar.push(listener) if (this.listenersVar.length === 1) { this.listeningStarted() } return listener }
identifier_body
notifier.ts
/** * Generic base class for notifiers. * * Copyright (c) 2017 Mark A. Linton * * Use of this source code is governed by the MIT-style license that is * in the LICENSE file or at https://opensource.org/licenses/MIT. * VERSION 0.1.1 README ## notifier The notifier module provides a base class to implement notifi...
this.listenersVar.push(listener) if (this.listenersVar.length === 1) { this.listeningStarted() } return listener } /** * Remove a listener, returning the removed listener or null * if there was none. */ listenerDel(listener: T): T { const...
random_line_split
notifier.ts
/** * Generic base class for notifiers. * * Copyright (c) 2017 Mark A. Linton * * Use of this source code is governed by the MIT-style license that is * in the LICENSE file or at https://opensource.org/licenses/MIT. * VERSION 0.1.1 README ## notifier The notifier module provides a base class to implement notifi...
} return null } /** * Remove all the listeners. */ listenerDelAll(): void { if (this.listenersVar.length > 0) { this.listenersVar = [] this.listeningStopped() } } /** * Post a notification to all listeners. Notification shoul...
{ listeners.splice(i, 1) if (listeners.length === 0) { this.listeningStopped() } return listener }
conditional_block
config_check.tsx
import React from "react"; import Const from "../../const"; import ConfigCheck from "../../types/config_check"; type Props = { item: ConfigCheck, }; type State = { item: ConfigCheck, }; class ConfigCheckComponent extends React.Component<Props, State> { state: State = { item: {} as ConfigCheck, ...
componentWillReceiveProps(nextProps: Props) { this.setState({item: nextProps.item}); } getClassName() { switch (this.state.item.Status) { case Const.WARNING: return "is-warning"; case Const.CRITICAL: return "is-danger"; d...
{ super(props); this.state.item = this.props.item; }
identifier_body
config_check.tsx
import React from "react"; import Const from "../../const"; import ConfigCheck from "../../types/config_check"; type Props = { item: ConfigCheck, }; type State = { item: ConfigCheck, }; class ConfigCheckComponent extends React.Component<Props, State> { state: State = { item: {} as ConfigCheck, ...
this.state.item = this.props.item; } componentWillReceiveProps(nextProps: Props) { this.setState({item: nextProps.item}); } getClassName() { switch (this.state.item.Status) { case Const.WARNING: return "is-warning"; case Const.CRITICAL: ...
super(props);
random_line_split
config_check.tsx
import React from "react"; import Const from "../../const"; import ConfigCheck from "../../types/config_check"; type Props = { item: ConfigCheck, }; type State = { item: ConfigCheck, }; class ConfigCheckComponent extends React.Component<Props, State> { state: State = { item: {} as ConfigCheck, ...
() { switch (this.state.item.Status) { case Const.WARNING: return "is-warning"; case Const.CRITICAL: return "is-danger"; default: return ""; } } getStatusStr() { switch (this.state.item.Status) { ...
getClassName
identifier_name
config.py
import codecs from ConfigParser import ConfigParser import os import subprocess import sys import six import twiggy from twiggy import log from twiggy.levels import name2level from xdg import BaseDirectory def asbool(some_value): """ Cast config values to boolean. """ return six.text_type(some_value).lower()...
def load_config(main_section): config = ConfigParser({'log.level': "DEBUG", 'log.file': None}) path = None first_path = BaseDirectory.load_first_config('bugwarrior') if first_path is not None: path = os.path.join(first_path, 'bugwarriorrc') old_path = os.path.expanduser("~/.bugwarriorrc")...
service = config.get(target, 'service') if not service: die("No 'service' in [%s]" % target) if service not in SERVICES: die("'%s' in [%s] is not a valid service." % (service, target)) # Call the service-specific validator SERVICES[service].validate_config(confi...
conditional_block
config.py
import codecs from ConfigParser import ConfigParser import os import subprocess import sys import six import twiggy from twiggy import log from twiggy.levels import name2level from xdg import BaseDirectory def asbool(some_value): """ Cast config values to boolean. """ return six.text_type(some_value).lower()...
(main_section): config = ConfigParser({'log.level': "DEBUG", 'log.file': None}) path = None first_path = BaseDirectory.load_first_config('bugwarrior') if first_path is not None: path = os.path.join(first_path, 'bugwarriorrc') old_path = os.path.expanduser("~/.bugwarriorrc") if path is No...
load_config
identifier_name
config.py
import codecs from ConfigParser import ConfigParser import os import subprocess import sys import six import twiggy from twiggy import log from twiggy.levels import name2level from xdg import BaseDirectory def asbool(some_value): """ Cast config values to boolean. """ return six.text_type(some_value).lower()...
config.readfp( codecs.open( path, "r", "utf-8", ) ) config.interactive = False # TODO: make this a command-line option validate_config(config, main_section) return config def get_taskrc_path(conf, main_section): path = '~/.taskrc' if co...
path = old_path else: path = os.path.join(BaseDirectory.save_config_path('bugwarrior'), 'bugwarriorrc')
random_line_split
config.py
import codecs from ConfigParser import ConfigParser import os import subprocess import sys import six import twiggy from twiggy import log from twiggy.levels import name2level from xdg import BaseDirectory def asbool(some_value): """ Cast config values to boolean. """ return six.text_type(some_value).lower()...
# Validate each target one by one. for target in targets: service = config.get(target, 'service') if not service: die("No 'service' in [%s]" % target) if service not in SERVICES: die("'%s' in [%s] is not a valid service." % (service, target)) # Call the...
if not config.has_section(main_section): die("No [%s] section found." % main_section) twiggy.quickSetup( name2level(config.get(main_section, 'log.level')), config.get(main_section, 'log.file') ) if not config.has_option(main_section, 'targets'): die("No targets= item in [%s...
identifier_body