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
lib.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/. */ #![crate_name = "devtools_traits"] #![crate_type = "rlib"] #![comment = "The Servo Parallel Browser Project"] #![...
VoidValue, NullValue, BooleanValue(bool), NumberValue(f64), StringValue(String), ActorValue(String), } pub struct AttrInfo { pub namespace: String, pub name: String, pub value: String, } pub struct NodeInfo { pub uniqueId: String, pub baseURI: String, pub parent: String...
random_line_split
lib.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/. */ #![crate_name = "devtools_traits"] #![crate_type = "rlib"] #![comment = "The Servo Parallel Browser Project"] #![...
{ VoidValue, NullValue, BooleanValue(bool), NumberValue(f64), StringValue(String), ActorValue(String), } pub struct AttrInfo { pub namespace: String, pub name: String, pub value: String, } pub struct NodeInfo { pub uniqueId: String, pub baseURI: String, pub parent: Str...
EvaluateJSReply
identifier_name
MRFreeframe.py
import nibabel as nib from nibabel import freesurfer import numpy as np class Region(object): _defaults = ['data', '_name', '_layer', 'hemi', 'header', 'space', 'shape', 'img'] def __init__(self, source): self._source = source for key in self._defaults: if key not in self.__di...
@layer.setter def layer(self, layernum): self._layer = layernum def set_space(self, space_name = 'MNI'): self.space = space_name if space_name == 'MNI': self.shape = (91,109,91) elif space_name == 'fsaverage': self.shape = (163842,1) elif...
def layer(self): return self._layer
random_line_split
MRFreeframe.py
import nibabel as nib from nibabel import freesurfer import numpy as np class Region(object): _defaults = ['data', '_name', '_layer', 'hemi', 'header', 'space', 'shape', 'img'] def __init__(self, source): self._source = source for key in self._defaults: if key not in self.__di...
else: raise Exception('Wrong data formats') self.set_hemi() def calc_distance(self): pass class Morphology(Region): def __init__(self, source): super(Morphology, self).__init__(source) self._data_type() def get_data(self): if self._sourc...
self.coordinate = nib.load(source).darrays[0].data self.face = nib.load(source).darrays[1].data
conditional_block
MRFreeframe.py
import nibabel as nib from nibabel import freesurfer import numpy as np class Region(object): _defaults = ['data', '_name', '_layer', 'hemi', 'header', 'space', 'shape', 'img'] def __init__(self, source): self._source = source for key in self._defaults: if key not in self.__di...
def get_size(self): self.size = [] if self.data is not None: for i in range(self.data.shape[-1]): self.size.append(self.data[...,i][self.data[...,i]!=0].shape[0]) return self.size class Geometry(Region): def __init__(self): super(Geometry, self).__i...
if ('lh' in self._source) & ('rh' in self._source): self.hemi = 'both' elif ('lh' in self._source) & ('rh' not in self._source): self.hemi = 'lh' elif ('lh' not in self._source) & ('rh' in self._source): self.hemi = 'rh' else: self.hemi = hemi
identifier_body
MRFreeframe.py
import nibabel as nib from nibabel import freesurfer import numpy as np class Region(object): _defaults = ['data', '_name', '_layer', 'hemi', 'header', 'space', 'shape', 'img'] def __init__(self, source): self._source = source for key in self._defaults: if key not in self.__di...
(self): self.size = [] if self.data is not None: for i in range(self.data.shape[-1]): self.size.append(self.data[...,i][self.data[...,i]!=0].shape[0]) return self.size class Geometry(Region): def __init__(self): super(Geometry, self).__init__() ...
get_size
identifier_name
confirm_dialog.js
// 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. cr.define('options', function() { /** @const */ var SettingsDialog = options.SettingsDialog; /** * A dialog that will pop up when the user att...
(name, title, pageDivName, okButton, cancelButton, pref, metric, confirmed_pref) { SettingsDialog.call(this, name, title, pageDivName, okButton, cancelButton); this.pref = pref; this.metric = metric; this.confirmed_pref = confirmed_pref; this.confirmed_ = false; } Confi...
ConfirmDialog
identifier_name
confirm_dialog.js
// 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. cr.define('options', function() { /** @const */ var SettingsDialog = options.SettingsDialog; /** * A dialog that will pop up when the user att...
/** * Handle changes to |confirmed_pref| by caching them. * @param {Event} event Change event. * @private */ onConfirmedChanged_: function(event) { this.confirmed_ = event.value.value; }, /** @override */ initializePage: function() { SettingsDialog.prototype.initial...
OptionsPage.showPageByName(this.name, false); else Preferences.getInstance().commitPref(this.pref, this.metric); },
random_line_split
confirm_dialog.js
// 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. cr.define('options', function() { /** @const */ var SettingsDialog = options.SettingsDialog; /** * A dialog that will pop up when the user att...
}, /** * Handle the confirm button by committing the |pref| change. If * |confirmed_pref| has been specified, also remember that the dialog has * been confirmed to avoid bringing it up in the future. * @override */ handleConfirm: function() { SettingsDialog.prototype.handleC...
{ Preferences.getInstance().addEventListener( this.confirmed_pref, this.onConfirmedChanged_.bind(this)); }
conditional_block
confirm_dialog.js
// 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. cr.define('options', function() { /** @const */ var SettingsDialog = options.SettingsDialog; /** * A dialog that will pop up when the user att...
ConfirmDialog.prototype = { // Set up the prototype chain __proto__: SettingsDialog.prototype, /** * Handle changes to |pref|. Only uncommitted changes are relevant as these * originate from user and need to be explicitly committed to take effect. * Pop up the dialog or commit the change...
{ SettingsDialog.call(this, name, title, pageDivName, okButton, cancelButton); this.pref = pref; this.metric = metric; this.confirmed_pref = confirmed_pref; this.confirmed_ = false; }
identifier_body
nfs2.rs
/* Copyright (C) 2017-2020 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY...
nfs_status = stat; } SCLogDebug!("NFSv2: REPLY {} to procedure {} blob size {}", r.hdr.xid, xidmap.procedure, r.prog_data.len()); self.mark_response_tx_done(r.hdr.xid, r.reply_state, nfs_status, &resp_handle); } }
{ let mut nfs_status = 0; let resp_handle = Vec::new(); if xidmap.procedure == NFSPROC3_READ { match parse_nfs2_reply_read(r.prog_data) { Ok((_, ref reply)) => { SCLogDebug!("NFSv2: READ reply record"); self.process_read_record...
identifier_body
nfs2.rs
/* Copyright (C) 2017-2020 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY...
<'b>(&mut self, r: &RpcPacket<'b>) { SCLogDebug!("NFSv2: REQUEST {} procedure {} ({}) blob size {}", r.hdr.xid, r.procedure, self.requestmap.len(), r.prog_data.len()); let mut xidmap = NFSRequestXidMap::new(r.progver, r.procedure, 0); let aux_file_name = Vec::new(); if ...
process_request_record_v2
identifier_name
nfs2.rs
/* Copyright (C) 2017-2020 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY...
, }; } if !(r.procedure == NFSPROC3_COMMIT || // commit handled separately r.procedure == NFSPROC3_WRITE || // write handled in file tx r.procedure == NFSPROC3_READ) // read handled in file tx at reply { let mut tx = self.new_tx(); ...
{ self.set_event(NFSEvent::MalformedData); }
conditional_block
nfs2.rs
/* Copyright (C) 2017-2020 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY...
use crate::nfs::types::*; use crate::nfs::rpc_records::*; use crate::nfs::nfs2_records::*; use nom::IResult; use nom::number::streaming::be_u32; impl NFSState { /// complete request record pub fn process_request_record_v2<'b>(&mut self, r: &RpcPacket<'b>) { SCLogDebug!("NFSv2: REQUEST {} procedure {} ...
use crate::log::*; use crate::nfs::nfs::*;
random_line_split
LegacyPagination.tsx
import { useState } from 'react' import { useDispatch } from 'react-redux' import styled from 'styled-components' import { Button, themeSpacing } from '@amsterdam/asc-ui' import type { FunctionComponent } from 'react' import { setPage } from '../../../shared/ducks/data-selection/actions' import First from '../../../sha...
} if (numberOfPages && currentPage > numberOfPages) { dispatch(setPage(1)) } return showPagination ? ( <div className="c-data-selection-pagination"> <div className="c-data-selection-pagination__separator" /> <div className="c-data-selection-pagination__controls"> <div className="...
{ dispatch(setPage(currentPage)) }
conditional_block
LegacyPagination.tsx
import { useState } from 'react' import { useDispatch } from 'react-redux' import styled from 'styled-components' import { Button, themeSpacing } from '@amsterdam/asc-ui'
import type { FunctionComponent } from 'react' import { setPage } from '../../../shared/ducks/data-selection/actions' import First from '../../../shared/assets/icons/first.svg' import Previous from '../../../shared/assets/icons/previous.svg' import Next from '../../../shared/assets/icons/next.svg' import Last from '../...
random_line_split
divisible_by_power_of_2.rs
use integer::Integer; use malachite_base::num::arithmetic::traits::DivisibleByPowerOf2; impl<'a> DivisibleByPowerOf2 for &'a Integer { /// Returns whether `self` is divisible by 2<sup>`pow`</sup>. If `self` is 0, the result is /// always true; otherwise, it is equivalent to `self.trailing_zeros().unwrap() <= p...
}
{ self.abs.divisible_by_power_of_2(pow) }
identifier_body
divisible_by_power_of_2.rs
use integer::Integer; use malachite_base::num::arithmetic::traits::DivisibleByPowerOf2; impl<'a> DivisibleByPowerOf2 for &'a Integer { /// Returns whether `self` is divisible by 2<sup>`pow`</sup>. If `self` is 0, the result is /// always true; otherwise, it is equivalent to `self.trailing_zeros().unwrap() <= p...
/// ``` /// extern crate malachite_base; /// extern crate malachite_nz; /// /// use malachite_base::num::arithmetic::traits::DivisibleByPowerOf2; /// use malachite_base::num::basic::traits::Zero; /// use malachite_nz::integer::Integer; /// /// assert_eq!(Integer::ZERO.divisible_by_po...
/// /// where n = `self.significant_bits` /// /// # Examples
random_line_split
divisible_by_power_of_2.rs
use integer::Integer; use malachite_base::num::arithmetic::traits::DivisibleByPowerOf2; impl<'a> DivisibleByPowerOf2 for &'a Integer { /// Returns whether `self` is divisible by 2<sup>`pow`</sup>. If `self` is 0, the result is /// always true; otherwise, it is equivalent to `self.trailing_zeros().unwrap() <= p...
(self, pow: u64) -> bool { self.abs.divisible_by_power_of_2(pow) } }
divisible_by_power_of_2
identifier_name
utils.js
/* * Generic utils. */ // Language-Level var Level = { success: 2, info: 1, debug: 0, warning: -1, error: -2, fatal: -3 }; function Result(level, msg, data) { if (_.isNumber(level)) this.level = level; else if (_.isString(level)) { var parsedLevel = Number(level); if (_.isNumber(parsedL...
// UI-Level ----------------------------------------------------------------- END
{ if (event && func && event.keyCode === 13) func(); }
identifier_body
utils.js
/* * Generic utils. */ // Language-Level var Level = { success: 2, info: 1, debug: 0, warning: -1, error: -2, fatal: -3 };
function Result(level, msg, data) { if (_.isNumber(level)) this.level = level; else if (_.isString(level)) { var parsedLevel = Number(level); if (_.isNumber(parsedLevel) && !_.isNaN(parsedLevel)) this.level = parsedLevel; else { level = level.toLowerCase(); if (level == "success") ...
random_line_split
utils.js
/* * Generic utils. */ // Language-Level var Level = { success: 2, info: 1, debug: 0, warning: -1, error: -2, fatal: -3 }; function Result(level, msg, data) { if (_.isNumber(level)) this.level = level; else if (_.isString(level)) { var parsedLevel = Number(level); if (_.isNumber(parsedL...
(id) { return document.getElementById(id); } var entityMap = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': '&quot;', "'": '&#39;', "/": '&#x2F;' }; function escapeHtml(text) { return String(text).replace(/[&<>"'\/]/g, function (s) { return entityMap[s]; }); } function onEnter(event, func)...
get
identifier_name
kendo.culture.ms.js
/* * Kendo UI v2014.3.1119 (http://www.telerik.com/kendo-ui) * Copyright 2014 Telerik AD. All rights reserved. * * Kendo UI commercial licenses may be obtained at * http://www.telerik.com/purchase/license-agreement/kendo-ui-complete * If you do not own a commercial license, this file shall be governed by the trial lice...
standard: { days: { names: ["Ahad","Isnin","Selasa","Rabu","Khamis","Jumaat","Sabtu"], namesAbbr: ["Ahad","Isnin","Sel","Rabu","Khamis","Jumaat","Sabtu"], namesShort: ["A","I","S","R","K","J","S"] }, ...
random_line_split
DropdownSchema.ts
import { FieldSchema } from '@ephox/boulder'; import { Fun, Optional } from '@ephox/katamari'; import { Coupling } from '../../api/behaviour/Coupling'; import { Focusing } from '../../api/behaviour/Focusing'; import { Keying } from '../../api/behaviour/Keying'; import { Toggling } from '../../api/behaviour/Toggling'; ...
schema: [ Fields.tieredMenuMarkers() ], name: 'menu', defaults: (detail) => { return { onExecute: detail.onExecute }; } }), InternalSink.partType() ]); const name = Fun.constant('Dropdown'); export { name, schema, parts };
SketcherFields.sandboxFields() )); const parts: () => PartType.PartTypeAdt[] = Fun.constant([ PartType.external<DropdownDetail, DropdownSpec>({
random_line_split
feature_representation.rs
// // This file is part of zero_sum. // // zero_sum is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // zero_sum is distributed in...
// 1 - Black reserve flatstones features.push(state.p2_flatstones as f32 / 21.0); // 1 - Empty board spaces let mut stacks = state.board.iter().flat_map(|column| column.iter()).enumerate().map(|(i, stack)| (stack, (i / 5) as f32 / 4.0, (i % 5) as f32 / 4.0)).collect::<Vec<_>>(); features.push(stack...
// 1 - White reserve flatstones features.push(state.p1_flatstones as f32 / 21.0);
random_line_split
feature_representation.rs
// // This file is part of zero_sum. // // zero_sum is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // zero_sum is distributed in...
for level in (0..len - 1).rev() { let carry = bitmap & accumulator[level]; accumulator[level] ^= carry; accumulator[level + 1] |= carry; bitmap ^= carry; } accumulator[0] |= bitmap; } let own_blocks = blocks & own_pieces; let mut s...
{ accumulator[len - 1] ^= carry; accumulator.push(carry); bitmap ^= carry; }
conditional_block
feature_representation.rs
// // This file is part of zero_sum. // // zero_sum is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // zero_sum is distributed in...
(mut bitmap: Bitmap) -> (f32, f32) { if bitmap == 0 { return (0.0, 0.0); } let mut x = 0; while bitmap & EDGE[5][Direction::West as usize] == 0 { bitmap <<= 1; x += 1; } let mut y = 0; while bitmap & EDGE[5][Direction::South as usize] == 0 { bitmap >>= 5; ...
get_position
identifier_name
feature_representation.rs
// // This file is part of zero_sum. // // zero_sum is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // zero_sum is distributed in...
accumulator[0] |= bitmap; } let own_blocks = blocks & own_pieces; let mut stack_levels = Vec::new(); add_bitmap(&mut stack_levels, own_blocks); for &level in own_stacks { add_bitmap(&mut stack_levels, level & own_pieces); } let add_influence = |influence: &mut Vec<Bitmap...
{ if accumulator.is_empty() { accumulator.push(bitmap); return; } let len = accumulator.len(); let carry = bitmap & accumulator[len - 1]; if carry != 0 { accumulator[len - 1] ^= carry; accumulator.push(carry); bitmap ^=...
identifier_body
mod.rs
pub mod handlers; pub mod middleware; pub mod requests; pub mod responses; pub mod tokens; use crate::api::requests::brand_requests::{EditBrandRequest, NewBrandRequest}; use actix_web::HttpRequest; use actix_web::{error, web, FromRequest, HttpResponse}; use handlers::catalog::brand_handlers; use handlers::{account_han...
.route(web::post().to(brand_handlers::post_new_brand)) ) .service( web::resource("/{brand}") .app_data(web::Json::<EditBrandRequest>::configure(|cfg| { cfg.error_handler(json_error_handler...
{ #[rustfmt::skip] cfg.service( web::scope("/api/v1") .service( web::resource("/authenticate") .route(web::post().to(account_handlers::authenticate)) ) .service( web::resource("/health_check") .ro...
identifier_body
mod.rs
pub mod handlers; pub mod middleware; pub mod requests; pub mod responses; pub mod tokens; use crate::api::requests::brand_requests::{EditBrandRequest, NewBrandRequest}; use actix_web::HttpRequest; use actix_web::{error, web, FromRequest, HttpResponse}; use handlers::catalog::brand_handlers; use handlers::{account_han...
})) .route(web::get().to(brand_handlers::get_brand)) .route(web::put().to(brand_handlers::edit_brand)) ) ) ); } fn json_error_handler(err: error::JsonPayloadError, _req: &HttpRequest) -> error::Error { use actix...
cfg.error_handler(json_error_handler)
random_line_split
mod.rs
pub mod handlers; pub mod middleware; pub mod requests; pub mod responses; pub mod tokens; use crate::api::requests::brand_requests::{EditBrandRequest, NewBrandRequest}; use actix_web::HttpRequest; use actix_web::{error, web, FromRequest, HttpResponse}; use handlers::catalog::brand_handlers; use handlers::{account_han...
(err: error::JsonPayloadError, _req: &HttpRequest) -> error::Error { use actix_web::error::JsonPayloadError; let detail = err.to_string(); let resp = match &err { JsonPayloadError::ContentType => HttpResponse::UnsupportedMediaType().body(detail), JsonPayloadError::Deserialize(json_err) if j...
json_error_handler
identifier_name
LoLS.rs
pub fn length_of_longest_substring(s: String) -> i32 { let mut temp_cache = vec![]; let mut to_bytes = s.bytes(); let mut result: i32 = 0; while let Some(b) = to_bytes.next() { if temp_cache.contains(&b) { if temp_cache.len() as i32 >= result { result = temp_cache.len...
() { dbg!(length_of_longest_substring(String::from("abcabcb"))); //=> 3 dbg!(length_of_longest_substring(String::from("bbb"))); //=> 1 dbg!(length_of_longest_substring(String::from("pwwkew"))); //=> 3 dbg!(length_of_longest_substring(String::from("dvdf"))); //=> 3 }
main
identifier_name
LoLS.rs
pub fn length_of_longest_substring(s: String) -> i32 { let mut temp_cache = vec![]; let mut to_bytes = s.bytes(); let mut result: i32 = 0; while let Some(b) = to_bytes.next() { if temp_cache.contains(&b) { if temp_cache.len() as i32 >= result { result = temp_cache.len...
fn main() { dbg!(length_of_longest_substring(String::from("abcabcb"))); //=> 3 dbg!(length_of_longest_substring(String::from("bbb"))); //=> 1 dbg!(length_of_longest_substring(String::from("pwwkew"))); //=> 3 dbg!(length_of_longest_substring(String::from("dvdf"))); //=> 3 }
} else { result } }
random_line_split
LoLS.rs
pub fn length_of_longest_substring(s: String) -> i32 { let mut temp_cache = vec![]; let mut to_bytes = s.bytes(); let mut result: i32 = 0; while let Some(b) = to_bytes.next() { if temp_cache.contains(&b) { if temp_cache.len() as i32 >= result { result = temp_cache.len...
} if temp_cache.len() as i32 > result { temp_cache.len() as i32 } else { result } } fn main() { dbg!(length_of_longest_substring(String::from("abcabcb"))); //=> 3 dbg!(length_of_longest_substring(String::from("bbb"))); //=> 1 dbg!(length_of_longest_substring(String::from("p...
{ temp_cache.push(b); }
conditional_block
LoLS.rs
pub fn length_of_longest_substring(s: String) -> i32
} } fn main() { dbg!(length_of_longest_substring(String::from("abcabcb"))); //=> 3 dbg!(length_of_longest_substring(String::from("bbb"))); //=> 1 dbg!(length_of_longest_substring(String::from("pwwkew"))); //=> 3 dbg!(length_of_longest_substring(String::from("dvdf"))); //=> 3 }
{ let mut temp_cache = vec![]; let mut to_bytes = s.bytes(); let mut result: i32 = 0; while let Some(b) = to_bytes.next() { if temp_cache.contains(&b) { if temp_cache.len() as i32 >= result { result = temp_cache.len() as i32 } let index = temp_...
identifier_body
package.py
############################################################################## # Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-64...
(Package): """Simple package which acts as a build dependency""" homepage = "http://www.example.com" url = "http://www.example.com/dtbuild2-1.0.tar.gz" version('1.0', '0123456789abcdef0123456789abcdef') def install(self, spec, prefix): pass
Dtbuild2
identifier_name
package.py
############################################################################## # Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-64...
"""Simple package which acts as a build dependency""" homepage = "http://www.example.com" url = "http://www.example.com/dtbuild2-1.0.tar.gz" version('1.0', '0123456789abcdef0123456789abcdef') def install(self, spec, prefix): pass
identifier_body
package.py
############################################################################## # Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. #
# # For details, see https://github.com/llnl/spack # Please also see the NOTICE and LICENSE files for our notice and the LGPL. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License (as # published by the Free Software Foundation) version 2...
# This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-647188
random_line_split
tests.py
#!/usr/bin/env python # Licensed to Cloudera, Inc. under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. Cloudera, Inc. licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you ma...
(TestAboutBase, OozieBase): def test_admin_wizard_permissions(self): response = self.client_admin.get(reverse('about:index')) assert_true('Check Configuration' in response.content, response.content) response = self.client.get(reverse('about:index')) assert_false('Check Configuration' in response.con...
TestAbout
identifier_name
tests.py
#!/usr/bin/env python # Licensed to Cloudera, Inc. under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. Cloudera, Inc. licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you ma...
from desktop.lib.django_test_util import make_logged_in_client from desktop.lib.test_utils import grant_access from desktop.models import Settings from oozie.tests import OozieBase class TestAboutBase(object): def setUp(self): self.client = make_logged_in_client(username="about", is_superuser=False) grant_...
random_line_split
tests.py
#!/usr/bin/env python # Licensed to Cloudera, Inc. under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. Cloudera, Inc. licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you ma...
def test_collect_usage(self): collect_usage = Settings.get_settings().collect_usage try: response = self.client.post(reverse('about:update_preferences'), {'collect_usage': False}) data = json.loads(response.content) assert_equal(data['status'], 0) assert_false(data['collect_usage'] ...
self.client_admin.get(reverse('about:index'), HTTP_ACCEPT_LANGUAGE='fr-fr')
identifier_body
widgets.py
# -*- coding: utf-8 -*- from django.forms import widgets from django.template.loader import render_to_string from django.utils.translation import gettext_lazy as _ from .conf import settings class PlacesWidget(widgets.MultiWidget): template_name = 'places/widgets/places.html' def __init__(self, attrs=None)...
def decompress(self, value): if isinstance(value, str): return value.rsplit(',') if value: return [value.place, value.latitude, value.longitude] return [None, None] def get_context(self, name, value, attrs): context = super(PlacesWidget, self).get_conte...
_widgets = ( widgets.TextInput( attrs={'data-geo': 'formatted_address', 'data-id': 'map_place'} ), widgets.TextInput( attrs={ 'data-geo': 'lat', 'data-id': 'map_latitude', 'placeholder': _('La...
identifier_body
widgets.py
# -*- coding: utf-8 -*- from django.forms import widgets from django.template.loader import render_to_string from django.utils.translation import gettext_lazy as _ from .conf import settings class PlacesWidget(widgets.MultiWidget): template_name = 'places/widgets/places.html' def __init__(self, attrs=None)...
if value: return [value.place, value.latitude, value.longitude] return [None, None] def get_context(self, name, value, attrs): context = super(PlacesWidget, self).get_context(name, value, attrs) context['map_widget_height'] = settings.MAP_WIDGET_HEIGHT context['...
return value.rsplit(',')
conditional_block
widgets.py
# -*- coding: utf-8 -*- from django.forms import widgets from django.template.loader import render_to_string from django.utils.translation import gettext_lazy as _ from .conf import settings class PlacesWidget(widgets.MultiWidget): template_name = 'places/widgets/places.html' def
(self, attrs=None): _widgets = ( widgets.TextInput( attrs={'data-geo': 'formatted_address', 'data-id': 'map_place'} ), widgets.TextInput( attrs={ 'data-geo': 'lat', 'data-id': 'map_latitude', ...
__init__
identifier_name
widgets.py
# -*- coding: utf-8 -*- from django.forms import widgets from django.template.loader import render_to_string from django.utils.translation import gettext_lazy as _ from .conf import settings class PlacesWidget(widgets.MultiWidget): template_name = 'places/widgets/places.html' def __init__(self, attrs=None)...
'placeholder': _('Latitude'), } ), widgets.TextInput( attrs={ 'data-geo': 'lng', 'data-id': 'map_longitude', 'placeholder': _('Longitude'), } ), ) ...
random_line_split
generate-poll.component.ts
import { Component } from '@angular/core'; import { Router } from '@angular/router'; import { AuthService } from '../../services/auth.service'; import { FetchPollsService } from '../../services/fetch-polls.service'; import { FlashMessagesService } from 'angular2-flash-messages'; import 'rxjs/add/operator/map'; @Compon...
}; // Iterate over optionsArr and initalize unique property to 0. this.optionsArr.forEach(option => { pollData['poll']['votes'][option] = 0; }); // Use service to register a new poll to the collection. Show success/error // as flash messages. this.fetchService.registerPoll(pollData)....
{ // Split up the textarea input by line break and store it. this.optionsArr = this.options.split('\n'); // Generate a unique key. this.dbKey = this.genKey(); // Get user from localStorage. const data = this.authService.getUser(); // Create the object to store as a document. const pol...
identifier_body
generate-poll.component.ts
import { Component } from '@angular/core'; import { Router } from '@angular/router'; import { AuthService } from '../../services/auth.service'; import { FetchPollsService } from '../../services/fetch-polls.service'; import { FlashMessagesService } from 'angular2-flash-messages'; import 'rxjs/add/operator/map'; @Compon...
if (i % 5 === 0) { key += letters[Math.floor(Math.random() * 10)].toUpperCase(); } key += letters[Math.floor(Math.random() * 10)]; } return key; } }
{ key += nums[Math.floor(Math.random() * 10)]; }
conditional_block
generate-poll.component.ts
import { Component } from '@angular/core'; import { Router } from '@angular/router'; import { AuthService } from '../../services/auth.service'; import { FetchPollsService } from '../../services/fetch-polls.service'; import { FlashMessagesService } from 'angular2-flash-messages'; import 'rxjs/add/operator/map'; @Compon...
() { const letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']; const nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; let key = ''; for (let i = 0; i < 25; i++) { if (i % 2 === 0) { ...
genKey
identifier_name
generate-poll.component.ts
import { Component } from '@angular/core'; import { Router } from '@angular/router'; import { AuthService } from '../../services/auth.service'; import { FetchPollsService } from '../../services/fetch-polls.service'; import { FlashMessagesService } from 'angular2-flash-messages'; import 'rxjs/add/operator/map'; @Compon...
}
key += letters[Math.floor(Math.random() * 10)]; } return key; }
random_line_split
action_dlcontent.py
""" Downloads bootloader content for all arches for when the user doesn't want to supply their own. Copyright 2009, Red Hat, Inc Michael DeHaan <mdehaan@redhat.com> This program 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 Softwa...
return True
src = f[0] dst = f[1] if os.path.exists(dst) and not force: self.logger.info("path %s already exists, not overwriting existing content, use --force if you wish to update" % dst) continue self.logger.info("downloading %s to %s" % (src,dst)) urlgrabber.url...
conditional_block
action_dlcontent.py
""" Downloads bootloader content for all arches for when the user doesn't want to supply their own. Copyright 2009, Red Hat, Inc Michael DeHaan <mdehaan@redhat.com> This program 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 Softwa...
) self.logger.info("downloading content required to netboot all arches") for f in files: src = f[0] dst = f[1] if os.path.exists(dst) and not force: self.logger.info("path %s already exists, not overwriting existing content, use --force if you wish to upd...
""" Download bootloader content for all of the latest bootloaders, since the user has chosen to not supply their own. You may ask "why not get this from yum", though Fedora has no IA64 repo, for instance, and we also want this to be able to work on Debian and further do not want folks to ha...
identifier_body
action_dlcontent.py
""" Downloads bootloader content for all arches for when the user doesn't want to supply their own. Copyright 2009, Red Hat, Inc Michael DeHaan <mdehaan@redhat.com> This program 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 Softwa...
content_server = "http://mdehaan.fedorapeople.org/loaders" dest = "/var/lib/cobbler/loaders" files = ( ( "%s/README" % content_server, "%s/README" % dest ), ( "%s/COPYING.elilo" % content_server, "%s/COPYING.elilo" % dest ), ( "%s/COPYING.yaboot" % content_server, "%s...
Fedora has no IA64 repo, for instance, and we also want this to be able to work on Debian and further do not want folks to have to install a cross compiler. For those that don't like this approach they can still source their cross-arch bootloader content manually. """
random_line_split
action_dlcontent.py
""" Downloads bootloader content for all arches for when the user doesn't want to supply their own. Copyright 2009, Red Hat, Inc Michael DeHaan <mdehaan@redhat.com> This program 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 Softwa...
: def __init__(self,config,logger=None): """ Constructor """ self.config = config self.settings = config.settings() if logger is None: logger = clogger.Logger() self.logger = logger def run(self,force=False): """ Download bo...
ContentDownloader
identifier_name
gcp.py
######## # Copyright (c) 2014-2020 Cloudify Platform Ltd. 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 ...
return creds_func(self.auth, scopes=scope) def get_common_instance_metadata(self): """ Get project's common instance metadata. :return: CommonInstanceMetadata list extracted from REST response get project metadata. """ self.logger.info( 'Get co...
creds_func = ServiceAccountCredentials.from_json_keyfile_name
conditional_block
gcp.py
######## # Copyright (c) 2014-2020 Cloudify Platform Ltd. All rights reserved #
# You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the...
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License.
random_line_split
gcp.py
######## # Copyright (c) 2014-2020 Cloudify Platform Ltd. 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 ...
def get_credentials(self, scope): # Crypto.Random.atfork() must be called here because celery doesn't do # it atfork() if hasattr(self.auth, 'get'): creds_func = ServiceAccountCredentials.from_json_keyfile_dict else: creds_func = ServiceAccountCreden...
""" GoogleCloudPlatform class constructor. Create API discovery object that will be making GCP REST API calls. :param config: dictionary with project properties: path to auth file, project and zone :param logger: logger object that the class methods will be logging to :p...
identifier_body
gcp.py
######## # Copyright (c) 2014-2020 Cloudify Platform Ltd. 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 ...
(self): """ Lazily load the discovery so we don't make API calls during __init__ """ if hasattr(self, '_discovery'): return self._discovery self._discovery = self.create_discovery(self.__discovery, self.scope, self.api_v...
discovery
identifier_name
test_0211.py
import unittest import utils class WordDictionary: def __init__(self): """ Initialize your data structure here. """ self.root = {} def addWord(self, word: str) -> None:
def search(self, word: str) -> bool: def search(curr, start): for i in range(start, len(word)): ch = word[i] if ch == '.': for k, v in curr.items(): if k != '#' and search(v, i + 1): return...
curr = self.root for ch in word: child = curr.get(ch) if not child: curr[ch] = child = {} curr = child curr['#'] = True
identifier_body
test_0211.py
import unittest import utils class WordDictionary: def __init__(self): """ Initialize your data structure here. """ self.root = {} def addWord(self, word: str) -> None: curr = self.root for ch in word: child = curr.get(ch) if not chil...
curr = child return curr.get('#', False) return search(self.root, 0) class Test(unittest.TestCase): def test(self): utils.test_invocations(self, __file__, WordDictionary) if __name__ == '__main__': unittest.main()
random_line_split
test_0211.py
import unittest import utils class WordDictionary: def
(self): """ Initialize your data structure here. """ self.root = {} def addWord(self, word: str) -> None: curr = self.root for ch in word: child = curr.get(ch) if not child: curr[ch] = child = {} curr = child ...
__init__
identifier_name
test_0211.py
import unittest import utils class WordDictionary: def __init__(self): """ Initialize your data structure here. """ self.root = {} def addWord(self, word: str) -> None: curr = self.root for ch in word:
curr['#'] = True def search(self, word: str) -> bool: def search(curr, start): for i in range(start, len(word)): ch = word[i] if ch == '.': for k, v in curr.items(): if k != '#' and search(v, i + 1): ...
child = curr.get(ch) if not child: curr[ch] = child = {} curr = child
conditional_block
diff_html.py
# -*- coding: iso-8859-1 -*- """ MoinMoin - Side by side diffs @copyright: 2002 Juergen Hermann <jh@web.de>, 2002 Scott Moonen <smoonen@andstuff.org> @license: GNU GPL, see COPYING for details. """ from MoinMoin.support import difflib from MoinMoin.wikiutil import escape def i...
#return "%d / %d / %s" % (len(line), len(stripped), line) return eol + line # This code originally by Scott Moonen, used with permission. def diff(request, old, new, old_top='', new_top='', old_bottom='', new_bottom='', old_top_class='', new_top_class='', old_bottom_class='', new_bottom_class=''): ...
line = "&nbsp;" * (len(line) - len(stripped)) + stripped
conditional_block
diff_html.py
# -*- coding: iso-8859-1 -*- """ MoinMoin - Side by side diffs @copyright: 2002 Juergen Hermann <jh@web.de>, 2002 Scott Moonen <smoonen@andstuff.org> @license: GNU GPL, see COPYING for details. """ from MoinMoin.support import difflib from MoinMoin.wikiutil import escape def i...
# This code originally by Scott Moonen, used with permission. def diff(request, old, new, old_top='', new_top='', old_bottom='', new_bottom='', old_top_class='', new_top_class='', old_bottom_class='', new_bottom_class=''): """ Find changes between old and new and return HTML markup visualising them...
eol = '' while line and line[0] == '\n': eol += '\n' line = line[1:] stripped = line.lstrip() if len(line) - len(stripped): line = "&nbsp;" * (len(line) - len(stripped)) + stripped #return "%d / %d / %s" % (len(line), len(stripped), line) return eol + line
identifier_body
diff_html.py
# -*- coding: iso-8859-1 -*- """ MoinMoin - Side by side diffs @copyright: 2002 Juergen Hermann <jh@web.de>, 2002 Scott Moonen <smoonen@andstuff.org> @license: GNU GPL, see COPYING for details. """ from MoinMoin.support import difflib from MoinMoin.wikiutil import escape def
(line): eol = '' while line and line[0] == '\n': eol += '\n' line = line[1:] stripped = line.lstrip() if len(line) - len(stripped): line = "&nbsp;" * (len(line) - len(stripped)) + stripped #return "%d / %d / %s" % (len(line), len(stripped), line) return eol + lin...
indent
identifier_name
diff_html.py
# -*- coding: iso-8859-1 -*- """ MoinMoin - Side by side diffs @copyright: 2002 Juergen Hermann <jh@web.de>, 2002 Scott Moonen <smoonen@andstuff.org> @license: GNU GPL, see COPYING for details. """ from MoinMoin.support import difflib from MoinMoin.wikiutil import escape def i...
lastmatch = (match[0] + match[2], match[1] + match[2]) if old_bottom or new_bottom: result += '<tr><td class="%s">%s</td><td class="%s">%s</td></tr>' % (old_top_class, old_top, new_top_class, new_top) result += '</table>\n' return result
</tr> """ % (leftpane, rightpane)
random_line_split
message.rs
}; use {OutputSegments, Result, Word}; /// Options controlling how data is read. #[derive(Clone, Copy)] pub struct ReaderOptions { /// Limits how many total words of data are allowed to be traversed. Traversal is counted when /// a new struct or list builder is obtained, e.g. from a get() accessor. This means...
fn get_root_internal(&self) -> Result<any_pointer::Reader> { unsafe { let segment : *const SegmentReader = &self.arena.segment0; let pointer_reader = try!(layout::PointerReader::get_root( segment, (*segment).get_start_ptr(), self.options.nesting_limit)); ...
{ let boxed_segments = Box::new(segments); let boxed_segments_ref = { let r :&S = &*boxed_segments; unsafe { ::std::mem::transmute(r as &ReaderSegments) } }; let arena = ReaderArena::new(boxed_segments_ref, options); Reader { arena: arena, segments: boxed_...
identifier_body
message.rs
}; use {OutputSegments, Result, Word}; /// Options controlling how data is read. #[derive(Clone, Copy)] pub struct ReaderOptions { /// Limits how many total words of data are allowed to be traversed. Traversal is counted when /// a new struct or list builder is obtained, e.g. from a get() accessor. This means...
pub fn init_root<'a, T : FromPointerBuilder<'a>>(&'a mut self) -> T { self.get_root_internal().init_as() } /// Gets the root, interpreting it as the given type. pub fn get_root<'a, T : FromPointerBuilder<'a>>(&'a mut self) -> Result<T> { self.get_root_internal().get_as() } /// ...
} /// Initializes the root as a value of the given type.
random_line_split
message.rs
{ pub fn new(segments: &'a [&'a [Word]]) -> SegmentArray<'a> { SegmentArray { segments: segments } } } impl <'b> ReaderSegments for SegmentArray<'b> { fn get_segment<'a>(&'a self, id: u32) -> Option<&'a [Word]> { self.segments.get(id as usize).map(|slice| *slice) } } /// A container u...
{ self.scratch_space.in_use = true; (self.scratch_space.slice.as_mut_ptr(), self.scratch_space.slice.len() as u32) }
conditional_block
message.rs
a problem in practice. pub nesting_limit : i32, } pub const DEFAULT_READER_OPTIONS : ReaderOptions = ReaderOptions { traversal_limit_in_words : 8 * 1024 * 1024, nesting_limit : 64 }; impl ReaderOptions { pub fn new() -> ReaderOptions { DEFAULT_READER_OPTIONS } pub fn nesting_limit<'a>(&'a mut self, ...
new
identifier_name
client-pool.d.ts
import AsyncStreamEmitter = require('async-stream-emitter'); import { AGClientSocket } from 'socketcluster-client'; import { Secret } from 'jsonwebtoken'; import AGChannel = require('ag-channel'); import ConsumableStream = require('consumable-stream'); import Hasher = require('./hasher'); interface ClientPoolOptions ...
extends AsyncStreamEmitter<any> { hasher: Hasher; clientCount: number; targetURI: string; authKey?: Secret | undefined; clients: AGClientSocket[]; constructor(options?: ClientPoolOptions); emit(eventName: 'error', data: { error: Error }): void; emit(eventName: 'subscribe', data: Clien...
ClientPool
identifier_name
client-pool.d.ts
import AsyncStreamEmitter = require('async-stream-emitter'); import { AGClientSocket } from 'socketcluster-client'; import { Secret } from 'jsonwebtoken'; import AGChannel = require('ag-channel'); import ConsumableStream = require('consumable-stream'); import Hasher = require('./hasher'); interface ClientPoolOptions ...
invokePublish(channelName: string, data: any): Promise<void>; subscriptions(includePending?: boolean): string[]; subscribe(channelName: string, options?: AGClientSocket.SubscribeOptions): AGChannel<any>; unsubscribe(channelName: string): Promise<void>; isSubscribed(channelName: string, includePen...
breakDownURI(uri: string): BrokenDownURI; selectClient(key: string): AGClientSocket;
random_line_split
imagelike.py
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 FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import renpy.display from renpy.disp...
draw(left, -right, -bottom, 0) if right: draw(-right, 0, -bottom, 0) def sw_render(self, crend, dw, dh, left, top, right, bottom): source = crend.render_to_texture(True) sw, sh = source.get_size() dest = renpy.display.swdraw.surface...
draw(0, left, -bottom, 0)
conditional_block
imagelike.py
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 FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import renpy.display from renpy.disp...
(x0, x1, y0, y1): # Compute the coordinates of the left, right, top, and # bottom sides of the region, for both the source and # destination surfaces. # left side. if x0 >= 0: dx0 = x0 sx0 = x0 else: ...
draw
identifier_name
imagelike.py
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 FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import renpy.display from renpy.disp...
newcr = Render(cdw, cdh) newcr.clipping = True for x in xrange(0, cdw, csw): for y in xrange(0, cdh, csh): newcr.blit(cr, (x, y)) cr = newcr ...
# Scale or tile if we have to. if csw != cdw or csh != cdh: if self.tile:
random_line_split
imagelike.py
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 FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import renpy.display from renpy.disp...
def render(self, width, height, st, at): color = self.color or self.style.color rv = Render(width, height) if color is None or width <= 0 or height <= 0: return rv SIZE = 10 if width < SIZE or height < SIZE: tex = renpy.display.d...
return [ ]
identifier_body
unreachable-code.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} } pub fn main() {}
{}
conditional_block
unreachable-code.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
pub fn main() {}
} }
random_line_split
unreachable-code.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(x: bool) -> bool { x } fn call_id() { let c = panic!(); id(c); } fn call_id_2() { id(true) && id(return); } fn call_id_3() { id(return) && id(return); } fn ret_guard() { match 2 { x if (return) => { x; } _ => {} } } pub fn main() {}
id
identifier_name
unreachable-code.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
fn ret_guard() { match 2 { x if (return) => { x; } _ => {} } } pub fn main() {}
{ id(return) && id(return); }
identifier_body
use-plans.tsx
import { useLocale } from '@automattic/i18n-utils'; import { useDispatch, useSelect } from '@wordpress/data'; import { useContext, useState, useEffect } from 'react'; import LaunchContext from '../context'; import { PLANS_STORE, SITE_STORE } from '../stores'; import { isPlanProduct } from '../utils'; import type { Plan...
defaultFreePlan, defaultPaidPlan, defaultFreePlanProduct, defaultPaidPlanProduct, }; }, [ billingPeriod, locale ] ); } export function usePlanProductFromCart(): PlanProductForFlow | undefined { const { siteId } = useContext( LaunchContext ); const { getCart } = useDispatch( SITE_STORE ); co...
billingPeriod ); return {
random_line_split
use-plans.tsx
import { useLocale } from '@automattic/i18n-utils'; import { useDispatch, useSelect } from '@wordpress/data'; import { useContext, useState, useEffect } from 'react'; import LaunchContext from '../context'; import { PLANS_STORE, SITE_STORE } from '../stores'; import { isPlanProduct } from '../utils'; import type { Plan...
(): number | undefined { const planProductFromCart = usePlanProductFromCart(); const planProductId = planProductFromCart?.product_id; return planProductId; }
usePlanProductIdFromCart
identifier_name
use-plans.tsx
import { useLocale } from '@automattic/i18n-utils'; import { useDispatch, useSelect } from '@wordpress/data'; import { useContext, useState, useEffect } from 'react'; import LaunchContext from '../context'; import { PLANS_STORE, SITE_STORE } from '../stores'; import { isPlanProduct } from '../utils'; import type { Plan...
defaultPaidPlan, defaultFreePlanProduct, defaultPaidPlanProduct, }; }, [ billingPeriod, locale ] ); } export function usePlanProductFromCart(): PlanProductForFlow | undefined { const { siteId } = useContext( LaunchContext ); const { getCart } = useDispatch( SITE_STORE ); const [ planProductFro...
{ const locale = useLocale(); return useSelect( ( select ) => { const plansStore = select( PLANS_STORE ); const defaultFreePlan = plansStore.getDefaultFreePlan( locale ); const defaultPaidPlan = plansStore.getDefaultPaidPlan( locale ); const defaultPaidPlanProduct = plansStore.getPlanProduct( defa...
identifier_body
decorator.py
#!-*- coding:utf-8 -*- import time def retries(times=3, timeout=1): """对未捕获异常进行重试""" def decorator(func): def _wrapper(*args, **kw): att, retry = 0, 0 while retry < times: retry += 1 try: return func(*args, **kw) ...
ret = func(*args, **kw) if ret: return ret att += timeout time.sleep(att) return _wrapper return decorator def use_logging(level): """带参数的装饰器""" def decorator(func): print func.__name__ def wrapper(...
att, retry = 0, 0 while retry < times: retry += 1
random_line_split
decorator.py
#!-*- coding:utf-8 -*- import time def retries(times=3, timeout=1): """对未捕获异常进行重试""" def decorator(func): def _wrapper(*args, **kw): att, retry = 0, 0 while retry < times: retry += 1 try: return func(*args, **kw) ...
kw): att, retry = 0, 0 while retry < times: retry += 1 ret = func(*args, **kw) if ret: return ret att += timeout time.sleep(att) return _wrapper return decorator def use_logging(leve...
*args, **
identifier_name
decorator.py
#!-*- coding:utf-8 -*- import time def retries(times=3, timeout=1): """对未捕获异常进行重试""" def decorator(func): def _wrapper(*args, **kw): att, retry = 0, 0 while retry < times: retry += 1 try: return func(*args, **kw) ...
rint ("level:%s, %s is running" % (level, func.__name__)) return func(*args, **kwargs) return wrapper return decorator if __name__ == "__main__": @use_logging(level="warn") def foo(name='foo'): print("i am %s" % name) foo()
me__)) elif level == "info": p
conditional_block
decorator.py
#!-*- coding:utf-8 -*- import time def retries(times=3, timeout=1): """对未捕获异常进行重试""" def decorator(func): def _wrapper(*args, **kw): att, retry = 0, 0 while retry < times: retry += 1 try: return func(*args, **kw) ...
corator def use_logging(level): """带参数的装饰器""" def decorator(func): print func.__name__ def wrapper(*args, **kwargs): if level == "warn": print ("level:%s, %s is running" % (level, func.__name__)) elif level == "info": print ("level:%s, %s...
try < times: retry += 1 ret = func(*args, **kw) if ret: return ret att += timeout time.sleep(att) return _wrapper return de
identifier_body
can_activate_spec.ts
import {verifyNoBrowserErrors} from 'angular2/src/testing/e2e_util'; import {Promise} from 'angular2/src/facade/async'; function
(selector) { var EC = (<any>protractor).ExpectedConditions; // Waits for the element with id 'abc' to be present on the dom. browser.wait(EC.presenceOf($(selector)), 20000); } describe('reuse example app', function() { afterEach(verifyNoBrowserErrors); var URL = 'angular2/examples/router/ts/can_activate/';...
waitForElement
identifier_name
can_activate_spec.ts
import {verifyNoBrowserErrors} from 'angular2/src/testing/e2e_util'; import {Promise} from 'angular2/src/facade/async'; function waitForElement(selector)
describe('reuse example app', function() { afterEach(verifyNoBrowserErrors); var URL = 'angular2/examples/router/ts/can_activate/'; it('should navigate to user 1', function() { browser.get(URL); waitForElement('home-cmp'); element(by.css('#user-1-link')).click(); waitForElement('control-pane...
{ var EC = (<any>protractor).ExpectedConditions; // Waits for the element with id 'abc' to be present on the dom. browser.wait(EC.presenceOf($(selector)), 20000); }
identifier_body
can_activate_spec.ts
import {verifyNoBrowserErrors} from 'angular2/src/testing/e2e_util'; import {Promise} from 'angular2/src/facade/async'; function waitForElement(selector) { var EC = (<any>protractor).ExpectedConditions; // Waits for the element with id 'abc' to be present on the dom. browser.wait(EC.presenceOf($(selector)), 2000...
expect(element(by.css('control-panel-cmp')).getText()).toContain('Settings'); }); it('should not navigate to user 2', function() { browser.get(URL); waitForElement('home-cmp'); element(by.css('#user-2-link')).click(); waitForElement('home-cmp'); expect(element(by.css('home-cmp')).getText...
random_line_split
setup.py
#!/usr/bin/python3 import os import requests import sys structure_template = 'src/{}/kotlin/solutions/day{}' solver_template = """ package solutions.{package} import solutions.Solver class {clazz}: Solver {{ override fun solve(input: List<String>, partTwo: Boolean): String {{ TODO("not implemented") ...
with open(input_file, 'wb') as f: for chunk in res.iter_content(chunk_size=128): f.write(chunk) if __name__ == '__main__': if len(sys.argv) != 3: print("Usage: setup.py token day") exit(1) token = sys.argv[1] day = sys.argv[2] day_int = -1 try: day...
res = requests.get(url, cookies={'session': token}) input_file = '{}/input'.format(folder)
random_line_split
setup.py
#!/usr/bin/python3 import os import requests import sys structure_template = 'src/{}/kotlin/solutions/day{}' solver_template = """ package solutions.{package} import solutions.Solver class {clazz}: Solver {{ override fun solve(input: List<String>, partTwo: Boolean): String {{ TODO("not implemented") ...
(day, kind, template): day_as_string = str(day).zfill(2) clazz = 'Day{}'.format(day) package = 'day{}'.format(day_as_string) folder = structure_template.format(kind, day_as_string) os.makedirs(folder) suffix = '' if kind == 'test': suffix = 'Test' path = "{}/{}.{}".format(folder...
generate_files
identifier_name
setup.py
#!/usr/bin/python3 import os import requests import sys structure_template = 'src/{}/kotlin/solutions/day{}' solver_template = """ package solutions.{package} import solutions.Solver class {clazz}: Solver {{ override fun solve(input: List<String>, partTwo: Boolean): String {{ TODO("not implemented") ...
def fetch_input(day, token, folder): url = 'https://adventofcode.com/2017/day/{}/input'.format(day) res = requests.get(url, cookies={'session': token}) input_file = '{}/input'.format(folder) with open(input_file, 'wb') as f: for chunk in res.iter_content(chunk_size=128): f.write(c...
day_as_string = str(day).zfill(2) clazz = 'Day{}'.format(day) package = 'day{}'.format(day_as_string) folder = structure_template.format(kind, day_as_string) os.makedirs(folder) suffix = '' if kind == 'test': suffix = 'Test' path = "{}/{}.{}".format(folder, clazz+suffix, 'kt') c...
identifier_body
setup.py
#!/usr/bin/python3 import os import requests import sys structure_template = 'src/{}/kotlin/solutions/day{}' solver_template = """ package solutions.{package} import solutions.Solver class {clazz}: Solver {{ override fun solve(input: List<String>, partTwo: Boolean): String {{ TODO("not implemented") ...
if len(sys.argv) != 3: print("Usage: setup.py token day") exit(1) token = sys.argv[1] day = sys.argv[2] day_int = -1 try: day_int = int(day) except ValueError: print("Could not parse day as number: [{}]".format(day)) exit(1) folder = generate_files(day_...
conditional_block
statistical_mapping.py
, 0) # Thresholding if height_control == 'fpr': zth = sp_stats.norm.isf(height_th) elif height_control == 'fdr': zth = empirical_pvalue.gaussian_fdr_threshold(zmap, height_th) elif height_control == 'bonferroni': zth = sp_stats.norm.isf(height_th / nvoxels) else: ## Brute-fo...
# FDR-corrected p-values fdr_pvalue = empirical_pvalue.gaussian_fdr(zmap)[above_th] # Default "nulls" if not 'zmax' in nulls: nulls['zmax'] = 'bonferroni' if not 'smax' in nulls: nulls['smax'] = None if not 's' in nulls: nulls['s'] = None # Report significance level...
clusters.sort(key=lambda c : c['size'], reverse=True)
random_line_split
statistical_mapping.py
, 0) # Thresholding if height_control == 'fpr': zth = sp_stats.norm.isf(height_th) elif height_control == 'fdr': zth = empirical_pvalue.gaussian_fdr_threshold(zmap, height_th) elif height_control == 'bonferroni': zth = sp_stats.norm.isf(height_th / nvoxels) else: ## Brute-fo...
def twosample_test(data_images, vardata_images, mask_images, labels, stat_id, permutations=0, cluster_forming_th=0.01): """ Helper function for permutation-based mass univariate twosample group analysis. Labels is a binary vector (1-2). Regions more active for group 1 than group 2 ...
cluster_def = (ptest.height_threshold(cluster_forming_th), None) # Calibration voxel_res, cluster_res, region_res = \ ptest.calibrate(nperms=permutations, clusters=[cluster_def]) nulls = {} nulls['zmax'] = ptest.zscore(voxel_res['perm_maxT_values']) nulls['s'] = clus...
conditional_block
statistical_mapping.py
(p, n): return np.minimum(1., p * n) def simulated_pvalue(t, simu_t): return 1 - np.searchsorted(simu_t, t) / float(np.size(simu_t)) def cluster_stats(zimg, mask, height_th, height_control='fpr', cluster_th=0, nulls={}): """ Return a list of clusters, each cluster being represented...
bonferroni
identifier_name
statistical_mapping.py
0]) == 0: return None, None ## FIXME zmap_th = zmap[above_th] xyz_th = xyz[above_th] # Clustering ## Extract local maxima and connex components above some threshold ff = field_from_graph_and_data(wgraph_from_3d_grid(xyz_th, k=18), zmap_th) maxima, depth = ff.get_local_maxima(th=zth) ...
""" Helper function for permutation-based mass univariate twosample group analysis. Labels is a binary vector (1-2). Regions more active for group 1 than group 2 are inferred. """ # Prepare arrays data, vardata, xyz, mask = prepare_arrays(data_images, vardata_images, ...
identifier_body
test_linux_ip_addr.rs
extern crate linux_ip; // use std::io::prelude::*; #[cfg(test)] mod tests { use std::fs::File; use std::io::Read; use std::path::Path; fn ip_addr_show() -> String
#[test] fn test_me() { let ip_addr = ::linux_ip::addr::parse_from_string(&ip_addr_show()); assert_eq!(26, ip_addr.length()); assert_eq!("br995", ip_addr.find("br995").unwrap().name); assert_eq!(vec!["10.10.95.11/22", "10.10.95.12/22", "fe80::d227:88ff:fed1:16d/64"], ...
{ let mut f = File::open(Path::new("tests/ip_addr.out")).unwrap(); let mut s = String::new(); f.read_to_string(&mut s).ok(); return s; }
identifier_body
test_linux_ip_addr.rs
extern crate linux_ip; // use std::io::prelude::*; #[cfg(test)] mod tests { use std::fs::File; use std::io::Read; use std::path::Path; fn ip_addr_show() -> String { let mut f = File::open(Path::new("tests/ip_addr.out")).unwrap(); let mut s = String::new(); f.read_to_string(&m...
() { let mut ip_addr = ::linux_ip::addr::IpAddr { interfaces: Vec::new() }; let idx = ip_addr.add_interface(&"eth0".to_string()); ip_addr.interfaces[idx].add_ip("47.11.1.1/26".to_string()); assert!(ip_addr.as_commands("del") .iter() .find(|s| *s == "ip addr del 47...
test_from_scratch
identifier_name
test_linux_ip_addr.rs
extern crate linux_ip; // use std::io::prelude::*; #[cfg(test)] mod tests { use std::fs::File; use std::io::Read; use std::path::Path; fn ip_addr_show() -> String { let mut f = File::open(Path::new("tests/ip_addr.out")).unwrap(); let mut s = String::new(); f.read_to_string(&mu...
assert!(ip_addr.as_commands("del") .iter() .find(|s| *s == "ip addr del 10.1.0.11/16 dev br110") .is_some()); } #[test] fn test_from_scratch() { let mut ip_addr = ::linux_ip::addr::IpAddr { interfaces: Vec::new() }; let idx = ip_addr.add_interface(...
assert!(ip_addr.as_commands("add") .iter() .find(|s| *s == "ip addr add fe80::d227:88ff:fed1:16d/64 dev p1p1.402") .is_some());
random_line_split