file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
dom_adapter.js | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { isBlank } from '../facade/lang';
var _DOM = null;
export function getDOM() {
return _DOM;
}
export funct... | (value) { this._attrToPropMap = value; }
;
}
//# sourceMappingURL=dom_adapter.js.map | attrToPropMap | identifier_name |
dom_adapter.js | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { isBlank } from '../facade/lang';
var _DOM = null;
export function getDOM() {
return _DOM;
}
export funct... |
}
/* tslint:disable:requireParameterType */
/**
* Provides DOM operations in an environment-agnostic way.
*/
export class DomAdapter {
constructor() {
this.xhrType = null;
}
/** @deprecated */
getXHR() { return this.xhrType; }
/**
* Maps attribute names to their corresponding propert... | {
_DOM = adapter;
} | conditional_block |
dom_adapter.js | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { isBlank } from '../facade/lang';
var _DOM = null;
export function getDOM() {
return _DOM;
}
export funct... | }
}
/* tslint:disable:requireParameterType */
/**
* Provides DOM operations in an environment-agnostic way.
*/
export class DomAdapter {
constructor() {
this.xhrType = null;
}
/** @deprecated */
getXHR() { return this.xhrType; }
/**
* Maps attribute names to their corresponding pr... | }
export function setRootDomAdapter(adapter) {
if (isBlank(_DOM)) {
_DOM = adapter; | random_line_split |
MasonryLayout.tsx | import React from 'react';
interface IElementProps {
component: string | JSX.Element;
size: number;
}
interface IMasonryLayoutProps {
elements: IElementProps[];
numPerRow: number;
minWidth?: number;
gutter?: number;
customizeStyle?: React.CSSProperties;
totalWidth?: number;
}
const MasonryLayout = ... | );
};
export default MasonryLayout; | );
})}
</ul> | random_line_split |
gamelib.js | /**
* Game class library, utility functions and globals.
*
* (C) 2010 Kevin Roast kevtoast@yahoo.com @kevinroast
*
* Please see: license.txt
* You are welcome to use this code, but I would appreciate an email or tweet
* if you do anything interesting with it!
*
* 30/04/09 Initial version.
* 12/05/09 Refact... | /**
* Play sound helper
*/
playSound: function(id)
{
if (this.soundEnabled && this.hasAudio() && this.sounds[id])
{
var source = this.audioContext.createBufferSource();
source.buffer = this.sounds[id];
source.connect(this.audioGain);
source.start(0);
... | },
| random_line_split |
gamelib.js | /**
* Game class library, utility functions and globals.
*
* (C) 2010 Kevin Roast kevtoast@yahoo.com @kevinroast
*
* Please see: license.txt
* You are welcome to use this code, but I would appreciate an email or tweet
* if you do anything interesting with it!
*
* 30/04/09 Initial version.
* 12/05/09 Refact... |
}
// update global frame counter and current scene reference
this.currentScene = currentScene;
GameHandler.frameCount++;
// calculate frame total time interval and frame multiplier required for smooth animation
var frameInterval = frameStart - G... | {
currentScene.interval.intervalRenderer.call(currentScene, currentScene.interval, ctx);
} | conditional_block |
ncbo-selection.js | function getSelectedInformation(txt, element) {
txt = txt.toString();
text = jQuery.trim(txt);
len = text.length;
full = jQuery.trim($(element).text());
field_name = $(element).attr("id");
start = full.indexOf(text)+1;
end = start+len-1;
return {'from':start, 'to':end, 'text':text, 'field_name':field_na... |
$(function() {
// rightClickMenu();
$("#new_annotation").bind("submit", submit_annotation);
$("input#annotation_cancel").bind("click", function(){
$("#new-annotation").hide();
return false;
});
$(".dataTable span").contextMenu({
menu: 'annotation-menu'
},
function(ontology, el, pos) ... | {
$.post("/annotations", $("#new_annotation input").serialize(), function() {
load_curators();
}, "script");
return false;
} | identifier_body |
ncbo-selection.js | function getSelectedInformation(txt, element) {
txt = txt.toString();
text = jQuery.trim(txt);
len = text.length;
full = jQuery.trim($(element).text());
field_name = $(element).attr("id");
start = full.indexOf(text)+1;
end = start+len-1;
return {'from':start, 'to':end, 'text':text, 'field_name':field_na... |
return txt;
}
function unbindEvents() {
$("input[class*='bp_form_complete']").each(function(){
$(this).unbind();
});
}
function submit_annotation() {
$.post("/annotations", $("#new_annotation input").serialize(), function() {
load_curators();
}, "script");
return false;
}
$(function() {
// righ... | {
txt = document.selection.createRange().text;
} | conditional_block |
ncbo-selection.js | function getSelectedInformation(txt, element) {
txt = txt.toString();
text = jQuery.trim(txt);
len = text.length;
full = jQuery.trim($(element).text());
field_name = $(element).attr("id");
start = full.indexOf(text)+1;
end = start+len-1;
return {'from':start, 'to':end, 'text':text, 'field_name':field_na... | () {
$.post("/annotations", $("#new_annotation input").serialize(), function() {
load_curators();
}, "script");
return false;
}
$(function() {
// rightClickMenu();
$("#new_annotation").bind("submit", submit_annotation);
$("input#annotation_cancel").bind("click", function(){
$("#new-annotation").hi... | submit_annotation | identifier_name |
ncbo-selection.js | function getSelectedInformation(txt, element) {
txt = txt.toString();
text = jQuery.trim(txt);
len = text.length;
full = jQuery.trim($(element).text());
field_name = $(element).attr("id");
start = full.indexOf(text)+1;
end = start+len-1;
return {'from':start, 'to':end, 'text':text, 'field_name':field_na... | var txt = '';
if (window.getSelection) {
txt = window.getSelection();
// FireFox
} else if (document.getSelection) {
txt = document.getSelection();
// IE 6/7
} else if (document.selection) {
txt = document.selection.createRange().text;
}
return txt;
}
function unbindEvents() {
$("input[cl... |
function getSelectedText() { | random_line_split |
test_connect_combo_selection.py | import pytest
import numpy as np
from qtpy import QtWidgets
from echo.core import CallbackProperty
from echo.selection import SelectionCallbackProperty, ChoiceSeparator
from echo.qt.connect import connect_combo_selection
class Example(object):
|
def test_connect_combo_selection():
t = Example()
a_prop = getattr(type(t), 'a')
a_prop.set_choices(t, [4, 3.5])
a_prop.set_display_func(t, lambda x: 'value: {0}'.format(x))
combo = QtWidgets.QComboBox()
c1 = connect_combo_selection(t, 'a', combo) # noqa
assert combo.itemText(0) == ... | a = SelectionCallbackProperty(default_index=1)
b = CallbackProperty() | identifier_body |
test_connect_combo_selection.py | import pytest
import numpy as np
from qtpy import QtWidgets
from echo.core import CallbackProperty
from echo.selection import SelectionCallbackProperty, ChoiceSeparator
from echo.qt.connect import connect_combo_selection
class Example(object):
a = SelectionCallbackProperty(default_index=1)
b = CallbackPrope... | ():
t = Example()
a_prop = getattr(type(t), 'a')
a_prop.set_choices(t, [4, 3.5])
a_prop.set_display_func(t, lambda x: 'value: {0}'.format(x))
combo = QtWidgets.QComboBox()
c1 = connect_combo_selection(t, 'a', combo) # noqa
assert combo.itemText(0) == 'value: 4'
assert combo.itemTex... | test_connect_combo_selection | identifier_name |
test_connect_combo_selection.py | import pytest
import numpy as np
| from echo.selection import SelectionCallbackProperty, ChoiceSeparator
from echo.qt.connect import connect_combo_selection
class Example(object):
a = SelectionCallbackProperty(default_index=1)
b = CallbackProperty()
def test_connect_combo_selection():
t = Example()
a_prop = getattr(type(t), 'a')
... | from qtpy import QtWidgets
from echo.core import CallbackProperty | random_line_split |
variants.rs | #![feature(decl_macro)]
#[rustfmt::skip]
macro x($macro_name:ident, $macro2_name:ident, $type_name:ident, $variant_name:ident) {
#[repr(u8)]
pub enum $type_name {
Variant = 0,
$variant_name = 1,
}
#[macro_export]
macro_rules! $macro_name {
() => {{
assert_eq!($t... | test_variants!();
test_variants2!();
} |
x!(test_variants, test_variants2, MyEnum, Variant);
pub fn check_variants() { | random_line_split |
variants.rs | #![feature(decl_macro)]
#[rustfmt::skip]
macro x($macro_name:ident, $macro2_name:ident, $type_name:ident, $variant_name:ident) {
#[repr(u8)]
pub enum $type_name {
Variant = 0,
$variant_name = 1,
}
#[macro_export]
macro_rules! $macro_name {
() => {{
assert_eq!($t... | () {
test_variants!();
test_variants2!();
}
| check_variants | identifier_name |
variants.rs | #![feature(decl_macro)]
#[rustfmt::skip]
macro x($macro_name:ident, $macro2_name:ident, $type_name:ident, $variant_name:ident) {
#[repr(u8)]
pub enum $type_name {
Variant = 0,
$variant_name = 1,
}
#[macro_export]
macro_rules! $macro_name {
() => {{
assert_eq!($t... | {
test_variants!();
test_variants2!();
} | identifier_body | |
test_preparers.py | import unittest
from restkiss.preparers import Preparer, FieldsPreparer
class InstaObj(object):
def __init__(self, **kwargs):
for k, v in kwargs.items():
setattr(self, k, v)
class LookupDataTestCase(unittest.TestCase):
def setUp(self):
super(LookupDataTestCase, self).setUp()
... | with self.assertRaises(AttributeError):
self.preparer.lookup_data('whee', self.obj_data)
def test_dict_nullable_fk(self):
self.assertEqual(self.preparer.lookup_data('parent.id', self.dict_data), None)
def test_obj_nullable_fk(self):
self.assertEqual(self.preparer.lookup_dat... | def test_dict_miss(self):
with self.assertRaises(KeyError):
self.preparer.lookup_data('another', self.dict_data)
def test_obj_miss(self): | random_line_split |
test_preparers.py | import unittest
from restkiss.preparers import Preparer, FieldsPreparer
class InstaObj(object):
def __init__(self, **kwargs):
for k, v in kwargs.items():
|
class LookupDataTestCase(unittest.TestCase):
def setUp(self):
super(LookupDataTestCase, self).setUp()
self.preparer = FieldsPreparer(fields=None)
self.obj_data = InstaObj(
say='what',
count=453,
moof={
'buried': {
'id... | setattr(self, k, v) | conditional_block |
test_preparers.py | import unittest
from restkiss.preparers import Preparer, FieldsPreparer
class InstaObj(object):
def __init__(self, **kwargs):
for k, v in kwargs.items():
setattr(self, k, v)
class LookupDataTestCase(unittest.TestCase):
def setUp(self):
super(LookupDataTestCase, self).setUp()
... | with self.assertRaises(AttributeError):
self.preparer.lookup_data('more.nested.nope', self.dict_data) | identifier_body | |
test_preparers.py | import unittest
from restkiss.preparers import Preparer, FieldsPreparer
class InstaObj(object):
def __init__(self, **kwargs):
for k, v in kwargs.items():
setattr(self, k, v)
class LookupDataTestCase(unittest.TestCase):
def setUp(self):
super(LookupDataTestCase, self).setUp()
... | (self):
self.assertEqual(self.preparer.lookup_data('say', self.obj_data), 'what')
self.assertEqual(self.preparer.lookup_data('count', self.obj_data), 453)
def test_dict_nested(self):
self.assertEqual(self.preparer.lookup_data('more.things', self.dict_data), 'here')
self.assertEqual(... | test_obj_simple | identifier_name |
dsv2.rs | #[doc = "Register `DSV2` reader"]
pub struct R(crate::R<DSV2_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<DSV2_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<DSV2_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<DSV2_SP... | self.w.bits = (self.w.bits & !0x03ff) | (value as u32 & 0x03ff);
self.w
}
}
impl R {
#[doc = "Bits 0:9 - DAC reference value 2"]
#[inline(always)]
pub fn dsv2(&self) -> DSV2_R {
DSV2_R::new((self.bits & 0x03ff) as u16)
}
}
impl W {
#[doc = "Bits 0:9 - DAC reference value ... | #[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u16) -> &'a mut W { | random_line_split |
dsv2.rs | #[doc = "Register `DSV2` reader"]
pub struct R(crate::R<DSV2_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<DSV2_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<DSV2_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<DSV2_SP... | (&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl From<crate::W<DSV2_SPEC>> for W {
#[inline(always)]
fn from(writer: crate::W<DSV2_SPEC>) -> Self {
W(writer)
}
}
#[doc = "Field `DSV2` reader - DAC reference value 2"]
pub struct DSV2_R(crate::FieldReader<u16, u16>);
impl DSV2_R {
... | deref_mut | identifier_name |
dsv2.rs | #[doc = "Register `DSV2` reader"]
pub struct R(crate::R<DSV2_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<DSV2_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<DSV2_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<DSV2_SP... |
}
#[doc = "Field `DSV2` reader - DAC reference value 2"]
pub struct DSV2_R(crate::FieldReader<u16, u16>);
impl DSV2_R {
pub(crate) fn new(bits: u16) -> Self {
DSV2_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for DSV2_R {
type Target = crate::FieldReader<u16, u16>;
#[inline(always... | {
W(writer)
} | identifier_body |
models.py | from django.db import models
from django.contrib.auth.models import User
class OrganisationType(models.Model):
type_desc = models.CharField(max_length=200)
def __unicode__(self):
return self.type_desc
class Address(models.Model):
street_address = models.CharField(max_length=100)
city = model... | (HattiUser):
title = models.CharField(max_length=200)
organisation_type = models.ForeignKey(OrganisationType)
def __unicode__(self):
return self.title
class Customer(HattiUser):
title = models.CharField(max_length=200, blank=True, null=True)
is_org = models.BooleanField();
org_type = m... | AdminOrganisations | identifier_name |
models.py | from django.db import models
from django.contrib.auth.models import User
class OrganisationType(models.Model):
type_desc = models.CharField(max_length=200)
def __unicode__(self):
return self.type_desc
class Address(models.Model):
street_address = models.CharField(max_length=100)
city = model... |
class Customer(HattiUser):
title = models.CharField(max_length=200, blank=True, null=True)
is_org = models.BooleanField();
org_type = models.ForeignKey(OrganisationType)
company = models.CharField(max_length = 200)
def __unicode__(self, arg):
return unicode(self.user)
| return self.title | identifier_body |
models.py | from django.db import models
from django.contrib.auth.models import User
class OrganisationType(models.Model):
type_desc = models.CharField(max_length=200)
def __unicode__(self):
return self.type_desc
class Address(models.Model):
street_address = models.CharField(max_length=100)
city = model... |
class AdminOrganisations(HattiUser):
title = models.CharField(max_length=200)
organisation_type = models.ForeignKey(OrganisationType)
def __unicode__(self):
return self.title
class Customer(HattiUser):
title = models.CharField(max_length=200, blank=True, null=True)
is_org = models.Boolea... | random_line_split | |
float.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | {
/// `-` will be printed for negative values, but no sign will be emitted
/// for positive numbers.
SignNeg
}
const DIGIT_E_RADIX: u32 = ('e' as u32) - ('a' as u32) + 11;
/// Converts a number to its string representation as a byte vector.
/// This is meant to be a common base implementation for all num... | SignFormat | identifier_name |
float.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
}
}
}
}
// if number of digits is not exact, remove all trailing '0's up to
// and including the '.'
if !exact {
let buf_max_i = end - 1;
// index to truncate from
let mut i = buf_max_i;
// discover trailing zeros of fractional part... | {
buf[i as usize] = value2ascii(0);
i -= 1;
} | conditional_block |
float.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | // If limited digits, calculate one digit more for rounding.
let (limit_digits, digit_count, exact) = match digits {
DigMax(count) => (true, count + 1, false),
DigExact(count) => (true, count + 1, true)
};
// Decide what sign to put in front
match sign {
SignNeg if neg => ... | random_line_split | |
pyunit_wide_dataset_largeGLM.py | import sys
sys.path.insert(1, "../../../")
import h2o
import numpy as np
def wide_dataset_large(ip,port):
print("Reading in Arcene training data for binomial modeling.")
trainDataResponse = np.genfromtxt(h2o.locate("smalldata/arcene/arcene_train_labels.labels"), delimiter=' ')
trainDataResponse ... | print("Check that prediction AUC better than guessing (0.5).")
assert performance.auc() > 0.5, "predictions should be better then pure chance"
if __name__ == "__main__":
h2o.run_test(sys.argv, wide_dataset_large) | random_line_split | |
pyunit_wide_dataset_largeGLM.py | import sys
sys.path.insert(1, "../../../")
import h2o
import numpy as np
def wide_dataset_large(ip,port):
print("Reading in Arcene training data for binomial modeling.")
trainDataResponse = np.genfromtxt(h2o.locate("smalldata/arcene/arcene_train_labels.labels"), delimiter=' ')
trainDataResponse ... | h2o.run_test(sys.argv, wide_dataset_large) | conditional_block | |
pyunit_wide_dataset_largeGLM.py | import sys
sys.path.insert(1, "../../../")
import h2o
import numpy as np
def wide_dataset_large(ip,port):
|
if __name__ == "__main__":
h2o.run_test(sys.argv, wide_dataset_large)
| print("Reading in Arcene training data for binomial modeling.")
trainDataResponse = np.genfromtxt(h2o.locate("smalldata/arcene/arcene_train_labels.labels"), delimiter=' ')
trainDataResponse = np.where(trainDataResponse == -1, 0, 1)
trainDataFeatures = np.genfromtxt(h2o.locate("smalldata/arcene/arcene_train.... | identifier_body |
pyunit_wide_dataset_largeGLM.py | import sys
sys.path.insert(1, "../../../")
import h2o
import numpy as np
def | (ip,port):
print("Reading in Arcene training data for binomial modeling.")
trainDataResponse = np.genfromtxt(h2o.locate("smalldata/arcene/arcene_train_labels.labels"), delimiter=' ')
trainDataResponse = np.where(trainDataResponse == -1, 0, 1)
trainDataFeatures = np.genfromtxt(h2o.locate("smal... | wide_dataset_large | identifier_name |
other.py | """
pygments.lexers.other
~~~~~~~~~~~~~~~~~~~~~
Just export lexer classes previously contained in this module.
| from pygments.lexers.shell import BashLexer, BashSessionLexer, BatchLexer, \
TcshLexer
from pygments.lexers.robotframework import RobotFrameworkLexer
from pygments.lexers.testing import GherkinLexer
from pygments.lexers.esoteric import BrainfuckLexer, BefungeLexer, RedcodeLexer
from pygments.lexers.prolog import Lo... | :copyright: Copyright 2006-2022 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from pygments.lexers.sql import SqlLexer, MySqlLexer, SqliteConsoleLexer | random_line_split |
main.py | from prompt_toolkit import Application
from prompt_toolkit.interface import CommandLineInterface
from prompt_toolkit.shortcuts import create_eventloop
from prompt_toolkit.key_binding.manager import KeyBindingManager
from prompt_toolkit.keys import Keys
from prompt_toolkit.buffer import Buffer, AcceptAction
from prompt_... |
buffers[DEFAULT_BUFFER].on_text_changed += default_buffer_changed
def get_bottom_toolbar_tokens(cli):
return [(Token.Toolbar, ' This is a toolbar. ')]
layout = VSplit([
Window(content=BufferControl(
buffer_name=DEFAULT_BUFFER, focus_on_click=True)),
Window(w... | buffers['RESULT'].text = buffers[DEFAULT_BUFFER].text[::-1] | random_line_split |
main.py | from prompt_toolkit import Application
from prompt_toolkit.interface import CommandLineInterface
from prompt_toolkit.shortcuts import create_eventloop
from prompt_toolkit.key_binding.manager import KeyBindingManager
from prompt_toolkit.keys import Keys
from prompt_toolkit.buffer import Buffer, AcceptAction
from prompt_... | (cli):
return [(Token.Toolbar, ' This is a toolbar. ')]
layout = VSplit([
Window(content=BufferControl(
buffer_name=DEFAULT_BUFFER, focus_on_click=True)),
Window(width=D.exact(1),
content=FillControl('|', token=Token.Line)),
... | get_bottom_toolbar_tokens | identifier_name |
main.py | from prompt_toolkit import Application
from prompt_toolkit.interface import CommandLineInterface
from prompt_toolkit.shortcuts import create_eventloop
from prompt_toolkit.key_binding.manager import KeyBindingManager
from prompt_toolkit.keys import Keys
from prompt_toolkit.buffer import Buffer, AcceptAction
from prompt_... |
buffers = {
DEFAULT_BUFFER: Buffer(is_multiline=True),
'PROMPT': Buffer(
accept_action=AcceptAction(handler=handle_action),
enable_history_search=True,
complete_while_typing=True,
auto_suggest=AutoSuggestFromHistory()),
'RESULT': Buffer(is_multiline=True),
}
def default_... | ' When enter is pressed in the Vi command line. '
text = buffer.text # Remember: leave_command_mode resets the buffer.
buffer.delete_before_cursor(len(text))
cli.focus(DEFAULT_BUFFER)
# First leave command mode. We want to make sure that the working
# pane is focussed again before executing the co... | identifier_body |
db.py | # copyright 2003-2010 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
# contact http://www.logilab.fr/ -- mailto:contact@logilab.fr
#
# This file is part of logilab-common.
#
# logilab-common is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as publ... | (driver, *args, **kwargs):
module = _gdcm(driver, *args, **kwargs)
module.adv_func_helper = _gdh(driver)
return module
| get_dbapi_compliant_module | identifier_name |
db.py | # copyright 2003-2010 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
# contact http://www.logilab.fr/ -- mailto:contact@logilab.fr
#
# This file is part of logilab-common.
#
# logilab-common is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as publ... |
from logilab.database import (get_connection, set_prefered_driver,
get_dbapi_compliant_module as _gdcm,
get_db_helper as _gdh)
def get_dbapi_compliant_module(driver, *args, **kwargs):
module = _gdcm(driver, *args, **kwargs)
module.adv_func_helper = _gdh(driver)
... | __docformat__ = "restructuredtext en"
from warnings import warn
warn('this module is deprecated, use logilab.database instead',
DeprecationWarning, stacklevel=1) | random_line_split |
db.py | # copyright 2003-2010 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
# contact http://www.logilab.fr/ -- mailto:contact@logilab.fr
#
# This file is part of logilab-common.
#
# logilab-common is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as publ... | module = _gdcm(driver, *args, **kwargs)
module.adv_func_helper = _gdh(driver)
return module | identifier_body | |
ping.node.js | /* eslint-env mocha */
'use strict'
const chai = require('chai')
chai.use(require('dirty-chai'))
const expect = chai.expect
const parallel = require('async/parallel')
const createNode = require('./utils/create-node.js')
const echo = require('./utils/echo')
describe('ping', () => {
let nodeA
let nodeB
before((... | nodeB = node
node.handle('/echo/1.0.0', echo)
node.start(cb)
})
], done)
})
after((done) => {
parallel([
(cb) => nodeA.stop(cb),
(cb) => nodeB.stop(cb)
], done)
})
it('should be able to ping another node', (done) => {
nodeA.ping(nodeB.peerInfo, (err, p... | (cb) => createNode('/ip4/0.0.0.0/tcp/0', (err, node) => {
expect(err).to.not.exist() | random_line_split |
value.rs | use std::collections::HashMap;
use std::fmt;
use std::cell::RefCell;
use std::rc::Rc;
use common::util::unescape;
use parser::ast::*;
use evaluator::types::*;
#[derive(Eq, Debug)]
pub enum Value {
Int(i64),
Bool(bool),
String(String),
Array(Vec<Rc<Value>>),
Hash(HashMap<Hashable, Rc<Value>>),
F... |
}
| {
assert_eq!(format!("{}", Value::Int(35)), "35");
assert_eq!(format!("{}", Value::Bool(true)), "true");
assert_eq!(format!("{}", Value::String(String::from("hello\nworld"))),
"\"hello\\nworld\"");
assert_eq!(format!("{}", Value::Array(vec![])), "[]");
assert_e... | identifier_body |
value.rs | use std::collections::HashMap;
use std::fmt;
use std::cell::RefCell;
use std::rc::Rc;
use common::util::unescape;
use parser::ast::*;
use evaluator::types::*;
#[derive(Eq, Debug)]
pub enum Value {
Int(i64),
Bool(bool),
String(String),
Array(Vec<Rc<Value>>),
Hash(HashMap<Hashable, Rc<Value>>),
F... | (&self, other: &Self) -> bool {
match (self, other) {
(&Value::Int(i1), &Value::Int(i2)) => i1 == i2,
(&Value::Bool(b1), &Value::Bool(b2)) => b1 == b2,
(&Value::String(ref s1), &Value::String(ref s2)) => s1 == s2,
(&Value::Array(ref v1), &Value::Array(ref v2)) => ... | eq | identifier_name |
value.rs | use std::collections::HashMap;
use std::fmt;
use std::cell::RefCell;
use std::rc::Rc;
use common::util::unescape;
use parser::ast::*;
use evaluator::types::*;
#[derive(Eq, Debug)]
pub enum Value {
Int(i64),
Bool(bool),
String(String),
Array(Vec<Rc<Value>>),
Hash(HashMap<Hashable, Rc<Value>>),
F... |
pub type BuiltInFn = fn(Vec<((i32, i32), Rc<Value>)>) -> Result<Value>;
#[cfg(test)]
mod tests {
use super::*;
use std::iter::FromIterator;
fn dummy(_: Vec<((i32, i32), Rc<Value>)>) -> Result<Value> {
unreachable!()
}
#[test]
fn value_display() {
assert_eq!(format!("{}", Valu... | &Hashable::String(ref s) => Value::String(s.clone()),
})
}
} | random_line_split |
value.rs | use std::collections::HashMap;
use std::fmt;
use std::cell::RefCell;
use std::rc::Rc;
use common::util::unescape;
use parser::ast::*;
use evaluator::types::*;
#[derive(Eq, Debug)]
pub enum Value {
Int(i64),
Bool(bool),
String(String),
Array(Vec<Rc<Value>>),
Hash(HashMap<Hashable, Rc<Value>>),
F... | ,
&Value::Fn { .. } => write!(f, "[function]"),
&Value::BuiltInFn { ref name, .. } => write!(f, "[built-in function: {}]", name),
&Value::Return(ref o) => o.fmt(f),
&Value::Null => write!(f, "null"),
}
}
}
impl PartialEq for Value {
fn eq(&self, other: &S... | {
let mut mapped: Vec<String> = m.iter().map(|(h, v)| format!("{}: {}", h, v)).collect();
mapped.sort();
write!(f, "{{{}}}", mapped.join(", "))
} | conditional_block |
webpack.config.js | var path = require('path');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin')
var TARGET = process.env.TARGET;
var config = {
devtool: 'eval-source-map',
entry: [
'webpack-dev-server/client?http://localhost:3000',
'webpack/hot/only-dev-server',
'./app/index'
], | plugins: [
new webpack.HotModuleReplacementPlugin(),
new HtmlWebpackPlugin({
filename: 'index.html',
template: 'App/Views/template.html'
})
],
module: {
loaders: [{
test: /\.js$/,
loaders: ['react-hot', 'babel'],
include: path.join(__dirname, 'app')
}]... | output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
}, | random_line_split |
webpack.config.js | var path = require('path');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin')
var TARGET = process.env.TARGET;
var config = {
devtool: 'eval-source-map',
entry: [
'webpack-dev-server/client?http://localhost:3000',
'webpack/hot/only-dev-server',
'./app/index'
],
... |
module.exports = config;
| {
var config = {
devtool: 'source-map',
entry: [
'./app/index'
],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/ui/'
},
plugins: [
new webpack.NoErrorsPlugin(),
new webpack.optimize.UglifyJsPlugin({
compressor: { ... | conditional_block |
shared.ts | /**
* A found external editor on the user's machine
*/
export type FoundEditor = {
/**
* The friendly name of the editor, to be used in labels
*/
editor: string
/**
* The executable associated with the editor to launch
*/
path: string
/**
* the editor requires a shell spawn to launch
*/
... | extends Error {
/** The error's metadata. */
public readonly metadata: IErrorMetadata
public constructor(message: string, metadata: IErrorMetadata = {}) {
super(message)
this.metadata = metadata
}
}
export const suggestedExternalEditor = {
name: 'Visual Studio Code',
url: 'https://code.visualstu... | ExternalEditorError | identifier_name |
shared.ts | /**
* A found external editor on the user's machine
*/
export type FoundEditor = {
/**
* The friendly name of the editor, to be used in labels
*/
editor: string
/**
* The executable associated with the editor to launch
*/ | /**
* the editor requires a shell spawn to launch
*/
usesShell?: boolean
}
interface IErrorMetadata {
/** The error dialog should link off to the default editor's website */
suggestDefaultEditor?: boolean
/** The error dialog should direct the user to open Preferences */
openPreferences?: boolean
}
... | path: string | random_line_split |
issues.py | # Copyright (c) 2015 - present Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the BSD style license found in the
# LICENSE file in the root directory of this source tree. An additional grant
# of patent rights can be found in the PATENTS file in the same directory.
from __future__ import ... | (report_paths):
json_data = []
for json_path in report_paths:
json_data.extend(utils.load_json_from_path(json_path))
return _sort_and_uniq_rows(json_data)
def _pmd_xml_of_issues(issues):
if etree is None:
print('ERROR: "etree" Python package not found.')
print('ERROR: You need ... | merge_reports_from_paths | identifier_name |
issues.py | # Copyright (c) 2015 - present Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the BSD style license found in the
# LICENSE file in the root directory of this source tree. An additional grant
# of patent rights can be found in the PATENTS file in the same directory.
from __future__ import ... |
else:
return 'No issues found'
text_errors_list = []
for report in reports[:limit]:
filename = report[JSON_INDEX_FILENAME]
line = report[JSON_INDEX_LINE]
source_context = ''
source_context = source.build_source_context(
os.path.join(project_root... | out = colorize.color(' No issues found ',
colorize.SUCCESS, formatter)
return out + '\n' | conditional_block |
issues.py | # Copyright (c) 2015 - present Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the BSD style license found in the
# LICENSE file in the root directory of this source tree. An additional grant
# of patent rights can be found in the PATENTS file in the same directory.
from __future__ import ... |
def merge_reports_from_paths(report_paths):
json_data = []
for json_path in report_paths:
json_data.extend(utils.load_json_from_path(json_path))
return _sort_and_uniq_rows(json_data)
def _pmd_xml_of_issues(issues):
if etree is None:
print('ERROR: "etree" Python package not found.')
... | errors = utils.load_json_from_path(json_report)
errors = [e for e in errors if _is_user_visible(project_root, e)]
console_out = _text_of_report_list(project_root, errors, bugs_out,
limit=10)
utils.stdout('\n' + console_out)
plain_out = _text_of_report_list(project_... | identifier_body |
issues.py | # Copyright (c) 2015 - present Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the BSD style license found in the
# LICENSE file in the root directory of this source tree. An additional grant
# of patent rights can be found in the PATENTS file in the same directory.
from __future__ import ... | ), sorted_error_types)
text_errors = '\n\n'.join(text_errors_list)
if limit >= 0 and n_issues > limit:
text_errors += colorize.color(
('\n\n...too many issues to display (limit=%d exceeded), please ' +
'see %s or run `inferTraceBugs` for the remaining issues.')
... | sorted_error_types.sort(key=operator.itemgetter(1), reverse=True)
types_text_list = map(lambda (t, count): '%s: %d' % (
t.rjust(max_type_length),
count, | random_line_split |
hourly.js | *
* Copyright (C) 2015 Cam Moore.
*
* The MIT License (MIT)
*
* 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, including without limitation the rights
* to use, c... | /**
* This file is a part of hale_aloha_dashboard.
*
* Created by Cam Moore on 11/12/15. | random_line_split | |
slick.media.js | /**
* @file
*/
(function ($) {
"use strict";
Drupal.behaviors.slickMedia = {
attach: function (context, settings) {
var $slider = $('.slick', context),
player = '.media--switch--player';
$(player, context).once('slick-media', function () {
var t = $(this);
// Remove SRC... | if (media.scheme === 'soundcloud') {
if (url.indexOf('auto_play') < 0 || url.indexOf('auto_play') === false) {
url = url.indexOf('?') < 0 ? url + '?auto_play=true' : url + '&auto_play=true';
}
}
else if (url.indexOf('autoplay') < 0 || u... | random_line_split | |
slick.media.js | /**
* @file
*/
(function ($) {
"use strict";
Drupal.behaviors.slickMedia = {
attach: function (context, settings) {
var $slider = $('.slick', context),
player = '.media--switch--player';
$(player, context).once('slick-media', function () {
var t = $(this);
// Remove SRC... |
// First, reset any video to avoid multiple videos from playing.
$(player).removeClass('is-playing').find('iframe').attr('src', '');
// Clean up any pause marker.
$('.is-paused').removeClass('is-paused');
// Last, pause the slide, for just in case autoplay is on and... | {
url = url.indexOf('?') < 0 ? url + '?autoplay=1' : url + '&autoplay=1';
} | conditional_block |
jsclass_async.js | /*********************************************************************************
* SugarCRM Community Edition is a customer relationship management program developed by
* SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* ... | (o){var resp=YAHOO.lang.JSON.parse(o.responseText),request_id=o.tId,result=resp.result;if(result==null){return;}
reqid=global_request_registry[request_id];if(typeof(reqid)!='undefined'){widget=global_request_registry[request_id][0];method_name=global_request_registry[request_id][1];widget[method_name](result);}}
Suga... | method_callback | identifier_name |
jsclass_async.js | /*********************************************************************************
* SugarCRM Community Edition is a customer relationship management program developed by
* SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* ... |
SugarClass.inherit("SugarVCalClient","SugarClass");function SugarVCalClient(){this.init();}
SugarVCalClient.prototype.init=function(){}
SugarVCalClient.prototype.load=function(user_id,request_id){this.user_id=user_id;YAHOO.util.Connect.asyncRequest('GET','./vcal_server.php?type=vfb&source=outlook&noAuth=noAuth&user... | {var resp=YAHOO.lang.JSON.parse(o.responseText),request_id=o.tId,result=resp.result;if(result==null){return;}
reqid=global_request_registry[request_id];if(typeof(reqid)!='undefined'){widget=global_request_registry[request_id][0];method_name=global_request_registry[request_id][1];widget[method_name](result);}} | identifier_body |
jsclass_async.js | /*********************************************************************************
| * SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by the
* Free Software Foundation with the addition of the following permission added
* to Secti... | * SugarCRM Community Edition is a customer relationship management program developed by
| random_line_split |
OfferManager.py | import re
from gi.repository import GObject
from pychess.Utils.const import DRAW_OFFER, ABORT_OFFER, ADJOURN_OFFER, TAKEBACK_OFFER, \
PAUSE_OFFER, RESUME_OFFER, SWITCH_OFFER, RESIGNATION, FLAG_CALL, MATCH_OFFER, \
WHITE, ACTION_ERROR_SWITCH_UNDERWAY, ACTION_ERROR_CLOCK_NOT_STARTED, \
ACTION_ERROR_CLOCK_NO... | self.emit("onOfferAdd", offer)
def onOfferRemove(self, match):
log.debug("OfferManager.onOfferRemove: match.string=%s" % match.string)
index = int(match.groups()[0])
if index not in self.offers:
return
if self.offers[index].type == MATCH_OFFER:
se... | self.emit("onChallengeAdd", challenge)
else:
log.debug("OfferManager.onOfferAdd: emitting onOfferAdd: %s" %
offer) | random_line_split |
OfferManager.py | import re
from gi.repository import GObject
from pychess.Utils.const import DRAW_OFFER, ABORT_OFFER, ADJOURN_OFFER, TAKEBACK_OFFER, \
PAUSE_OFFER, RESUME_OFFER, SWITCH_OFFER, RESIGNATION, FLAG_CALL, MATCH_OFFER, \
WHITE, ACTION_ERROR_SWITCH_UNDERWAY, ACTION_ERROR_CLOCK_NOT_STARTED, \
ACTION_ERROR_CLOCK_NO... | log.debug("OfferManager.playIndex: index=%s" % index)
self.connection.client.run_command("play %s" % index) | identifier_body | |
OfferManager.py | import re
from gi.repository import GObject
from pychess.Utils.const import DRAW_OFFER, ABORT_OFFER, ADJOURN_OFFER, TAKEBACK_OFFER, \
PAUSE_OFFER, RESUME_OFFER, SWITCH_OFFER, RESIGNATION, FLAG_CALL, MATCH_OFFER, \
WHITE, ACTION_ERROR_SWITCH_UNDERWAY, ACTION_ERROR_CLOCK_NOT_STARTED, \
ACTION_ERROR_CLOCK_NO... | (self, offer):
log.debug("OfferManager.withdraw: %s" % offer)
self.connection.client.run_command("withdraw t %s" %
offerTypeToStr[offer.type])
def accept(self, offer):
log.debug("OfferManager.accept: %s" % offer)
if offer.index is not None:... | withdraw | identifier_name |
OfferManager.py | import re
from gi.repository import GObject
from pychess.Utils.const import DRAW_OFFER, ABORT_OFFER, ADJOURN_OFFER, TAKEBACK_OFFER, \
PAUSE_OFFER, RESUME_OFFER, SWITCH_OFFER, RESIGNATION, FLAG_CALL, MATCH_OFFER, \
WHITE, ACTION_ERROR_SWITCH_UNDERWAY, ACTION_ERROR_CLOCK_NOT_STARTED, \
ACTION_ERROR_CLOCK_NO... |
else:
self.connection.client.run_command("accept t %s" %
offerTypeToStr[offer.type])
def decline(self, offer):
log.debug("OfferManager.decline: %s" % offer)
if offer.index is not None:
self.declineIndex(offer.index)
... | self.acceptIndex(offer.index) | conditional_block |
MessageConnection.js |
var util = require('util');
var EventEmitter = require('events').EventEmitter;
var MessageCodec = require('./MessageCodec');
exports = module.exports = MessageConnection;
function MessageConnection(socket, options) |
util.inherits(MessageConnection, EventEmitter);
MessageConnection.prototype.send = function(message) {
try {
this._socket.write(this._messageCodec.encode(message));
} catch (err) {
this._onError(err);
}
};
MessageConnection.prototype._onSockData = function(data) {
try {
var self = this;
this... | {
EventEmitter.call(this);
this._socket = socket;
this._messageCodec = new MessageCodec(options);
socket.on('data', MessageConnection.prototype._onSockData.bind(this));
socket.on('close', MessageConnection.prototype.close .bind(this));
socket.on('error', MessageConnection.prototype._onError .bind(th... | identifier_body |
MessageConnection.js |
var util = require('util');
var EventEmitter = require('events').EventEmitter;
var MessageCodec = require('./MessageCodec');
exports = module.exports = MessageConnection;
function | (socket, options) {
EventEmitter.call(this);
this._socket = socket;
this._messageCodec = new MessageCodec(options);
socket.on('data', MessageConnection.prototype._onSockData.bind(this));
socket.on('close', MessageConnection.prototype.close .bind(this));
socket.on('error', MessageConnection.prototype._... | MessageConnection | identifier_name |
MessageConnection.js | var util = require('util');
var EventEmitter = require('events').EventEmitter;
var MessageCodec = require('./MessageCodec');
exports = module.exports = MessageConnection;
function MessageConnection(socket, options) {
EventEmitter.call(this);
this._socket = socket;
this._messageCodec = new MessageCodec(options)... | }
};
MessageConnection.prototype.close = function() {
if(this._socket) {
this._socket.destroy();
this._socket = undefined;
if(this.onclose) this.onclose();
this.emit('close');
}
};
MessageConnection.prototype.destroy = MessageConnection.prototype.close;
MessageConnection.prototype._onMessage = ... | this._onError(err); | random_line_split |
login.ts | import Controller from '@ember/controller';
import { get, setProperties, getProperties } from '@ember/object';
import Session from 'ember-simple-auth/services/session';
import { twoFABannerMessage, twoFABannerType } from 'wherehows-web/constants/notifications';
import BannerService from 'wherehows-web/services/banners'... | extends Controller {
/**
* References the application session service
* @type {Session}
* @memberof Login
*/
@service
session: Session;
/**
* Banner alert service
* @type {BannerService}
* @memberof Login
*/
@service
banners: BannerService;
/**
* Aliases the name property on ... | Login | identifier_name |
login.ts | import Controller from '@ember/controller';
import { get, setProperties, getProperties } from '@ember/object';
import Session from 'ember-simple-auth/services/session';
import { twoFABannerMessage, twoFABannerType } from 'wherehows-web/constants/notifications';
import BannerService from 'wherehows-web/services/banners'... | authenticateUser(this: Login): void {
const { username, password, banners } = getProperties(this, ['username', 'password', 'banners']);
get(this, 'session')
.authenticate('authenticator:custom-ldap', username, password)
.then(results => {
// Once user has chosen to authenticate, then we r... | @action | random_line_split |
login.ts | import Controller from '@ember/controller';
import { get, setProperties, getProperties } from '@ember/object';
import Session from 'ember-simple-auth/services/session';
import { twoFABannerMessage, twoFABannerType } from 'wherehows-web/constants/notifications';
import BannerService from 'wherehows-web/services/banners'... |
}
| {
const { username, password, banners } = getProperties(this, ['username', 'password', 'banners']);
get(this, 'session')
.authenticate('authenticator:custom-ldap', username, password)
.then(results => {
// Once user has chosen to authenticate, then we remove the login banner (if it exists) ... | identifier_body |
main.rs | #![feature(box_syntax)]
#![feature(asm)]
extern crate e2d2;
extern crate fnv;
extern crate getopts;
extern crate rand;
extern crate time;
use self::nf::*;
use e2d2::config::{basic_opts, read_matches};
use e2d2::interface::*;
use e2d2::operators::*;
use e2d2::scheduler::*;
use std::env;
use std::fmt::Display;
use std::p... | {
let mut opts = basic_opts();
opts.optopt(
"",
"dur",
"Test duration",
"If this option is set to a nonzero value, then the \
test will exit after X seconds.",
);
let args: Vec<String> = env::args().collect();
let matches = match opts.parse(&args[1..]) {
... | identifier_body | |
main.rs | #![feature(box_syntax)]
#![feature(asm)]
extern crate e2d2;
extern crate fnv;
extern crate getopts;
extern crate rand;
extern crate time;
use self::nf::*;
use e2d2::config::{basic_opts, read_matches};
use e2d2::interface::*;
use e2d2::operators::*;
use e2d2::scheduler::*;
use std::env;
use std::fmt::Display;
use std::p... | () {
let mut opts = basic_opts();
opts.optopt(
"",
"dur",
"Test duration",
"If this option is set to a nonzero value, then the \
test will exit after X seconds.",
);
let args: Vec<String> = env::args().collect();
let matches = match opts.parse(&args[1..]) {
... | main | identifier_name |
main.rs | #![feature(box_syntax)]
#![feature(asm)]
extern crate e2d2;
extern crate fnv;
extern crate getopts;
extern crate rand;
extern crate time;
use self::nf::*;
use e2d2::config::{basic_opts, read_matches};
use e2d2::interface::*;
use e2d2::operators::*;
use e2d2::scheduler::*;
use std::env;
use std::fmt::Display;
use std::p... | for pipeline in pipelines {
sched.add_task(pipeline).unwrap();
}
}
fn main() {
let mut opts = basic_opts();
opts.optopt(
"",
"dur",
"Test duration",
"If this option is set to a nonzero value, then the \
test will exit after X seconds.",
);
let a... | .map(|port| macswap(ReceiveBatch::new(port.clone())).send(port.clone()))
.collect();
println!("Running {} pipelines", pipelines.len()); | random_line_split |
gumby.fixed.js | /**
* Gumby Fixed
*/
!function() {
'use strict';
function | ($el) {
this.$el = $el;
this.fixedPoint = '';
this.pinPoint = false;
this.offset = 0;
this.pinOffset = 0;
this.top = 0;
this.constrainEl = true;
this.state = false;
this.measurements = {
left: 0,
width: 0
};
// set up module based on attributes
this.setup();
var scope = this;
// mo... | Fixed | identifier_name |
gumby.fixed.js | /**
* Gumby Fixed
*/
!function() {
'use strict';
function Fixed($el) {
this.$el = $el;
this.fixedPoint = '';
this.pinPoint = false;
this.offset = 0;
this.pinOffset = 0;
this.top = 0;
this.constrainEl = true;
this.state = false;
this.measurements = {
left: 0,
width: 0
};
// set up modul... |
// fix it
if((scrollAmount >= fixedPoint) && this.state !== 'fixed') {
if(!pinPoint || scrollAmount < pinPoint) {
this.fix();
}
// unfix it
} else if(scrollAmount < fixedPoint && this.state === 'fixed') {
this.unfix();
// pin it
} else if(pinPoint && scrollAmount >= pinPoint && this.state !=... | { pinPoint -= this.pinOffset; } | conditional_block |
gumby.fixed.js | /**
* Gumby Fixed
*/
!function() {
'use strict';
function Fixed($el) |
// set up module based on attributes
Fixed.prototype.setup = function() {
var scope = this;
this.fixedPoint = this.parseAttrValue(Gumby.selectAttr.apply(this.$el, ['fixed']));
// pin point is optional
this.pinPoint = Gumby.selectAttr.apply(this.$el, ['pin']) || false;
// offset from fixed point
this.... | {
this.$el = $el;
this.fixedPoint = '';
this.pinPoint = false;
this.offset = 0;
this.pinOffset = 0;
this.top = 0;
this.constrainEl = true;
this.state = false;
this.measurements = {
left: 0,
width: 0
};
// set up module based on attributes
this.setup();
var scope = this;
// monitor ... | identifier_body |
gumby.fixed.js | /**
* Gumby Fixed
*/
!function() {
'use strict';
function Fixed($el) {
this.$el = $el;
this.fixedPoint = '';
this.pinPoint = false;
this.offset = 0;
this.pinOffset = 0;
this.top = 0;
this.constrainEl = true;
this.state = false;
this.measurements = {
left: 0,
width: 0
};
// set up modul... | }(); | }); | random_line_split |
syntax-ambiguity-2018.rs | // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
use std::ops::Range;
if let Range { start: _, end: _ } = true..true && false { }
//~^ ERROR ambiguous use of `&&`
if let Range { start: _, end: _ } = true..true || false { }
//~^ ERROR ambiguous use of `||`
while let Range { start: _, end: _ } = true..true && false { }
//~^ ERROR amb... | main | identifier_name |
syntax-ambiguity-2018.rs | // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
if let true = false && false { }
//~^ ERROR ambiguous use of `&&`
while let true = (1 == 2) && false { }
//~^ ERROR ambiguous use of `&&`
// The following cases are not an error as parenthesis are used to
// clarify intent:
if let Range { start: _, end: _ } = true..(true || false) { }
... |
while let Range { start: _, end: _ } = true..true || false { }
//~^ ERROR ambiguous use of `||` | random_line_split |
syntax-ambiguity-2018.rs | // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
use std::ops::Range;
if let Range { start: _, end: _ } = true..true && false { }
//~^ ERROR ambiguous use of `&&`
if let Range { start: _, end: _ } = true..true || false { }
//~^ ERROR ambiguous use of `||`
while let Range { start: _, end: _ } = true..true && false { }
//~^ ERROR ambigu... | identifier_body | |
syntax-ambiguity-2018.rs | // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
//~^ ERROR ambiguous use of `||`
while let Range { start: _, end: _ } = true..true && false { }
//~^ ERROR ambiguous use of `&&`
while let Range { start: _, end: _ } = true..true || false { }
//~^ ERROR ambiguous use of `||`
if let true = false && false { }
//~^ ERROR ambiguous use of `&... | { } | conditional_block |
expander.module.d.ts | /// <reference path="../../ts/default.module.d.ts" />
export declare class MPCExpanderElement extends HTMLElement {
constructor();
readonly ownerExpander: MPCExpanderElement;
readonly isOwnerExpander: boolean;
private _selected;
selected: MPCExpanderElement; | expand(): boolean;
collapse(): boolean;
toggle(force?: boolean): void;
readonly label: HTMLElement;
labelText: string;
expandable: boolean;
expanded: boolean;
static readonly observedAttributes: string[];
attributeChangedCallback(name: string, oldValue: string, newValue: string): voi... | random_line_split | |
expander.module.d.ts | /// <reference path="../../ts/default.module.d.ts" />
export declare class | extends HTMLElement {
constructor();
readonly ownerExpander: MPCExpanderElement;
readonly isOwnerExpander: boolean;
private _selected;
selected: MPCExpanderElement;
expand(): boolean;
collapse(): boolean;
toggle(force?: boolean): void;
readonly label: HTMLElement;
labelText: str... | MPCExpanderElement | identifier_name |
long.py | # http://rosalind.info/problems/long/
def superstring(arr, accumulator=''):
# We now have all strings
if len(arr) == 0: | accumulator = arr.pop(0)
return superstring(arr, accumulator)
# Recursive call
else:
for i in range(len(arr)):
sample = arr[i]
l = len(sample)
for p in range(l / 2):
q = l - p
if accumulator.startswith(sample[p:]):
... | return accumulator
# Initial call
elif len(accumulator) == 0: | random_line_split |
long.py | # http://rosalind.info/problems/long/
def | (arr, accumulator=''):
# We now have all strings
if len(arr) == 0:
return accumulator
# Initial call
elif len(accumulator) == 0:
accumulator = arr.pop(0)
return superstring(arr, accumulator)
# Recursive call
else:
for i in range(len(arr)):
sample = a... | superstring | identifier_name |
long.py | # http://rosalind.info/problems/long/
def superstring(arr, accumulator=''):
# We now have all strings
|
f = open("rosalind_long.txt", "r")
dnas = {}
currentKey = ''
for content in f:
# Beginning of a new sample
if '>' in content:
key = content.rstrip().replace('>', '')
currentKey = key
dnas[currentKey] = ''
else:
dnas[currentKey] += content.rstrip()
print superstring(dnas.va... | if len(arr) == 0:
return accumulator
# Initial call
elif len(accumulator) == 0:
accumulator = arr.pop(0)
return superstring(arr, accumulator)
# Recursive call
else:
for i in range(len(arr)):
sample = arr[i]
l = len(sample)
for p in r... | identifier_body |
long.py | # http://rosalind.info/problems/long/
def superstring(arr, accumulator=''):
# We now have all strings
if len(arr) == 0:
return accumulator
# Initial call
elif len(accumulator) == 0:
accumulator = arr.pop(0)
return superstring(arr, accumulator)
# Recursive call
else:
... |
f = open("rosalind_long.txt", "r")
dnas = {}
currentKey = ''
for content in f:
# Beginning of a new sample
if '>' in content:
key = content.rstrip().replace('>', '')
currentKey = key
dnas[currentKey] = ''
else:
dnas[currentKey] += content.rstrip()
print superstring(dnas.va... | q = l - p
if accumulator.startswith(sample[p:]):
arr.pop(i)
return superstring(arr, sample[:p] + accumulator)
if accumulator.endswith(sample[:q]):
arr.pop(i)
return superstring(arr, accumulator + sample[q:]) | conditional_block |
bootstrap.rs | // Copyright 2015-2017 Intecture Developers. See the COPYRIGHT file at the
// top-level directory of this distribution and at
// https://intecture.io/COPYRIGHT.
//
// Licensed under the Mozilla Public License 2.0 <LICENSE or
// https://www.tldrlegal.com/l/mpl-2.0>. This file may not be copied,
// modified, or distribut... |
fn channel_exec(&mut self, cmd: &str) -> Result<String> {
let mut channel = self.session.channel_session()?;
channel.exec(cmd)?;
channel.send_eof()?;
channel.wait_eof()?;
let mut out = String::new();
channel.read_to_string(&mut out)?;
if channel.exit_statu... | {
let mut auth = try!(Auth::new(&env::current_dir().unwrap()));
let agent_cert = try!(auth.add("host", &self.hostname));
// As we are in a project directory, it's safe to assume that
// the auth public key must be present.
let mut fh = File::open("auth.crt")?;
let mut au... | identifier_body |
bootstrap.rs | // Copyright 2015-2017 Intecture Developers. See the COPYRIGHT file at the
// top-level directory of this distribution and at
// https://intecture.io/COPYRIGHT.
//
// Licensed under the Mozilla Public License 2.0 <LICENSE or
// https://www.tldrlegal.com/l/mpl-2.0>. This file may not be copied,
// modified, or distribut... | hostname: String,
_stream: TcpStream,
session: Session,
is_root: bool,
}
impl Bootstrap {
pub fn new(hostname: &str,
port: Option<u32>,
username: Option<&str>,
password: Option<&str>,
identity_file: Option<&str>) -> Result<Bootstrap> {
... | pub struct Bootstrap { | random_line_split |
bootstrap.rs | // Copyright 2015-2017 Intecture Developers. See the COPYRIGHT file at the
// top-level directory of this distribution and at
// https://intecture.io/COPYRIGHT.
//
// Licensed under the Mozilla Public License 2.0 <LICENSE or
// https://www.tldrlegal.com/l/mpl-2.0>. This file may not be copied,
// modified, or distribut... | else {
sess.userauth_agent(u)?;
}
if sess.authenticated() {
Ok(Bootstrap {
hostname: hostname.into(),
_stream: tcp,
session: sess,
is_root: u == "root",
})
} else {
Err(Error::Bootst... | {
sess.userauth_password(u, p).unwrap();
} | conditional_block |
bootstrap.rs | // Copyright 2015-2017 Intecture Developers. See the COPYRIGHT file at the
// top-level directory of this distribution and at
// https://intecture.io/COPYRIGHT.
//
// Licensed under the Mozilla Public License 2.0 <LICENSE or
// https://www.tldrlegal.com/l/mpl-2.0>. This file may not be copied,
// modified, or distribut... | (hostname: &str,
port: Option<u32>,
username: Option<&str>,
password: Option<&str>,
identity_file: Option<&str>) -> Result<Bootstrap> {
let tcp = TcpStream::connect(&*format!("{}:{}", hostname, port.unwrap_or(22)))?;
let mut sess = Session::new... | new | identifier_name |
main.rs | #![feature(plugin, no_std, start, core_intrinsics)] | use zinc::drivers::chario::CharIO;
platformtree!(
tiva_c@mcu {
clock {
source = "MOSC";
xtal = "X16_0MHz";
pll = true;
div = 5;
}
timer {
/* The mcu contain both 16/32bit and "wide" 32/64bit timers. */
timer@w0 {
/* prescale sysclk to 1Mhz since th... | #![no_std]
#![plugin(macro_platformtree)]
extern crate zinc;
| random_line_split |
main.rs | #![feature(plugin, no_std, start, core_intrinsics)]
#![no_std]
#![plugin(macro_platformtree)]
extern crate zinc;
use zinc::drivers::chario::CharIO;
platformtree!(
tiva_c@mcu {
clock {
source = "MOSC";
xtal = "X16_0MHz";
pll = true;
div = 5;
}
timer {
/* The mc... | (args: &pt::run_args) {
use zinc::hal::timer::Timer;
use zinc::hal::pin::Gpio;
args.uart.puts("Hello, world\r\n");
let mut i = 0;
loop {
args.txled.set_high();
args.uart.puts("Waiting for ");
args.uart.puti(i);
args.uart.puts(" seconds...\r\n");
i += 1;
args.txled.set_low();
ar... | run | identifier_name |
main.rs | #![feature(plugin, no_std, start, core_intrinsics)]
#![no_std]
#![plugin(macro_platformtree)]
extern crate zinc;
use zinc::drivers::chario::CharIO;
platformtree!(
tiva_c@mcu {
clock {
source = "MOSC";
xtal = "X16_0MHz";
pll = true;
div = 5;
}
timer {
/* The mc... | {
use zinc::hal::timer::Timer;
use zinc::hal::pin::Gpio;
args.uart.puts("Hello, world\r\n");
let mut i = 0;
loop {
args.txled.set_high();
args.uart.puts("Waiting for ");
args.uart.puti(i);
args.uart.puts(" seconds...\r\n");
i += 1;
args.txled.set_low();
args.timer.wait(1);
}
... | identifier_body | |
htmldatalistelement.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/. */
use dom::bindings::codegen::Bindings::HTMLDataListElementBinding;
use dom::bindings::codegen::Bindings::HTMLDataLi... | (&self) -> Root<HTMLCollection> {
#[derive(JSTraceable, HeapSizeOf)]
struct HTMLDataListOptionsFilter;
impl CollectionFilter for HTMLDataListOptionsFilter {
fn filter(&self, elem: &Element, _root: &Node) -> bool {
elem.is::<HTMLOptionElement>()
}
}... | Options | identifier_name |
htmldatalistelement.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/. */
use dom::bindings::codegen::Bindings::HTMLDataListElementBinding;
use dom::bindings::codegen::Bindings::HTMLDataLi... | }
impl HTMLDataListElementMethods for HTMLDataListElement {
// https://html.spec.whatwg.org/multipage/#dom-datalist-options
fn Options(&self) -> Root<HTMLCollection> {
#[derive(JSTraceable, HeapSizeOf)]
struct HTMLDataListOptionsFilter;
impl CollectionFilter for HTMLDataListOptionsFilte... | Node::reflect_node(box element, document, HTMLDataListElementBinding::Wrap)
} | random_line_split |
htmldatalistelement.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/. */
use dom::bindings::codegen::Bindings::HTMLDataListElementBinding;
use dom::bindings::codegen::Bindings::HTMLDataLi... |
}
impl HTMLDataListElementMethods for HTMLDataListElement {
// https://html.spec.whatwg.org/multipage/#dom-datalist-options
fn Options(&self) -> Root<HTMLCollection> {
#[derive(JSTraceable, HeapSizeOf)]
struct HTMLDataListOptionsFilter;
impl CollectionFilter for HTMLDataListOptionsFilt... | {
let element = HTMLDataListElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLDataListElementBinding::Wrap)
} | identifier_body |
CancelTextCommand.js | var CancelTextCommand = function() {
this.Extends = SimpleCommand;
this.execute = function(note) {
//alert("CancelTextCommand");
var mediator = note.getBody();
var textEditor = null;
if (mediator instanceof ModelObjectsTextsEditorMediator) {
textEditor = mediator.getViewComponent().gridListSplitter.rig... |
var properties = {
"state": SjamayeeMediator.STATE_LIST,
"textEditor": textEditor
};
this.sendNotification(SjamayeeFacade.DATA_MODEL_CHANGE, properties);
//this.sendNotification(SjamayeeFacade.TEXT_CANCELED,mediator);
var toolBarMediator = null;
if (mediator instanceof ModelObjectsText... | {
textEditor = mediator.getViewComponent().gridListSplitter.right.modelRelationsTextsEditor;
} | conditional_block |
CancelTextCommand.js | var CancelTextCommand = function() {
this.Extends = SimpleCommand;
this.execute = function(note) {
//alert("CancelTextCommand");
var mediator = note.getBody();
var textEditor = null;
if (mediator instanceof ModelObjectsTextsEditorMediator) {
textEditor = mediator.getViewComponent().gridListSplitter.rig... | } else {
textEditor = mediator.getViewComponent().gridListSplitter.right.modelRelationsTextsEditor;
}
var properties = {
"state": SjamayeeMediator.STATE_LIST,
"textEditor": textEditor
};
this.sendNotification(SjamayeeFacade.DATA_MODEL_CHANGE, properties);
//this.sendNotification(Sjama... | random_line_split | |
experiment.py | #!/usr/bin/env python
"""
Manage and display experimental results.
"""
__license__ = 'MIT License <http://www.opensource.org/licenses/mit-license.php>'
__author__ = 'Lucas Theis <lucas@theis.io>'
__docformat__ = 'epytext'
__version__ = '0.4.3'
import sys
import os
import numpy
import random
import scipy
import socke... |
class XUnpickler(Unpickler):
"""
An extension of the Unpickler class which resolves some backwards
compatibility issues of Numpy.
"""
def find_class(self, module, name):
"""
Helps Unpickler to find certain Numpy modules.
"""
try:
numpy_version = StrictVersion(numpy.__version__)
if numpy_versio... | instances = ExperimentRequestHandler.running
instance = eval(self.rfile.read(int(self.headers['Content-Length'])))
if instance['status'] is 'PROGRESS':
if instance['id'] not in instances:
instances[instance['id']] = instance
instances[instance['id']]['status'] = 'running'
instances[instance['id']][... | identifier_body |
experiment.py | #!/usr/bin/env python
"""
Manage and display experimental results.
"""
__license__ = 'MIT License <http://www.opensource.org/licenses/mit-license.php>'
__author__ = 'Lucas Theis <lucas@theis.io>'
__docformat__ = 'epytext'
__version__ = '0.4.3'
import sys
import os
import numpy
import random
import scipy
import socke... | (self, progress):
self.status('PROGRESS', progress=progress)
def save(self, filename=None, overwrite=False):
"""
Store results. If a filename is given, the default is overwritten.
@type filename: string
@param filename: path to where the experiment will be stored
@type overwrite: boolean
@param ov... | progress | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.