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
groomer.js
/** * Interactive Linter Copyright (c) 2015 Miguel Castillo. * * Licensed under MIT */ define(function (/*require, exports, module*/) { "use strict"; function getType(message) { return (message.fatal || message.severity === 2) ? "error" : "warning"; } /**
* data that interactive linter is expecting in the proper place. * * @param message {Object} message - A linting result item * @param settings {Object} settings - Settings used during the linting step */ function groom(message /*, settings*/) { message.type = getType(message); ...
* Generates codemirror tokens. Also massages the message so that it has the
random_line_split
test_cli20_servicetype.py
# Copyright 2013 Mirantis Inc. # All Rights Reserved # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by ...
cmd = servicetype.ListServiceProvider(test_cli20.MyApp(sys.stdout), None) self._test_list_resources(resources, cmd, sort_key=["name"], sort_dir=["asc", "desc"]) def test_list_service_pr...
def test_list_service_providers_sort(self): resources = "service_providers"
random_line_split
test_cli20_servicetype.py
# Copyright 2013 Mirantis Inc. # All Rights Reserved # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by ...
resources = "service_providers" cmd = servicetype.ListServiceProvider(test_cli20.MyApp(sys.stdout), None) self._test_list_resources(resources, cmd, sort_key=["name"], sort_dir=["asc"...
id_field = "name" def setUp(self): super(CLITestV20ServiceProvidersJSON, self).setUp( plurals={'tags': 'tag'} ) def test_list_service_providers(self): resources = "service_providers" cmd = servicetype.ListServiceProvider(test_cli20.MyApp(sys.stdout), ...
identifier_body
test_cli20_servicetype.py
# Copyright 2013 Mirantis Inc. # All Rights Reserved # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by ...
(self): resources = "service_providers" cmd = servicetype.ListServiceProvider(test_cli20.MyApp(sys.stdout), None) self._test_list_resources(resources, cmd, True) def test_list_service_providers_pagination(self): resources = "service_prov...
test_list_service_providers
identifier_name
__openerp__.py
# -*- coding: utf-8 -*- # © <YEAR(S)> <AUTHOR(S)> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Account Analytic Warehouse", "summary": "Add analytic in stock_warehouse", "version": "9.0.1.0.0", "category": "Accounting", "website": "https://odoo-community.org/", ...
"python": [], "bin": [], }, "depends": [ "base", "account", "stock" ], "data": [ "views/stock_warehouse_view.xml", "views/stock_location_view.xml", ], "demo": [ ], "qweb": [ ] }
random_line_split
frameobject.rs
use libc::c_int; use crate::code::{PyCodeObject, CO_MAXBLOCKS}; use crate::object::*; use crate::pyport::Py_ssize_t; use crate::pystate::PyThreadState; #[repr(C)] #[derive(Copy, Clone)] pub struct PyTryBlock { pub b_type: c_int, pub b_handler: c_int, pub b_level: c_int, } #[repr(C)] #[derive(Copy, Clone)...
(op: *mut PyObject) -> c_int { ((*op).ob_type == &mut PyFrame_Type) as c_int } ignore! { #[inline] pub unsafe fn PyFrame_IsRestricted(f: *mut PyFrameObject) -> c_int { ((*f).f_builtins != (*(*(*f).f_tstate).interp).builtins) as c_int } } #[cfg_attr(windows, link(name = "pythonXY"))] extern "C"...
PyFrame_Check
identifier_name
frameobject.rs
use libc::c_int; use crate::code::{PyCodeObject, CO_MAXBLOCKS}; use crate::object::*; use crate::pyport::Py_ssize_t; use crate::pystate::PyThreadState;
pub b_type: c_int, pub b_handler: c_int, pub b_level: c_int, } #[repr(C)] #[derive(Copy, Clone)] pub struct PyFrameObject { #[cfg(py_sys_config = "Py_TRACE_REFS")] pub _ob_next: *mut PyObject, #[cfg(py_sys_config = "Py_TRACE_REFS")] pub _ob_prev: *mut PyObject, pub ob_refcnt: Py_ssize_t...
#[repr(C)] #[derive(Copy, Clone)] pub struct PyTryBlock {
random_line_split
jquery.tablesorter.pager.js
(t) ? 1 : (c.filteredRows === 0 ? 0 : c.size * c.page + 1); c.page = (t) ? 0 : c.page; c.endRow = Math.min( c.filteredRows, c.totalRows, c.size * ( c.page + 1 ) ); out = c.$container.find(c.cssPageDisplay); // form the output string s = c.output.replace(/\{(page|filteredRows|filteredPages|totalPage...
// only add new header text if the length matches if ( th && th.length === hl ) { hsh = $t.hasClass('hasStickyHeaders'); $sh = hsh ? tc.$sticky.children('thead:first').children().children() : ''; $f = $t.find('tfoot tr:first').children(); $t.find('th.' + tc.cssHeader).each(function(j){...
random_line_split
jquery.tablesorter.pager.js
[j]); } } $.tablesorter.processTbody(table, $tb, false); } if ( c.page >= c.totalPages ) { moveToLastPage(table, c); } updatePageDisplay(table, c); if ( !c.isDisabled ) { fixHeight(table, c); } $(table).trigger('applyWidgets'); }, showAllRows = function(table, c){ if ( c.ajax ...
{ setPageSize(table, parseInt( $(this).val(), 10 ), c); changeHeight(table, c); }
conditional_block
Size.tsx
import React from 'react'; import { D3Scale } from '@visx/scale'; import Legend, { LegendProps } from './Legend'; import labelTransformFactory from '../util/labelTransformFactory'; import defaultDomain from '../util/defaultDomain'; import identity from '../util/identity'; // eslint-disable-next-line @typescript-eslint...
type AnySizeScale = D3Scale<number, any, any>; export type LegendSizeProps<Scale extends AnySizeScale> = { steps?: number; } & LegendProps<Scale>; export default function Size<Scale extends AnySizeScale>({ scale, domain: inputDomain, steps = 5, labelFormat = identity, labelTransform = labelTransformFactor...
random_line_split
Size.tsx
import React from 'react'; import { D3Scale } from '@visx/scale'; import Legend, { LegendProps } from './Legend'; import labelTransformFactory from '../util/labelTransformFactory'; import defaultDomain from '../util/defaultDomain'; import identity from '../util/identity'; // eslint-disable-next-line @typescript-eslint...
{ const domain = inputDomain || defaultDomain({ steps, scale }); return ( <Legend<Scale> scale={scale} domain={domain} labelFormat={labelFormat} labelTransform={labelTransform} {...restProps} /> ); }
identifier_body
Size.tsx
import React from 'react'; import { D3Scale } from '@visx/scale'; import Legend, { LegendProps } from './Legend'; import labelTransformFactory from '../util/labelTransformFactory'; import defaultDomain from '../util/defaultDomain'; import identity from '../util/identity'; // eslint-disable-next-line @typescript-eslint...
<Scale extends AnySizeScale>({ scale, domain: inputDomain, steps = 5, labelFormat = identity, labelTransform = labelTransformFactory, ...restProps }: LegendSizeProps<Scale>) { const domain = inputDomain || defaultDomain({ steps, scale }); return ( <Legend<Scale> scale={scale} domain={do...
Size
identifier_name
server_state.py
#!/usr/bin/env python # # Copyright (C) 2013 Google Inc. # # This file is part of YouCompleteMe. # # YouCompleteMe 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 you...
def ShouldUseFiletypeCompleter( self, request_data ): """ Determines whether or not the semantic completer should be called, and returns an indication of the reason why. Specifically, returns a tuple: ( should_use_completer_now, was_semantic_completion_forced ), where: - should_use_completer_now:...
random_line_split
server_state.py
#!/usr/bin/env python # # Copyright (C) 2013 Google Inc. # # This file is part of YouCompleteMe. # # YouCompleteMe 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 you...
self._gencomp.Shutdown() def _GetFiletypeCompleterForFiletype( self, filetype ): with self._filetype_completers_lock: try: return self._filetype_completers[ filetype ] except KeyError: pass module_path = PathToFiletypeCompleterPluginLoader( filetype ) completer = N...
if completer: completer.Shutdown()
conditional_block
server_state.py
#!/usr/bin/env python # # Copyright (C) 2013 Google Inc. # # This file is part of YouCompleteMe. # # YouCompleteMe 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 you...
( self, request_data ): return self._gencomp.ShouldUseNow( request_data ) def ShouldUseFiletypeCompleter( self, request_data ): """ Determines whether or not the semantic completer should be called, and returns an indication of the reason why. Specifically, returns a tuple: ( should_use_complete...
ShouldUseGeneralCompleter
identifier_name
server_state.py
#!/usr/bin/env python # # Copyright (C) 2013 Google Inc. # # This file is part of YouCompleteMe. # # YouCompleteMe 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 you...
# don't use semantic, ignore whether or not the user requested forced # completion return ( False, False ) def GetGeneralCompleter( self ): return self._gencomp def CurrentFiletypeCompletionEnabled( self, current_filetypes ): filetype_to_disable = self._user_options[ 'filetype_spec...
""" Determines whether or not the semantic completer should be called, and returns an indication of the reason why. Specifically, returns a tuple: ( should_use_completer_now, was_semantic_completion_forced ), where: - should_use_completer_now: if True, the semantic engine should be used - was_sema...
identifier_body
dsfs_chapter01.py
# 'Data Science from Scratch' Chapter 1 exampl # Create list of users userNames = ["Hero", "Dunn", "Sue", "Chi", "Thor", "Clive", "Hicks", "Devin", "Kate", "Klein"] users = [] for ind, name in enumerate( userNames ):
# Helper function to get id get_id = lambda userlist: map( lambda user: user["id"], userlist) # Friendship friendships = [(0,1), (0,2), (1,2), (1,3), (2,3), (3,4), (4,5), (5,6), (5,7), (6,8), (7,8), (8,9)] # Store as directed graph g = friendships g.extend(map(lambda(i,j): (j,i), friendships)) # Add the li...
users.append( {"id": ind, "name": name})
conditional_block
dsfs_chapter01.py
# 'Data Science from Scratch' Chapter 1 exampl # Create list of users userNames = ["Hero", "Dunn", "Sue", "Chi", "Thor", "Clive", "Hicks", "Devin", "Kate", "Klein"] users = [] for ind, name in enumerate( userNames ): users.append( {"id": ind, "name": name})
# Store as directed graph g = friendships g.extend(map(lambda(i,j): (j,i), friendships)) # Add the list of friends to each user for user in users: user["friends"] = [] for i,j in g: users[i]["friends"].append(users[j]) # Number of friends each user has number_of_friends = lambda (user): len(user["fr...
# Helper function to get id get_id = lambda userlist: map( lambda user: user["id"], userlist) # Friendship friendships = [(0,1), (0,2), (1,2), (1,3), (2,3), (3,4), (4,5), (5,6), (5,7), (6,8), (7,8), (8,9)]
random_line_split
dsfs_chapter01.py
# 'Data Science from Scratch' Chapter 1 exampl # Create list of users userNames = ["Hero", "Dunn", "Sue", "Chi", "Thor", "Clive", "Hicks", "Devin", "Kate", "Klein"] users = [] for ind, name in enumerate( userNames ): users.append( {"id": ind, "name": name}) # Helper function to get id get_id = lambda userlist...
(user): user_interests = interests_dict[user["id"]] id_list = map( lambda interest: users_dict[interest], user_interests) all_ids = filter(lambda x: x!= user["id"], reduce( lambda acc, ids: acc+ids, id_list, [])) return Counter(all_ids) # Find topics of interest topic_count = map( lambda k: (k.lowe...
most_common_interests_with
identifier_name
dsfs_chapter01.py
# 'Data Science from Scratch' Chapter 1 exampl # Create list of users userNames = ["Hero", "Dunn", "Sue", "Chi", "Thor", "Clive", "Hicks", "Devin", "Kate", "Klein"] users = [] for ind, name in enumerate( userNames ): users.append( {"id": ind, "name": name}) # Helper function to get id get_id = lambda userlist...
# Find topics of interest topic_count = map( lambda k: (k.lower(), len(users_dict[k])), users_dict.keys()) topic_dict = defaultdict(int) for topic, count in topic_count: topic_dict[topic] += count Counter(topic_dict)
user_interests = interests_dict[user["id"]] id_list = map( lambda interest: users_dict[interest], user_interests) all_ids = filter(lambda x: x!= user["id"], reduce( lambda acc, ids: acc+ids, id_list, [])) return Counter(all_ids)
identifier_body
dead.js
module.exports = (function () { 'use strict'; var strings = require('../../strings').dead, style = require('../../style'); return { create: function(){ this.game.world.width = this.game.canvas.width; this.game.world.height = this.game.canvas.height; this.game.camera.reset(); this...
align: 'center' } ); instructions.anchor.setTo(0.5); }, capabilities: { 'revive': function(){this.game.state.start('map');} } }; })();
strings.instructions, { font: 'bold 20px ' + style.font.regular, fill: style.color.white,
random_line_split
disable.py
# # Copyright 2013, 2018, 2019 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio 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, or (at your option) # any later ...
raise ModToolException("Invalid pattern!") def run(self): """ Go, go, go! """ def _handle_py_qa(cmake, fname): """ Do stuff for py qa """ cmake.comment_out_lines('GR_ADD_TEST.*'+fname) self.scm.mark_file_updated(cmake.filename) return True...
""" Validates the arguments """ ModTool._validate(self) if not self.info['pattern'] or self.info['pattern'].isspace():
random_line_split
disable.py
# # Copyright 2013, 2018, 2019 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio 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, or (at your option) # any later ...
(cmake, fname): """ Comment out include files from the SWIG file, as well as the block magic """ with open(self._file['swig']) as f: swigfile = f.read() blockname = os.path.splitext(fname[len(self.info['modname'])+1:])[0] if self.info['version'...
_handle_i_swig
identifier_name
disable.py
# # Copyright 2013, 2018, 2019 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio 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, or (at your option) # any later ...
def run(self): """ Go, go, go! """ def _handle_py_qa(cmake, fname): """ Do stuff for py qa """ cmake.comment_out_lines('GR_ADD_TEST.*'+fname) self.scm.mark_file_updated(cmake.filename) return True def _handle_py_mod(cmake, fname): ...
raise ModToolException("Invalid pattern!")
conditional_block
disable.py
# # Copyright 2013, 2018, 2019 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio 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, or (at your option) # any later ...
def run(self): """ Go, go, go! """ def _handle_py_qa(cmake, fname): """ Do stuff for py qa """ cmake.comment_out_lines('GR_ADD_TEST.*'+fname) self.scm.mark_file_updated(cmake.filename) return True def _handle_py_mod(cmake, fname): ...
""" Validates the arguments """ ModTool._validate(self) if not self.info['pattern'] or self.info['pattern'].isspace(): raise ModToolException("Invalid pattern!")
identifier_body
rhsm_ks.py
# # Copyright (C) 2015 Red Hat, Inc. # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Public License v.2, or (at your option) any later version. # This program is distributed in the hope that it will be...
(self, storage, ksdata, instclass): super(RHSMAddonData, self).__init__(storage, ksdata, instclass) self.log.debug("storage %s", storage) self.log.debug("ksdata %s", ksdata) self.log.debug("instclass %s", instclass)
setup
identifier_name
rhsm_ks.py
# # Copyright (C) 2015 Red Hat, Inc. # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Public License v.2, or (at your option) any later version. # This program is distributed in the hope that it will be...
super(RHSMAddonData, self).__init__(storage, ksdata, instclass) self.log.debug("storage %s", storage) self.log.debug("ksdata %s", ksdata) self.log.debug("instclass %s", instclass)
def setup(self, storage, ksdata, instclass):
random_line_split
rhsm_ks.py
# # Copyright (C) 2015 Red Hat, Inc. # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Public License v.2, or (at your option) any later version. # This program is distributed in the hope that it will be...
log = logging.getLogger(__name__) def setup(self, storage, ksdata, instclass): super(RHSMAddonData, self).__init__(storage, ksdata, instclass) self.log.debug("storage %s", storage) self.log.debug("ksdata %s", ksdata) self.log.debug("instclass %s", instclass)
identifier_body
current-date-indicator.src.js
/** * @license Highcharts Gantt JS v7.2.0 (2019-09-03) * * CurrentDateIndicator * * (c) 2010-2019 Lars A. V. Cabrera * * License: www.highcharts.com/license */ 'use strict'; (function (factory) { if (typeof module === 'object' && module.exports) { factory['default'] = factory; module.exports...
}); _registerModule(_modules, 'masters/modules/current-date-indicator.src.js', [], function () { }); }));
} return defaultMethod.call(this, defaultLabelOptions); });
random_line_split
current-date-indicator.src.js
/** * @license Highcharts Gantt JS v7.2.0 (2019-09-03) * * CurrentDateIndicator * * (c) 2010-2019 Lars A. V. Cabrera * * License: www.highcharts.com/license */ 'use strict'; (function (factory) { if (typeof module === 'object' && module.exports) { factory['default'] = factory; module.exports...
}); wrap(PlotLineOrBand.prototype, 'getLabelText', function (defaultMethod, defaultLabelOptions) { var options = this.options; if (options.currentDateIndicator && options.label && typeof options.label.formatter === 'function') { options.value = ne...
{ this.label.attr({ text: this.getLabelText(this.options.label) }); }
conditional_block
current-date-indicator.src.js
/** * @license Highcharts Gantt JS v7.2.0 (2019-09-03) * * CurrentDateIndicator * * (c) 2010-2019 Lars A. V. Cabrera * * License: www.highcharts.com/license */ 'use strict'; (function (factory) { if (typeof module === 'object' && module.exports) { factory['default'] = factory; module.exports...
_registerModule(_modules, 'parts-gantt/CurrentDateIndicator.js', [_modules['parts/Globals.js']], function (H) { /* * * * (c) 2016-2019 Highsoft AS * * Author: Lars A. V. Cabrera * * License: www.highcharts.com/license * * !!!!!!! S...
{ if (!obj.hasOwnProperty(path)) { obj[path] = fn.apply(null, args); } }
identifier_body
current-date-indicator.src.js
/** * @license Highcharts Gantt JS v7.2.0 (2019-09-03) * * CurrentDateIndicator * * (c) 2010-2019 Lars A. V. Cabrera * * License: www.highcharts.com/license */ 'use strict'; (function (factory) { if (typeof module === 'object' && module.exports) { factory['default'] = factory; module.exports...
(obj, path, args, fn) { if (!obj.hasOwnProperty(path)) { obj[path] = fn.apply(null, args); } } _registerModule(_modules, 'parts-gantt/CurrentDateIndicator.js', [_modules['parts/Globals.js']], function (H) { /* * * * (c) 2016-2019 Highsoft AS * ...
_registerModule
identifier_name
lib.rs
/*! # graphite-rust Herein lies a humble reimplementation of the graphite metrics system -- a time series database system, with HTTP frontend and management tools. It strikes a reasonable balance between features you need, easy management, and a rich ecosystem of tools which can talk to graphite. `graphite-rust` aim...
// TODO: scuttled until I want to fix all the iron related issues // pub mod graphite;
pub mod carbon;
random_line_split
accept_ranges.rs
//! The Accept-Ranges request header, defined in RFC 2616, Section 14.5. use std::io::IoResult; use std::ascii::AsciiExt; pub use self::AcceptableRanges::{RangeUnits, NoAcceptableRanges}; pub use self::RangeUnit::{Bytes, OtherRangeUnit}; #[derive(Clone, PartialEq, Eq)] // RFC 2616: range-unit = bytes-unit | other-ra...
RangeUnits(ref range_units) => { let mut result = String::new(); for ru in range_units.iter() { match ru { &Bytes => result.push_str("bytes"), &OtherRangeUnit(ref ru) => result.push_str(&ru[]), ...
random_line_split
accept_ranges.rs
//! The Accept-Ranges request header, defined in RFC 2616, Section 14.5. use std::io::IoResult; use std::ascii::AsciiExt; pub use self::AcceptableRanges::{RangeUnits, NoAcceptableRanges}; pub use self::RangeUnit::{Bytes, OtherRangeUnit}; #[derive(Clone, PartialEq, Eq)] // RFC 2616: range-unit = bytes-unit | other-ra...
}
{ match *self { NoAcceptableRanges => String::from_str("none"), RangeUnits(ref range_units) => { let mut result = String::new(); for ru in range_units.iter() { match ru { &Bytes => result.push_str("bytes"), ...
identifier_body
accept_ranges.rs
//! The Accept-Ranges request header, defined in RFC 2616, Section 14.5. use std::io::IoResult; use std::ascii::AsciiExt; pub use self::AcceptableRanges::{RangeUnits, NoAcceptableRanges}; pub use self::RangeUnit::{Bytes, OtherRangeUnit}; #[derive(Clone, PartialEq, Eq)] // RFC 2616: range-unit = bytes-unit | other-ra...
{ RangeUnits(Vec<RangeUnit>), NoAcceptableRanges, } impl super::HeaderConvertible for AcceptableRanges { fn from_stream<R: Reader>(reader: &mut super::HeaderValueByteIterator<R>) -> Option<AcceptableRanges> { let mut range_units = Vec::new(); loop { match reader.rea...
AcceptableRanges
identifier_name
NumberedList.ts
import { concat } from '../CollectionHelpers' import { Renderer } from '../Rendering/Renderer' import { Heading } from './Heading' import { InlineSyntaxNode } from './InlineSyntaxNode' import { OutlineSyntaxNode } from './OutlineSyntaxNode' import { OutlineSyntaxNodeContainer } from './OutlineSyntaxNodeContainer' exp...
render(renderer: Renderer): string { return renderer.numberedList(this) } } export namespace NumberedList { export class Item extends OutlineSyntaxNodeContainer { ordinal?: number constructor( public children: OutlineSyntaxNode[], options?: { ordinal?: number } ) { super(chi...
{ return concat( this.items.map(item => item.inlineDescendants())) }
identifier_body
NumberedList.ts
import { concat } from '../CollectionHelpers' import { Renderer } from '../Rendering/Renderer' import { Heading } from './Heading' import { InlineSyntaxNode } from './InlineSyntaxNode' import { OutlineSyntaxNode } from './OutlineSyntaxNode' import { OutlineSyntaxNodeContainer } from './OutlineSyntaxNodeContainer' exp...
(): InlineSyntaxNode[] { return concat( this.items.map(item => item.inlineDescendants())) } render(renderer: Renderer): string { return renderer.numberedList(this) } } export namespace NumberedList { export class Item extends OutlineSyntaxNodeContainer { ordinal?: number constructor( ...
inlineDescendants
identifier_name
NumberedList.ts
import { concat } from '../CollectionHelpers' import { Renderer } from '../Rendering/Renderer' import { Heading } from './Heading' import { InlineSyntaxNode } from './InlineSyntaxNode' import { OutlineSyntaxNode } from './OutlineSyntaxNode' import { OutlineSyntaxNodeContainer } from './OutlineSyntaxNodeContainer' exp...
} protected readonly NUMBERED_LIST_ITEM = undefined } export type Order = 'asc' | 'desc' }
public children: OutlineSyntaxNode[], options?: { ordinal?: number } ) { super(children) this.ordinal = options?.ordinal
random_line_split
mutations.py
from django.contrib.auth import authenticate, get_user_model from graphene import AbstractType, relay, Field, String, ObjectType, Union, List from users.jwt_schema import TokensSuccess from users.jwt_util import get_jwt_token from users.schema.definitions import Viewer class Error(ObjectType): """Form Errors ...
: email = String(required=True) password = String(required=True) auth_form_payload = Field(AuthFormUnion) @classmethod def mutate_and_get_payload(cls, input, context, info): email = input.get('email') password = input.get('password') user = get_user_model().objects....
Input
identifier_name
mutations.py
from django.contrib.auth import authenticate, get_user_model from graphene import AbstractType, relay, Field, String, ObjectType, Union, List from users.jwt_schema import TokensSuccess from users.jwt_util import get_jwt_token from users.schema.definitions import Viewer class Error(ObjectType): """Form Errors ...
if user: error = Error( key='email', message='A user with this email already exists.') errors.append(error) return SignupUserMutation(FormErrors(errors)) class UserMutations(AbstractType): login = LoginMutation.Field() signup = Signu...
user = get_user_model().objects.create_user(email=email, password=password) jwt_token = get_jwt_token(user) token = TokensSuccess( token=jwt_token ) viewer = Viewer( user=user, tokens=token ) return S...
conditional_block
mutations.py
from django.contrib.auth import authenticate, get_user_model from graphene import AbstractType, relay, Field, String, ObjectType, Union, List from users.jwt_schema import TokensSuccess from users.jwt_util import get_jwt_token from users.schema.definitions import Viewer class Error(ObjectType):
class FormErrors(ObjectType): """Form Errors https://medium.com/@tarkus/validation-and-user-errors-in-graphql-mutations-39ca79cd00bf#.ts99uxfnr """ errors = List(Error) class AuthFormUnion(Union): """Returns either token error or token success""" class Meta: types = (Viewer, Fo...
"""Form Errors https://medium.com/@tarkus/validation-and-user-errors-in-graphql-mutations-39ca79cd00bf#.ts99uxfnr """ key = String() message = String(required=True)
identifier_body
mutations.py
from django.contrib.auth import authenticate, get_user_model from graphene import AbstractType, relay, Field, String, ObjectType, Union, List from users.jwt_schema import TokensSuccess from users.jwt_util import get_jwt_token from users.schema.definitions import Viewer class Error(ObjectType): """Form Errors ...
user_exists = get_user_model().objects.filter(email=email) errors = [] if not user_exists: error = Error( key='email', message='A user with this email doesn\'t exist.') errors.append(error) return LoginMutation(FormErrors(errors...
password = input.get('password')
random_line_split
embedding.py
import glob import os import numpy as np def load_emebeddings(folder): files = [filename for filename in glob.iglob(folder + '**', recursive=True) if not os.path.isdir(filename)] w2v = {} for file in files: with open(file, "r", encoding='utf8') as lines: for line in lines: ...
return res
k /= divisor
conditional_block
embedding.py
import glob import os import numpy as np def load_emebeddings(folder):
# derive a vector by multiplying the tfidf with every line of the embeddingg vector # then sum all embedding vectors together # then divide by the sum of the length of all embedding vectors def compute_embedding_vec(embeddings, doc_tfidf): intersect = set(doc_tfidf.keys()).intersection(embeddings.keys()) res ...
files = [filename for filename in glob.iglob(folder + '**', recursive=True) if not os.path.isdir(filename)] w2v = {} for file in files: with open(file, "r", encoding='utf8') as lines: for line in lines: # based on http://nadbordrozd.github.io/blog/2016/05/20/text-classificati...
identifier_body
embedding.py
import glob import os import numpy as np def
(folder): files = [filename for filename in glob.iglob(folder + '**', recursive=True) if not os.path.isdir(filename)] w2v = {} for file in files: with open(file, "r", encoding='utf8') as lines: for line in lines: # based on http://nadbordrozd.github.io/blog/2016/05/20/tex...
load_emebeddings
identifier_name
embedding.py
import glob import os import numpy as np def load_emebeddings(folder): files = [filename for filename in glob.iglob(folder + '**', recursive=True) if not os.path.isdir(filename)] w2v = {} for file in files: with open(file, "r", encoding='utf8') as lines: for line in lines:
return w2v # derive a vector by multiplying the tfidf with every line of the embeddingg vector # then sum all embedding vectors together # then divide by the sum of the length of all embedding vectors def compute_embedding_vec(embeddings, doc_tfidf): intersect = set(doc_tfidf.keys()).intersection(embeddings.ke...
# based on http://nadbordrozd.github.io/blog/2016/05/20/text-classification-with-word2vec/ w2v[line.split()[0]] = line.split()[1:]
random_line_split
revidx.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::ops::{Add, Mul}; use std::str::FromStr; use std::u32; /// Index into a `RevLog` #[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, ...
else { None } } } #[cfg(test)] mod test { use super::*; use std::str::FromStr; #[test] fn zero() { assert_eq!(RevIdx::zero(), RevIdx(0)) } #[test] fn succ() { assert_eq!(RevIdx::zero().succ(), RevIdx(1)); assert_eq!(RevIdx::zero().succ().su...
{ let ret = RevIdx(self.0); self.0 += 1; Some(ret) }
conditional_block
revidx.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::ops::{Add, Mul}; use std::str::FromStr; use std::u32; /// Index into a `RevLog` #[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, ...
RevIdx(self.0 - 1) } /// Return iterator for a range from index to `lim`. pub fn range_to(&self, lim: Self) -> RevIdxRange { RevIdxRange(self.0, lim.0) } /// Return an open ended iterator from index. pub fn range(&self) -> RevIdxRange { RevIdxRange(self.0, u32::MAX) ...
random_line_split
revidx.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::ops::{Add, Mul}; use std::str::FromStr; use std::u32; /// Index into a `RevLog` #[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, ...
#[test] fn range_to() { let v: Vec<_> = RevIdx::zero().range_to(RevIdx(5)).collect(); assert_eq!( v, vec![RevIdx(0), RevIdx(1), RevIdx(2), RevIdx(3), RevIdx(4)] ); } #[test] fn iter() { let v: Vec<_> = RevIdx::zero().into_iter().take(5).coll...
{ println!("bad {:?}", RevIdx::zero().pred()); }
identifier_body
revidx.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::ops::{Add, Mul}; use std::str::FromStr; use std::u32; /// Index into a `RevLog` #[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, ...
() { let v: Vec<_> = RevIdx::zero().into_iter().take(5).collect(); assert_eq!( v, vec![RevIdx(0), RevIdx(1), RevIdx(2), RevIdx(3), RevIdx(4)] ) } #[test] fn fromstr() { let idx: RevIdx = FromStr::from_str("555").expect("Valid string"); assert_...
iter
identifier_name
test_long.py
so the test still does something # under -O. def check(ok, *args): if not ok: raise TestFailed, join(map(str, args), " ") # Get quasi-random long consisting of ndigits digits (in base BASE). # quasi == the most-significant digit will not be 0, and the number # is constructed to contain long strings of 0 ...
"not x & -p2 == x >> n << n == x & ~(p2 - 1) for x n p2", x, n, p2) def test_bitop_identities_2(x, y): check(x & y == y & x, "x & y != y & x for", x, y) check(x | y == y | x, "x | y != y | x for", x, y) check(x ^ y == y ^ x, "x ^ y != y ^ x for", x, y) check(x ^ y ^ x == y, "x ...
check(x & 0 == 0, "x & 0 != 0 for", x) check(x | 0 == x, "x | 0 != x for", x) check(x ^ 0 == x, "x ^ 0 != x for", x) check(x & -1 == x, "x & -1 != x for", x) check(x | -1 == -1, "x | -1 != -1 for", x) check(x ^ -1 == ~x, "x ^ -1 != ~x for", x) check(x == ~~x, "x != ~~x for", x) check(x & x =...
identifier_body
test_long.py
so the test still does something # under -O. def check(ok, *args): if not ok: raise TestFailed, join(map(str, args), " ") # Get quasi-random long consisting of ndigits digits (in base BASE). # quasi == the most-significant digit will not be 0, and the number # is constructed to contain long strings of 0 ...
return answer # Get random long consisting of ndigits random digits (relative to base # BASE). The sign bit is also random. def getran2(ndigits): answer = 0L for i in range(ndigits): answer = (answer << SHIFT) | randint(0, MASK) if random() < 0.5: answer = -answer return answer ...
answer = -answer
conditional_block
test_long.py
the test still does something # under -O. def check(ok, *args): if not ok: raise TestFailed, join(map(str, args), " ") # Get quasi-random long consisting of ndigits digits (in base BASE). # quasi == the most-significant digit will not be 0, and the number # is constructed to contain long strings of 0 and...
(x, base): if (x, base) == (0, 8): # this is an oddball! return "0L" digits = [] sign = 0 if x < 0: sign, x = 1, -x while x: x, r = divmod(x, base) digits.append(int(r)) digits.reverse() digits = digits or [0] return '-'[:sign] + \ {8: '...
slow_format
identifier_name
test_long.py
so the test still does something # under -O. def check(ok, *args): if not ok: raise TestFailed, join(map(str, args), " ") # Get quasi-random long consisting of ndigits digits (in base BASE). # quasi == the most-significant digit will not be 0, and the number # is constructed to contain long strings of 0 ...
test_bitop_identities_1(x) for leny in digits: y = getran(leny) test_bitop_identities_2(x, y) test_bitop_identities_3(x, y, getran((lenx + leny)/2)) # ------------------------------------------------- hex oct repr str atol def slow_format(x, base): if (x, base) ...
digits = range(1, maxdigits+1) for lenx in digits: x = getran(lenx)
random_line_split
setup.py
import os from setuptools import setup # Utility function to read the README file.
return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name = "pyUniSR", version = "0.0.7", author = "Nicolo Balzarotti", author_email = "anothersms@gmail.com", description = ("Python class to access studenti.unisr.it (Univerity Vita-Salute San Raffaele, Milano)"), licens...
# Used for the long_description. It's nice, because now 1) we have a top level # README file and 2) it's easier to type in the README file than to put a raw # string in below ... def read(fname):
random_line_split
setup.py
import os from setuptools import setup # Utility function to read the README file. # Used for the long_description. It's nice, because now 1) we have a top level # README file and 2) it's easier to type in the README file than to put a raw # string in below ... def read(fname):
setup( name = "pyUniSR", version = "0.0.7", author = "Nicolo Balzarotti", author_email = "anothersms@gmail.com", description = ("Python class to access studenti.unisr.it (Univerity Vita-Salute San Raffaele, Milano)"), license = "GPLv2", keywords = "unisr class milano university raffaele", ...
return open(os.path.join(os.path.dirname(__file__), fname)).read()
identifier_body
setup.py
import os from setuptools import setup # Utility function to read the README file. # Used for the long_description. It's nice, because now 1) we have a top level # README file and 2) it's easier to type in the README file than to put a raw # string in below ... def
(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name = "pyUniSR", version = "0.0.7", author = "Nicolo Balzarotti", author_email = "anothersms@gmail.com", description = ("Python class to access studenti.unisr.it (Univerity Vita-Salute San Raffaele, Milano)"), ...
read
identifier_name
App.tsx
import React from "react"; import { Chart } from "react-google-charts"; export const data = [ [ { type: "date", id: "Date" }, { type: "number", id: "Won/Loss" }, ], [new Date(2013, 2, 4), 10], [new Date(2013, 2, 5), 3], [new Date(2013, 2, 7), -1], [new Date(2013, 2, 8), 2], [new Date(2013, 2, 12)...
{ return ( <Chart chartType="Calendar" width="100%" height="400px" data={data} options={options} /> ); }
identifier_body
App.tsx
import React from "react"; import { Chart } from "react-google-charts"; export const data = [ [ { type: "date", id: "Date" }, { type: "number", id: "Won/Loss" }, ], [new Date(2013, 2, 4), 10], [new Date(2013, 2, 5), 3], [new Date(2013, 2, 7), -1],
[new Date(2013, 2, 13), 1], [new Date(2013, 2, 15), 1], [new Date(2013, 2, 16), -4], [new Date(2013, 1, 4), 10], [new Date(2013, 1, 5), 3], [new Date(2013, 1, 7), -1], [new Date(2013, 1, 8), 2], [new Date(2013, 1, 12), -1], [new Date(2013, 1, 13), 1], [new Date(2013, 1, 15), 1], [new Date(2013, 1,...
[new Date(2013, 2, 8), 2], [new Date(2013, 2, 12), -1],
random_line_split
App.tsx
import React from "react"; import { Chart } from "react-google-charts"; export const data = [ [ { type: "date", id: "Date" }, { type: "number", id: "Won/Loss" }, ], [new Date(2013, 2, 4), 10], [new Date(2013, 2, 5), 3], [new Date(2013, 2, 7), -1], [new Date(2013, 2, 8), 2], [new Date(2013, 2, 12)...
() { return ( <Chart chartType="Calendar" width="100%" height="400px" data={data} options={options} /> ); }
App
identifier_name
tipoDocumentoFormulario.js
var baseURL; $.validator.addMethod("alfanumerico", function(value, element) { return this.optional(element) || /^[-._a-z0-9\- ]+$/i.test(value); }, "Este campo es alfanumerico."); $("#frmGuardaTipoDocumento").validate({ rules : { descripcion : "required", codigo : {required:true,alfanumerico:true}, ...
{ var baseURL; baseURL = $("#baseURL").val(); $("#contenidoPrincipal").html("Cargando . . ."); $.get(baseURL + "mantenimientoInterno/listarTiposDocumentos", function(respuesta) { $("#contenidoPrincipal").html(respuesta); $("#title-page").html("Mantenimiento Tipo Entidad Documento - Listado"); }); }
identifier_body
tipoDocumentoFormulario.js
var baseURL; $.validator.addMethod("alfanumerico", function(value, element) { return this.optional(element) || /^[-._a-z0-9\- ]+$/i.test(value); }, "Este campo es alfanumerico."); $("#frmGuardaTipoDocumento").validate({ rules : { descripcion : "required", codigo : {required:true,alfanumerico:true}, ...
function cancelarTipoDocumento(){ var baseURL; baseURL = $("#baseURL").val(); $("#contenidoPrincipal").html("Cargando . . ."); $.get(baseURL + "mantenimientoInterno/listarTiposDocumentos", function(respuesta) { $("#contenidoPrincipal").html(respuesta); $("#title-page").html("Mantenimiento Tipo Entidad Do...
});
random_line_split
tipoDocumentoFormulario.js
var baseURL; $.validator.addMethod("alfanumerico", function(value, element) { return this.optional(element) || /^[-._a-z0-9\- ]+$/i.test(value); }, "Este campo es alfanumerico."); $("#frmGuardaTipoDocumento").validate({ rules : { descripcion : "required", codigo : {required:true,alfanumerico:true}, ...
(){ var baseURL; baseURL = $("#baseURL").val(); $("#contenidoPrincipal").html("Cargando . . ."); $.get(baseURL + "mantenimientoInterno/listarTiposDocumentos", function(respuesta) { $("#contenidoPrincipal").html(respuesta); $("#title-page").html("Mantenimiento Tipo Entidad Documento - Listado"); }); } ...
cancelarTipoDocumento
identifier_name
tipoDocumentoFormulario.js
var baseURL; $.validator.addMethod("alfanumerico", function(value, element) { return this.optional(element) || /^[-._a-z0-9\- ]+$/i.test(value); }, "Este campo es alfanumerico."); $("#frmGuardaTipoDocumento").validate({ rules : { descripcion : "required", codigo : {required:true,alfanumerico:true}, ...
else{ baseURL = $("#baseURL").val(); $.get(baseURL + "mantenimientoInterno/listarTiposDocumentos?info="+contenido, function(respuesta) { $("#contenidoPrincipal").html(respuesta); $("#title-page").html("Mantenimiento Tipo Entidad Documento - Listado"); }); } } }); ...
{ var mensaje="Este tipo de documento ya ha sido registrado"; alert(mensaje); }
conditional_block
param_vasicek.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Vasicek parameter class ~~~~~~~~~~~~~~~~~~~~~~~ """ from __future__ import print_function, division import numpy as np from .param_generic import GenericParam __all__ = ['VasicekParam'] class VasicekParam(GenericParam): """Parameter storage for Vasicek model....
self.update_ajd() @staticmethod def get_model_name(): """Return model name. Returns ------- str Parameter vector """ return 'Vasicek' @staticmethod def get_names(subset='all', measure='PQ'): """Return parameter names. ...
self.mean, self.kappa, self.eta = theta
random_line_split
param_vasicek.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Vasicek parameter class ~~~~~~~~~~~~~~~~~~~~~~~ """ from __future__ import print_function, division import numpy as np from .param_generic import GenericParam __all__ = ['VasicekParam'] class VasicekParam(GenericParam): """Parameter storage for Vasicek model....
(self, theta): """Update attributes from parameter vector. Parameters ---------- theta : (nparams, ) array Parameter vector """ self.mean, self.kappa, self.eta = theta self.update_ajd() @staticmethod def get_model_name(): """Return m...
update
identifier_name
param_vasicek.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Vasicek parameter class ~~~~~~~~~~~~~~~~~~~~~~~ """ from __future__ import print_function, division import numpy as np from .param_generic import GenericParam __all__ = ['VasicekParam'] class VasicekParam(GenericParam):
mean : float Mean of the process kappa : float Mean reversion speed eta : float Instantaneous standard deviation measure : str Under which measure: - 'P' : physical measure - 'Q' : risk-neutral """ ...
"""Parameter storage for Vasicek model. Attributes ---------- mean : float Mean of the process kappa : float Mean reversion speed eta : float Instantaneous standard deviation measure : str Under which measure (P or Q) """ def __init__(self, mean=.5, kap...
identifier_body
HolidayVillageTwoTone.js
import createSvgIcon from './utils/createSvgIcon'; import { jsx as _jsx } from "react/jsx-runtime"; export default createSvgIcon([/*#__PURE__*/_jsx("path", { d: "m8 6.83-4 4V18h3v-3h2v3h3v-7.17l-4-4zM9 13H7v-2h2v2z",
opacity: ".3" }, "0"), /*#__PURE__*/_jsx("path", { d: "m8 4-6 6v10h12V10L8 4zm4 14H9v-3H7v3H4v-7.17l4-4 4 4V18zm-3-5H7v-2h2v2zm9 7V8.35L13.65 4h-2.83L16 9.18V20h2zm4 0V6.69L19.31 4h-2.83L20 7.52V20h2z" }, "1")], 'HolidayVillageTwoTone');
random_line_split
sessions.js
at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS-IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific languag...
} function writeSessionsToDisk() { try { var dateString = dateutils.dateFormat(new Date(), "yyyy-MM-dd"); var dataFile = new Packages.java.io.File(appjet.config.sessionStoreDir+"/sessions-"+dateString+".jslog"); var tmpFile = new Packages.java.io.File(dataFile.toString() + ".tmp"); dataFile.getPare...
{ // get expiring session map var db = _getCachedDb(); var map = _getExpiringSessionMap(db); map.remove(dataKey[0]); appjet.requestCache.sessionDomains = null; }
conditional_block
sessions.js
License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS-IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific...
// Keep sessionId in requestCache so this function can be called multiple // times per request without multiple calls to setCookie(). if (!appjet.requestCache.sessionId) { var sessionId = randomHash(16); response.setCookie({ name: cookieName, value: sessionId, path: "/", domain: (...
random_line_split
sessions.js
at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS-IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific languag...
function readLatestSessionsFromDisk() { var dir = new Packages.java.io.File(appjet.config.sessionStoreDir); if (! dir.exists()) { return; } var files = dir.listFiles(new Packages.java.io.FilenameFilter({ accept: function(dir, name) { return startsWith(name, "sessions") && endsWith(name, ".jslog") ...
{ var datePart = fname.substr("sessions-".length, "2009-09-24".length); return Number(datePart.split("-").join("")); }
identifier_body
sessions.js
License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS-IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific...
(fname) { var datePart = fname.substr("sessions-".length, "2009-09-24".length); return Number(datePart.split("-").join("")); } function readLatestSessionsFromDisk() { var dir = new Packages.java.io.File(appjet.config.sessionStoreDir); if (! dir.exists()) { return; } var files = dir.listFiles(new Packages.jav...
_extractDate
identifier_name
init.rs
; use api::egl; use api::egl::Context as EglContext; use api::egl::ffi::egl::Egl; #[derive(Clone)] pub enum RawContext { Egl(egl::ffi::egl::types::EGLContext), Wgl(winapi::HGLRC), } unsafe impl Send for RawContext {} unsafe impl Sync for RawContext {} pub fn new_window(window: &WindowAttributes, pf_reqs: &Pi...
}; // now that the `Window` struct is initialized, the main `Window::new()` function will // return and this events loop will run in parallel loop { let mut msg = mem::uninitialized(); if user32::GetMessageW(&mut msg, ptr::null_mut(), 0...
{ tx.send(Err(e)).ok(); return; }
conditional_block
init.rs
; use api::egl; use api::egl::Context as EglContext; use api::egl::ffi::egl::Egl; #[derive(Clone)] pub enum RawContext { Egl(egl::ffi::egl::types::EGLContext), Wgl(winapi::HGLRC), } unsafe impl Send for RawContext {} unsafe impl Sync for RawContext {} pub fn new_window(window: &WindowAttributes, pf_reqs: &Pi...
() -> Vec<u16> { let class_name = OsStr::new("Window Class").encode_wide().chain(Some(0).into_iter()) .collect::<Vec<_>>(); let class = winapi::WNDCLASSEXW { cbSize: mem::size_of::<winapi::WNDCLASSEXW>() as winapi::UINT, style: winapi::CS_HREDRAW |...
register_window_class
identifier_name
init.rs
; use api::egl; use api::egl::Context as EglContext; use api::egl::ffi::egl::Egl; #[derive(Clone)] pub enum RawContext { Egl(egl::ffi::egl::types::EGLContext), Wgl(winapi::HGLRC), } unsafe impl Send for RawContext {} unsafe impl Sync for RawContext {} pub fn new_window(window: &WindowAttributes, pf_reqs: &Pi...
user32::TranslateMessage(&msg); user32::DispatchMessageW(&msg); // calls `callback` (see the callback module) } } }); rx.recv().unwrap() } unsafe fn init(title: Vec<u16>, window: &WindowAttributes, pf_reqs: &PixelFormatRequirements, opengl:...
break; }
random_line_split
init.rs
Context; use api::egl; use api::egl::Context as EglContext; use api::egl::ffi::egl::Egl; #[derive(Clone)] pub enum RawContext { Egl(egl::ffi::egl::types::EGLContext), Wgl(winapi::HGLRC), } unsafe impl Send for RawContext {} unsafe impl Sync for RawContext {} pub fn new_window(window: &WindowAttributes, pf_re...
Err(e) => { tx.send(Err(e)).ok(); return; } }; // now that the `Window` struct is initialized, the main `Window::new()` function will // return and this events loop will run in parallel loop { ...
{ let egl = egl.map(|e| e.clone()); let window = window.clone(); let pf_reqs = pf_reqs.clone(); let opengl = opengl.clone(); // initializing variables to be sent to the task let title = OsStr::new(&window.title).encode_wide().chain(Some(0).into_iter()) ...
identifier_body
TestNativeExp2.rs
/* * Copyright (C) 2016 The Android Open Source Project * * 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...
float4 __attribute__((kernel)) testNativeExp2Float4Float4(float4 inV) { return native_exp2(inV); } half __attribute__((kernel)) testNativeExp2HalfHalf(half inV) { return native_exp2(inV); } half2 __attribute__((kernel)) testNativeExp2Half2Half2(half2 inV) { return native_exp2(inV); } half3 __attribute__...
random_line_split
exercise-delete-dialog.component.spec.ts
/* tslint:disable max-line-length */ import { ComponentFixture, TestBed, inject, fakeAsync, tick } from '@angular/core/testing'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import { Observable, of } from 'rxjs'; import { JhiEventManager } from 'ng-jhipster'; import { ArTEMiSTestModule } from '../../.....
TestBed.configureTestingModule({ imports: [ArTEMiSTestModule], declarations: [ExerciseDeleteDialogComponent], }) .overrideTemplate(ExerciseDeleteDialogComponent, '') .compileComponents(); fixture = TestBed.createComponen...
let service: ExerciseService; let mockEventManager: any; let mockActiveModal: any; beforeEach(() => {
random_line_split
setup.py
#!/usr/bin/env python ''' Created on Jan 6, 2018 @author: consultit ''' from panda3d.core import Filename import sys, os from subprocess import call ### NOTE: currently this script works only on GNU/Linux currdir = os.path.abspath(sys.path[0]) builddir = Filename.from_os_specific(os.path.join(currdir, '/ely/')).get...
modulelib = mpref + module + lsuff print('building "' + modulelib + '" ...') moduledir = '..' + elydir + module args = ['build.py', '--dir', moduledir, '--libs', libtools, '--libs_src', toolsdir, '--clean'] call(['/usr/bin/python'] + args) #print('installing "' +...
conditional_block
setup.py
#!/usr/bin/env python ''' Created on Jan 6, 2018 @author: consultit ''' from panda3d.core import Filename
currdir = os.path.abspath(sys.path[0]) builddir = Filename.from_os_specific(os.path.join(currdir, '/ely/')).get_fullpath() elydir = Filename.fromOsSpecific(os.path.join(currdir, '/ely/')).getFullpath() lpref = '' mpref = '' lsuff = '.so' ### tools = 'libtools' modules = ['ai', 'audio', 'control', 'physics'] if __name...
import sys, os from subprocess import call ### NOTE: currently this script works only on GNU/Linux
random_line_split
config.js
var dest = './public'; var src = './src'; module.exports = { browserSync: { server: { // Serve up our build folder baseDir: dest }, open: false, https: false }, sass: { src: [ src + '/assets/css/*.{sass,scss}', src + '/assets/css/**/*.{sass,scss}', src + '/assets/css/**/**/*.{sass,scss}' ...
src + '/assets/libs/*' ], dest: dest }, templateCache: { src: src, dest: dest }, jshint: { src: [ src + '/app/*.js', src + '/app/**/*.js', src + '/app/**/**/*.js', src + '/app/**/**/**/*.js' ] } };
src + '/app/**/**/*.html',
random_line_split
storeService.js
angular.module('macysApp') .service('storeService', function($http) { //ADD/DELETE PRODUCTS this.getAllProductData = function() { return $http({ method: 'GET', url: '/api/products' }); }; this.getOneProduct = function() { return $http({ method: 'GET', ...
}); }; //Post New Order to Cart this.postOrderToCart = function(orderInfo) { return $http({ method: 'POST', url: '/api/cart', data: orderInfo }).then(function(resp){ alert("Added to Cart"); }); }; });
data: placedOrder }).then(function(resp){ alert("Order Placed!");
random_line_split
snapUtils.ts
import { Box, Point, Diff, BoundingBox } from "./types"; export const SNAP_DISTANCE = 15; export const top = (box: Box) => box.y; export const bottom = (box: Box) => box.y + box.height; export const left = (box: Box) => box.x; export const right = (box: Box) => box.x + box.width; export const near = (a: number, b: n...
<B extends Box>( areConnected: (candidate: Box, n: Box) => boolean ) { return (candidates: B[], node: B): Set<B> => { const connected = new Set<B>(); const checkNode = (n: B) => { for (const candidate of candidates) { if (!connected.has(candidate) && areConnected(candidate, n)) { con...
traceConnection
identifier_name
snapUtils.ts
import { Box, Point, Diff, BoundingBox } from "./types"; export const SNAP_DISTANCE = 15; export const top = (box: Box) => box.y; export const bottom = (box: Box) => box.y + box.height; export const left = (box: Box) => box.x; export const right = (box: Box) => box.x + box.width; export const near = (a: number, b: n...
export const applyDiff = (a: Point, b: Point) => ({ x: a.x + b.x, y: a.y + b.y, }); // TODO: This should not export const applyMultipleDiffs = (initial: Point, ...diffs: Point[]) => { const metaDiff = diffs.reduce((m, diff) => ({ // Use the smallest non-zero diff for each axis. // TODO: Min should be t...
{ return (candidates: B[], node: B): Set<B> => { const connected = new Set<B>(); const checkNode = (n: B) => { for (const candidate of candidates) { if (!connected.has(candidate) && areConnected(candidate, n)) { connected.add(candidate); checkNode(candidate); } ...
identifier_body
snapUtils.ts
import { Box, Point, Diff, BoundingBox } from "./types"; export const SNAP_DISTANCE = 15; export const top = (box: Box) => box.y; export const bottom = (box: Box) => box.y + box.height; export const left = (box: Box) => box.x; export const right = (box: Box) => box.x + box.width; export const near = (a: number, b: n...
} if (overlapX(boxA, boxB)) { if (near(top(boxA), bottom(boxB))) { y = bottom(boxB); } else if (near(bottom(boxA), top(boxB))) { y = top(boxB) - boxA.height; } else if (near(top(boxA), top(boxB))) { y = top(boxB); } else if (near(bottom(boxA), bottom(boxB))) { y = bottom(bo...
{ x = right(boxB) - boxA.width; }
conditional_block
snapUtils.ts
import { Box, Point, Diff, BoundingBox } from "./types"; export const SNAP_DISTANCE = 15; export const top = (box: Box) => box.y; export const bottom = (box: Box) => box.y + box.height; export const left = (box: Box) => box.x; export const right = (box: Box) => box.x + box.width; export const near = (a: number, b: n...
boxes.forEach((node) => { bounding.top = Math.min(bounding.top, top(node)); bounding.right = Math.max(bounding.right, right(node)); bounding.bottom = Math.max(bounding.bottom, bottom(node)); bounding.left = Math.min(bounding.left, left(node)); }); return { x: bounding.left, y: bounding.to...
};
random_line_split
reader.rs
// Copyright 2016 MaidSafe.net limited. // // This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License, // version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which // licence you accepted on initial access to the Software (the "Licences"). // // By ...
} }
{ debug!( "Reading {len} bytes of data from file starting at offset of {pos} bytes ...", len = length, pos = position ); self.self_encryptor .read(position, length) .map_err(From::from) .i...
conditional_block
reader.rs
// Copyright 2016 MaidSafe.net limited. // // This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License, // version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which // licence you accepted on initial access to the Software (the "Licences"). // // By ...
position, length ); if (position + length) > self.size() { err!(NfsError::InvalidRange) } else { debug!( "Reading {len} bytes of data from file starting at offset of {pos} bytes ...", len = length, p...
random_line_split
reader.rs
// Copyright 2016 MaidSafe.net limited. // // This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License, // version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which // licence you accepted on initial access to the Software (the "Licences"). // // By ...
<T> { client: Client<T>, self_encryptor: SelfEncryptor<SelfEncryptionStorage<T>>, } impl<T: 'static> Reader<T> { /// Create a new instance of Reader pub fn new( client: Client<T>, storage: SelfEncryptionStorage<T>, file: &File, encryption_key: Option<shared_secretbox::Ke...
Reader
identifier_name
storage.test.ts
import * as test from 'tape' import { Storage } from './storage' class MockStorage extends Storage { storage = new Map<string, any>() constructor(private _prefix: string = '') { super() } get<T>(key: string, fallback: T): T { return this.storage.get(this._prefix + key) || fallback }...
(_prefix: string): Storage { throw new Error('Not implemented') } keys(): string[] { throw new Error('Not implemented') } } const tn = ([s]: TemplateStringsArray) => `Storage - ${s}` test(tn`Should use the original value if no value is returned`, t => { let s = new MockStorage() le...
prefix
identifier_name
storage.test.ts
import * as test from 'tape' import { Storage } from './storage' class MockStorage extends Storage { storage = new Map<string, any>() constructor(private _prefix: string = '') { super() } get<T>(key: string, fallback: T): T { return this.storage.get(this._prefix + key) || fallback }...
keys(): string[] { throw new Error('Not implemented') } } const tn = ([s]: TemplateStringsArray) => `Storage - ${s}` test(tn`Should use the original value if no value is returned`, t => { let s = new MockStorage() let fallback = {someKey: 'val'} s.with('key', fallback, () => {}) t.de...
{ throw new Error('Not implemented') }
identifier_body
storage.test.ts
import * as test from 'tape' import { Storage } from './storage' class MockStorage extends Storage { storage = new Map<string, any>() constructor(private _prefix: string = '') {
} get<T>(key: string, fallback: T): T { return this.storage.get(this._prefix + key) || fallback } set(key: string, value: any): void { this.storage.set(this._prefix + key, value) } clear(_prefix?: string | undefined): void { throw new Error('Not implemented') } pr...
super()
random_line_split
editpw.js
import React from "react"; import PropTypes from "prop-types"; import { withRouter } from "react-router-dom"; import { fetch_single_user, reset_password } from '../../api'; import { notify } from 'react-notify-toast'; import validatePassword from '../../common/utilities/validatePassword'; import Spinner from '../../co...
}); } editPassword() { this.setState({ loading: true, saving: true }); let errors = this.state.error; errors.password = ""; errors.confirmPassword = ""; errors.generic = ""; // Check fields are not empty if (this.state.password.trim() == "") { errors.password = "Please enter a password."; } ...
{ self.props.history.push("/users"); }
conditional_block
editpw.js
import React from "react"; import PropTypes from "prop-types"; import { withRouter } from "react-router-dom"; import { fetch_single_user, reset_password } from '../../api'; import { notify } from 'react-notify-toast'; import validatePassword from '../../common/utilities/validatePassword'; import Spinner from '../../co...
this.editPassword = this.editPassword.bind(this); this.changeField = this.changeField.bind(this); } componentDidMount() { this.loadUser(); } loadUser() { this.setState({ loading: true }); const fullstr = document.location.pathname.toString(); const tmpfullsre = fullstr.split("/"); const id = tmp...
this.loadUser = this.loadUser.bind(this);
random_line_split
editpw.js
import React from "react"; import PropTypes from "prop-types"; import { withRouter } from "react-router-dom"; import { fetch_single_user, reset_password } from '../../api'; import { notify } from 'react-notify-toast'; import validatePassword from '../../common/utilities/validatePassword'; import Spinner from '../../co...
(props) { super(props); this.state = { id: "", password: "", confpassword: "", header: "", loading: false, deleting: false, saving: false, error: { password: null, confirmPassword: null, generic: null, } }; this.loadUser = this.loadUser.bind(this); this.editPassword...
constructor
identifier_name
flush.rs
use core::marker::PhantomData; use core::pin::Pin; use futures_core::future::Future; use futures_core::task::{Context, Poll}; use futures_sink::Sink; /// Future for the [`flush`](super::SinkExt::flush) method. #[derive(Debug)] #[must_use = "futures do nothing unless you `.await` or poll them"] pub struct Flush<'a, Si:...
( mut self: Pin<&mut Self>, cx: &mut Context<'_>, ) -> Poll<Self::Output> { Pin::new(&mut self.sink).poll_flush(cx) } }
poll
identifier_name
flush.rs
use core::marker::PhantomData; use core::pin::Pin; use futures_core::future::Future; use futures_core::task::{Context, Poll}; use futures_sink::Sink; /// Future for the [`flush`](super::SinkExt::flush) method. #[derive(Debug)] #[must_use = "futures do nothing unless you `.await` or poll them"] pub struct Flush<'a, Si:...
} impl<Si: Sink<Item> + Unpin + ?Sized, Item> Future for Flush<'_, Si, Item> { type Output = Result<(), Si::Error>; fn poll( mut self: Pin<&mut Self>, cx: &mut Context<'_>, ) -> Poll<Self::Output> { Pin::new(&mut self.sink).poll_flush(cx) } }
{ Flush { sink, _phantom: PhantomData, } }
identifier_body
flush.rs
use core::marker::PhantomData; use core::pin::Pin; use futures_core::future::Future; use futures_core::task::{Context, Poll}; use futures_sink::Sink; /// Future for the [`flush`](super::SinkExt::flush) method.
} // Pin is never projected to a field. impl<Si: Unpin + ?Sized, Item> Unpin for Flush<'_, Si, Item> {} /// A future that completes when the sink has finished processing all /// pending requests. /// /// The sink itself is returned after flushing is complete; this adapter is /// intended to be used when you want to s...
#[derive(Debug)] #[must_use = "futures do nothing unless you `.await` or poll them"] pub struct Flush<'a, Si: ?Sized, Item> { sink: &'a mut Si, _phantom: PhantomData<fn(Item)>,
random_line_split
account_wizard.py
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) conexus.at # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public ...
(osv.osv_memory): _inherit='wizard.multi.charts.accounts' _defaults = { 'code_digits' : 0, } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
AccountWizard_cd
identifier_name