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
Concurrent.rs
extern crate sync; use sync::{Arc, Mutex}; fn
() { // let mut numbers = ~[1, 2, 3, 4]; // let (tx, rx) = channel (); // numbers[0] = 4; // tx.send(numbers); // spawn (proc () { // let mut numbers = rx.recv (); // println! ("{}", numbers[0]); // numbers[0] = 5; // println! ("{}", numbers[0]); // tx.send(numbers); // }) // let n...
main
identifier_name
icons.py
""" Various kinds of icon widgets. """ from __future__ import absolute_import from ...properties import Bool, Float, Enum from ...enums import NamedIcon from ..widget import Widget class
(Widget): """ An abstract base class for icon widgets. ``AbstractIcon`` is not generally useful to instantiate on its own. """ class Icon(AbstractIcon): """ A "stock" icon based on FontAwesome. """ name = Enum(NamedIcon, help=""" What icon to use. See http://fortawesome.github.io/Font-Aw...
AbstractIcon
identifier_name
icons.py
""" Various kinds of icon widgets. """
from ..widget import Widget class AbstractIcon(Widget): """ An abstract base class for icon widgets. ``AbstractIcon`` is not generally useful to instantiate on its own. """ class Icon(AbstractIcon): """ A "stock" icon based on FontAwesome. """ name = Enum(NamedIcon, help=""" What icon t...
from __future__ import absolute_import from ...properties import Bool, Float, Enum from ...enums import NamedIcon
random_line_split
icons.py
""" Various kinds of icon widgets. """ from __future__ import absolute_import from ...properties import Bool, Float, Enum from ...enums import NamedIcon from ..widget import Widget class AbstractIcon(Widget):
class Icon(AbstractIcon): """ A "stock" icon based on FontAwesome. """ name = Enum(NamedIcon, help=""" What icon to use. See http://fortawesome.github.io/Font-Awesome/icons/ for the list of available icons. """) size = Float(None, help=""" The size multiplier (1x, 2x, ..., 5x). ...
""" An abstract base class for icon widgets. ``AbstractIcon`` is not generally useful to instantiate on its own. """
identifier_body
cksum.rs
#![crate_name = "uu_cksum"] /* * This file is part of the uutils coreutils package. * * (c) Michael Gehring <mg@ebfe.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #[macro_use] extern crate uucore; use std::fs::File; use s...
() -> [u8; 1024 * 1024] { unsafe { mem::uninitialized() } } #[inline] fn cksum(fname: &str) -> io::Result<(u32, usize)> { let mut crc = 0u32; let mut size = 0usize; let file; let mut rd: Box<Read> = match fname { "-" => Box::new(stdin()), _ => { file = try!(File::open(&...
init_byte_array
identifier_name
cksum.rs
#![crate_name = "uu_cksum"] /* * This file is part of the uutils coreutils package. * * (c) Michael Gehring <mg@ebfe.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #[macro_use] extern crate uucore; use std::fs::File; use s...
#[cfg(not(windows))] fn init_byte_array() -> [u8; 1024 * 1024] { unsafe { mem::uninitialized() } } #[inline] fn cksum(fname: &str) -> io::Result<(u32, usize)> { let mut crc = 0u32; let mut size = 0usize; let file; let mut rd: Box<Read> = match fname { "-" => Box::new(stdin()), _ ...
{ vec![0; 1024 * 1024] }
identifier_body
cksum.rs
#![crate_name = "uu_cksum"] /* * This file is part of the uutils coreutils package. * * (c) Michael Gehring <mg@ebfe.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #[macro_use] extern crate uucore; use std::fs::File; use s...
let mut rd: Box<Read> = match fname { "-" => Box::new(stdin()), _ => { file = try!(File::open(&Path::new(fname))); Box::new(BufReader::new(file)) } }; let mut bytes = init_byte_array(); loop { match rd.read(&mut bytes) { Ok(num_bytes) ...
let file;
random_line_split
traversal.rs
we defer initial styling of XBL subtrees until // frame construction, which does an explicit traversal of the unstyled // children after shuffling the subtree. That explicit traversal may in // turn find other bound elements, which get handled in the same way. // // We explicitl...
{ note_children::<E, D, F>( context, element, data, propagated_hint, data.restyle.reconstructed_self_or_ancestor(), note_child ); }
conditional_block
traversal.rs
mut node: E::ConcreteNode, children_to_process: isize ) { // If the postorder step is a no-op, don't bother. if !Self::needs_postorder_traversal() { return; } if children_to_process == 0 { // We are a leaf. Walk up the chain. loop ...
root: OpaqueNode,
random_line_split
traversal.rs
.traversal_parent(); let parent_data = parent.as_ref().and_then(|p| p.borrow_data()); let should_traverse = Self::element_needs_traversal( root, flags, data.map(|d| &*d), parent_data.as_ref().map(|d| &**d) ); PreTraverseToken(should_traver...
// To avoid wasting work, we defer initial styling of XBL subtrees until // frame construction, which does an explicit traversal of the unstyled // children after shuffling the subtree. That explicit traversal may in // turn find other bound elements, which get handled in the same way. ...
{ debug_assert!(cfg!(feature = "gecko") || parent.has_current_styles_for_traversal(parent_data, context.shared.traversal_flags)); // If the parent computed display:none, we don't style the subtree. if parent_data.styles.is_display_none() { debug!("Parent {:?} i...
identifier_body
traversal.rs
( root: E, shared_context: &SharedStyleContext, traversal_flags: TraversalFlags ) -> PreTraverseToken { // If this is an unstyled-only traversal, the caller has already verified // that there's something to traverse, and we don't need to do any // invalidation since w...
pre_traverse
identifier_name
16853_H1.rs
13E-001 0.200 2.8676498E-001 1.4930499E-001 1.3740356E-001 1.2805711E-001 1.1609120E-001 1.1030254E-001 0.220 2.6867819E-001 1.8119521E-001 1.6100505E-001 1.4197567E-001 1.1538588E-001 1.1160781E-001 0.240 3.5831174E-001 1.6528116E-001 1.5364350E-001 1.3919891E-001 1.1542684E-001 1.1361472E-001 0.260 3.6949748E-001...
0.650 2.1797280E-001 1.8877083E-001 1.7303199E-001 1.5523672E-001 1.1628085E-001 9.2407720E-002 0.700 1.4387584E-001 2.1101710E-001 1.7496218E-001 1.4056417E-001 1.0735576E-001 8.4936020E-002 0.750 2.1221133E-001 1.6501458E-001 1.4778031E-001 1.3065909E-001 9.7020360E-002 7.7791750E-002 0.800 2.4024567E-001 1.3
0.550 2.2443265E-001 2.0542115E-001 1.7928344E-001 1.5216398E-001 1.2084850E-001 1.0293319E-001 0.600 3.2437012E-001 2.1653445E-001 1.8949097E-001 1.6210338E-001 1.2160170E-001 9.8512280E-002
random_line_split
fibonacci.py
def _checkInput(index): if index < 0:
elif type(index) != int: raise TypeError("Inserire un intero [tipo input {}]".format(type(index).__name__)) def fib_from_string(index): _checkInput(index) serie = "0 1 1 2 3 5 8".replace(" ", "") return int(serie[index]) def fib_from_list(index): _checkInput(index) serie = [0,1,1,2,3,...
raise ValueError("Indice negativo non supportato [{}]".format(index))
conditional_block
fibonacci.py
def _checkInput(index):
def fib_from_string(index): _checkInput(index) serie = "0 1 1 2 3 5 8".replace(" ", "") return int(serie[index]) def fib_from_list(index): _checkInput(index) serie = [0,1,1,2,3,5,8] return serie[index] def fib_from_algo(index): _checkInput(index) current_number = current_index = 0 ...
if index < 0: raise ValueError("Indice negativo non supportato [{}]".format(index)) elif type(index) != int: raise TypeError("Inserire un intero [tipo input {}]".format(type(index).__name__))
identifier_body
fibonacci.py
def _checkInput(index):
elif type(index) != int: raise TypeError("Inserire un intero [tipo input {}]".format(type(index).__name__)) def fib_from_string(index): _checkInput(index) serie = "0 1 1 2 3 5 8".replace(" ", "") return int(serie[index]) def fib_from_list(index): _checkInput(index) serie = [0,1,1,2,3,5...
if index < 0: raise ValueError("Indice negativo non supportato [{}]".format(index))
random_line_split
fibonacci.py
def
(index): if index < 0: raise ValueError("Indice negativo non supportato [{}]".format(index)) elif type(index) != int: raise TypeError("Inserire un intero [tipo input {}]".format(type(index).__name__)) def fib_from_string(index): _checkInput(index) serie = "0 1 1 2 3 5 8".replace(" ", ""...
_checkInput
identifier_name
Gruntfile.js
// Generated on 2014-12-14 using generator-chrome-extension 0.2.11 'use strict'; // # Globbing // for performance reasons we're only matching one level down: // 'test/spec/{,*/}*.js' // use this if you want to recursively match all subfolders: // 'test/spec/**/*.js' module.exports = function (grunt) { // Load grun...
'jshint', 'test', 'build' ]); };
random_line_split
wl_buffer.rs
// Copyright 2014 Jonathan Eyolfson use libc::{c_int, c_void, uint32_t}; use raw; use raw::types::listeners; use raw::types::objects; pub const WL_BUFFER_DESTROY: uint32_t = 0; #[inline(always)] pub unsafe fn wl_buffer_add_listener( wl_buffer: *mut objects::wl_buffer, listener: *const listeners::wl_buffer_l...
( wl_buffer: *mut objects::wl_buffer, user_data: *mut c_void ) { raw::wl_proxy_set_user_data( wl_buffer as *mut objects::wl_proxy, user_data ) } #[inline(always)] pub unsafe fn wl_buffer_get_user_data( wl_buffer: *mut objects::wl_buffer ) -> *mut c_void { raw::wl_proxy_get_user_...
wl_buffer_set_user_data
identifier_name
wl_buffer.rs
// Copyright 2014 Jonathan Eyolfson use libc::{c_int, c_void, uint32_t}; use raw; use raw::types::listeners; use raw::types::objects; pub const WL_BUFFER_DESTROY: uint32_t = 0; #[inline(always)] pub unsafe fn wl_buffer_add_listener( wl_buffer: *mut objects::wl_buffer, listener: *const listeners::wl_buffer_l...
listener as *mut extern fn(), data ) } #[inline(always)] pub unsafe fn wl_buffer_set_user_data( wl_buffer: *mut objects::wl_buffer, user_data: *mut c_void ) { raw::wl_proxy_set_user_data( wl_buffer as *mut objects::wl_proxy, user_data ) } #[inline(always)] pub unsaf...
wl_buffer as *mut objects::wl_proxy,
random_line_split
wl_buffer.rs
// Copyright 2014 Jonathan Eyolfson use libc::{c_int, c_void, uint32_t}; use raw; use raw::types::listeners; use raw::types::objects; pub const WL_BUFFER_DESTROY: uint32_t = 0; #[inline(always)] pub unsafe fn wl_buffer_add_listener( wl_buffer: *mut objects::wl_buffer, listener: *const listeners::wl_buffer_l...
{ raw::wl_proxy_marshal( wl_buffer as *mut objects::wl_proxy, WL_BUFFER_DESTROY ); raw::wl_proxy_destroy(wl_buffer as *mut objects::wl_proxy) }
identifier_body
remove.py
import math import wx import eos.db import gui.mainFrame from gui import globalEvents as GE from gui.fitCommands.calc.cargo.remove import CalcRemoveCargoCommand from gui.fitCommands.helpers import CargoInfo, InternalCommandHistory from service.market import Market class GuiRemoveCargosCommand(wx.Command): def ...
success = self.internalHistory.undoAll() eos.db.commit() wx.PostEvent(gui.mainFrame.MainFrame.getInstance(), GE.FitChanged(fitIDs=(self.fitID,))) return success
identifier_body
remove.py
import math import wx import eos.db import gui.mainFrame from gui import globalEvents as GE from gui.fitCommands.calc.cargo.remove import CalcRemoveCargoCommand from gui.fitCommands.helpers import CargoInfo, InternalCommandHistory from service.market import Market class GuiRemoveCargosCommand(wx.Command): def ...
(self): success = self.internalHistory.undoAll() eos.db.commit() wx.PostEvent(gui.mainFrame.MainFrame.getInstance(), GE.FitChanged(fitIDs=(self.fitID,))) return success
Undo
identifier_name
remove.py
import math import wx import eos.db import gui.mainFrame from gui import globalEvents as GE from gui.fitCommands.calc.cargo.remove import CalcRemoveCargoCommand from gui.fitCommands.helpers import CargoInfo, InternalCommandHistory from service.market import Market class GuiRemoveCargosCommand(wx.Command): def ...
success = any(results) eos.db.commit() wx.PostEvent(gui.mainFrame.MainFrame.getInstance(), GE.FitChanged(fitIDs=(self.fitID,))) return success def Undo(self): success = self.internalHistory.undoAll() eos.db.commit() wx.PostEvent(gui.mainFrame.MainFrame.getIn...
cmd = CalcRemoveCargoCommand( fitID=self.fitID, cargoInfo=CargoInfo(itemID=itemID, amount=math.inf)) results.append(self.internalHistory.submit(cmd)) sMkt.storeRecentlyUsed(itemID)
conditional_block
remove.py
import math import wx import eos.db import gui.mainFrame from gui import globalEvents as GE from gui.fitCommands.calc.cargo.remove import CalcRemoveCargoCommand from gui.fitCommands.helpers import CargoInfo, InternalCommandHistory from service.market import Market class GuiRemoveCargosCommand(wx.Command): def ...
sMkt = Market.getInstance() results = [] for itemID in self.itemIDs: cmd = CalcRemoveCargoCommand( fitID=self.fitID, cargoInfo=CargoInfo(itemID=itemID, amount=math.inf)) results.append(self.internalHistory.submit(cmd)) sMkt.stor...
self.fitID = fitID self.itemIDs = itemIDs def Do(self):
random_line_split
sped_documento_item_declaracao_importacao.py
# -*- coding: utf-8 -*- # # Copyright 2016 Taŭga Tecnologia # Aristides Caldeira <aristides.caldeira@tauga.com.br> # License AGPL-3 or later (http://www.gnu.org/licenses/agpl) # from __future__ import division, print_function, unicode_literals from odoo import fields, models from odoo.addons.l10n_br_base.models.spe...
comodel_name='sped.documento.item', string='Item do Documento', ondelete='cascade', required=True, ) numero_documento = fields.Char( string='Nº do documento de importação', size=12, ) data_registro = fields.Date( string='Data de registro', ) ...
item_id = fields.Many2one(
random_line_split
sped_documento_item_declaracao_importacao.py
# -*- coding: utf-8 -*- # # Copyright 2016 Taŭga Tecnologia # Aristides Caldeira <aristides.caldeira@tauga.com.br> # License AGPL-3 or later (http://www.gnu.org/licenses/agpl) # from __future__ import division, print_function, unicode_literals from odoo import fields, models from odoo.addons.l10n_br_base.models.spe...
inherit = 'sped.documento.item' declaracao_ids = fields.One2many( comodel_name='sped.documento.item.declaracao.importacao', inverse_name='item_id', string='Declarações de importação', )
Model): _
identifier_name
sped_documento_item_declaracao_importacao.py
# -*- coding: utf-8 -*- # # Copyright 2016 Taŭga Tecnologia # Aristides Caldeira <aristides.caldeira@tauga.com.br> # License AGPL-3 or later (http://www.gnu.org/licenses/agpl) # from __future__ import division, print_function, unicode_literals from odoo import fields, models from odoo.addons.l10n_br_base.models.spe...
uf_desembaraco_id = fields.Many2one( comodel_name='sped.estado', string='Estado do desembaraço', ) data_desembaraco = fields.Date( string='Data do desembaraço', ) via_trans_internacional = fields.Selection( selection=VIA_TRANSPORTE_IMPORTACAO, string='Via de t...
name = b'sped.documento.item.declaracao.importacao' _description = 'Declarações de Importação do Item do Documento Fiscal' item_id = fields.Many2one( comodel_name='sped.documento.item', string='Item do Documento', ondelete='cascade', required=True, ) numero_documento = f...
identifier_body
memory_usage.rs
use concurrency_manager::ConcurrencyManager; use futures::executor::block_on; use rand::prelude::*;
// This test is heavy so we shouldn't run it daily. // Run it with the following command (recommending release mode) and see the printed stats: // // ``` // cargo test --package concurrency_manager --test memory_usage --features jemalloc --release -- test_memory_usage --exact --ignored --nocapture // ``` #[test] #[igno...
use std::{mem::forget, mem::ManuallyDrop, thread}; use txn_types::{Key, Lock, LockType};
random_line_split
memory_usage.rs
use concurrency_manager::ConcurrencyManager; use futures::executor::block_on; use rand::prelude::*; use std::{mem::forget, mem::ManuallyDrop, thread}; use txn_types::{Key, Lock, LockType}; // This test is heavy so we shouldn't run it daily. // Run it with the following command (recommending release mode) and see the p...
let guard = block_on(cm.lock_key(&key)); guard.with_lock(|l| { *l = Some(lock); }); forget(guard); } }); ths.push(th); } ths.into_iter().for_each(|th| th.join().unwrap()); println!("{:?}", tik...
{ continue; }
conditional_block
memory_usage.rs
use concurrency_manager::ConcurrencyManager; use futures::executor::block_on; use rand::prelude::*; use std::{mem::forget, mem::ManuallyDrop, thread}; use txn_types::{Key, Lock, LockType}; // This test is heavy so we shouldn't run it daily. // Run it with the following command (recommending release mode) and see the p...
let lock = Lock::new( LockType::Put, raw, 10.into(), 1000, None, 10.into(), 1, 20.into(), ); // Key already exi...
{ // Make key as small as possible, so concurrent writes in the scheduler // can be as many as possible. Then, we can maximize the amplication // caused by the data structure. const KEY_LEN: usize = 16; // We allow 100MB pending writes in the scheduler. const LOCK_COUNT: usize = 100 * 1024 * 102...
identifier_body
memory_usage.rs
use concurrency_manager::ConcurrencyManager; use futures::executor::block_on; use rand::prelude::*; use std::{mem::forget, mem::ManuallyDrop, thread}; use txn_types::{Key, Lock, LockType}; // This test is heavy so we shouldn't run it daily. // Run it with the following command (recommending release mode) and see the p...
() { // Make key as small as possible, so concurrent writes in the scheduler // can be as many as possible. Then, we can maximize the amplication // caused by the data structure. const KEY_LEN: usize = 16; // We allow 100MB pending writes in the scheduler. const LOCK_COUNT: usize = 100 * 1024 * ...
test_memory_usage
identifier_name
.eslintrc.js
module.exports = { "env": { "browser": true, "es6": true, "node": true }, "extends": "eslint:recommended", "globals": { "__DEV__": true }, "parser": "babel-eslint", "parserOptions": { "ecmaFeatures": { "experimentalObjectRestSpread": true, "jsx": true }, "sourceType...
{ "args": "after-used", "vars": "all", "ignoreRestSiblings": true, "argsIgnorePattern": "^_" } ], "quotes": [ "error", "single" ], "react-native/no-unused-styles": 2, "react-native/split-platform-components": 2, "react-native/no-inline-styl...
} ], "no-unused-vars": [ "error",
random_line_split
UI_ProgressBar.ts
import { Laya } from "Laya"; import { Stage } from "laya/display/Stage"; import { ProgressBar } from "laya/ui/ProgressBar"; import { Handler } from "laya/utils/Handler"; import { Main } from "./../Main"; export class UI_ProgressBar { private progressBar: ProgressBar; Main: typeof Main = null;
constructor(maincls: typeof Main) { this.Main = maincls; // 不支持WebGL时自动切换至Canvas //Laya.init(800, 600, WebGL); Laya.init(800, 600); Laya.stage.alignV = Stage.ALIGN_MIDDLE; Laya.stage.alignH = Stage.ALIGN_CENTER; Laya.stage.scaleMode = Stage.SCALE_SHOWALL; Laya.stage.bgColor = "#232628"; Laya.load...
random_line_split
UI_ProgressBar.ts
import { Laya } from "Laya"; import { Stage } from "laya/display/Stage"; import { ProgressBar } from "laya/ui/ProgressBar"; import { Handler } from "laya/utils/Handler"; import { Main } from "./../Main"; export class UI_ProgressBar { private progressBar: ProgressBar; Main: typeof Main = null; constructor(maincls: ...
度:" + Math.floor(value * 100) + "%"); } }
identifier_body
UI_ProgressBar.ts
import { Laya } from "Laya"; import { Stage } from "laya/display/Stage"; import { ProgressBar } from "laya/ui/ProgressBar"; import { Handler } from "laya/utils/Handler"; import { Main } from "./../Main"; export class UI_ProgressBar { private progressBar: ProgressBar; Main: typeof Main = null; constructor(maincls: ...
oid { this.progressBar = new ProgressBar("res/ui/progressBar.png"); this.progressBar.width = 400; this.progressBar.x = (Laya.stage.width - this.progressBar.width) / 2; this.progressBar.y = Laya.stage.height / 2; this.progressBar.sizeGrid = "5,5,5,5"; this.progressBar.changeHandler = new Handler(this, thi...
any = null): v
identifier_name
tests.py
#! python 3 # -*- coding: utf8 -*-
cov.start() import os import unittest from datetime import datetime, timedelta import bcrypt from config import basedir, SQLALCHEMY_DATABASE_URI from application import app, db from application.models import User, Group class TestCase(unittest.TestCase): def setUp(self): app.config['TESTING'] = True ...
from coverage import coverage cov = coverage(branch=True, omit=['venv/*', 'tests.py'])
random_line_split
tests.py
#! python 3 # -*- coding: utf8 -*- from coverage import coverage cov = coverage(branch=True, omit=['venv/*', 'tests.py']) cov.start() import os import unittest from datetime import datetime, timedelta import bcrypt from config import basedir, SQLALCHEMY_DATABASE_URI from application import app, db from application....
(unittest.TestCase): def setUp(self): app.config['TESTING'] = True app.config['WTF_CSRF_ENABLED'] = False app.config['SQLALCHEMY_DATABASE_URI'] = SQLALCHEMY_DATABASE_URI db.create_all() def tearDown(self): db.session.remove() def test_user(self): password =...
TestCase
identifier_name
tests.py
#! python 3 # -*- coding: utf8 -*- from coverage import coverage cov = coverage(branch=True, omit=['venv/*', 'tests.py']) cov.start() import os import unittest from datetime import datetime, timedelta import bcrypt from config import basedir, SQLALCHEMY_DATABASE_URI from application import app, db from application....
try: unittest.main() except: pass cov.stop() cov.save() print('\n\nCoverage Report:\n') cov.report() print('\nHTML version: {}'.format(os.path.join(basedir, 'tmp/coverage/index.html'))) cov.html_report(directory='tmp/coverage') cov.erase()
conditional_block
tests.py
#! python 3 # -*- coding: utf8 -*- from coverage import coverage cov = coverage(branch=True, omit=['venv/*', 'tests.py']) cov.start() import os import unittest from datetime import datetime, timedelta import bcrypt from config import basedir, SQLALCHEMY_DATABASE_URI from application import app, db from application....
if __name__ == '__main__': try: unittest.main() except: pass cov.stop() cov.save() print('\n\nCoverage Report:\n') cov.report() print('\nHTML version: {}'.format(os.path.join(basedir, 'tmp/coverage/index.html'))) cov.html_report(directory='tmp/coverage') cov.erase...
password = 'testicles' password = password.encode('utf-8') password = bcrypt.hashpw(password, bcrypt.gensalt()) # add user u1 = u = User(name='John Doe', email='john@example.com', username='jdoe', password=password) db.session.add(u1) # add group g = Group(group...
identifier_body
factorial.js
'use strict'; module.exports = function (math) { var util = require('../../util/index'), BigNumber = math.type.BigNumber, collection = require('../../type/collection'), isNumber = util.number.isNumber, isBoolean = util['boolean'].isBoolean, isInteger = util.number.isInteger, isC...
value = n.minus(one); res = n; while (value.gt(one)) { res = res.times(value); value = value.minus(one); } if (res.equals(0)) { res = one; // 0! is per definition 1 } return res; } if (isBoolean(n)) { return 1; // factorial(1) = 1...
throw new TypeError('Positive integer value expected in function factorial'); } var one = new BigNumber(1);
random_line_split
factorial.js
'use strict'; module.exports = function (math) { var util = require('../../util/index'), BigNumber = math.type.BigNumber, collection = require('../../type/collection'), isNumber = util.number.isNumber, isBoolean = util['boolean'].isBoolean, isInteger = util.number.isInteger, isC...
if (isCollection(n)) { return collection.deepMap(n, factorial); } throw new math.error.UnsupportedTypeError('factorial', math['typeof'](n)); }; /** * Test whether BigNumber n is a positive integer * @param {BigNumber} n * @returns {boolean} isPositiveInteger */ var isPositiveInte...
{ return 1; // factorial(1) = 1, factorial(0) = 1 }
conditional_block
test_extended_virtual_interfaces_net.py
# Copyright 2013 IBM Corp. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
def get_vifs_by_instance(self, context, instance_id): return FAKE_VIFS def get_vif_by_mac_address(self, context, mac_address): if mac_address == "00-00-00-00-00-00": return {'net_uuid': '00000000-0000-0000-0000-00000000000000001'} else: return {'net_uuid': '11111111-1111-1111-1111-111111...
def compute_api_get(self, context, instance_id, expected_attrs=None, want_objects=False): return dict(uuid=FAKE_UUID, id=instance_id, instance_type_id=1, host='bob')
random_line_split
test_extended_virtual_interfaces_net.py
# Copyright 2013 IBM Corp. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
yield vif.attrib['%snet_id' % self.prefix]
conditional_block
test_extended_virtual_interfaces_net.py
# Copyright 2013 IBM Corp. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
content_type = 'application/xml' prefix = "{%s}" % extended_virtual_interfaces_net. \ Extended_virtual_interfaces_net.namespace def setUp(self): super(ExtendedServerVIFNetSerializerTest, self).setUp() self.namespace = wsgi.XMLNS_V11 self.serializer = extended_vir...
identifier_body
test_extended_virtual_interfaces_net.py
# Copyright 2013 IBM Corp. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by app...
(self, context, mac_address): if mac_address == "00-00-00-00-00-00": return {'net_uuid': '00000000-0000-0000-0000-00000000000000001'} else: return {'net_uuid': '11111111-1111-1111-1111-11111111111111112'} class ExtendedServerVIFNetTest(test.NoDBTestCase): content_type = 'application/json' ...
get_vif_by_mac_address
identifier_name
print.rs
// TODO: get num cols of terminal dynamically // TODO: care about the given print options use super::{Report, ReportKind, RemarkKind, Snippet}; use code::{FileMap, LineIdx, Span}; use term_painter::ToStyle; use term_painter::Color::*; use std::default::Default; /// Options for printing on the terminal. By `default()`...
let line = line_orig.replace("\t", " "); let num_tabs = line_orig[..start.col.0 as usize] .chars() .filter(|&c| c == '\t') .count(); // adjust cols in case of replaced tabs let startcol = start.col.0 as usize + 3*num_tabs; let endcol = end....
{ let start = src.get_loc(span.lo); let end = src.get_loc(span.hi); trace!("Span is from {:?} to {:?}", start, end); // ----- Dummyspan ----- if span.is_dummy() { println!(" {} {} ! no snippet due to <dummy-span>, this is a bug !", Magenta.bold().paint("?"), Magen...
identifier_body
print.rs
// TODO: get num cols of terminal dynamically // TODO: care about the given print options use super::{Report, ReportKind, RemarkKind, Snippet}; use code::{FileMap, LineIdx, Span}; use term_painter::ToStyle; use term_painter::Color::*; use std::default::Default; /// Options for printing on the terminal. By `default()`...
(rep: &Report, src: &FileMap, _: PrintOptions) { trace!("Printing report: {:#?}", rep); trace!("Printing with filemap: {:#?}", src); // print header let title = match rep.kind { ReportKind::Error => White.bold().bg(Red).paint("ERROR"), ReportKind::Warning => White.bold().bg(Yellow).pain...
print
identifier_name
print.rs
// TODO: get num cols of terminal dynamically // TODO: care about the given print options use super::{Report, ReportKind, RemarkKind, Snippet}; use code::{FileMap, LineIdx, Span}; use term_painter::ToStyle; use term_painter::Color::*; use std::default::Default; /// Options for printing on the terminal. By `default()`...
); }); } // ----- Multiline ----- else { let (lines, color) = match *snippet { Snippet::Replace { ref with, .. } => { let mut lines = Vec::new(); if let Some(first_break) = with.find("\n") { // we can unwrap, beca...
println!(" {: <2$}{:^<3$}", " ", "^", startcol + 1, underline_len,
random_line_split
magic_square.rs
extern crate magic_square; use magic_square::*; #[test] pub fn magic_square_contains_the_postage_stamp_values() { let mut values = create_magic_square().values; values.sort_by(|a, b| a.partial_cmp(b).unwrap()); assert_eq!(POSTAGE_STAMP_VALUES, values); }
pub fn rows_sum_to_the_same_value() { let values = create_magic_square().values; let magic_number = magic_number(); for &sum in sum_rows(values).iter() { assert_eq!(magic_number, sum); } } #[test] pub fn columns_sum_to_the_same_value() { let values = create_magic_square().values; let ma...
#[test]
random_line_split
magic_square.rs
extern crate magic_square; use magic_square::*; #[test] pub fn magic_square_contains_the_postage_stamp_values() { let mut values = create_magic_square().values; values.sort_by(|a, b| a.partial_cmp(b).unwrap()); assert_eq!(POSTAGE_STAMP_VALUES, values); } #[test] pub fn rows_sum_to_the_same_value() { ...
(values: [f32; 9]) -> [f32; 3] { panic!("For you to do"); } fn sum_diagonals(values: [f32; 9]) -> [f32; 3] { panic!("For you to do"); }
sum_columns
identifier_name
magic_square.rs
extern crate magic_square; use magic_square::*; #[test] pub fn magic_square_contains_the_postage_stamp_values() { let mut values = create_magic_square().values; values.sort_by(|a, b| a.partial_cmp(b).unwrap()); assert_eq!(POSTAGE_STAMP_VALUES, values); } #[test] pub fn rows_sum_to_the_same_value() { ...
fn sum_columns(values: [f32; 9]) -> [f32; 3] { panic!("For you to do"); } fn sum_diagonals(values: [f32; 9]) -> [f32; 3] { panic!("For you to do"); }
{ panic!("For you to do"); }
identifier_body
transport.rs
.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Support for implementing transport layer protocols //! //! The transport module provides the ability to send and receive packet...
<T : Packet>(&mut self, packet: T, dst: net::IpAddr) -> io::Result<usize> { use packet::ipv4::MutableIpv4Packet; // FreeBSD and OS X expect total length and fragment offset fields of IPv4 packets to be in // host byte order rather than network byte order (man 4 ip/Raw IP Sockets) if mat...
send_to_impl
identifier_name
transport.rs
.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Support for implementing transport layer protocols //! //! The transport module provides the ability to send and receive packet...
macro_rules! transport_channel_iterator { ($ty:ident, $iter:ident, $func:ident) => ( /// An iterator over packets of type $ty pub struct $iter<'a> { tr: &'a mut TransportReceiver } /// Return a packet iterator with packets of type $ty for some transport receiver p...
/// ipv4_packet_iter) // Name of function to create iterator /// ``` #[macro_export]
random_line_split
html.js
//>>built define("dojox/highlight/languages/pygments/html",["../../_base","./_html"],function(dh){
_1.html={case_insensitive:true,defaultMode:{contains:["name entity","comment","comment preproc","_script","_style","_tag"]},modes:[{className:"comment",begin:"<!--",end:"-->"},{className:"comment preproc",begin:"\\<\\!\\[CDATA\\[",end:"\\]\\]\\>"},{className:"comment preproc",begin:"\\<\\!",end:"\\>"},{className:"strin...
var _1=dh.languages,_2=[],ht=_1.pygments._html.tags; for(var _3 in ht){ _2.push(_3); } _2="\\b("+_2.join("|")+")\\b";
random_line_split
alsace20.py
# -*- coding: utf-8 -*- """ Catch-up TV & More Copyright (C) 2019 SylvainCecchetto This file is part of Catch-up TV & More. Catch-up TV & More 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 Foundat...
item = Listitem() item.label = category_name item.set_callback( list_programs, item_id=item_id, category_url=category_url) item_post_treatment(item) yield item @Route.register def list_programs(plugin, item_id, category_url, **kwargs): """ Build programs l...
category_url = URL_ROOT + category_datas.find('.//a').get('href')
conditional_block
alsace20.py
# -*- coding: utf-8 -*- """ Catch-up TV & More Copyright (C) 2019 SylvainCecchetto This file is part of Catch-up TV & More. Catch-up TV & More 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 Foundat...
(plugin, item_id, video_url, download_mode=False, **kwargs): is_helper = inputstreamhelper.Helper('mpd') if not is_helper.check_inputstream(): return False resp = urlquick.get( video_url, headers={"User-Agent": web_uti...
get_video_url
identifier_name
alsace20.py
# -*- coding: utf-8 -*- """ Catch-up TV & More Copyright (C) 2019 SylvainCecchetto This file is part of Catch-up TV & More. Catch-up TV & More 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 Foundat...
list_videos, item_id=item_id, program_url=program_url) item_post_treatment(item) yield item elif 'VOD' in category_url: if program_datas.get('href').split('/')[2] in category_url: program_name = program_datas.find( ...
""" Build programs listing - ... """ resp = urlquick.get(category_url) root = resp.parse("div", attrs={"class": "emissions hidden-xs"}) for program_datas in root.iterfind(".//a"): if 'VOD/est' in category_url: if 'Est' in program_datas.get('href').split('/')[2]: ...
identifier_body
alsace20.py
# -*- coding: utf-8 -*- """ Catch-up TV & More Copyright (C) 2019 SylvainCecchetto This file is part of Catch-up TV & More. Catch-up TV & More 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 Foundat...
if '#' in category_datas.find('.//a').get('href'): category_url = URL_ROOT else: category_url = URL_ROOT + category_datas.find('.//a').get('href') item = Listitem() item.label = category_name item.set_callback( list_programs, item_id=item_id, ...
root = resp.parse("ul", attrs={"class": "menu-vod hidden-xs"}) for category_datas in root.iterfind(".//li"): category_name = category_datas.find('.//a').text
random_line_split
crypto.rs
new random key pair. /// /// # Example /// ```rust /// extern crate ethcore_util; /// use ethcore_util::crypto::*; /// use ethcore_util::hash::*; /// fn main() { /// let pair = KeyPair::create().unwrap(); /// let message = H256::random(); /// let signature = ec::sign(pair.secret(), &message).unwrap(); /// /// ...
} /// ECDH functions #[cfg_attr(feature="dev", allow(similar_names))] pub mod ecdh { use crypto::*; use crypto; /// Agree on a shared secret pub fn agree(secret: &Secret, public: &Public) -> Result<Secret, CryptoError> { use secp256k1::*; let context = &crypto::SECP256K1; let mut pdata: [u8; 65] = [4u8; 65...
{ sig[64] <= 1 && H256::from_slice(&sig[0..32]) < h256_from_hex("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141") && H256::from_slice(&sig[32..64]) < h256_from_hex("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141") && H256::from_slice(&sig[32..64]) >= h256_from_u64(1) && H256::from_...
identifier_body
crypto.rs
a new random key pair. /// /// # Example /// ```rust /// extern crate ethcore_util; /// use ethcore_util::crypto::*; /// use ethcore_util::hash::*; /// fn main() { /// let pair = KeyPair::create().unwrap(); /// let message = H256::random(); /// let signature = ec::sign(pair.secret(), &message).unwrap(); /// /// ...
(sig: &Signature) -> bool { sig[64] <= 1 && H256::from_slice(&sig[0..32]) < h256_from_hex("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141") && H256::from_slice(&sig[32..64]) < h256_from_hex("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141") && H256::from_slice(&sig[32..64]) >= h256_...
is_valid
identifier_name
crypto.rs
/// Invalid EC signature InvalidSignature, /// Invalid AES message InvalidMessage, /// IO Error Io(::std::io::Error), } impl From<::secp256k1::Error> for CryptoError { fn from(e: ::secp256k1::Error) -> CryptoError { match e { ::secp256k1::Error::InvalidMessage => CryptoError::InvalidMessage, ::secp256k1...
pub enum CryptoError { /// Invalid secret key InvalidSecret, /// Invalid public key InvalidPublic,
random_line_split
assignment-processor-functions.ts
import { createStripeSetupIntent } from '@automattic/calypso-stripe'; import {
} from '@automattic/composite-checkout'; import { addQueryArgs } from '@wordpress/url'; import { useTranslate } from 'i18n-calypso'; import wp from 'calypso/lib/wp'; import { recordTracksEvent } from 'calypso/state/analytics/actions'; import { updateCreditCard, saveCreditCard } from './stored-payment-method-api'; impor...
makeRedirectResponse, makeSuccessResponse, makeErrorResponse,
random_line_split
assignment-processor-functions.ts
import { createStripeSetupIntent } from '@automattic/calypso-stripe'; import { makeRedirectResponse, makeSuccessResponse, makeErrorResponse, } from '@automattic/composite-checkout'; import { addQueryArgs } from '@wordpress/url'; import { useTranslate } from 'i18n-calypso'; import wp from 'calypso/lib/wp'; import { r...
if ( ! stripe || ! stripeConfiguration || ! stripeSetupIntentId ) { throw new Error( 'Cannot assign payment method if Stripe is not loaded' ); } if ( ! cardNumberElement ) { throw new Error( 'Cannot assign payment method if there is no card number' ); } const { name, countryCode, postalCode, useForAll...
{ throw new Error( 'Credit Card data is missing country' ); }
conditional_block
assignment-processor-functions.ts
import { createStripeSetupIntent } from '@automattic/calypso-stripe'; import { makeRedirectResponse, makeSuccessResponse, makeErrorResponse, } from '@automattic/composite-checkout'; import { addQueryArgs } from '@wordpress/url'; import { useTranslate } from 'i18n-calypso'; import wp from 'calypso/lib/wp'; import { r...
function isNewCardDataValid( data: unknown ): data is NewCardSubmitData { const newCardData = data as NewCardSubmitData; return !! newCardData.countryCode; } interface NewCardSubmitData { name?: string; countryCode: string; postalCode?: string; useForAllSubscriptions: boolean; } export async function assignEx...
{ const paymentDetailsForStripe = { name, address: { country, postal_code, }, }; return createStripeSetupIntent( stripe, cardNumberElement, setupIntentId, paymentDetailsForStripe ); }
identifier_body
assignment-processor-functions.ts
import { createStripeSetupIntent } from '@automattic/calypso-stripe'; import { makeRedirectResponse, makeSuccessResponse, makeErrorResponse, } from '@automattic/composite-checkout'; import { addQueryArgs } from '@wordpress/url'; import { useTranslate } from 'i18n-calypso'; import wp from 'calypso/lib/wp'; import { r...
( { purchase, useForAllSubscriptions, }: { purchase?: Purchase; useForAllSubscriptions?: boolean; } ) { return purchase?.productSlug ? recordTracksEvent( 'calypso_purchases_credit_card_form_submit', { product_slug: purchase.productSlug, use_for_all_subs: String( useForAllSubscriptions ), } ) : reco...
recordFormSubmitEvent
identifier_name
country.rs
use std::collections::BTreeMap; use std::f64; use super::country_page_data::CountryPageData; use super::event::Event; use super::event_trunc::{EventTrunc, EventTruncRenderable}; use super::year::Year; use super::year_page_data::YearPageData; /// `Country` contains full country data #[derive(Debug, Clone, RustcEncodab...
pub num_events: i32, pub num_fatalities: i32, } impl Country { pub fn new(t_link: String, t_name: String, num_eve: i32, num_fat: i32) -> Country { Country { events: Vec::new(), link: t_link, name: t_name, num_events: num_eve, num_fatalitie...
pub link: String, pub name: String,
random_line_split
country.rs
use std::collections::BTreeMap; use std::f64; use super::country_page_data::CountryPageData; use super::event::Event; use super::event_trunc::{EventTrunc, EventTruncRenderable}; use super::year::Year; use super::year_page_data::YearPageData; /// `Country` contains full country data #[derive(Debug, Clone, RustcEncodab...
{ pub events: Vec<Event>, pub link: String, pub name: String, pub num_events: i32, pub num_fatalities: i32, } impl Country { pub fn new(t_link: String, t_name: String, num_eve: i32, num_fat: i32) -> Country { Country { events: Vec::new(), link: t_link, ...
Country
identifier_name
country.rs
use std::collections::BTreeMap; use std::f64; use super::country_page_data::CountryPageData; use super::event::Event; use super::event_trunc::{EventTrunc, EventTruncRenderable}; use super::year::Year; use super::year_page_data::YearPageData; /// `Country` contains full country data #[derive(Debug, Clone, RustcEncodab...
} YearPageData { eve_vec: t_eve, name: self.name.clone(), year: inp_year, } } }
{ t_eve.push(EventTruncRenderable::from_event(elem)); }
conditional_block
country.rs
use std::collections::BTreeMap; use std::f64; use super::country_page_data::CountryPageData; use super::event::Event; use super::event_trunc::{EventTrunc, EventTruncRenderable}; use super::year::Year; use super::year_page_data::YearPageData; /// `Country` contains full country data #[derive(Debug, Clone, RustcEncodab...
}
{ let mut t_eve: Vec<EventTruncRenderable> = Vec::new(); for elem in &self.events { if elem.year == inp_year { t_eve.push(EventTruncRenderable::from_event(elem)); } } YearPageData { eve_vec: t_eve, name: self.name.clone(), ...
identifier_body
lint.js
/* jshint node:true, laxbreak: true */ 'use strict'; // Sets up the tasks that lints css and js files. // @task: /gulp-config/lint.js /////////////////////////////////////////////////////////////////////////// // Required modules. /////////////////////////////////////////////////////////////////////////// var csslint...
var buildConfig = require('./../build-config'); /////////////////////////////////////////////////////////////////////////// // Create Tasks /////////////////////////////////////////////////////////////////////////// /** * The class that holds all of our gulp tasks for this configuration. * * @class GulpTask * @pa...
var path = require('path');
random_line_split
lights.rs
use cgmath::Point2; use layer::LayerId; #[derive(Clone, Debug)] pub struct AmbientLight { pub color: LightColor, pub intensity: f32, } #[derive(Clone, Debug)] pub struct Light { pub center: Point2<f32>, pub radius: f32, pub source_radius: f32, pub source_layer: LayerId, pu...
([r, g, b]: [f32; 3]) -> Self { use color::component_srgb_to_linear as conv; LightColor { r: conv(r), g: conv(g), b: conv(b), } } pub fn from_array([r, g, b]: [f32; 3]) -> Self { LightColor { r: r, g: g, b: b } } pub fn t...
from_srgb
identifier_name
lights.rs
use cgmath::Point2; use layer::LayerId; #[derive(Clone, Debug)] pub struct AmbientLight { pub color: LightColor, pub intensity: f32, } #[derive(Clone, Debug)] pub struct Light { pub center: Point2<f32>, pub radius: f32, pub source_radius: f32, pub source_layer: LayerId, pu...
#[derive(Clone, Copy, Debug)] pub struct LightColor { pub r: f32, pub g: f32, pub b: f32, } impl LightColor { pub fn from_srgb([r, g, b]: [f32; 3]) -> Self { use color::component_srgb_to_linear as conv; LightColor { r: conv(r), g: conv(g), ...
pub intensity: f32, }
random_line_split
distribution-controller-test.js
/* * This program is part of the OpenLMIS logistics management information system platform software. * Copyright © 2013 VillageReach * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, eith...
var postResponse = {"success": "Data has been downloaded", message:"already initiated", "distribution": {facilityDistributions: {}, deliveryZone: {id: 1, name: 'zone1'}, program: {id: 1, name: 'program1'}, period: {id: 1, name: 'period1'}}}; httpBackend.expect('POST', '/distributions.json').respond(200, postRe...
it('should confirm caching of already initiated distribution', function () { scope.selectedZone = {id: 4, name: 'zone1'}; scope.selectedProgram = {id: 4, name: 'program1'}; scope.selectedPeriod = {id: 4, name: 'period1'};
random_line_split
ng_model_group.d.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import { OnDestroy, OnInit } from '@angular/core'; import { AbstractFormGroupDirective } from './abstract_form_group_...
extends AbstractFormGroupDirective implements OnInit, OnDestroy { /** * @description * Tracks the name of the `NgModelGroup` bound to the directive. The name corresponds * to a key in the parent `NgForm`. */ name: string; constructor(parent: ControlContainer, validators: any[], asyncVal...
NgModelGroup
identifier_name
ng_model_group.d.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import { OnDestroy, OnInit } from '@angular/core'; import { AbstractFormGroupDirective } from './abstract_form_group_...
export declare class NgModelGroup extends AbstractFormGroupDirective implements OnInit, OnDestroy { /** * @description * Tracks the name of the `NgModelGroup` bound to the directive. The name corresponds * to a key in the parent `NgForm`. */ name: string; constructor(parent: ControlConta...
* * @ngModule FormsModule * @publicApi */
random_line_split
winery-alert.module.ts
/** * Copyright (c) 2017 University of Stuttgart. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and the Apache License 2.0 which both accompany this distribution, * and are available at http://www.eclipse.org/legal/epl-v...
(): ModuleWithProviders { return { ngModule: WineryAlertModule, providers: [WineryAlertService] }; } }
forRoot
identifier_name
tile.rs
use std::f64::{self, consts}; const EARTH_RADIUS: f64 = 6378137.0; const PERIMETER: f64 = EARTH_RADIUS * 2. * consts::PI; #[allow(dead_code)] /** * Turns WGS 84 coordinates into WebMercator * tiles numbering */ pub fn lon_lat_to_tile(lon: f64, lat: f64, zoom: u32) -> (u32, u32, u32) { let lat = lat.to_radians...
{ let bbox = LonLatBbox { west: 78.75, south: 66.51326044311186, east: 90.0, north: 70.61261423801925 }; let tile = Tile { x: 23, y: 7, z: 5, }; assert_eq!(bbox, tile.bounds()); }
identifier_body
tile.rs
use std::f64::{self, consts}; const EARTH_RADIUS: f64 = 6378137.0; const PERIMETER: f64 = EARTH_RADIUS * 2. * consts::PI;
* tiles numbering */ pub fn lon_lat_to_tile(lon: f64, lat: f64, zoom: u32) -> (u32, u32, u32) { let lat = lat.to_radians(); let n = 2_f64.powf(zoom as f64); let xtile: f64 = ((lon + 180.0) / 360.0) * n; let ytile: f64 = (1.0 - (lat.tan() + (1.0 / lat.cos())).ln() / consts::PI) / 2.0 * n; (xtile.fl...
#[allow(dead_code)] /** * Turns WGS 84 coordinates into WebMercator
random_line_split
tile.rs
use std::f64::{self, consts}; const EARTH_RADIUS: f64 = 6378137.0; const PERIMETER: f64 = EARTH_RADIUS * 2. * consts::PI; #[allow(dead_code)] /** * Turns WGS 84 coordinates into WebMercator * tiles numbering */ pub fn lon_lat_to_tile(lon: f64, lat: f64, zoom: u32) -> (u32, u32, u32) { let lat = lat.to_radians...
(&self) -> Bbox { let (west, north) = wgs84_to_meters(self.west, self.north); let (east, south) = wgs84_to_meters(self.east, self.south); Bbox {west, south, east, north} } } #[derive(Debug, PartialEq)] pub struct Bbox { /// meters pub west: f64, /// meters pub south: f64, ...
xy
identifier_name
chat.component.ts
import { Component, OnDestroy } from '@angular/core'; import { WebSocketService } from "../services/websocket.service"; import { ChatChannelService } from "../services/chat.channel.service"; import { Message } from '../things/message'; @Component({ selector: 'chat', templateUrl: 'a...
public onSubmit():void { this.sendMessage(); } public timestamp_to_date( timestamp:number ):string{ let date = new Date(); date.setTime( timestamp * 1000 ); return `${ date.getHours() }:${ date.getMinutes() } ${ date.getDate() }-${ ( date.getMonth() + 1 ) }-${ date.ge...
{ this.chatChannelService.send( this.newMessageData ); this.newMessageData = { name: '', text: '',action: 'create' }; }
identifier_body
chat.component.ts
import { Component, OnDestroy } from '@angular/core'; import { WebSocketService } from "../services/websocket.service"; import { ChatChannelService } from "../services/chat.channel.service"; import { Message } from '../things/message'; @Component({ selector: 'chat', templateUrl: 'a...
this.webSocketService.close(); } private sendMessage():void{ this.chatChannelService.send( this.newMessageData ); this.newMessageData = { name: '', text: '',action: 'create' }; } public onSubmit():void { this.sendMessage(); } public timestamp_to_date( tim...
random_line_split
chat.component.ts
import { Component, OnDestroy } from '@angular/core'; import { WebSocketService } from "../services/websocket.service"; import { ChatChannelService } from "../services/chat.channel.service"; import { Message } from '../things/message'; @Component({ selector: 'chat', templateUrl: 'a...
implements OnDestroy{ messages: Message[] = []; newMessageData: Object = { name: '', text: '', action: 'create' }; chatSubscribed:boolean = false; constructor( private chatChannelService:ChatChannelService, private webSocketService:WebSocketService ){ this.webSo...
ChatComponent
identifier_name
chat.component.ts
import { Component, OnDestroy } from '@angular/core'; import { WebSocketService } from "../services/websocket.service"; import { ChatChannelService } from "../services/chat.channel.service"; import { Message } from '../things/message'; @Component({ selector: 'chat', templateUrl: 'a...
} ); this.chatChannelService.observableData.subscribe( ( data:Object ) => { self.messages = data['messages']; } ); } private getAllMessages():void { this.chatChannelService.send( { action: 'index' } ); } ngOnDestroy():void { this.chatChannel...
{ this.getAllMessages(); }
conditional_block
rect.rs
use std::convert::From; use graphics::math::{ self, Scalar }; use { Point, Size }; /// A rectangle. #[derive(Clone, Copy, Debug)] pub struct Rect { /// The position of the top left corner of the rectangle. pub pos: Point, /// The width and height of the rectangle. pub size: Size, } impl<P: Into<Point...
/// Computes a scaled rectangle with the same position as self. pub fn scaled<T: Into<Size>>(self, v: T) -> Rect { let v: Size = v.into(); Rect { pos: self.pos, size: self.size * v, } } /// Returns the position of the top side of the rectangle. pub fn...
/// Returns the position of the right side of the rectangle. pub fn right(&self) -> Scalar { self.pos.x + self.size.w }
random_line_split
rect.rs
use std::convert::From; use graphics::math::{ self, Scalar }; use { Point, Size }; /// A rectangle. #[derive(Clone, Copy, Debug)] pub struct Rect { /// The position of the top left corner of the rectangle. pub pos: Point, /// The width and height of the rectangle. pub size: Size, } impl<P: Into<Point...
} impl Rect { /// Returns the position of the bottom side of the rectangle. pub fn bottom(&self) -> Scalar { self.pos.y + self.size.h } /// Computes a rectangle with quadruple the surface area of self and with center /// (self.x, self.y). pub fn centered(self) -> Rect { Rect {...
{ Rect { pos: Point { x: x, y: y }, size: Size { w: w, h: h }, } }
identifier_body
rect.rs
use std::convert::From; use graphics::math::{ self, Scalar }; use { Point, Size }; /// A rectangle. #[derive(Clone, Copy, Debug)] pub struct Rect { /// The position of the top left corner of the rectangle. pub pos: Point, /// The width and height of the rectangle. pub size: Size, } impl<P: Into<Point...
(v: [Scalar; 4]) -> Rect { Rect { pos: Point { x: v[0], y: v[1] }, size: Size { w: v[2], h: v[3] }, } } } impl From<(Scalar, Scalar, Scalar, Scalar)> for Rect { fn from((x, y, w, h): (Scalar, Scalar, Scalar, Scalar)) -> Rect { Rect { pos: Point { x: x...
from
identifier_name
regepe_flask_server.py
= trackdesc return('<map mapid="%s" lat="%s" lon="%s" date="%s" user="%s">%s</map>' % (mapid,lat,lon,startdate,trackuser,desc)) def latlonmapids2xml(latlonmapids): lat,lon,mapids = latlonmapids return '<maps lat="%.4f" lon="%.4f">%s</maps>' % (lat,lon,''.join(map(lambda mapid:map_search_result2(lat,lon,ma...
"" Check session_id for a given user """ try: ret = CheckSession(user,sess) except Exception, e: out = '<answer><result>Error: %s</result><user>NoUser</user><sess>-1</sess></answer>' % str(e) return Response(out, mimetype='text/xml') if ret: result = 'OK' else: re...
identifier_body
regepe_flask_server.py
idxtodel)) @application.route('/map/export/<mapid>') def exportmap(mapid): # TODO: build it from client side pass @application.route('/map/demize/<int:index>/<mapid>/<pwd>',defaults={'user':None,'sess':None}) @application.route('/map/demize/<int:index>/<mapid>/<pwd>/<user>/<sess>') def demize(index,mapid,pwd,...
repare(
identifier_name
regepe_flask_server.py
Recompute thumbnail previewfile = 'data/thumbnail_cache/%s.png' % mapid if os.access(previewfile,os.F_OK): os.remove(previewfile) message = None except Exception, e: message = str(e) if message==None: return redirect('/showmap/%s'%mapid) else: ret...
tlistmerged[pt.datetime] = pt
conditional_block
regepe_flask_server.py
from textutils import remove_accents from log import Log from mapparser import ParseMap from model import Track from options import options_default from dem import GetEleFromLatLon from computeprofile import ComputeProfile from demize import Demize from generate_id import uniqid from config import keysnpwds, config fro...
from searchparser import SearchQueryParser from sets import Set
random_line_split
ajax.js
/**! * ajax - v0.0.9 * Ajax module in Vanilla JS * https://github.com/fdaciuk/ajax * Wed Aug 26 2015 07:30:42 GMT-0300 (BRT) * MIT (c) Fernando Daciuk */ ; (function(factory) { 'use strict'; var root = (typeof window === 'object' && window.window === window && window) || (typeof global === 'object' && globa...
$private.methods = { done: function() {}, error: function() {}, always: function() {} }; $public.jsonp = function jsonp(url, passedInCallback) { var jsonPcallback = function(data) { // remove from global scope delete root.jsonCallback; return passedInCallback...
{ var t; if (u.indexOf(p + "=") !== -1) { t = u.substring(u.indexOf(p + "=") + (p.length + 1)); if (t.indexOf("&") !== -1) { t = t.substring(0, t.indexOf("&")); } } return t || null; }
identifier_body
ajax.js
/**! * ajax - v0.0.9 * Ajax module in Vanilla JS * https://github.com/fdaciuk/ajax * Wed Aug 26 2015 07:30:42 GMT-0300 (BRT) * MIT (c) Fernando Daciuk */ ; (function(factory) { 'use strict'; var root = (typeof window === 'object' && window.window === window && window) || (typeof global === 'object' && globa...
var $private = {}; var root = r; function getParamUrl(u, p) { var t; if (u.indexOf(p + "=") !== -1) { t = u.substring(u.indexOf(p + "=") + (p.length + 1)); if (t.indexOf("&") !== -1) { t = t.substring(0, t.indexOf("&")); } } return t || null; } ...
function Ajax() { var $public = {};
random_line_split
ajax.js
/**! * ajax - v0.0.9 * Ajax module in Vanilla JS * https://github.com/fdaciuk/ajax * Wed Aug 26 2015 07:30:42 GMT-0300 (BRT) * MIT (c) Fernando Daciuk */ ; (function(factory) { 'use strict'; var root = (typeof window === 'object' && window.window === window && window) || (typeof global === 'object' && globa...
() { var $public = {}; var $private = {}; var root = r; function getParamUrl(u, p) { var t; if (u.indexOf(p + "=") !== -1) { t = u.substring(u.indexOf(p + "=") + (p.length + 1)); if (t.indexOf("&") !== -1) { t = t.substring(0, t.indexOf("&")); } } ...
Ajax
identifier_name
clock.ts
{ /** * The date to display in this clock view. */ @Input() get activeDate(): Date { return this._activeDate; } set activeDate(value: Date) { let oldActiveDate = this._activeDate; this._activeDate = this._util.clampDate(value, this.min, this.max); if (!this._util.isSameMinute(oldActiveDate, t...
date.setMinutes(value); }
random_line_split
clock.ts
27.5; export const CLOCK_OUTER_RADIUS = 41.25; export const CLOCK_TICK_RADIUS = 7.0833; export type ClockView = 'hour' | 'minute'; /** * A clock that is used as part of the datepicker. * @docs-private */ @Component({ moduleId: module.id, selector: 'md2-clock', templateUrl: 'clock.html', styleUrls: ['clock....
/** Handles minute selection in the clock view. */ _minuteSelected(): void { this._hourView = true; } /** Handles mousedown events on the clock body. */ _handleMousedown(event: any) { this.setTime(event); document.addEventListener('mousemove', this.mouseMoveListener); document.addEventListe...
{ this._hourView = false; }
identifier_body
clock.ts
27.5; export const CLOCK_OUTER_RADIUS = 41.25; export const CLOCK_TICK_RADIUS = 7.0833; export type ClockView = 'hour' | 'minute'; /** * A clock that is used as part of the datepicker. * @docs-private */ @Component({ moduleId: module.id, selector: 'md2-clock', templateUrl: 'clock.html', styleUrls: ['clock....
else { for (let i = 0; i < 24; i++) { let radian = i / 6 * Math.PI; let outer = i > 0 && i < 13, radius = outer ? CLOCK_OUTER_RADIUS : CLOCK_INNER_RADIUS; let date = new Date(this.activeDate.getTime()); date.setHours(i + 1, 0, 0, 0); let enabled = this._util.isDa...
{ for (let i = 1; i < 13; i++) { let radian = i / 6 * Math.PI; let radius = CLOCK_OUTER_RADIUS; let date = new Date(this.activeDate.getTime()); date.setHours(i + 1, 0, 0, 0); let enabled = this._util.isDateWithinRange1(date, this.min, this.max); this._hours.push({ ...
conditional_block
clock.ts
27.5; export const CLOCK_OUTER_RADIUS = 41.25; export const CLOCK_TICK_RADIUS = 7.0833; export type ClockView = 'hour' | 'minute'; /** * A clock that is used as part of the datepicker. * @docs-private */ @Component({ moduleId: module.id, selector: 'md2-clock', templateUrl: 'clock.html', styleUrls: ['clock....
(): Date { return this._min; } set min(date: Date) { this._min = this._util.parse(date); } private _min: Date; /** The maximum selectable date. */ @Input() get max(): Date { return this._max; } set max(date: Date) { this._max = this._util.parse(date); } private _max: Date; /** Whether the clock should...
min
identifier_name
bounding_box_tracker.ts
/** * @license * Copyright 2021 Google LLC. 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by ...
const intersection = (xMax - xMin) * (yMax - yMin); const areaPose = pose.box.width * pose.box.height; const areaTrack = track.box.width * track.box.height; return intersection / (areaPose + areaTrack - intersection); } }
{ return 0.0; }
conditional_block
bounding_box_tracker.ts
/** * @license * Copyright 2021 Google LLC. All Rights Reserved.
* you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://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 WARRA...
* Licensed under the Apache License, Version 2.0 (the "License");
random_line_split
bounding_box_tracker.ts
/** * @license * Copyright 2021 Google LLC. 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by ...
(poses: Pose[]): number[][] { if (poses.length === 0 || this.tracks.length === 0) { return [[]]; } const simMatrix = poses.map(pose => { return this.tracks.map(track => { return this.iou(pose, track); }); }); return simMatrix; } /** * Computes the intersection-over-...
computeSimilarity
identifier_name