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
scalar.rs
// mrusty. mruby safe bindings for Rust // Copyright (C) 2016 Dragoș Tiselice // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. use mrusty::MrubyImpl; use super::...
}); def!("value=", |mruby, slf: (&mut Scalar), v: f64| { slf.set_value(v as f32); mruby.nil() }); def!("*", |mruby, slf: (&Scalar), vector: (&Vector)| { mruby.obj((*slf).clone() * (*vector).clone()) }); def!("panic", |_slf: Value| { panic!("I always panic."); ...
}); def!("value", |mruby, slf: (&Scalar)| { mruby.float(slf.value as f64)
random_line_split
scalar.rs
// mrusty. mruby safe bindings for Rust // Copyright (C) 2016 Dragoș Tiselice // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. use mrusty::MrubyImpl; use super::...
} mrusty_class!(Scalar, { def!("initialize", |v: f64| { Scalar::new(v as f32) }); def!("value", |mruby, slf: (&Scalar)| { mruby.float(slf.value as f64) }); def!("value=", |mruby, slf: (&mut Scalar), v: f64| { slf.set_value(v as f32); mruby.nil() }); def!(...
self.value = value; }
identifier_body
index.js
"use strict"; exports.__esModule = true; exports.default = function (_ref) { var t = _ref.types; function addDisplayName(id, call) { var props = call.arguments[0].properties; var safe = true; for (var i = 0; i < props.length; i++) { var prop = props[i]; var key = t.toComputedKey(prop); ...
} addDisplayName(displayName, node.declaration); } }, CallExpression: function CallExpression(path) { var node = path.node; if (!isCreateClass(node)) return; var id = void 0; path.find(function (path) { if (path.isAssignmentExpression...
var displayName = state.file.opts.basename; if (displayName === "index") { displayName = _path2.default.basename(_path2.default.dirname(state.file.opts.filename));
random_line_split
index.js
"use strict"; exports.__esModule = true; exports.default = function (_ref) { var t = _ref.types; function addDisplayName(id, call) { var props = call.arguments[0].properties; var safe = true; for (var i = 0; i < props.length; i++) { var prop = props[i]; var key = t.toComputedKey(prop); ...
return { visitor: { ExportDefaultDeclaration: function ExportDefaultDeclaration(_ref2, state) { var node = _ref2.node; if (isCreateClass(node.declaration)) { var displayName = state.file.opts.basename; if (displayName === "index") { displayName = _path2.de...
{ if (!node || !t.isCallExpression(node)) return false; if (!isCreateClassCallExpression(node.callee)) return false; var args = node.arguments; if (args.length !== 1) return false; var first = args[0]; if (!t.isObjectExpression(first)) return false; return true; }
identifier_body
index.js
"use strict"; exports.__esModule = true; exports.default = function (_ref) { var t = _ref.types; function addDisplayName(id, call) { var props = call.arguments[0].properties; var safe = true; for (var i = 0; i < props.length; i++)
if (safe) { props.unshift(t.objectProperty(t.identifier("displayName"), t.stringLiteral(id))); } } var isCreateClassCallExpression = t.buildMatchMemberExpression("React.createClass"); function isCreateClass(node) { if (!node || !t.isCallExpression(node)) return false; if (!isCreateClass...
{ var prop = props[i]; var key = t.toComputedKey(prop); if (t.isLiteral(key, { value: "displayName" })) { safe = false; break; } }
conditional_block
index.js
"use strict"; exports.__esModule = true; exports.default = function (_ref) { var t = _ref.types; function addDisplayName(id, call) { var props = call.arguments[0].properties; var safe = true; for (var i = 0; i < props.length; i++) { var prop = props[i]; var key = t.toComputedKey(prop); ...
(obj) { return obj && obj.__esModule ? obj : { default: obj }; } module.exports = exports["default"];
_interopRequireDefault
identifier_name
map.ts
import type { GTFSData, Stop } from '../../shared/gtfs-types.js'; import { memoize } from '../../shared/utils/memoize.js'; import { findClosestStop } from '../info-worker.js'; import type { State } from './store.js'; const getClosestToUser = memoize(findClosestStop); const getClosestToSearch = memoize(findClosestStop)...
(stop: Stop | undefined) { return stop?.stop_id; } /** * Returns the ID of the stop that should be displayed in the user interface. * @param stops Map of stop IDs to stops. * @param state Current UI state. */ export function stopToDisplay( stops: GTFSData['stops'], selectedStop: string | null | undefined, ...
getStopId
identifier_name
map.ts
import type { GTFSData, Stop } from '../../shared/gtfs-types.js'; import { memoize } from '../../shared/utils/memoize.js'; import { findClosestStop } from '../info-worker.js'; import type { State } from './store.js'; const getClosestToUser = memoize(findClosestStop); const getClosestToSearch = memoize(findClosestStop)...
return selectedStop || undefined; } }); }
return closestToUser(stops, state).then(getStopId); case 'search': return closestToSearch(stops, state).then(getStopId); case 'stop':
random_line_split
map.ts
import type { GTFSData, Stop } from '../../shared/gtfs-types.js'; import { memoize } from '../../shared/utils/memoize.js'; import { findClosestStop } from '../info-worker.js'; import type { State } from './store.js'; const getClosestToUser = memoize(findClosestStop); const getClosestToSearch = memoize(findClosestStop)...
/** * Returns the ID of the stop that should be displayed in the user interface. * @param stops Map of stop IDs to stops. * @param state Current UI state. */ export function stopToDisplay( stops: GTFSData['stops'], selectedStop: string | null | undefined, state: State, ) { return Promise.resolve().then(()...
{ return stop?.stop_id; }
identifier_body
lib.rs
//! A simple X11 status bar for use with simple WMs. //! //! Cnx is written to be customisable, simple and fast. Where possible, it //! prefers to asynchronously wait for changes in the underlying data sources //! (and uses [`tokio`] to achieve this), rather than periodically //! calling out to external programs. //! /...
ync fn run_inner(self) -> Result<()> { let mut bar = Bar::new(self.position)?; let mut widgets = StreamMap::with_capacity(self.widgets.len()); for widget in self.widgets { let idx = bar.add_content(Vec::new())?; widgets.insert(idx, widget.into_stream()?); } ...
// Use a single-threaded event loop. We aren't interested in // performance too much, so don't mind if we block the loop // occasionally. We are using events to get woken up as // infrequently as possible (to save battery). let rt = Runtime::new()?; let local = task::LocalSet::...
identifier_body
lib.rs
//! A simple X11 status bar for use with simple WMs. //! //! Cnx is written to be customisable, simple and fast. Where possible, it //! prefers to asynchronously wait for changes in the underlying data sources //! (and uses [`tokio`] to achieve this), rather than periodically //! calling out to external programs. //! /...
//! customizing Cnx are then limited). //! //! Before running Cnx, you'll need to make sure your system has the required //! dependencies, which are described in the [`README`][readme-deps]. //! //! # Built-in widgets //! //! There are currently these widgets available: //! //! - [`crate::widgets::ActiveWindowTitle`] —...
//! A more complex example is given in [`cnx-bin/src/main.rs`] alongside the project. //! (This is the default `[bin]` target for the crate, so you _could_ use it by //! either executing `cargo run` from the crate root, or even running `cargo //! install cnx; cnx`. However, neither of these are recommended as options f...
random_line_split
lib.rs
//! A simple X11 status bar for use with simple WMs. //! //! Cnx is written to be customisable, simple and fast. Where possible, it //! prefers to asynchronously wait for changes in the underlying data sources //! (and uses [`tokio`] to achieve this), rather than periodically //! calling out to external programs. //! /...
self, widget: W) where W: Widget + 'static, { self.widgets.push(Box::new(widget)); } /// Runs the Cnx instance. /// /// This method takes ownership of the Cnx instance and runs it until either /// the process is terminated, or an internal error is returned. pub fn run(s...
et<W>(&mut
identifier_name
groups.js
"use strict"; /*global define, templates, socket, ajaxify, app, admin, bootbox, utils, config */ define('admin/manage/groups', [ 'translator', 'components' ], function(translator, components) { var Groups = {}; var intervalId = 0; Groups.init = function() { var createModal = $('#create-modal'), createGroup...
groupsEl.find('tr').after(html); }); }); } var queryEl = $('#group-search'); queryEl.on('keyup', function() { if (intervalId) { clearTimeout(intervalId); intervalId = 0; } intervalId = setTimeout(doSearch, 200); }); } return Groups; });
{ if (!queryEl.val()) { return ajaxify.refresh(); } $('.pagination').addClass('hide'); var groupsEl = $('.groups-list'); socket.emit('groups.search', { query: queryEl.val(), options: { sort: 'date' } }, function(err, groups) { if (err) { return app.alertError(err.message)...
identifier_body
groups.js
"use strict"; /*global define, templates, socket, ajaxify, app, admin, bootbox, utils, config */ define('admin/manage/groups', [ 'translator', 'components' ], function(translator, components) { var Groups = {}; var intervalId = 0; Groups.init = function() { var createModal = $('#create-modal'), createGroup...
$('.groups-list').on('click', 'button[data-action]', function() { var el = $(this), action = el.attr('data-action'), groupName = el.parents('tr[data-groupname]').attr('data-groupname'); switch (action) { case 'delete': bootbox.confirm('Are you sure you wish to delete this group?', function(conf...
}); });
random_line_split
groups.js
"use strict"; /*global define, templates, socket, ajaxify, app, admin, bootbox, utils, config */ define('admin/manage/groups', [ 'translator', 'components' ], function(translator, components) { var Groups = {}; var intervalId = 0; Groups.init = function() { var createModal = $('#create-modal'), createGroup...
}); $('#create').on('click', function() { createModal.modal('show'); setTimeout(function() { createGroupName.focus(); }, 250); }); createModalGo.on('click', function() { var submitObj = { name: createGroupName.val(), description: $('#create-group-desc').val() }, errorText; ...
{ createModalGo.click(); }
conditional_block
groups.js
"use strict"; /*global define, templates, socket, ajaxify, app, admin, bootbox, utils, config */ define('admin/manage/groups', [ 'translator', 'components' ], function(translator, components) { var Groups = {}; var intervalId = 0; Groups.init = function() { var createModal = $('#create-modal'), createGroup...
() { if (!queryEl.val()) { return ajaxify.refresh(); } $('.pagination').addClass('hide'); var groupsEl = $('.groups-list'); socket.emit('groups.search', { query: queryEl.val(), options: { sort: 'date' } }, function(err, groups) { if (err) { return app.alertError(err.messa...
doSearch
identifier_name
inherited_table.mako.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ <%namespace name="helpers" file="/helpers.mako.rs" /> <% data.new_style_struct("InheritedTable", inherited=True, ...
Ok(()) } } impl ToComputedValue for SpecifiedValue { type ComputedValue = computed_value::T; #[inline] fn to_computed_value(&self, context: &Context) -> computed_value::T { let horizontal = self.horizontal.to_computed_value(context); compute...
{ try!(dest.write_str(" ")); vertical.to_css(dest)?; }
conditional_block
inherited_table.mako.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ <%namespace name="helpers" file="/helpers.mako.rs" /> <% data.new_style_struct("InheritedTable", inherited=True, ...
} } } pub fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<SpecifiedValue,ParseError<'i>> { let mut first = None; let mut second = None; match Length::parse_non_negative_quirky(context, input, AllowQuirks::Yes) ...
random_line_split
inherited_table.mako.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ <%namespace name="helpers" file="/helpers.mako.rs" /> <% data.new_style_struct("InheritedTable", inherited=True, ...
(&self, other: &Self, self_portion: f64, other_portion: f64) -> Result<Self, ()> { Ok(T { horizontal: try!(self.horizontal.add_weighted(&other.horizontal, self_portion, other_portion)), ...
add_weighted
identifier_name
inherited_table.mako.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ <%namespace name="helpers" file="/helpers.mako.rs" /> <% data.new_style_struct("InheritedTable", inherited=True, ...
#[inline] fn compute_squared_distance(&self, other: &Self) -> Result<f64, ()> { Ok(try!(self.horizontal.compute_squared_distance(&other.horizontal)) + try!(self.vertical.compute_squared_distance(&other.vertical))) } } } #[derive(C...
{ self.compute_squared_distance(other).map(|sd| sd.sqrt()) }
identifier_body
generate.py
############################################################################### # Language Modeling on Penn Tree Bank # # This file generates new sentences sampled from the language model # ############################################################################### import argparse import torch from torch.autograd...
parser = argparse.ArgumentParser(description='PyTorch PTB Language Model') # Model parameters. parser.add_argument('--data', type=str, default='./data/penn', help='location of the data corpus') parser.add_argument('--checkpoint', type=str, default='./model.pt', help='model chec...
import data
random_line_split
generate.py
############################################################################### # Language Modeling on Penn Tree Bank # # This file generates new sentences sampled from the language model # ############################################################################### import argparse import torch from torch.autograd...
else: model.cpu() corpus = data.Corpus(args.data) ntokens = len(corpus.dictionary) hidden = model.init_hidden(1) input = Variable(torch.rand(1, 1).mul(ntokens).long(), volatile=True) if args.cuda: input.data = input.data.cuda() with open(args.outf, 'w') as outf: for i in range(args.words): output...
model.cuda()
conditional_block
base.py
from django.conf import settings from django.db import models from django.utils.translation import ugettext_lazy as _ from .fields import HexIntegerField from .managers import APNSDeviceManager, GCMDeviceManager try: instapush_settings = settings.INSTAPUSH_SETTINGS except AttributeError: raise ImproperlyCon...
return gcm_send_message(registration_id=self.registration_id, data=data, **kwargs) class APNSDevice(BaseDevice): """ Represents an iOS device """ device_id = models.UUIField(_('Device ID'), blank=True, null=True, db_index=True) registration_id = models.CharFi...
data["message"] = message
conditional_block
base.py
from django.conf import settings from django.db import models from django.utils.translation import ugettext_lazy as _ from .fields import HexIntegerField from .managers import APNSDeviceManager, GCMDeviceManager try: instapush_settings = settings.INSTAPUSH_SETTINGS except AttributeError: raise ImproperlyCon...
device_id = HexIntegerField(_('Device ID'), blank=True, null=True, db_index=True) registration_id = models.TextField(_('Registration ID')) ## Set custom manager objects = GCMDeviceManager() class Meta: verbose_name = _('GCM Device') verbose_name_plural = _('GCM Devices'...
"""
random_line_split
base.py
from django.conf import settings from django.db import models from django.utils.translation import ugettext_lazy as _ from .fields import HexIntegerField from .managers import APNSDeviceManager, GCMDeviceManager try: instapush_settings = settings.INSTAPUSH_SETTINGS except AttributeError: raise ImproperlyCon...
(models.Model): """ Represents a base device object. This class defines the generic fields to be used by all device types. All other device types should inherit from this. """ name = models.CharField(_('name'), max_length=255, blank=True, null=True) active = models.BooleanField(_('active'),...
BaseDevice
identifier_name
base.py
from django.conf import settings from django.db import models from django.utils.translation import ugettext_lazy as _ from .fields import HexIntegerField from .managers import APNSDeviceManager, GCMDeviceManager try: instapush_settings = settings.INSTAPUSH_SETTINGS except AttributeError: raise ImproperlyCon...
class APNSDevice(BaseDevice): """ Represents an iOS device """ device_id = models.UUIField(_('Device ID'), blank=True, null=True, db_index=True) registration_id = models.CharField(_('Registration ID'), max_length=64, unique=True) ## Set custom manager APNSDeviceM...
""" Sends a push notification to this device via GCM """ from ..libs.gcm import gcm_send_message data = kwargs.pop("extra", {}) if message is not None: data["message"] = message return gcm_send_message(registration_id=self.registration_id, da...
identifier_body
switchMapFirst.js
var RxOld = require('rx'); var RxNew = require('../../../../index'); module.exports = function (suite) { var oldMergeMapWithCurrentThreadScheduler = RxOld.Observable.range(0, 25, RxOld.Scheduler.currentThread) .flatMapFirst(function (x) { return RxOld.Observable.range(x, 25, RxOld.Scheduler.currentThread);...
(x) { } function _error(e) { } function _complete() { } return suite .add('old switchMapFirst with current thread scheduler', function () { oldMergeMapWithCurrentThreadScheduler.subscribe(_next, _error, _complete); }) .add('new switchMapFirst with current thread scheduler', function () { n...
_next
identifier_name
switchMapFirst.js
var RxOld = require('rx'); var RxNew = require('../../../../index'); module.exports = function (suite) { var oldMergeMapWithCurrentThreadScheduler = RxOld.Observable.range(0, 25, RxOld.Scheduler.currentThread) .flatMapFirst(function (x) { return RxOld.Observable.range(x, 25, RxOld.Scheduler.currentThread);...
function _complete() { } return suite .add('old switchMapFirst with current thread scheduler', function () { oldMergeMapWithCurrentThreadScheduler.subscribe(_next, _error, _complete); }) .add('new switchMapFirst with current thread scheduler', function () { newMergeMapWithCurrentThreadSched...
{ }
identifier_body
switchMapFirst.js
var RxOld = require('rx'); var RxNew = require('../../../../index'); module.exports = function (suite) { var oldMergeMapWithCurrentThreadScheduler = RxOld.Observable.range(0, 25, RxOld.Scheduler.currentThread) .flatMapFirst(function (x) { return RxOld.Observable.range(x, 25, RxOld.Scheduler.currentThread);...
};
}) .add('new switchMapFirst with current thread scheduler', function () { newMergeMapWithCurrentThreadScheduler.subscribe(_next, _error, _complete); });
random_line_split
register-custom-component.ts
import { Injector, Type } from '@angular/core'; import { createCustomElement } from '@angular/elements'; import { Components } from 'formiojs'; import { FormioCustomComponentInfo } from '../elements.common'; import { createCustomFormioComponent } from './create-custom-component'; import { CustomTagsService } from './cu...
( options: FormioCustomComponentInfo, angularComponent: Type<any>, formioClass: any, injector: Injector, ): void { registerCustomTag(options.selector, injector); const complexCustomComponent = createCustomElement(angularComponent, { injector }); customElements.define(options.selector, complexCustomCompon...
registerCustomFormioComponentWithClass
identifier_name
register-custom-component.ts
import { Injector, Type } from '@angular/core'; import { createCustomElement } from '@angular/elements'; import { Components } from 'formiojs'; import { FormioCustomComponentInfo } from '../elements.common'; import { createCustomFormioComponent } from './create-custom-component'; import { CustomTagsService } from './cu...
}
const complexCustomComponent = createCustomElement(angularComponent, { injector }); customElements.define(options.selector, complexCustomComponent); Components.setComponent(options.type, formioClass);
random_line_split
register-custom-component.ts
import { Injector, Type } from '@angular/core'; import { createCustomElement } from '@angular/elements'; import { Components } from 'formiojs'; import { FormioCustomComponentInfo } from '../elements.common'; import { createCustomFormioComponent } from './create-custom-component'; import { CustomTagsService } from './cu...
export function registerCustomFormioComponent( options: FormioCustomComponentInfo, angularComponent: Type<any>, injector: Injector, ): void { registerCustomTag(options.selector, injector); const complexCustomComponent = createCustomElement(angularComponent, { injector }); customElements.define(options.se...
{ tags.forEach(tag => registerCustomTag(tag, injector)); }
identifier_body
main.rs
// Copyright (c) 2013-2015 Sandstorm Development Group, Inc. and contributors // Licensed under the MIT License: // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, inc...
println!("usage: {} [client | server] ADDRESS", args[0]); }
random_line_split
main.rs
// Copyright (c) 2013-2015 Sandstorm Development Group, Inc. and contributors // Licensed under the MIT License: // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, inc...
{ let args : Vec<String> = ::std::env::args().collect(); if args.len() >= 2 { match &args[1][..] { "client" => return client::main(), "server" => return server::main(), _ => (), } } println!("usage: {} [client | server] ADDRESS", args[0]); }
identifier_body
main.rs
// Copyright (c) 2013-2015 Sandstorm Development Group, Inc. and contributors // Licensed under the MIT License: // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, inc...
() { let args : Vec<String> = ::std::env::args().collect(); if args.len() >= 2 { match &args[1][..] { "client" => return client::main(), "server" => return server::main(), _ => (), } } println!("usage: {} [client | server] ADDRESS", args[0]); }
main
identifier_name
timestamp.rs
// Copyright: Ankitects Pty Ltd and contributors // License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html use crate::define_newtype;
use chrono::prelude::*; use lazy_static::lazy_static; use std::env; use std::time; define_newtype!(TimestampSecs, i64); define_newtype!(TimestampMillis, i64); impl TimestampSecs { pub fn now() -> Self { Self(elapsed().as_secs() as i64) } pub fn zero() -> Self { Self(0) } pub fn e...
random_line_split
timestamp.rs
// Copyright: Ankitects Pty Ltd and contributors // License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html use crate::define_newtype; use chrono::prelude::*; use lazy_static::lazy_static; use std::env; use std::time; define_newtype!(TimestampSecs, i64); define_newtype!(TimestampMillis, i64); im...
{ if *TESTING { // shift clock around rollover time to accomodate Python tests that make bad assumptions. // we should update the tests in the future and remove this hack. let mut elap = time::SystemTime::now() .duration_since(time::SystemTime::UNIX_EPOCH) .unwrap(); ...
identifier_body
timestamp.rs
// Copyright: Ankitects Pty Ltd and contributors // License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html use crate::define_newtype; use chrono::prelude::*; use lazy_static::lazy_static; use std::env; use std::time; define_newtype!(TimestampSecs, i64); define_newtype!(TimestampMillis, i64); im...
else { time::SystemTime::now() .duration_since(time::SystemTime::UNIX_EPOCH) .unwrap() } }
{ // shift clock around rollover time to accomodate Python tests that make bad assumptions. // we should update the tests in the future and remove this hack. let mut elap = time::SystemTime::now() .duration_since(time::SystemTime::UNIX_EPOCH) .unwrap(); let now = ...
conditional_block
timestamp.rs
// Copyright: Ankitects Pty Ltd and contributors // License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html use crate::define_newtype; use chrono::prelude::*; use lazy_static::lazy_static; use std::env; use std::time; define_newtype!(TimestampSecs, i64); define_newtype!(TimestampMillis, i64); im...
() -> Self { Self(0) } pub fn elapsed_secs(self) -> u64 { (Self::now().0 - self.0).max(0) as u64 } /// YYYY-mm-dd pub(crate) fn date_string(self, offset: FixedOffset) -> String { offset.timestamp(self.0, 0).format("%Y-%m-%d").to_string() } pub fn local_utc_offset(s...
zero
identifier_name
is_present.js
import isBlank from 'ember-metal/is_blank'; /** A value is present if it not `isBlank`. ```javascript Ember.isPresent(); // false Ember.isPresent(null); // false Ember.isPresent(undefined); // false Ember.isPresent(''); // false Ember.isPresent([]); ...
(obj) { return !isBlank(obj); }
isPresent
identifier_name
is_present.js
import isBlank from 'ember-metal/is_blank'; /** A value is present if it not `isBlank`. ```javascript Ember.isPresent(); // false Ember.isPresent(null); // false Ember.isPresent(undefined); // false Ember.isPresent(''); // false Ember.isPresent([]); ...
@param {Object} obj Value to test @return {Boolean} @since 1.8.0 @public */ export default function isPresent(obj) { return !isBlank(obj); }
@method isPresent @for Ember
random_line_split
is_present.js
import isBlank from 'ember-metal/is_blank'; /** A value is present if it not `isBlank`. ```javascript Ember.isPresent(); // false Ember.isPresent(null); // false Ember.isPresent(undefined); // false Ember.isPresent(''); // false Ember.isPresent([]); ...
{ return !isBlank(obj); }
identifier_body
globals.d.ts
/// <reference lib="es2015" /> type StackTraceRecord = { [key: string]: string; }
code: number; /** * The parsed stack trace for this exception. */ readonly stackTrace: StackTraceRecord[]; /** * The exception message. */ message: string; /** * Constructor. */ __construct(message?: string, code?: number, previous?: Error): void; constru...
declare class Exception extends Error { name: string; previous?: Exception|Error;
random_line_split
globals.d.ts
/// <reference lib="es2015" /> type StackTraceRecord = { [key: string]: string; } declare class Exception extends Error { name: string; previous?: Exception|Error; code: number; /** * The parsed stack trace for this exception. */ readonly stackTrace: StackTraceRecord[]; /** ...
extends Exception {} declare class RuntimeException extends Exception {} declare class UnderflowException extends Exception {} declare class UnexpectedValueException extends Exception {} export {}; declare global { namespace NodeJS { interface Global { Exception: Newable<Exception>; ...
OutOfBoundsException
identifier_name
timestamp-picker.component.ts
import { startWith, takeUntil } from 'rxjs/operators'; import { Component, forwardRef, Input, OnDestroy, OnInit } from '@angular/core'; import { Subject } from 'rxjs'; import { ControlValueAccessor, FormBuilder, FormControl, FormGroup, NG_VALUE_ACCESSOR } from '@angular/forms'; import { coerceBooleanProperty } from '@a...
@Input() get disabled() { return this._disabled; } set disabled(dis) { this._disabled = coerceBooleanProperty(dis); this.setInnerInputDisableState(); } // Allows Angular to disable the input. setDisabledState(isDisabled: boolean): void { this.disabled = isDisabled; } private setInne...
}
random_line_split
timestamp-picker.component.ts
import { startWith, takeUntil } from 'rxjs/operators'; import { Component, forwardRef, Input, OnDestroy, OnInit } from '@angular/core'; import { Subject } from 'rxjs'; import { ControlValueAccessor, FormBuilder, FormControl, FormGroup, NG_VALUE_ACCESSOR } from '@angular/forms'; import { coerceBooleanProperty } from '@a...
ngOnInit() { this.formGroup = this.fb.group({ internalDate: new FormControl() }); this.formGroup.controls[INTERNAL_FIELD_NAME].valueChanges .pipe(startWith(null)) .pipe(takeUntil(this.componentDestroyed)) .subscribe((date: Date) => { if (date) { // offset need ...
{ return moment.tz(moment(date), 'America/Los_Angeles').utcOffset(); }
identifier_body
timestamp-picker.component.ts
import { startWith, takeUntil } from 'rxjs/operators'; import { Component, forwardRef, Input, OnDestroy, OnInit } from '@angular/core'; import { Subject } from 'rxjs'; import { ControlValueAccessor, FormBuilder, FormControl, FormGroup, NG_VALUE_ACCESSOR } from '@angular/forms'; import { coerceBooleanProperty } from '@a...
else if (isNullOrUndefined(value)) { this.formGroup.controls[INTERNAL_FIELD_NAME].reset(); } } propagateChange = (_: any) => {}; registerOnChange(fn) { this.propagateChange = fn; } registerOnTouched(fn: () => void): void { this.onTouched = fn; } @Input() get placeholder() { re...
{ const date = moment(value); const shift = this.getSeattleOffset(date) - this.getUserOffsetAtDate(date); const shiftedDate = date.add(shift, 'minutes').toDate(); this.formGroup.controls[INTERNAL_FIELD_NAME].patchValue(shiftedDate); }
conditional_block
timestamp-picker.component.ts
import { startWith, takeUntil } from 'rxjs/operators'; import { Component, forwardRef, Input, OnDestroy, OnInit } from '@angular/core'; import { Subject } from 'rxjs'; import { ControlValueAccessor, FormBuilder, FormControl, FormGroup, NG_VALUE_ACCESSOR } from '@angular/forms'; import { coerceBooleanProperty } from '@a...
(date: Date): number { return moment.tz(moment(date), this.userTimeZone).utcOffset(); } private getSeattleOffset(date: Date): number { return moment.tz(moment(date), 'America/Los_Angeles').utcOffset(); } ngOnInit() { this.formGroup = this.fb.group({ internalDate: new FormControl() }); ...
getUserOffsetAtDate
identifier_name
deleteNode.py
# Write a function to delete a node (except the tail) in a singly linked list, # given only access to that node. # # Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node # with value 3, the linked list should become 1 -> 2 -> 4 after calling your function. # # time: O(1) # space: O(1) # Defini...
(self, node): """ :type node: ListNode :rtype: void Do not return anything, modify node in-place instead. """ node.val = node.next.val node.next = node.next.next return if __name__ == '__main__': n1 = ListNode(1) n2 = ListNode(2) n3 = ListNode(3) ...
deleteNode
identifier_name
deleteNode.py
# Write a function to delete a node (except the tail) in a singly linked list, # given only access to that node. # # Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node # with value 3, the linked list should become 1 -> 2 -> 4 after calling your function. # # time: O(1) # space: O(1) # Defini...
node.next = node.next.next return if __name__ == '__main__': n1 = ListNode(1) n2 = ListNode(2) n3 = ListNode(3) n4 = ListNode(4) n1.next = n2 n2.next = n3 n3.next = n4 sol = Solution() sol.deleteNode(n1) print n1.val, n1.next.val, n1.next.next.val try: ...
""" :type node: ListNode :rtype: void Do not return anything, modify node in-place instead. """ node.val = node.next.val
random_line_split
deleteNode.py
# Write a function to delete a node (except the tail) in a singly linked list, # given only access to that node. # # Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node # with value 3, the linked list should become 1 -> 2 -> 4 after calling your function. # # time: O(1) # space: O(1) # Defini...
def deleteNode1(self, node): """ :type node: ListNode :rtype: void Do not return anything, modify node in-place instead. """ curt = node while curt.next is not None: curt.val = curt.next.val if curt.next.next is None: curt.next...
""" :type node: ListNode :rtype: void Do not return anything, modify node in-place instead. """ curt = node prev = None while curt.next is not None: curt.val = curt.next.val prev = curt curt = curt.next if prev is not None: ...
identifier_body
deleteNode.py
# Write a function to delete a node (except the tail) in a singly linked list, # given only access to that node. # # Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node # with value 3, the linked list should become 1 -> 2 -> 4 after calling your function. # # time: O(1) # space: O(1) # Defini...
if prev is not None: prev.next = None return def deleteNode1(self, node): """ :type node: ListNode :rtype: void Do not return anything, modify node in-place instead. """ curt = node while curt.next is not None: curt.val = curt....
curt.val = curt.next.val prev = curt curt = curt.next
conditional_block
divider.js
/*! * Angular Material Design * https://github.com/angular/material * @license MIT * v1.1.0-rc4-master-b1c1bde */ (function( window, angular, undefined ){ "use strict"; /** * @ngdoc module * @name material.components.divider * @description Divider module! */ angular.module('material.components.divider', [ '...
($mdTheming) { return { restrict: 'E', link: $mdTheming }; } MdDividerDirective.$inject = ["$mdTheming"]; })(window, window.angular);
MdDividerDirective
identifier_name
divider.js
/*! * Angular Material Design * https://github.com/angular/material * @license MIT * v1.1.0-rc4-master-b1c1bde */ (function( window, angular, undefined ){ "use strict"; /** * @ngdoc module * @name material.components.divider * @description Divider module! */ angular.module('material.components.divider', [ '...
* */ function MdDividerDirective($mdTheming) { return { restrict: 'E', link: $mdTheming }; } MdDividerDirective.$inject = ["$mdTheming"]; })(window, window.angular);
* </hljs>
random_line_split
divider.js
/*! * Angular Material Design * https://github.com/angular/material * @license MIT * v1.1.0-rc4-master-b1c1bde */ (function( window, angular, undefined ){ "use strict"; /** * @ngdoc module * @name material.components.divider * @description Divider module! */ angular.module('material.components.divider', [ '...
MdDividerDirective.$inject = ["$mdTheming"]; })(window, window.angular);
{ return { restrict: 'E', link: $mdTheming }; }
identifier_body
Map.js
import React, { PureComponent } from "react"; import PropTypes from "prop-types"; import classNames from "classnames"; import FormContainer from "global/containers/form"; import Form from "global/components/form"; import connectAndFetch from "utils/connectAndFetch"; import { Link } from "react-router-dom"; import lh fr...
() { const { resourceImport } = this.props; return ( <div> <FormContainer.Form model={resourceImport} name="backend-resource-import-update" create={this.create} update={this.update} onSuccess={this.onSuccess} className="form-secondary" ...
render
identifier_name
Map.js
import React, { PureComponent } from "react"; import PropTypes from "prop-types"; import classNames from "classnames"; import FormContainer from "global/containers/form"; import Form from "global/components/form"; import connectAndFetch from "utils/connectAndFetch"; import { Link } from "react-router-dom"; import lh fr...
onSuccess = model => { const { projectId } = this.props.match.params; const importId = model.id; const url = lh.link("backendResourceImportResults", projectId, importId); this.props.history.push(url); }; get buttonClasses() { return classNames( "buttons-icon-horizontal__button", ...
{ const { resourceImport } = this.props; if (resourceImport.attributes.state === "pending") { const { projectId } = this.props.match.params; const url = lh.link( "backendResourceImportEdit", projectId, resourceImport.id ); this.props.history.push(url); } }
identifier_body
Map.js
import React, { PureComponent } from "react"; import PropTypes from "prop-types"; import classNames from "classnames"; import FormContainer from "global/containers/form"; import Form from "global/components/form"; import connectAndFetch from "utils/connectAndFetch"; import { Link } from "react-router-dom"; import lh fr...
} onSuccess = model => { const { projectId } = this.props.match.params; const importId = model.id; const url = lh.link("backendResourceImportResults", projectId, importId); this.props.history.push(url); }; get buttonClasses() { return classNames( "buttons-icon-horizontal__button", ...
{ const { projectId } = this.props.match.params; const url = lh.link( "backendResourceImportEdit", projectId, resourceImport.id ); this.props.history.push(url); }
conditional_block
Map.js
import React, { PureComponent } from "react"; import PropTypes from "prop-types"; import classNames from "classnames"; import FormContainer from "global/containers/form"; import Form from "global/components/form"; import connectAndFetch from "utils/connectAndFetch"; import { Link } from "react-router-dom"; import lh fr...
} create = model => { return this.props.create(this.preSave(model)); }; update = (id, model) => { return this.props.update(id, this.preSave(model)); }; /* eslint-disable no-param-reassign */ preSave = model => { model.attributes.state = "mapped"; return model; }; /* eslint-enable no...
match.params.id );
random_line_split
edgeos_facts.py
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (c) 2018 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', ...
(self): self.responses = run_commands(self.module, list(self.COMMANDS)) class Default(FactsBase): COMMANDS = [ 'show version', 'show host name', ] def populate(self): super(Default, self).populate() data = self.responses[0] self.facts['version'] = self.pa...
populate
identifier_name
edgeos_facts.py
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (c) 2018 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', ...
entry = dict(revision=match.group(1), datetime=match.group(2), by=str(match.group(3)).strip(), via=str(match.group(4)).strip(), comment=None) elif entry: entry...
if match: if entry: entries.append(entry)
random_line_split
edgeos_facts.py
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (c) 2018 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', ...
subset = subset[1:] if subset == 'all': exclude_subsets.update(VALID_SUBSETS) continue exclude = True else: exclude = False if subset not in VALID_SUBSETS: module.fail_json(msg='Subset must be one of [%s], got %...
spec = dict( gather_subset=dict(default=['!config'], type='list') ) module = AnsibleModule(argument_spec=spec, supports_check_mode=True) warnings = list() gather_subset = module.params['gather_subset'] runable_subsets = set() exclude_subsets = set() fo...
identifier_body
edgeos_facts.py
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (c) 2018 Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', ...
self.facts['commits'] = entries class Neighbors(FactsBase): COMMANDS = [ 'show lldp neighbors', 'show lldp neighbors detail', ] def populate(self): super(Neighbors, self).populate() all_neighbors = self.responses[0] if 'LLDP not configured' not in all_n...
entry['comment'] = line.strip()
conditional_block
comm.rs
// -*- rust -*- // Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// option. This file may not be copied, modified, or distributed // except according to those terms. use core::comm::*; pub fn main() { let (p, ch) = stream(); let t = task::spawn(|| child(&ch) ); let y = p.recv(); error!("received"); error!(y); assert!((y == 10)); } fn child(c: &Chan<int>) {...
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
random_line_split
comm.rs
// -*- rust -*- // Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // ...
(c: &Chan<int>) { error!("sending"); c.send(10); error!("value sent"); }
child
identifier_name
comm.rs
// -*- rust -*- // Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // ...
fn child(c: &Chan<int>) { error!("sending"); c.send(10); error!("value sent"); }
{ let (p, ch) = stream(); let t = task::spawn(|| child(&ch) ); let y = p.recv(); error!("received"); error!(y); assert!((y == 10)); }
identifier_body
urls.py
import warnings from django.core.urlresolvers import ResolverMatch from django.core.urlresolvers import ( RegexURLPattern as DjangoRegexURLPattern, RegexURLResolver ) from django.core.exceptions import ImproperlyConfigured from django.utils import six from django.utils.deprecation import RemovedInDjango20Warni...
(prefix, *args): pattern_list = [] for t in args: if isinstance(t, (list, tuple)): t = url(prefix=prefix, *t) elif isinstance(t, RegexURLPattern): t.add_prefix(prefix) pattern_list.append(t) return pattern_list
patterns
identifier_name
urls.py
import warnings from django.core.urlresolvers import ResolverMatch from django.core.urlresolvers import ( RegexURLPattern as DjangoRegexURLPattern, RegexURLResolver ) from django.core.exceptions import ImproperlyConfigured from django.utils import six from django.utils.deprecation import RemovedInDjango20Warni...
warnings.warn( 'Support for string view arguments to url() is deprecated and ' 'will be removed in Django 2.0 (got %s). Pass the callable ' 'instead.' % view, RemovedInDjango20Warning, stacklevel=2 ) if not view: ...
if isinstance(view, six.string_types):
random_line_split
urls.py
import warnings from django.core.urlresolvers import ResolverMatch from django.core.urlresolvers import ( RegexURLPattern as DjangoRegexURLPattern, RegexURLResolver ) from django.core.exceptions import ImproperlyConfigured from django.utils import six from django.utils.deprecation import RemovedInDjango20Warni...
return RegexURLPattern(regex, view, kwargs, name) def patterns(prefix, *args): pattern_list = [] for t in args: if isinstance(t, (list, tuple)): t = url(prefix=prefix, *t) elif isinstance(t, RegexURLPattern): t.add_prefix(prefix) pattern_list.append(t) ...
view = prefix + '.' + view
conditional_block
urls.py
import warnings from django.core.urlresolvers import ResolverMatch from django.core.urlresolvers import ( RegexURLPattern as DjangoRegexURLPattern, RegexURLResolver ) from django.core.exceptions import ImproperlyConfigured from django.utils import six from django.utils.deprecation import RemovedInDjango20Warni...
def patterns(prefix, *args): pattern_list = [] for t in args: if isinstance(t, (list, tuple)): t = url(prefix=prefix, *t) elif isinstance(t, RegexURLPattern): t.add_prefix(prefix) pattern_list.append(t) return pattern_list
if isinstance(view, (list, tuple)): urlconf_module, app_name, namespace = ViewTimeProfiler(view) if DJANGO_VIEW_TIMER_ENABLED else view return RegexURLResolver(regex, urlconf_module, kwargs, app_name=app_name, namespace=namespace) else: if isinstance(view, six.string_types): warn...
identifier_body
shell.rs
lcccc :l ox 'cccc' 0 :l. :l .lxOKKXo kXKK0ko. "; */ const HELP: &'static str = "Available Commands: echo [string ...] clear eval <lhs> <op> <rhs> blink [rate] stop uptime rocket [timer] uname exit ...
fn previous(&self) -> Token { self.tokens[self.current - 1] } fn parse(&mut self) -> Result<Expr, ParseError> { self.expression() } fn expression(&mut self) -> Result<Expr, ParseError> { self.term() } fn term(&mut self) -> Result<Expr, ParseError> { let m...
{ self.tokens[self.current] }
identifier_body
shell.rs
lcccc :l ox 'cccc' 0 :l. :l .lxOKKXo kXKK0ko. "; */ const HELP: &'static str = "Available Commands: echo [string ...] clear eval <lhs> <op> <rhs> blink [rate] stop uptime rocket [timer] uname exit ...
enum ReadError { UnclosedString, } impl Display for ReadError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let msg = match *self { ReadError::UnclosedString => "unclosed string found", }; write!(f, "{}", msg) } } enum Command<'a> { Echo, Clear, ...
const UNAME_HELP: &'static str = "Displays system information"; const EXIT_HELP: &'static str = "Exit the shell"; const HELP_HELP: &'static str = "Display available commands or more information about a certain command";
random_line_split
shell.rs
lcccc :l ox 'cccc' 0 :l. :l .lxOKKXo kXKK0ko. "; */ const HELP: &'static str = "Available Commands: echo [string ...] clear eval <lhs> <op> <rhs> blink [rate] stop uptime rocket [timer] uname exit ...
else { Err(ParseError::UnmatchedParens) } }, _ => Err(ParseError::UnexpectedToken), } } } enum Expr { Op(Box<Expr>, Operator, Box<Expr>), Val(isize), } impl Expr { fn eval(&self) -> isize { match *self { ...
{ Ok(expr) }
conditional_block
shell.rs
lcccc :l ox 'cccc' 0 :l. :l .lxOKKXo kXKK0ko. "; */ const HELP: &'static str = "Available Commands: echo [string ...] clear eval <lhs> <op> <rhs> blink [rate] stop uptime rocket [timer] uname exit ...
(&mut self) -> Result<Expr, ParseError> { let mut expr = self.primary()?; while self.matches(Operator::Mul) || self.matches(Operator::Div) { let operator = if let Token::Op(op) = self.previous() { op } else { return Err(ParseError::Inv...
factor
identifier_name
index.d.ts
// Type definitions for jsrp 0.2 // Project: https://github.com/alax/jsrp // Definitions by: Harry Shipton <https://github.com/harryshipton> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export as namespace jsrp; export interface ClientOptions { username: string; password: string; len...
*/ getPublicKey(): string; /** * Returns the hex representation of the salt, as was passed into {@link init} * @returns {string} - hex representation of the salt */ getSalt(): string; /** * Sets the client's A value on the server, and compute values to complete authentication ...
/** * Returns the hex representation of the server's B value * @returns {string} - hex representation of B
random_line_split
index.d.ts
// Type definitions for jsrp 0.2 // Project: https://github.com/alax/jsrp // Definitions by: Harry Shipton <https://github.com/harryshipton> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export as namespace jsrp; export interface ClientOptions { username: string; password: string; len...
{ /** Client SRP constructor */ constructor(); /** * Initialise the client SRP and calculate needed SRP values * @param {ClientOptions} options - the client options including the username and password * @param {function(): any} callback - called when the client instance is ready to use ...
client
identifier_name
transaction.rs
: Address) -> SignedTransaction { SignedTransaction { transaction: UnverifiedTransaction { unsigned: self, r: U256::default(), s: U256::default(), v: 0, hash: 0.into(), }.compute_hash(), sender: from, public: Public::default(), } } /// Get the transaction cost in gas for the given...
} /// Signed transaction information. #[derive(Debug, Clone, Eq, PartialEq)] #[cfg_attr(feature = "ipc", binary)] pub struct UnverifiedTransaction { /// Plain Transaction. unsigned: Transaction, /// The V field of the signature; the LS bit described which half of the curve our point falls /// in. The MS bits desc...
{ Self::gas_required_for(match self.action{Action::Create=>true, Action::Call(_)=>false}, &self.data, schedule) }
identifier_body
transaction.rs
(&self) -> u8 { match self.v { v if v == 27 || v == 28 || v > 36 => ((v - 1) % 2) as u8, _ => 4 } } /// The `v` value that appears in the RLP. pub fn original_v(&self) -> u64 { self.v } /// The network ID, or `None` if this is a global transaction. pub fn network_id(&self) -> Option<u64> { match self.v { v i...
should_recover_from_network_specific_signing
identifier_name
transaction.rs
use rlp::*; use util::sha3::Hashable; use util::{H256, Address, U256, Bytes, HeapSizeOf}; use ethkey::{Signature, Secret, Public, recover, public_to_address, Error as EthkeyError}; use error::*; use evm::Schedule; use header::BlockNumber; use ethjson; #[derive(Debug, Clone, PartialEq, Eq)] #[cfg_attr(feature = "ipc", ...
random_line_split
transaction.rs
: Address) -> SignedTransaction { SignedTransaction { transaction: UnverifiedTransaction { unsigned: self, r: U256::default(), s: U256::default(), v: 0, hash: 0.into(), }.compute_hash(), sender: from, public: Public::default(), } } /// Get the transaction cost in gas for the given...
else { Ok(()) } } /// Get the hash of this header (sha3 of the RLP). pub fn hash(&self) -> H256 { self.hash } /// Recovers the public key of the sender. pub fn recover_public(&self) -> Result<Public, Error> { Ok(recover(&self.signature(), &self.unsigned.hash(self.network_id()))?) } /// Do basic val...
{ Err(EthkeyError::InvalidSignature.into()) }
conditional_block
visEdge.js
var _ = require('underscore'); var Backbone = require('backbone'); var GRAPHICS = require('../util/constants').GRAPHICS; var VisBase = require('../visuals/visBase').VisBase; var VisEdge = VisBase.extend({ defaults: { tail: null, head: null, animationSpeed: GRAPHICS.defaultAnimationTime, animationEas...
}, this); }, getID: function() { return this.get('tail').get('id') + '.' + this.get('head').get('id'); }, initialize: function() { this.validateAtInit(); // shorthand for the main objects this.gitVisuals = this.get('gitVisuals'); this.gitEngine = this.get('gitEngine'); this.get(...
{ throw new Error(key + ' is required!'); }
conditional_block
visEdge.js
var _ = require('underscore'); var Backbone = require('backbone'); var GRAPHICS = require('../util/constants').GRAPHICS; var VisBase = require('../visuals/visBase').VisBase; var VisEdge = VisBase.extend({ defaults: { tail: null, head: null, animationSpeed: GRAPHICS.defaultAnimationTime, animationEas...
getBezierCurve: function() { return this.genSmoothBezierPathString(this.get('tail'), this.get('head')); }, getStrokeColor: function() { return GRAPHICS.visBranchStrokeColorNone; }, setOpacity: function(opacity) { opacity = (opacity === undefined) ? 1 : opacity; this.get('path').attr({opacit...
random_line_split
be_true.rs
use matchers::matcher::Matcher; #[derive(Copy, Clone)] pub struct BeTrue { file_line: (&'static str, u32) } impl Matcher<bool> for BeTrue { #[allow(unused_variables)] fn assert_check(&self, expected: bool) -> bool { expected == true } #[allow(unused_variables)] fn msg(&self, expected: bool) -...
(&self, expected: bool) -> String { format!("Expected {} NOT to be true but it was.", stringify!(expected)) } fn get_file_line(&self) -> (&'static str, u32) { self.file_line } } pub fn be_true(file_line: (&'static str, u32)) -> Box<BeTrue> { Box::new(BeTrue { file_line: file_line }) } ...
negated_msg
identifier_name
be_true.rs
use matchers::matcher::Matcher; #[derive(Copy, Clone)] pub struct BeTrue { file_line: (&'static str, u32) }
#[allow(unused_variables)] fn assert_check(&self, expected: bool) -> bool { expected == true } #[allow(unused_variables)] fn msg(&self, expected: bool) -> String { format!("Expected {} to be true but it was not.", stringify!(expected)) } #[allow(unused_variables)] fn negated_msg(&s...
impl Matcher<bool> for BeTrue {
random_line_split
be_true.rs
use matchers::matcher::Matcher; #[derive(Copy, Clone)] pub struct BeTrue { file_line: (&'static str, u32) } impl Matcher<bool> for BeTrue { #[allow(unused_variables)] fn assert_check(&self, expected: bool) -> bool { expected == true } #[allow(unused_variables)] fn msg(&self, expected: bool) -...
fn get_file_line(&self) -> (&'static str, u32) { self.file_line } } pub fn be_true(file_line: (&'static str, u32)) -> Box<BeTrue> { Box::new(BeTrue { file_line: file_line }) } #[macro_export] macro_rules! be_true( () => ( be_true((file!(), expand_line!())) ); );
{ format!("Expected {} NOT to be true but it was.", stringify!(expected)) }
identifier_body
recent_data.rs
// Copyright 2013-2015, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> use ffi; use libc::c_char; use glib::translate::{ToGlib, ToGlibPtr, Stash}; pub struct Recen...
(&self) -> Stash<'a, *mut ffi::GtkRecentData, &'a RecentData> { let display_name = self.display_name.to_glib_none(); let description = self.description.to_glib_none(); let mime_type = self.mime_type.to_glib_none(); let app_name = self.app_name.to_glib_none(); let app_exec...
to_glib_none
identifier_name
recent_data.rs
// Copyright 2013-2015, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> use ffi; use libc::c_char; use glib::translate::{ToGlib, ToGlibPtr, Stash}; pub struct Recen...
} }
{ let display_name = self.display_name.to_glib_none(); let description = self.description.to_glib_none(); let mime_type = self.mime_type.to_glib_none(); let app_name = self.app_name.to_glib_none(); let app_exec = self.app_exec.to_glib_none(); let groups = (&*self.groups)....
identifier_body
recent_data.rs
// Copyright 2013-2015, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> use ffi; use libc::c_char; use glib::translate::{ToGlib, ToGlibPtr, Stash}; pub struct Recen...
mime_type: mime_type.0 as *mut c_char, app_name: app_name.0 as *mut c_char, app_exec: app_exec.0 as *mut c_char, groups: groups.0 as *mut *mut c_char, is_private: self.is_private.to_glib(), }); Stash(&mut *data, (data, [display_name, descripti...
let groups = (&*self.groups).to_glib_none(); let mut data = Box::new(ffi::GtkRecentData { display_name: display_name.0 as *mut c_char, description: description.0 as *mut c_char,
random_line_split
PhpUnitResolver.ts
import * as vscode from "vscode"; import Composer from "./ComposerDriver"; import GlobalPhpUnit from "./GlobalPhpUnitDriver"; import IPhpUnitDriver from "./IPhpUnitDriver"; import Path from "./PathDriver"; import Phar from "./PharDriver"; const phpUnitPath = async (): Promise<string> => { let path: string; const ...
(array) { const a = array.concat(); for (let i = 0; i < a.length; ++i) { for (let j = i + 1; j < a.length; ++j) { if (a[i] === a[j]) { a.splice(j--, 1); } } } return a; } order = arrayUnique((order || []).concat(drivers.map(d => d.name))); const sortedDriver...
arrayUnique
identifier_name
PhpUnitResolver.ts
import * as vscode from "vscode"; import Composer from "./ComposerDriver"; import GlobalPhpUnit from "./GlobalPhpUnitDriver"; import IPhpUnitDriver from "./IPhpUnitDriver"; import Path from "./PathDriver"; import Phar from "./PharDriver"; const phpUnitPath = async (): Promise<string> => { let path: string; const ...
} return null; }; const getDrivers = (order?: string[]): IPhpUnitDriver[] => { const drivers: IPhpUnitDriver[] = [ new Path(), new Composer(), new Phar(), new GlobalPhpUnit() ]; function arrayUnique(array) { const a = array.concat(); for (let i = 0; i < a.length; ++i) { for (...
{ return path; }
conditional_block
PhpUnitResolver.ts
import * as vscode from "vscode"; import Composer from "./ComposerDriver"; import GlobalPhpUnit from "./GlobalPhpUnitDriver"; import IPhpUnitDriver from "./IPhpUnitDriver"; import Path from "./PathDriver"; import Phar from "./PharDriver"; const phpUnitPath = async (): Promise<string> => { let path: string; const ...
return null; }; const getDrivers = (order?: string[]): IPhpUnitDriver[] => { const drivers: IPhpUnitDriver[] = [ new Path(), new Composer(), new Phar(), new GlobalPhpUnit() ]; function arrayUnique(array) { const a = array.concat(); for (let i = 0; i < a.length; ++i) { for (let j...
} }
random_line_split
PhpUnitResolver.ts
import * as vscode from "vscode"; import Composer from "./ComposerDriver"; import GlobalPhpUnit from "./GlobalPhpUnitDriver"; import IPhpUnitDriver from "./IPhpUnitDriver"; import Path from "./PathDriver"; import Phar from "./PharDriver"; const phpUnitPath = async (): Promise<string> => { let path: string; const ...
order = arrayUnique((order || []).concat(drivers.map(d => d.name))); const sortedDrivers = drivers.sort((a, b) => { return order.indexOf(a.name) - order.indexOf(b.name); }); return sortedDrivers; }; export { phpUnitPath as resolvePhpUnitPath };
{ const a = array.concat(); for (let i = 0; i < a.length; ++i) { for (let j = i + 1; j < a.length; ++j) { if (a[i] === a[j]) { a.splice(j--, 1); } } } return a; }
identifier_body
translate.ts
. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ export let current_language = window["ogs_current_language"] || 'en'; export let languages = window["ogs_languages"] || {'en': 'English'}; export let countries =...
export function npgettext(context, singular, plural, count) { let key = context + "" + singular + "" + plural; if (key in catalog) { return catalog[key][count === 1 ? 0 : 1]; } return debug_wrap(count === 1 ? singular : plural); } let gettext_formats = {}; gettext_formats["DATETIME_FORMAT"...
{ let key = context + "" + msgid; if (key in catalog) { return catalog[key][0]; } return debug_wrap(msgid); }
identifier_body
translate.ts
. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ export let current_language = window["ogs_current_language"] || 'en'; export let languages = window["ogs_languages"] || {'en': 'English'}; export let countries =...
(format_type) { let value = gettext_formats[format_type]; if (typeof(value) === "undefined") { return format_type; } else { return value; } } //let original_countries=dup(countries); let extended_countries = []; extended_countries.push(["_African_Union", gettext("African Union")]); exten...
get_format
identifier_name
translate.ts
. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ export let current_language = window["ogs_current_language"] || 'en'; export let languages = window["ogs_languages"] || {'en': 'English'}; export let countries =...
return params[key]; }); } return str.replace(/%[sd]/g, (_, __, position) => params); } export function _(str): string { return gettext(str); } export function cc_to_country_name(country_code) { if (current_language in countries) { return countries[current_language][country_...
{ throw new Error(`Missing interpolation key: ${key} for string: ${str}`); }
conditional_block
translate.ts
. *
export let languages = window["ogs_languages"] || {'en': 'English'}; export let countries = window["ogs_countries"] || {'en': {'us': 'United States'}}; export let locales = window["ogs_locales"] || {'en': {}}; export let sorted_locale_countries = []; let catalog; try { catalog = locales[current_language] || {}; ...
* You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ export let current_language = window["ogs_current_language"] || 'en';
random_line_split
index.d.ts
/* * @license Apache-2.0 * * Copyright (c) 2019 The Stdlib Authors. * * 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 ap...
/** * Uniform distribution cumulative distribution function (CDF). * * @param x - input value * @param a - minimum support * @param b - maximum support * @returns evaluated CDF * * @example * var y = cdf( 5.0, 0.0, 4.0 ); * // returns 1.0 * * var mycdf = cdf.factory( 0.0, 10.0 ); * y = mycdf( 0.5 ); * // returns 0.05 ...
* y = mycdf( 8.0 ); * // returns 0.8 */ factory( a: number, b: number ): Unary; }
random_line_split
job-overview.ts
/* * 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 ...
export interface JobOverview { jobs: JobsItem[]; } export interface JobsItem { jid: string; name: string; state: string; 'start-time': number; 'end-time': number; duration: number; 'last-modification': number; tasks: TaskStatus; completed?: boolean; } export interface TaskStatus { CANCELED: numb...
random_line_split
074_First_Bad_Version.py
#class SVNRepo: # @classmethod # def isBadVersion(cls, id) # # Run unit tests to check whether verison `id` is a bad version # # return true if unit tests passed else false. # You can use SVNRepo.isBadVersion(10) to check whether version 10 is a # bad version. class Solution: """ @param n:...
return start
end = i - 1
conditional_block
074_First_Bad_Version.py
#class SVNRepo: # @classmethod # def isBadVersion(cls, id) # # Run unit tests to check whether verison `id` is a bad version # # return true if unit tests passed else false. # You can use SVNRepo.isBadVersion(10) to check whether version 10 is a # bad version. class Solution: """ @param n:...
return start
random_line_split