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
object-lifetime-default-ambiguous.rs
// Test that if a struct declares multiple region bounds for a given // type parameter, an explicit lifetime bound is required on object // lifetimes within. #![allow(dead_code)] trait Test { fn foo(&self) { } } struct Ref0<T:?Sized> { r: *mut T } struct Ref1<'a,T:'a+?Sized> { r: &'a T } struct Ref2<'a...
} fn d(t: Ref2<Ref1<dyn Test>>) { // In this case, the lifetime parameter from the Ref1 overrides. } fn e(t: Ref2<Ref0<dyn Test>>) { // In this case, Ref2 is ambiguous, but Ref0 overrides with 'static. } fn f(t: &Ref2<dyn Test>) { //~^ ERROR lifetime bound for this object type cannot be deduced from cont...
fn c(t: Ref2<&dyn Test>) { // In this case, the &'a overrides.
random_line_split
object-lifetime-default-ambiguous.rs
// Test that if a struct declares multiple region bounds for a given // type parameter, an explicit lifetime bound is required on object // lifetimes within. #![allow(dead_code)] trait Test { fn foo(&self) { } } struct Ref0<T:?Sized> { r: *mut T } struct Ref1<'a,T:'a+?Sized> { r: &'a T } struct Ref2<'a...
<'a,'b>(t: Ref2<'a,'b, dyn Test>) { //~^ ERROR lifetime bound for this object type cannot be deduced from context } fn b(t: Ref2<dyn Test>) { //~^ ERROR lifetime bound for this object type cannot be deduced from context } fn c(t: Ref2<&dyn Test>) { // In this case, the &'a overrides. } fn d(t: Ref2<Ref1<...
a
identifier_name
object-lifetime-default-ambiguous.rs
// Test that if a struct declares multiple region bounds for a given // type parameter, an explicit lifetime bound is required on object // lifetimes within. #![allow(dead_code)] trait Test { fn foo(&self) { } } struct Ref0<T:?Sized> { r: *mut T } struct Ref1<'a,T:'a+?Sized> { r: &'a T } struct Ref2<'a...
fn main() { }
{ //~^ ERROR lifetime bound for this object type cannot be deduced from context }
identifier_body
groups.js
// // Webble World 3.0 (IntelligentPad system for the web) // // Copyright (c) 2010-2015 Micke Nicander Kuwahara, Giannis Georgalis, Yuzuru Tanaka // in Meme Media R&D Group of Hokkaido University, Japan. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use t...
$http.put('/api/groups/' + $scope.selectedGroup.id + '/objects', { obj: obj.id, remove: true }).then(function() { $scope.publishedObjects.splice(index, 1); }, function (err) { $scope.alerts.push({ type: 'danger', msg: err.data }); }); }); }; //********************************************...
random_line_split
groups.js
// // Webble World 3.0 (IntelligentPad system for the web) // // Copyright (c) 2010-2015 Micke Nicander Kuwahara, Giannis Georgalis, Yuzuru Tanaka // in Meme Media R&D Group of Hokkaido University, Japan. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use t...
//****************************************************************** function refreshAllGroups() { return $http.get('/api/groups').then(function(resp) { $scope.groups = resp.data; $scope.chartData = generateChartData($scope.groups, $scope.myGroups); }); } ////////////////////////////////////////////...
{ if (myGroupsArray) { var myGroupsById = {}; for (var i = 0; i < myGroupsArray.length; ++i) myGroupsById[myGroupsArray[i].id] = myGroupsArray[i]; for (i = 0; i < groupsArray.length; ++i) { if (!myGroupsById.hasOwnProperty(groupsArray[i].id)) groupsArray[i].readonly = true; } } return...
identifier_body
groups.js
// // Webble World 3.0 (IntelligentPad system for the web) // // Copyright (c) 2010-2015 Micke Nicander Kuwahara, Giannis Georgalis, Yuzuru Tanaka // in Meme Media R&D Group of Hokkaido University, Japan. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use t...
(g) { return [{ v: g.id, f: gToF(g) }, g.parent_id, g.description]; } function gsToData(gs) { var rows = [ ['Name', 'Parent Group', 'Tooltip'] ]; // cols gs.forEach(function(g) { rows.push(gToRow(g)); }); return rows; } //****************************************************************** function genera...
gToRow
identifier_name
test_funcs.py
import unittest from libs.funcs import * class TestFuncs(unittest.TestCase): def test_buildPaths(self): recPaths, repPaths, rouPaths, corePaths = buildPaths() findTxt = lambda x, y: x.find(y) > -1 assert findTxt(recPaths["Task"][0], "base") assert findTxt(recPaths["Department"][0...
(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(TestFuncs)) return suite if __name__ == '__main__': unittest.main(defaultTest='test_suite')
test_suite
identifier_name
test_funcs.py
import unittest from libs.funcs import * class TestFuncs(unittest.TestCase): def test_buildPaths(self): recPaths, repPaths, rouPaths, corePaths = buildPaths() findTxt = lambda x, y: x.find(y) > -1 assert findTxt(recPaths["Task"][0], "base") assert findTxt(recPaths["Department"][0...
if __name__ == '__main__': unittest.main(defaultTest='test_suite')
suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(TestFuncs)) return suite
identifier_body
test_funcs.py
import unittest from libs.funcs import * class TestFuncs(unittest.TestCase): def test_buildPaths(self): recPaths, repPaths, rouPaths, corePaths = buildPaths() findTxt = lambda x, y: x.find(y) > -1 assert findTxt(recPaths["Task"][0], "base") assert findTxt(recPaths["Department"][0...
"generateTaxes", "roundValue", "getOriginType", "bring", "getXML", "createField")]) assert meth["fieldIsEditable"][0] == "self" assert meth["fieldIsEditable"][1] == "fieldname" assert meth["fieldIsEditable"][2] == {"rowfieldname":'None'} assert meth["fieldIsEditable"][3] == {...
assert attr["ParentInvoice"] == "SuperClass" assert isinstance(attr["DocTypes"], list) assert isinstance(attr["Origin"], dict) assert all([m in meth for m in ("getCardReader", "logTransactionAction", "updateCredLimit",
random_line_split
test_funcs.py
import unittest from libs.funcs import * class TestFuncs(unittest.TestCase): def test_buildPaths(self): recPaths, repPaths, rouPaths, corePaths = buildPaths() findTxt = lambda x, y: x.find(y) > -1 assert findTxt(recPaths["Task"][0], "base") assert findTxt(recPaths["Department"][0...
unittest.main(defaultTest='test_suite')
conditional_block
attr.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 https://mozilla.org/MPL/2.0/. */ use crate::parser::SelectorImpl; use cssparser::ToCss; use std::fmt; #[derive(Clone, Eq, PartialEq, ToShmem)] #[...
<NamespaceUrl> { Any, /// Empty string for no namespace Specific(NamespaceUrl), } #[derive(Clone, Eq, PartialEq, ToShmem)] pub enum ParsedAttrSelectorOperation<AttrValue> { Exists, WithValue { operator: AttrSelectorOperator, case_sensitivity: ParsedCaseSensitivity, expected...
NamespaceConstraint
identifier_name
attr.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 https://mozilla.org/MPL/2.0/. */ use crate::parser::SelectorImpl; use cssparser::ToCss; use std::fmt; #[derive(Clone, Eq, PartialEq, ToShmem)] #[...
#[derive(Clone, Copy, Eq, PartialEq, ToShmem)] pub enum AttrSelectorOperator { Equal, Includes, DashMatch, Prefix, Substring, Suffix, } impl ToCss for AttrSelectorOperator { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write, { // https://drafts.css...
random_line_split
attr.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 https://mozilla.org/MPL/2.0/. */ use crate::parser::SelectorImpl; use cssparser::ToCss; use std::fmt; #[derive(Clone, Eq, PartialEq, ToShmem)] #[...
ParsedCaseSensitivity::CaseSensitive | ParsedCaseSensitivity::ExplicitCaseSensitive => { CaseSensitivity::CaseSensitive }, ParsedCaseSensitivity::AsciiCaseInsensitive => CaseSensitivity::AsciiCaseInsensitive, } } } #[derive(Clone, Copy, Debug, Eq, Partia...
CaseSensitivity::CaseSensitive },
conditional_block
attr.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 https://mozilla.org/MPL/2.0/. */ use crate::parser::SelectorImpl; use cssparser::ToCss; use std::fmt; #[derive(Clone, Eq, PartialEq, ToShmem)] #[...
pub fn contains(self, haystack: &str, needle: &str) -> bool { match self { CaseSensitivity::CaseSensitive => haystack.contains(needle), CaseSensitivity::AsciiCaseInsensitive => { if let Some((&n_first_byte, n_rest)) = needle.as_bytes().split_first() { ...
match self { CaseSensitivity::CaseSensitive => a == b, CaseSensitivity::AsciiCaseInsensitive => a.eq_ignore_ascii_case(b), } }
identifier_body
subroutines.js
/** * Copyright 2012-2019, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict'; var d3 = require('d3'); var Registry = require('../registry'); var Plots = require('../plots/plots'); var Lib =...
(fullLayout) { var title = fullLayout.title; var dy = '0em'; if(Lib.isTopAnchor(title)) { dy = alignmentConstants.CAP_SHIFT + 'em'; } else if(Lib.isMiddleAnchor(title)) { dy = alignmentConstants.MID_SHIFT + 'em'; } return dy; } exports.doTraceStyle = function(gd) { var cal...
getMainTitleDy
identifier_name
subroutines.js
/** * Copyright 2012-2019, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict'; var d3 = require('d3'); var Registry = require('../registry'); var Plots = require('../plots/plots'); var Lib =...
/* * should we draw a line on counterAx at this side of ax? * It's assumed that counterAx is known to overlay the subplot we're working on * but it may not be its main axis. */ function shouldShowLineThisSide(ax, side, counterAx) { // does counterAx get a line at all? if(!counterAx.showline || !counterAx....
{ return (ax.ticks || ax.showline) && (subplot === ax._mainSubplot || ax.mirror === 'all' || ax.mirror === 'allticks'); }
identifier_body
subroutines.js
/** * Copyright 2012-2019, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict'; var d3 = require('d3'); var Registry = require('../registry'); var Plots = require('../plots/plots'); var Lib =...
// figure out which backgrounds we need to draw, // and in which layers to put them var lowerBackgroundIDs = []; var backgroundIds = []; var lowerDomains = []; // no need to draw background when paper and plot color are the same color, // activate mode just for large splom (which benefit t...
{ ax = axList[i]; var counterAx = ax._anchorAxis; // clear axis line positions, to be set in the subplot loop below ax._linepositions = {}; // stash crispRounded linewidth so we don't need to pass gd all over the place ax._lw = Drawing.crispRound(gd, ax.linewidth, 1); ...
conditional_block
subroutines.js
/** * Copyright 2012-2019, Plotly, Inc. * All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict'; var d3 = require('d3'); var Registry = require('../registry'); var Plots = require('../plots/plots'); var Lib =...
if(textAnchor === SVG_TEXT_ANCHOR_START) { hPadShift = title.pad.l; } else if(textAnchor === SVG_TEXT_ANCHOR_END) { hPadShift = -title.pad.r; } switch(title.xref) { case 'paper': return gs.l + gs.w * title.x + hPadShift; case 'container': default: ...
random_line_split
web.py
# Copyright [2017] [name of copyright owner] # 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 ...
ENFDA_API_URL = "api.fda.gov" OPENFDA_API_EVENT = "/drug/event.json" OPENFDA_API_LYRICA = '?search=patient.drug.medicinalproduct:"LYRICA"&limit=10' def get_main_page(self): html = ''' <html> <head> <title>OpenFDA app</title> </head> <body>...
identifier_body
web.py
# Copyright [2017] [name of copyright owner] # 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 ...
return com_num def drug_page(self,medicamentos): s='' for drug in medicamentos: s += "<li>"+drug+"</li>" html=''' <html> <head></head> <body> <ul> %s </ul> ...
m_num+=[event['companynumb']]
conditional_block
web.py
# Copyright [2017] [name of copyright owner] # 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 ...
data1 = r1.read() data = data1.decode('utf8') events = json.loads(data) #event = events['results'][0]['patient']['drug'] return events def get_medicinalproduct(self,com_num): conn = http.client.HTTPSConnection(self.OPENFDA_API_URL) conn.request("GET", self.OPE...
random_line_split
web.py
# Copyright [2017] [name of copyright owner] # 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 ...
ttp.server.BaseHTTPRequestHandler): OPENFDA_API_URL = "api.fda.gov" OPENFDA_API_EVENT = "/drug/event.json" OPENFDA_API_LYRICA = '?search=patient.drug.medicinalproduct:"LYRICA"&limit=10' def get_main_page(self): html = ''' <html> <head> <title>OpenFDA app</ti...
stHTTPRequestHandler(h
identifier_name
common.ts
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
it('should accept a basic message', () => { const message = 'QUACK!'; const grpcStatus = {code: 1, message}; const status = decorateStatus(grpcStatus); assert.strictEqual(status!.message, message); }); it('should parse JSON from the response message', () => { const message = { descripti...
random_line_split
lib.rs
// Copyright 2013-2018, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <https://opensource.org/licenses/MIT> #![allow(deprecated)] #![cfg_attr(feature = "cargo-clippy", allow(cast_ptr_alignment))] #![c...
mod time_coord; mod visual; mod window; pub use gdk_sys::GdkColor as Color; pub use self::rt::{init, set_initialized}; pub use atom::Atom; pub use atom::NONE as ATOM_NONE; pub use atom::SELECTION_CLIPBOARD; pub use atom::SELECTION_PRIMARY; pub use atom::SELECTION_SECONDARY; pub use atom::SELECTION_TYPE_ATOM; pub use...
mod rgba; mod screen;
random_line_split
CacheClient.js
var EventEmitter = require('eventemitter2').EventEmitter2, inherits = require('util').inherits, assert = require('assert'), assign = require('lodash/object/assign'), requireDir = require('require-directory'), StoreFacade = require('./StoreFacade'), Cache = require('./Cache'), deco = requireDir(module, './...
/*eslint-enable */
{ console.error('[distribucache] (%s) error from an unhandled ' + '`error` event:\n', namespace, err && err.stack || err); }
identifier_body
CacheClient.js
var EventEmitter = require('eventemitter2').EventEmitter2, inherits = require('util').inherits, assert = require('assert'), assign = require('lodash/object/assign'), requireDir = require('require-directory'), StoreFacade = require('./StoreFacade'), Cache = require('./Cache'), deco = requireDir(module, './...
if (!config.optimizeForBuffers) { cache = new deco.MarshallDecorator(cache); } if (config.expiresIn || config.staleIn) { cache = new deco.ExpiresDecorator(cache, { expiresIn: config.expiresIn, staleIn: config.staleIn }); } cache = new deco.EventDecorator(cache); if (config.popul...
{ cache = new deco.OnlySetChangedDecorator(cache); }
conditional_block
CacheClient.js
var EventEmitter = require('eventemitter2').EventEmitter2, inherits = require('util').inherits, assert = require('assert'), assign = require('lodash/object/assign'), requireDir = require('require-directory'), StoreFacade = require('./StoreFacade'), Cache = require('./Cache'), deco = requireDir(module, './...
(err, namespace) { console.error('[distribucache] (%s) error from an unhandled ' + '`error` event:\n', namespace, err && err.stack || err); } /*eslint-enable */
unhandledErrorListener
identifier_name
CacheClient.js
var EventEmitter = require('eventemitter2').EventEmitter2, inherits = require('util').inherits, assert = require('assert'), assign = require('lodash/object/assign'), requireDir = require('require-directory'), StoreFacade = require('./StoreFacade'), Cache = require('./Cache'), deco = requireDir(module, './...
* @param {String} [config.password] * @param {String} [config.namespace] * * @param {Boolean} [config.optimizeForSmallValues] defaults to false * @param {Boolean} [config.optimizeForBuffers] defaults to false * * @param {String} [config.expiresIn] in ms * @param {String} [config.staleIn] in ms * * @param {Fun...
* @param {Boolean} [config.isPreconfigured] defaults to false * * @param {String} [config.host] defaults to 'localhost' * @param {Number} [config.port] defaults to 6379
random_line_split
test_rest_providers_remove.py
""" Test for the remove.py module in the vcontrol/rest/providers directory """ from os import remove as delete_file from web import threadeddict from vcontrol.rest.providers import remove PROVIDERS_FILE_PATH = "../vcontrol/rest/providers/providers.txt" class ContextDummy(): env = threadeddict() env['HTTP_HO...
"\n", "Test:" ]) assert remove_provider.GET(test_provider) == "removed " + test_provider # read the file and see if it has removed the line with the test_provider with open(PROVIDERS_FILE_PATH, 'r') as f: provider_contents = f.readlines() delete_file(PROVIDERS_...
f.writelines([ "What:", "\n", test_provider + ":",
random_line_split
test_rest_providers_remove.py
""" Test for the remove.py module in the vcontrol/rest/providers directory """ from os import remove as delete_file from web import threadeddict from vcontrol.rest.providers import remove PROVIDERS_FILE_PATH = "../vcontrol/rest/providers/providers.txt" class
(): env = threadeddict() env['HTTP_HOST'] = 'localhost:8080' class WebDummy(): # dummy class to emulate the web.ctx.env call in remove.py ctx = ContextDummy() def test_successful_provider_removal(): """ Here we give the module a text file with PROVIDER: written in it, it should remove th...
ContextDummy
identifier_name
test_rest_providers_remove.py
""" Test for the remove.py module in the vcontrol/rest/providers directory """ from os import remove as delete_file from web import threadeddict from vcontrol.rest.providers import remove PROVIDERS_FILE_PATH = "../vcontrol/rest/providers/providers.txt" class ContextDummy(): env = threadeddict() env['HTTP_HO...
""" Here we give the module a text file without the provider written in it, it should tell us that it couldn't find the provider we gave it as an argument""" remove_provider = remove.RemoveProviderR() remove.web = WebDummy() # override the web variable in remove.py test_provider = "PROV" expec...
identifier_body
macros.rs
// Copyright 2013 The Servo Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution. // // 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 http://opensource.org/licenses/MIT>, at ...
mint::$std_name { $( $field: self.$field, )* } } } } }
#[cfg(feature = "mint")] impl<T, U> Into<mint::$std_name<T>> for $name<T, U> { fn into(self) -> mint::$std_name<T> {
random_line_split
reset.request.controller.js
(function() { 'use strict'; angular .module('fitappApp') .controller('RequestResetController', RequestResetController); RequestResetController.$inject = ['$timeout', 'Auth']; function
($timeout, Auth) { var vm = this; vm.error = null; vm.errorEmailNotExists = null; vm.requestReset = requestReset; vm.resetAccount = {}; vm.success = null; $timeout(function (){angular.element('#email').focus();}); function requestReset () { ...
RequestResetController
identifier_name
reset.request.controller.js
(function() { 'use strict'; angular .module('fitappApp') .controller('RequestResetController', RequestResetController); RequestResetController.$inject = ['$timeout', 'Auth']; function RequestResetController ($timeout, Auth)
})();
{ var vm = this; vm.error = null; vm.errorEmailNotExists = null; vm.requestReset = requestReset; vm.resetAccount = {}; vm.success = null; $timeout(function (){angular.element('#email').focus();}); function requestReset () { vm.error = null;...
identifier_body
reset.request.controller.js
(function() { 'use strict'; angular .module('fitappApp') .controller('RequestResetController', RequestResetController); RequestResetController.$inject = ['$timeout', 'Auth'];
function RequestResetController ($timeout, Auth) { var vm = this; vm.error = null; vm.errorEmailNotExists = null; vm.requestReset = requestReset; vm.resetAccount = {}; vm.success = null; $timeout(function (){angular.element('#email').focus();}); fun...
random_line_split
reset.request.controller.js
(function() { 'use strict'; angular .module('fitappApp') .controller('RequestResetController', RequestResetController); RequestResetController.$inject = ['$timeout', 'Auth']; function RequestResetController ($timeout, Auth) { var vm = this; vm.error = null; vm...
}); } } })();
{ vm.error = 'ERROR'; }
conditional_block
i2c_ds3231.rs
// i2c_ds3231.rs - Sets and retrieves the time on a Maxim Integrated DS3231 // RTC using I2C. use std::error::Error; use std::thread; use std::time::Duration; use rppal::i2c::I2c; // DS3231 I2C default slave address. const ADDR_DS3231: u16 = 0x68;
const REG_SECONDS: usize = 0x00; const REG_MINUTES: usize = 0x01; const REG_HOURS: usize = 0x02; // Helper functions to encode and decode binary-coded decimal (BCD) values. fn bcd2dec(bcd: u8) -> u8 { (((bcd & 0xF0) >> 4) * 10) + (bcd & 0x0F) } fn dec2bcd(dec: u8) -> u8 { ((dec / 10) << 4) | (dec % 10) } fn ...
// DS3231 register addresses.
random_line_split
i2c_ds3231.rs
// i2c_ds3231.rs - Sets and retrieves the time on a Maxim Integrated DS3231 // RTC using I2C. use std::error::Error; use std::thread; use std::time::Duration; use rppal::i2c::I2c; // DS3231 I2C default slave address. const ADDR_DS3231: u16 = 0x68; // DS3231 register addresses. const REG_SECONDS: usize = 0x00; const...
fn dec2bcd(dec: u8) -> u8 { ((dec / 10) << 4) | (dec % 10) } fn main() -> Result<(), Box<dyn Error>> { let mut i2c = I2c::new()?; // Set the I2C slave address to the device we're communicating with. i2c.set_slave_address(ADDR_DS3231)?; // Set the time to 11:59:50 AM. Start at register address 0...
{ (((bcd & 0xF0) >> 4) * 10) + (bcd & 0x0F) }
identifier_body
i2c_ds3231.rs
// i2c_ds3231.rs - Sets and retrieves the time on a Maxim Integrated DS3231 // RTC using I2C. use std::error::Error; use std::thread; use std::time::Duration; use rppal::i2c::I2c; // DS3231 I2C default slave address. const ADDR_DS3231: u16 = 0x68; // DS3231 register addresses. const REG_SECONDS: usize = 0x00; const...
(bcd: u8) -> u8 { (((bcd & 0xF0) >> 4) * 10) + (bcd & 0x0F) } fn dec2bcd(dec: u8) -> u8 { ((dec / 10) << 4) | (dec % 10) } fn main() -> Result<(), Box<dyn Error>> { let mut i2c = I2c::new()?; // Set the I2C slave address to the device we're communicating with. i2c.set_slave_address(ADDR_DS3231)?;...
bcd2dec
identifier_name
i2c_ds3231.rs
// i2c_ds3231.rs - Sets and retrieves the time on a Maxim Integrated DS3231 // RTC using I2C. use std::error::Error; use std::thread; use std::time::Duration; use rppal::i2c::I2c; // DS3231 I2C default slave address. const ADDR_DS3231: u16 = 0x68; // DS3231 register addresses. const REG_SECONDS: usize = 0x00; const...
else { // 24-hour format. println!( "{:0>2}:{:0>2}:{:0>2}", bcd2dec(reg[REG_HOURS] & 0x3F), bcd2dec(reg[REG_MINUTES]), bcd2dec(reg[REG_SECONDS]) ); } thread::sleep(Duration::from_secs(1)); } }
{ // 12-hour format. println!( "{:0>2}:{:0>2}:{:0>2} {}", bcd2dec(reg[REG_HOURS] & 0x1F), bcd2dec(reg[REG_MINUTES]), bcd2dec(reg[REG_SECONDS]), if reg[REG_HOURS] & (1 << 5) > 0 { "PM" ...
conditional_block
check-types.js
/** * Copyright 2019 The AMP HTML Authors. 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 require...
() { const handlerProcess = createCtrlcHandler('check-types'); process.env.NODE_ENV = 'production'; cleanupBuildDir(); maybeInitializeExtensions(); typecheckNewServer(); const srcFiles = [ 'src/amp.js', 'src/amp-shadow.js', 'src/inabox/amp-inabox.js', 'ads/alp/install-alp.js', 'ads/inabo...
checkTypes
identifier_name
check-types.js
/** * Copyright 2019 The AMP HTML Authors. 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 require...
module.exports = { checkTypes, }; /* eslint "google-camelcase/google-camelcase": 0 */ checkTypes.description = 'Check source code for JS type errors'; checkTypes.flags = { closure_concurrency: 'Sets the number of concurrent invocations of closure', debug: 'Outputs the file contents during compilation lifecycl...
{ const handlerProcess = createCtrlcHandler('check-types'); process.env.NODE_ENV = 'production'; cleanupBuildDir(); maybeInitializeExtensions(); typecheckNewServer(); const srcFiles = [ 'src/amp.js', 'src/amp-shadow.js', 'src/inabox/amp-inabox.js', 'ads/alp/install-alp.js', 'ads/inabox/i...
identifier_body
check-types.js
/** * Copyright 2019 The AMP HTML Authors. 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 require...
'src/amp.js', 'src/amp-shadow.js', 'src/inabox/amp-inabox.js', 'ads/alp/install-alp.js', 'ads/inabox/inabox-host.js', 'src/web-worker/web-worker.js', ]; const extensionValues = Object.keys(extensions).map((key) => extensions[key]); const extensionSrcs = extensionValues .filter((ext) =>...
maybeInitializeExtensions(); typecheckNewServer(); const srcFiles = [
random_line_split
setup.py
""" Shopify Trois --------------- Shopify API for Python 3 """ from setuptools import setup setup( name='shopify-trois', version='1.1-dev', url='http://masom.github.io/shopify-trois', license='MIT', author='Martin Samson', author_email='pyrolian@gmail.com', maintainer='Martin Samson', ...
'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development :: Libraries :: Python Modules' ] )
'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent',
random_line_split
dfs.rs
//! `PathExplorer` that works by exploring the CFG in Depth First Order. use std::collections::VecDeque; use libsmt::theories::core; use explorer::explorer::PathExplorer; use engine::rune::RuneControl; use context::context::{Context, Evaluate, RegisterRead}; use context::rune_ctx::RuneContext; #[derive(Clone, Copy,...
} #[derive(Clone, Debug)] struct SavedState<C: Context> { pub ctx: C, pub branch: BranchType, } impl<C: Context> SavedState<C> { fn new(ctx: C, b: BranchType) -> SavedState<C> { SavedState { ctx: ctx, branch: b, } } } /// An explorer that traverses the program ...
random_line_split
dfs.rs
//! `PathExplorer` that works by exploring the CFG in Depth First Order. use std::collections::VecDeque; use libsmt::theories::core; use explorer::explorer::PathExplorer; use engine::rune::RuneControl; use context::context::{Context, Evaluate, RegisterRead}; use context::rune_ctx::RuneContext; #[derive(Clone, Copy,...
else { None } } fn register_branch(&mut self, ctx: &mut Self::Ctx, condition: <Self::Ctx as RegisterRead>::VarRef) -> RuneControl { // When a new branch is encountered, push the false branch into the queue and ...
{ *ctx = state.ctx.clone(); Some(match state.branch { BranchType::True => RuneControl::ExploreTrue, BranchType::False => RuneControl::ExploreFalse, }) }
conditional_block
dfs.rs
//! `PathExplorer` that works by exploring the CFG in Depth First Order. use std::collections::VecDeque; use libsmt::theories::core; use explorer::explorer::PathExplorer; use engine::rune::RuneControl; use context::context::{Context, Evaluate, RegisterRead}; use context::rune_ctx::RuneContext; #[derive(Clone, Copy,...
{ True, False, } #[derive(Clone, Debug)] struct SavedState<C: Context> { pub ctx: C, pub branch: BranchType, } impl<C: Context> SavedState<C> { fn new(ctx: C, b: BranchType) -> SavedState<C> { SavedState { ctx: ctx, branch: b, } } } /// An explorer tha...
BranchType
identifier_name
dfs.rs
//! `PathExplorer` that works by exploring the CFG in Depth First Order. use std::collections::VecDeque; use libsmt::theories::core; use explorer::explorer::PathExplorer; use engine::rune::RuneControl; use context::context::{Context, Evaluate, RegisterRead}; use context::rune_ctx::RuneContext; #[derive(Clone, Copy,...
fn register_branch(&mut self, ctx: &mut Self::Ctx, condition: <Self::Ctx as RegisterRead>::VarRef) -> RuneControl { // When a new branch is encountered, push the false branch into the queue and // explore the // true bran...
{ if let Some(ref state) = self.queue.pop_back() { *ctx = state.ctx.clone(); Some(match state.branch { BranchType::True => RuneControl::ExploreTrue, BranchType::False => RuneControl::ExploreFalse, }) } else { None } ...
identifier_body
decimal.js-tests.ts
/// <reference path="decimal.js.d.ts" /> var x = new Decimal(9) var y = new Decimal(x) Decimal(435.345) new Decimal('5032485723458348569331745.33434346346912144534543') new Decimal('4.321e+4') new Decimal('-735.0918e-430') new Decimal('5.6700000') new Decimal(Infinity) new Decimal(NaN) new Decimal('.5') new Decimal('...
Decimal.random(20) x = Decimal.sqrt('987654321.123456789') y = new Decimal('987654321.123456789').sqrt() x.equals(y)
x.equals(y) Decimal.config({ precision: 10 }) Decimal.random()
random_line_split
chacha.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} impl<'a> SeedableRng<&'a [u32]> for ChaChaRng { fn reseed(&mut self, seed: &'a [u32]) { // reset state self.init(&[0u32, ..KEY_WORDS]); // set key inplace let key = self.state.slice_mut(4, 4+KEY_WORDS); for (k, s) in key.iter_mut().zip(seed.iter()) { *k = *s;...
{ if self.index == STATE_WORDS { self.update(); } let value = self.buffer[self.index % STATE_WORDS]; self.index += 1; value }
identifier_body
chacha.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { // Test vectors 1 and 2 from // http://tools.ietf.org/html/draft-nir-cfrg-chacha20-poly1305-04 let seed : &[_] = &[0u32, ..8]; let mut ra: ChaChaRng = SeedableRng::from_seed(seed); let v = Vec::from_fn(16, |_| ra.next_u32()); assert_eq!(v, vec!(0x...
test_rng_true_values
identifier_name
chacha.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
let value = self.buffer[self.index % STATE_WORDS]; self.index += 1; value } } impl<'a> SeedableRng<&'a [u32]> for ChaChaRng { fn reseed(&mut self, seed: &'a [u32]) { // reset state self.init(&[0u32, ..KEY_WORDS]); // set key inplace let key = self.stat...
{ self.update(); }
conditional_block
chacha.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
/// /// The ChaCha algorithm is widely accepted as suitable for /// cryptographic purposes, but this implementation has not been /// verified as such. Prefer a generator like `OsRng` that defers to /// the operating system for cases that need high security. /// /// [1]: D. J. Bernstein, [*ChaCha, a variant of /// Salsa...
const CHACHA_ROUNDS: uint = 20; // Cryptographically secure from 8 upwards as of this writing /// A random number generator that uses the ChaCha20 algorithm [1].
random_line_split
audio.rs
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait}; use ringbuf::{Producer, RingBuffer}; pub struct AudioPlayer { buffer_producer: Producer<f32>, output_stream: cpal::Stream, } impl AudioPlayer { pub fn new(sample_rate: u32) -> Self { let host = cpal::default_host(); let output_device...
(&self) { self.output_stream.play().unwrap(); } /// Pause the player /// > not used for now, but maybe later #[allow(dead_code)] pub fn pause(&self) { self.output_stream.pause().unwrap(); } pub fn queue(&mut self, data: &[f32]) { self.buffer_producer.push_slice(data...
play
identifier_name
audio.rs
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait}; use ringbuf::{Producer, RingBuffer}; pub struct AudioPlayer { buffer_producer: Producer<f32>, output_stream: cpal::Stream, } impl AudioPlayer { pub fn new(sample_rate: u32) -> Self { let host = cpal::default_host(); let output_device...
.expect("failed to get default output audio device"); let config = cpal::StreamConfig { channels: 2, sample_rate: cpal::SampleRate(sample_rate), buffer_size: cpal::BufferSize::Default, }; // Limiting the number of samples in the buffer is better ...
.default_output_device()
random_line_split
channel_model.js
// // // 'use strict'; var defs = require('./defs'); var when = require('when'), defer = when.defer; var inherits = require('util').inherits; var EventEmitter = require('events').EventEmitter; var BaseChannel = require('./channel').BaseChannel; var acceptMessage = require('./channel').acceptMessage; var Args = requir...
Args.assertExchange(exchange, type, options), defs.ExchangeDeclareOk) .then(function(_ok) { return { exchange: exchange }; }); }; C.checkExchange = function(exchange) { return this.rpc(defs.ExchangeDeclare, Args.checkExchange(exchange), defs...
return this.rpc(defs.ExchangeDeclare,
random_line_split
channel_model.js
// // // 'use strict'; var defs = require('./defs'); var when = require('when'), defer = when.defer; var inherits = require('util').inherits; var EventEmitter = require('events').EventEmitter; var BaseChannel = require('./channel').BaseChannel; var acceptMessage = require('./channel').acceptMessage; var Args = requir...
inherits(Channel, BaseChannel); module.exports.Channel = Channel; CM.createChannel = function() { var c = new Channel(this.connection); return c.open().then(function(openOk) { return c; }); }; var C = Channel.prototype; // An RPC that returns a 'proper' promise, which resolves to just the // response's fields;...
{ BaseChannel.call(this, connection); this.on('delivery', this.handleDelivery.bind(this)); this.on('cancel', this.handleCancel.bind(this)); }
identifier_body
channel_model.js
// // // 'use strict'; var defs = require('./defs'); var when = require('when'), defer = when.defer; var inherits = require('util').inherits; var EventEmitter = require('events').EventEmitter; var BaseChannel = require('./channel').BaseChannel; var acceptMessage = require('./channel').acceptMessage; var Args = requir...
(connection) { if (!(this instanceof ChannelModel)) return new ChannelModel(connection); this.connection = connection; var self = this; ['error', 'close', 'blocked', 'unblocked'].forEach(function(ev) { connection.on(ev, self.emit.bind(self, ev)); }); } inherits(ChannelModel, EventEmitter); module.exp...
ChannelModel
identifier_name
snippet.rs
// # Snippet example // // This example shows how to return a representative snippet of // your hit result. // Snippet are an extracted of a target document, and returned in HTML format. // The keyword searched by the user are highlighted with a `<b>` tag. // --- // Importing tantivy... use tantivy::collector::TopDocs...
highlight(snippet: Snippet) -> String { let mut result = String::new(); let mut start_from = 0; for fragment_range in snippet.highlighted() { result.push_str(&snippet.fragment()[start_from..fragment_range.start]); result.push_str(" --> "); result.push_str(&snippet.fragment()[fragme...
{ // Let's create a temporary directory for the // sake of this example let index_path = TempDir::new()?; // # Defining the schema let mut schema_builder = Schema::builder(); let title = schema_builder.add_text_field("title", TEXT | STORED); let body = schema_builder.add_text_field("body", ...
identifier_body
snippet.rs
// # Snippet example // // This example shows how to return a representative snippet of // your hit result. // Snippet are an extracted of a target document, and returned in HTML format. // The keyword searched by the user are highlighted with a `<b>` tag. // --- // Importing tantivy... use tantivy::collector::TopDocs...
let doc = searcher.doc(doc_address)?; let snippet = snippet_generator.snippet_from_doc(&doc); println!("Document score {}:", score); println!("title: {}", doc.get_first(title).unwrap().text().unwrap()); println!("snippet: {}", snippet.to_html()); println!("custom highligh...
let snippet_generator = SnippetGenerator::create(&searcher, &*query, body)?; for (score, doc_address) in top_docs {
random_line_split
snippet.rs
// # Snippet example // // This example shows how to return a representative snippet of // your hit result. // Snippet are an extracted of a target document, and returned in HTML format. // The keyword searched by the user are highlighted with a `<b>` tag. // --- // Importing tantivy... use tantivy::collector::TopDocs...
() -> tantivy::Result<()> { // Let's create a temporary directory for the // sake of this example let index_path = TempDir::new()?; // # Defining the schema let mut schema_builder = Schema::builder(); let title = schema_builder.add_text_field("title", TEXT | STORED); let body = schema_build...
main
identifier_name
index.ts
import TruffleConfig from "@truffle/config"; const provision = (contractAbstraction: any, truffleConfig: TruffleConfig) => { if (truffleConfig.provider) { contractAbstraction.setProvider(truffleConfig.provider); } if (truffleConfig.network_id) { contractAbstraction.setNetwork(truffleConfig.network_id); ...
}); return contractAbstraction; }; export = provision;
{ const obj: any = {}; obj[key] = truffleConfig[key]; contractAbstraction.defaults(obj); }
conditional_block
index.ts
import TruffleConfig from "@truffle/config"; const provision = (contractAbstraction: any, truffleConfig: TruffleConfig) => { if (truffleConfig.provider) { contractAbstraction.setProvider(truffleConfig.provider); } if (truffleConfig.network_id) { contractAbstraction.setNetwork(truffleConfig.network_id); ...
export = provision;
return contractAbstraction; };
random_line_split
checkbox.js
import React from 'react'; import ReactTable from 'react-table'; import 'react-table/react-table.css'; import Checkbox from 'widgets/checkbox'; export default class CheckboxTable extends React.Component { constructor(props) { super(props); this.visible = []; this.state = { checked: new Set...
(nextProps) { if (nextProps.data !== this.props.data) { this.clearTable(); } } handleCheckboxClick = (evt) => { // adds/removes paths for submission const { name, checked: targetChecked } = evt.target; this.setState((prevState) => { let { checked ...
UNSAFE_componentWillReceiveProps
identifier_name
checkbox.js
import React from 'react'; import ReactTable from 'react-table'; import 'react-table/react-table.css'; import Checkbox from 'widgets/checkbox'; export default class CheckboxTable extends React.Component { constructor(props) { super(props); this.visible = []; this.state = { checked: new Set...
} handleCheckboxClick = (evt) => { // adds/removes paths for submission const { name, checked: targetChecked } = evt.target; this.setState((prevState) => { let { checked } = prevState; checked = new Set(checked); targetChecked ? checked.add(name) : c...
{ this.clearTable(); }
conditional_block
checkbox.js
import React from 'react'; import ReactTable from 'react-table'; import 'react-table/react-table.css'; import Checkbox from 'widgets/checkbox'; export default class CheckboxTable extends React.Component { constructor(props) { super(props); this.visible = []; this.state = { checked: new Set...
targetChecked ? checked.add(name) : checked.delete(name); return { checked }; }); }; handleSelectAll = () => { // user clicked the select all checkbox... // if there are some resources checked already, all are removed // otherwise all visible are checked....
let { checked } = prevState; checked = new Set(checked);
random_line_split
checkbox.js
import React from 'react'; import ReactTable from 'react-table'; import 'react-table/react-table.css'; import Checkbox from 'widgets/checkbox'; export default class CheckboxTable extends React.Component { constructor(props) { super(props); this.visible = []; this.state = { checked: new Set...
render() { return ( <div> {this.renderTable()} {this.renderSubmit()} </div> ); } renderCheckbox = (item) => { const { checked } = this.state; this.visible.length = item.pageSize; this.visible[item.viewIndex] =...
{ // Returns a copy of the checked set with any resource paths that are // not in `this.visible` removed let { checked } = state; return new Set( [...checked].filter((v) => this.visible.indexOf(v) !== -1) ); }
identifier_body
string-utils.js
/** * Useful functions for dealing with strings. * * @module StringUtils */ (function(define) { 'use strict'; define([], function() { var interpolate; /** * Returns a string created by interpolating the provided parameters. * * The text is provided as a tokenized...
return { interpolate: interpolate }; }); }).call( this, // Pick a define function as follows: // 1. Use the default 'define' function if it is available // 2. If not, use 'RequireJS.define' if that is available // 3. else use the GlobalLoader to install the class int...
};
random_line_split
renderer.webgl.js
// req: glMatrix T5.Registry.register('renderer', 'webgl', function(view, panFrame, container, params, baseRenderer) { params = cog.extend({ }, params); /* some shaders */ var DEFAULT_SHADER_FRAGMENT = [ '#ifdef GL_ES', 'precision highp float;', '#endif', ...
tile = tiles[ii]; // calculate the image relative position relX = tile.screenX = tile.x - offsetX; relY = tile.screenY = tile.y - offsetY; // show or hide the image depending on whether it is in the viewport if ((! tile.buffer) && (! ...
relX, relY; for (var ii = tiles.length; ii--; ) {
random_line_split
renderer.webgl.js
// req: glMatrix T5.Registry.register('renderer', 'webgl', function(view, panFrame, container, params, baseRenderer) { params = cog.extend({ }, params); /* some shaders */ var DEFAULT_SHADER_FRAGMENT = [ '#ifdef GL_ES', 'precision highp float;', '#endif', ...
() { gl.uniformMatrix4fv(shaderProgram.pMatrixUniform, false, pMatrix); gl.uniformMatrix4fv(shaderProgram.mvMatrixUniform, false, mvMatrix); } // setMatrixUniforms /* exports */ function applyStyle(styleId) { var nextStyle = T5.Style.get(styleId); if (nextStyle) { ...
setMatrixUniforms
identifier_name
renderer.webgl.js
// req: glMatrix T5.Registry.register('renderer', 'webgl', function(view, panFrame, container, params, baseRenderer) { params = cog.extend({ }, params); /* some shaders */ var DEFAULT_SHADER_FRAGMENT = [ '#ifdef GL_ES', 'precision highp float;', '#endif', ...
} // drawTiles function image(img, x, y, width, height) { } // image function render() { // iterate through the tiles to render and render for (var ii = tilesToRender.length; ii--; ) { var tile = tilesToRender[ii]; // set the tile buffe...
{ tile = tiles[ii]; // calculate the image relative position relX = tile.screenX = tile.x - offsetX; relY = tile.screenY = tile.y - offsetY; // show or hide the image depending on whether it is in the viewport if ((! tile.buffer) && (...
conditional_block
renderer.webgl.js
// req: glMatrix T5.Registry.register('renderer', 'webgl', function(view, panFrame, container, params, baseRenderer) { params = cog.extend({ }, params); /* some shaders */ var DEFAULT_SHADER_FRAGMENT = [ '#ifdef GL_ES', 'precision highp float;', '#endif', ...
function initShaders() { function createShader(type, source) { var shader = gl.createShader(type); gl.shaderSource(shader, source); gl.compileShader(shader); return shader; } // createShader shaderProgram = ...
{ var vertices = [ 1.0, 1.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0 ]; squareVertexTextureBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, squareVertexTextureBuffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices...
identifier_body
same_struct_name_in_different_namespaces.rs
/* automatically generated by rust-bindgen */ #![allow( dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals )] #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct
{ _unused: [u8; 0], } #[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct JS_shadow_Zone { pub x: ::std::os::raw::c_int, pub y: ::std::os::raw::c_int, } #[test] fn bindgen_test_layout_JS_shadow_Zone() { assert_eq!( ::std::mem::size_of::<JS_shadow_Zone>(), 8usize, concat...
JS_Zone
identifier_name
same_struct_name_in_different_namespaces.rs
/* automatically generated by rust-bindgen */ #![allow( dead_code, non_snake_case,
#[repr(C)] #[derive(Debug, Copy, Clone)] pub struct JS_Zone { _unused: [u8; 0], } #[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct JS_shadow_Zone { pub x: ::std::os::raw::c_int, pub y: ::std::os::raw::c_int, } #[test] fn bindgen_test_layout_JS_shadow_Zone() { assert_eq!( ::std::mem:...
non_camel_case_types, non_upper_case_globals )]
random_line_split
preview.py
#!/usr/bin/env python # Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # This helps you preview the apps and extensions docs. # # ./preview.py --help # # There are two modes: server- and render- mode...
exit() print('Starting previewserver on port %s' % opts.port) print('') print('The extension documentation can be found at:') print('') print(' http://localhost:%s/extensions/' % opts.port) print('') print('The apps documentation can be found at:') print('') print(' http://localhost:%s/apps/' ...
print(response.content.ToString())
conditional_block
preview.py
#!/usr/bin/env python # Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # This helps you preview the apps and extensions docs. # # ./preview.py --help # # There are two modes: server- and render- mode...
(BaseHTTPRequestHandler): '''A HTTPRequestHandler that outputs the docs page generated by Handler. ''' def do_GET(self): # Sanitize path to guarantee that it stays within the server. if not posixpath.abspath(self.path.lstrip('/')).startswith( posixpath.abspath('')): retu...
_RequestHandler
identifier_name
preview.py
#!/usr/bin/env python # Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # This helps you preview the apps and extensions docs. # # ./preview.py --help # # There are two modes: server- and render- mode...
if __name__ == '__main__': parser = optparse.OptionParser( description='Runs a server to preview the extension documentation.', usage='usage: %prog [option]...') parser.add_option('-a', '--address', default='127.0.0.1', help='the local interface address to bind the server to') parser.add_optio...
if not posixpath.abspath(self.path.lstrip('/')).startswith( posixpath.abspath('')): return # Rewrite paths that would otherwise be served from app.yaml. self.path = { '/robots.txt': '../../server2/robots.txt', '/favicon.ico': '../../server2/chrome-32.ico', '...
identifier_body
preview.py
#!/usr/bin/env python # Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # This helps you preview the apps and extensions docs. # # ./preview.py --help # # There are two modes: server- and render- mode...
if opts.stat: pr.disable() s = StringIO.StringIO() pstats.Stats(pr, stream=s).sort_stats(opts.stat).print_stats() print(s.getvalue()) elif opts.time: print('Took %s seconds' % (time.time() - start_time)) else: print(response.content.ToString()) exit() print('Start...
for _ in range(extra_iterations): LocalRenderer.Render(path)
random_line_split
scim.component.ts
/* * Copyright (C) 2015 The Gravitee team (http://gravitee.io) * * 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 requi...
styleUrls: ['./scim.component.scss'] }) export class ScimComponent implements OnInit { domainId: string; domain: any = {}; formChanged = false; editMode: boolean; constructor(private domainService: DomainService, private snackbarService: SnackbarService, private authService: Aut...
@Component({ selector: 'app-scim', templateUrl: './scim.component.html',
random_line_split
scim.component.ts
/* * Copyright (C) 2015 The Gravitee team (http://gravitee.io) * * 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 requi...
isSCIMEnabled() { return this.domain.scim && this.domain.scim.enabled; } }
{ this.domain.scim = { 'enabled': (event.checked) }; this.formChanged = true; }
identifier_body
scim.component.ts
/* * Copyright (C) 2015 The Gravitee team (http://gravitee.io) * * 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 requi...
(private domainService: DomainService, private snackbarService: SnackbarService, private authService: AuthService, private route: ActivatedRoute, private router: Router) { } ngOnInit() { this.domain = this.route.snapshot.data['domain']; this.domainId ...
constructor
identifier_name
index.ts
import {Aurelia, LogManager} from "aurelia-framework" import config from './authConfig'; import {ConsoleAppender} from 'aurelia-logging-console'; import {ValidateCustomAttributeViewStrategy} from 'aurelia-validation'; LogManager.addAppender(new ConsoleAppender()); LogManager.setLevel(LogManager.logLevel.info); export...
}) .feature('_resources') .feature('auth', (baseConfig:any)=> { let cfg = baseConfig.configure(config); window.appConfig = cfg; }); aurelia.start().then(a => a.setRoot()); //'app', document.body }
.plugin('aurelia-animator-css') .plugin('toastr') .plugin('charlespockert/aurelia-bs-grid') .plugin('aurelia-validation', (config) => { config.useViewStrategy(ValidateCustomAttributeViewStrategy.TWBootstrapAppendToInput)
random_line_split
index.ts
import {Aurelia, LogManager} from "aurelia-framework" import config from './authConfig'; import {ConsoleAppender} from 'aurelia-logging-console'; import {ValidateCustomAttributeViewStrategy} from 'aurelia-validation'; LogManager.addAppender(new ConsoleAppender()); LogManager.setLevel(LogManager.logLevel.info); export...
{ let _theme:string = 'rdash'; aurelia.use .standardConfiguration() //.developmentLogging() .plugin('aurelia-animator-css') .plugin('toastr') .plugin('charlespockert/aurelia-bs-grid') .plugin('aurelia-validation', (config) => { config.useViewStrategy(ValidateCustomAttributeView...
identifier_body
index.ts
import {Aurelia, LogManager} from "aurelia-framework" import config from './authConfig'; import {ConsoleAppender} from 'aurelia-logging-console'; import {ValidateCustomAttributeViewStrategy} from 'aurelia-validation'; LogManager.addAppender(new ConsoleAppender()); LogManager.setLevel(LogManager.logLevel.info); export...
(aurelia: Aurelia) { let _theme:string = 'rdash'; aurelia.use .standardConfiguration() //.developmentLogging() .plugin('aurelia-animator-css') .plugin('toastr') .plugin('charlespockert/aurelia-bs-grid') .plugin('aurelia-validation', (config) => { config.useViewStrategy(Validate...
configure
identifier_name
async_common.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
elif length == 0: logger.error("Empty frame") self.transport.close() return if len(self.recvd) < length + 4: return frame = self.recvd[0 : 4 + length] self.recvd = self.recvd[4 + length :] self...
logger.error( "Frame size %d too large for THeaderProtocol", length, ) self.transport.close() return
conditional_block
async_common.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
def wrapAsyncioTransport(self, asyncio_transport): raise NotImplementedError def connection_made(self, transport): """Implements asyncio.Protocol.connection_made.""" assert self.transport is None, "Thrift transport already instantiated here." assert self.client is None, "Clien...
exc = TApplicationException( TApplicationException.TIMEOUT, "Call to {} timed out".format(fname) ) serialized_exc = self.serialize_texception(fname, seqid, exc) self._handle_message(serialized_exc, clear_timeout=False)
identifier_body
async_common.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
(self, data): """Implements asyncio.Protocol.data_received.""" self.recvd = self.recvd + data while len(self.recvd) >= 4: (length,) = struct.unpack("!I", self.recvd[:4]) if length > MAX_FRAME_SIZE: logger.error( "Frame size %d too large...
data_received
identifier_name
async_common.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
class ResourceWarning(RuntimeWarning): pass class TReadOnlyBuffer(TTransportBase): """Leaner version of TMemoryBuffer that is resettable.""" def __init__(self, value=b""): self._open = True self._value = value self.reset() def isOpen(self): return self._open ...
class PermissionError(IOError): pass
random_line_split
pages.routing.ts
import { Routes, RouterModule } from '@angular/router'; import { Pages } from './pages.component'; import { ModuleWithProviders } from '@angular/core'; import { AuthGuard } from '../auth/_guards/index'; // noinspection TypeScriptValidateTypes // export function loadChildren(path) { return System.import(path); }; exp...
path: 'pages', component: Pages, children: [ { path: '', redirectTo: 'products', pathMatch: 'full', canActivate: [AuthGuard] }, { path: 'products', loadChildren: './products/products.module#ProductsModule', canActivate: [AuthGuard] }, { path: 'categories', loadChildren: './categories/cate...
{
random_line_split
youtube.service.ts
import {Observable, BehaviorSubject} from 'rxjs/Rx'; import {Injectable} from '@angular/core'; import {Response, Http} from '@angular/http'; import {SearchResult} from '../models/search-result.model'; import {CurrentSearch} from '../models/current-search.model'; const YOUTUBE_API_KEY = 'AIzaSyDOfT_BO81aEZScosfTY...
.replace(/\{radius\}/g, radius.toString()); params.push(location); } const queryUrl: string = `${YOUTUBE_API_URL}?${params.join('&')}`; console.log(queryUrl); this.http.get(queryUrl) .map((response: Response) => { ...
const radius = query.radius ? query.radius : 50; const location = LOCATION_TEMPLATE .replace(/\{latitude\}/g, query.location.latitude.toString()) .replace(/\{longitude\}/g, query.location.longitude.toString())
random_line_split
youtube.service.ts
import {Observable, BehaviorSubject} from 'rxjs/Rx'; import {Injectable} from '@angular/core'; import {Response, Http} from '@angular/http'; import {SearchResult} from '../models/search-result.model'; import {CurrentSearch} from '../models/current-search.model'; const YOUTUBE_API_KEY = 'AIzaSyDOfT_BO81aEZScosfTY...
const queryUrl: string = `${YOUTUBE_API_URL}?${params.join('&')}`; console.log(queryUrl); this.http.get(queryUrl) .map((response: Response) => { console.log(response); return <any>response.json().items.map(item => { ...
{ const radius = query.radius ? query.radius : 50; const location = LOCATION_TEMPLATE .replace(/\{latitude\}/g, query.location.latitude.toString()) .replace(/\{longitude\}/g, query.location.longitude.toString()) .r...
conditional_block
youtube.service.ts
import {Observable, BehaviorSubject} from 'rxjs/Rx'; import {Injectable} from '@angular/core'; import {Response, Http} from '@angular/http'; import {SearchResult} from '../models/search-result.model'; import {CurrentSearch} from '../models/current-search.model'; const YOUTUBE_API_KEY = 'AIzaSyDOfT_BO81aEZScosfTY...
(query: CurrentSearch): Observable<SearchResult[]> { let params = [ `q=${query.name}`, `key=${YOUTUBE_API_KEY}`, `part=snippet`, `type=video`, `maxResults=50` ]; if (query.location) { const radius = query...
search
identifier_name
youtube.service.ts
import {Observable, BehaviorSubject} from 'rxjs/Rx'; import {Injectable} from '@angular/core'; import {Response, Http} from '@angular/http'; import {SearchResult} from '../models/search-result.model'; import {CurrentSearch} from '../models/current-search.model'; const YOUTUBE_API_KEY = 'AIzaSyDOfT_BO81aEZScosfTY...
search(query: CurrentSearch): Observable<SearchResult[]> { let params = [ `q=${query.name}`, `key=${YOUTUBE_API_KEY}`, `part=snippet`, `type=video`, `maxResults=50` ]; if (query.location) { co...
{}
identifier_body
publishtestresults.ts
import tl = require('azure-pipelines-task-lib/task'); import ffl = require('./find-files-legacy'); var testRunner = tl.getInput('testRunner', true); var testResultsFiles = tl.getInput('testResultsFiles', true); var mergeResults = tl.getInput('mergeTestResults'); var platform = tl.getInput('platform'); var config = tl....
else{ let tp = new tl.TestPublisher(testRunner); tp.publish(matchingTestResultsFiles, mergeResults, platform, config, testRunTitle, publishRunAttachments); } tl.setResult(tl.TaskResult.Succeeded, '');
{ tl.warning('No test result files matching ' + testResultsFiles + ' were found.'); }
conditional_block
publishtestresults.ts
import tl = require('azure-pipelines-task-lib/task'); import ffl = require('./find-files-legacy'); var testRunner = tl.getInput('testRunner', true); var testResultsFiles = tl.getInput('testResultsFiles', true); var mergeResults = tl.getInput('mergeTestResults');
tl.debug('testRunner: ' + testRunner); tl.debug('testResultsFiles: ' + testResultsFiles); tl.debug('mergeResults: ' + mergeResults); tl.debug('platform: ' + platform); tl.debug('config: ' + config); tl.debug('testRunTitle: ' + testRunTitle); tl.debug('publishRunAttachments: ' + publishRunAttachments); let matchingTes...
var platform = tl.getInput('platform'); var config = tl.getInput('configuration'); var testRunTitle = tl.getInput('testRunTitle'); var publishRunAttachments = tl.getInput('publishRunAttachments');
random_line_split
api-v3.service.ts
import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { map } from 'rxjs/operators'; import { ILuApiCollectionResponse, ILuApiItem } from '../api.model'; import { ALuApiService } from './api-service.model'; const MAGIC_PAGE_SIZE = 20; ...
protected _orderBy = 'orderBy=name,asc'; set orderBy(orderBy: string) { if (orderBy) { this._orderBy = `orderBy=${orderBy}`; } } get url() { return `${this._api}?${[...this._filters, this._orderBy, this._fields].filter((f) => !!f).join('&')}`; } constructor(protected _http: HttpClient) { super(); }...
{ if (filters) { this._filters = filters || []; } }
identifier_body
api-v3.service.ts
import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { map } from 'rxjs/operators'; import { ILuApiCollectionResponse, ILuApiItem } from '../api.model'; import { ALuApiService } from './api-service.model'; const MAGIC_PAGE_SIZE = 20; ...
(filters: string[]) { if (filters) { this._filters = filters || []; } } protected _orderBy = 'orderBy=name,asc'; set orderBy(orderBy: string) { if (orderBy) { this._orderBy = `orderBy=${orderBy}`; } } get url() { return `${this._api}?${[...this._filters, this._orderBy, this._fields].filter((f) => ...
filters
identifier_name
api-v3.service.ts
import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { map } from 'rxjs/operators'; import { ILuApiCollectionResponse, ILuApiItem } from '../api.model'; import { ALuApiService } from './api-service.model'; const MAGIC_PAGE_SIZE = 20; ...
}
}
random_line_split
api-v3.service.ts
import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { map } from 'rxjs/operators'; import { ILuApiCollectionResponse, ILuApiItem } from '../api.model'; import { ALuApiService } from './api-service.model'; const MAGIC_PAGE_SIZE = 20; ...
} protected _filters: string[] = []; set filters(filters: string[]) { if (filters) { this._filters = filters || []; } } protected _orderBy = 'orderBy=name,asc'; set orderBy(orderBy: string) { if (orderBy) { this._orderBy = `orderBy=${orderBy}`; } } get url() { return `${this._api}?${[...this._...
{ this._fields = `fields=${fields}`; }
conditional_block
main.rs
use std::hash::{Hash, Hasher}; use std::collections::HashSet; #[derive(Debug, Clone, Copy)] struct Foo { elem: usize, } impl PartialEq for Foo { #[inline] fn eq(&self, other: &Self) -> bool { self as *const Self == other as *const Self } } impl Eq for Foo {} impl Hash for Foo { #[inline] fn hash<H: ...
} fn main() { let a = Foo { elem: 5 }; let b = a.clone(); let c = a; let mut set = HashSet::new(); assert!(a != b); assert!(a != c); assert!(b != c); if !set.insert(a) { unreachable!(); } if !set.insert(b) { unreachable!(); } if !set.insert(c) { unreachable!(); } println...
{ (self as *const Self).hash(state); }
identifier_body