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
parse.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2008-2009 Zuza Software Foundation # # This file is part of the Translate Toolkit. # # 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 Software Foundation; e...
one argument (a ``unicode`` string to parse) and return a list of ``StringElem``s which, together, form the original string. If nothing could be parsed, it should return ``None``. """ if isinstance(tree, six.text_typ...
``parse_funcs``. :type tree: unicode|StringElem :param tree: The string or string element sub-tree to parse. :type parse_funcs: A list of parsing functions. It must take exactly
random_line_split
apachelogs_test.py
''' Simple test for apachelogs ''' import unittest from apachelogs import ApacheLogFile class apachelogs_test(unittest.TestCase): def test_foo(self): log = ApacheLogFile('test.log') line = iter(log).next() self.assertEquals(line.ip, '127.0.0.1') self.assertEquals(line.ident, '-...
unittest.main()
conditional_block
apachelogs_test.py
''' Simple test for apachelogs ''' import unittest from apachelogs import ApacheLogFile class apachelogs_test(unittest.TestCase): def test_foo(self):
def setUp(self): pass if __name__ == '__main__': unittest.main()
log = ApacheLogFile('test.log') line = iter(log).next() self.assertEquals(line.ip, '127.0.0.1') self.assertEquals(line.ident, '-') self.assertEquals(line.http_user, 'frank') self.assertEquals(line.time, '5/Oct/2000:13:55:36 -0700') self.assertEquals(line.request_line...
identifier_body
apachelogs_test.py
''' Simple test for apachelogs ''' import unittest from apachelogs import ApacheLogFile class apachelogs_test(unittest.TestCase): def test_foo(self): log = ApacheLogFile('test.log') line = iter(log).next() self.assertEquals(line.ip, '127.0.0.1') self.assertEquals(line.ident, '-...
if __name__ == '__main__': unittest.main()
random_line_split
apachelogs_test.py
''' Simple test for apachelogs ''' import unittest from apachelogs import ApacheLogFile class apachelogs_test(unittest.TestCase): def
(self): log = ApacheLogFile('test.log') line = iter(log).next() self.assertEquals(line.ip, '127.0.0.1') self.assertEquals(line.ident, '-') self.assertEquals(line.http_user, 'frank') self.assertEquals(line.time, '5/Oct/2000:13:55:36 -0700') self.assertEquals(l...
test_foo
identifier_name
imgui_demo.rs
(state: &DemoGLState, draw_data: &mut imgui::ImDrawData) { use std::mem; let io = imgui::get_io(); let fb_width = io.display_size.x * io.display_framebuffer_scale.x; let fb_height = io.display_size.y * io.display_framebuffer_scale.y; if fb_width == 0.0 || fb_height == 0.0 { return; } // draw_data.scale_clip_rect...
imgui_render_draw_lists
identifier_name
imgui_demo.rs
0]), gl::STREAM_DRAW ); gl::BindBuffer(gl::ELEMENT_ARRAY_BUFFER, state.elements_handle); gl::BufferData( gl::ELEMENT_ARRAY_BUFFER, (cmd_list.idx_buffer.size * mem::size_of::<imgui::ImDrawIdx>() as i32) as isize, mem::transmute(&cmd_list.idx_buffer[0]), gl::STREAM_DRAW ); for pcmd_idx in 0..c...
pub fn imgui_new_frame(state: &mut DemoGLState, window_size: (u32, u32), hidpi_factor: f32) { if state.font_texture == 0 { unsafe { imgui_create_device_objects(state) }; } let io = imgui::get_io(); let (w, h) = window_size; let hidpi_factor = hidpi_factor; io.display_size = imgui::vec2(w as f32, h as f32);...
{ for i in 0..draw_data.cmd_lists_count { let cmd_list = unsafe { (*draw_data.cmd_lists.offset(i as isize)).as_mut() .expect("Indexing CMD list in placeholder_scale_clip_rects") }; for cmd_i in 0..cmd_list.cmd_buffer.size { let imgui::ImVec4 {x, y, z, w} = cmd_list.cmd_buffer[cmd_i as usize].clip_rect;...
identifier_body
imgui_demo.rs
.mouse_pressed[0]); io.mouse_down[1] = imgui::cbool(state.mouse_pressed[1]); io.mouse_down[2] = imgui::cbool(state.mouse_pressed[2]); io.mouse_wheel = state.mouse_wheel; state.mouse_wheel = 0.0; imgui::new_frame(); } pub unsafe fn imgui_create_device_objects(state: &mut DemoGLState) { use std::mem; // Backing...
{ use std::ptr; gl::DeleteTextures(1, &state.font_texture); imgui::get_io().fonts.tex_id = ptr::null_mut(); state.font_texture = 0; }
conditional_block
imgui_demo.rs
[0]), gl::STREAM_DRAW ); gl::BindBuffer(gl::ELEMENT_ARRAY_BUFFER, state.elements_handle); gl::BufferData( gl::ELEMENT_ARRAY_BUFFER, (cmd_list.idx_buffer.size * mem::size_of::<imgui::ImDrawIdx>() as i32) as isize, mem::transmute(&cmd_list.idx_buffer[0]), gl::STREAM_DRAW ); for pcmd_idx in 0.....
else { gl::Disable(gl::CULL_FACE) } if last_enable_depth_test != 0 { gl::Enable(gl::DEPTH_TEST); } else { gl::Disable(gl::DEPTH_TEST); } if last_enable_scissor_test != 0 { gl::Enable(gl::SCISSOR_TEST); } else { gl::Disable(gl::SCISSOR_TEST); } gl::Viewport(last_viewport[0], last_viewport[1], last_viewport[2], ...
random_line_split
service.ts
// TODO debug only? import {assert} from './assert'; import {makeDecorator, getAnnotations, mergeAnnotations} from './reflection'; import {setIfInterface, isFunction} from './utils'; /** * Options available when decorating a class as a service */ export interface ServiceOptions { /** * The name the service...
(options: ServiceOptions) { // TODO debug only? assert.notNull(options, 'options must not be null'); assert.notEmpty(options.name, 'name cannot be null or empty'); setIfInterface(this, options); } } /** * Interface services may implement */ export interface Service { } /** * ...
constructor
identifier_name
service.ts
// TODO debug only? import {assert} from './assert'; import {makeDecorator, getAnnotations, mergeAnnotations} from './reflection'; import {setIfInterface, isFunction} from './utils'; /** * Options available when decorating a class as a service */ export interface ServiceOptions { /** * The name the service...
} else { ngModule.service(name, serviceClass); } return ngModule; }
{ // Reflect.decorate apply decorators reversely, so we need to reverse // the extracted annotations before merging them // var aux = getAnnotations(serviceClass, ServiceAnnotation).reverse(); var aux = getAnnotations(serviceClass, ServiceAnnotation); // TODO debug only? assert.notEmpty(aux, '...
identifier_body
service.ts
// TODO debug only? import {assert} from './assert'; import {makeDecorator, getAnnotations, mergeAnnotations} from './reflection'; import {setIfInterface, isFunction} from './utils'; /** * Options available when decorating a class as a service */ export interface ServiceOptions { /** * The name the service...
}
random_line_split
service.ts
// TODO debug only? import {assert} from './assert'; import {makeDecorator, getAnnotations, mergeAnnotations} from './reflection'; import {setIfInterface, isFunction} from './utils'; /** * Options available when decorating a class as a service */ export interface ServiceOptions { /** * The name the service...
return ngModule; }
{ ngModule.service(name, serviceClass); }
conditional_block
__init__.py
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
"VulnerabilityReport", )
random_line_split
slot.py
# This file is part of PARPG. # PARPG 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. # PARPG is distributed in the hope ...
(self): return self._image image = property(_getImage, _setImage)
_getImage
identifier_name
slot.py
# This file is part of PARPG. # PARPG 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. # PARPG is distributed in the hope ...
image = property(_getImage, _setImage)
return self._image
identifier_body
slot.py
# This file is part of PARPG.
# the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # PARPG is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General...
# PARPG is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by
random_line_split
interfaceorg_1_1onosproject_1_1net_1_1flow_1_1StoredFlowEntry.js
var interfaceorg_1_1onosproject_1_1net_1_1flow_1_1StoredFlowEntry = [ [ "setBytes", "interfaceorg_1_1onosproject_1_1net_1_1flow_1_1StoredFlowEntry.html#abcee4c5061efc787a287d076123efd1d", null ], [ "setLastSeen", "interfaceorg_1_1onosproject_1_1net_1_1flow_1_1StoredFlowEntry.html#acb36228a788838ba7138144b79c4aa...
[ "setPackets", "interfaceorg_1_1onosproject_1_1net_1_1flow_1_1StoredFlowEntry.html#aec00b06ee9dc6adf1ce4f841e11713b4", null ], [ "setState", "interfaceorg_1_1onosproject_1_1net_1_1flow_1_1StoredFlowEntry.html#aa3ec6f5b30996739a2541dceb76c6f75", null ] ];
random_line_split
writer-opts.js
'use strict' const Q = require(`q`) const readFile = Q.denodeify(require(`fs`).readFile) const resolve = require(`path`).resolve module.exports = Q.all([ readFile(resolve(__dirname, './templates/template.hbs'), 'utf-8'), readFile(resolve(__dirname, './templates/header.hbs'), 'utf-8'), readFile(resolve(__dirname...
{ return { transform: (commit) => { if (!commit.language) { return } if (typeof commit.hash === `string`) { commit.hash = commit.hash.substring(0, 7) } return commit }, groupBy: `language`, commitGroupsSort: `title`, commitsSort: [`language`, `type`,...
identifier_body
writer-opts.js
'use strict' const Q = require(`q`) const readFile = Q.denodeify(require(`fs`).readFile) const resolve = require(`path`).resolve module.exports = Q.all([ readFile(resolve(__dirname, './templates/template.hbs'), 'utf-8'), readFile(resolve(__dirname, './templates/header.hbs'), 'utf-8'), readFile(resolve(__dirname...
() { return { transform: (commit) => { if (!commit.language) { return } if (typeof commit.hash === `string`) { commit.hash = commit.hash.substring(0, 7) } return commit }, groupBy: `language`, commitGroupsSort: `title`, commitsSort: [`language`, `ty...
getWriterOpts
identifier_name
writer-opts.js
'use strict' const Q = require(`q`) const readFile = Q.denodeify(require(`fs`).readFile) const resolve = require(`path`).resolve module.exports = Q.all([ readFile(resolve(__dirname, './templates/template.hbs'), 'utf-8'), readFile(resolve(__dirname, './templates/header.hbs'), 'utf-8'), readFile(resolve(__dirname...
return commit }, groupBy: `language`, commitGroupsSort: `title`, commitsSort: [`language`, `type`, `message`] } }
{ commit.hash = commit.hash.substring(0, 7) }
conditional_block
writer-opts.js
'use strict' const Q = require(`q`) const readFile = Q.denodeify(require(`fs`).readFile) const resolve = require(`path`).resolve module.exports = Q.all([ readFile(resolve(__dirname, './templates/template.hbs'), 'utf-8'), readFile(resolve(__dirname, './templates/header.hbs'), 'utf-8'), readFile(resolve(__dirname...
writerOpts.mainTemplate = template writerOpts.headerPartial = header writerOpts.commitPartial = commit return writerOpts }) function getWriterOpts () { return { transform: (commit) => { if (!commit.language) { return } if (typeof commit.hash === `string`) { c...
.spread((template, header, commit) => { const writerOpts = getWriterOpts()
random_line_split
LC_375_Guess_Number_Higher_or_Lower_II.py
#!/usr/bin/env python #coding=utf8 ''' We are playing the Guess Game. The game is as follows: I pick a number from 1 to n. You have to guess which number I picked. Every time you guess wrong, I'll tell you whether the number I picked is higher or lower. However, when you guess a particular number x, and you guess w...
for k in xrange(1, n-1): for i in xrange(n-k): mini = min(f[i][i] + f[i+1][i+k], f[i][i+k-1] + f[i+k][i+k]) for x in xrange(i+1, i+k): mini = min(mini, f[x][x] + max(f[i][x-1], f[x+1][i+k]) ) f[i][i+k] = mini print ...
i][i] = i + 1
conditional_block
LC_375_Guess_Number_Higher_or_Lower_II.py
#!/usr/bin/env python #coding=utf8 ''' We are playing the Guess Game. The game is as follows: I pick a number from 1 to n. You have to guess which number I picked. Every time you guess wrong, I'll tell you whether the number I picked is higher or lower. However, when you guess a particular number x, and you guess w...
''' import heapq import datetime import time import sys import collections class Solution(object): def getMoneyAmount(self, n): """ :type n: int :rtype: int """ if not n or n==1: return 0 f = [[0]*n for _ in xrange(n)] for i in xrange(n): ...
@author: Chauncey beat 24.02%
random_line_split
LC_375_Guess_Number_Higher_or_Lower_II.py
#!/usr/bin/env python #coding=utf8 ''' We are playing the Guess Game. The game is as follows: I pick a number from 1 to n. You have to guess which number I picked. Every time you guess wrong, I'll tell you whether the number I picked is higher or lower. However, when you guess a particular number x, and you guess w...
mini = min(mini, max(f[0][x-1], f[x+1][n-1]) ) f[0][n-1] = mini return f[0][n-1] if __name__ == '__main__': solution = Solution() start_time = datetime.datetime.now() #print solution.getMoneyAmount(10) # print solution.getMoneyAmount(1) #0 print solution.getMoneyAmoun...
" :type n: int :rtype: int """ if not n or n==1: return 0 f = [[0]*n for _ in xrange(n)] for i in xrange(n): f[i][i] = i + 1 for k in xrange(1, n-1): for i in xrange(n-k): mini = min(f[i][i] + f[i+1][i+k], f[i]...
identifier_body
LC_375_Guess_Number_Higher_or_Lower_II.py
#!/usr/bin/env python #coding=utf8 ''' We are playing the Guess Game. The game is as follows: I pick a number from 1 to n. You have to guess which number I picked. Every time you guess wrong, I'll tell you whether the number I picked is higher or lower. However, when you guess a particular number x, and you guess w...
bject): def getMoneyAmount(self, n): """ :type n: int :rtype: int """ if not n or n==1: return 0 f = [[0]*n for _ in xrange(n)] for i in xrange(n): f[i][i] = i + 1 for k in xrange(1, n-1): for i in xrange(n-k): ...
lution(o
identifier_name
os_sv_list_display.js
/** * */ (function ($) { var data = {}; Drupal.behaviors.os_sv_list = { attach: function (ctx) { // add a click handler $(ctx).find('.block-boxes-os_sv_list_box', ctx).click(click_handler).each(function () { // save the current page to our cache // get the delta of the box a...
(elem) { return elem.id.replace('block-boxes-', ''); } })(jQuery);
get_delta
identifier_name
os_sv_list_display.js
/** * */ (function ($) { var data = {}; Drupal.behaviors.os_sv_list = { attach: function (ctx) { // add a click handler $(ctx).find('.block-boxes-os_sv_list_box', ctx).click(click_handler).each(function () { // save the current page to our cache // get the delta of the box a...
if ($(e.target).parents('.pager').length == 0 || e.target.nodeName != 'A') return; e.stopPropagation(); e.preventDefault(); // get the requested page and delta from the query args var args = query_args(e.target.href), delta = args.sv_list_box_delta; ...
function click_handler(e) { // do nothing if this isn't a pager link
random_line_split
os_sv_list_display.js
/** * */ (function ($) { var data = {}; Drupal.behaviors.os_sv_list = { attach: function (ctx) { // add a click handler $(ctx).find('.block-boxes-os_sv_list_box', ctx).click(click_handler).each(function () { // save the current page to our cache // get the delta of the box a...
function get_delta(elem) { return elem.id.replace('block-boxes-', ''); } })(jQuery);
{ var frags = url.split('?'), args = {}; frags = frags[1].split('&'); for (var i=0; i<frags.length; i++) { var arg = frags[i].split('='); args[arg[0]] = arg[1]; } return args; }
identifier_body
os_sv_list_display.js
/** * */ (function ($) { var data = {}; Drupal.behaviors.os_sv_list = { attach: function (ctx) { // add a click handler $(ctx).find('.block-boxes-os_sv_list_box', ctx).click(click_handler).each(function () { // save the current page to our cache // get the delta of the box a...
&& commands[i].data != "") { html = commands[i].data; break; } } // replace the existing page with the new one parent.html(html); Drupal.attachBehaviors(parent); // and add it ...
{ var s = Drupal.settings, page = decodeURIComponent(args.page).split(','); page = page[args.pager_id]; $.ajax({ url: s.basePath + (typeof s.pathPrefix != 'undefined'?s.pathPrefix:'') + 'os_sv_list/page/'+delta, data: { page: page ...
conditional_block
portal_upload.js
/* [Discuz!] (C)2001-2099 Comsenz Inc. This is NOT a freeware, use is subject to license terms $Id: portal_upload.js 32590 2013-02-22 09:42:48Z monkey $ */ var nowid = 0; var extensions = ''; function addAttach()
} nowid++; $('attachbody').appendChild(newnode); } function insertAttach(id) { var path = $('attach_' + id).value; if(path == '') { return; } var ext = path.lastIndexOf('.') == -1 ? '' : path.substr(path.lastIndexOf('.') + 1, path.length).toLowerCase(); var re = new RegExp("(^|\\s|,)" + ext + "($|\\s|,)",...
{ var newnode = $('upload').cloneNode(true); var id = nowid; var tags; newnode.id = 'upload_' + id; tags = newnode.getElementsByTagName('input'); for(i = 0;i < tags.length;i++) { if(tags[i].name == 'attach') { tags[i].id = 'attach_' + id; tags[i].name = 'attach'; tags[i].onchange = function() {this.fo...
identifier_body
portal_upload.js
/* [Discuz!] (C)2001-2099 Comsenz Inc. This is NOT a freeware, use is subject to license terms $Id: portal_upload.js 32590 2013-02-22 09:42:48Z monkey $ */ var nowid = 0; var extensions = ''; function addAttach() { var newnode = $('upload').cloneNode(true); var id = nowid; var tags; newnode.id = 'upload_' +...
rl); $('attach_list_' + attachid).style.display = 'none'; } function setConver(attach) { $('conver').value = attach; } addAttach();
{ ajaxget(u
identifier_name
portal_upload.js
/* [Discuz!] (C)2001-2099 Comsenz Inc. This is NOT a freeware, use is subject to license terms $Id: portal_upload.js 32590 2013-02-22 09:42:48Z monkey $ */ var nowid = 0; var extensions = ''; function addAttach() { var newnode = $('upload').cloneNode(true); var id = nowid; var tags; newnode.id = 'upload_' +...
nowid++; $('attachbody').appendChild(newnode); } function insertAttach(id) { var path = $('attach_' + id).value; if(path == '') { return; } var ext = path.lastIndexOf('.') == -1 ? '' : path.substr(path.lastIndexOf('.') + 1, path.length).toLowerCase(); var re = new RegExp("(^|\\s|,)" + ext + "($|\\s|,)", "i...
{ if(tags[i].id == 'localfile') { tags[i].id = 'localfile_' + id; } }
conditional_block
portal_upload.js
/* [Discuz!] (C)2001-2099 Comsenz Inc. This is NOT a freeware, use is subject to license terms $Id: portal_upload.js 32590 2013-02-22 09:42:48Z monkey $ */ var nowid = 0; var extensions = ''; function addAttach() { var newnode = $('upload').cloneNode(true);
tags = newnode.getElementsByTagName('input'); for(i = 0;i < tags.length;i++) { if(tags[i].name == 'attach') { tags[i].id = 'attach_' + id; tags[i].name = 'attach'; tags[i].onchange = function() {this.form.action = this.form.action.replace(/catid\=\d/, 'catid='+$('catid').value);insertAttach(id)}; tags[i...
var id = nowid; var tags; newnode.id = 'upload_' + id;
random_line_split
introHCI.js
'use strict'; // Call this function when the page loads (the "ready" event) $(document).ready(function() { initializePage(); }) /* * Function that is called when the document is ready. */ function initializePage() { $('.project a').click(addProjectDetails); $('#colorBtn').click(randomizeColors); $('#apibutton...
function getExternalApi(e) { e.preventDefault(); $.get('https://api.spotify.com/v1/artists/4dpARuHxo51G3z768sgnrY', getAPI); } function getAPI(result) { console.log(result); var images = result['images']; console.log(images); var adeleHTML = '<h1>' + result['name'] + '</h1>' + '<p> popularity: ' + result['po...
console.log(result); var colors = result['colors']['hex']; $('body').css('background-color', colors[0]); $('.thumbnail').css('background-color', colors[1]); $('h1, h2, h3, h4, h5, h5').css('color', colors[2]); $('p').css('color', colors[3]); $('.project img').css('opacity', .75); }
identifier_body
introHCI.js
'use strict'; // Call this function when the page loads (the "ready" event) $(document).ready(function() { initializePage(); }) /* * Function that is called when the document is ready. */ function initializePage() { $('.project a').click(addProjectDetails); $('#colorBtn').click(randomizeColors); $('#apibutton...
'<img src="' + result['image'] + '" class="detalsImage">' + '<p>' + result['title'] + '</p>' + '<p> <small>' + result['date'] + '</small></p>' + '<p>' + result['summary'] + '</p> </a>'; $("#project" + result['id'] + " .details").html(projectHTML);
 } /* * Make an AJAX call to retrieve a color pal...
var projectHTML = '<a href="#" class="thumbnail">' +
random_line_split
introHCI.js
'use strict'; // Call this function when the page loads (the "ready" event) $(document).ready(function() { initializePage(); }) /* * Function that is called when the document is ready. */ function initializePage() { $('.project a').click(addProjectDetails); $('#colorBtn').click(randomizeColors); $('#apibutton...
) { e.preventDefault(); $.get('https://api.spotify.com/v1/artists/4dpARuHxo51G3z768sgnrY', getAPI); } function getAPI(result) { console.log(result); var images = result['images']; console.log(images); var adeleHTML = '<h1>' + result['name'] + '</h1>' + '<p> popularity: ' + result['popularity'] + '</p>' + '<...
tExternalApi(e
identifier_name
__init__.py
# # @BEGIN LICENSE # # Psi4: an open-source quantum chemistry software package #
# # This file is part of Psi4. # # Psi4 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 3. # # Psi4 is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even th...
# Copyright (c) 2007-2022 The Psi4 Developers. # # The copyrights for code used from other parties are included in # the corresponding files.
random_line_split
conf.py
.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. #...
# -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options ava...
random_line_split
geometry.rs
(Encodable)] pub enum DevicePixel {} /// A normalized "pixel" at the default resolution for the display. /// /// Like the CSS "px" unit, the exact physical size of this unit may vary between devices, but it /// should approximate a device-independent reference length. This unit corresponds to Android's /// "density-i...
} #[inline] pub fn max(x: Au, y: Au) -> Au { if x > y { x } else { y } } impl NumCast for Au { #[inline] fn from<T:ToPrimitive>(n: T) -> Option<Au> { Some(Au(n.to_i32().unwrap())) } } impl ToPrimitive for Au { #[inline] fn to_i64(&self) -> Option<i64> { let Au(s) = *self; ...
{ y }
conditional_block
geometry.rs
(Encodable)] pub enum DevicePixel {} /// A normalized "pixel" at the default resolution for the display. /// /// Like the CSS "px" unit, the exact physical size of this unit may vary between devices, but it /// should approximate a device-independent reference length. This unit corresponds to Android's /// "density-i...
impl Mul<Au,Au> for Au { #[inline] fn mul(&self, other: &Au) -> Au { let Au(s) = *self; let Au(o) = *other; Au(s * o) } } impl Div<Au,Au> for Au { #[inline] fn div(&self, other: &Au) -> Au { let Au(s) = *self; let Au(o) = *other; Au(s / o) } } im...
Au(s - o) } }
random_line_split
geometry.rs
(Encodable)] pub enum DevicePixel {} /// A normalized "pixel" at the default resolution for the display. /// /// Like the CSS "px" unit, the exact physical size of this unit may vary between devices, but it /// should approximate a device-independent reference length. This unit corresponds to Android's /// "density-i...
} impl Sub<Au,Au> for Au { #[inline] fn sub(&self, other: &Au) -> Au { let Au(s) = *self; let Au(o) = *other; Au(s - o) } } impl Mul<Au,Au> for Au { #[inline] fn mul(&self, other: &Au) -> Au { let Au(s) = *self; let Au(o) = *other; Au(s * o) } ...
{ let Au(s) = *self; let Au(o) = *other; Au(s + o) }
identifier_body
geometry.rs
(Encodable)] pub enum DevicePixel {} /// A normalized "pixel" at the default resolution for the display. /// /// Like the CSS "px" unit, the exact physical size of this unit may vary between devices, but it /// should approximate a device-independent reference length. This unit corresponds to Android's /// "density-i...
(&self) -> int { let Au(s) = *self; ((s as f64) / 60f64).round() as int } #[inline] pub fn to_snapped(&self) -> Au { let Au(s) = *self; let res = s % 60i32; return if res >= 30i32 { return Au(s - res + 60i32) } else { return Au(s - res) }; ...
to_nearest_px
identifier_name
InventoryBody.tsx
} // #region Container constants const CONTAINER_PADDING_RIGHT = 10; const CONTAINER_PADDING_TOP = 30; // #endregion const Container = styled.div` position: relative; flex: 1 1 auto; display: flex; flex-direction: column; padding-right: ${CONTAINER_PADDING_RIGHT}px; padding-top: ${CONTAINER_PADDING_TOP}px;...
() { this.initializeSlotsData(); this.initBodyDimensionsTimeout = window.setTimeout(() => this.initializeBodyDimensions(true), 1); window.addEventListener('optimizedResize', () => { this.initializeBodyDimensions(true); }); this.dropItemHandler = game.on(eventNames.onDropItem, (payload: DropIte...
componentDidMount
identifier_name
InventoryBody.tsx
; } // #region Container constants const CONTAINER_PADDING_RIGHT = 10; const CONTAINER_PADDING_TOP = 30; // #endregion const Container = styled.div` position: relative; flex: 1 1 auto; display: flex; flex-direction: column; padding-right: ${CONTAINER_PADDING_RIGHT}px; padding-top: ${CONTAINER_PADDING_TOP}p...
if (!this.props.invBodyDimensions.width || !
} private initializeBodyDimensions = (override?: boolean) => { if (!this.bodyRef) return;
random_line_split
InventoryBody.tsx
} // #region Container constants const CONTAINER_PADDING_RIGHT = 10; const CONTAINER_PADDING_TOP = 30; // #endregion const Container = styled.div` position: relative; flex: 1 1 auto; display: flex; flex-direction: column; padding-right: ${CONTAINER_PADDING_RIGHT}px; padding-top: ${CONTAINER_PADDING_TOP}px;...
const { graphql } = this.props; const showLoading = graphql.loading; const showError = graphql.lastError && graphql.lastError !== 'OK'; const { rows, rowData } = base.createRowElements({ state: this.state, props: this.props, itemData: { items: this.props.inventoryItems }, onDrop...
{ let slotNumberToItem = this.props.slotNumberToItem; let itemIdToInfo = this.props.itemIdToInfo; if (hasActiveFilterButtons(this.props.activeFilters) || hasFilterText(this.props.searchValue)) { // Is being filtered const filteredData = base.distributeFilteredItems({ itemData: { items: ...
identifier_body
InventoryBody.tsx
} // #region Container constants const CONTAINER_PADDING_RIGHT = 10; const CONTAINER_PADDING_TOP = 30; // #endregion const Container = styled.div` position: relative; flex: 1 1 auto; display: flex; flex-direction: column; padding-right: ${CONTAINER_PADDING_RIGHT}px; padding-top: ${CONTAINER_PADDING_TOP}px;...
} public componentWillUnmount() { this.dropItemHandler.clear(); window.clearTimeout(this.initBodyDimensionsTimeout); window.removeEventListener('optimizedResize', () => this.initializeBodyDimensions(true)); } private refetch = () => { this.props.graphql.refetch(); } private initializeBod...
{ this.bodyRef.scrollTop = 0; }
conditional_block
option.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
#[test] fn test_get_resource() { use std::rc::Rc; use core::cell::RefCell; struct R { i: Rc<RefCell<int>>, } #[unsafe_destructor] impl Drop for R { fn drop(&mut self) { let ii = &*self.i; let i = *ii.borrow(); *ii.borrow_mut() = i + 1; ...
{ let x = "test".to_string(); let addr_x = x.as_ptr(); let opt = Some(x); let y = opt.unwrap(); let addr_y = y.as_ptr(); assert_eq!(addr_x, addr_y); }
identifier_body
option.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ i: Rc<RefCell<int>>, } #[unsafe_destructor] impl Drop for R { fn drop(&mut self) { let ii = &*self.i; let i = *ii.borrow(); *ii.borrow_mut() = i + 1; } } fn r(i: Rc<RefCell<int>>) -> R { R { i: i } } ...
R
identifier_name
option.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
// test that it does not take more elements than it needs let mut functions: [Box<Fn() -> Option<()>>; 3] = [box || Some(()), box || None, box || panic!()]; let v: Option<Vec<()>> = functions.iter_mut().map(|f| (*f)()).collect(); assert!(v == None); } */ #[test] fn test_cloned() { let val...
if x > 1 { None } else { Some(x) } }).collect(); assert!(v == None);
random_line_split
ngfuse.service.ts
import { Injectable } from '@angular/core'; import * as Fuse from 'fuse.js'; @Injectable() export class NgFuseService { defaults: NgFuseOptions = { shouldSort: true, threshold: 0.4, location: 0, distance: 100, maxPatternLength: 32, minMatchCharLength: 1, ...
else { return collection; } }; } export interface NgFuseOptions extends Fuse.FuseOptions { minSearchStringLenght?: 1; }
{ const fuse = new Fuse(collection, this.searchOptions); results = fuse.search(searchString); return results; }
conditional_block
ngfuse.service.ts
import { Injectable } from '@angular/core'; import * as Fuse from 'fuse.js'; @Injectable() export class NgFuseService { defaults: NgFuseOptions = { shouldSort: true, threshold: 0.4, location: 0, distance: 100, maxPatternLength: 32, minMatchCharLength: 1, ...
() { }; search(collection: Array<Object>, searchString: string, options: NgFuseOptions = {}) { Object.assign(this.searchOptions, this.defaults, options); let results = [] if (searchString && searchString.length >= this.searchOptions.minSearchStringLenght) { const fuse = ...
constructor
identifier_name
ngfuse.service.ts
import { Injectable } from '@angular/core'; import * as Fuse from 'fuse.js'; @Injectable() export class NgFuseService { defaults: NgFuseOptions = { shouldSort: true, threshold: 0.4, location: 0, distance: 100, maxPatternLength: 32, minMatchCharLength: 1, ...
constructor() { }; search(collection: Array<Object>, searchString: string, options: NgFuseOptions = {}) { Object.assign(this.searchOptions, this.defaults, options); let results = [] if (searchString && searchString.length >= this.searchOptions.minSearchStringLenght) { ...
searchOptions: NgFuseOptions = this.defaults;
random_line_split
SingularSudoDocker.ts
import {InstanceManager} from "../lib/instanceManager"; import {SudoDockerContainers} from "../lib/sudoDockerContainers"; const options = { serverConfig: { port: 8002, MATH_PROGRAM: "Singular", MATH_PROGRAM_COMMAND: "Singular", CONTAINERS(resources, hostConfig, guestInstance): InstanceManager
, resumeString: "Type 'listvar();' to print the list of " + "existing variables.\n" + "Type 'basering;' to print the currently active ring.\n> ", }, hostConfig: { containerType: "singular_container", }, startInstance: { host: "127.0.0.1", sshKey: process.env.HOME + "/InteractiveShell/set...
{ return new SudoDockerContainers(resources, hostConfig, guestInstance); }
identifier_body
SingularSudoDocker.ts
import {InstanceManager} from "../lib/instanceManager"; import {SudoDockerContainers} from "../lib/sudoDockerContainers"; const options = { serverConfig: { port: 8002, MATH_PROGRAM: "Singular", MATH_PROGRAM_COMMAND: "Singular",
(resources, hostConfig, guestInstance): InstanceManager { return new SudoDockerContainers(resources, hostConfig, guestInstance); }, resumeString: "Type 'listvar();' to print the list of " + "existing variables.\n" + "Type 'basering;' to print the currently active ring.\n> ", }, hostConfig: { ...
CONTAINERS
identifier_name
SingularSudoDocker.ts
import {InstanceManager} from "../lib/instanceManager"; import {SudoDockerContainers} from "../lib/sudoDockerContainers"; const options = { serverConfig: { port: 8002, MATH_PROGRAM: "Singular", MATH_PROGRAM_COMMAND: "Singular", CONTAINERS(resources, hostConfig, guestInstance): InstanceManager { ...
export {options};
random_line_split
htmlimageelement.rs
; use dom::bindings::js::{LayoutJS, Root}; use dom::bindings::refcounted::Trusted; use dom::document::{Document, DocumentHelpers}; use dom::element::AttributeHandlers; use dom::element::ElementTypeId; use dom::event::{Event, EventBubbles, EventCancelable, EventHelpers}; use dom::eventtarget::{EventTarget, EventTargetTy...
Ok(image) } } pub trait LayoutHTMLImageElementHelpers { #[allow(unsafe_code)] unsafe fn image(&self) -> Option<Arc<Image>>; #[allow(unsafe_code)] unsafe fn image_url(&self) -> Option<Url>; } impl LayoutHTMLImageElementHelpers for LayoutJS<HTMLImageElement> { #[allow(unsafe_code)] ...
{ image.SetHeight(h); }
conditional_block
htmlimageelement.rs
Ref; use dom::bindings::js::{LayoutJS, Root}; use dom::bindings::refcounted::Trusted; use dom::document::{Document, DocumentHelpers}; use dom::element::AttributeHandlers; use dom::element::ElementTypeId; use dom::event::{Event, EventBubbles, EventCancelable, EventHelpers}; use dom::eventtarget::{EventTarget, EventTarge...
(localName: DOMString, prefix: Option<DOMString>, document: &Document) -> Root<HTMLImageElement> { let element = HTMLImageElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLImageElementBinding::Wrap) } pub fn Image(gl...
new
identifier_name
htmlimageelement.rs
Ref; use dom::bindings::js::{LayoutJS, Root}; use dom::bindings::refcounted::Trusted; use dom::document::{Document, DocumentHelpers}; use dom::element::AttributeHandlers; use dom::element::ElementTypeId; use dom::event::{Event, EventBubbles, EventCancelable, EventHelpers}; use dom::eventtarget::{EventTarget, EventTarge...
ROUTER.add_route(responder_receiver.to_opaque(), box move |message| { // Return the image via a message to the script task, which marks the element // as dirty and triggers a reflow. let image_response = message.to().unwrap(); ...
random_line_split
jquery-validation-unobtrusive.d.ts
// Type definitions for Microsoft jQuery Unobtrusive Validation v3.2.3 // Project: http://aspnetwebstack.codeplex.com/ // Definitions by: Matt Brooks <https://github.com/EnableSoftware> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../jquery.validation/jquery.validation.d.ts" /> declare namespace MicrosoftJQueryUnobtrusiveValidation { type JQuerySelector = string | Document | Element | JQuery; interface Adapter { name: string; params: string[]; adapt: Function } interface Adapters e...
random_line_split
code_collector.py
#!/usr/bin/env python3 import logging import os import urllib.parse import urllib.request
LOGGER = logging.getLogger(__name__) class CodeCollector(object): """ Class to download source code from a https://bio.tools entry """ ZIP_NAME = "tool.zip" TAR_NAME = "tool.tar" TMP_NAME = "tmp" def __init__(self, biotool): """ :param biotool: Biotool object :typ...
import tarfile from tooldog import TMP_DIR from .utils import *
random_line_split
code_collector.py
#!/usr/bin/env python3 import logging import os import urllib.parse import urllib.request import tarfile from tooldog import TMP_DIR from .utils import * LOGGER = logging.getLogger(__name__) class CodeCollector(object): """ Class to download source code from a https://bio.tools entry """ ZIP_NAME ...
def _get_from_github(self, url): try: zip_url = os.path.join(url, "archive/master.zip") response = urllib.request.urlopen(zip_url) data = response.read() LOGGER.info('Writing data to zip file...') zip_path = os.path.join(TMP_DIR, self.ZIP_NAME) ...
LOGGER.warn("The url ({}) is not a Github url".format(url)) LOGGER.warn("ToolDog only deals with Github repository for the moment...")
conditional_block
code_collector.py
#!/usr/bin/env python3 import logging import os import urllib.parse import urllib.request import tarfile from tooldog import TMP_DIR from .utils import * LOGGER = logging.getLogger(__name__) class CodeCollector(object): """ Class to download source code from a https://bio.tools entry """ ZIP_NAME ...
(self, url): """ Get source code from a repository link :param url: url of the repository :type url: STRING """ # Here we deal with repository, have to use regex to test the url and # use appropriate strategy to get the code depending the type of repository ...
_get_from_repository
identifier_name
code_collector.py
#!/usr/bin/env python3 import logging import os import urllib.parse import urllib.request import tarfile from tooldog import TMP_DIR from .utils import * LOGGER = logging.getLogger(__name__) class CodeCollector(object): """ Class to download source code from a https://bio.tools entry """ ZIP_NAME ...
""" Retrieve source code of the tool using links provided in https://bio.tools """ source_code = None links = self.biotool.informations.links for link in links: link_type = link.type.lower().translate(str.maketrans(' ', '_')) try: source_co...
identifier_body
os_str.rs
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
#[inline] pub fn into_arc(&self) -> Arc<Slice> { let arc: Arc<[u8]> = Arc::from(&self.inner); unsafe { Arc::from_raw(Arc::into_raw(arc) as *const Slice) } } #[inline] pub fn into_rc(&self) -> Rc<Slice> { let rc: Rc<[u8]> = Rc::from(&self.inner); unsafe { Rc::from_r...
{ let boxed: Box<[u8]> = Default::default(); unsafe { mem::transmute(boxed) } }
identifier_body
os_str.rs
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
pub fn to_str(&self) -> Option<&str> { str::from_utf8(&self.inner).ok() } pub fn to_string_lossy(&self) -> Cow<str> { String::from_utf8_lossy(&self.inner) } pub fn to_owned(&self) -> Buf { Buf { inner: self.inner.to_vec() } } #[inline] pub fn into_box(&self) -...
}
random_line_split
os_str.rs
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(capacity: usize) -> Buf { Buf { inner: Vec::with_capacity(capacity) } } #[inline] pub fn clear(&mut self) { self.inner.clear() } #[inline] pub fn capacity(&self) -> usize { self.inner.capacity() } #[inline] pub fn reserve(&mut self, add...
with_capacity
identifier_name
rpc_getchaintips.py
#!/usr/bin/env python3 # Copyright (c) 2014-2018 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test the getchaintips RPC. - introduce a network split - work on chains of different lengths - join th...
# Join the network halves and check that we now have two tips # (at least at the nodes that previously had the short chain). self.join_network () tips = self.nodes[0].getchaintips () assert_equal (len (tips), 2) assert_equal (tips[0], longTip) assert_equal (tip...
longTip = tips[0] assert_equal (longTip['branchlen'], 0) assert_equal (longTip['height'], 220) assert_equal (tips[0]['status'], 'active')
random_line_split
rpc_getchaintips.py
#!/usr/bin/env python3 # Copyright (c) 2014-2018 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test the getchaintips RPC. - introduce a network split - work on chains of different lengths - join th...
GetChainTipsTest ().main ()
conditional_block
rpc_getchaintips.py
#!/usr/bin/env python3 # Copyright (c) 2014-2018 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test the getchaintips RPC. - introduce a network split - work on chains of different lengths - join th...
def run_test(self): tips = self.nodes[0].getchaintips() assert_equal(len(tips), 1) assert_equal(tips[0]['branchlen'], 0) assert_equal(tips[0]['height'], 200) assert_equal(tips[0]['status'], 'active') # Split the network and build two chains of different lengths. ...
self.num_nodes = 4
identifier_body
rpc_getchaintips.py
#!/usr/bin/env python3 # Copyright (c) 2014-2018 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test the getchaintips RPC. - introduce a network split - work on chains of different lengths - join th...
(self): self.num_nodes = 4 def run_test(self): tips = self.nodes[0].getchaintips() assert_equal(len(tips), 1) assert_equal(tips[0]['branchlen'], 0) assert_equal(tips[0]['height'], 200) assert_equal(tips[0]['status'], 'active') # Split the network and build t...
set_test_params
identifier_name
bitwise_operators.py
#!/usr/bin/python a = 60 # 60 = 2b00111100 b = 13 # 13 = 2b00001101 c = 0 # 0 = 2b00000000 c = a & b # 12 = 2b00001100 print "Line 1: Value of c = a & b is: ", c c = a | b # 61 = 2b00111101 print "Line 2: Value of c = a | b is: ", c c = a ^ b # 49 = 2b00110001 print "L...
print "Line 6: Value of c = a >> 2 is: ", c
c = a << 2 #240 = 2b11110000 print "Line 5: Value of c = a << 2 is: ", c c = a >> 2 # 15 = 2b00001111
random_line_split
i_renderobj.rs
extern crate mazth; use std::collections::HashMap; use self::mazth::mat::{ Mat4, Mat3x1 }; use implement::render::renderdevice_gl::RenderUniformCollection; pub trait Xform { fn get_xform() -> Mat4< f32 >; } pub trait ObjPos { fn get_pos( & self ) -> Mat3x1< f32 >; } #[derive(Debug)] #[derive(Clone)] #[deri...
{ ADS, PBR, NONE, } pub trait IRenderable : IRenderBuffer { fn get_render_method( & self ) -> RenderMethod; } pub trait IRenderUniform { fn load_into_uniform( & mut self, uniforms: & mut RenderUniformCollection ) -> Result< (), & 'static str >; }
RenderMethod
identifier_name
i_renderobj.rs
extern crate mazth; use std::collections::HashMap; use self::mazth::mat::{ Mat4, Mat3x1 }; use implement::render::renderdevice_gl::RenderUniformCollection; pub trait Xform { fn get_xform() -> Mat4< f32 >; } pub trait ObjPos { fn get_pos( & self ) -> Mat3x1< f32 >;
#[derive(Debug)] #[derive(Clone)] #[derive(Copy)] pub enum RenderObjType { TRI, //todo QUAD, POINT, LINE, } #[derive(Debug)] #[derive(Clone)] #[derive(Copy)] #[derive(Eq)] #[derive(Hash)] #[derive(PartialEq)] pub enum BuffDataType { POS, NORMAL, TC, } pub trait RenderDevice { fn b...
}
random_line_split
cast-rfc0401-vtable-kinds.rs
// Check that you can cast between different pointers to trait objects // whose vtable have the same kind (both lengths, or both trait pointers). trait Foo<T> { fn foo(&self, _: T) -> u32 { 42 } } trait Bar { fn
(&self) { println!("Bar!"); } } impl<T> Foo<T> for () {} impl Foo<u32> for u32 { fn foo(&self, _: u32) -> u32 { self+43 } } impl Bar for () {} unsafe fn round_trip_and_call<'a>(t: *const (dyn Foo<u32>+'a)) -> u32 { let foo_e : *const dyn Foo<u16> = t as *const _; let r_1 = foo_e as *mut dyn Foo<u32>; (&*...
bar
identifier_name
cast-rfc0401-vtable-kinds.rs
// Check that you can cast between different pointers to trait objects // whose vtable have the same kind (both lengths, or both trait pointers). trait Foo<T> { fn foo(&self, _: T) -> u32 { 42 } } trait Bar { fn bar(&self) { println!("Bar!"); } } impl<T> Foo<T> for () {} impl Foo<u32> for u32 { fn foo(&self,...
} fn main() { let x = 4u32; let y : &dyn Foo<u32> = &x; let fl = unsafe { round_trip_and_call(y as *const dyn Foo<u32>) }; assert_eq!(fl, (43+4)); let s = FooS([0,1,2]); let u: &FooS<[u32]> = &s; let u: *const FooS<[u32]> = u; let bar_ref : *const BarS<[u32]> = foo_to_bar(u); let z...
u as *const BarS<T>
random_line_split
Tree.js
/** * Tree 'class' constructure. Starts a tree at a given point with given genes * @param {object} genes The genes that rule the Tree's growth. See README for list of options * @param {THREE.Vector3} position The Vector3 from which the trunk sprouts */ var Tree = function (genes, position) { this.genes = ...
else { var newMxSegments = Math.round(maxSegments * thisTree.genes.maxSegmentsDimP); thisTree.branches.push(new Branch( origin, currentRadius, currentSegmentLenght, newMxSegments, depth + 1, thisTree )); } }
{ return false; //Dont make a new branch if depth is exceeded }
conditional_block
Tree.js
/** * Tree 'class' constructure. Starts a tree at a given point with given genes * @param {object} genes The genes that rule the Tree's growth. See README for list of options * @param {THREE.Vector3} position The Vector3 from which the trunk sprouts */ var Tree = function (genes, position) { this.genes = ...
var newMxSegments = Math.round(maxSegments * thisTree.genes.maxSegmentsDimP); thisTree.branches.push(new Branch( origin, currentRadius, currentSegmentLenght, newMxSegments, depth + 1, thisTree )); } }
return false; //Dont make a new branch if depth is exceeded } else {
random_line_split
issue-17718-const-borrow.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ a: UnsafeCell<usize> } const D: C = C { a: UnsafeCell::new(1) }; const E: &'static UnsafeCell<usize> = &D.a; //~^ ERROR: cannot borrow a constant which may contain interior mutability const F: &'static C = &D; //~^ ERROR: cannot borrow a constant which may contain interior mutability fn main() {}
C
identifier_name
issue-17718-const-borrow.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at
// http://www.apache.org/licenses/LICENSE-2.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. use std::cell::UnsafeCell; const A: UnsafeCell<usize> = UnsafeCell::new(1); const B: &'...
// http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
random_line_split
nlpService.ts
import { Direction } from "@/services/trades" import { DetectIntentResponse } from "dialogflow" import { ajax, AjaxResponse } from "rxjs/ajax" import { bind } from "@react-rxjs/core" import { createSignal } from "@react-rxjs/utils" import { catchError, distinctUntilChanged, map, mapTo, pluck, switchMap, } f...
symbol, }, } : null default: return null } }), distinctUntilChanged(equals) as any, ), null, ) export const [useIsNlpIntentLoading] = bind( nlpIntent$.pipe(map((intent) => intent === "loading")), false, )
return symbol ? { type: NlpIntentType.SpotQuote, payload: {
random_line_split
viewFactory.js
// namespaces var dwv = dwv || {}; dwv.image = dwv.image || {}; /** * {@link dwv.image.View} factory. * * @class */ dwv.image.ViewFactory = function () {}; /** * {@link dwv.image.View} factory. Defaults to local one. * * @see dwv.image.ViewFactory */ dwv.ViewFactory = dwv.image.ViewFactory; /** * Get an Vie...
view.setWindowPresets(windowPresets); // set the initial position view.setInitialPosition(); return view; };
// store
random_line_split
callExpressionTests.ts
import { SyntaxKind } from "@ts-morph/common"; import { expect } from "chai"; import { CallExpression } from "../../../../compiler"; import { getInfoFromText } from "../../testHelpers"; describe(nameof(CallExpression), () => { describe(nameof<CallExpression>(e => e.getReturnType), () => { function doTest(t...
it("should get the call expression's return type", () => { doTest("const func = () => ''; const myVar = func();", ["string"]); }); it("should get the call expression's return type when void", () => { doTest("const func = () => {}; const myVar = func();", ["void"]); ...
{ const { sourceFile } = getInfoFromText(text); const callExpressions = sourceFile.getDescendantsOfKind(SyntaxKind.CallExpression); expect(callExpressions.map(c => c.getReturnType().getText())).to.deep.equal(expectedTypes); }
identifier_body
callExpressionTests.ts
import { SyntaxKind } from "@ts-morph/common"; import { expect } from "chai"; import { CallExpression } from "../../../../compiler"; import { getInfoFromText } from "../../testHelpers"; describe(nameof(CallExpression), () => { describe(nameof<CallExpression>(e => e.getReturnType), () => { function doTest(t...
doTest("const func = () => {}; const myVar = func();", ["void"]); }); it("should get the call expression's return type when chained", () => { doTest("const func = () => () => 4; const myVar = func()();", ["number", "() => number"]); }); }); });
}); it("should get the call expression's return type when void", () => {
random_line_split
callExpressionTests.ts
import { SyntaxKind } from "@ts-morph/common"; import { expect } from "chai"; import { CallExpression } from "../../../../compiler"; import { getInfoFromText } from "../../testHelpers"; describe(nameof(CallExpression), () => { describe(nameof<CallExpression>(e => e.getReturnType), () => { function
(text: string, expectedTypes: string[]) { const { sourceFile } = getInfoFromText(text); const callExpressions = sourceFile.getDescendantsOfKind(SyntaxKind.CallExpression); expect(callExpressions.map(c => c.getReturnType().getText())).to.deep.equal(expectedTypes); } i...
doTest
identifier_name
json_codegen_test.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @generated SignedSource<<60c1b1263e2d35528792da979dcebe3f>> */ mod json_codegen; use json_codegen::transform_fixture; use fixtu...
#[test] fn stable_literals() { let input = include_str!("json_codegen/fixtures/stable-literals.graphql"); let expected = include_str!("json_codegen/fixtures/stable-literals.expected"); test_fixture(transform_fixture, "stable-literals.graphql", "json_codegen/fixtures/stable-literals.expected", input, expec...
{ let input = include_str!("json_codegen/fixtures/kitchen-sink.graphql"); let expected = include_str!("json_codegen/fixtures/kitchen-sink.expected"); test_fixture(transform_fixture, "kitchen-sink.graphql", "json_codegen/fixtures/kitchen-sink.expected", input, expected); }
identifier_body
json_codegen_test.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @generated SignedSource<<60c1b1263e2d35528792da979dcebe3f>> */ mod json_codegen;
fn kitchen_sink() { let input = include_str!("json_codegen/fixtures/kitchen-sink.graphql"); let expected = include_str!("json_codegen/fixtures/kitchen-sink.expected"); test_fixture(transform_fixture, "kitchen-sink.graphql", "json_codegen/fixtures/kitchen-sink.expected", input, expected); } #[test] fn stabl...
use json_codegen::transform_fixture; use fixture_tests::test_fixture; #[test]
random_line_split
json_codegen_test.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @generated SignedSource<<60c1b1263e2d35528792da979dcebe3f>> */ mod json_codegen; use json_codegen::transform_fixture; use fixtu...
() { let input = include_str!("json_codegen/fixtures/stable-literals.graphql"); let expected = include_str!("json_codegen/fixtures/stable-literals.expected"); test_fixture(transform_fixture, "stable-literals.graphql", "json_codegen/fixtures/stable-literals.expected", input, expected); }
stable_literals
identifier_name
index.js
opts); return results; }; // monkeypatch escope/referencer var referencerLoc; try { referencerLoc = Module._resolveFilename("./referencer", escopeMod); } catch (err) { throw new ReferenceError("couldn't resolve escope/referencer"); } var referencerMod = createModule(referencerLoc); var ref...
}
random_line_split
index.js
patch estraverse estraverse = estraverseRelative.require("estraverse"); estraverses.push(estraverse); assign(estraverse.VisitorKeys, t.VISITOR_KEYS); // monkeypatch estraverse-fb (only for eslint < 2.3.0) try { var estraverseFb = eslintMod.require("estraverse-fb"); estraverses.push(estraverseFb); ...
// iterate through part of t.VISITOR_KEYS var visitorKeysMap = pick(t.VISITOR_KEYS, function(k) { return t.FLIPPED_ALIAS_KEYS.Flow.concat([ "ArrayPattern", "ClassDeclaration", "ClassExpression", "FunctionDeclaration", "FunctionExpression", "Identifier", "ObjectPattern...
{ if (!node.decorators) { return; } for (var i = 0; i < node.decorators.length; i++) { if (node.decorators[i].expression) { this.visit(node.decorators[i]); } } }
identifier_body
index.js
patch estraverse estraverse = estraverseRelative.require("estraverse"); estraverses.push(estraverse); assign(estraverse.VisitorKeys, t.VISITOR_KEYS); // monkeypatch estraverse-fb (only for eslint < 2.3.0) try { var estraverseFb = eslintMod.require("estraverse-fb"); estraverses.push(estraverseFb); ...
(node) { if (node.typeAnnotation) { visitTypeAnnotation.call(this, node.typeAnnotation); } else if (node.type === "Identifier") { this.visit(node); } else { visitTypeAnnotation.call(this, node); } } function nestTypeParamScope(manager, node) { var parentScope = manager.__curre...
checkIdentifierOrVisit
identifier_name
index.js
assign(estraverseFb.VisitorKeys, t.VISITOR_KEYS); } catch (err) { // Ignore: ESLint v2.3.0 does not have estraverse-fb } // ESLint v1.9.0 uses estraverse directly to work around https://github.com/npm/npm/issues/9663 var estraverseOfEslint = eslintMod.require("estraverse"); if (estraverseOfEslint !...
{ for (var i = 0; i < node.declarations.length; i++) { var id = node.declarations[i].id; var typeAnnotation = id.typeAnnotation; if (typeAnnotation) { checkIdentifierOrVisit.call(this, typeAnnotation); } } }
conditional_block
model.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
self.args[key][:] = v def setup(self, *args, **kwargs): raise NotImplementedError("must override this")
random_line_split
model.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
else: for out, buff in zip(outputs, output_buffs): out.append(buff.asnumpy()) for out, buff in zip(exe.outputs, output_buffs): out.copyto(buff) for out, buff in zip(outputs, output_buffs): out.append(buff.asnumpy()) outputs = [np.concatenate(i, ax...
output_buffs = [mx.nd.empty(i.shape, ctx=mx.cpu()) for i in exe.outputs]
conditional_block
model.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
(self, *args, **kwargs): raise NotImplementedError("must override this")
setup
identifier_name
model.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
def setup(self, *args, **kwargs): raise NotImplementedError("must override this")
with open(fname, 'rb') as fin: args_save = pickle.load(fin) for key, v in args_save.items(): if key in self.args: self.args[key][:] = v
identifier_body
app.py
# -*- coding: utf-8 -*- import rapidsms import datetime from rapidsms.apps.base import AppBase from .models import Poll from django.db.models import Q from rapidsms_httprouter.models import Message,MessageBatch class
(AppBase): def respond_to_message(self,message,response_msg,poll): if response_msg == poll.default_response: try: batch=MessageBatch.objects.get(name=str(poll.pk)) batch.status="Q" batch.save() msg=Message.objects.create(text=respo...
App
identifier_name
app.py
# -*- coding: utf-8 -*- import rapidsms import datetime from rapidsms.apps.base import AppBase from .models import Poll from django.db.models import Q from rapidsms_httprouter.models import Message,MessageBatch class App(AppBase): def respond_to_message(self,message,response_msg,poll): if response_msg ==...
else: message.respond(response_msg) def handle (self, message): # see if this contact matches any of our polls if (message.connection.contact): try: poll = Poll.objects.filter(contacts=message.connection.contact).exclude(start_date=None).filter( ...
try: batch=MessageBatch.objects.get(name=str(poll.pk)) batch.status="Q" batch.save() msg=Message.objects.create(text=response_msg,status="Q",connection=message.connection,direction="O",in_response_to=message.db_message) batch.messages.add(m...
conditional_block
app.py
# -*- coding: utf-8 -*- import rapidsms import datetime from rapidsms.apps.base import AppBase from .models import Poll from django.db.models import Q from rapidsms_httprouter.models import Message,MessageBatch class App(AppBase): def respond_to_message(self,message,response_msg,poll): if response_msg ==...
db_message.handled_by = 'poll' db_message.save() if response_msg and response_msg.strip(): self.respond_to_message(message,response_msg,poll) else: ...
if hasattr(message, 'db_message'): db_message = message.db_message
random_line_split
app.py
# -*- coding: utf-8 -*- import rapidsms import datetime from rapidsms.apps.base import AppBase from .models import Poll from django.db.models import Q from rapidsms_httprouter.models import Message,MessageBatch class App(AppBase): def respond_to_message(self,message,response_msg,poll): if response_msg ==...
response_obj.delete() return False else: return False else: response_obj, response_msg = poll.process_response(message) if hasattr(message, 'db_message'): ...
if (message.connection.contact): try: poll = Poll.objects.filter(contacts=message.connection.contact).exclude(start_date=None).filter( Q(end_date=None) | (~Q(end_date=None) & Q(end_date__gt=datetime.datetime.now()))).latest( 'start_date') ...
identifier_body