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 |
|---|---|---|---|---|
account_db.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... | }
impl Factory {
/// Create a read-only accountdb.
/// This will panic when write operations are called.
pub fn readonly<'db>(&self, db: &'db HashDB, address_hash: H256) -> Box<HashDB + 'db> {
match *self {
Factory::Mangled => Box::new(AccountDB::from_hash(db, address_hash)),
Factory::Plain => Box::new(Wrap... |
impl Default for Factory {
fn default() -> Self { Factory::Mangled } | random_line_split |
account_db.rs | Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later... |
}
struct Wrapping<'db>(&'db HashDB);
impl<'db> HashDB for Wrapping<'db> {
fn keys(&self) -> HashMap<H256, i32> {
unimplemented!()
}
fn get(&self, key: &H256) -> Option<DBValue> {
if key == &SHA3_NULL_RLP {
return Some(DBValue::from_slice(&NULL_RLP_STATIC));
}
self.0.get(key)
}
fn contains(&self, ke... | {
if key == &SHA3_NULL_RLP {
return;
}
let key = combine_key(&self.address_hash, key);
self.db.remove(&key)
} | identifier_body |
account_db.rs | Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later... |
let key = combine_key(&self.address_hash, &key);
self.db.emplace(key, value)
}
fn remove(&mut self, key: &H256) {
if key == &SHA3_NULL_RLP {
return;
}
let key = combine_key(&self.address_hash, key);
self.db.remove(&key)
}
}
struct Wrapping<'db>(&'db HashDB);
impl<'db> HashDB for Wrapping<'db> {
f... | {
return;
} | conditional_block |
Task.test.tsx | import * as React from "react";
import createMockStore from "redux-mock-store";
import { mount, render, shallow } from "enzyme";
import { NewTask, Task, TaskImpl } from "../../src/components/Task/Task";
import { ISerenityState, SERENITY_INITIAL_STATE } from "../../src/model/SerenityState";
import { Store } from "react... | expect(tagOptions).toEqual([{label: "Test", value: 1}]);
expect(selectedTagOptions).toEqual([]);
});
it("creates Option objects for selected tags", () => {
const { tagOptions, selectedTagOptions } = TaskImpl.tagOptions([
{
id: 1,
name: "Test",
},
{
id: 2,
... | const { tagOptions, selectedTagOptions } = TaskImpl.tagOptions([{id: 1, name: "Test"}], undefined); | random_line_split |
messages.rs | //! Update parsing for user messages and conversation updates.
/// Specification on whether a message is incoming or outgoing.
#[derive(serde::Deserialize, Copy, Clone, Eq, PartialEq, Hash, Debug)]
pub enum MessageDirectionType {
/// Incoming messages: messages sent by someone other than the subscribed user.
#... | {
/// The unique identifier for this message.
#[serde(rename = "_id")]
pub message_id: String,
/// Whether or not it is now unread. Most likely `false`: going from read to unread is not supported in screeps
/// as of this writing.
pub unread: bool,
/// Phantom data in order to allow adding ... | MessageUnreadUpdate | identifier_name |
messages.rs | //! Update parsing for user messages and conversation updates.
/// Specification on whether a message is incoming or outgoing.
#[derive(serde::Deserialize, Copy, Clone, Eq, PartialEq, Hash, Debug)]
pub enum MessageDirectionType {
/// Incoming messages: messages sent by someone other than the subscribed user.
#... | /// [`ChannelUpdate::UserConversation`]: ../enum.ChannelUpdate.html
#[serde(rename = "type")]
pub direction: MessageDirectionType,
/// Whether or not the user who received this message has read it... Probably going to be false, as this is a
/// message that was just sent.
pub unread: bool,
/... | /// [`ChannelUpdate::UserMessage`]: ../enum.ChannelUpdate.html | random_line_split |
debug_node.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Injector} from '../di';
import {DebugContext} from '../view/index';
export class EventListener {
construc... |
}
/**
* @experimental
*/
export function asNativeElements(debugEls: DebugElement[]): any {
return debugEls.map((el) => el.nativeElement);
}
function _queryElementChildren(
element: DebugElement, predicate: Predicate<DebugElement>, matches: DebugElement[]) {
element.childNodes.forEach(node => {
if (node... | {
this.listeners.forEach((listener) => {
if (listener.name == eventName) {
listener.callback(eventObj);
}
});
} | identifier_body |
debug_node.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license |
import {Injector} from '../di';
import {DebugContext} from '../view/index';
export class EventListener {
constructor(public name: string, public callback: Function) {}
}
/**
* @experimental All debugging apis are currently experimental.
*/
export class DebugNode {
listeners: EventListener[] = [];
parent: Deb... | */ | random_line_split |
debug_node.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Injector} from '../di';
import {DebugContext} from '../view/index';
export class EventListener {
construc... | (
element: DebugElement, predicate: Predicate<DebugElement>, matches: DebugElement[]) {
element.childNodes.forEach(node => {
if (node instanceof DebugElement) {
if (predicate(node)) {
matches.push(node);
}
_queryElementChildren(node, predicate, matches);
}
});
}
function _quer... | _queryElementChildren | identifier_name |
debug_node.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Injector} from '../di';
import {DebugContext} from '../view/index';
export class EventListener {
construc... |
}
insertBefore(refChild: DebugNode, newChild: DebugNode): void {
const refIndex = this.childNodes.indexOf(refChild);
if (refIndex === -1) {
this.addChild(newChild);
} else {
if (newChild.parent) {
newChild.parent.removeChild(newChild);
}
newChild.parent = this;
th... | {
this.childNodes.splice(siblingIndex + 1, 0, ...newChildren);
newChildren.forEach(c => {
if (c.parent) {
c.parent.removeChild(c);
}
c.parent = this;
});
} | conditional_block |
main.rs | #![feature(plugin, start, core_intrinsics)]
#![no_std]
#![plugin(macro_platformtree)]
extern crate zinc;
use zinc::drivers::chario::CharIO;
use zinc::drivers::lcd::hd44780u::{Hd44780u, Font};
platformtree!(
tiva_c@mcu {
clock {
source = "MOSC";
xtal = "X16_0MHz";
pll = false;
}
... | lcd.custom_char_5x8(1,
[0b00100,
0b01010,
0b00100,
0b11111,
0b00100,
0b01010,
0b10001,
0b00000]);
// Enable blinking
lcd.display_c... | {
let lcd = Hd44780u::new(args.timer,
args.rs,
args.en,
[ args.d4, args.d5, args.d6, args.d7 ]);
lcd.init(true, Font::Font5x8);
// Create custom 'heart' character at index 0.
lcd.custom_char_5x8(0,
[0b00000,
... | identifier_body |
main.rs | #![feature(plugin, start, core_intrinsics)]
#![no_std]
#![plugin(macro_platformtree)]
extern crate zinc;
use zinc::drivers::chario::CharIO;
use zinc::drivers::lcd::hd44780u::{Hd44780u, Font};
platformtree!(
tiva_c@mcu {
clock {
source = "MOSC";
xtal = "X16_0MHz";
pll = false;
}
... | (args: &pt::run_args) {
let lcd = Hd44780u::new(args.timer,
args.rs,
args.en,
[ args.d4, args.d5, args.d6, args.d7 ]);
lcd.init(true, Font::Font5x8);
// Create custom 'heart' character at index 0.
lcd.custom_char_5x8(0,
... | run | identifier_name |
main.rs | #![feature(plugin, start, core_intrinsics)]
#![no_std]
#![plugin(macro_platformtree)]
extern crate zinc; | use zinc::drivers::chario::CharIO;
use zinc::drivers::lcd::hd44780u::{Hd44780u, Font};
platformtree!(
tiva_c@mcu {
clock {
source = "MOSC";
xtal = "X16_0MHz";
pll = false;
}
gpio {
a {
d7@5 { direction = "out"; }
}
b {
rs@0 { direction = "out"; }
... | random_line_split | |
check_static_recursion.rs | .
use ast_map;
use session::Session;
use middle::def::{DefStatic, DefConst, DefAssociatedConst, DefVariant, DefMap};
use util::nodemap::NodeMap;
use syntax::{ast, ast_util};
use syntax::codemap::Span;
use syntax::feature_gate::emit_feature_err;
use syntax::visit::Visitor;
use syntax::visit;
use std::cell::RefCell;
... | (&mut self, enum_definition: &'ast ast::EnumDef,
generics: &'ast ast::Generics) {
self.populate_enum_discriminants(enum_definition);
visit::walk_enum_def(self, enum_definition, generics);
}
fn visit_variant(&mut self, variant: &'ast ast::Variant,
_: &'... | visit_enum_def | identifier_name |
check_static_recursion.rs | .
use ast_map;
use session::Session;
use middle::def::{DefStatic, DefConst, DefAssociatedConst, DefVariant, DefMap};
use util::nodemap::NodeMap;
use syntax::{ast, ast_util};
use syntax::codemap::Span;
use syntax::feature_gate::emit_feature_err;
use syntax::visit::Visitor;
use syntax::visit;
use std::cell::RefCell;
... |
// Go through all the variants.
let mut variant_stack: Vec<ast::NodeId> = Vec::new();
for variant in enum_definition.variants.iter().rev() {
variant_stack.push(variant.node.id);
// When we find an expression, every variant currently on the stack
// is affecte... | } | random_line_split |
check_static_recursion.rs | let mut recursion_visitor =
CheckItemRecursionVisitor::new(self, &it.span);
recursion_visitor.visit_item(it);
},
ast::ItemEnum(ref enum_def, ref generics) => {
// We could process the whole enum, but handling the variants
// wi... | {
if let ast::ItemEnum(ref enum_def, ref generics) =
self.ast_map.expect_item(enum_id.local_id()).node {
self.populate_enum_discriminants(enum_def);
let variant = self.ast_map.expect_variant(variant_id.local_i... | conditional_block | |
check_static_recursion.rs | use ast_map;
use session::Session;
use middle::def::{DefStatic, DefConst, DefAssociatedConst, DefVariant, DefMap};
use util::nodemap::NodeMap;
use syntax::{ast, ast_util};
use syntax::codemap::Span;
use syntax::feature_gate::emit_feature_err;
use syntax::visit::Visitor;
use syntax::visit;
use std::cell::RefCell;
str... |
fn with_item_id_pushed<F>(&mut self, id: ast::NodeId, f: F)
where F: Fn(&mut Self) {
if self.idstack.iter().any(|&x| x == id) {
let any_static = self.idstack.iter().any(|&x| {
if let ast_map::NodeItem(item) = self.ast_map.get(x) {
if let ast::ItemSt... | {
CheckItemRecursionVisitor {
root_span: span,
sess: v.sess,
ast_map: v.ast_map,
def_map: v.def_map,
discriminant_map: &v.discriminant_map,
idstack: Vec::new(),
}
} | identifier_body |
bzr.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2013, André Paramés <git@andreparames.com>
# Based on the Git module by Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License a... | if self.version.lower() != 'head':
args_list = ["branch", "-r", self.version, self.parent, self.dest]
else:
args_list = ["branch", self.parent, self.dest]
return self._command(args_list, check_rc=True, cwd=dest_dirname)
def has_local_mods(self):
cmd = "%s st... | dest_dirname = os.path.dirname(self.dest)
try:
os.makedirs(dest_dirname)
except:
pass | random_line_split |
bzr.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2013, André Paramés <git@andreparames.com>
# Based on the Git module by Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License a... | f):
'''once pulled, switch to a particular revno or revid'''
if self.version.lower() != 'head':
args_list = ["revert", "-r", self.version]
else:
args_list = ["revert"]
return self._command(args_list, check_rc=True, cwd=self.dest)
# ===============================... | ch_version(sel | identifier_name |
bzr.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2013, André Paramés <git@andreparames.com>
# Based on the Git module by Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License a... | def reset(self, force):
'''
Resets the index and working tree to head.
Discards any changes to tracked files in the working
tree since that commit.
'''
if not force and self.has_local_mods():
self.module.fail_json(msg="Local modifications exist in branch (fo... | = "%s status -S" % self.bzr_path
rc, stdout, stderr = self.module.run_command(cmd, cwd=self.dest)
lines = stdout.splitlines()
lines = filter(lambda c: not re.search('^\\?\\?.*$', c), lines)
return len(lines) > 0
| identifier_body |
bzr.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2013, André Paramés <git@andreparames.com>
# Based on the Git module by Michael DeHaan <michael.dehaan@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License a... | else:
# else do a pull
local_mods = bzr.has_local_mods()
before = bzr.get_version()
(rc, out, err) = bzr.reset(force)
if rc != 0:
module.fail_json(msg=err)
(rc, out, err) = bzr.fetch()
if rc != 0:
module.fail_json(msg=err)
# switch t... | out, err) = bzr.clone()
| conditional_block |
os-RU.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
const u = undefined;
fun... | export default [
'os-RU',
[['AM', 'PM'], u, ['ӕмбисбоны размӕ', 'ӕмбисбоны фӕстӕ']],
[['AM', 'PM'], u, u],
[
['Х', 'К', 'Д', 'Ӕ', 'Ц', 'М', 'С'],
['хцб', 'крс', 'дцг', 'ӕрт', 'цпр', 'мрб', 'сбт'],
[
'хуыцаубон', 'къуырисӕр', 'дыццӕг', 'ӕртыццӕг',
'цыппӕрӕм', 'майрӕмбон', 'сабат'
],
... | return 5;
}
| random_line_split |
os-RU.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
const u = undefined;
fun... |
export default [
'os-RU',
[['AM', 'PM'], u, ['ӕмбисбоны размӕ', 'ӕмбисбоны фӕстӕ']],
[['AM', 'PM'], u, u],
[
['Х', 'К', 'Д', 'Ӕ', 'Ц', 'М', 'С'],
['хцб', 'крс', 'дцг', 'ӕрт', 'цпр', 'мрб', 'сбт'],
[
'хуыцаубон', 'къуырисӕр', 'дыццӕг', 'ӕртыццӕг',
'цыппӕрӕм', 'майрӕмбон', 'сабат'
],... | {
if (n === 1) return 1;
return 5;
} | identifier_body |
os-RU.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
const u = undefined;
fun... | (n: number): number {
if (n === 1) return 1;
return 5;
}
export default [
'os-RU',
[['AM', 'PM'], u, ['ӕмбисбоны размӕ', 'ӕмбисбоны фӕстӕ']],
[['AM', 'PM'], u, u],
[
['Х', 'К', 'Д', 'Ӕ', 'Ц', 'М', 'С'],
['хцб', 'крс', 'дцг', 'ӕрт', 'цпр', 'мрб', 'сбт'],
[
'хуыцаубон', 'къуырисӕр', 'дыццӕг... | plural | identifier_name |
which-browser.d.ts | declare module "which-browser" {
export interface WhichBrowserDetails {
toString(): string;
getName(): string;
getVersion(): string;
name: string;
version: WhichBrowserVersion;
}
export interface WhichBrowserVersion {
value: string | number;
alias: string;
details: number;
toSt... | {
constructor(userAgentString: string | any, options?: WhichBrowserOptions);
browser: WhichBrowserBrowser;
engine: WhichBrowserDetails;
os: WhichBrowserOS;
device: WhichBrowserDevice;
toString(): string;
isType(...args: string[]): boolean;
isBrowser(name: string, comparison?: string, ... | WhichBrowser | identifier_name |
which-browser.d.ts | declare module "which-browser" {
export interface WhichBrowserDetails {
toString(): string;
getName(): string;
getVersion(): string;
name: string;
version: WhichBrowserVersion;
}
export interface WhichBrowserVersion {
value: string | number;
alias: string;
details: number;
toSt... |
toString(): string;
isType(...args: string[]): boolean;
isBrowser(name: string, comparison?: string, version?: string | number): boolean;
isOs(name: string, comparison?: string, version?: string | number): boolean;
isEngine(name: string, comparison?: string, version?: string | number): boolean;
... |
browser: WhichBrowserBrowser;
engine: WhichBrowserDetails;
os: WhichBrowserOS;
device: WhichBrowserDevice; | random_line_split |
test_models.py | # -*- coding: utf-8 -*-
"""Model unit tests."""
import datetime as dt
import pytest
from cookie_flaskApp.user.models import User, Role
from .factories import UserFactory
@pytest.mark.usefixtures('db')
class TestUser:
def test_get_by_id(self):
user = User('foo', 'foo@bar.com')
user.save()
... | (self):
user = User(username='foo', email='foo@bar.com')
user.save()
assert bool(user.created_at)
assert isinstance(user.created_at, dt.datetime)
def test_password_is_nullable(self):
user = User(username='foo', email='foo@bar.com')
user.save()
assert user.pas... | test_created_at_defaults_to_datetime | identifier_name |
test_models.py | # -*- coding: utf-8 -*-
"""Model unit tests."""
import datetime as dt
import pytest
from cookie_flaskApp.user.models import User, Role
from .factories import UserFactory
@pytest.mark.usefixtures('db')
class TestUser:
def test_get_by_id(self):
user = User('foo', 'foo@bar.com')
user.save()
... | u = UserFactory()
u.roles.append(role)
u.save()
assert role in u.roles | random_line_split | |
test_models.py | # -*- coding: utf-8 -*-
"""Model unit tests."""
import datetime as dt
import pytest
from cookie_flaskApp.user.models import User, Role
from .factories import UserFactory
@pytest.mark.usefixtures('db')
class TestUser:
def test_get_by_id(self):
user = User('foo', 'foo@bar.com')
user.save()
... |
def test_factory(self):
user = UserFactory(password="myprecious")
assert bool(user.username)
assert bool(user.email)
assert bool(user.created_at)
assert user.is_admin is False
assert user.active is True
assert user.check_password('myprecious')
def test_... | user = User(username='foo', email='foo@bar.com')
user.save()
assert user.password is None | identifier_body |
link.js | /*
* ------------------------------------------
* 超链接执行命令封装实现文件
* @version 1.0
* @author genify(caijf@corp.netease.com)
* ------------------------------------------
*/
/** util/editor/command/link */ | 'ui/editor/command/link'
],function(NEJ,_k,_t0,_i0,_p,_o,_f,_r){
var _pro;
/**
* 超链接执行命令封装
*
* @class module:util/editor/command/link._$$Link
* @extends module:util/editor/command/card._$$CardCommand
* @param {Object} options - 可选配置参数
*/
_p._$$Link = _k._$klass();
_... | NEJ.define([
'base/global',
'base/klass',
'util/editor/command/card', | random_line_split |
link.js | /*
* ------------------------------------------
* 超链接执行命令封装实现文件
* @version 1.0
* @author genify(caijf@corp.netease.com)
* ------------------------------------------
*/
/** util/editor/command/link */
NEJ.define([
'base/global',
'base/klass',
'util/editor/command/card',
'ui/editor/command/link'
... | conditional_block | ||
FocusDetail.js | import React from 'react';
import PrimaryCallToAction from '../../../shared/js/components/gironde.fr/PrimaryCallToAction';
import Markdown from '../../../shared/js/components/Markdown';
import MoneyAmount from '../../../shared/js/components/MoneyAmount';
/*
interface FocusDetailProps{
className: string
title... | );
} | })
) : undefined,
React.createElement(PrimaryCallToAction, {href: moreUrl, text: 'En savoir plus'})
) | random_line_split |
array.ts | /*
* Kuzzle, a backend software, self-hostable and ready to use
* to power modern apps
*
* Copyright 2015-2020 Kuzzle
* mailto: support AT kuzzle.io
* website: http://kuzzle.io
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.... |
while (lowerBound <= upperBound) {
// 5x faster than Math.floor((lowerBound + upperBound) / 2)
const index = (lowerBound + upperBound) >> 1;
const comparison = predicate(array[index]);
if (comparison < 0) {
upperBound = index - 1;
}
else if (comparison > 0) {
lowerBound = index + ... |
if (array.length === 1) {
return predicate(array[0]) === 0 ? 0 : -1;
} | random_line_split |
array.ts | /*
* Kuzzle, a backend software, self-hostable and ready to use
* to power modern apps
*
* Copyright 2015-2020 Kuzzle
* mailto: support AT kuzzle.io
* website: http://kuzzle.io
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.... | (array: any[], predicate: (value: any) => number) {
let lowerBound = 0;
let upperBound = array.length - 1;
if (array.length === 1) {
return predicate(array[0]) === 0 ? 0 : -1;
}
while (lowerBound <= upperBound) {
// 5x faster than Math.floor((lowerBound + upperBound) / 2)
const index = (lowerBo... | binarySearch | identifier_name |
array.ts | /*
* Kuzzle, a backend software, self-hostable and ready to use
* to power modern apps
*
* Copyright 2015-2020 Kuzzle
* mailto: support AT kuzzle.io
* website: http://kuzzle.io
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.... | }
}
return -1;
} | {
let lowerBound = 0;
let upperBound = array.length - 1;
if (array.length === 1) {
return predicate(array[0]) === 0 ? 0 : -1;
}
while (lowerBound <= upperBound) {
// 5x faster than Math.floor((lowerBound + upperBound) / 2)
const index = (lowerBound + upperBound) >> 1;
const comparison = pred... | identifier_body |
array.ts | /*
* Kuzzle, a backend software, self-hostable and ready to use
* to power modern apps
*
* Copyright 2015-2020 Kuzzle
* mailto: support AT kuzzle.io
* website: http://kuzzle.io
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.... |
}
return -1;
} | {
return index;
} | conditional_block |
EnvironmentCheck.ts | /*
* This file is part of the TYPO3 CMS project.
*
* It is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, either version 2
* of the License, or any later version.
*
* For the full copyright and license information, please read the
* LICENSE.txt file ... | if (Array.isArray(element) && element.length > 0) {
element.forEach((aStatus: any): void => {
if (aStatus.severity === 1) {
warningCount++;
}
if (aStatus.severity === 2) {
errorCount++;
... | {
this.setModalButtonsState(false);
const modalContent = this.getModalBody();
const $errorBadge = $(this.selectorGridderBadge);
$errorBadge.text('').hide();
const message = ProgressBar.render(Severity.loading, 'Loading...', '');
modalContent.find(this.selectorOutputContainer).empty().append(mes... | identifier_body |
EnvironmentCheck.ts | /*
* This file is part of the TYPO3 CMS project.
*
* It is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, either version 2
* of the License, or any later version.
*
* For the full copyright and license information, please read the
* LICENSE.txt file ... | },
(error: AjaxResponse): void => {
Router.handleAjaxError(error, modalContent);
}
);
}
}
export = new EnvironmentCheck(); | random_line_split | |
EnvironmentCheck.ts | /*
* This file is part of the TYPO3 CMS project.
*
* It is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, either version 2
* of the License, or any later version.
*
* For the full copyright and license information, please read the
* LICENSE.txt file ... |
const aMessage = InfoBox.render(aStatus.severity, aStatus.title, aStatus.message);
modalContent.find(this.selectorOutputContainer).append(aMessage);
});
}
});
if (errorCount > 0) {
$errorBadge.removeClass('label-war... | {
errorCount++;
} | conditional_block |
EnvironmentCheck.ts | /*
* This file is part of the TYPO3 CMS project.
*
* It is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, either version 2
* of the License, or any later version.
*
* For the full copyright and license information, please read the
* LICENSE.txt file ... | (currentModal: JQuery): void {
this.currentModal = currentModal;
// Get status on initialize to have the badge and content ready
this.runTests();
currentModal.on('click', this.selectorExecuteTrigger, (e: JQueryEventObject): void => {
e.preventDefault();
this.runTests();
});
}
priv... | initialize | identifier_name |
constellation_msg.rs | IpcReceiver<T>, ConstellationChan<T>) {
let (chan, port) = ipc::channel().unwrap();
(port, ConstellationChan(chan))
}
}
impl<T: Serialize + Deserialize> Clone for ConstellationChan<T> {
fn clone(&self) -> ConstellationChan<T> {
ConstellationChan(self.0.clone())
}
}
pub type PanicMs... | fake_root_pipeline_id | identifier_name | |
constellation_msg.rs | ;
use url::Url;
use util::geometry::{PagePx, ViewportPx};
use webdriver_msg::{LoadStatus, WebDriverScriptCommand};
use webrender_traits;
#[derive(Deserialize, Serialize)]
pub struct ConstellationChan<T: Deserialize + Serialize>(pub IpcSender<T>);
impl<T: Deserialize + Serialize> ConstellationChan<T> {
pub fn new(... | LeftControl,
LeftAlt,
LeftSuper,
RightShift,
RightControl,
RightAlt,
RightSuper,
Menu,
NavigateBackward,
NavigateForward,
}
bitflags! {
#[derive(Deserialize, Serialize)]
flags KeyModifiers: u8 {
const NONE = 0x00,
const SHIFT = 0x01,
const CONTRO... | random_line_split | |
timer.js | var endtime = null;
var stepper = null;
var defaulttime = (2 * 60 + 30) * 1000;
function displayTime(d, func) {
var min = 0, sec = 0, ms = 0;
if (d > 0) {
var dd = d;
ms = Math.floor(d % 1000 / 100);
d = Math.floor(d / 1000);
sec = d % 60;
d = Math.floor(d / 60);
... | (func) {
$("#timer").text("Stop").removeClass("btn-default btn-success").addClass("btn-danger");
endtime = Date.now() + defaulttime;
stepper = setInterval(function() {
displayTime(endtime - Date.now(), func);
}, 100);
ga("send", "event", "timer", "start");
}
function stopTimer(reset) {
... | startTimer | identifier_name |
timer.js | var endtime = null;
var stepper = null;
var defaulttime = (2 * 60 + 30) * 1000;
function displayTime(d, func) {
var min = 0, sec = 0, ms = 0;
if (d > 0) {
var dd = d; | d = Math.floor(d / 60);
min = d;
d = dd;
}
else {
stopTimer();
}
$('#time #min').text(min);
$('#time #sec').text((sec < 10 ? '0' : '') + sec);
$('#time #ms').text(ms);
(func || function(){})(d);
}
function startTimer(func) {
$("#timer").text("Stop").re... |
ms = Math.floor(d % 1000 / 100);
d = Math.floor(d / 1000);
sec = d % 60; | random_line_split |
timer.js | var endtime = null;
var stepper = null;
var defaulttime = (2 * 60 + 30) * 1000;
function displayTime(d, func) {
var min = 0, sec = 0, ms = 0;
if (d > 0) {
var dd = d;
ms = Math.floor(d % 1000 / 100);
d = Math.floor(d / 1000);
sec = d % 60;
d = Math.floor(d / 60);
... |
function stopTimer(reset) {
$("#timer").text("Start").removeClass("btn-default btn-danger").addClass("btn-success");
endtime = null;
clearInterval(stepper);
stepper = null;
if (!reset)
ga("send", "event", "timer", "stop", $("#time").text().trim());
}
function resetTimer(func) {
disp... | {
$("#timer").text("Stop").removeClass("btn-default btn-success").addClass("btn-danger");
endtime = Date.now() + defaulttime;
stepper = setInterval(function() {
displayTime(endtime - Date.now(), func);
}, 100);
ga("send", "event", "timer", "start");
} | identifier_body |
2d4882d39dbb_add_graphql_acl_to_users.py | """add graphql ACL to users
Revision ID: 2d4882d39dbb
Revises: c4d0e9ec46a9
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '2d4882d39dbb'
down_revision = 'dc2848563b53'
POLICY_NAME = 'wazo_default_user_policy'
ACL_TEMPLATES = ['dird.graphql.me']
policy_tabl... | conn = op.get_bind()
acl_template_ids = _find_acl_templates(conn, ACL_TEMPLATES)
if not acl_template_ids:
return
policy_uuid = _get_policy_uuid(conn, POLICY_NAME)
if not policy_uuid:
return
delete_query = policy_template.delete().where(
sa.sql.and_(
policy_templ... | identifier_body | |
2d4882d39dbb_add_graphql_acl_to_users.py | """add graphql ACL to users
Revision ID: 2d4882d39dbb
Revises: c4d0e9ec46a9
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '2d4882d39dbb'
down_revision = 'dc2848563b53'
POLICY_NAME = 'wazo_default_user_policy'
ACL_TEMPLATES = ['dird.graphql.me']
policy_tabl... |
acl_template_ids = _insert_acl_template(conn, ACL_TEMPLATES)
acl_template_ids_already_associated = _get_acl_template_ids(conn, policy_uuid)
for template_id in set(acl_template_ids) - set(acl_template_ids_already_associated):
query = policy_template.insert().values(
policy_uuid=policy_u... | return | conditional_block |
2d4882d39dbb_add_graphql_acl_to_users.py | """add graphql ACL to users
Revision ID: 2d4882d39dbb
Revises: c4d0e9ec46a9
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '2d4882d39dbb'
down_revision = 'dc2848563b53'
POLICY_NAME = 'wazo_default_user_policy'
ACL_TEMPLATES = ['dird.graphql.me']
policy_tabl... | ():
conn = op.get_bind()
acl_template_ids = _find_acl_templates(conn, ACL_TEMPLATES)
if not acl_template_ids:
return
policy_uuid = _get_policy_uuid(conn, POLICY_NAME)
if not policy_uuid:
return
delete_query = policy_template.delete().where(
sa.sql.and_(
poli... | downgrade | identifier_name |
2d4882d39dbb_add_graphql_acl_to_users.py | """add graphql ACL to users
Revision ID: 2d4882d39dbb
Revises: c4d0e9ec46a9
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '2d4882d39dbb'
down_revision = 'dc2848563b53'
| 'auth_policy', sa.Column('uuid', sa.String(38)), sa.Column('name', sa.String(80))
)
acl_template_table = sa.sql.table(
'auth_acl_template', sa.Column('id', sa.Integer), sa.Column('template', sa.Text)
)
policy_template = sa.sql.table(
'auth_policy_template',
sa.Column('policy_uuid', sa.String(38)),
s... | POLICY_NAME = 'wazo_default_user_policy'
ACL_TEMPLATES = ['dird.graphql.me']
policy_table = sa.sql.table( | random_line_split |
websocket_session.rs | use async_trait::async_trait;
use futures::{stream::SplitSink, FutureExt, SinkExt};
use serde::Serialize;
use std::net::SocketAddr;
use tokio::io::Result;
use warp::ws::{Message, WebSocket};
use super::session::Session;
use super::{SessionOutput, SessionPromptInfo, SessionState, SignInState};
#[derive(Serialize)]
str... | }
}
SessionOutput::None => {}
}
}
fn set_state(&mut self, state: SessionState) {
self.state = state;
}
fn source(&self) -> String {
format!("{}", self.addr.ip())
}
fn state(&self) -> &SessionState {
&self.state
}
}
a... | self.send(output).await | random_line_split |
websocket_session.rs | use async_trait::async_trait;
use futures::{stream::SplitSink, FutureExt, SinkExt};
use serde::Serialize;
use std::net::SocketAddr;
use tokio::io::Result;
use warp::ws::{Message, WebSocket};
use super::session::Session;
use super::{SessionOutput, SessionPromptInfo, SessionState, SignInState};
#[derive(Serialize)]
str... | (&mut self) -> Result<()> {
self.tx.close().map(|_| Ok(())).await
}
async fn send(&mut self, output: SessionOutput) {
match output {
SessionOutput::Json(data) => {
send_message(&mut self.tx, Message::text(data.to_string())).await
}
SessionOutp... | close | identifier_name |
websocket_session.rs | use async_trait::async_trait;
use futures::{stream::SplitSink, FutureExt, SinkExt};
use serde::Serialize;
use std::net::SocketAddr;
use tokio::io::Result;
use warp::ws::{Message, WebSocket};
use super::session::Session;
use super::{SessionOutput, SessionPromptInfo, SessionState, SignInState};
#[derive(Serialize)]
str... |
}
#[async_trait]
impl Session for WebSocketSession {
async fn close(&mut self) -> Result<()> {
self.tx.close().map(|_| Ok(())).await
}
async fn send(&mut self, output: SessionOutput) {
match output {
SessionOutput::Json(data) => {
send_message(&mut self.tx, Mes... | {
Self {
id,
addr,
tx,
state: SessionState::SigningIn(Box::new(SignInState::new())),
}
} | identifier_body |
websocket_session.rs | use async_trait::async_trait;
use futures::{stream::SplitSink, FutureExt, SinkExt};
use serde::Serialize;
use std::net::SocketAddr;
use tokio::io::Result;
use warp::ws::{Message, WebSocket};
use super::session::Session;
use super::{SessionOutput, SessionPromptInfo, SessionState, SignInState};
#[derive(Serialize)]
str... |
SessionOutput::Aggregate(outputs) => {
for output in outputs {
self.send(output).await
}
}
SessionOutput::None => {}
}
}
fn set_state(&mut self, state: SessionState) {
self.state = state;
}
fn sour... | {
let prompt = Prompt { player: info };
send_message(
&mut self.tx,
Message::text(serde_json::to_string(&prompt).unwrap()),
)
.await
} | conditional_block |
index.js | 'use strict';
var fs = require('fs');
var irc = require('irc');
var nconf = require('nconf');
var path = require('path');
nconf.argv()
.env() | irc_username:'ircbotjs',
});
if(!nconf.get('irc_nickname')){
console.error("irc_nickname is not defined, exiting!");
process.exit(1);
}
if(!nconf.get('irc_server')){
console.error("irc_server is not defined, exiting!");
process.exit(1);
}
var client = new irc.Client(nconf.get('irc_server'), nconf.get(... | .file({ file: 'config.json' })
.defaults({script_directory:'scripts',
sasl:false,
irc_server_password:'',
irc_realname:'ircbotjs', | random_line_split |
index.js | 'use strict';
var fs = require('fs');
var irc = require('irc');
var nconf = require('nconf');
var path = require('path');
nconf.argv()
.env()
.file({ file: 'config.json' })
.defaults({script_directory:'scripts',
sasl:false,
irc_server_password:'',
irc_realname:'ircbotjs',
irc_username:'ircbotjs... |
});
client.addListener('error', function(message) {
console.log('error: ', message);
});
| {
client.say(to,visible_modules.length+" modules visible:");
visible_modules.forEach((m,i) => {
setTimeout(() =>{
client.say(to," * "+m);
},600*i);
});
} | conditional_block |
index.js | /**
* External dependencies
*/
import React, { useEffect } from 'react';
import { translate as __ } from 'i18n-calypso';
import { connect } from 'react-redux';
/**
* Internal dependencies
*/
import {
getGroup,
setPage,
performTableAction,
setOrderBy,
setFilter,
setDisplay,
setSelected,
} from 'state/group... | onSetDisplay: ( displayType, displaySelected ) => {
dispatch( setDisplay( displayType, displaySelected ) );
},
onSetAll: ( allOrClear ) => {
dispatch( setSelected( allOrClear, allOrClear ) );
},
};
}
export default connect(
mapStateToProps,
mapDispatchToProps
)( Groups );
| {
return {
onLoadGroups: () => {
dispatch( getGroup() );
},
onChangePage: ( page ) => {
dispatch( setPage( page ) );
},
onBulk: ( action, ids ) => {
dispatch( performTableAction( action, ids ) );
},
onSelect: ( items ) => {
dispatch( setSelected( items ) );
},
onSetOrder: ( column, direct... | identifier_body |
index.js | /**
* External dependencies
*/
import React, { useEffect } from 'react';
import { translate as __ } from 'i18n-calypso';
import { connect } from 'react-redux';
/**
* Internal dependencies
*/
import {
getGroup,
setPage,
performTableAction,
setOrderBy,
setFilter,
setDisplay,
setSelected,
} from 'state/group... | displayFilters: getDisplayOptions(),
displayGroups: getDisplayGroups(),
searchOptions: getSearchOptions(),
groupBy: [],
bulk: getBulk(),
rowFilters: getFilterOptions(
getModules().map( ( module ) => ( { label: module.label, value: `${ module.value }` } ) )
),
headers: getHeaders().filter( ( item ) =>... |
const logOptions = { | random_line_split |
index.js | /**
* External dependencies
*/
import React, { useEffect } from 'react';
import { translate as __ } from 'i18n-calypso';
import { connect } from 'react-redux';
/**
* Internal dependencies
*/
import {
getGroup,
setPage,
performTableAction,
setOrderBy,
setFilter,
setDisplay,
setSelected,
} from 'state/group... | ( item, table ) {
return table.displaySelected.indexOf( item ) !== -1;
}
function Groups( props ) {
const { onDelete, group } = props;
const { status, total, table, rows, saving } = group;
useEffect(() => {
props.onLoadGroups();
}, []);
const logOptions = {
displayFilters: getDisplayOptions(),
displayGro... | isAvailable | identifier_name |
index.js | /**
* External dependencies
*/
import React, { useEffect } from 'react';
import { translate as __ } from 'i18n-calypso';
import { connect } from 'react-redux';
/**
* Internal dependencies
*/
import {
getGroup,
setPage,
performTableAction,
setOrderBy,
setFilter,
setDisplay,
setSelected,
} from 'state/group... |
return selected;
}
function isAvailable( item, table ) {
return table.displaySelected.indexOf( item ) !== -1;
}
function Groups( props ) {
const { onDelete, group } = props;
const { status, total, table, rows, saving } = group;
useEffect(() => {
props.onLoadGroups();
}, []);
const logOptions = {
displa... | {
return selected.concat( [ 'name' ] );
} | conditional_block |
play_20170531212602.js | var playState = {
create: function(){
var background = game.add.sprite(0, 0, 'cidade');
background.width = 1300;
background.height = 650;
graphics = game.add.graphics(0, 0);
groupCidade = game.add.group();
groupCidade.inputEnableChildren = true;
var x = 1... | gato.height = 170;
// Desenha o passaro e a borda da box
var passaro = game.add.sprite(910, 210, 'passaro');
passaro.width = 300;
passaro.height = 170;
groupCidade.onChildInputDown.add(onDown, this);
groupCidade.onChildInputOver.add(onOver, this);
... | // Desenha o gato e a borda da box
var gato = game.add.sprite(510, 210, 'gato');
gato.width = 300; | random_line_split |
play_20170531212602.js | var playState = {
create: function(){
var background = game.add.sprite(0, 0, 'cidade');
background.width = 1300;
background.height = 650;
graphics = game.add.graphics(0, 0);
groupCidade = game.add.group();
groupCidade.inputEnableChildren = true;
var x = 1... |
function onOut (sprite) {
sprite.tint = 0xff7b00;
}
},
update: function(){
},
Win: function(){
game.state.start('win');
}
}; |
sprite.tint = 0xff7b00;
}
| identifier_body |
play_20170531212602.js | var playState = {
create: function(){
var background = game.add.sprite(0, 0, 'cidade');
background.width = 1300;
background.height = 650;
graphics = game.add.graphics(0, 0);
groupCidade = game.add.group();
groupCidade.inputEnableChildren = true;
var x = 1... | (sprite) {
sprite.tint = 0xff7b00;
}
function onOut (sprite) {
sprite.tint = 0xff7b00;
}
},
update: function(){
},
Win: function(){
game.state.start('win');
}
}; | nOver | identifier_name |
play_20170531212602.js | var playState = {
create: function(){
var background = game.add.sprite(0, 0, 'cidade');
background.width = 1300;
background.height = 650;
graphics = game.add.graphics(0, 0);
groupCidade = game.add.group();
groupCidade.inputEnableChildren = true;
var x = 1... | graphics.destroy();
var cachorro = game.add.sprite(110, 210, 'cachorro');
cachorro.width = 300;
cachorro.height = 170;
// Desenha o gato e a borda da box
var gato = game.add.sprite(510, 210, 'gato');
gato.width = 300;
gato.height = 170;
... | {
// Gera os retangulos que ficarão atras das imagens
graphics.beginFill(0xff7b00);
graphics.lineStyle(3, 0x05005e, 1);
graphics.drawRoundedRect(x, 200, 315, 190, 10);
graphics.endFill();
var button = groupCidade.create(x, 200, graphics.generateTe... | conditional_block |
rdxml.py | try:
from xml.etree import cElementTree as etree
except ImportError:
from xml.etree import ElementTree as etree
import xml2nrn
# module names derived from the namespace. Add new tags in proper namespace
import neuroml
import metadata
import morphml
import biophysics
class FileWrapper:
def __init__(self, sou... |
if (ho):
ho.parsed(x2n)
if __name__ == '__main__':
rdxml('temp.xml')
| if ig != elem:
if handle(x2n, f, event, elem) == 0:
ig = elem | conditional_block |
rdxml.py | try:
from xml.etree import cElementTree as etree
except ImportError:
from xml.etree import ElementTree as etree
import xml2nrn
# module names derived from the namespace. Add new tags in proper namespace
import neuroml
import metadata
import morphml
import biophysics
class FileWrapper:
def __init__(self, sou... | (fname, ho = None):
f = FileWrapper(open(fname))
x2n = xml2nrn.XML2Nrn()
ig = None
for event, elem in etree.iterparse(f, events=("start", "end")):
if ig != elem:
if handle(x2n, f, event, elem) == 0:
ig = elem
if (ho):
ho.parsed(x2n)
if __name__ == '__main__':
rdxml('temp.xml')
| rdxml | identifier_name |
rdxml.py | try:
from xml.etree import cElementTree as etree
except ImportError:
from xml.etree import ElementTree as etree
import xml2nrn
# module names derived from the namespace. Add new tags in proper namespace
import neuroml
import metadata
import morphml
import biophysics
class FileWrapper:
def __init__(self, sou... | except:
print tag,' failed at ', x2n.locator.getLineNumber()
elif event == 'start':
print 'ignore', node.tag # no function to handle the element
return 0
return 1
def rdxml(fname, ho = None):
f = FileWrapper(open(fname))
x2n = xml2nrn.XML2Nrn()
ig = None
for event, elem in etree.iterparse... | try:
f(x2n, node) # handle the element when it opens | random_line_split |
rdxml.py | try:
from xml.etree import cElementTree as etree
except ImportError:
from xml.etree import ElementTree as etree
import xml2nrn
# module names derived from the namespace. Add new tags in proper namespace
import neuroml
import metadata
import morphml
import biophysics
class FileWrapper:
def __init__(self, sou... |
def read(self, bytes):
s = self.source.readline()
self.lineno += 1
return s
# for each '{namespace}element' call the corresponding module.func
def handle(x2n, fw, event, node):
tag = node.tag.split('}')
# hopefully a namespace token corresponding to an imported module name
ns = t... | self.source = source
self.lineno = 0 | identifier_body |
preferences.py | #!/usr/bin/python
"""
Preferences Frame
Copyright (c) 2014, 2015 Andrew Hawkins
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 us... | # Load the preferences from the pickle file.
pref = pickle.load(open(os.path.join(idata.DATA, "Forsteri",
"pref.p"), "rb"))
# Set all of the prefernce objects.
self.row1Obj.SetValue(pref["report_type"])
return True
def savePref(self):
"""
"""
... | random_line_split | |
preferences.py | #!/usr/bin/python
"""
Preferences Frame
Copyright (c) 2014, 2015 Andrew Hawkins
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 us... |
# Create the reporting sizer.
reportSizer = wx.StaticBoxSizer(reportSB, wx.VERTICAL)
# Create the first rows sizer.
row1Sizer = wx.BoxSizer(wx.HORIZONTAL)
# Create the label for the first row.
row1Label = wx.StaticText(masterPanel, label="Forecast Type")
# Cre... | """
"""
def __init__(self, *args, **kwargs):
"""
"""
## Panel
# Initialize the parents constructor.
super(PreferencesFrame, self).__init__(*args, **kwargs)
# Create the master panel.
masterPanel = wx.Panel(self)
# Create the master sizer.
... | identifier_body |
preferences.py | #!/usr/bin/python
"""
Preferences Frame
Copyright (c) 2014, 2015 Andrew Hawkins
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 us... | (self, event):
"""
"""
self.Destroy()
def main():
"""
When the file is called independently create and display the manager frame.
"""
app = wx.App()
PreferencesFrame(None, style=wx.DEFAULT_FRAME_STYLE)#^wx.RESIZE_BORDER)
app.MainLoop()
if __name__ == '__main__':
... | onClose | identifier_name |
preferences.py | #!/usr/bin/python
"""
Preferences Frame
Copyright (c) 2014, 2015 Andrew Hawkins
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 us... | main() | conditional_block | |
buildsets.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without eve... |
if branch:
q = q.where(ss_tbl.c.branch == branch)
if repository:
q = q.where(ss_tbl.c.repository == repository)
res = conn.execute(q)
return list(reversed([self._row2dict(row)
for row in res.fetchall()]))
... | if complete:
q = q.where(bs_tbl.c.complete != 0)
else:
q = q.where((bs_tbl.c.complete == 0) |
(bs_tbl.c.complete == None)) | conditional_block |
buildsets.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without eve... | transaction.commit()
return (bsid, brids)
return self.db.pool.do(thd)
def completeBuildset(self, bsid, results, complete_at=None,
_reactor=reactor):
if complete_at is not None:
complete_at = datetime2epoch(complete_at)
else:
... |
brids[buildername] = r.inserted_primary_key[0]
| random_line_split |
buildsets.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without eve... |
return self.db.pool.do(thd)
def _row2dict(self, row):
def mkdt(epoch):
if epoch:
return epoch2datetime(epoch)
return BsDict(external_idstring=row.external_idstring,
reason=row.reason, sourcestampsetid=row.sourcestampsetid,
... | bsp_tbl = self.db.model.buildset_properties
q = sa.select(
[bsp_tbl.c.property_name, bsp_tbl.c.property_value],
whereclause=(bsp_tbl.c.buildsetid == buildsetid))
l = []
for row in conn.execute(q):
try:
properties = j... | identifier_body |
buildsets.py | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without eve... | (self, complete=None):
def thd(conn):
bs_tbl = self.db.model.buildsets
q = bs_tbl.select()
if complete is not None:
if complete:
q = q.where(bs_tbl.c.complete != 0)
else:
q = q.where((bs_tbl.c.complete ==... | getBuildsets | identifier_name |
versions.py | import os
import glob
from pathlib import Path
import flask
import yaml
class VersionManager(object):
def __init__(self, versions=None):
self._versions = versions
@property
def versions(self):
if self._versions is None:
version_paths = Path('versions').glob('**/*.yaml')
... | return VersionManager(versions)
def get(self, **kwargs):
if kwargs:
versions = self.filter(**kwargs)
return versions.get()
if len(self.versions) == 1:
return self.versions[0]
raise flask.abort(404)
class Version(object):
objects = Version... | versions = self.versions
if version:
versions = [v for v in versions if v.version == version]
if pre_release is True:
versions = [v for v in versions if v.is_pre_release]
if pre_release is False:
versions = [v for v in versions if not v.is_pre_release]
... | identifier_body |
versions.py | import os
import glob
from pathlib import Path
import flask
import yaml
class VersionManager(object):
def __init__(self, versions=None):
self._versions = versions
@property
def versions(self):
if self._versions is None:
version_paths = Path('versions').glob('**/*.yaml')
... | (cls, path):
version = os.path.splitext(os.path.basename(path))[0]
with open(path) as fp:
content = yaml.safe_load(fp.read())
binaries = {}
for (key, value) in content['binaries'].items():
# convert between old and new schema
if isinst... | fromfile | identifier_name |
versions.py | import os
import glob
from pathlib import Path
import flask
import yaml
class VersionManager(object):
def __init__(self, versions=None):
self._versions = versions
@property
def versions(self):
if self._versions is None:
version_paths = Path('versions').glob('**/*.yaml')
... |
return False
@property
def is_pre_release(self):
return '-' in self.version
@property
def is_snapshot(self):
return 'SNAPSHOT' in self.version
def supports_platform(self, platform):
"""
Returns if the version has a binary release for the given platform.
... | if isinstance(other, Version):
return self.version == other.version and self.binaries == other.binaries | random_line_split |
versions.py | import os
import glob
from pathlib import Path
import flask
import yaml
class VersionManager(object):
def __init__(self, versions=None):
self._versions = versions
@property
def versions(self):
if self._versions is None:
version_paths = Path('versions').glob('**/*.yaml')
... |
if snapshots is False:
versions = [v for v in versions if not v.is_snapshot]
if platform:
versions = [v for v in versions if v.supports_platform(platform)]
return VersionManager(versions)
def get(self, **kwargs):
if kwargs:
versions = self.fil... | versions = [v for v in versions if v.is_snapshot] | conditional_block |
freq_handler.rs | use compression::BlockDecoder;
use common::VInt;
use common::BinarySerializable;
use compression::{CompositeDecoder, VIntDecoder};
use postings::SegmentPostingsOption;
use compression::NUM_DOCS_PER_BLOCK;
/// `FreqHandler` is in charge of decompressing
/// frequencies and/or positions.
pub struct FreqHandler {
f... | }
/// Decompresses an incomplete frequency block
pub fn read_freq_vint(&mut self, data: &[u8], num_els: usize) {
match self.option {
SegmentPostingsOption::NoFreq => {}
SegmentPostingsOption::Freq => {
self.freq_decoder.uncompress_vint_unsorted(data, num_els)... | remaining
}
} | random_line_split |
freq_handler.rs | use compression::BlockDecoder;
use common::VInt;
use common::BinarySerializable;
use compression::{CompositeDecoder, VIntDecoder};
use postings::SegmentPostingsOption;
use compression::NUM_DOCS_PER_BLOCK;
/// `FreqHandler` is in charge of decompressing
/// frequencies and/or positions.
pub struct FreqHandler {
f... | (position_data: &[u8]) -> FreqHandler {
let positions = read_positions(position_data);
FreqHandler {
freq_decoder: BlockDecoder::new(),
positions: positions,
option: SegmentPostingsOption::FreqAndPositions,
positions_offsets: [0; NUM_DOCS_PER_BLOCK + 1],
... | new_with_freq_and_position | identifier_name |
freq_handler.rs | use compression::BlockDecoder;
use common::VInt;
use common::BinarySerializable;
use compression::{CompositeDecoder, VIntDecoder};
use postings::SegmentPostingsOption;
use compression::NUM_DOCS_PER_BLOCK;
/// `FreqHandler` is in charge of decompressing
/// frequencies and/or positions.
pub struct FreqHandler {
f... |
}
}
}
| {
self.freq_decoder.uncompress_vint_unsorted(data, num_els);
self.fill_positions_offset();
} | conditional_block |
freq_handler.rs | use compression::BlockDecoder;
use common::VInt;
use common::BinarySerializable;
use compression::{CompositeDecoder, VIntDecoder};
use postings::SegmentPostingsOption;
use compression::NUM_DOCS_PER_BLOCK;
/// `FreqHandler` is in charge of decompressing
/// frequencies and/or positions.
pub struct FreqHandler {
f... |
fn fill_positions_offset(&mut self) {
let mut cur_position: usize = self.positions_offsets[NUM_DOCS_PER_BLOCK];
let mut i: usize = 0;
self.positions_offsets[i] = cur_position;
let mut last_cur_position = cur_position;
for &doc_freq in self.freq_decoder.output_array() {
... | {
let positions = read_positions(position_data);
FreqHandler {
freq_decoder: BlockDecoder::new(),
positions: positions,
option: SegmentPostingsOption::FreqAndPositions,
positions_offsets: [0; NUM_DOCS_PER_BLOCK + 1],
}
} | identifier_body |
dstr-meth-obj-ptrn-prop-ary-trailing-comma.js | // This file was procedurally generated from the following sources:
// - src/dstr-binding/obj-ptrn-prop-ary-trailing-comma.case
// - src/dstr-binding/default/cls-decl-meth.template
/*---
description: Trailing comma is allowed following BindingPropertyList (class expression method)
esid: sec-runtime-semantics-bindingcla... | {
method({ x: [y], }) {
assert.sameValue(y,45);
callCount = callCount + 1;
}
};
new C().method({ x: [45] });
assert.sameValue(callCount, 1, 'method invoked exactly once');
| C | identifier_name |
dstr-meth-obj-ptrn-prop-ary-trailing-comma.js | // This file was procedurally generated from the following sources:
// - src/dstr-binding/obj-ptrn-prop-ary-trailing-comma.case
// - src/dstr-binding/default/cls-decl-meth.template
/*---
description: Trailing comma is allowed following BindingPropertyList (class expression method)
esid: sec-runtime-semantics-bindingcla... | var callCount = 0;
class C {
method({ x: [y], }) {
assert.sameValue(y,45);
callCount = callCount + 1;
}
};
new C().method({ x: [45] });
assert.sameValue(callCount, 1, 'method invoked exactly once'); | { BindingPropertyList[?Yield] , }
---*/
| random_line_split |
dstr-meth-obj-ptrn-prop-ary-trailing-comma.js | // This file was procedurally generated from the following sources:
// - src/dstr-binding/obj-ptrn-prop-ary-trailing-comma.case
// - src/dstr-binding/default/cls-decl-meth.template
/*---
description: Trailing comma is allowed following BindingPropertyList (class expression method)
esid: sec-runtime-semantics-bindingcla... |
};
new C().method({ x: [45] });
assert.sameValue(callCount, 1, 'method invoked exactly once');
| {
assert.sameValue(y,45);
callCount = callCount + 1;
} | identifier_body |
partial.rs | // Copyright 2014 Pierre Talbot (IRCAM)
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to... |
pub fn map<U, F: FnOnce(T) -> U>(self, f: F) -> Partial<U> {
match self {
Value(x) => Value(f(x)),
Fake(x) => Fake(f(x)),
Nothing => Nothing
}
}
pub fn and_then<U, F: FnOnce(T) -> Partial<U>>(self, f: F) -> Partial<U> {
match self {
Value(x) => f(x),
Fake(x) => match f... | {
match self {
Value(x) => x,
Fake(_) => panic!("called `Partial::unwrap()` on a `Fake` value"),
Nothing => panic!("called `Partial::unwrap()` on a `Nothing` value")
}
} | identifier_body |
partial.rs | // Copyright 2014 Pierre Talbot (IRCAM)
| // Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed unde... | random_line_split | |
partial.rs | // Copyright 2014 Pierre Talbot (IRCAM)
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to... | <U, F: FnOnce(T) -> Partial<U>>(self, f: F) -> Partial<U> {
match self {
Value(x) => f(x),
Fake(x) => match f(x) {
Value(x) => Fake(x),
x => x
},
Nothing => Nothing
}
}
}
#[test]
fn partial() {
assert_eq!(Value(9i32).unwrap(), 9i32);
assert_eq!(Value(9i32).map(|i|i... | and_then | identifier_name |
mod.rs | use co_slog;
pub fn | () {
let log = co_slog::logger();
let server = log.new(o!("host" => "localhost", "port" => "8080"));
let _log = co_slog::set_logger(server);
info!("starting");
info!("listening");
let log = co_slog::logger();
join!(
{
let peer1 = log.clone().new(
o!("p... | simulate_server | identifier_name |
mod.rs | use co_slog;
pub fn simulate_server() | debug!("disconnected");
},
{
let peer2 = log.clone().new(
o!("peer_addr" => "82.9.9.9", "port" => "42381"),
);
let _log = co_slog::set_logger(peer2);
debug!("connected");
debug!("message received"; "length" => 2);
... | {
let log = co_slog::logger();
let server = log.new(o!("host" => "localhost", "port" => "8080"));
let _log = co_slog::set_logger(server);
info!("starting");
info!("listening");
let log = co_slog::logger();
join!(
{
let peer1 = log.clone().new(
o!("peer... | identifier_body |
mod.rs | use co_slog;
pub fn simulate_server() {
let log = co_slog::logger();
let server = log.new(o!("host" => "localhost", "port" => "8080"));
let _log = co_slog::set_logger(server);
info!("starting");
info!("listening");
let log = co_slog::logger();
join!(
{
let peer1 = lo... | );
crit!("internal error");
info!("exit");
} | random_line_split | |
tooltip-20cd2b9b.js | import { B as Behavior, J as isTouch, f as fixPosition } from './index-c8e86d4d.js';
class TooltipBehavior extends Behavior {
| () {
const { host } = this;
const parent = this.parent = this.host.parentNode;
if (parent && parent.nuElement && !parent.hasAttribute('describedby')) {
parent.setAttribute('describedby', this.nuId);
}
let hover = false;
let focus = false;
host.hidden = true;
this.setMod('toolti... | connected | identifier_name |
tooltip-20cd2b9b.js | import { B as Behavior, J as isTouch, f as fixPosition } from './index-c8e86d4d.js';
class TooltipBehavior extends Behavior {
connected() {
const { host } = this;
const parent = this.parent = this.host.parentNode;
if (parent && parent.nuElement && !parent.hasAttribute('describedby')) {
parent.setA... | disconnected() {
const removeListeners = this.removeListeners;
if (removeListeners) {
removeListeners();
}
}
}
export default TooltipBehavior; | random_line_split | |
mutability-inherits-through-fixed-length-vec.rs | // 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
// <LICENSE-MIT or ... | () {
let mut ints = [0; 32];
for i in &mut ints { *i += 22; }
for i in &ints { assert_eq!(*i, 22); }
}
pub fn main() {
test1();
test2();
}
| test2 | identifier_name |
mutability-inherits-through-fixed-length-vec.rs | // 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
// <LICENSE-MIT or ... |
fn test2() {
let mut ints = [0; 32];
for i in &mut ints { *i += 22; }
for i in &ints { assert_eq!(*i, 22); }
}
pub fn main() {
test1();
test2();
}
| {
let mut ints = [0; 32];
ints[0] += 1;
assert_eq!(ints[0], 1);
} | identifier_body |
mutability-inherits-through-fixed-length-vec.rs | // 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
// <LICENSE-MIT or ... | test1();
test2();
} |
pub fn main() { | random_line_split |
invite_coteachers_modal.tsx | import * as React from 'react'
import * as moment from 'moment'
import { Input, DataTable, } from '../../../Shared/index'
import { requestPost, } from '../../../../modules/request/index.js';
interface InviteCoteachersModalProps {
close: () => void;
onSuccess: (event) => void;
classrooms: Array<any>;
classroom... |
uncheckAllRows() {
this.setState({ selectedClassroomIds: [] })
}
inviteCoteachers() {
const { onSuccess, close, } = this.props
const { email, selectedClassroomIds } = this.state
const dataForInvite = { classroom_ids: selectedClassroomIds, invitee_email: email }
requestPost('/invitations/cre... | {
const { classrooms } = this.props
const newSelectedClassroomIds = classrooms.map(classroom => classroom.id)
this.setState({ selectedClassroomIds: newSelectedClassroomIds })
} | identifier_body |
invite_coteachers_modal.tsx | import * as React from 'react'
import * as moment from 'moment'
import { Input, DataTable, } from '../../../Shared/index'
import { requestPost, } from '../../../../modules/request/index.js';
interface InviteCoteachersModalProps {
close: () => void;
onSuccess: (event) => void;
classrooms: Array<any>;
classroom... | () {
const { classrooms } = this.props
const newSelectedClassroomIds = classrooms.map(classroom => classroom.id)
this.setState({ selectedClassroomIds: newSelectedClassroomIds })
}
uncheckAllRows() {
this.setState({ selectedClassroomIds: [] })
}
inviteCoteachers() {
const { onSuccess, close... | checkAllRows | identifier_name |
invite_coteachers_modal.tsx | import * as React from 'react'
import * as moment from 'moment'
import { Input, DataTable, } from '../../../Shared/index'
import { requestPost, } from '../../../../modules/request/index.js';
interface InviteCoteachersModalProps {
close: () => void;
onSuccess: (event) => void;
classrooms: Array<any>;
classroom... |
return buttonClass;
}
handleEmailChange(event) {
this.setState({ email: event.target.value })
}
checkRow(id) {
const { selectedClassroomIds } = this.state
const newSelectedClassroomIds = selectedClassroomIds.concat(id)
this.setState({ selectedClassroomIds: newSelectedClassroomIds })
}
... | {
buttonClass += ' disabled';
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.