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
test_util.rs
extern crate mazth; #[allow(unused_imports)] use std::ops::Div; #[allow(unused_imports)] use std::cmp::Ordering; use self::mazth::i_comparable::IComparableError; use self::mazth::mat::{Mat3x1, Mat4}; use implement::math::util; #[test] fn
(){ //look_at { let eye : Mat3x1<f32> = Mat3x1 { _val: [5.0,5.0,5.0] }; let center : Mat3x1<f32> = Mat3x1 { _val: [0.0,0.0,0.0] }; let up : Mat3x1<f32> = Mat3x1 { _val: [0.0,1.0,0.0] }; let lookat = util::look_at( eye, center, up ); assert!( lookat.is_equal( &Mat4{ _val...
test_math_util
identifier_name
test_util.rs
extern crate mazth; #[allow(unused_imports)] use std::ops::Div; #[allow(unused_imports)] use std::cmp::Ordering; use self::mazth::i_comparable::IComparableError; use self::mazth::mat::{Mat3x1, Mat4}; use implement::math::util; #[test] fn test_math_util()
let far = 100.0; let persp = util::perspective( fov, aspect, near, far ); println!( "{:?}", persp ); assert!( persp.is_equal( &Mat4{ _val: [ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, -...
{ //look_at { let eye : Mat3x1<f32> = Mat3x1 { _val: [5.0,5.0,5.0] }; let center : Mat3x1<f32> = Mat3x1 { _val: [0.0,0.0,0.0] }; let up : Mat3x1<f32> = Mat3x1 { _val: [0.0,1.0,0.0] }; let lookat = util::look_at( eye, center, up ); assert!( lookat.is_equal( &Mat4{ _val: ...
identifier_body
test_util.rs
extern crate mazth; #[allow(unused_imports)] use std::ops::Div; #[allow(unused_imports)] use std::cmp::Ordering; use self::mazth::i_comparable::IComparableError; use self::mazth::mat::{Mat3x1, Mat4}; use implement::math::util; #[test] fn test_math_util(){ //look_at { let eye : Mat3x1<f32> = Mat3x1 {...
0.0, 0.0, 0.0, 1.0 ], _is_row_major: true }, 0.0001f32 ).expect("look_at result unexpected") ); } //perspective transform { let fov = 90.0; let aspect = 1.0; let near = 0.1; let far = 100.0; let persp = util::perspecti...
let lookat = util::look_at( eye, center, up ); assert!( lookat.is_equal( &Mat4{ _val: [ 0.70711, 0.0, -0.70711, 0.0, -0.40825, 0.81650, -0.40825, 0.0, 0.57735, 0.57735, 0.57735, -8.66025,
random_line_split
arduino.js
var five = require('johnny-five'); var plane = require('./plane'); var config = require('../config');
var board, paintMotor; module.exports = { init: function() { if (config.arduino) { board = new five.Board(); board.on('ready', this.onBoardReady); } }, onBoardReady: function() { console.log('OK') plane.init(); paintMotor = new five.Servo({ pin: 9, range: [80,170] ...
var state = 'waiting';
random_line_split
arduino.js
var five = require('johnny-five'); var plane = require('./plane'); var config = require('../config'); var state = 'waiting'; var board, paintMotor; module.exports = { init: function() { if (config.arduino)
}, onBoardReady: function() { console.log('OK') plane.init(); paintMotor = new five.Servo({ pin: 9, range: [80,170] }); this.repl.inject({ paint: paintMotor }); state = 'ready'; }, applyRotation: function(gamma, beta) { if (state === 'ready') { plane.ap...
{ board = new five.Board(); board.on('ready', this.onBoardReady); }
conditional_block
cache.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
(): CacheResult<T> { if (this.result) { return this.result; } const cts = new CancellationTokenSource(); const promise = this.task(cts.token); this.result = { promise, dispose: () => { this.result = null; cts.cancel(); cts.dispose(); } }; return this.result; } }
get
identifier_name
cache.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
}
{ if (this.result) { return this.result; } const cts = new CancellationTokenSource(); const promise = this.task(cts.token); this.result = { promise, dispose: () => { this.result = null; cts.cancel(); cts.dispose(); } }; return this.result; }
identifier_body
cache.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
}
return this.result; }
random_line_split
cache.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
const cts = new CancellationTokenSource(); const promise = this.task(cts.token); this.result = { promise, dispose: () => { this.result = null; cts.cancel(); cts.dispose(); } }; return this.result; } }
{ return this.result; }
conditional_block
manager.py
""" The events manager contains the class that manages custom and abstract callbacks into the system callbacks. Once a signals is registered here it could be used by string reference. This makes it easy to have dynamically signals being created by other apps in a single place so it could be used over all apps. For exa...
else: self.signals[signal_code] = instance def listen(self, signal, target, conditions=None, **kwargs): """ Register a listing client to the signal given (signal instance or string). :param signal: Signal instance or string: "namespace:code" :param target: Target method to call. :param conditions: Re...
self.callbacks[code] = instance
conditional_block
manager.py
""" The events manager contains the class that manages custom and abstract callbacks into the system callbacks. Once a signals is registered here it could be used by string reference. This makes it easy to have dynamically signals being created by other apps in a single place so it could be used over all apps. For exa...
try: signal = self.get_signal(sig_name) signal.set_self(func, slf) except Exception as e: logging.warning(str(e), exc_info=sys.exc_info()) self.reserved = dict() self.reserved_self = dict() def init_app(self, app): """ Initiate app, load all signal/callbacks files. (just import, they s...
for sig_name, recs in self.reserved_self.items(): for func, slf in recs:
random_line_split
manager.py
""" The events manager contains the class that manages custom and abstract callbacks into the system callbacks. Once a signals is registered here it could be used by string reference. This makes it easy to have dynamically signals being created by other apps in a single place so it could be used over all apps. For exa...
(cls): SignalManager.register_signal(cls) return cls
public_callback
identifier_name
manager.py
""" The events manager contains the class that manages custom and abstract callbacks into the system callbacks. Once a signals is registered here it could be used by string reference. This makes it easy to have dynamically signals being created by other apps in a single place so it could be used over all apps. For exa...
def create_app_manager(self, app): """ This method will create the manager instance for the app context. :param app: App instance. :type app: pyplanet.apps.config.AppConfig :return: SignalManager instance for the app. :rtype: pyplanet.core.events.manager.AppSignalManager """ return AppSignalManager(...
""" Finish startup the core, this will copy reservations. (PRIVATE). """ self.finish_reservations()
identifier_body
register.js
/** * Copyright (c) 2011 Bruno Jouhier <bruno.jouhier@sage.com> * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, ...
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *...
random_line_split
amp-embedly-card-impl.js
import {removeElement} from '#core/dom'; import {Layout_Enum, applyFillContent} from '#core/dom/layout'; import {Services} from '#service'; import {userAssert} from '#utils/log'; import {TAG as KEY_TAG} from './amp-embedly-key'; import {getIframe} from '../../../src/3p-frame'; import {listenFor} from '../../../src/...
} /** @override */ layoutCallback() { // Add optional paid api key attribute if provided // to remove embedly branding. if (this.apiKey_) { this.element.setAttribute(API_KEY_ATTR_NAME, this.apiKey_); } const iframe = getIframe(this.win, this.element, 'embedly'); iframe.title = thi...
{ this.apiKey_ = ampEmbedlyKeyElement.getAttribute('value'); }
conditional_block
amp-embedly-card-impl.js
import {removeElement} from '#core/dom'; import {Layout_Enum, applyFillContent} from '#core/dom/layout'; import {Services} from '#service'; import {userAssert} from '#utils/log'; import {TAG as KEY_TAG} from './amp-embedly-key'; import {getIframe} from '../../../src/3p-frame'; import {listenFor} from '../../../src/...
applyFillContent(iframe); this.getVsync().mutate(() => { this.element.appendChild(iframe); }); this.iframe_ = iframe; return this.loadPromise(iframe); } /** @override */ unlayoutCallback() { if (this.iframe_) { removeElement(this.iframe_); this.iframe_ = null; } ...
{ // Add optional paid api key attribute if provided // to remove embedly branding. if (this.apiKey_) { this.element.setAttribute(API_KEY_ATTR_NAME, this.apiKey_); } const iframe = getIframe(this.win, this.element, 'embedly'); iframe.title = this.element.title || 'Embedly card'; cons...
identifier_body
amp-embedly-card-impl.js
import {removeElement} from '#core/dom'; import {Layout_Enum, applyFillContent} from '#core/dom/layout'; import {Services} from '#service'; import {userAssert} from '#utils/log'; import {TAG as KEY_TAG} from './amp-embedly-key';
/** * Component tag identifier. * @const {string} */ export const TAG = 'amp-embedly-card'; /** * Attribute name used to set api key with name * expected by embedly. * @const {string} */ const API_KEY_ATTR_NAME = 'data-card-key'; /** * Implementation of the amp-embedly-card component. * See {@link ../amp-em...
import {getIframe} from '../../../src/3p-frame'; import {listenFor} from '../../../src/iframe-helper';
random_line_split
amp-embedly-card-impl.js
import {removeElement} from '#core/dom'; import {Layout_Enum, applyFillContent} from '#core/dom/layout'; import {Services} from '#service'; import {userAssert} from '#utils/log'; import {TAG as KEY_TAG} from './amp-embedly-key'; import {getIframe} from '../../../src/3p-frame'; import {listenFor} from '../../../src/...
() { userAssert( this.element.getAttribute('data-url'), 'The data-url attribute is required for <%s> %s', TAG, this.element ); const ampEmbedlyKeyElement = document.querySelector(KEY_TAG); if (ampEmbedlyKeyElement) { this.apiKey_ = ampEmbedlyKeyElement.getAttribute('value'...
buildCallback
identifier_name
test_unquote.py
# coding: utf-8 # (c) 2015, Toshio Kuratomi <tkuratomi@ansible.com> # # This file is part of Ansible # # Ansible 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 o...
(u'\'1 \\\'2\\\' 3\'', u'1 \\\'2\\\' 3'), (u'"', u'"'), (u'\'', u'\''), # Not entirely sure these are good but they match the current # behaviour (u'"1""2"', u'1""2'), (u'\'1\'\'2\'', u'1\'\'2'), (u'"1" 2 "3"', u'1" 2 "3'), ...
(u'\'1\\\'', u'\'1\\\''), (u'"1 \\"2\\" 3"', u'1 \\"2\\" 3'),
random_line_split
test_unquote.py
# coding: utf-8 # (c) 2015, Toshio Kuratomi <tkuratomi@ansible.com> # # This file is part of Ansible # # Ansible 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 o...
: UNQUOTE_DATA = ( (u'1', u'1'), (u'\'1\'', u'1'), (u'"1"', u'1'), (u'"1 \'2\'"', u'1 \'2\''), (u'\'1 "2"\'', u'1 "2"'), (u'\'1 \'2\'\'', u'1 \'2\''), (u'"1\\"', u'"1\\"'), (u'\'1\\\'', u'\'1\\\''), (u'"1 \\"...
TestUnquote
identifier_name
test_unquote.py
# coding: utf-8 # (c) 2015, Toshio Kuratomi <tkuratomi@ansible.com> # # This file is part of Ansible # # Ansible 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 o...
def test_unquote(self): for datapoint in self.UNQUOTE_DATA: yield self.check_unquote, datapoint[0], datapoint[1]
tools.eq_(unquote(quoted), expected)
identifier_body
test_unquote.py
# coding: utf-8 # (c) 2015, Toshio Kuratomi <tkuratomi@ansible.com> # # This file is part of Ansible # # Ansible 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 o...
yield self.check_unquote, datapoint[0], datapoint[1]
conditional_block
cloud_formation.py
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
( self, *, stack_name: str, params: Optional[dict] = None, aws_conn_id: str = 'aws_default', **kwargs ): super().__init__(**kwargs) self.params = params or {} self.stack_name = stack_name self.aws_conn_id = aws_conn_id def execute(self, context): self.log.info('P...
__init__
identifier_name
cloud_formation.py
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
cloudformation_hook = AWSCloudFormationHook(aws_conn_id=self.aws_conn_id) cloudformation_hook.delete_stack(self.stack_name, self.params)
random_line_split
cloud_formation.py
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
def execute(self, context): self.log.info('Parameters: %s', self.params) cloudformation_hook = AWSCloudFormationHook(aws_conn_id=self.aws_conn_id) cloudformation_hook.create_stack(self.stack_name, self.params) class CloudFormationDeleteStackOperator(BaseOperator): """ An operato...
super().__init__(**kwargs) self.stack_name = stack_name self.params = params self.aws_conn_id = aws_conn_id
identifier_body
filters.js
angular.module('Directory.csvImports.filters', ['Directory.csvImports.models']) .filter('type', ['Schema', function(Schema) { return function (inputs, cond) { if (typeof cond == 'undefined' || cond == null || cond == '' || cond == '*') { return inputs; } var things = []; angular.forEach(inputs, ...
}); return things; } }]) .filter('isExtraField', ['Schema', function(Schema) { return function isExtraField (headers, mapping) { if (mapping) { var things = []; angular.forEach(mapping, function (mapping, index) { var match = false; angular.forEach(Schema.columns, function ...
{ things.push(column); }
conditional_block
filters.js
angular.module('Directory.csvImports.filters', ['Directory.csvImports.models']) .filter('type', ['Schema', function(Schema) { return function (inputs, cond) { if (typeof cond == 'undefined' || cond == null || cond == '' || cond == '*') { return inputs; } var things = []; angular.forEach(inputs, ...
});
return getIntVal(a.state) - getIntVal(b.state); }) }
random_line_split
filters.js
angular.module('Directory.csvImports.filters', ['Directory.csvImports.models']) .filter('type', ['Schema', function(Schema) { return function (inputs, cond) { if (typeof cond == 'undefined' || cond == null || cond == '' || cond == '*') { return inputs; } var things = []; angular.forEach(inputs, ...
return function sortByImportState (imports) { if (imports) return imports.sort(function (a, b) { return getIntVal(a.state) - getIntVal(b.state); }) } });
{ switch(state) { case 'error': return 0; case 'new': return 1; case 'analyzed': return 2; case 'analyzing': return 3; case 'importing': return 4; case 'queued_analyze': return 5; case 'queud_import': return 6; case 'imported': return 7; case 'cancelled': return...
identifier_body
filters.js
angular.module('Directory.csvImports.filters', ['Directory.csvImports.models']) .filter('type', ['Schema', function(Schema) { return function (inputs, cond) { if (typeof cond == 'undefined' || cond == null || cond == '' || cond == '*') { return inputs; } var things = []; angular.forEach(inputs, ...
(state) { switch(state) { case 'error': return 0; case 'new': return 1; case 'analyzed': return 2; case 'analyzing': return 3; case 'importing': return 4; case 'queued_analyze': return 5; case 'queud_import': return 6; case 'imported': return 7; case 'cancelled'...
getIntVal
identifier_name
impala_test_suite.py
_section['RESULTS'] \ .replace('$NAMENODE', NAMENODE) \ .replace('$IMPALA_HOME', IMPALA_HOME) verify_raw_results(test_section, result, vector.get_value('table_format').file_format, pytest.config.option.update_results) # If --update_...
if pytest.config.option.table_formats: table_formats = list() for tf in pytest.config.option.table_formats.split(','): dataset = get_dataset_from_workload(cls.get_workload()) table_formats.append(TableFormatInfo.create_from_string(dataset, tf)) tf_dimensions = TestDimension('table_form...
identifier_body
impala_test_suite.py
gr_name target_impalad_clients = list() if multiple_impalad: target_impalad_clients =\ map(ImpalaTestSuite.create_impala_client, IMPALAD_HOST_PORT_LIST) else: target_impalad_clients = [self.client] # Change the database to reflect the file_format, compression codec etc, or the ...
def close_query_using_client(self, client, query):
random_line_split
impala_test_suite.py
suite""" cls.hive_client, cls.client = [None, None] # Create a Hive Metastore Client (used for executing some test SETUP steps metastore_host, metastore_port = pytest.config.option.metastore_server.split(':') trans_type = 'buffered' if pytest.config.option.use_kerberos: trans_type = 'kerberos...
(cls, host_port=IMPALAD): client = create_connection(host_port=host_port, use_kerberos=pytest.config.option.use_kerberos) client.connect() return client @classmethod def create_impala_service(cls, host_port=IMPALAD, webserver_port=25000): host, port = host_port.split(':') return Impalad...
create_impala_client
identifier_name
impala_test_suite.py
suite""" cls.hive_client, cls.client = [None, None] # Create a Hive Metastore Client (used for executing some test SETUP steps metastore_host, metastore_port = pytest.config.option.metastore_server.split(':') trans_type = 'buffered' if pytest.config.option.use_kerberos: trans_type = 'kerberos...
else: host, port = pytest.config.option.namenode_http_address.split(":") hdfs_client = get_hdfs_client(host, port) return hdfs_client @classmethod def all_db_names(self): results = self.client.execute("show databases").data # Extract first column - database name return [row.split(...
hdfs_client = get_hdfs_client_from_conf(HDFS_CONF)
conditional_block
server.rs
, Err(err) => { // TODO: Print to stderr println!("An error occurred: {:?}", err); Response::with((status::InternalServerError, err.to_string())) } }; resp.set_mut(Header(AccessControlAllowOrigin::Any)); Ok(resp) } ...
{ let mut resp = Response::with((status::Ok, serde_json::to_string(&json).unwrap())); resp.set_mut(Header(ContentType(Mime(TopLevel::Application, SubLevel::Json, vec![])))); resp }
conditional_block
server.rs
(Self::handle(data.deref())) } } } use self::handler::{PostHandler, GetHandler}; #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] enum
{ Crate, Phase, } impl serde::Deserialize for GroupBy { fn deserialize<D>(deserializer: &mut D) -> ::std::result::Result<GroupBy, D::Error> where D: serde::de::Deserializer { struct GroupByVisitor; impl serde::de::Visitor for GroupByVisitor { type Value = GroupBy; ...
GroupBy
identifier_name
server.rs
respond(Self::handle(data.deref())) } } } use self::handler::{PostHandler, GetHandler}; #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] enum GroupBy { Crate, Phase, } impl serde::Deserialize for GroupBy { fn deserialize<D>(deserializer: &mut D) -> ::std::result::Result<GroupBy, D::Error> ...
for krate in benchmark.by_crate.values() { if krate.contains_key("total") { sum += krate["total"]; count += 1; } } if rustc.by_crate["total"].contains_key("total") { sum += 2.0 * rustc.by_crate["...
let mut sum = 0.0; let mut count = 0;
random_line_split
server.rs
let Some(phase) = phase { self.time += phase.time; self.rss = max(self.rss, phase.rss.unwrap()); } } } let crates = crate_names.into_iter().filter_map(|crate_name| { day.by_crate.get(crate_name).map(|krate| { (crate_name, krate) }...
{ let mut router = Router::new(); router.get("/summary", Summary::handler); router.get("/info", Info::handler); router.post("/data", Data::handler); router.post("/get_tabular", Tabular::handler); router.post("/get", Days::handler); router.post("/stats", Stats::handler); let mut chain =...
identifier_body
tests.rs
// Copyright 2021 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; use std::time::Duration; use crate::{Process, ProcessResultMetadata}; use bazel_protos::gen::build::bazel::...
restored_action_metadata, ExecutedActionMetadata { worker_start_timestamp: Some(Timestamp { seconds: 0, nanos: 0, }), worker_completed_timestamp: Some(Timestamp { seconds: 20, nanos: 30, }), ..ExecutedActionMetadata::default() } ); // The re...
random_line_split
tests.rs
// Copyright 2021 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; use std::time::Duration; use crate::{Process, ProcessResultMetadata}; use bazel_protos::gen::build::bazel::...
// Process should derive a PartialEq and Hash that ignores the description assert_eq!(a, b); assert_eq!(hash(&a), hash(&b)); // ..but not other fields. assert_ne!(a, c); assert_ne!(hash(&a), hash(&c)); // Absence of timeout is included in hash. assert_ne!(a, d); assert_ne!(hash(&a), hash(&d)); } ...
{ // TODO: Tests like these would be cleaner with the builder pattern for the rust-side Process API. let process_generator = |description: String, timeout: Option<Duration>| { let mut p = Process::new(vec![]); p.description = description; p.timeout = timeout; p }; fn hash<Hashable: Hash>(hasha...
identifier_body
tests.rs
// Copyright 2021 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; use std::time::Duration; use crate::{Process, ProcessResultMetadata}; use bazel_protos::gen::build::bazel::...
() { let metadata = ProcessResultMetadata::new(Some(concrete_time::Duration::new(5, 150))); let time_saved = metadata.time_saved_from_cache(Duration::new(1, 100)); assert_eq!(time_saved, Some(Duration::new(4, 50))); // If the cache lookup took more time than the process, we return 0. let metadata = ProcessRe...
process_result_metadata_time_saved_from_cache
identifier_name
node.py
import threading from queue import Queue, Empty from time import sleep from libAnt.drivers.driver import Driver from libAnt.message import * class Network: def __init__(self, key: bytes = b'\x00' * 8, name: str = None):
def __str__(self): return self.name class Pump(threading.Thread): def __init__(self, driver: Driver, initMessages, out: Queue, onSucces, onFailure): super().__init__() self._stopper = threading.Event() self._driver = driver self._out = out self._initMessages =...
self.key = key self.name = name self.number = 0
identifier_body
node.py
import threading from queue import Queue, Empty from time import sleep from libAnt.drivers.driver import Driver
class Network: def __init__(self, key: bytes = b'\x00' * 8, name: str = None): self.key = key self.name = name self.number = 0 def __str__(self): return self.name class Pump(threading.Thread): def __init__(self, driver: Driver, initMessages, out: Queue, onSucces, onFailur...
from libAnt.message import *
random_line_split
node.py
import threading from queue import Queue, Empty from time import sleep from libAnt.drivers.driver import Driver from libAnt.message import * class Network: def __init__(self, key: bytes = b'\x00' * 8, name: str = None): self.key = key self.name = name self.number = 0 def __str__(self...
elif msg.type == MESSAGE_CHANNEL_BROADCAST_DATA: bmsg = BroadcastMessage(msg.type, msg.content).build(msg.content) self._onSuccess(bmsg) except Empty: pass except ...
for w in self._waiters: if w.type == msg.content[1]: # ACK self._waiters.remove(w) # TODO: Call waiter callback from tuple (waiter, callback) break
conditional_block
node.py
import threading from queue import Queue, Empty from time import sleep from libAnt.drivers.driver import Driver from libAnt.message import * class Network: def __init__(self, key: bytes = b'\x00' * 8, name: str = None): self.key = key self.name = name self.number = 0 def __str__(self...
(self): pass
getCapabilities
identifier_name
mod.rs
}; use BuilderAttribs; pub use self::monitor::{MonitorID, get_available_monitors, get_primary_monitor}; use winapi; mod event; mod gl; mod init; mod monitor; /// pub struct HeadlessContext(Window); impl HeadlessContext { /// See the docs in the crate root file. pub fn new(builder: BuilderAttribs) -> Resu...
{ /// Main handle for the window. window: winapi::HWND, /// This represents a "draw context" for the surface of the window. hdc: winapi::HDC, /// OpenGL context. context: winapi::HGLRC, /// Binded to `opengl32.dll`. /// /// `wglGetProcAddress` returns null for GL 1.1 functions be...
Window
identifier_name
mod.rs
}; use BuilderAttribs; pub use self::monitor::{MonitorID, get_available_monitors, get_primary_monitor}; use winapi; mod event; mod gl; mod init; mod monitor; /// pub struct HeadlessContext(Window);
impl HeadlessContext { /// See the docs in the crate root file. pub fn new(builder: BuilderAttribs) -> Result<HeadlessContext, CreationError> { let BuilderAttribs { dimensions, gl_version, gl_debug, .. } = builder; init::new_window(dimensions, "".to_string(), None, gl_version, gl_debug, false, t...
random_line_split
mod.rs
use BuilderAttribs; pub use self::monitor::{MonitorID, get_available_monitors, get_primary_monitor}; use winapi; mod event; mod gl; mod init; mod monitor; /// pub struct HeadlessContext(Window); impl HeadlessContext { /// See the docs in the crate root file. pub fn new(builder: BuilderAttribs) -> Result<H...
/// See the docs in the crate root file. pub fn get_outer_size(&self) -> Option<(uint, uint)> { use std::mem; let mut rect: winapi::RECT = unsafe { mem::uninitialized() }; if unsafe { winapi::GetWindowRect(self.window, &mut rect) } == 0 { return None } Som...
{ use std::mem; let mut rect: winapi::RECT = unsafe { mem::uninitialized() }; if unsafe { winapi::GetClientRect(self.window, &mut rect) } == 0 { return None } Some(( (rect.right - rect.left) as uint, (rect.bottom - rect.top) as uint )...
identifier_body
detailRowCompCache.d.ts
// Type definitions for @ag-grid-community/core v25.1.0 // Project: http://www.ag-grid.com/ // Definitions by: Niall Crosby <https://github.com/ag-grid/> import { ICellRendererComp } from "../cellRenderers/iCellRenderer"; import { RowNode } from "../../entities/rowNode"; import { BeanStub } from "../../context/beanStub...
extends BeanStub { private cacheItems; private maxCacheSize; private active; private postConstruct; addOrDestroy(rowNode: RowNode, pinned: string | null, comp: ICellRendererComp): void; private getCacheItem; private stampCacheItem; private destroyFullWidthRow; private purgeCache; ...
DetailRowCompCache
identifier_name
detailRowCompCache.d.ts
// Type definitions for @ag-grid-community/core v25.1.0 // Project: http://www.ag-grid.com/ // Definitions by: Niall Crosby <https://github.com/ag-grid/> import { ICellRendererComp } from "../cellRenderers/iCellRenderer"; import { RowNode } from "../../entities/rowNode"; import { BeanStub } from "../../context/beanStub...
private cacheItems; private maxCacheSize; private active; private postConstruct; addOrDestroy(rowNode: RowNode, pinned: string | null, comp: ICellRendererComp): void; private getCacheItem; private stampCacheItem; private destroyFullWidthRow; private purgeCache; get(rowNode: RowNo...
* still be applied after the detail grid is shown for the second time. */ export declare class DetailRowCompCache extends BeanStub {
random_line_split
skills_scene.rs
use std::path::Path; use uorustlibs::skills::Skills; use cgmath::Point2; use ggez::event::{KeyCode, KeyMods}; use ggez::graphics::{self, Text}; use ggez::{Context, GameResult}; use scene::{BoxedScene, Scene, SceneChangeEvent, SceneName}; pub struct SkillsScene { pages: Vec<Text>, exiting: bool, } impl<'a> Sk...
}
{ match keycode { KeyCode::Escape => self.exiting = true, _ => (), } }
identifier_body
skills_scene.rs
use std::path::Path; use uorustlibs::skills::Skills; use cgmath::Point2; use ggez::event::{KeyCode, KeyMods}; use ggez::graphics::{self, Text}; use ggez::{Context, GameResult}; use scene::{BoxedScene, Scene, SceneChangeEvent, SceneName}; pub struct SkillsScene { pages: Vec<Text>, exiting: bool, } impl<'a> Sk...
; format!("{} {}", glyph, skill.name) }) .collect(); Text::new(skills.join("\n")) }) .collect(); items } Err(error) => { ...
{ "-" }
conditional_block
skills_scene.rs
use std::path::Path; use uorustlibs::skills::Skills; use cgmath::Point2; use ggez::event::{KeyCode, KeyMods}; use ggez::graphics::{self, Text}; use ggez::{Context, GameResult}; use scene::{BoxedScene, Scene, SceneChangeEvent, SceneName}; pub struct SkillsScene { pages: Vec<Text>, exiting: bool, } impl<'a> Sk...
fn update( &mut self, _ctx: &mut Context, _engine_data: &mut (), ) -> GameResult<Option<SceneChangeEvent<SceneName>>> { if self.exiting { Ok(Some(SceneChangeEvent::PopScene)) } else { Ok(None) } } fn key_down_event( &mut se...
Ok(()) }
random_line_split
skills_scene.rs
use std::path::Path; use uorustlibs::skills::Skills; use cgmath::Point2; use ggez::event::{KeyCode, KeyMods}; use ggez::graphics::{self, Text}; use ggez::{Context, GameResult}; use scene::{BoxedScene, Scene, SceneChangeEvent, SceneName}; pub struct
{ pages: Vec<Text>, exiting: bool, } impl<'a> SkillsScene { pub fn new() -> BoxedScene<'a, SceneName, ()> { let skills = Skills::new( &Path::new("./assets/skills.idx"), &Path::new("./assets/skills.mul"), ); let text = match skills { Ok(skills) =>...
SkillsScene
identifier_name
fakeipmitool.py
import os import time import yaml import random import argparse from rackattack.physical import pikapatch from rackattack.physical.tests.integration.main import useFakeRackConf, useFakeIPMITool intervalRanges = {0: (0.01, 0.05), 0.85: (0.3, 0.6), 0.95: (2, 4)} rangesProbabilities = intervalRanges.keys() rangesProbabi...
else: raise NotImplementedError def sol(subaction): if subaction != "activate": return possibleOutputLines = ("Yo yo i'm a cool server", "This server has got swag.", "Wow this totally looks like a serial log of a linux server", ...
print "Chassis Power Control: Down/Off"
conditional_block
fakeipmitool.py
import os import time import yaml import random import argparse from rackattack.physical import pikapatch from rackattack.physical.tests.integration.main import useFakeRackConf, useFakeIPMITool intervalRanges = {0: (0.01, 0.05), 0.85: (0.3, 0.6), 0.95: (2, 4)} rangesProbabilities = intervalRanges.keys() rangesProbabi...
def main(args): useFakeRackConf() useFakeIPMITool() if args.I != "lanplus": assert args.I is None action = dict(power=power, sol=sol).get(args.action) action(args.subaction) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("-I", default=None, typ...
if subaction != "activate": return possibleOutputLines = ("Yo yo i'm a cool server", "This server has got swag.", "Wow this totally looks like a serial log of a linux server", "asdasd") while True: withinBound = ran...
identifier_body
fakeipmitool.py
import os import time import yaml import random import argparse from rackattack.physical import pikapatch from rackattack.physical.tests.integration.main import useFakeRackConf, useFakeIPMITool
intervalRanges = {0: (0.01, 0.05), 0.85: (0.3, 0.6), 0.95: (2, 4)} rangesProbabilities = intervalRanges.keys() rangesProbabilities.sort() def informFakeConsumersManagerOfReboot(hostname): rebootsPipe = os.environ["FAKE_REBOOTS_PIPE_PATH"] fd = os.open(rebootsPipe, os.O_WRONLY) os.write(fd, "%(hostname)s,"...
random_line_split
fakeipmitool.py
import os import time import yaml import random import argparse from rackattack.physical import pikapatch from rackattack.physical.tests.integration.main import useFakeRackConf, useFakeIPMITool intervalRanges = {0: (0.01, 0.05), 0.85: (0.3, 0.6), 0.95: (2, 4)} rangesProbabilities = intervalRanges.keys() rangesProbabi...
(args): useFakeRackConf() useFakeIPMITool() if args.I != "lanplus": assert args.I is None action = dict(power=power, sol=sol).get(args.action) action(args.subaction) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("-I", default=None, type=str) ...
main
identifier_name
lagos.py
#! /usr/bin/python3 # -*- coding:utf-8 -*- # lagos # by antoine@2ohm.fr """ Play a little with imap. """ import imaplib import smtplib from lib.remail import remail from lib.redoc import redoc import yaml import sys import os import logging # Config the log machine logging.basicConfig( format='\033[90m[%(lev...
# Define aliases pool = config.get('pool', '/tmp/pool/') # Init the connexion with the IMAP server logging.info('Connect to the IMAP server') M = imaplib.IMAP4_SSL(config.get('imap_server', '')) M.login(config.get('imap_user', ''), config.get('imap_password', '')) M.select() # Fetch all mails typ, data = M...
"""Send a mail. """ S = smtplib.SMTP(config.get('smtp_server', '')) S.login(config.get('smtp_user', ''), config.get('smtp_password', '')) S.sendmail(fromaddr, toaddr, mss) S.quit()
identifier_body
lagos.py
#! /usr/bin/python3 # -*- coding:utf-8 -*- # lagos # by antoine@2ohm.fr """ Play a little with imap. """ import imaplib import smtplib from lib.remail import remail from lib.redoc import redoc import yaml import sys import os import logging # Config the log machine logging.basicConfig( format='\033[90m[%(lev...
d.meta_write() #logging.info('Send a message back') #sendMail(config.get('imap_user', ''), sender, 'Hello back.', config) M.close() M.logout()
newMeta = allMeta.get(filename, allMeta) d.meta_add(newMeta)
conditional_block
lagos.py
#! /usr/bin/python3 # -*- coding:utf-8 -*- # lagos # by antoine@2ohm.fr """ Play a little with imap. """ import imaplib import smtplib from lib.remail import remail from lib.redoc import redoc import yaml import sys import os import logging # Config the log machine logging.basicConfig( format='\033[90m[%(lev...
(fromaddr, toaddr, mss, config): """Send a mail. """ S = smtplib.SMTP(config.get('smtp_server', '')) S.login(config.get('smtp_user', ''), config.get('smtp_password', '')) S.sendmail(fromaddr, toaddr, mss) S.quit() # Define aliases pool = config.get('pool', '/tmp/pool/') # Init t...
sendMail
identifier_name
lagos.py
#! /usr/bin/python3 # -*- coding:utf-8 -*- # lagos # by antoine@2ohm.fr """ Play a little with imap. """ import imaplib import smtplib from lib.remail import remail from lib.redoc import redoc import yaml import sys import os import logging # Config the log machine logging.basicConfig( format='\033[90m[%(lev...
print('from: %s' % sender) print('about: %s' % subject) print('%s' % content) print(filenames) for filename in filenames: # Create a redoc path = os.path.join(pool, filename) d = redoc(path) # Look for additional metadata allMeta = yaml.load(content) ...
random_line_split
subscribe.component.ts
import { Component, OnInit } from '@angular/core'; import {Router} from '@angular/router'; import {Person} from './person' import {RepPwdValidator} from './repPwdValidator.directive' import {SubscribeService} from './subscribe.service'; @Component({ selector: 'subscription', templateUrl: 'app/subscribe/sub...
else this.passwordFieldType = 'password'; } onBlurEmail(){ console.log('ONBLUREMAIL'); } register(){ this.subscribeService.post(this.person).then( rc => { this.returnedCode = rc; console.log('returnedCode: '+rc); if(rc=='registration_completed') { this.router.navigate(['...
hideShowPassword(){ if (this.passwordFieldType == 'password') this.passwordFieldType = 'text';
random_line_split
subscribe.component.ts
import { Component, OnInit } from '@angular/core'; import {Router} from '@angular/router'; import {Person} from './person' import {RepPwdValidator} from './repPwdValidator.directive' import {SubscribeService} from './subscribe.service'; @Component({ selector: 'subscription', templateUrl: 'app/subscribe/sub...
if(rc=='wrong_captcha') { this.reloadCaptcha(); } } ); } reloadCaptcha(){ /*this.router.navigate(['/authenticate', 'registration_completed']); */ if(this.captchaUrl.includes('captchaTempArg1')) this.captchaUrl = 'api/showCaptcha?captchaTempArg2=1'; else this.captchaUrl = 'api/sho...
{ this.router.navigate(['/authenticate', rc]); }
conditional_block
subscribe.component.ts
import { Component, OnInit } from '@angular/core'; import {Router} from '@angular/router'; import {Person} from './person' import {RepPwdValidator} from './repPwdValidator.directive' import {SubscribeService} from './subscribe.service'; @Component({ selector: 'subscription', templateUrl: 'app/subscribe/sub...
}
{ }
identifier_body
subscribe.component.ts
import { Component, OnInit } from '@angular/core'; import {Router} from '@angular/router'; import {Person} from './person' import {RepPwdValidator} from './repPwdValidator.directive' import {SubscribeService} from './subscribe.service'; @Component({ selector: 'subscription', templateUrl: 'app/subscribe/sub...
implements OnInit{ constructor(router: Router, private subscribeService: SubscribeService) { this.router=router; } router:Router; person = new Person('','','',''); active = true; passwordFieldType = 'password'; returnedCode: String; captchaUrl = 'api/showCaptcha'; newPerson()...
SubscribeComponent
identifier_name
student-routing.module.ts
import {NgModule} from '@angular/core'; import {Routes, RouterModule} from '@angular/router'; import {StudentListComponent} from './student-list/student-list.component'; import {StudentDetailComponent} from './student-detail/student-detail.component'; import {StudentComponent} from './student/student.component'; impo...
{ path: 'add', canActivate: [AuthGuardService], component: StudentDetailComponent }, { path: 'delete/:studentId', canActivate: [AuthGuardService], component: StudentComponent }, { path: 'detail/:studentId', canActivate: [AuthGuardService], component: StudentComponent }, { path: 'update/:st...
// {path: ':studentId', component: StudentComponent} // ] // },
random_line_split
student-routing.module.ts
import {NgModule} from '@angular/core'; import {Routes, RouterModule} from '@angular/router'; import {StudentListComponent} from './student-list/student-list.component'; import {StudentDetailComponent} from './student-detail/student-detail.component'; import {StudentComponent} from './student/student.component'; impo...
{ }
StudentRoutingModule
identifier_name
config.js
(function(App) { 'use strict'; var Config = { title: 'Guimovie', platform: process.platform, genres: [ 'All', 'Action', 'Adventure', 'Animation', 'Biography', 'Comedy', 'Crime', 'Documentary'...
'Mystery', 'Romance', 'Sci-Fi', 'Short', 'Sport', 'Thriller', 'War', 'Western' ], sorters: [ 'popularity', 'date', 'year', 'rating', 'alphabet' ...
'Film-Noir', 'History', 'Horror', 'Music', 'Musical',
random_line_split
config.js
(function(App) { 'use strict'; var Config = { title: 'Guimovie', platform: process.platform, genres: [ 'All', 'Action', 'Adventure', 'Animation', 'Biography', 'Comedy', 'Crime', 'Documentary'...
return App.Providers.get(provider); } }; App.Config = Config; })(window.App);
{ return _.map(provider, function(t) { return App.Providers.get(t); }); }
conditional_block
advanced.service.ts
import { Injectable } from '@angular/core'; import { Observable } from 'rxjs/Observable'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import 'rxjs/add/observable/empty'; import { GlobalService } from '../../shared/services/global.service'; import { NavigationService, Page } from '../../shared/serv...
(urlPostfix: string): string { return `${this.urlPrefix}${urlPostfix}`; } }
makeUrl
identifier_name
advanced.service.ts
import { Injectable } from '@angular/core'; import { Observable } from 'rxjs/Observable'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import 'rxjs/add/observable/empty'; import { GlobalService } from '../../shared/services/global.service'; import { NavigationService, Page } from '../../shared/serv...
} @Injectable() export class AdvancedService { private urlPrefix = ''; private readonly walletName; private readonly accountName = 'account 0'; private headers = new HttpHeaders({'Content-Type': 'application/json'}); constructor(private httpClient: HttpClient, private globalService: GlobalService...
{}
identifier_body
advanced.service.ts
import { Injectable } from '@angular/core'; import { Observable } from 'rxjs/Observable'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import 'rxjs/add/observable/empty'; import { GlobalService } from '../../shared/services/global.service'; import { NavigationService, Page } from '../../shared/serv...
} return addresses; } private makeUrl(urlPostfix: string): string { return `${this.urlPrefix}${urlPostfix}`; } }
private processAddresses(response: any): string[] { const addresses = new Array<string>(); for (const address of response) { addresses.push(address);
random_line_split
cycle_basis.py
if it is absent, a closed path will be calculated together with coordinates. coords is an array of x-y pairs representing the coordinates of the cycle path elements. """ def __init__(self, graph, edges, coords=None): """ Initializes the Cycle with an edge list representing the cy...
def outer_loop(G, cycles): """ Detects the boundary loop in the set of fundamental cycles by noting that the boundary is precisely the one loop with maximum area (since it contains all other loops, they all must have smaller area) """
""" Returns a matplotlib Path object describing the cycle. """ # Set up polygon verts = zeros((cycle.coords.shape[0] + 1, cycle.coords.shape[1])) verts[:-1,:] = cycle.coords verts[-1,:] = cycle.coords[0,:] codes = Path.LINETO*ones(verts.shape[0]) codes[0] = Path.MOVETO codes[-1] = Path....
identifier_body
cycle_basis.py
'], graph.node[n]['y']] for n in self.path]) else: self.coords = coords self.edges = edges # This allows comparisons self.edgeset = set([tuple(sorted(e)) for e in edges]) self.com = mean(self.coords, axis=0) # This frozenset is used to co...
path, edges, coords = traverse_graph(G, u, v) cycleset.add(Cycle(G, edges, coords=coords)) path, edges, coords = traverse_graph(G, v, u) cycleset.add(Cycle(G, edges, coords=coords))
conditional_block
cycle_basis.py
if it is absent, a closed path will be calculated together with coordinates. coords is an array of x-y pairs representing the coordinates of the cycle path elements. """ def __init__(self, graph, edges, coords=None): """ Initializes the Cycle with an edge list representing the cy...
(self, other): """ Returns an edge set representing the intersection of the two cycles. """ inters = self.edgeset.intersection(other.edgeset) return inters def union(self, other, data=True): """ Returns the edge set corresponding to the union of two cycles. ...
intersection
identifier_name
cycle_basis.py
. if it is absent, a closed path will be calculated together with coordinates. coords is an array of x-y pairs representing the coordinates of the cycle path elements. """ def __init__(self, graph, edges, coords=None): """ Initializes the Cycle with an edge list representing the ...
# Remove pathological protruding loops if prev in nodes_visited_set: n_ind = nodes_visited.index(prev) del nodes_visited[n_ind+1:] del coords[n_ind+1:] del edges_visited[n_ind:] nodes_visited_set.add(prev) edges_visited.append((nodes_visited...
random_line_split
setup.py
from setuptools import setup, find_packages from codecs import open from os import path
long_description = f.read() setup( name='jestocke-mangopaysdk', version='3.0.6', description='A client library written in python to work with mangopay v2 api', long_description='This SDK is a client library for interacting with the Mangopay API.', url='https://github.com/Mangopay/mangopay2-pyth...
here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'DESCRIPTION.md'), encoding='utf-8') as f:
random_line_split
views.py
""" Views to support bulk email functionalities like opt-out. """ import logging from six import text_type from django.contrib.auth.models import User from django.http import Http404 from bulk_email.models import Optout from courseware.courses import get_course_by_id from edxmako.shortcuts import render_to_respons...
except InvalidKeyError: raise Http404("course") unsub_check = request.POST.get('unsubscribe', False) context = { 'course': course, 'unsubscribe': unsub_check } if request.method == 'GET': return render_to_response('bulk_email/confirm_unsubscribe.html', context) ...
except UsernameDecryptionException as exn: raise Http404(text_type(exn)) except User.DoesNotExist: raise Http404("username")
random_line_split
views.py
""" Views to support bulk email functionalities like opt-out. """ import logging from six import text_type from django.contrib.auth.models import User from django.http import Http404 from bulk_email.models import Optout from courseware.courses import get_course_by_id from edxmako.shortcuts import render_to_respons...
raise Http404("username") except InvalidKeyError: raise Http404("course") unsub_check = request.POST.get('unsubscribe', False) context = { 'course': course, 'unsubscribe': unsub_check } if request.method == 'GET': return render_to_response('bulk_email/confir...
""" A view that let users opt out of any email updates. This meant is meant to be the target of an opt-out link or button. The `token` parameter must decrypt to a valid username. The `course_id` is the string course key of any course. Raises a 404 if there are any errors parsing the input. """...
identifier_body
views.py
""" Views to support bulk email functionalities like opt-out. """ import logging from six import text_type from django.contrib.auth.models import User from django.http import Http404 from bulk_email.models import Optout from courseware.courses import get_course_by_id from edxmako.shortcuts import render_to_respons...
return render_to_response('bulk_email/unsubscribe_success.html', context)
Optout.objects.get_or_create(user=user, course_id=course_key) log.info( u"User %s (%s) opted out of receiving emails from course %s", user.username, user.email, course_id, )
conditional_block
views.py
""" Views to support bulk email functionalities like opt-out. """ import logging from six import text_type from django.contrib.auth.models import User from django.http import Http404 from bulk_email.models import Optout from courseware.courses import get_course_by_id from edxmako.shortcuts import render_to_respons...
(request, token, course_id): """ A view that let users opt out of any email updates. This meant is meant to be the target of an opt-out link or button. The `token` parameter must decrypt to a valid username. The `course_id` is the string course key of any course. Raises a 404 if there are any ...
opt_out_email_updates
identifier_name
and.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/. // //! AND implementation. //! //! Will be automatically included when including `filter::Filter`, so importing th...
<T, U>(T, U); impl<T, U> FailableAnd<T, U> { pub fn new(a: T, b: U) -> FailableAnd<T, U> { FailableAnd(a, b) } } impl<N, T, U, E> FailableFilter<N> for FailableAnd<T, U> where T: FailableFilter<N, Error = E>, U: FailableFilter<N, Error = E> { type Error = E; fn filter(&self, e...
FailableAnd
identifier_name
and.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/. // //! AND implementation. //! //! Will be automatically included when including `filter::Filter`, so importing th...
}
{ Ok(self.0.filter(e)? && self.1.filter(e)?) }
identifier_body
and.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/. // //! AND implementation. //! //! Will be automatically included when including `filter::Filter`, so importing th...
}
}
random_line_split
drag-and-drop.js
/** * @license Copyright 2017 Google Inc. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or a...
{ module.exports = DragAndDrop; }
conditional_block
drag-and-drop.js
/** * @license Copyright 2017 Google Inc. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or a...
document.addEventListener('dragenter', _ => { this._dropZone.classList.add('dropping'); this._dragging = true; }); document.addEventListener('drop', e => { e.stopPropagation(); e.preventDefault(); this._resetDraggingUI(); // Note, this ignores multiple files in the dro...
e.stopPropagation(); e.preventDefault(); e.dataTransfer.dropEffect = 'copy'; // Explicitly show as copy action. });
random_line_split
drag-and-drop.js
/** * @license Copyright 2017 Google Inc. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or a...
(fileHandlerCallback) { this._dropZone = document.querySelector('.drop_zone'); this._fileHandlerCallback = fileHandlerCallback; this._dragging = false; this._addListeners(); } _addListeners() { // The mouseleave event is more reliable than dragleave when the user drops // the file outside ...
constructor
identifier_name
drag-and-drop.js
/** * @license Copyright 2017 Google Inc. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or a...
} if (typeof module !== 'undefined' && module.exports) { module.exports = DragAndDrop; }
{ this._dropZone.classList.remove('dropping'); this._dragging = false; }
identifier_body
fullcalendar.js
/** * --------------------------------------------------------------------- * GLPI - Gestionnaire Libre de Parc Informatique * Copyright (C) 2015-2020 Teclib' and contributors. * * http://glpi-project.org * * based on GLPI - Gestionnaire Libre de Parc Informatique * Copyright (C) 2003-2014 by the INDEPNET Devel...
require('@fullcalendar/core'); require('@fullcalendar/daygrid'); require('@fullcalendar/interaction'); require('@fullcalendar/list'); require('@fullcalendar/timegrid'); require('@fullcalendar/rrule'); require('@fullcalendar/core/main.css'); require('@fullcalendar/daygrid/main.css'); require('@fullcalendar/list/main.cs...
// lib is exported as a module, so it must be imported as a module import { } from 'rrule' // Fullcalendar library
random_line_split
__init__.py
): """ This function does the rollback itself and resets the dirty flag. """ self._rollback() self.set_clean() def savepoint(self): """ Creates a savepoint (if supported and required by the backend) inside the current transaction. Returns an identifie...
newly created ID. """ return cursor.fetchone()[0] def field_cast_sql(self, db_type): """ Given a column type (e.g. 'BLOB', 'VARCHAR'), returns the SQL necessary to cast it before using it in a WHERE statement. Note that the resulting string should contain a '...
Given a cursor object that has just performed an INSERT...RETURNING statement into a table that has an auto-incrementing ID, returns the
random_line_split
__init__.py
""" This function does the rollback itself and resets the dirty flag. """ self._rollback() self.set_clean() def savepoint(self): """ Creates a savepoint (if supported and required by the backend) inside the current transaction. Returns an identifier f...
""" Given a lookup_type of 'year', 'month' or 'day', returns the SQL that extracts a value from the given date field field_name. """ raise NotImplementedError() def date_interval_sql(self, sql, connector, timedelta): """ Implements the date interval functiona...
""" This class encapsulates all backend-specific differences, such as the way a backend performs ordering or calculates the ID of a recently-inserted row. """ compiler_module = "django.db.models.sql.compiler" def __init__(self): self._cache = None def autoinc_sql(self, table, colum...
identifier_body
__init__.py
None if no SQL is necessary. This SQL is executed when a table is created. """ return None def date_extract_sql(self, lookup_type, field_name): """ Given a lookup_type of 'year', 'month' or 'day', returns the SQL that extracts a value from the given date field fiel...
value_to_db_datetime
identifier_name
__init__.py
a dirty transaction need to be rolled back # before the cursor can be used again? requires_rollback_on_dirty_transaction = False # Does the backend allow very long model names without error? supports_long_model_names = True # Is there a REAL datatype in addition to floats/doubles? has_real_da...
self._cache = import_module(self.compiler_module)
conditional_block
utils.test.ts
import { validateNameVersion } from './utils' describe('Validate name and version', () => { test('Standard naming', () => { const axios = { name: 'axios', version: '^0.21.1' } expect(validateNameVersion(axios)).toEqual(axios) const pkg = { name: 'pkg', version: '4.3.7' } expect(validateNameVersion(p...
name: 'hard-source-webpack-plugin', version: 'git+https://github.com/botpress/hard-source-webpack-plugin.git' } expect(validateNameVersion(pkg)).toEqual(pkg) }) })
random_line_split
testrunner.py
#!/usr/bin/env python from __future__ import print_function import argparse import os from falafel import findout_terminal_width from falafel import test_list from falafel.runners import FalafelTestRunner from falafel.loaders import FalafelTestLoader parser = argparse.ArgumentParser(description='custom test runner ...
width = findout_terminal_width() print(" info ".center(width, '=')) print("suite: %s" % pkg) print("tests: %s" % allowed_tests) print("interactive tests: %s" % args.interactive) print('=' * width) if args.interactive: os.environ['INTERACTIVE_TESTS'] = '1' loader = FalafelTestLoader(allowed_tests=allowed_tests) ...
pkg = args.suite allowed_tests = args.test
random_line_split
testrunner.py
#!/usr/bin/env python from __future__ import print_function import argparse import os from falafel import findout_terminal_width from falafel import test_list from falafel.runners import FalafelTestRunner from falafel.loaders import FalafelTestLoader parser = argparse.ArgumentParser(description='custom test runner ...
try: from tabulate import tabulate except ImportError: for data in tdata: print(" %-30s\tin %-30s\tskipped: %s" % data) else: headers = ['class.method', 'module'] if with_skipped: headers.append('skipped') print('\n%s' % tabulate(tdata, heade...
print("The following tests will be run:", end='')
conditional_block
thread-local-in-ctfe.rs
// Copyright 2017 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 ...
() -> u32 { A //~^ ERROR thread-local statics cannot be accessed at compile-time } fn main() {}
f
identifier_name
thread-local-in-ctfe.rs
// Copyright 2017 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 ...
#[thread_local] static A: u32 = 1; static B: u32 = A; //~^ ERROR thread-local statics cannot be accessed at compile-time static C: &u32 = &A; //~^ ERROR thread-local statics cannot be accessed at compile-time const D: u32 = A; //~^ ERROR thread-local statics cannot be accessed at compile-time const E: &u32 = &A; /...
#![feature(const_fn, thread_local)]
random_line_split
thread-local-in-ctfe.rs
// Copyright 2017 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 ...
{}
identifier_body
build-config.js
/** * @license Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.md or http://ckeditor.com/license */ /** * This file was added automatically by CKEditor builder. * You may re-use it at any time to build CKEditor again.
* Visit online builder to build CKEditor from scratch. * * (2) http://ckeditor.com/builder/3a8f489fb5f950a53ad1186816ce3747 * Visit online builder to build CKEditor, starting with the same setup as before. * * (3) http://ckeditor.com/builder/download/3a8f489fb5f950a53ad1186816ce3747 * Straight ...
* * If you would like to build CKEditor online again * (for example to upgrade), visit one the following links: * * (1) http://ckeditor.com/builder
random_line_split