file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
highlight.js
var Highlight = function() { /* Utility functions */ function escape(value) { return value.replace(/&/gm, '&amp;').replace(/</gm, '&lt;').replace(/>/gm, '&gt;'); } function tag(node) { return node.nodeName.toLowerCase(); } function testRe(re, lexeme) { var match = re && re.exec(lexeme); ...
(classname, insideSpan, leaveOpen, noPrefix) { var classPrefix = noPrefix ? '' : options.classPrefix, openSpan = '<span class="' + classPrefix, closeSpan = leaveOpen ? '' : '</span>'; openSpan += classname + '">'; return openSpan + insideSpan + closeSpan; } function...
buildSpan
identifier_name
highlight.js
var Highlight = function() { /* Utility functions */ function escape(value) { return value.replace(/&/gm, '&amp;').replace(/</gm, '&lt;').replace(/>/gm, '&gt;'); } function tag(node) { return node.nodeName.toLowerCase(); } function testRe(re, lexeme) { var match = re && re.exec(lexeme); ...
var text = node.textContent; var result = language ? highlight(language, text, true) : highlightAuto(text); var originalStream = nodeStream(node); if (originalStream.length) { var resultNode = document.createElementNS('http://www.w3.org/1999/xhtml', 'div'); resultNode.innerHTML = result.val...
} else { node = block; }
random_line_split
index.js
/** * lodash 3.0.3 (Custom Build) <https://lodash.com/> * Build: `lodash modularize exports="npm" -o ./` * Copyright 2012-2016 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2016 Jeremy Ashkenas, DocumentCloud and Investigative Rep...
module.exports = isBoolean;
{ return !!value && typeof value == 'object'; }
identifier_body
index.js
/** * lodash 3.0.3 (Custom Build) <https://lodash.com/> * Build: `lodash modularize exports="npm" -o ./` * Copyright 2012-2016 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2016 Jeremy Ashkenas, DocumentCloud and Investigative Rep...
(value) { return value === true || value === false || (isObjectLike(value) && objectToString.call(value) == boolTag); } /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @static * @memberOf _ * @category Lang * @param {*} value T...
isBoolean
identifier_name
index.js
/** * lodash 3.0.3 (Custom Build) <https://lodash.com/> * Build: `lodash modularize exports="npm" -o ./` * Copyright 2012-2016 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2016 Jeremy Ashkenas, DocumentCloud and Investigative Rep...
function isBoolean(value) { return value === true || value === false || (isObjectLike(value) && objectToString.call(value) == boolTag); } /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @static * @memberOf _ * @category Lang * ...
random_line_split
Capture.py
"""This modules is used to capture the screen """ import pyautogui import time import Globals PATH = './Captures/' def capture_area(area): """ Captures area of the screen Args: area (Tuple (x,y,width,height)): Area to capture Returns: Image : Image of the area captured """ ...
save_img(capture_area(area=area), filename) def get_game_screen(): """ Get game screen image Returns: Image : Image of screen area """ return capture_area(area=Globals.GAME_REGION) def save_game_screen(filename=('full_snap_' + str(time.time()))): """ Saves game area scree...
filename = ('area_snap_' + str(area).replace('(', ' ').replace(')', ' '))
conditional_block
Capture.py
"""This modules is used to capture the screen """ import pyautogui import time import Globals PATH = './Captures/' def capture_area(area): """ Captures area of the screen Args: area (Tuple (x,y,width,height)): Area to capture Returns: Image : Image of the area captured """ ...
Returns: Image : Image of screen area """ return capture_area(area=Globals.GAME_REGION) def save_game_screen(filename=('full_snap_' + str(time.time()))): """ Saves game area screen shot to file Args: filename (String): Name of file to save to """ save_img(get_game_sc...
def get_game_screen(): """ Get game screen image
random_line_split
Capture.py
"""This modules is used to capture the screen """ import pyautogui import time import Globals PATH = './Captures/' def capture_area(area): """ Captures area of the screen Args: area (Tuple (x,y,width,height)): Area to capture Returns: Image : Image of the area captured """ ...
def save_img(img, filename): """ Saves image to file Args: img (Image): Image to save filename (String): Image save name """ img.save(PATH + filename + '.png')
""" Saves game area screen shot to file Args: filename (String): Name of file to save to """ save_img(get_game_screen(), filename)
identifier_body
Capture.py
"""This modules is used to capture the screen """ import pyautogui import time import Globals PATH = './Captures/' def capture_area(area): """ Captures area of the screen Args: area (Tuple (x,y,width,height)): Area to capture Returns: Image : Image of the area captured """ ...
(img, filename): """ Saves image to file Args: img (Image): Image to save filename (String): Image save name """ img.save(PATH + filename + '.png')
save_img
identifier_name
report.component.ts
import { Component } from '@angular/core'; import { ChartComponent } from '../chart'; import { ChartConfig } from '../chart/chart.config'; import { ChartDataService } from '../shared/chart-data.service'; @Component({ moduleId: module.id, selector: 'app-report', templateUrl: 'report.component.html', styleUrls:...
// getStats() { // // For now we hardcode the customer Id until we build a user interface. // this.chartDataService.byCustomer(1, 'monthly').subscribe(stats => { // // Get JSON Object from Response // stats = stats.json(); // // We create a new AreaChartConfig object to set income b...
{ // this.getStats(); }
identifier_body
report.component.ts
import { Component } from '@angular/core'; import { ChartComponent } from '../chart'; import { ChartConfig } from '../chart/chart.config'; import { ChartDataService } from '../shared/chart-data.service'; @Component({ moduleId: module.id, selector: 'app-report', templateUrl: 'report.component.html', styleUrls:...
// }; // customerOrderArea.dataset = stats.customerOrderStats.map(data => { // return { x: new Date(data.date), y: data.count }; // }); // // to finish we append our AreaChartConfigs into an array of configs // this.areaChartConfig = new Array<ChartConfig>(); // this....
// // We create a new AreaChartConfig object to set orders by customer config // let customerOrderArea = new ChartConfig(); // customerOrderArea.settings = { // fill: 'rgba(195, 0, 47, 1)', // interpolation: 'monotone'
random_line_split
report.component.ts
import { Component } from '@angular/core'; import { ChartComponent } from '../chart'; import { ChartConfig } from '../chart/chart.config'; import { ChartDataService } from '../shared/chart-data.service'; @Component({ moduleId: module.id, selector: 'app-report', templateUrl: 'report.component.html', styleUrls:...
{ private areaChartConfig: Array<ChartConfig>; constructor(private chartDataService: ChartDataService) { // this.getStats(); } // getStats() { // // For now we hardcode the customer Id until we build a user interface. // this.chartDataService.byCustomer(1, 'monthly').subscribe(stats => { // ...
ReportComponent
identifier_name
lib.rs
//! A small library meant to be used as a build dependency with Cargo for easily //! integrating [ISPC](https://ispc.github.io/) code into Rust projects. The //! `ispc_compile` crate provides functionality to use the ISPC compiler //! from your build script to build your ISPC code into a library, //! and generate Rust ...
() -> Config { // Query the ISPC compiler version. This also acts as a check that we can // find the ISPC compiler when we need it later. let cmd_output = Command::new("ispc") .arg("--version") .output() .expect("Failed to find ISPC compiler in PATH"); ...
new
identifier_name
lib.rs
//! A small library meant to be used as a build dependency with Cargo for easily //! integrating [ISPC](https://ispc.github.io/) code into Rust projects. The //! `ispc_compile` crate provides functionality to use the ISPC compiler //! from your build script to build your ISPC code into a library, //! and generate Rust ...
if let Some(ref t) = self.target_isa { let mut isa_str = String::from("--target="); isa_str.push_str(&t[0].to_string()); for isa in t.iter().skip(1) { isa_str.push_str(&format!(",{}", isa.to_string())); } ispc_args.push(isa_str); ...
{ ispc_args.push(String::from("--instrument")); }
conditional_block
lib.rs
//! A small library meant to be used as a build dependency with Cargo for easily //! integrating [ISPC](https://ispc.github.io/) code into Rust projects. The //! `ispc_compile` crate provides functionality to use the ISPC compiler //! from your build script to build your ISPC code into a library, //! and generate Rust ...
pub mod opt; use std::collections::BTreeSet; use std::env; use std::fmt::Display; use std::fs::File; use std::io::{BufRead, BufReader, Write}; use std::path::{Path, PathBuf}; use std::process::{Command, ExitStatus}; use regex::Regex; use semver::{BuildMetadata, Prerelease, Version}; pub use opt::{Addressing, Archite...
extern crate gcc; extern crate libc; extern crate regex; extern crate semver;
random_line_split
lib.rs
//! A small library meant to be used as a build dependency with Cargo for easily //! integrating [ISPC](https://ispc.github.io/) code into Rust projects. The //! `ispc_compile` crate provides functionality to use the ISPC compiler //! from your build script to build your ISPC code into a library, //! and generate Rust ...
/// Returns the user-set optimization level if they've set one, otherwise /// returns env("OPT_LEVEL") fn get_opt_level(&self) -> u32 { self.opt_level.unwrap_or_else(|| { let opt = env::var("OPT_LEVEL").unwrap(); opt.parse::<u32>().unwrap() }) } /// Returns t...
{ self.debug .unwrap_or_else(|| env::var("DEBUG").map(|x| x == "true").unwrap()) }
identifier_body
dialogs_gl_ES.ts
<?xml version="1.0" ?><!DOCTYPE TS><TS version="2.1" language="gl_ES"> <context> <name>ReminderDialog</name> <message> <location filename="../src/reboot-reminder-dialog/reminderdialog.cpp" line="35"/> <source>Restart the computer to use the system and the applications properly</source> <...
</TS>
</context>
random_line_split
dynamoDB.js
var moment = require('moment'); var _ = require('lodash'); var uuid = require('uuid'); /** * Initiate AWS DynamoDB bucket event. * @param {Object} options - Passed config options. * @param {Object} options.schema - DynamoDB table schema. * @param {string} options.region - Region of AWS S3 bucket. * @param {string...
keyType.N = options.item[options.schema.primaryKey]; break; case 'binary': keyType.B = options.item[options.schema.primaryKey]; break; default: keyType.S = options.item[options.schema.primaryKey]; } keyObj[options.schema.primaryKey] = keyType; return key...
keyType.S = options.item[options.schema.primaryKey]; break; case 'number':
random_line_split
dynamoDB.js
var moment = require('moment'); var _ = require('lodash'); var uuid = require('uuid'); /** * Initiate AWS DynamoDB bucket event. * @param {Object} options - Passed config options. * @param {Object} options.schema - DynamoDB table schema. * @param {string} options.region - Region of AWS S3 bucket. * @param {string...
() { var imageObj = {}; for (var key in options.item) { var type = {}; // TODO: Implement unified parser for schema types. switch (options.schema[key].toLowerCase()) { case 'string': type.S = options.item[key]; break; case 'number': type.N = opti...
getImage
identifier_name
dynamoDB.js
var moment = require('moment'); var _ = require('lodash'); var uuid = require('uuid'); /** * Initiate AWS DynamoDB bucket event. * @param {Object} options - Passed config options. * @param {Object} options.schema - DynamoDB table schema. * @param {string} options.region - Region of AWS S3 bucket. * @param {string...
function getImage() { var imageObj = {}; for (var key in options.item) { var type = {}; // TODO: Implement unified parser for schema types. switch (options.schema[key].toLowerCase()) { case 'string': type.S = options.item[key]; break; case 'number': ...
{ var keyObj = {}; var keyType = {}; // TODO: Implement unified parser for schema types. switch (options.schema[options.schema.primaryKey].toLowerCase()) { case 'string': keyType.S = options.item[options.schema.primaryKey]; break; case 'number': keyType.N = options.i...
identifier_body
core.ts
import { Point } from './geometry'; export interface Config { options?: Options; workerURL?: string; } export interface DrawingSurface { width: number | SVGAnimatedLength; height: number | SVGAnimatedLength; } export interface Options { maxRandomnessOffset?: number; roughness?: number; bowing?: number;...
shape: string; options: ResolvedOptions; sets: OpSet[]; } export interface PathInfo { d: string; stroke: string; strokeWidth: number; fill?: string; pattern?: PatternInfo; } export interface PatternInfo { x: number; y: number; width: number; height: number; viewBox: string; patternUnits: s...
path?: string; } export interface Drawable {
random_line_split
oop.js
/* YUI 3.4.1 (build 4118) Copyright 2011 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ YUI.add('oop', function(Y) { /** Adds object inheritance and manipulation utilities to the YUI instance. This module is required by most YUI components. @module oop **/ var L ...
(o, f, c, proto, action) { if (o && o[action] && o !== Y) { return o[action].call(o, f, c); } else { switch (A.test(o)) { case 1: return A[action](o, f, c); case 2: return A[action](Y.Array(o, 0, true), f, c); default: ...
dispatch
identifier_name
oop.js
/* YUI 3.4.1 (build 4118) Copyright 2011 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ YUI.add('oop', function(Y) { /** Adds object inheritance and manipulation utilities to the YUI instance. This module is required by most YUI components. @module oop **/ var L ...
}; unsequester = function (instance, fn, fnArgs) { // Unsequester all sequestered functions. for (var key in sequestered) { if (hasOwn.call(sequestered, key) && instance[key] === replacements[key]) { instance[key] = s...
{ if (toString.call(value) === '[object Function]') { sequestered[key] = value; newPrototype[key] = replacements[key] = function () { return unsequester(this, value, arguments); }; } else { ...
conditional_block
oop.js
/* YUI 3.4.1 (build 4118) Copyright 2011 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ YUI.add('oop', function(Y) { /** Adds object inheritance and manipulation utilities to the YUI instance. This module is required by most YUI components. @module oop **/ var L ...
}; }, '3.4.1' ,{requires:['yui-base']});
return fn.apply(c || fn, args); };
random_line_split
oop.js
/* YUI 3.4.1 (build 4118) Copyright 2011 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ YUI.add('oop', function(Y) { /** Adds object inheritance and manipulation utilities to the YUI instance. This module is required by most YUI components. @module oop **/ var L ...
/** Augments the _receiver_ with prototype properties from the _supplier_. The receiver may be a constructor function or an object. The supplier must be a constructor function. If the _receiver_ is an object, then the _supplier_ constructor will be called immediately after _receiver_ is augmented, with _receiver_ as...
{ if (o && o[action] && o !== Y) { return o[action].call(o, f, c); } else { switch (A.test(o)) { case 1: return A[action](o, f, c); case 2: return A[action](Y.Array(o, 0, true), f, c); default: return Y.Object[ac...
identifier_body
script.js
const defaults = { base_css: true, // the base dark theme css inline_youtube: true, // makes youtube videos play inline the chat collapse_onebox: true, // can collapse collapse_onebox_default: false, // default option for collapse pause_youtube_on_collapse: true, // default option for pausing yo...
function injectJS(file, cb) { const elm = document.createElement('script'); elm.type = 'text/javascript'; elm.src = chrome.extension.getURL(file); elm.onload = cb; document.body.appendChild(elm); }
{ const elm = document.createElement('link'); elm.rel = 'stylesheet'; elm.type = 'text/css'; elm.href = chrome.extension.getURL(file); elm.onload = cb; document.head.appendChild(elm); }
identifier_body
script.js
const defaults = { base_css: true, // the base dark theme css inline_youtube: true, // makes youtube videos play inline the chat collapse_onebox: true, // can collapse collapse_onebox_default: false, // default option for collapse pause_youtube_on_collapse: true, // default option for pausing yo...
'CodeMirror/mode/coffeescript/coffeescript.js', 'CodeMirror/mode/commonlisp/commonlisp.js', 'CodeMirror/mode/css/css.js', 'CodeMirror/mode/dart/dart.js', 'CodeMirror/mode/go/go.js', 'CodeMirror/mode/groovy/groovy.js', 'CodeMirror/mode/haml/haml.js', 'CodeMirror/mode/haske...
'CodeMirror/mode/cmake/cmake.js', 'CodeMirror/mode/cobol/cobol.js',
random_line_split
script.js
const defaults = { base_css: true, // the base dark theme css inline_youtube: true, // makes youtube videos play inline the chat collapse_onebox: true, // can collapse collapse_onebox_default: false, // default option for collapse pause_youtube_on_collapse: true, // default option for pausing yo...
(file, cb) { const elm = document.createElement('link'); elm.rel = 'stylesheet'; elm.type = 'text/css'; elm.href = chrome.extension.getURL(file); elm.onload = cb; document.head.appendChild(elm); } function injectJS(file, cb) { const elm = document.createElement('script'); elm.type = 'text/javascript'; elm.src...
injectCSS
identifier_name
account-template-test.js
'use strict' const path = require('path') const fs = require('fs-extra') const chai = require('chai') const expect = chai.expect const sinonChai = require('sinon-chai') chai.use(sinonChai) chai.should() const AccountTemplate = require('../../lib/models/account-template') const templatePath = path.join(__dirname, '.....
expect(rootAcl).to.exist }) }) }) describe('processAccount()', () => { it('should process all the files in an account', () => { let substitutions = { webId: 'https://alice.example.com/#me', email: 'alice@example.com', name: 'Alice Q.' } let templa...
return AccountTemplate.copyTemplateDir(templatePath, accountPath) .then(() => { let rootAcl = fs.readFileSync(path.join(accountPath, '.acl'), 'utf8')
random_line_split
validapass.py
#! /usr/bin/python3 import re err = "La contraseña no es segura" msg = "Escriba una contraseña al menos 8 caracteres alfanumericos" def ismayor8(a): """ Compara si es mayor a 8 caracteres """ if (len(a) < 8): return False return True def minus(a): """ compara si existe alguna le...
: """ Compara si la cadena es alfanumerica """ if (a.isalnum()): return True else: return False def vpass(): """ Validamos contraseña """ salida = False while salida is False: try: print (msg, end='\n') paswd = str(input('passwd: ...
anumeric(a)
identifier_name
validapass.py
#! /usr/bin/python3 import re err = "La contraseña no es segura" msg = "Escriba una contraseña al menos 8 caracteres alfanumericos" def ismayor8(a): """ Compara si es mayor a 8 caracteres """ if (len(a) < 8): return False return True def minus(a): """ compara si existe alguna le...
return flag def alfanumeric(a): """ Compara si la cadena es alfanumerica """ if (a.isalnum()): return True else: return False def vpass(): """ Validamos contraseña """ salida = False while salida is False: try: print (msg, end='\n') ...
(re.match(patron, letra)): flag = True
conditional_block
validapass.py
#! /usr/bin/python3 import re err = "La contraseña no es segura" msg = "Escriba una contraseña al menos 8 caracteres alfanumericos" def ismayor8(a): """ Compara si es mayor a 8 caracteres """ if (len(a) < 8): return False return True def minus(a): """ compara si existe alguna le...
for letra in a: if (re.match(patron, letra)): flag = True return flag def mayus(a): """ Compara si existe alguna letra mayuscula """ patron = ('[A-Z]') flag = False for letra in a: if (re.match(patron, letra)): flag = True return flag def u...
flag = False
random_line_split
validapass.py
#! /usr/bin/python3 import re err = "La contraseña no es segura" msg = "Escriba una contraseña al menos 8 caracteres alfanumericos" def ismayor8(a): """ Compara si es mayor a 8 caracteres """ if (len(a) < 8): return False return True def minus(a): """ compara si existe alguna le...
Validamos contraseña """ salida = False while salida is False: try: print (msg, end='\n') paswd = str(input('passwd: ')) if (ismayor8(paswd)): if (alfanumeric(paswd)): if (minus(paswd) and mayus(paswd) and unnum(paswd)): ...
identifier_body
setup.py
#!/usr/bin/env python # coding: utf-8 import os import sys from setuptools.command.test import test as TestCommand from jsonmodels import __version__, __author__, __email__ from setuptools import setup PROJECT_NAME = 'jsonmodels' if sys.argv[-1] == 'publish': os.system('python setup.py sdist upload') sys.e...
def run_tests(self): import pytest errno = pytest.main(self.pytest_args) sys.exit(errno) # Hacking tests. try: import tests except ImportError: pass else: if 'test' in sys.argv and '--no-lint' in sys.argv: tests.LINT = False del sys.argv[sys.argv.index('--no-li...
TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True
random_line_split
setup.py
#!/usr/bin/env python # coding: utf-8 import os import sys from setuptools.command.test import test as TestCommand from jsonmodels import __version__, __author__, __email__ from setuptools import setup PROJECT_NAME = 'jsonmodels' if sys.argv[-1] == 'publish': os.system('python setup.py sdist upload') sys.e...
(self): TestCommand.initialize_options(self) self.pytest_args = ['--cov', PROJECT_NAME] def finalize_options(self): TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True def run_tests(self): import pytest errno = pytest.main(self....
initialize_options
identifier_name
setup.py
#!/usr/bin/env python # coding: utf-8 import os import sys from setuptools.command.test import test as TestCommand from jsonmodels import __version__, __author__, __email__ from setuptools import setup PROJECT_NAME = 'jsonmodels' if sys.argv[-1] == 'publish': os.system('python setup.py sdist upload') sys.e...
readme = open('README.rst').read() history = open('HISTORY.rst').read().replace('.. :changelog:', '') setup( name=PROJECT_NAME, version=__version__, description='Models to make easier to deal with structures that' ' are converted to, or read from JSON.', long_description=readme + '\n\n' + history...
if 'test' in sys.argv and '--no-lint' in sys.argv: tests.LINT = False del sys.argv[sys.argv.index('--no-lint')] if 'test' in sys.argv and '--spelling' in sys.argv: tests.CHECK_SPELLING = True del sys.argv[sys.argv.index('--spelling')]
conditional_block
setup.py
#!/usr/bin/env python # coding: utf-8 import os import sys from setuptools.command.test import test as TestCommand from jsonmodels import __version__, __author__, __email__ from setuptools import setup PROJECT_NAME = 'jsonmodels' if sys.argv[-1] == 'publish': os.system('python setup.py sdist upload') sys.e...
# Hacking tests. try: import tests except ImportError: pass else: if 'test' in sys.argv and '--no-lint' in sys.argv: tests.LINT = False del sys.argv[sys.argv.index('--no-lint')] if 'test' in sys.argv and '--spelling' in sys.argv: tests.CHECK_SPELLING = True del sys.ar...
user_options = [('pytest-args=', 'a', "Arguments to pass to py.test")] def initialize_options(self): TestCommand.initialize_options(self) self.pytest_args = ['--cov', PROJECT_NAME] def finalize_options(self): TestCommand.finalize_options(self) self.test_args = [] self.t...
identifier_body
pluginmanager.py
#!/usr/bin/env jython from __future__ import with_statement from contextlib import contextmanager import logging from plugins import __all__ log = logging.getLogger('kahuna') class PluginManager: """ Manages available plugins """ def __init__(self): """ Initialize the plugin list """ self.__...
(self, plugin): """ Prints the help for the given plugin """ commands = plugin._commands() plugin_name = plugin.__module__.split('.')[-1] print "%s" % plugin.__doc__ for command in sorted(commands.iterkeys()): print " %s %s\t%s" % (plugin_name, command, ...
help
identifier_name
pluginmanager.py
#!/usr/bin/env jython from __future__ import with_statement from contextlib import contextmanager import logging from plugins import __all__ log = logging.getLogger('kahuna') class PluginManager: """ Manages available plugins """ def __init__(self): """ Initialize the plugin list """ self.__...
print " %s %s\t%s" % (plugin_name, command, commands[command].__doc__) def help_all(self): """ Prints the help for all registered plugins """ for name in sorted(__all__): plugin = self.load_plugin(name) self.help(plugin) print ...
""" Prints the help for the given plugin """ commands = plugin._commands() plugin_name = plugin.__module__.split('.')[-1] print "%s" % plugin.__doc__ for command in sorted(commands.iterkeys()):
random_line_split
pluginmanager.py
#!/usr/bin/env jython from __future__ import with_statement from contextlib import contextmanager import logging from plugins import __all__ log = logging.getLogger('kahuna') class PluginManager: """ Manages available plugins """ def __init__(self):
def load_plugin(self, plugin_name): """ Loads a single plugin given its name """ if not plugin_name in __all__: raise KeyError("Plugin " + plugin_name + " not found") try: plugin = self.__plugins[plugin_name] except KeyError: # Load the plugin on...
""" Initialize the plugin list """ self.__plugins = {}
identifier_body
pluginmanager.py
#!/usr/bin/env jython from __future__ import with_statement from contextlib import contextmanager import logging from plugins import __all__ log = logging.getLogger('kahuna') class PluginManager: """ Manages available plugins """ def __init__(self): """ Initialize the plugin list """ self.__...
@contextmanager def opencontext(plugin): """ Loads the context each plugin needs to be initialized in order to be executed """ plugin._load_context() yield plugin._close_context()
plugin = self.load_plugin(name) self.help(plugin) print
conditional_block
dialogflow_generated_dialogflow_v2_session_entity_types_create_session_entity_type_async.py
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
(): # Create a client client = dialogflow_v2.SessionEntityTypesAsyncClient() # Initialize request argument(s) session_entity_type = dialogflow_v2.SessionEntityType() session_entity_type.name = "name_value" session_entity_type.entity_override_mode = "ENTITY_OVERRIDE_MODE_SUPPLEMENT" session_...
sample_create_session_entity_type
identifier_name
dialogflow_generated_dialogflow_v2_session_entity_types_create_session_entity_type_async.py
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
# [END dialogflow_generated_dialogflow_v2_SessionEntityTypes_CreateSessionEntityType_async]
client = dialogflow_v2.SessionEntityTypesAsyncClient() # Initialize request argument(s) session_entity_type = dialogflow_v2.SessionEntityType() session_entity_type.name = "name_value" session_entity_type.entity_override_mode = "ENTITY_OVERRIDE_MODE_SUPPLEMENT" session_entity_type.entities.value = "...
identifier_body
dialogflow_generated_dialogflow_v2_session_entity_types_create_session_entity_type_async.py
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
# Initialize request argument(s) session_entity_type = dialogflow_v2.SessionEntityType() session_entity_type.name = "name_value" session_entity_type.entity_override_mode = "ENTITY_OVERRIDE_MODE_SUPPLEMENT" session_entity_type.entities.value = "value_value" session_entity_type.entities.synonyms =...
async def sample_create_session_entity_type(): # Create a client client = dialogflow_v2.SessionEntityTypesAsyncClient()
random_line_split
accounts.component.ts
import { Component } from '@angular/core'; import { OnInit } from '@angular/core'; import { Account } from '../../models/account.model'; import { Totals } from '../../models/totals.model'; import { Prices } from '../../models/prices.model'; import { AccountsService } from '../../services/accounts.service'; import { Con...
(account: Account) { return account.current / account.invested - 1; } }
getNetPercent
identifier_name
accounts.component.ts
import { Component } from '@angular/core'; import { OnInit } from '@angular/core'; import { Account } from '../../models/account.model'; import { Totals } from '../../models/totals.model'; import { Prices } from '../../models/prices.model'; import { AccountsService } from '../../services/accounts.service'; import { Con...
} getAccounts() { if(this.accounts) { this.historyService.set(this.accounts); } this.loading = true; this.accountsService.getAll() .subscribe( accounts => { let selected; this.accounts = accounts; this.loading = false; this.lastAccountRefresh = new Date(); this.totalsServi...
{ clearInterval(this.loopTimerId); }
conditional_block
accounts.component.ts
import { Component } from '@angular/core'; import { OnInit } from '@angular/core'; import { Account } from '../../models/account.model'; import { Totals } from '../../models/totals.model'; import { Prices } from '../../models/prices.model'; import { AccountsService } from '../../services/accounts.service'; import { Con...
HistoryService, TotalsService, PricesService ] }) export class AccountsComponent implements OnInit { selectedAccount: Account; accounts: Account[]; errorMessage: string; loopTimerId: number; totals: Totals; loading: boolean; lastAccountRefresh: Date; prices: Prices; constructor( private configServic...
@Component({ selector: 'accounts', template: require('./accounts.component.html'), providers: [ ConfigService,
random_line_split
accounts.component.ts
import { Component } from '@angular/core'; import { OnInit } from '@angular/core'; import { Account } from '../../models/account.model'; import { Totals } from '../../models/totals.model'; import { Prices } from '../../models/prices.model'; import { AccountsService } from '../../services/accounts.service'; import { Con...
getNetValue(account: Account) { return account.current - account.invested; } getNetPercent(account: Account) { return account.current / account.invested - 1; } }
{ if(account) { this.selectedAccount = this.selectedAccount === account ? undefined : account; if(this.selectedAccount) { this.prices = undefined; this.pricesService.getPrices(this.selectedAccount.id) .subscribe( prices => this.prices = prices, error => this.errorMessage = <any>error); ...
identifier_body
test_sahara_job_binary.py
# # 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 under t...
(common.HeatTestCase): def setUp(self): super(SaharaJobBinaryTest, self).setUp() t = template_format.parse(job_binary_template) self.stack = utils.parse_stack(t) resource_defns = self.stack.t.resource_definitions(self.stack) self.rsrc_defn = resource_defns['job-binary'] ...
SaharaJobBinaryTest
identifier_name
test_sahara_job_binary.py
# # 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 under t...
def test_create(self): jb = self._create_resource('job-binary', self.rsrc_defn, self.stack) args = self.client.job_binaries.create.call_args[1] expected_args = { 'name': 'my-jb', 'description': '', 'url': 'swift://container/jar-example.jar', ...
jb = job_binary.JobBinary(name, snippet, stack) value = mock.MagicMock(id='12345') self.client.job_binaries.create.return_value = value scheduler.TaskRunner(jb.create)() return jb
identifier_body
test_sahara_job_binary.py
# # 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 under t...
'is not a valid job location.') self.assertEqual(error_msg, six.text_type(ex)) def test_validate_password_without_user(self): self.rsrc_defn['Properties']['credentials'].pop('user') jb = job_binary.JobBinary('job-binary', self.rsrc_defn, self.stack) ex = self.as...
ex = self.assertRaises(exception.StackValidationFailed, jb.validate) error_msg = ('resources.job-binary.properties: internal-db://38273f82 '
random_line_split
list.d.ts
/// <reference types="react" /> import React from 'react'; import { TransferItem } from './index'; export interface TransferListProps { prefixCls: string; titleText: string; dataSource: TransferItem[]; filter: string; filterOption?: (filterText: any, item: any) => boolean; style?: React.CSSPrope...
extends React.Component<TransferListProps, any> { static defaultProps: { dataSource: never[]; titleText: string; showSearch: boolean; render: () => void; lazy: {}; }; timer: number; triggerScrollTimer: number; constructor(props: any); componentDidMount():...
TransferList
identifier_name
list.d.ts
/// <reference types="react" /> import React from 'react'; import { TransferItem } from './index'; export interface TransferListProps { prefixCls: string; titleText: string; dataSource: TransferItem[]; filter: string; filterOption?: (filterText: any, item: any) => boolean; style?: React.CSSPrope...
} export default class TransferList extends React.Component<TransferListProps, any> { static defaultProps: { dataSource: never[]; titleText: string; showSearch: boolean; render: () => void; lazy: {}; }; timer: number; triggerScrollTimer: number; constructor(pr...
itemsUnit: string; body?: (props: any) => any; footer?: (props: any) => void; lazy?: boolean | {}; onScroll: Function;
random_line_split
new-cron.trigger.component.ts
import {Component, EventEmitter, Output} from '@angular/core'; import {CronTrigger} from "../shared/cron-trigger"; import { DatePickerOptions, DateModel } from 'ng2-datepicker'; import {Date} from "../shared/date"; import {Trigger} from "../shared/trigger"; @Component({ selector: 'new-cron-trigger', templateUrl: '...
() { let cronTrigger = new CronTrigger(); cronTrigger.misfireInstruction = this.misfireInstruction; cronTrigger.startAt = Date.fromMoment(this.date.momentObj); cronTrigger.expression = this.expression; this.onTriggerAdded.emit(cronTrigger); } }
add
identifier_name
new-cron.trigger.component.ts
import {Component, EventEmitter, Output} from '@angular/core'; import {CronTrigger} from "../shared/cron-trigger"; import { DatePickerOptions, DateModel } from 'ng2-datepicker'; import {Date} from "../shared/date"; import {Trigger} from "../shared/trigger"; @Component({ selector: 'new-cron-trigger', templateUrl: '...
}
{ let cronTrigger = new CronTrigger(); cronTrigger.misfireInstruction = this.misfireInstruction; cronTrigger.startAt = Date.fromMoment(this.date.momentObj); cronTrigger.expression = this.expression; this.onTriggerAdded.emit(cronTrigger); }
identifier_body
new-cron.trigger.component.ts
import {Component, EventEmitter, Output} from '@angular/core'; import {CronTrigger} from "../shared/cron-trigger"; import { DatePickerOptions, DateModel } from 'ng2-datepicker'; import {Date} from "../shared/date"; import {Trigger} from "../shared/trigger"; @Component({ selector: 'new-cron-trigger', templateUrl: '...
let moment = require('moment'); let now = moment(); // this.options.minDate =now.toDate(); this.options.initialDate = now.toDate(); this.expression = '* * * * *'; this.misfireInstruction = 'fire_once_now'; } add() { let cronTrigger = new CronTrigger(); ...
constructor() { this.options = new DatePickerOptions();
random_line_split
str_match.rs
/// Decompose the string pattern pub fn decompose(rule: &str) -> Vec<String> { let mut res = vec![String::new()]; let mut escape = false; for c in rule.chars() { let l = res.len(); if escape { res[l - 1].push(c); escape = false; } else if c == '\\' { ...
} res } /// Check if a pattern matches a given string pub fn str_match(rule: &str, other: &str) -> bool { let mut pos = 0; for i in decompose(rule) { match (&other[pos..]).find(&i) { Some(n) => pos = n, None => return false, } } true }
}
random_line_split
str_match.rs
/// Decompose the string pattern pub fn decompose(rule: &str) -> Vec<String>
/// Check if a pattern matches a given string pub fn str_match(rule: &str, other: &str) -> bool { let mut pos = 0; for i in decompose(rule) { match (&other[pos..]).find(&i) { Some(n) => pos = n, None => return false, } } true }
{ let mut res = vec![String::new()]; let mut escape = false; for c in rule.chars() { let l = res.len(); if escape { res[l - 1].push(c); escape = false; } else if c == '\\' { escape = true; } else if c == '*' { res.push(String::n...
identifier_body
str_match.rs
/// Decompose the string pattern pub fn decompose(rule: &str) -> Vec<String> { let mut res = vec![String::new()]; let mut escape = false; for c in rule.chars() { let l = res.len(); if escape { res[l - 1].push(c); escape = false; } else if c == '\\' { ...
(rule: &str, other: &str) -> bool { let mut pos = 0; for i in decompose(rule) { match (&other[pos..]).find(&i) { Some(n) => pos = n, None => return false, } } true }
str_match
identifier_name
read.rs
// Copyright 2013 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 ...
fn next_u64(&mut self) -> u64 { // see above for explanation. let mut buf = [0; 8]; fill(&mut self.reader, &mut buf).unwrap(); unsafe { *(buf.as_ptr() as *const u64) } } fn fill_bytes(&mut self, v: &mut [u8]) { if v.len() == 0 { return } fill(&mut self.reader...
{ // This is designed for speed: reading a LE integer on a LE // platform just involves blitting the bytes into the memory // of the u32, similarly for BE on BE; avoiding byteswapping. let mut buf = [0; 4]; fill(&mut self.reader, &mut buf).unwrap(); unsafe { *(buf.as_ptr(...
identifier_body
read.rs
// Copyright 2013 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 ...
() { let v = [1u8, 2, 3, 4, 5, 6, 7, 8]; let mut w = [0u8; 8]; let mut rng = ReadRng::new(&v[..]); rng.fill_bytes(&mut w); assert!(v == w); } #[test] #[should_panic] #[cfg_attr(target_env = "msvc", ignore)] fn test_reader_rng_insufficient_bytes() { ...
test_reader_rng_fill_bytes
identifier_name
read.rs
// Copyright 2013 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 ...
Ok(()) } #[cfg(test)] mod test { use super::ReadRng; use Rng; #[test] fn test_reader_rng_u64() { // transmute from the target to avoid endianness concerns. let v = vec![0u8, 0, 0, 0, 0, 0, 0, 1, 0 , 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0,...
0 => return Err(io::Error::new(io::ErrorKind::Other, "end of file reached")), n => buf = &mut mem::replace(&mut buf, &mut [])[n..], } }
random_line_split
gen_sps.py
#!/usr/bin/env python import click from copy import copy from netCDF4 import Dataset import numpy as np import numpy.ma as ma import os import rasterio import rasterio.warp as rwarp import time import osr from .. import geotools from .. import utils def earth_radius(): srs = osr.SpatialReference() srs.ImportFrom...
return out def get_transform(r1, r2): # Get the geo transform using r1 resolution but r2 bounds dst = rasterio.open(r1) src = rasterio.open(r2) #src_bounds = np.around(src.bounds, decimals=3) affine, width, height = rwarp.calculate_default_transform(src.crs, ...
dst_data = dst_ds.createVariable(name, dtype, ("time", "lat","lon"), zlib = True, least_significant_digit = 4, fill_value = fill) dst_data.units = units dst_data.grid_mapping = 'crs' out[name] = ds...
conditional_block
gen_sps.py
#!/usr/bin/env python import click from copy import copy from netCDF4 import Dataset import numpy as np import numpy.ma as ma import os import rasterio import rasterio.warp as rwarp import time import osr from .. import geotools from .. import utils def earth_radius(): srs = osr.SpatialReference() srs.ImportFrom...
if __name__ == '__main__': main()
years = range(2010, 2101) ssps = ['ssp%d' % i for i in range(1, 6)] variables = [(ssp, 'f4', 'ppl/km^2', -9999) for ssp in ssps] fname = '%s/luh2/un_codes-full.tif' % utils.outdir() affine, lats, lons, res, cfudge = get_transform(fname, utils.sps(ssps[0], 2010))...
identifier_body
gen_sps.py
#!/usr/bin/env python import click from copy import copy from netCDF4 import Dataset import numpy as np import numpy.ma as ma import os import rasterio import rasterio.warp as rwarp import time import osr from .. import geotools from .. import utils def earth_radius(): srs = osr.SpatialReference() srs.ImportFrom...
(dst_ds, transform, lats, lons, years, variables): # Set attributes dst_ds.setncattr('Conventions', u'CF-1.5') dst_ds.setncattr('GDAL', u'GDAL 1.11.3, released 2015/09/16') # Create dimensions dst_ds.createDimension('time', None) dst_ds.createDimension('lat', len(lats)) dst_ds.createDimension('lon', len(...
init_nc
identifier_name
gen_sps.py
#!/usr/bin/env python import click from copy import copy from netCDF4 import Dataset import numpy as np import numpy.ma as ma import os import rasterio import rasterio.warp as rwarp import time import osr from .. import geotools from .. import utils def earth_radius(): srs = osr.SpatialReference() srs.ImportFrom...
carea = static.read(1, window=static.window(*src.bounds)) rcs = (np.sin(np.radians(lats + dst.res[0] / 2.0)) - np.sin(np.radians(lats - dst.res[0] / 2.0))) * \ (dst.res[0] * np.pi/180) * earth_radius() ** 2 / 1e6 #carea *= rcs.reshape(carea.shape[0], 1) return affine, lats, lons, dst.res, crat...
static = rasterio.open(utils.luh2_static('carea'))
random_line_split
config.py
import copy import datetime import json import os from typing import Dict, List, Optional import jinja2 import jsonschema import yaml from ray_release.anyscale_util import find_cloud_by_name from ray_release.exception import ReleaseTestConfigError from ray_release.logger import logger from ray_release.util import dee...
if num_errors > 0: raise ReleaseTestConfigError( f"Release test configuration error: Found {num_errors} test " f"validation errors." ) def validate_test(test: Test, schema: Optional[Dict] = None) -> Optional[str]: schema = schema or load_schema_file() try: ...
error = validate_test(test, schema) if error: logger.error( f"Failed to validate test {test.get('name', '(unnamed)')}: {error}" ) num_errors += 1
conditional_block
config.py
import copy import datetime import json import os from typing import Dict, List, Optional import jinja2 import jsonschema import yaml from ray_release.anyscale_util import find_cloud_by_name from ray_release.exception import ReleaseTestConfigError from ray_release.logger import logger from ray_release.util import dee...
def read_and_validate_release_test_collection(config_file: str) -> List[Test]: """Read and validate test collection from config file""" with open(config_file, "rt") as fp: test_config = yaml.safe_load(fp) validate_release_test_collection(test_config) return test_config def load_schema_file...
test_env = get_test_environment() return test_env.get(key, default)
identifier_body
config.py
import copy import datetime import json import os from typing import Dict, List, Optional import jinja2 import jsonschema import yaml from ray_release.anyscale_util import find_cloud_by_name from ray_release.exception import ReleaseTestConfigError from ray_release.logger import logger from ray_release.util import dee...
if num_errors > 0: raise ReleaseTestConfigError( f"Release test configuration error: Found {num_errors} test " f"validation errors." ) def validate_test(test: Test, schema: Optional[Dict] = None) -> Optional[str]: schema = schema or load_schema_file() try: ...
num_errors += 1
random_line_split
config.py
import copy import datetime import json import os from typing import Dict, List, Optional import jinja2 import jsonschema import yaml from ray_release.anyscale_util import find_cloud_by_name from ray_release.exception import ReleaseTestConfigError from ray_release.logger import logger from ray_release.util import dee...
(dict): pass DEFAULT_WHEEL_WAIT_TIMEOUT = 7200 # Two hours DEFAULT_COMMAND_TIMEOUT = 1800 DEFAULT_BUILD_TIMEOUT = 1800 DEFAULT_CLUSTER_TIMEOUT = 1800 DEFAULT_CLOUD_ID = "cld_4F7k8814aZzGG8TNUGPKnc" DEFAULT_ENV = { "DATESTAMP": str(datetime.datetime.now().strftime("%Y%m%d")), "TIMESTAMP": str(int(dateti...
Test
identifier_name
LoadMoreListView.js
define([ './ListView', './BaseView', 'underscore' ], function(ListView, BaseView, _) {
events: { 'click .load-more': 'loadMore' }, className: 'list-group-load-more', ItemView: null, ListView: null, defaultListViewOptions: function () { return { tagName: 'ul', ItemView: this.ItemView, ...
return BaseView.extend({ tpl: '<a href="#" class="btn btn-link load-more"><h4>Show More</h4></a>',
random_line_split
laravel_form.js
/** * Created by dlouvard_imac on 26/12/2016. */ (function () { var laravel = { initialize: function () { this.methodLinks = $('a[data-method]'); this.registerEvents(); }, registerEvents: function () { this.methodLinks.on('click', this.handleMethod); ...
if (ButtonPressed === "No") { return false } }); } else { form = laravel.createForm(link); form.submit(); } e.preventDefault(); }, createForm: function (...
form = laravel.createForm(link); form.submit(); }
random_line_split
laravel_form.js
/** * Created by dlouvard_imac on 26/12/2016. */ (function () { var laravel = { initialize: function () { this.methodLinks = $('a[data-method]'); this.registerEvents(); }, registerEvents: function () { this.methodLinks.on('click', this.handleMethod); ...
else { form = laravel.createForm(link); form.submit(); } e.preventDefault(); }, createForm: function (link) { var form = $('<form>', { 'method': 'POST', 'action': link.attr('hre...
{ $.SmartMessageBox({ //: "Confirmation ?", title: link.data('confirm'), buttons: '[No][Yes]' }, function (ButtonPressed) { if (ButtonPressed === "Yes") { form = laravel.createForm(li...
conditional_block
registry.py
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2013, 2014, 2015 CERN. # # Invenio 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 2 of the # License, or (at your optio...
(): """Create output formats.""" out = {} for f in output_formats_files: of = os.path.basename(f).lower() data = {'names': {}} if of.endswith('.yml'): of = of[:-4] with open(f, 'r') as f: data.update(yaml.load(f) or {}) data['c...
create_output_formats_lookup
identifier_name
registry.py
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2013, 2014, 2015 CERN. # # Invenio 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 2 of the # License, or (at your optio...
output_formats = LazyDict(create_output_formats_lookup) export_formats = LazyDict(lambda: dict( (code, of) for code, of in output_formats.items() if of.get('content_type', '') != 'text/html' and of.get('visibility', 0) ))
"""Create output formats.""" out = {} for f in output_formats_files: of = os.path.basename(f).lower() data = {'names': {}} if of.endswith('.yml'): of = of[:-4] with open(f, 'r') as f: data.update(yaml.load(f) or {}) data['code'] = ...
identifier_body
registry.py
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2013, 2014, 2015 CERN. # # Invenio 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 2 of the # License, or (at your optio...
normpath = os.path.normpath(path) if os.path.isdir(normpath): for p in os.listdir(normpath): _register(os.path.join(normpath, p), level=level+1) else: parts = normpath.split(os.path.sep) out[os.path.sep.join(parts[-level:])] = normpath fo...
return
conditional_block
registry.py
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2013, 2014, 2015 CERN. # # Invenio 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 2 of the # License, or (at your optio...
format_templates_directories = RegistryProxy( 'format_templates_directories', ModuleAutoDiscoveryRegistry, 'format_templates' ) format_templates = RegistryProxy( 'format_templates', PkgResourcesDirDiscoveryRegistry, '.', registry_namespace=format_templates_directories ) output_formats_director...
random_line_split
client.rs
/// By default and in most scenarios, `DEFAULT_BASE_URL` /// will be the base url for requests via this Client library. static DEFAULT_BASE_URL: &'static str = "https://api.github.com/"; /// By default and in most scenarios, `DEFAULT_BASE_URL` /// will be the base upload url for requests via this Client library. static...
/// `user_agent` represents the value given /// under the User-Agent key as part of /// the header of each request. pub user_agent: String, /// The base url for non-upload requests. pub base_url: String, /// The base url for upload requests. pub upload_url: String, } impl Client { /...
/// and for th sake of parallel processing, you should try to keep it immutable. pub struct Client {
random_line_split
client.rs
/// By default and in most scenarios, `DEFAULT_BASE_URL` /// will be the base url for requests via this Client library. static DEFAULT_BASE_URL: &'static str = "https://api.github.com/"; /// By default and in most scenarios, `DEFAULT_BASE_URL` /// will be the base upload url for requests via this Client library. static...
(user: &str) -> Client { Client::custom(user, DEFAULT_BASE_URL, DEFAULT_UPLOAD_BASE_URL) } }
new
identifier_name
client.rs
/// By default and in most scenarios, `DEFAULT_BASE_URL` /// will be the base url for requests via this Client library. static DEFAULT_BASE_URL: &'static str = "https://api.github.com/"; /// By default and in most scenarios, `DEFAULT_BASE_URL` /// will be the base upload url for requests via this Client library. static...
/// Construct a `Client` using the default URLs as defined by GitHub. pub fn new(user: &str) -> Client { Client::custom(user, DEFAULT_BASE_URL, DEFAULT_UPLOAD_BASE_URL) } }
{ Client { user_agent: user.to_string(), base_url: base_url.to_string(), upload_url: upload_url.to_string(), } }
identifier_body
collision.js
var canvas = document.querySelector("canvas"), context = canvas.getContext("2d"), width = canvas.width, height = canvas.height, radius = 20; var circles = d3.range(324).map(function(i) { return { x: (i % 25) * (radius + 1) * 2, y: Math.floor(i / 25) * (radius + 1) * 2 }; }); var simulation...
} function dragended() { if (!d3.event.active) simulation.alphaTarget(0); d3.event.subject.fx = null; d3.event.subject.fy = null; }
d3.event.subject.fx = d3.event.x; d3.event.subject.fy = d3.event.y;
random_line_split
collision.js
var canvas = document.querySelector("canvas"), context = canvas.getContext("2d"), width = canvas.width, height = canvas.height, radius = 20; var circles = d3.range(324).map(function(i) { return { x: (i % 25) * (radius + 1) * 2, y: Math.floor(i / 25) * (radius + 1) * 2 }; }); var simulation...
function dragsubject() { return simulation.find(d3.event.x, d3.event.y, radius); } function dragstarted() { if (!d3.event.active) simulation.alphaTarget(0.3).restart(); d3.event.subject.fx = d3.event.subject.x; d3.event.subject.fy = d3.event.subject.y; } function dragged() { d3.event.subject.fx = d3.event...
{ context.moveTo(d.x + radius, d.y); context.arc(d.x, d.y, radius, 0, 2 * Math.PI); }
identifier_body
collision.js
var canvas = document.querySelector("canvas"), context = canvas.getContext("2d"), width = canvas.width, height = canvas.height, radius = 20; var circles = d3.range(324).map(function(i) { return { x: (i % 25) * (radius + 1) * 2, y: Math.floor(i / 25) * (radius + 1) * 2 }; }); var simulation...
() { return simulation.find(d3.event.x, d3.event.y, radius); } function dragstarted() { if (!d3.event.active) simulation.alphaTarget(0.3).restart(); d3.event.subject.fx = d3.event.subject.x; d3.event.subject.fy = d3.event.subject.y; } function dragged() { d3.event.subject.fx = d3.event.x; d3.event.subject...
dragsubject
identifier_name
_createRecurry.js
import isLaziable from './_isLaziable.js'; import setData from './_setData.js'; import setWrapToString from './_setWrapToString.js'; /** Used to compose bitmasks for function metadata. */ var BIND_FLAG = 1, BIND_KEY_FLAG = 2, CURRY_BOUND_FLAG = 4, CURRY_FLAG = 8, PARTIAL_FLAG = 32, PARTIAL_RIGHT_FL...
export default createRecurry;
{ var isCurry = bitmask & CURRY_FLAG, newHolders = isCurry ? holders : undefined, newHoldersRight = isCurry ? undefined : holders, newPartials = isCurry ? partials : undefined, newPartialsRight = isCurry ? undefined : partials; bitmask |= (isCurry ? PARTIAL_FLAG : PARTIAL_RIGHT_FLAG); bit...
identifier_body
_createRecurry.js
import isLaziable from './_isLaziable.js'; import setData from './_setData.js'; import setWrapToString from './_setWrapToString.js'; /** Used to compose bitmasks for function metadata. */ var BIND_FLAG = 1, BIND_KEY_FLAG = 2, CURRY_BOUND_FLAG = 4, CURRY_FLAG = 8, PARTIAL_FLAG = 32, PARTIAL_RIGHT_FL...
(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) { var isCurry = bitmask & CURRY_FLAG, newHolders = isCurry ? holders : undefined, newHoldersRight = isCurry ? undefined : holders, newPartials = isCurry ? partials : undefined, newPartialsRight = isCurry ? u...
createRecurry
identifier_name
_createRecurry.js
import isLaziable from './_isLaziable.js'; import setData from './_setData.js'; import setWrapToString from './_setWrapToString.js'; /** Used to compose bitmasks for function metadata. */ var BIND_FLAG = 1, BIND_KEY_FLAG = 2, CURRY_BOUND_FLAG = 4, CURRY_FLAG = 8, PARTIAL_FLAG = 32, PARTIAL_RIGHT_FL...
var newData = [ func, bitmask, thisArg, newPartials, newHolders, newPartialsRight, newHoldersRight, argPos, ary, arity ]; var result = wrapFunc.apply(undefined, newData); if (isLaziable(func)) { setData(result, newData); } result.placeholder = placeholder; return setWrapToString(result, func...
{ bitmask &= ~(BIND_FLAG | BIND_KEY_FLAG); }
conditional_block
_createRecurry.js
import isLaziable from './_isLaziable.js'; import setData from './_setData.js'; import setWrapToString from './_setWrapToString.js';
CURRY_BOUND_FLAG = 4, CURRY_FLAG = 8, PARTIAL_FLAG = 32, PARTIAL_RIGHT_FLAG = 64; /** * Creates a function that wraps `func` to continue currying. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {...
/** Used to compose bitmasks for function metadata. */ var BIND_FLAG = 1, BIND_KEY_FLAG = 2,
random_line_split
snapshot.rs
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0. use crate::db_vector::PanicDBVector; use crate::engine::PanicEngine; use engine_traits::{ IterOptions, Iterable, Iterator, Peekable, ReadOptions, Result, SeekKey, Snapshot, }; use std::ops::Deref; #[derive(Clone, Debug)] pub struct PanicSnapshot; ...
fn valid(&self) -> Result<bool> { panic!() } }
{ panic!() }
identifier_body
snapshot.rs
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0. use crate::db_vector::PanicDBVector; use crate::engine::PanicEngine; use engine_traits::{ IterOptions, Iterable, Iterator, Peekable, ReadOptions, Result, SeekKey, Snapshot, }; use std::ops::Deref; #[derive(Clone, Debug)] pub struct PanicSnapshot; ...
(&self) -> &[u8] { panic!() } fn value(&self) -> &[u8] { panic!() } fn valid(&self) -> Result<bool> { panic!() } }
key
identifier_name
snapshot.rs
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0. use crate::db_vector::PanicDBVector; use crate::engine::PanicEngine; use engine_traits::{ IterOptions, Iterable, Iterator, Peekable, ReadOptions, Result, SeekKey, Snapshot, }; use std::ops::Deref; #[derive(Clone, Debug)] pub struct PanicSnapshot; ...
panic!() } }
random_line_split
testing-topo.py
#!/usr/bin/python "Assignment 5 - This defines a topology for running a firewall. It is not \ necessarily the topology that will be used for grading, so feel free to \ edit and create new topologies and share them." from mininet.topo import Topo from mininet.net import Mininet from mininet.node import CPULim...
(Topo): ''' Creates the following topoplogy: e1 e2 e3 | | | \ | / firwall (s1) / | \ | | | w1 w2 w3 ''' def __init__(self, cpu=.1, bw=10, delay=None, **params): super(FWTopo,self).__init__() # Host in link configurati...
FWTopo
identifier_name
testing-topo.py
#!/usr/bin/python "Assignment 5 - This defines a topology for running a firewall. It is not \ necessarily the topology that will be used for grading, so feel free to \ edit and create new topologies and share them." from mininet.topo import Topo from mininet.net import Mininet from mininet.node import CPULim...
def main(): print "Starting topology" topo = FWTopo() net = Mininet(topo=topo, link=TCLink, controller=RemoteController, autoSetMacs=True) net.start() try: from unit_tests import run_tests raw_input('Unit tests to be run next. Make sure your firewall is running, then press a key'...
''' Creates the following topoplogy: e1 e2 e3 | | | \ | / firwall (s1) / | \ | | | w1 w2 w3 ''' def __init__(self, cpu=.1, bw=10, delay=None, **params): super(FWTopo,self).__init__() # Host in link configuration h...
identifier_body
testing-topo.py
#!/usr/bin/python "Assignment 5 - This defines a topology for running a firewall. It is not \ necessarily the topology that will be used for grading, so feel free to \ edit and create new topologies and share them." from mininet.topo import Topo from mininet.net import Mininet from mininet.node import CPULim...
if __name__ == '__main__': main()
CLI(net)
random_line_split
testing-topo.py
#!/usr/bin/python "Assignment 5 - This defines a topology for running a firewall. It is not \ necessarily the topology that will be used for grading, so feel free to \ edit and create new topologies and share them." from mininet.topo import Topo from mininet.net import Mininet from mininet.node import CPULim...
main()
conditional_block
search.js
import React from 'react'; import PropTypes from 'prop-types'; import { defineMessages, injectIntl } from 'react-intl'; const messages = defineMessages({ placeholder: { id: 'search.placeholder', defaultMessage: 'Search' }, }); class Search extends React.PureComponent { static propTypes = { value: PropTypes.s...
handleFocus = () => { this.props.onShow(); } render () { const { intl, value, submitted } = this.props; const hasValue = value.length > 0 || submitted; return ( <div className='search'> <input className='search__input' type='text' placeholder={intl.for...
}
random_line_split
search.js
import React from 'react'; import PropTypes from 'prop-types'; import { defineMessages, injectIntl } from 'react-intl'; const messages = defineMessages({ placeholder: { id: 'search.placeholder', defaultMessage: 'Search' }, }); class Search extends React.PureComponent { static propTypes = { value: PropTypes.s...
() { } handleFocus = () => { this.props.onShow(); } render () { const { intl, value, submitted } = this.props; const hasValue = value.length > 0 || submitted; return ( <div className='search'> <input className='search__input' type='text' placehold...
noop
identifier_name
search.js
import React from 'react'; import PropTypes from 'prop-types'; import { defineMessages, injectIntl } from 'react-intl'; const messages = defineMessages({ placeholder: { id: 'search.placeholder', defaultMessage: 'Search' }, }); class Search extends React.PureComponent { static propTypes = { value: PropTypes.s...
} noop () { } handleFocus = () => { this.props.onShow(); } render () { const { intl, value, submitted } = this.props; const hasValue = value.length > 0 || submitted; return ( <div className='search'> <input className='search__input' type='text' ...
{ e.preventDefault(); this.props.onSubmit(); }
conditional_block
search.js
import React from 'react'; import PropTypes from 'prop-types'; import { defineMessages, injectIntl } from 'react-intl'; const messages = defineMessages({ placeholder: { id: 'search.placeholder', defaultMessage: 'Search' }, }); class Search extends React.PureComponent { static propTypes = { value: PropTypes.s...
} export default injectIntl(Search);
{ const { intl, value, submitted } = this.props; const hasValue = value.length > 0 || submitted; return ( <div className='search'> <input className='search__input' type='text' placeholder={intl.formatMessage(messages.placeholder)} value={value} ...
identifier_body
useContactsListener.ts
import { canonizeEmail } from '@proton/shared/lib/helpers/email'; import { useEffect } from 'react'; import { OpenPGPKey } from 'pmcrypto'; import { useEventManager, useUserKeys, useCache } from '@proton/components'; import { Cache } from '@proton/shared/lib/helpers/cache'; import { CONTACT_CARD_TYPE } from '@proton/sh...
}); }; export const useContactsListener = () => { const globalCache = useCache(); const messageCache = useMessageCache(); const { subscribe } = useEventManager(); const [userKeys = []] = useUserKeys(); const { publicKeys } = splitKeys(userKeys); useEffect( () => subsc...
{ updateMessageCache(messageCache, localID, { verification: undefined }); }
conditional_block
useContactsListener.ts
import { canonizeEmail } from '@proton/shared/lib/helpers/email'; import { useEffect } from 'react'; import { OpenPGPKey } from 'pmcrypto'; import { useEventManager, useUserKeys, useCache } from '@proton/components'; import { Cache } from '@proton/shared/lib/helpers/cache'; import { CONTACT_CARD_TYPE } from '@proton/sh...
* @param globalCache Proton main cache * @param messageCache Message cache */ const processContactUpdate = async ( contact: Contact | undefined, publicKeys: OpenPGPKey[], globalCache: Cache<string, any>, messageCache: MessageCache ) => { const signedCard = contact?.Cards.find(({ Type }) => Type =...
* Deal with contact update from the event manager * Will read the updated contact to invalidate some cached related data * * @param contact Contact data update from the event manager * @param publicKeys Public keys of the current user
random_line_split