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 |
|---|---|---|---|---|
main.rs | // Copyright 2015 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 ... | {
// The AST of `exported_generic` stored in crate_with_invalid_spans's
// metadata should contain an invalid span where span.lo() > span.hi().
// Let's make sure the compiler doesn't crash when encountering this.
let _ = crate_with_invalid_spans::exported_generic(32u32, 7u32);
} | identifier_body | |
20require.js | /*xlib.20require 资源加载函数*/
(function(x){
x.define=function(id,deps,result){/*定义一个资源 id是可选项 rs可以是data也可以是函数 资源的加载*/
for(var i=0;i<rsList.length;i++){
var rs=rsList[i];
if(rs.id==id){/*如果id一致,且对象处于load状态*/
rs.state="complete";/*加载完毕*/ | rs.callBack(result);
break;
}
}
}
/*每个rs拥有src属性,加载状态属性,加载结果*/
var seed_id=1;
x.require=function(id,src,callBack,flag){/*按顺序加载资源 异步执行 执行完调用回调函数 flag是调试信息是否输出*/
/*每次require都会产生一条记录 相当于每次require只能执行一个加载请求*/
var obj={};
if(id==null) id=seed_id++;
obj.id=id; /*关联id*/
obj.src=src;
obj.state=... | random_line_split | |
20require.js | /*xlib.20require 资源加载函数*/
(function(x){
x.define=function(id,deps,result){/*定义一个资源 id是可选项 rs可以是data也可以是函数 资源的加载*/
for(var i=0;i<rsList.length;i++){
var rs=rsList[i];
if(rs.id==id){/*如果id一致,且对象处于load状态*/
rs.state="complete";/*加载完毕*/
rs.callBack(result);
break;
}
}
}
/*每个rs拥有src属性,加载状态属性... | conditional_block | ||
vga.rs | use extra::prelude::*;
use cpu;
use cpu::io;
#[packed]
pub struct | {
char: u8,
attr: u8,
}
static SCREEN_ROWS: uint = 25;
static SCREEN_COLS: uint = 80;
static SCREEN_SIZE: uint = SCREEN_ROWS*SCREEN_COLS;
type screen_buf = [character, ..SCREEN_SIZE];
static screen: *mut screen_buf = 0xB8000 as *mut screen_buf;
static mut cur_pos: uint = 0;
pub fn init() {
unsafe {
... | character | identifier_name |
vga.rs | use extra::prelude::*;
use cpu;
use cpu::io;
#[packed]
pub struct character {
char: u8,
attr: u8,
}
static SCREEN_ROWS: uint = 25;
static SCREEN_COLS: uint = 80;
static SCREEN_SIZE: uint = SCREEN_ROWS*SCREEN_COLS;
type screen_buf = [character, ..SCREEN_SIZE];
static screen: *mut screen_buf = 0xB8000 as *mut s... | }
#[inline]
unsafe fn mem_ptr_of(row: uint, col: uint) -> uint {
screen as uint +
row * SCREEN_COLS * mem::size_of::<character>() +
col * mem::size_of::<character>()
} | unsafe fn cursor_to(pos: uint) {
io::outb(0x3D4, 14);
io::outb(0x3D5, (pos >> 8) as u8);
io::outb(0x3D4, 15);
io::outb(0x3D5, pos as u8); | random_line_split |
vga.rs | use extra::prelude::*;
use cpu;
use cpu::io;
#[packed]
pub struct character {
char: u8,
attr: u8,
}
static SCREEN_ROWS: uint = 25;
static SCREEN_COLS: uint = 80;
static SCREEN_SIZE: uint = SCREEN_ROWS*SCREEN_COLS;
type screen_buf = [character, ..SCREEN_SIZE];
static screen: *mut screen_buf = 0xB8000 as *mut s... |
pub fn puts(string: &str, attr: term::color::Color) {
stdio::puts(string, attr, putc, new_line);
}
pub fn putc(c: char, attr: term::color::Color) {
unsafe {
put_char(cur_pos, character{char: c as u8, attr: attr as u8});
cursor_move(1);
}
}
pub fn new_line() {
unsafe {
cursor_... | {
unsafe {
cur_pos = cursor_pos();
}
} | identifier_body |
vga.rs | use extra::prelude::*;
use cpu;
use cpu::io;
#[packed]
pub struct character {
char: u8,
attr: u8,
}
static SCREEN_ROWS: uint = 25;
static SCREEN_COLS: uint = 80;
static SCREEN_SIZE: uint = SCREEN_ROWS*SCREEN_COLS;
type screen_buf = [character, ..SCREEN_SIZE];
static screen: *mut screen_buf = 0xB8000 as *mut s... |
cursor_to(cur_pos);
}
#[inline]
unsafe fn put_char(pos: uint, c: character) {
(*screen)[pos] = c;
}
#[inline]
unsafe fn cursor_pos() -> uint {
let mut pos: uint;
io::outb(0x3D4, 14);
pos = (io::inb(0x3D5) as uint) << 8;
io::outb(0x3D4, 15);
pos |= io::inb(0x3D5) as uint;
pos
}
#[inli... | {
cpu::memmove(mem_ptr_of(0, 0), mem_ptr_of(1, 0),
(SCREEN_SIZE - SCREEN_COLS) * mem::size_of::<character>());
let mut i = SCREEN_SIZE - SCREEN_COLS;
while i < SCREEN_SIZE {
put_char(i, character{char: ' ' as u8, attr: term::color::BLACK as u8});
i += 1;
... | conditional_block |
debug.py | license: BSD, see LICENSE for more details.
"""
import sys
import traceback
from jinja2.utils import CodeType, missing, internal_code
from jinja2.exceptions import TemplateSyntaxError
# how does the raise helper look like?
try:
exec "raise TypeError, 'foo'"
except SyntaxError:
raise_helper = 'raise __jinja_ex... |
class _Traceback(_PyObject):
pass
_Traceback._fields_ = [
('tb_next', ctypes.POINTER(_Traceback)),
('tb_frame', ctypes.POINTER(_PyObject)),
('tb_lasti', ctypes.c_int),
('tb_lineno', ctypes.c_int)
]
def tb_set_next(tb, next):
"""Set the tb_next attribute... | class _PyObject(ctypes.Structure):
pass
_PyObject._fields_ = [
('_ob_next', ctypes.POINTER(_PyObject)),
('_ob_prev', ctypes.POINTER(_PyObject)),
('ob_refcnt', _Py_ssize_t),
('ob_type', ctypes.POINTER(_PyObject))
] | conditional_block |
debug.py | license: BSD, see LICENSE for more details.
"""
import sys
import traceback
from jinja2.utils import CodeType, missing, internal_code
from jinja2.exceptions import TemplateSyntaxError
# how does the raise helper look like?
try:
exec "raise TypeError, 'foo'"
except SyntaxError:
raise_helper = 'raise __jinja_ex... | (_PyObject):
pass
_Traceback._fields_ = [
('tb_next', ctypes.POINTER(_Traceback)),
('tb_frame', ctypes.POINTER(_PyObject)),
('tb_lasti', ctypes.c_int),
('tb_lineno', ctypes.c_int)
]
def tb_set_next(tb, next):
"""Set the tb_next attribute of a traceback object... | _Traceback | identifier_name |
debug.py | license: BSD, see LICENSE for more details.
"""
import sys
import traceback
from jinja2.utils import CodeType, missing, internal_code
from jinja2.exceptions import TemplateSyntaxError
# how does the raise helper look like?
try:
exec "raise TypeError, 'foo'"
except SyntaxError:
raise_helper = 'raise __jinja_ex... |
def translate_exception(exc_info, initial_skip=0):
"""If passed an exc_info it will automatically rewrite the exceptions
all the way down to the correct line numbers and frames.
"""
tb = exc_info[2]
frames = []
# skip some internal frames if wanted
for x in xrange(initial_skip):
... | """Rewrites a syntax error to please traceback systems."""
error.source = source
error.translated = True
exc_info = (error.__class__, error, None)
filename = error.filename
if filename is None:
filename = '<unknown>'
return fake_exc_info(exc_info, filename, error.lineno) | identifier_body |
debug.py | :license: BSD, see LICENSE for more details.
"""
import sys
import traceback
from jinja2.utils import CodeType, missing, internal_code
from jinja2.exceptions import TemplateSyntaxError
# how does the raise helper look like?
try:
exec "raise TypeError, 'foo'"
except SyntaxError:
raise_helper = 'raise __jinja_... |
tb_next = property(_get_tb_next, _set_tb_next)
del _get_tb_next, _set_tb_next
@property
def is_jinja_frame(self):
return '__jinja_template__' in self.tb.tb_frame.f_globals
def __getattr__(self, name):
return getattr(self.tb, name)
class ProcessedTraceback(object):
"""Holds a... | tb_set_next(self.tb, next and next.tb or None)
self._tb_next = next
def _get_tb_next(self):
return self._tb_next | random_line_split |
test.js |
function main() {
var N = 10000;
var lines = generateLines(N);
//timeCanvas2D(lines, N);
timeBatchDraw(lines, N);
}
function generateLines(N) {
var lines = new Array(N);
let canvas = document.getElementById("canvas");
let w = canvas.width;
let h = canvas.height;
// Create funky ... | (lines, N) {
let canvas = document.getElementById("canvas");
let params = {
maxLines: N,
clearColor: {r: 1, g: 1, b: 1, a: 1}
};
let batchDrawer = new BatchDrawer(canvas, params);
if (batchDrawer.error != null) {
console.log(batchDrawer.error);
return;
}
cons... | timeBatchDraw | identifier_name |
test.js |
function main() {
var N = 10000;
var lines = generateLines(N);
//timeCanvas2D(lines, N);
timeBatchDraw(lines, N);
}
function generateLines(N) {
var lines = new Array(N);
let canvas = document.getElementById("canvas");
let w = canvas.width;
let h = canvas.height;
// Create funky ... |
function timeCanvas2D(lines, N) {
let canvas = document.getElementById("canvas");
let ctx = canvas.getContext("2d");
ctx.lineWidth = 0.01;
ctx.strokeStyle = '#ffa500';
ctx.fillStyle="#FFFFFF";
console.time("Canvas2D");
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (i=0; i<N;... | {
let canvas = document.getElementById("canvas");
let params = {
maxLines: N,
clearColor: {r: 1, g: 1, b: 1, a: 1}
};
let batchDrawer = new BatchDrawer(canvas, params);
if (batchDrawer.error != null) {
console.log(batchDrawer.error);
return;
}
console.time("B... | identifier_body |
test.js |
function main() {
var N = 10000;
var lines = generateLines(N);
//timeCanvas2D(lines, N);
timeBatchDraw(lines, N);
}
function generateLines(N) {
var lines = new Array(N);
let canvas = document.getElementById("canvas");
let w = canvas.width;
let h = canvas.height;
// Create funky ... |
//console.log(lines);
return lines;
}
function timeBatchDraw(lines, N) {
let canvas = document.getElementById("canvas");
let params = {
maxLines: N,
clearColor: {r: 1, g: 1, b: 1, a: 1}
};
let batchDrawer = new BatchDrawer(canvas, params);
if (batchDrawer.error != null) {... | {
lines[i] = {
fromX: (1.3*i/N) * w,
fromY: 0.5/(2*(i/N) + 1) * h,
toX: (0.1*i-1)/(N - i) * w,
toY: (0.3*N)/(5*(i*i)/N) * 0.5 * h
};
} | conditional_block |
test.js | function main() {
var N = 10000;
var lines = generateLines(N);
//timeCanvas2D(lines, N);
timeBatchDraw(lines, N);
}
function generateLines(N) {
var lines = new Array(N);
let canvas = document.getElementById("canvas");
let w = canvas.width;
let h = canvas.height;
// Create funky l... | let params = {
maxLines: N,
clearColor: {r: 1, g: 1, b: 1, a: 1}
};
let batchDrawer = new BatchDrawer(canvas, params);
if (batchDrawer.error != null) {
console.log(batchDrawer.error);
return;
}
console.time("BatchDraw");
for (i=0; i<N; i++) {
batchDra... |
function timeBatchDraw(lines, N) {
let canvas = document.getElementById("canvas"); | random_line_split |
example-pane-trigger.component.ts | import { Component, ChangeDetectionStrategy, ViewChild, AfterViewInit } from '@angular/core';
import { DataService, Human } from '../data.service';
import { Observable } from 'rxjs';
import { Command, GridComponent, PaneComponent } from 'ng2-qgrid';
const EXAMPLE_TAGS = [
'pane-trigger',
'Pane for selected row can b... |
});
}
}
| {
this.selectedRow = e.state.items[0];
this.openPane.canExecuteCheck.next();
} | conditional_block |
example-pane-trigger.component.ts | import { Component, ChangeDetectionStrategy, ViewChild, AfterViewInit } from '@angular/core';
import { DataService, Human } from '../data.service';
import { Observable } from 'rxjs';
import { Command, GridComponent, PaneComponent } from 'ng2-qgrid';
const EXAMPLE_TAGS = [
'pane-trigger',
'Pane for selected row can b... | this.selectedRow = e.state.items[0];
this.openPane.canExecuteCheck.next();
}
});
}
} |
ngAfterViewInit() {
const { model } = this.grid;
model.selectionChanged.watch(e => {
if (e.hasChanges('items')) { | random_line_split |
example-pane-trigger.component.ts | import { Component, ChangeDetectionStrategy, ViewChild, AfterViewInit } from '@angular/core';
import { DataService, Human } from '../data.service';
import { Observable } from 'rxjs';
import { Command, GridComponent, PaneComponent } from 'ng2-qgrid';
const EXAMPLE_TAGS = [
'pane-trigger',
'Pane for selected row can b... |
}
| {
const { model } = this.grid;
model.selectionChanged.watch(e => {
if (e.hasChanges('items')) {
this.selectedRow = e.state.items[0];
this.openPane.canExecuteCheck.next();
}
});
} | identifier_body |
example-pane-trigger.component.ts | import { Component, ChangeDetectionStrategy, ViewChild, AfterViewInit } from '@angular/core';
import { DataService, Human } from '../data.service';
import { Observable } from 'rxjs';
import { Command, GridComponent, PaneComponent } from 'ng2-qgrid';
const EXAMPLE_TAGS = [
'pane-trigger',
'Pane for selected row can b... | () {
const { model } = this.grid;
model.selectionChanged.watch(e => {
if (e.hasChanges('items')) {
this.selectedRow = e.state.items[0];
this.openPane.canExecuteCheck.next();
}
});
}
}
| ngAfterViewInit | identifier_name |
lib.rs | pub fn score(word: &str) -> usize | {
// lowercase for case insensitivity
// use map to convert to numbers
// sum them
word.to_lowercase()
.chars()
.map(|c| match c {
'a' | 'e' | 'i' | 'o' | 'u' | 'l' | 'n' | 'r' | 's' | 't' => 1,
'd' | 'g' => 2,
'b' | 'c' | 'm' | 'p' => 3,
'... | identifier_body | |
lib.rs | pub fn | (word: &str) -> usize {
// lowercase for case insensitivity
// use map to convert to numbers
// sum them
word.to_lowercase()
.chars()
.map(|c| match c {
'a' | 'e' | 'i' | 'o' | 'u' | 'l' | 'n' | 'r' | 's' | 't' => 1,
'd' | 'g' => 2,
'b' | 'c' | 'm' | '... | score | identifier_name |
lib.rs | pub fn score(word: &str) -> usize {
// lowercase for case insensitivity
// use map to convert to numbers | 'd' | 'g' => 2,
'b' | 'c' | 'm' | 'p' => 3,
'f' | 'h' | 'v' | 'w' | 'y' => 4,
'k' => 5,
'j' | 'x' => 8,
'q' | 'z' => 10,
_ => 0,
})
.fold(0, |accu, x| accu + x)
} | // sum them
word.to_lowercase()
.chars()
.map(|c| match c {
'a' | 'e' | 'i' | 'o' | 'u' | 'l' | 'n' | 'r' | 's' | 't' => 1, | random_line_split |
hash_matcher.py | import hashlib
import re
import os
import pickle
from functools import partial
from externals.lib.misc import file_scan, update_dict
import logging
log = logging.getLogger(__name__)
VERSION = "0.0"
# Constants --------------------------------------------------------------------
DEFAULT_DESTINATION = './files/'
DEF... | if __name__ == "__main__":
main() | random_line_split | |
hash_matcher.py | import hashlib
import re
import os
import pickle
from functools import partial
from externals.lib.misc import file_scan, update_dict
import logging
log = logging.getLogger(__name__)
VERSION = "0.0"
# Constants --------------------------------------------------------------------
DEFAULT_DESTINATION = './files/'
DEF... |
# ------------------------------------------------------------------------------
def move_files():
pass
# Command Line -----------------------------------------------------------------
def get_args():
import argparse
parser = argparse.ArgumentParser(
description="""
Find the duplicate... | f = source_files[key]
log.debug(f.file)
if not dry_run:
try:
os.symlink(f.absolute, os.path.join(destination_folder, f.file))
except OSError:
log.info('unable to symlink {0}'.format(f.file)) | conditional_block |
hash_matcher.py | import hashlib
import re
import os
import pickle
from functools import partial
from externals.lib.misc import file_scan, update_dict
import logging
log = logging.getLogger(__name__)
VERSION = "0.0"
# Constants --------------------------------------------------------------------
DEFAULT_DESTINATION = './files/'
DEF... |
if __name__ == "__main__":
main()
| args = get_args()
logging.basicConfig(level=logging.DEBUG if args['verbose'] else logging.INFO)
try:
with open(args['cache_filename'], 'rb') as f:
data = pickle.load(f)
except IOError:
with open(args['cache_filename'], 'wb') as f:
data = hash_source_dest(**args)
... | identifier_body |
hash_matcher.py | import hashlib
import re
import os
import pickle
from functools import partial
from externals.lib.misc import file_scan, update_dict
import logging
log = logging.getLogger(__name__)
VERSION = "0.0"
# Constants --------------------------------------------------------------------
DEFAULT_DESTINATION = './files/'
DEF... | ():
import argparse
parser = argparse.ArgumentParser(
description="""
Find the duplicates
""",
epilog=""" """
)
# Folders
parser.add_argument('-d', '--destination_folder', action='store', help='', default=DEFAULT_DESTINATION)
parser.add_argument('-s', '--source_f... | get_args | identifier_name |
parser.py | from parso.python import tree
from parso.python.token import PythonTokenTypes
from parso.parser import BaseParser
NAME = PythonTokenTypes.NAME
INDENT = PythonTokenTypes.INDENT
DEDENT = PythonTokenTypes.DEDENT
class Parser(BaseParser):
"""
This class is used to parse a Python file, it then divides them into ... |
return super().parse(tokens)
def convert_node(self, nonterminal, children):
"""
Convert raw node information to a PythonBaseNode instance.
This is passed to the parser driver which calls it whenever a reduction of a
grammar rule produces a new complete node, so that the t... | if self._start_nonterminal != 'file_input':
raise NotImplementedError
tokens = self._recovery_tokenize(tokens) | conditional_block |
parser.py | from parso.python import tree
from parso.python.token import PythonTokenTypes
from parso.parser import BaseParser
NAME = PythonTokenTypes.NAME
INDENT = PythonTokenTypes.INDENT
DEDENT = PythonTokenTypes.DEDENT
class Parser(BaseParser):
"""
This class is used to parse a Python file, it then divides them into ... | self._indent_counter -= 1
continue
self._indent_counter -= 1
elif typ == INDENT:
self._indent_counter += 1
yield token | if o and o[-1] == self._indent_counter:
o.pop() | random_line_split |
parser.py | from parso.python import tree
from parso.python.token import PythonTokenTypes
from parso.parser import BaseParser
NAME = PythonTokenTypes.NAME
INDENT = PythonTokenTypes.INDENT
DEDENT = PythonTokenTypes.DEDENT
class Parser(BaseParser):
"""
This class is used to parse a Python file, it then divides them into ... | (self, type, value, prefix, start_pos):
# print('leaf', repr(value), token.tok_name[type])
if type == NAME:
if value in self._pgen_grammar.reserved_syntax_strings:
return tree.Keyword(value, start_pos, prefix)
else:
return tree.Name(value, start_po... | convert_leaf | identifier_name |
parser.py | from parso.python import tree
from parso.python.token import PythonTokenTypes
from parso.parser import BaseParser
NAME = PythonTokenTypes.NAME
INDENT = PythonTokenTypes.INDENT
DEDENT = PythonTokenTypes.DEDENT
class Parser(BaseParser):
"""
This class is used to parse a Python file, it then divides them into ... |
until_index = current_suite(self.stack)
if self._stack_removal(until_index + 1):
self._add_token(token)
else:
typ, value, start_pos, prefix = token
if typ == INDENT:
# For every deleted INDENT we have to delete a DEDENT as well.
... | for until_index, stack_node in reversed(list(enumerate(stack))):
# `suite` can sometimes be only simple_stmt, not stmt.
if stack_node.nonterminal == 'file_input':
break
elif stack_node.nonterminal == 'suite':
# In the case where we ... | identifier_body |
advance.rs | ;
use security::SecurityManager;
use tikv_util::timer::SteadyTimer;
use tikv_util::worker::Scheduler;
use tokio::runtime::{Builder, Runtime};
use txn_types::TimeStamp;
use crate::endpoint::Task;
use crate::errors::Result;
use crate::metrics::{CHECK_LEADER_REQ_ITEM_COUNT_HISTOGRAM, CHECK_LEADER_REQ_SIZE_HISTOGRAM};
co... | .filter_map(|resp| match resp {
Ok(resp) => Some(resp),
Err(e) => {
debug!("resolved-ts check leader error"; "err" =>?e);
None
}
})
.map(|(store_id, resp)| {
resp.regions
... | });
let resps = futures::future::join_all(stores).await;
resps
.into_iter() | random_line_split |
advance.rs | use security::SecurityManager;
use tikv_util::timer::SteadyTimer;
use tikv_util::worker::Scheduler;
use tokio::runtime::{Builder, Runtime};
use txn_types::TimeStamp;
use crate::endpoint::Task;
use crate::errors::Result;
use crate::metrics::{CHECK_LEADER_REQ_ITEM_COUNT_HISTOGRAM, CHECK_LEADER_REQ_SIZE_HISTOGRAM};
cons... |
}
impl<E: KvEngine> AdvanceTsWorker<E> {
pub fn advance_ts_for_regions(&self, regions: Vec<u64>) {
let pd_client = self.pd_client.clone();
let scheduler = self.scheduler.clone();
let cm: ConcurrencyManager = self.concurrency_manager.clone();
let env = self.env.clone();
let ... | {
let worker = Builder::new_multi_thread()
.thread_name("advance-ts")
.worker_threads(1)
.enable_time()
.build()
.unwrap();
Self {
env,
security_mgr,
scheduler,
pd_client,
worker,
... | identifier_body |
advance.rs | ;
use security::SecurityManager;
use tikv_util::timer::SteadyTimer;
use tikv_util::worker::Scheduler;
use tokio::runtime::{Builder, Runtime};
use txn_types::TimeStamp;
use crate::endpoint::Task;
use crate::errors::Result;
use crate::metrics::{CHECK_LEADER_REQ_ITEM_COUNT_HISTOGRAM, CHECK_LEADER_REQ_SIZE_HISTOGRAM};
co... | <E: KvEngine> {
store_meta: Arc<Mutex<StoreMeta>>,
region_read_progress: RegionReadProgressRegistry,
pd_client: Arc<dyn PdClient>,
timer: SteadyTimer,
worker: Runtime,
scheduler: Scheduler<Task<E::Snapshot>>,
/// The concurrency manager for transactions. It's needed for CDC to check locks wh... | AdvanceTsWorker | identifier_name |
25-status.js | /**
* Copyright JS Foundation and other contributors, http://js.foundation
*
* 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 r... | * limitations under the License.
**/
module.exports = function(RED) {
"use strict";
function StatusNode(n) {
RED.nodes.createNode(this,n);
var node = this;
this.scope = n.scope;
this.on("input", function(msg) {
this.send(msg);
});
}
RED.nodes.regi... | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and | random_line_split |
25-status.js | /**
* Copyright JS Foundation and other contributors, http://js.foundation
*
* 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 r... | (n) {
RED.nodes.createNode(this,n);
var node = this;
this.scope = n.scope;
this.on("input", function(msg) {
this.send(msg);
});
}
RED.nodes.registerType("status",StatusNode);
}
| StatusNode | identifier_name |
25-status.js | /**
* Copyright JS Foundation and other contributors, http://js.foundation
*
* 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 r... |
RED.nodes.registerType("status",StatusNode);
}
| {
RED.nodes.createNode(this,n);
var node = this;
this.scope = n.scope;
this.on("input", function(msg) {
this.send(msg);
});
} | identifier_body |
SWIGOUTDIR.py | #!/usr/bin/env python
#
# Copyright (c) 2001 - 2016 The SCons Foundation
#
# 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... |
"""
Verify that use of the $SWIGOUTDIR variable causes SCons to recognize
that Java files are created in the specified output directory.
"""
import TestSCons
test = TestSCons.TestSCons()
swig = test.where_is('swig')
if not swig:
test.skip_test('Can not find installed "swig", skipping test.\n')
where_java_incl... | # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "test/SWIG/SWIGOUTDIR.py rel_2.5.1:3735:9dc6cee5c168 2016/11/03 14:02:02 bdbaddog" | random_line_split |
SWIGOUTDIR.py | #!/usr/bin/env python
#
# Copyright (c) 2001 - 2016 The SCons Foundation
#
# 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... |
test.write(['SConstruct'], """\
env = Environment(tools = ['default', 'swig'],
CPPPATH=%(where_java_include)s,
)
Java_foo_interface = env.SharedLibrary(
'Java_foo_interface',
'Java_foo_interface.i',
SWIGOUTDIR = 'java/build dir',
SWIGFLAGS = '-c++ -j... | test.skip_test('Can not find installed Java include files, skipping test.\n') | conditional_block |
break-points.spec.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
*/
// RxJS Operators used by the classes...
import 'rxjs/add/operator/filter';
import 'rxjs/add/operator/map';
import... | })));
it('has the standard breakpoints', () => {
expect(breakPoints.length).toEqual(DEFAULT_BREAKPOINTS.length);
expect(breakPoints[0].alias).toEqual('xs');
expect(breakPoints[breakPoints.length - 1].alias).toEqual('xl');
});
});
describe('with custom configuration', () => {
let ... | });
});
beforeEach(async(inject([BREAKPOINTS], (_breakPoints_) => {
breakPoints = _breakPoints_; | random_line_split |
conftest.py | import json
import os
from textwrap import dedent
import boto3
import moto
import pytest
from moto.ec2 import ec2_backend
from moto.ec2 import utils as ec2_utils
from ecs_deplojo.connection import Connection
from ecs_deplojo.task_definitions import TaskDefinition
BASE_DIR = os.path.dirname(os.path.abspath(__file__))... | ():
path = os.path.join(BASE_DIR, "files/default_config.yml")
with open(path, "r") as fh:
yield fh
@pytest.fixture
def example_project(tmpdir):
data = """
{
"family": "default",
"volumes": [],
"containerDefinitions": [
{
"name": "web-1",
"image": ... | default_config | identifier_name |
conftest.py | import json
import os
from textwrap import dedent
import boto3
import moto
import pytest
from moto.ec2 import ec2_backend
from moto.ec2 import utils as ec2_utils
from ecs_deplojo.connection import Connection
from ecs_deplojo.task_definitions import TaskDefinition
BASE_DIR = os.path.dirname(os.path.abspath(__file__))... |
@pytest.fixture
def example_project(tmpdir):
data = """
{
"family": "default",
"volumes": [],
"containerDefinitions": [
{
"name": "web-1",
"image": "${image}",
"essential": true,
"command": ["hello", "world"],
"memory": 256,
... | path = os.path.join(BASE_DIR, "files/default_config.yml")
with open(path, "r") as fh:
yield fh | identifier_body |
conftest.py | import json
import os
from textwrap import dedent
import boto3
import moto
import pytest
from moto.ec2 import ec2_backend
from moto.ec2 import utils as ec2_utils
from ecs_deplojo.connection import Connection
from ecs_deplojo.task_definitions import TaskDefinition
BASE_DIR = os.path.dirname(os.path.abspath(__file__))... | ENV_CODE: 12345
task_definitions:
web:
template: %(template_filename)s
environment_group: group-1
task_role_arn: my-test
overrides:
web-1:
memory: 512
portMappings:
- hostPort: 0
containerPort: 8080
... | random_line_split | |
day_5.rs | pub use tdd_kata::lcd_kata::day_5::Display;
pub use tdd_kata::lcd_kata::day_5::Number::{One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Zero};
pub use tdd_kata::lcd_kata::day_5::Data::{NotANumber, Output};
pub use expectest::prelude::be_equal_to;
describe! lcd_tests {
before_each {
let mut display ... | it "should output all numbers" {
display.input("1234567890");
expect!(display.output()).to(be_equal_to(Output(vec![One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Zero])));
}
it "should show error when input is not a number" {
display.input("abc");
expect!(display.ou... | random_line_split | |
sagas.js | import { takeLatest, call, put } from 'redux-saga/effects';
import { gql } from 'react-apollo';
import { push } from 'react-router-redux';
import jwtDecode from 'jwt-decode';
import { setJwtToken } from '../../utils/auth';
import { bootstrap } from '../../utils/sagas';
import { registerError, registerSuccess } from '.... |
function* register({ user }) {
try {
const response = yield call(sendRegister, user);
const token = response.data.register;
const userInfo = jwtDecode(token);
setJwtToken(token);
yield put(registerSuccess());
yield put(loginSuccess(userInfo));
yield put(push(homePage()));
} catch (e) {... | {
return client.mutate({ mutation: RegisterMutation, variables: user });
} | identifier_body |
sagas.js | import { takeLatest, call, put } from 'redux-saga/effects';
import { gql } from 'react-apollo';
import { push } from 'react-router-redux';
import jwtDecode from 'jwt-decode';
import { setJwtToken } from '../../utils/auth';
import { bootstrap } from '../../utils/sagas';
import { registerError, registerSuccess } from '.... | (user) {
return client.mutate({ mutation: RegisterMutation, variables: user });
}
function* register({ user }) {
try {
const response = yield call(sendRegister, user);
const token = response.data.register;
const userInfo = jwtDecode(token);
setJwtToken(token);
yield put(registerSuccess());
... | sendRegister | identifier_name |
print_with_newline.rs | // FIXME: Ideally these suggestions would be fixed via rustfix. Blocked by rust-lang/rust#53934
// // run-rustfix
#![allow(clippy::print_literal)]
#![warn(clippy::print_with_newline)]
fn | () {
print!("Hello\n");
print!("Hello {}\n", "world");
print!("Hello {} {}\n", "world", "#2");
print!("{}\n", 1265);
print!("\n");
// these are all fine
print!("");
print!("Hello");
println!("Hello");
println!("Hello\n");
println!("Hello {}\n", "world");
print!("Issue\n{... | main | identifier_name |
print_with_newline.rs | // FIXME: Ideally these suggestions would be fixed via rustfix. Blocked by rust-lang/rust#53934
// // run-rustfix
#![allow(clippy::print_literal)]
#![warn(clippy::print_with_newline)]
fn main() {
print!("Hello\n");
print!("Hello {}\n", "world");
print!("Hello {} {}\n", "world", "#2");
print!("{}\n", 1... | );
print!(
r"
"
);
// Don't warn on CRLF (#4208)
print!("\r\n");
print!("foo\r\n");
print!("\\r\n"); //~ ERROR
print!("foo\rbar\n") // ~ ERROR
} | print!(
"
" | random_line_split |
print_with_newline.rs | // FIXME: Ideally these suggestions would be fixed via rustfix. Blocked by rust-lang/rust#53934
// // run-rustfix
#![allow(clippy::print_literal)]
#![warn(clippy::print_with_newline)]
fn main() | println!("\nbla\n\n"); // #3126
// Escaping
print!("\\n"); // #3514
print!("\\\n"); // should fail
print!("\\\\n");
// Raw strings
print!(r"\n"); // #3778
// Literal newlines should also fail
print!(
"
"
);
print!(
r"
"
);
// Don't warn on CRLF (#4... | {
print!("Hello\n");
print!("Hello {}\n", "world");
print!("Hello {} {}\n", "world", "#2");
print!("{}\n", 1265);
print!("\n");
// these are all fine
print!("");
print!("Hello");
println!("Hello");
println!("Hello\n");
println!("Hello {}\n", "world");
print!("Issue\n{}",... | identifier_body |
GW_SCENE_INFORMATION_CHANGED_NTF-test.ts | "use strict";
import { expect } from "chai";
import 'mocha';
import { GW_SCENE_INFORMATION_CHANGED_NTF, SceneChangeType } from "../../src";
describe("KLF200-API", function() {
describe("GW_SCENE_INFORMATION_CHANGED_NTF", function() {
describe("Constructor", function() {
const data = Buffer.fro... | const result = new GW_SCENE_INFORMATION_CHANGED_NTF(data);
expect(result.SceneChangeType).to.equal(SceneChangeType.Modified);
});
});
});
}); | const result = new GW_SCENE_INFORMATION_CHANGED_NTF(data);
expect(result.SceneID).to.equal(42);
});
it("should return the scenes change type", function() { | random_line_split |
app.js | (function () {
var app = angular.module('app', ['firebase', 'ui.router'])
.constant('firebaseUrl', "https://popping-torch-4767.firebaseio.com/");
app.config(function ($stateProvider, $urlRouterProvider, firebaseUrl) {
$urlRouterProvider.otherwise('/home');
$stateProvi... | var ref = new Firebase(firebaseUrl);
var authObj = $firebaseAuth(ref);
return authObj.$requireAuth();
}]
}
});
});
})(); | // controller will not be loaded until $waitForAuth resolves
// Auth refers to our $firebaseAuth wrapper in the example above
"currentAuth": ["$firebaseAuth", function ($firebaseAuth) {
// $waitForAuth returns a promise so the resolve waits for it to c... | random_line_split |
cmd_interface_02_server_clients.py | #!/usr/bin/env python
# coding: utf-8
#
# StreamBuddy - a video and data streaming serviweng zieleinfahrtce.
# Copyright (c) 2015, Tobias Bleiker & Dumeni Manatschal
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# ... | (name, role, zeromq_context, address, port_pub, port_pull):
client = cmd_interface.Client(name, role, zeromq_context, address,
port_pub, port_pull)
def test():
return 'test successful'
client.add_command('test', test, 'simple test')
client.start()
# send... | f1_thread | identifier_name |
cmd_interface_02_server_clients.py | #!/usr/bin/env python
# coding: utf-8
#
# StreamBuddy - a video and data streaming serviweng zieleinfahrtce.
# Copyright (c) 2015, Tobias Bleiker & Dumeni Manatschal
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# ... | log.info('### Test 3: Request help.')
client.get_help('F1')
time.sleep(0.5)
log.info('### Test 4: Send command test1.')
ret = client.send_cmd('F1', 'test')
log.info('Got: {ret}'.format(ret=ret))
if __name__ == '__main__':
zeromq_context = zmq.Context()
client_c1 = multiprocessing.Pro... |
time.sleep(0.5)
| random_line_split |
cmd_interface_02_server_clients.py | #!/usr/bin/env python
# coding: utf-8
#
# StreamBuddy - a video and data streaming serviweng zieleinfahrtce.
# Copyright (c) 2015, Tobias Bleiker & Dumeni Manatschal
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# ... | time.sleep(0.1)
client_c1.join()
client_f1.terminate()
server.terminate()
| zeromq_context = zmq.Context()
client_c1 = multiprocessing.Process(name='Client-c1', target=c1_thread,
args=('c1', 'commander',
zeromq_context, '0.0.0.0', 7001,
7000))
client_f1 =... | conditional_block |
cmd_interface_02_server_clients.py | #!/usr/bin/env python
# coding: utf-8
#
# StreamBuddy - a video and data streaming serviweng zieleinfahrtce.
# Copyright (c) 2015, Tobias Bleiker & Dumeni Manatschal
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# ... |
def c1_thread(name, role, zeromq_context, address, port_pub, port_pull):
client = cmd_interface.Client(name, role, zeromq_context, address,
port_pub, port_pull)
def update_func(msg):
log.info('Got update message: {msg}'.format(msg=msg))
client.set_update_func(u... | client = cmd_interface.Client(name, role, zeromq_context, address,
port_pub, port_pull)
def test():
return 'test successful'
client.add_command('test', test, 'simple test')
client.start()
# send an update and join client
time.sleep(0.5)
log.info('###... | identifier_body |
os.js | 0xFE02,
//
// Implementation of OUT
0x0430: 0x3E0A,
0x0431: 0x3208,
0x0432: 0xA205,
0x0433: 0x07FE,
0x0434: 0xB004,
0x0435: 0x2204,
0x0436: 0x2E04,
0x0437: 0xC1C0,
0x0438: 0xFE04,
0x0439: 0xFE06,
//
// Imple... | 0xFD7C: 0xC1C0,
//
// 0xFD7D, 0xFD7E, and 0xFD7F are callee-saved register locations.
// The "halting the processor" message
// occupies addresses 0xFD80 through 0xFDA4, inclusive. | random_line_split | |
os.js | 0x2E04,
0x0437: 0xC1C0,
0x0438: 0xFE04,
0x0439: 0xFE06,
//
// Implementation of PUTS
0x0450: 0x3E16,
0x0451: 0x3012,
0x0452: 0x3212,
0x0453: 0x3412,
0x0454: 0x6200,
0x0455: 0x0405,
0x0456: 0xA409,
0x0457: 0x07FE,
... | {
if (memory[i] === undefined) {
memory[i] = 0xFD00;
}
} | conditional_block | |
urls.py | from django.conf.urls import url, include
from rest_framework.routers import DefaultRouter
from rest_framework_swagger.views import get_swagger_view
from . import views, views_api
# Django REST framework
router = DefaultRouter()
router.register(r'election', views_api.ElectionInterface)
router.register(r'district', vi... | url(r'^api/docs$', schema_view)
] | urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^loaderio-eac9628bcae9be5601e1f3c62594d162.txt$', views.load_test, name='load_test'),
url(r'^api/', include(router.urls)), | random_line_split |
GroupInfo.tsx | // TODO: Chance the databse schema to include: creator, current members, lat, long, and radius | import * as React from "react";
import {
BackHandler,
DeviceEventEmitter,
Dimensions,
Platform,
StatusBar,
StyleSheet,
Text,
TextInput,
TouchableOpacity,
View,
ScrollView
} from "react-native";
import {SocialIcon, Button} from "react-native-elements";
var MapView = require('... | //
//
//
// | random_line_split |
GroupInfo.tsx | // TODO: Chance the databse schema to include: creator, current members, lat, long, and radius
//
//
//
//
import * as React from "react";
import {
BackHandler,
DeviceEventEmitter,
Dimensions,
Platform,
StatusBar,
StyleSheet,
Text,
TextInput,
TouchableOpacity,
View,
ScrollVie... |
componentDidMount() {
this.getGroupInfo();
}
map: any;
static navigationOptions = ({navigation}) => {
return {
title: 'Crowd Information',
headerTintColor: "#FFFFFF",
gesturesEnabled: false,
headerStyle: {
backgroundColor:... | {
super(props);
this.state = {
desc: '',
name: '',
region: {
latitude: 42.405804,
longitude: -71.11956,
latitudeDelta: 0.02,
longitudeDelta: 0.01,
}
};
} | identifier_body |
GroupInfo.tsx | // TODO: Chance the databse schema to include: creator, current members, lat, long, and radius
//
//
//
//
import * as React from "react";
import {
BackHandler,
DeviceEventEmitter,
Dimensions,
Platform,
StatusBar,
StyleSheet,
Text,
TextInput,
TouchableOpacity,
View,
ScrollVie... | () {
this.getGroupInfo();
}
map: any;
static navigationOptions = ({navigation}) => {
return {
title: 'Crowd Information',
headerTintColor: "#FFFFFF",
gesturesEnabled: false,
headerStyle: {
backgroundColor: "#003EFF",
... | componentDidMount | identifier_name |
test_settings.py | from django.test import override_settings, SimpleTestCase
from arcutils.settings import NO_DEFAULT, PrefixedSettings, get_setting
@override_settings(ARC={
'a': 'a',
'b': [0, 1],
'c': [{'c': 'c'}],
'd': 'd',
})
class TestGetSettings(SimpleTestCase):
def get_setting(self, key, default=NO_DEFAULT):... | super().setUp()
defaults = {
'base_url': 'http://example.com/cas/',
'parent': {
'child': 'child',
},
'overridden': 'default',
}
self.settings = PrefixedSettings('CAS', defaults)
def test_get_from_defaults(self):
... |
def setUp(self): | random_line_split |
test_settings.py | from django.test import override_settings, SimpleTestCase
from arcutils.settings import NO_DEFAULT, PrefixedSettings, get_setting
@override_settings(ARC={
'a': 'a',
'b': [0, 1],
'c': [{'c': 'c'}],
'd': 'd',
})
class TestGetSettings(SimpleTestCase):
def get_setting(self, key, default=NO_DEFAULT):... |
def test_raises_when_not_found_and_no_default(self):
self.assertRaises(KeyError, self.get_setting, 'NOPE')
def test_can_traverse_into_string_setting(self):
self.assertEqual(self.get_setting('ARC.d.0'), 'd')
def test_bad_index_causes_type_error(self):
self.assertRaises(TypeError, ... | default = object()
self.assertIs(self.get_setting('ARC.nope', default), default) | identifier_body |
test_settings.py | from django.test import override_settings, SimpleTestCase
from arcutils.settings import NO_DEFAULT, PrefixedSettings, get_setting
@override_settings(ARC={
'a': 'a',
'b': [0, 1],
'c': [{'c': 'c'}],
'd': 'd',
})
class | (SimpleTestCase):
def get_setting(self, key, default=NO_DEFAULT):
return get_setting(key, default=default)
def test_can_traverse_into_dict(self):
self.assertEqual(self.get_setting('ARC.a'), 'a')
def test_can_traverse_into_dict_then_list(self):
self.assertEqual(self.get_setting('AR... | TestGetSettings | identifier_name |
cache.rs | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use async_trait::async_trait;
use kvproto::coprocessor::Response;
use crate::coprocessor::RequestHandler;
use crate::coprocessor::*;
use crate::storage::Snapshot;
pub struct CachedRequestHandler {
data_version: Option<u64>,
}
impl CachedRequestH... |
}
| {
let mut resp = Response::default();
resp.set_is_cache_hit(true);
if let Some(v) = self.data_version {
resp.set_cache_last_version(v);
}
Ok(resp)
} | identifier_body |
cache.rs | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use async_trait::async_trait;
use kvproto::coprocessor::Response;
use crate::coprocessor::RequestHandler;
use crate::coprocessor::*;
use crate::storage::Snapshot;
pub struct CachedRequestHandler {
data_version: Option<u64>,
}
impl CachedRequestH... | resp.set_cache_last_version(v);
}
Ok(resp)
}
} | resp.set_is_cache_hit(true);
if let Some(v) = self.data_version { | random_line_split |
cache.rs | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use async_trait::async_trait;
use kvproto::coprocessor::Response;
use crate::coprocessor::RequestHandler;
use crate::coprocessor::*;
use crate::storage::Snapshot;
pub struct CachedRequestHandler {
data_version: Option<u64>,
}
impl CachedRequestH... | <S: Snapshot>(snap: S) -> Self {
Self {
data_version: snap.get_data_version(),
}
}
pub fn builder<S: Snapshot>() -> RequestHandlerBuilder<S> {
Box::new(|snap, _req_ctx: &ReqContext| Ok(CachedRequestHandler::new(snap).into_boxed()))
}
}
#[async_trait]
impl RequestHandler... | new | identifier_name |
cache.rs | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use async_trait::async_trait;
use kvproto::coprocessor::Response;
use crate::coprocessor::RequestHandler;
use crate::coprocessor::*;
use crate::storage::Snapshot;
pub struct CachedRequestHandler {
data_version: Option<u64>,
}
impl CachedRequestH... |
Ok(resp)
}
}
| {
resp.set_cache_last_version(v);
} | conditional_block |
igcformat.js | goog.provide('ol.format.IGC');
goog.provide('ol.format.IGCZ');
goog.require('goog.asserts');
goog.require('goog.string');
goog.require('goog.string.newlines');
goog.require('ol.Feature');
goog.require('ol.format.Feature');
goog.require('ol.format.TextFeature');
goog.require('ol.geom.LineString');
goog.require('ol.proj... | * @api
*/
ol.format.IGC = function(opt_options) {
var options = goog.isDef(opt_options) ? opt_options : {};
goog.base(this);
/**
* @inheritDoc
*/
this.defaultDataProjection = ol.proj.get('EPSG:4326');
/**
* @private
* @type {ol.format.IGCZ}
*/
this.altitudeMode_ = goog.isDef(options.alt... | *
* @constructor
* @extends {ol.format.TextFeature}
* @param {olx.format.IGCOptions=} opt_options Options. | random_line_split |
igcformat.js | goog.provide('ol.format.IGC');
goog.provide('ol.format.IGCZ');
goog.require('goog.asserts');
goog.require('goog.string');
goog.require('goog.string.newlines');
goog.require('ol.Feature');
goog.require('ol.format.Feature');
goog.require('ol.format.TextFeature');
goog.require('ol.geom.LineString');
goog.require('ol.proj... | else {
goog.asserts.fail();
z = 0;
}
flatCoordinates.push(z);
}
var dateTime = Date.UTC(year, month, day, hour, minute, second);
flatCoordinates.push(dateTime / 1000);
}
} else if (line.charAt(0) == 'H') {
m = ol.format.IGC.HFDTE_RECOR... | {
z = parseInt(m[12], 10);
} | conditional_block |
language.ts | <message>
<source>English</source>
<translation>Angļu</translation>
</message>
<message>
<source>default</source>
<translation>noklusētā</translation>
</message>
<message>
<source>Language</source>
<translation>Valoda</translation>
</message>
<... | <!DOCTYPE TS><TS>
<context>
<name>LanguageSettings</name> | random_line_split | |
error.rs | /*
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to i... |
}
/// An error representing failure to convert a filter's protobuf configuration
/// to its static representation.
#[derive(Debug, PartialEq, thiserror::Error)]
#[error(
"{}failed to convert protobuf config: {}",
self.field.as_ref().map(|f| format!("Field `{f}`")).unwrap_or_default(),
reason
)]
pub struct... | {
Error::InitializeMetricsFailed(error.to_string())
} | identifier_body |
error.rs | /*
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to i... | #[derive(Debug, PartialEq, thiserror::Error)]
pub enum Error {
#[error("filter `{}` not found", .0)]
NotFound(String),
#[error("filter `{}` requires configuration, but none provided", .0)]
MissingConfig(&'static str),
#[error("field `{}` is invalid, reason: {}", field, reason)]
FieldInvalid { fi... | /// a [`FilterFactory`]. | random_line_split |
error.rs | /*
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to i... | {
/// Reason for the failure.
reason: String,
/// Set if the failure is specific to a single field in the config.
field: Option<String>,
}
impl ConvertProtoConfigError {
pub fn new(reason: impl std::fmt::Display, field: Option<String>) -> Self {
Self {
reason: reason.to_string(... | ConvertProtoConfigError | identifier_name |
periodo.module.ts | import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { NgaModule } from '../../theme/nga.module';
import { HttpModule, JsonpModule } from '@angular/http';
import { Ng2Bs3ModalModule } from 'ng2-bs3-modal... | imports: [
CommonModule,
ReactiveFormsModule,
FormsModule,
NgaModule,
HttpModule,
JsonpModule,
Ng2Bs3ModalModule,
routing
],
declarations: [
Periodo
],
providers: [
PeriodosService,
Constants
]
})
export default class PeriodoModule {} | import { Constants } from '../../app.constants';
@NgModule({ | random_line_split |
periodo.module.ts | import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { NgaModule } from '../../theme/nga.module';
import { HttpModule, JsonpModule } from '@angular/http';
import { Ng2Bs3ModalModule } from 'ng2-bs3-modal... | {}
| PeriodoModule | identifier_name |
mod.rs | use std::rc::Rc;
use std::cell::RefCell;
use rand;
use rand::XorShiftRng;
use rand::Rng;
use gmath::vectors::Vec2;
use game::entity::{Object, Physics};
use game::entity::creature::Creature;
use keyboard::KeyboardState;
use sdl2::keycode;
pub trait Controller<A> {
/// Update the controller
/// # Arguments
... | (&mut self, object: &mut Creature, _: f32) {
let keyboard = self.keyboard.borrow();
let move_accel = object.move_accel;
let x_accel =
if keyboard.is_keydown(keycode::LeftKey) {
-move_accel * if object.is_on_ground() { 1.0 } else { 0.6 }
}
else... | update | identifier_name |
mod.rs | use std::rc::Rc;
use std::cell::RefCell;
use rand;
use rand::XorShiftRng;
use rand::Rng;
use gmath::vectors::Vec2;
use game::entity::{Object, Physics};
use game::entity::creature::Creature;
use keyboard::KeyboardState;
use sdl2::keycode;
pub trait Controller<A> {
/// Update the controller
/// # Arguments
... |
else if keyboard.is_keydown(keycode::RightKey) {
move_accel * if object.is_on_ground() { 1.0 } else { 0.6 }
}
else {
0.0
};
let new_accel = Vec2::new(x_accel, object.acceleration().y);
object.set_acceleration(new_accel);
... | {
-move_accel * if object.is_on_ground() { 1.0 } else { 0.6 }
} | conditional_block |
mod.rs | use std::rc::Rc;
use std::cell::RefCell;
use rand;
use rand::XorShiftRng;
use rand::Rng;
use gmath::vectors::Vec2;
use game::entity::{Object, Physics};
use game::entity::creature::Creature;
use keyboard::KeyboardState;
use sdl2::keycode;
pub trait Controller<A> {
/// Update the controller
/// # Arguments
... | impl Controller<Creature> for KeyboardController {
fn update(&mut self, object: &mut Creature, _: f32) {
let keyboard = self.keyboard.borrow();
let move_accel = object.move_accel;
let x_accel =
if keyboard.is_keydown(keycode::LeftKey) {
-move_accel * if object.is... | }
| random_line_split |
mod.rs | use std::rc::Rc;
use std::cell::RefCell;
use rand;
use rand::XorShiftRng;
use rand::Rng;
use gmath::vectors::Vec2;
use game::entity::{Object, Physics};
use game::entity::creature::Creature;
use keyboard::KeyboardState;
use sdl2::keycode;
pub trait Controller<A> {
/// Update the controller
/// # Arguments
... |
}
pub struct NoneController<A>;
impl<A: Object> NoneController<A> {
pub fn new() -> NoneController<A> {
NoneController
}
}
impl<A: Object> Controller<A> for NoneController<A> {
// Just use default trait implementations
}
/// A controller that controls objects using the keyboard
pub struct Keyb... | {
} | identifier_body |
dojox.widget._CalendarYearView.d.ts | /// <reference path="Object.d.ts" />
/// <reference path="dojox.widget._CalendarView.d.ts" />
/// <reference path="dijit._Templated.d.ts" />
module dojox.widget{
export class | extends dojox.widget._CalendarView {
templateString : String;
templatePath : String;
widgetsInTemplate : bool;
_skipNodeCache : bool;
_earlyTemplatedStartup : bool;
_attachPoints : any;
_attachEvents : any[];
declaredClass : any;
_startupWidgets : Object;
_supportingWidgets : Object;
_templateCache : Object;
_stringRe... | _CalendarYearView | identifier_name |
dojox.widget._CalendarYearView.d.ts | /// <reference path="Object.d.ts" />
/// <reference path="dojox.widget._CalendarView.d.ts" />
/// <reference path="dijit._Templated.d.ts" />
module dojox.widget{
export class _CalendarYearView extends dojox.widget._CalendarView { | widgetsInTemplate : bool;
_skipNodeCache : bool;
_earlyTemplatedStartup : bool;
_attachPoints : any;
_attachEvents : any[];
declaredClass : any;
_startupWidgets : Object;
_supportingWidgets : Object;
_templateCache : Object;
_stringRepl (tmpl:any) : any;
_fillContent (source:HTMLElement) : any;
_attachTemplateNodes (ro... | templateString : String;
templatePath : String; | random_line_split |
getaddons.py | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'designer/getaddons.ui'
#
# Created: Fri Aug 22 00:57:31 2014
# by: PyQt4 UI code generator 4.10.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
ex... | (self, Dialog):
Dialog.setWindowTitle(_("Install Add-on"))
self.label.setText(_("To browse add-ons, please click the browse button below.<br><br>When you\'ve found an add-on you like, please paste its code below."))
self.label_2.setText(_("Code:"))
| retranslateUi | identifier_name |
getaddons.py | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'designer/getaddons.ui'
#
# Created: Fri Aug 22 00:57:31 2014
# by: PyQt4 UI code generator 4.10.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
ex... |
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName(_fromUtf8("Dialog"))
Dialog.resize(367, 204)
self.verticalLayout = QtGui.QVBoxLa... | return QtGui.QApplication.translate(context, text, disambig, _encoding) | identifier_body |
getaddons.py | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'designer/getaddons.ui'
#
# Created: Fri Aug 22 00:57:31 2014
# by: PyQt4 UI code generator 4.10.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
ex... | self.verticalLayout.addItem(spacerItem)
self.horizontalLayout = QtGui.QHBoxLayout()
self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
self.label_2 = QtGui.QLabel(Dialog)
self.label_2.setObjectName(_fromUtf8("label_2"))
self.horizontalLayout.addWidget(self... | self.label.setWordWrap(True)
self.label.setObjectName(_fromUtf8("label"))
self.verticalLayout.addWidget(self.label)
spacerItem = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding) | random_line_split |
nav.d.ts | import { AfterViewInit, ComponentFactoryResolver, ElementRef, NgZone, Renderer, ViewContainerRef } from '@angular/core';
import { App } from '../app/app';
import { Config } from '../../config/config';
import { DeepLinker } from '../../navigation/deep-linker';
import { GestureController } from '../../gestures/gesture-co... | * })
* class MyApp {
* root = GettingStartedPage;
*
* constructor(){
* }
* }
* ```
*
* @demo /docs/demos/src/navigation/
* @see {@link /docs/components#navigation Navigation Component Docs}
*/
export declare class Nav extends NavControllerBase implements AfterViewInit {
private _root;
private ... | * import { Component } from '@angular/core';
* import { GettingStartedPage } from './getting-started';
*
* @Component({
* template: `<ion-nav [root]="root"></ion-nav>` | random_line_split |
nav.d.ts | import { AfterViewInit, ComponentFactoryResolver, ElementRef, NgZone, Renderer, ViewContainerRef } from '@angular/core';
import { App } from '../app/app';
import { Config } from '../../config/config';
import { DeepLinker } from '../../navigation/deep-linker';
import { GestureController } from '../../gestures/gesture-co... | extends NavControllerBase implements AfterViewInit {
private _root;
private _hasInit;
constructor(viewCtrl: ViewController, parent: NavController, app: App, config: Config, keyboard: Keyboard, elementRef: ElementRef, zone: NgZone, renderer: Renderer, cfr: ComponentFactoryResolver, gestureCtrl: GestureContr... | Nav | identifier_name |
p_2_0_01.rs | // P_2_0_01
//
// Generative Gestaltung – Creative Coding im Web
// ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018
// Benedikt Groß, Hartmut Bohnacker, Julia Laub, Claudius Lazzeroni
// with contributions by Joey Lee and Niels Poldervaart
// Copyright 2018
//
// http://www.generative-gestaltung.de... | app.main_window()
.capture_frame(app.exe_name().unwrap() + ".png");
}
}
| conditional_block | |
p_2_0_01.rs | // P_2_0_01
//
// Generative Gestaltung – Creative Coding im Web
// ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018
// Benedikt Groß, Hartmut Bohnacker, Julia Laub, Claudius Lazzeroni
// with contributions by Joey Lee and Niels Poldervaart
// Copyright 2018
//
// http://www.generative-gestaltung.de... | draw.to_frame(app, &frame).unwrap();
if app.keys.down.contains(&Key::S) {
app.main_window()
.capture_frame(app.exe_name().unwrap() + ".png");
}
}
| // Prepare to draw.
let draw = app.draw();
let win = app.window_rect();
let circle_resolution = map_range(app.mouse.y, win.top(), win.bottom(), 2, 80);
let radius = app.mouse.x - win.left();
let angle = TAU / circle_resolution as f32;
draw.background().color(BLACK);
for i in 0..circle_r... | identifier_body |
p_2_0_01.rs | // P_2_0_01
//
// Generative Gestaltung – Creative Coding im Web
// ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018
// Benedikt Groß, Hartmut Bohnacker, Julia Laub, Claudius Lazzeroni
// with contributions by Joey Lee and Niels Poldervaart
// Copyright 2018
//
// http://www.generative-gestaltung.de... | p: &App, frame: Frame) {
// Prepare to draw.
let draw = app.draw();
let win = app.window_rect();
let circle_resolution = map_range(app.mouse.y, win.top(), win.bottom(), 2, 80);
let radius = app.mouse.x - win.left();
let angle = TAU / circle_resolution as f32;
draw.background().color(BLACK);... | w(ap | identifier_name |
p_2_0_01.rs | // P_2_0_01
//
// Generative Gestaltung – Creative Coding im Web
// ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018
// Benedikt Groß, Hartmut Bohnacker, Julia Laub, Claudius Lazzeroni
// with contributions by Joey Lee and Niels Poldervaart
// Copyright 2018
//
// http://www.generative-gestaltung.de... | .caps_round()
.color(WHITE);
}
// Write to the window frame.
draw.to_frame(app, &frame).unwrap();
if app.keys.down.contains(&Key::S) {
app.main_window()
.capture_frame(app.exe_name().unwrap() + ".png");
}
} | .stroke_weight(app.mouse.y / 20.0) | random_line_split |
goal_lists.js | /*
* This file is part of Saladay <https://www.crimx.com/rn-saladay/>.
* Copyright (C) 2017 CRIMX <straybugs@gmail.com>
*
* Saladay is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* Saladay... | (listItem) {
return new Promise((resolve, reject) => {
if (!listItem.list_id) { return reject('updateListItem: Missing PK list_id') }
let keys = [
'list_title',
'list_color',
'list_order'
].filter(k => listItem[k] !== undefined)
this.db.transaction(tx => {
... | update | identifier_name |
goal_lists.js | /*
* This file is part of Saladay <https://www.crimx.com/rn-saladay/>.
* Copyright (C) 2017 CRIMX <straybugs@gmail.com>
*
* Saladay is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* Saladay... |
let keys = [
'list_title',
'list_color',
'list_order'
].filter(k => listItem[k] !== undefined)
this.db.transaction(tx => {
tx.executeSql(
`UPDATE goal_lists
SET ${keys.map(k => k + ' = ?').join(',')}
WHERE list_id = ?`,
[...key... | { return reject('updateListItem: Missing PK list_id') } | conditional_block |
goal_lists.js | /*
* This file is part of Saladay <https://www.crimx.com/rn-saladay/>.
* Copyright (C) 2017 CRIMX <straybugs@gmail.com>
*
* Saladay is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as | * GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Saladay. If not, see <http://www.gnu.org/licenses/>.
*/
import { SQLite } from 'expo'
import { pickle } from './helpers'
export default class GoalLists {
constructor (db) {
thi... | * published by the Free Software Foundation.
*
* Saladay is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | random_line_split |
parameter.ts | import { Type, ReflectionType } from '../types/index';
import { Reflection, DefaultValueContainer, TypeContainer, TraverseCallback, TraverseProperty } from './abstract';
import { SignatureReflection } from './signature';
export class ParameterReflection extends Reflection implements DefaultValueContainer, TypeContaine... |
if (this.defaultValue) {
result.defaultValue = this.defaultValue;
}
return result;
}
/**
* Return a string representation of this reflection.
*/
toString() {
return super.toString() + (this.type ? ':' + this.type.toString() : '');
}
}
| {
result.type = this.type.toObject();
} | conditional_block |
parameter.ts | import { Type, ReflectionType } from '../types/index';
import { Reflection, DefaultValueContainer, TypeContainer, TraverseCallback, TraverseProperty } from './abstract';
import { SignatureReflection } from './signature';
export class | extends Reflection implements DefaultValueContainer, TypeContainer {
parent?: SignatureReflection;
defaultValue?: string;
type?: Type;
/**
* Traverse all potential child reflections of this reflection.
*
* The given callback will be invoked for all children, signatures and type parame... | ParameterReflection | identifier_name |
parameter.ts | import { Type, ReflectionType } from '../types/index';
import { Reflection, DefaultValueContainer, TypeContainer, TraverseCallback, TraverseProperty } from './abstract';
import { SignatureReflection } from './signature';
export class ParameterReflection extends Reflection implements DefaultValueContainer, TypeContaine... |
/**
* Return a string representation of this reflection.
*/
toString() {
return super.toString() + (this.type ? ':' + this.type.toString() : '');
}
}
| {
const result = super.toObject();
if (this.type) {
result.type = this.type.toObject();
}
if (this.defaultValue) {
result.defaultValue = this.defaultValue;
}
return result;
} | identifier_body |
parameter.ts | import { Type, ReflectionType } from '../types/index';
import { Reflection, DefaultValueContainer, TypeContainer, TraverseCallback, TraverseProperty } from './abstract';
import { SignatureReflection } from './signature';
export class ParameterReflection extends Reflection implements DefaultValueContainer, TypeContaine... | if (this.defaultValue) {
result.defaultValue = this.defaultValue;
}
return result;
}
/**
* Return a string representation of this reflection.
*/
toString() {
return super.toString() + (this.type ? ':' + this.type.toString() : '');
}
} | result.type = this.type.toObject();
}
| random_line_split |
SearchUtility.js | /** @flow */
import { INDEX_MODES } from "./constants";
import SearchIndex from "./SearchIndex";
import type { IndexMode } from "./constants";
import type { SearchApiIndex } from "../types";
type UidMap = {
[uid: string]: boolean
};
/**
* Synchronous client-side full-text search utility.
* Forked from JS search... | else {
var tokens: Array<string> = this._tokenize(this._sanitize(query));
return this._searchIndex.search(tokens, this._matchAnyToken);
}
};
/**
* Sets a new case-sensitive bit
*/
setCaseSensitive(caseSensitive: boolean): void {
this._caseSensitive = caseSensitive;
}
/**
* Set... | {
return Object.keys(this._uids);
} | identifier_body |
SearchUtility.js | /** @flow */
import { INDEX_MODES } from "./constants";
import SearchIndex from "./SearchIndex";
import type { IndexMode } from "./constants";
import type { SearchApiIndex } from "../types";
type UidMap = {
[uid: string]: boolean
};
/**
* Synchronous client-side full-text search utility.
* Forked from JS search... |
} catch (error) {
console.error(`Unable to parse token "${token}" ${error}`);
}
return expandedTokens;
}
_expandPrefixTokens(token: string): Array<string> {
const expandedTokens = [];
// String.prototype.charAt() may return surrogate halves instead of whole characters.
// When this... | {
let substring: string = "";
for (let j = i; j < length; ++j) {
substring += token.charAt(j);
expandedTokens.push(substring);
}
} | conditional_block |
SearchUtility.js | /** @flow */
import { INDEX_MODES } from "./constants";
import SearchIndex from "./SearchIndex";
import type { IndexMode } from "./constants";
import type { SearchApiIndex } from "../types";
type UidMap = {
[uid: string]: boolean
};
/**
* Synchronous client-side full-text search utility.
* Forked from JS search... | var tokens: Array<string> = this._tokenize(this._sanitize(query));
return this._searchIndex.search(tokens, this._matchAnyToken);
}
};
/**
* Sets a new case-sensitive bit
*/
setCaseSensitive(caseSensitive: boolean): void {
this._caseSensitive = caseSensitive;
}
/**
* Sets a new ... | if (!query) {
return Object.keys(this._uids);
} else { | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.