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 |
|---|---|---|---|---|
voxel_tree.rs | replace(&mut self.contents, Branches::empty());
// We re-construct the tree with bounds twice the size (but still centered
// around the origin) by deconstructing the top level of branches,
// creating a new doubly-sized top level, and moving the old branches back
// in as the new top level's c... | {0} | conditional_block | |
voxel_tree.rs | high &&
{
let low = -high;
voxel.x >= low &&
voxel.y >= low &&
voxel.z >= low &&
true
}
}
/// Ensure that this tree can hold the provided voxel.
pub fn grow_to_hold(&mut self, voxel: &voxel::Bounds) {
while !self.contains_bounds(voxel) {
// Double the bounds in ev... |
pub fn cast_ray<'a, Act, R>(
&'a self | {
if !self.contains_bounds(voxel) {
return None
}
let get_step = |branch| {
match branch {
&mut TreeBody::Branch(ref mut branches) => Ok(branches.deref_mut()),
_ => Err(()),
}
};
match self.find_mut(voxel, get_step) {
Ok(&mut TreeBody::Leaf(ref mut t)) => So... | identifier_body |
voxel_tree.rs | lhh: TreeBody,
hll: TreeBody,
hlh: TreeBody,
hhl: TreeBody,
hhh: TreeBody,
}
/// The main, recursive, tree-y part of the `VoxelTree`.
#[derive(Debug, PartialEq, Eq)]
pub enum TreeBody {
Empty,
Leaf(Voxel),
Branch(Box<Branches>),
}
impl Branches {
pub fn empty() -> Branches {
Branches {
lll... | lhl: TreeBody, | random_line_split | |
read.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use std::io;
use std::result;
use anyhow::{bail, Context as _};
use byteorder::{ByteOrder, NativeEndian};
#[cfg(feature = "debu... | self.index += 1;
Ok(ch)
}
fn peek(&mut self) -> anyhow::Result<u8> {
if self.index >= self.slice.len() {
bail!("eof while peeking next byte");
}
Ok(self.slice[self.index])
}
#[inline]
fn read_count(&self) -> usize {
self.index
}
... | let ch = self.slice[self.index]; | random_line_split |
read.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use std::io;
use std::result;
use anyhow::{bail, Context as _};
use byteorder::{ByteOrder, NativeEndian};
#[cfg(feature = "debu... |
let borrowed = &self.slice[self.index..(self.index + len)];
self.index += len;
Ok(Reference::Borrowed(borrowed))
}
}
impl<'de, R> DeRead<'de> for IoRead<R>
where
R: io::Read,
{
fn next(&mut self) -> anyhow::Result<u8> {
match self.peeked.take() {
Some(peeked) =>... | {
bail!("eof while parsing bytes/string");
} | conditional_block |
read.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use std::io;
use std::result;
use anyhow::{bail, Context as _};
use byteorder::{ByteOrder, NativeEndian};
#[cfg(feature = "debu... | <'a>(&'a [u8]);
#[cfg(feature = "debug_bytes")]
impl<'a> fmt::LowerHex for ByteBuf<'a> {
fn fmt(&self, fmtr: &mut fmt::Formatter) -> result::Result<(), fmt::Error> {
for byte in self.0 {
let val = byte.clone();
if (val >= b'-' && val <= b'9')
|| (val >= b'A' && val <=... | ByteBuf | identifier_name |
read.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use std::io;
use std::result;
use anyhow::{bail, Context as _};
use byteorder::{ByteOrder, NativeEndian};
#[cfg(feature = "debu... |
}
pub trait DeRead<'de> {
/// read next byte (if peeked byte not discarded return it)
fn next(&mut self) -> anyhow::Result<u8>;
/// peek next byte (peeked byte should come in next and next_bytes unless discarded)
fn peek(&mut self) -> anyhow::Result<u8>;
/// how many bytes have been read so far.
... | {
for byte in self.0 {
let val = byte.clone();
if (val >= b'-' && val <= b'9')
|| (val >= b'A' && val <= b'Z')
|| (val >= b'a' && val <= b'z')
|| val == b'_'
{
fmtr.write_fmt(format_args!("{}", val as char))?;
... | identifier_body |
tags.py | import parsers
import tokenizer
import context
html_escape_table = {
"&": "&",
'"': """,
"'": "'",
">": ">",
"<": "<",
}
def html_escape(text):
"""Produce entities within text."""
return "".join(html_escape_table.get(c,c) for c in unicode(text)) | self.args = args
def render(self, context):
return ''
class PairedTag(Tag):
def __init__(self, args):
self.children = []
super(PairedTag, self).__init__(args)
def render(self, context):
char_buffer = ''
for child in self.chi... |
class Tag(object):
def __init__(self, args): | random_line_split |
tags.py | import parsers
import tokenizer
import context
html_escape_table = {
"&": "&",
'"': """,
"'": "'",
">": ">",
"<": "<",
}
def html_escape(text):
"""Produce entities within text."""
return "".join(html_escape_table.get(c,c) for c in unicode(text))
class Tag(object):... |
break
return retval
class ElseTag(Tag):
def render(self, context):
raise Exception("Cannot call render directly on else tag")
class ForTag(PairedTag):
closing_literal = 'for'
def render(self, var_context):
if len(self.... | retval += unicode(tag.render(context)) | conditional_block |
tags.py | import parsers
import tokenizer
import context
html_escape_table = {
"&": "&",
'"': """,
"'": "'",
">": ">",
"<": "<",
}
def html_escape(text):
"""Produce entities within text."""
return "".join(html_escape_table.get(c,c) for c in unicode(text))
class Tag(object):... |
class TemplateContentTag(PairedTag):
pass
class LiteralContent(Tag):
def __init__(self, content):
self.content = content
def render(self, context):
return unicode(self.content)
#tags should support expressions, like #index+1
class EscapedContentTag(Tag):
def render(self,... | pass | identifier_body |
tags.py | import parsers
import tokenizer
import context
html_escape_table = {
"&": "&",
'"': """,
"'": "'",
">": ">",
"<": "<",
}
def html_escape(text):
"""Produce entities within text."""
return "".join(html_escape_table.get(c,c) for c in unicode(text))
class Tag(object):... | (Tag):
def render(self, context):
raise Exception("Cannot call render directly on else tag")
class ForTag(PairedTag):
closing_literal = 'for'
def render(self, var_context):
if len(self.args) <> 3:
raise Exception('The for tag takes exactly three arguments following the... | ElseTag | identifier_name |
952da73b5eff_add_dag_code_table.py | #
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... | ():
"""Create DagCode Table."""
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class SerializedDagModel(Base):
__tablename__ = 'serialized_dag'
# There are other columns here, but these are the only ones we need for the SELECT/UPDATE we are doing
... | upgrade | identifier_name |
952da73b5eff_add_dag_code_table.py | #
# Licensed to the Apache Software Foundation (ASF) under one | # or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You ma... | random_line_split | |
952da73b5eff_add_dag_code_table.py | #
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... |
sessionmaker = sa.orm.sessionmaker()
session = sessionmaker(bind=conn)
serialized_dags = session.query(SerializedDagModel).all()
for dag in serialized_dags:
dag.fileloc_hash = DagCode.dag_fileloc_hash(dag.fileloc)
session.merge(dag)
session.commit()
def downgrade():
"""Unappl... | op.create_index('idx_fileloc_hash', 'serialized_dag', ['fileloc_hash']) | conditional_block |
952da73b5eff_add_dag_code_table.py | #
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... |
"""Apply add source code table"""
op.create_table(
'dag_code',
sa.Column('fileloc_hash', sa.BigInteger(), nullable=False, primary_key=True, autoincrement=False),
sa.Column('fileloc', sa.String(length=2000), nullable=False),
sa.Column('source_code', sa.UnicodeText(), nullable=Fa... | __tablename__ = 'serialized_dag'
# There are other columns here, but these are the only ones we need for the SELECT/UPDATE we are doing
dag_id = sa.Column(sa.String(250), primary_key=True)
fileloc = sa.Column(sa.String(2000), nullable=False)
fileloc_hash = sa.Column(sa.BigInteger, nulla... | identifier_body |
main.ts | 'use strict';
import * as path from 'path';
import {
workspace, Disposable, ExtensionContext, window
} from 'vscode';
import {
LanguageClient, LanguageClientOptions, ServerOptions, TransportKind
} from 'vscode-languageclient';
/**
* Activates the extension.
*/
export function activate(context: ExtensionCo... |
});
});
let disposable: Disposable = languageClient.start();
context.subscriptions.push(disposable);
} | {
window.setStatusBarMessage('Swagger definition is valid!', 2000);
} | conditional_block |
main.ts | 'use strict';
import * as path from 'path';
import {
workspace, Disposable, ExtensionContext, window
} from 'vscode';
import {
LanguageClient, LanguageClientOptions, ServerOptions, TransportKind
} from 'vscode-languageclient';
/**
* Activates the extension.
*/
export function activate(context: ExtensionCo... |
// create client options
let clientOptions: LanguageClientOptions = {
documentSelector: [
{ scheme: 'file', language: 'yaml' },
{ scheme: 'file', language: 'yml' },
{ scheme: 'file', language: 'json' }
],
synchronize: {
configurationSectio... | }
} | random_line_split |
main.ts | 'use strict';
import * as path from 'path';
import {
workspace, Disposable, ExtensionContext, window
} from 'vscode';
import {
LanguageClient, LanguageClientOptions, ServerOptions, TransportKind
} from 'vscode-languageclient';
/**
* Activates the extension.
*/
export function | (context: ExtensionContext) {
// build path to server module
let serverModule = context.asAbsolutePath(path.join('server', 'main.js'));
// server debug options
let debugOptions = {
execArgv: [
"--nolazy",
"--inspect=6004"
]
};
// create server options
... | activate | identifier_name |
main.ts | 'use strict';
import * as path from 'path';
import {
workspace, Disposable, ExtensionContext, window
} from 'vscode';
import {
LanguageClient, LanguageClientOptions, ServerOptions, TransportKind
} from 'vscode-languageclient';
/**
* Activates the extension.
*/
export function activate(context: ExtensionCo... | module: serverModule,
transport: TransportKind.ipc,
options: debugOptions
}
}
// create client options
let clientOptions: LanguageClientOptions = {
documentSelector: [
{ scheme: 'file', language: 'yaml' },
{ scheme: 'file', languag... | {
// build path to server module
let serverModule = context.asAbsolutePath(path.join('server', 'main.js'));
// server debug options
let debugOptions = {
execArgv: [
"--nolazy",
"--inspect=6004"
]
};
// create server options
let serverOptions: Server... | identifier_body |
dashboard.js | /**
Template Controllers
@module Templates
*/
/**
The dashboard template | @class [template] views_dashboard
@constructor
*/
Template['views_dashboard'].helpers({
/**
Get all current wallets
@method (wallets)
*/
'wallets': function(disabled){
var wallets = Wallets.find({disabled: disabled}, {sort: {creationBlock: 1}}).fetch();
// sort wallets by balance... | random_line_split | |
dashboard.js | /**
Template Controllers
@module Templates
*/
/**
The dashboard template
@class [template] views_dashboard
@constructor
*/
Template['views_dashboard'].helpers({
/**
Get all current wallets
@method (wallets)
*/
'wallets': function(disabled){
var wallets = Wallets.find({disabled: disable... |
});
}
}); | {
account = account.toLowerCase();
EthAccounts.upsert({address: account}, {$set: {
address: account,
new: true
}});
} | conditional_block |
mercurial.py |
from mercurial import cmdutil
_hgignore_content = """\
syntax: glob
*~
*.pyc
*.pyo
*.bak
cache/*
databases/*
sessions/*
errors/*
"""
def | ():
app = request.args[0]
path = apath(app, r=request)
uio = ui.ui()
uio.quiet = True
if not os.environ.get('HGUSER') and not uio.config("ui", "username"):
os.environ['HGUSER'] = 'web2py@localhost'
try:
r = hg.repository(ui=uio, path=path)
except:
r = hg.repository(... | commit | identifier_name |
mercurial.py |
from mercurial import cmdutil
_hgignore_content = """\
syntax: glob
*~
*.pyc
*.pyo
*.bak
cache/*
databases/*
sessions/*
errors/*
"""
def commit():
app = request.args[0]
path = apath(app, r=request)
uio = ui.ui()
uio.quiet = True
if not os.environ.get('HGUSER') and not uio.config("ui", "usernam... |
files = r[r.lookup('.')].files()
return dict(form=form,files=TABLE(*[TR(file) for file in files]),repo=r)
| response.flash = 'no changes' | conditional_block |
mercurial.py | from mercurial import cmdutil
_hgignore_content = """\
syntax: glob
*~
*.pyc
*.pyo
*.bak
cache/*
databases/*
sessions/*
errors/*
"""
def commit():
app = request.args[0]
path = apath(app, r=request)
uio = ui.ui()
uio.quiet = True
if not os.environ.get('HGUSER') and not uio.config("ui", "username... | r.commit(text=form.vars.comment)
if r[r.lookup('.')] == oldid:
response.flash = 'no changes'
files = r[r.lookup('.')].files()
return dict(form=form,files=TABLE(*[TR(file) for file in files]),repo=r) | oldid = r[r.lookup('.')]
cmdutil.addremove(r) | random_line_split |
mercurial.py |
from mercurial import cmdutil
_hgignore_content = """\
syntax: glob
*~
*.pyc
*.pyo
*.bak
cache/*
databases/*
sessions/*
errors/*
"""
def commit():
| if r[r.lookup('.')] == oldid:
response.flash = 'no changes'
files = r[r.lookup('.')].files()
return dict(form=form,files=TABLE(*[TR(file) for file in files]),repo=r)
| app = request.args[0]
path = apath(app, r=request)
uio = ui.ui()
uio.quiet = True
if not os.environ.get('HGUSER') and not uio.config("ui", "username"):
os.environ['HGUSER'] = 'web2py@localhost'
try:
r = hg.repository(ui=uio, path=path)
except:
r = hg.repository(ui=uio, p... | identifier_body |
FileNameSource.py | # coding=utf-8
"""Ingest workflow management tool
FileNameSource Class
"""
__copyright__ = "Copyright (C) 2016 University of Maryland"
__license__ = "GNU AFFERO GENERAL PUBLIC LICENSE, Version 3"
import abc
import os
import sys
import psycopg2
class FileNameSource:
def __init__(self): pass
def __ite... |
self.credentials = credentials
self.cnx = psycopg2.connect(**credentials)
self.cs1 = self.cnx.cursor()
table = args.get('--dataset', 'resource')
if not table: table = 'resource'
self.tablename = table
### Do JIT set up of other queries....
self.update... | if not credentials[k]: credentials[k] = v | conditional_block |
FileNameSource.py | # coding=utf-8
"""Ingest workflow management tool
FileNameSource Class
"""
__copyright__ = "Copyright (C) 2016 University of Maryland"
__license__ = "GNU AFFERO GENERAL PUBLIC LICENSE, Version 3"
import abc
import os
import sys
import psycopg2
class FileNameSource:
def __init__(self): pass
def __ite... | (FileNameSource):
def __init__(self, args, cfg):
FileNameSource.__init__(self)
src = args['<source_directory>']
if src == '-':
print ' Incompatible mode -- Cannot Walk stdin '
raise ValueError
self.prefix = args['--prefix']
self.offset = len(self.prefi... | DirectoryWalk | identifier_name |
FileNameSource.py | # coding=utf-8
"""Ingest workflow management tool
FileNameSource Class
"""
__copyright__ = "Copyright (C) 2016 University of Maryland"
__license__ = "GNU AFFERO GENERAL PUBLIC LICENSE, Version 3"
import abc
import os
import sys
import psycopg2
class FileNameSource:
def __init__(self): pass
def __ite... | except Exception as e:
cs.connection.rollback()
class DBPrepare(DB):
"""
Class to be used when preparing.
"""
def __init__(self, args, cfg):
DB.__init__(self, args, cfg)
self.prefix = (args['--prefix'])
self.offset = len(self.prefix)
... | cs = self.cnx.cursor()
# Create the status Enum
try:
cs.execute("CREATE TYPE resource_status AS ENUM ('READY','IN-PROGRESS','DONE','BROKEN','VERIFIED')")
except:
cs.connection.rollback()
#
cmds = [
'''CREATE TABLE IF NOT EXISTS "{0}" (... | identifier_body |
FileNameSource.py | # coding=utf-8
"""Ingest workflow management tool
FileNameSource Class
"""
__copyright__ = "Copyright (C) 2016 University of Maryland"
__license__ = "GNU AFFERO GENERAL PUBLIC LICENSE, Version 3"
import abc
import os
import sys
import psycopg2
class FileNameSource:
def __init__(self): pass
def __ite... | """
Class to be used when preparing.
"""
def __init__(self, args, cfg):
DB.__init__(self, args, cfg)
self.prefix = (args['--prefix'])
self.offset = len(self.prefix)
self.cs = self.cnx.cursor('AB1', withhold=True)
self._setup_db(self.tablename)
cmd = '''PR... |
class DBPrepare(DB): | random_line_split |
geometry_test.py |
import unittest
from pytextgame.geometry import Direction, Position, Rectangle
class TestGeometry(unittest.TestCase):
def setUp(self):
self.pos1 = Position(5, 0)
self.pos2 = Position(10, 0)
self.pos3 = Position(9, 3)
self.dir1 = Direction(1, 1)
self.dir2 = Direction(5, 0)... | (self):
self.assertEqual(self.pos1.x, 5)
self.assertEqual(self.pos1.y, 0)
def test_position_distance_x(self):
self.assertEqual(self.pos1.distance(self.pos2), 5)
def test_position_distance_345(self):
self.assertEqual(self.pos1.distance(self.pos3), 5.0)
def test_translate_fi... | test_position_attributes | identifier_name |
geometry_test.py | import unittest
from pytextgame.geometry import Direction, Position, Rectangle
class TestGeometry(unittest.TestCase):
def setUp(self):
self.pos1 = Position(5, 0)
self.pos2 = Position(10, 0)
self.pos3 = Position(9, 3)
self.dir1 = Direction(1, 1)
self.dir2 = Direction(5, 0)
... |
def test_direction_descale(self):
self.dir3.descale(7)
self.assertEqual(self.dir3.dx, 1)
self.assertEqual(self.dir3.dy, 2)
if __name__ == '__main__':
unittest.main() | def test_direction_scale(self):
self.dir2.scale(2)
self.assertEqual(self.dir2.dx, 10)
self.assertEqual(self.dir2.dy, 0) | random_line_split |
geometry_test.py |
import unittest
from pytextgame.geometry import Direction, Position, Rectangle
class TestGeometry(unittest.TestCase):
def setUp(self):
self.pos1 = Position(5, 0)
self.pos2 = Position(10, 0)
self.pos3 = Position(9, 3)
self.dir1 = Direction(1, 1)
self.dir2 = Direction(5, 0)... |
def test_translate_five(self):
self.pos1.translate(self.dir2)
self.assertEqual(self.pos1.x, self.pos2.x)
self.assertEqual(self.pos1.y, self.pos2.y)
def test_direction_of_position(self):
direct = self.pos2.direction()
self.assertEqual(direct.dx, 10)
self.assertE... | self.assertEqual(self.pos1.distance(self.pos3), 5.0) | identifier_body |
geometry_test.py |
import unittest
from pytextgame.geometry import Direction, Position, Rectangle
class TestGeometry(unittest.TestCase):
def setUp(self):
self.pos1 = Position(5, 0)
self.pos2 = Position(10, 0)
self.pos3 = Position(9, 3)
self.dir1 = Direction(1, 1)
self.dir2 = Direction(5, 0)... | unittest.main() | conditional_block | |
immutable-array.js | (() => {
'use strict';
const
expect = require('expect'),
deepFreeze = require('deep-freeze'),
immutable = require('../src/immutable-array');
describe('Avoid Array Mutation', () => {
it('addCounter must return new list without mutating the existing list', () => {
const
listBefore =... |
expect(
immutable.addCounter(listBefore)
).toEqual(listAfter);
});
it('removeCounter must return new list without mutating the existing list', () => {
const
listBefore = [0, 10, 20],
listAfter = [0, 20];
deepFreeze(listBefore);
expect(
immutable... | listAfter = [1, 0];
deepFreeze(listBefore); | random_line_split |
cjson-tests.ts | import cjson = require('cjson');
import { decomment, extend, freeze, load, options, parse, replace } from 'cjson';
const paths = ['/path/to/conf.json', '/path/to/conf-prod.json'];
const conf = cjson.load('/path/to/your/config.json'); // ExpectType any
const conf2 = load(['/path/to/your/config1.json', '/path/to/your/c... |
return data[search];
}
return match;
});
};
| {
return JSON.stringify(data[search]);
} | conditional_block |
cjson-tests.ts | import cjson = require('cjson');
import { decomment, extend, freeze, load, options, parse, replace } from 'cjson';
const paths = ['/path/to/conf.json', '/path/to/conf-prod.json'];
const conf = cjson.load('/path/to/your/config.json'); // ExpectType any
const conf2 = load(['/path/to/your/config1.json', '/path/to/your/c... | });
// $ExpectType any
parse('{"1": 1, "2": 2, "3": {"4": 4, "5": {"6": 6}}}', (key, value) => {
return value;
});
cjson.replace(JSON.stringify(conf), { root: '/usr' }); // $ExpectType string
replace(JSON.stringify(conf), { root: '/usr' }); // $ExpectType string
cjson.freeze(conf2); // $ExpectType Readonly<any>
fre... | cjson.extend({}, conf2, conf3); // $ExpectType any
extend({}, conf2, conf3); // $ExpectType any
// $ExpectType any
cjson.parse('{"1": 1, "2": 2, "3": {"4": 4, "5": {"6": 6}}}', (key, value) => {
return value; | random_line_split |
htmlbuttonelement.rs | is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::activation::Activatable;
use dom::attr::Attr;
use dom::bindings::codegen::Bindings::HTMLButtonElementBinding;
use dom::bindings::... |
// https://html.spec.whatwg.org/multipage/#run-canceled-activation-steps
fn canceled_activation(&self) {
}
// https://html.spec.whatwg.org/multipage/#run-post-click-activation-steps
fn activation_behavior(&self, _event: &Event, _target: &EventTarget) {
let ty = self.button_type.get();
... | {
} | identifier_body |
htmlbuttonelement.rs | is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::activation::Activatable;
use dom::attr::Attr;
use dom::bindings::codegen::Bindings::HTMLButtonElementBinding;
use dom::bindings::... | (&self) {
}
// https://html.spec.whatwg.org/multipage/#run-canceled-activation-steps
fn canceled_activation(&self) {
}
// https://html.spec.whatwg.org/multipage/#run-post-click-activation-steps
fn activation_behavior(&self, _event: &Event, _target: &EventTarget) {
let ty = self.button_... | pre_click_activation | identifier_name |
htmlbuttonelement.rs | is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::activation::Activatable;
use dom::attr::Attr;
use dom::bindings::codegen::Bindings::HTMLButtonElementBinding;
use dom::bindings::... | }
// https://html.spec.whatwg.org/multipage/#implicit-submission
#[allow(unsafe_code)]
fn implicit_submission(&self, ctrlKey: bool, shiftKey: bool, altKey: bool, metaKey: bool) {
let doc = document_from_node(*self);
let node = NodeCast::from_ref(doc.r());
let owner = self.form_o... | random_line_split | |
cli.rs | //! Command argument types
//! The deserialized structures of the command args.
#![allow(non_camel_case_types,non_snake_case)]
use core::fmt;
use core::str::FromStr;
use docopt;
use opengl_graphics::OpenGL;
use rustc_serialize::{Decodable,Decoder};
use std::net;
docopt!(pub Args derive Debug,concat!("
Usage: ",PROGR... | (pub net::IpAddr);
impl Decodable for Host{
fn decode<D: Decoder>(d: &mut D) -> Result<Self,D::Error>{
let str = try!(d.read_str());
let str = &*str;
Ok(Host(match net::IpAddr::from_str(str){
Ok(addr) => addr,
Err(_) => try!(try!(try!(
net::lookup_host(str).map_err(|_| d.error("Error when lookup_hos... | Host | identifier_name |
cli.rs | //! Command argument types
//! The deserialized structures of the command args.
#![allow(non_camel_case_types,non_snake_case)]
use core::fmt;
use core::str::FromStr;
use docopt;
use opengl_graphics::OpenGL;
use rustc_serialize::{Decodable,Decoder};
use std::net;
docopt!(pub Args derive Debug,concat!("
Usage: ",PROGR... | impl fmt::Debug for GlVersion{
fn fmt(&self,f: &mut fmt::Formatter) -> fmt::Result{
write!(f,"{}",match self.0{
OpenGL::V2_0 => "v2.0",
OpenGL::V2_1 => "v2.1",
OpenGL::V3_0 => "v3.0",
OpenGL::V3_1 => "v3.1",
OpenGL::V3_2 => "v3.2",
OpenGL::V3_3 => "v3.3",
OpenGL::V4_0 => "v4.0",
OpenGL::V4_1 ... | random_line_split | |
issue-1652.ts | import "reflect-metadata";
import {Connection} from "../../../src/connection/Connection";
import {closeTestingConnections, createTestingConnections} from "../../utils/test-utils";
describe("github issues > #1652 Multiple primary key defined", () => {
let connections: Connection[];
before(async () => {
... | })));
}); | table!.findColumnByName("name")!.isPrimary.should.be.true;
await queryRunner.release();
| random_line_split |
install_uninstall.py | from __future__ import print_function
from __future__ import unicode_literals
import io
import os.path
import pipes
import sys
from pre_commit import output
from pre_commit.util import make_executable
from pre_commit.util import mkdirp
from pre_commit.util import resource_filename
# This is used to identify the hoo... |
elif os.path.exists(legacy_path):
output.write_line(
'Running in migration mode with existing hooks at {}\n'
'Use -f to use only pre-commit.'.format(
legacy_path,
),
)
with io.open(hook_path, 'w') as pre_commit_file_obj:
if hook_type ... | os.remove(legacy_path) | conditional_block |
install_uninstall.py | from __future__ import print_function
from __future__ import unicode_literals
import io
import os.path
import pipes
import sys
from pre_commit import output
from pre_commit.util import make_executable
from pre_commit.util import mkdirp
from pre_commit.util import resource_filename
# This is used to identify the hoo... | (filename):
if not os.path.exists(filename):
return False
contents = io.open(filename).read()
return any(h in contents for h in (CURRENT_HASH,) + PRIOR_HASHES)
def install(
runner, overwrite=False, hooks=False, hook_type='pre-commit',
skip_on_missing_conf=False,
):
"""Install t... | is_our_script | identifier_name |
install_uninstall.py | from __future__ import print_function
from __future__ import unicode_literals
import io
import os.path
import pipes
import sys
from pre_commit import output
from pre_commit.util import make_executable
from pre_commit.util import mkdirp
from pre_commit.util import resource_filename
# This is used to identify the hoo... |
with io.open(hook_path, 'w') as pre_commit_file_obj:
if hook_type == 'pre-push':
with io.open(resource_filename('pre-push-tmpl')) as f:
hook_specific_contents = f.read()
elif hook_type == 'commit-msg':
with io.open(resource_filename('commit-msg-tmpl')) as f:
... | """Install the pre-commit hooks."""
hook_path = runner.get_hook_path(hook_type)
legacy_path = hook_path + '.legacy'
mkdirp(os.path.dirname(hook_path))
# If we have an existing hook, move it to pre-commit.legacy
if os.path.lexists(hook_path) and not is_our_script(hook_path):
os.rename(hook_... | identifier_body |
install_uninstall.py | from __future__ import print_function
from __future__ import unicode_literals
import io
import os.path
import pipes
import sys
from pre_commit import output
from pre_commit.util import make_executable
from pre_commit.util import mkdirp
from pre_commit.util import resource_filename
# This is used to identify the hoo... | elif os.path.exists(legacy_path):
output.write_line(
'Running in migration mode with existing hooks at {}\n'
'Use -f to use only pre-commit.'.format(
legacy_path,
),
)
with io.open(hook_path, 'w') as pre_commit_file_obj:
if hook_type =... | os.remove(legacy_path) | random_line_split |
75.py | from qiita_db.user import User
from json import loads, dumps
from qiita_core.qiita_settings import r_client
from qiita_db.sql_connection import TRN
from qiita_db.software import Software, Command
from qiita_db.exceptions import QiitaDBError, QiitaDBDuplicateError
from qiita_db.util import convert_to_id
# one of the ... | ('choice', 'mchoice', 'artifact')):
supported_types.extend(['choice', 'mchoice', 'artifact'])
raise QiitaDBError(
"Unsupported parameters type '%s' for parameter %s. "
"Supported types are: %s"
% (ptype, pname, ', '.join(supported_t... | r"""Replicates the Command.create code at the time the patch was written"""
# Perform some sanity checks in the parameters dictionary
if not parameters:
raise QiitaDBError(
"Error creating command %s. At least one parameter should "
"be provided." % name)
sql_param_values = [... | identifier_body |
75.py | from qiita_db.user import User
from json import loads, dumps
from qiita_core.qiita_settings import r_client
from qiita_db.sql_connection import TRN
from qiita_db.software import Software, Command
from qiita_db.exceptions import QiitaDBError, QiitaDBDuplicateError
from qiita_db.util import convert_to_id
# one of the ... | (software, name, description, parameters, outputs=None,
analysis_only=False):
r"""Replicates the Command.create code at the time the patch was written"""
# Perform some sanity checks in the parameters dictionary
if not parameters:
raise QiitaDBError(
"Error creating co... | create_command | identifier_name |
75.py | from qiita_db.user import User
from json import loads, dumps
from qiita_core.qiita_settings import r_client
from qiita_db.sql_connection import TRN
from qiita_db.software import Software, Command
from qiita_db.exceptions import QiitaDBError, QiitaDBDuplicateError
from qiita_db.util import convert_to_id
# one of the ... |
# If the software type is 'artifact definition', there are a couple
# of extra steps
if software.type == 'artifact definition':
# If supported types is not empty, link the software with these
# types
if supported_types:
sql = """INSERT INTO q... | sql_params = [c_id, pname, p_type, True, None]
TRN.add(sql, sql_params)
pid = TRN.execute_fetchlast()
sql_params = [[pid, convert_to_id(at, 'artifact_type')]
for at in atypes]
TRN.add(sql_type, sql_params, many=True)
supported_types.e... | conditional_block |
75.py | from qiita_db.user import User
from json import loads, dumps
from qiita_core.qiita_settings import r_client
from qiita_db.sql_connection import TRN
from qiita_db.software import Software, Command
from qiita_db.exceptions import QiitaDBError, QiitaDBDuplicateError
from qiita_db.util import convert_to_id
# one of the ... | % (software.id, name))
# Add the command to the DB
sql = """INSERT INTO qiita.software_command
(name, software_id, description, is_analysis)
VALUES (%s, %s, %s, %s)
RETURNING command_id"""
sql_params = [name, so... | "command", "software: %d, name: %s" | random_line_split |
test_cargo_publish.rs | use std::io::prelude::*;
use std::fs::{self, File};
use std::io::{Cursor, SeekFrom};
use std::path::PathBuf;
use flate2::read::GzDecoder;
use tar::Archive;
use url::Url;
use support::{project, execs};
use support::{UPDATING, PACKAGING, UPLOADING};
use support::paths;
use support::git::repo;
use hamcrest::assert_that... |
fn upload() -> Url { Url::from_file_path(&*upload_path()).ok().unwrap() }
fn setup() {
let config = paths::root().join(".cargo/config");
fs::create_dir_all(config.parent().unwrap()).unwrap();
File::create(&config).unwrap().write_all(&format!(r#"
[registry]
index = "{reg}"
t... | { paths::root().join("upload") } | identifier_body |
test_cargo_publish.rs | use std::io::prelude::*;
use std::fs::{self, File};
use std::io::{Cursor, SeekFrom};
use std::path::PathBuf;
use flate2::read::GzDecoder;
use tar::Archive;
use url::Url; | use support::git::repo;
use hamcrest::assert_that;
fn registry_path() -> PathBuf { paths::root().join("registry") }
fn registry() -> Url { Url::from_file_path(&*registry_path()).ok().unwrap() }
fn upload_path() -> PathBuf { paths::root().join("upload") }
fn upload() -> Url { Url::from_file_path(&*upload_path()).ok().... |
use support::{project, execs};
use support::{UPDATING, PACKAGING, UPLOADING};
use support::paths; | random_line_split |
test_cargo_publish.rs | use std::io::prelude::*;
use std::fs::{self, File};
use std::io::{Cursor, SeekFrom};
use std::path::PathBuf;
use flate2::read::GzDecoder;
use tar::Archive;
use url::Url;
use support::{project, execs};
use support::{UPDATING, PACKAGING, UPLOADING};
use support::paths;
use support::git::repo;
use hamcrest::assert_that... | () -> Url { Url::from_file_path(&*upload_path()).ok().unwrap() }
fn setup() {
let config = paths::root().join(".cargo/config");
fs::create_dir_all(config.parent().unwrap()).unwrap();
File::create(&config).unwrap().write_all(&format!(r#"
[registry]
index = "{reg}"
token = "ap... | upload | identifier_name |
no-shadow.js | /**
* @fileoverview Rule to flag on declaring variables already declared in the outer scope
* @author Ilya Volodin
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
let ... | (variable) {
let def = variable.defs[0];
return def && def.name.range;
}
/**
* Checks if a variable is in TDZ of scopeVar.
* @param {Object} variable The variable to check.
* @param {Object} scopeVar The variable of TDZ.
* @returns {boolean} ... | getNameRange | identifier_name |
no-shadow.js | /**
* @fileoverview Rule to flag on declaring variables already declared in the outer scope
* @author Ilya Volodin
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
let ... |
create: function(context) {
let options = {
builtinGlobals: Boolean(context.options[0] && context.options[0].builtinGlobals),
hoist: (context.options[0] && context.options[0].hoist) || "functions",
allow: (context.options[0] && context.options[0].allow) || []
};... | random_line_split | |
no-shadow.js | /**
* @fileoverview Rule to flag on declaring variables already declared in the outer scope
* @author Ilya Volodin
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
let ... |
/**
* Checks if a variable is inside the initializer of scopeVar.
*
* To avoid reporting at declarations such as `var a = function a() {};`.
* But it should report `var a = function(a) {};` or `var a = function() { function a() {} };`.
*
* @param {Object} ... | {
let block = variable.scope.block;
return block.type === "ClassDeclaration" && block.id === variable.identifiers[0];
} | identifier_body |
no-shadow.js | /**
* @fileoverview Rule to flag on declaring variables already declared in the outer scope
* @author Ilya Volodin
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
let ... |
}
};
}
};
| {
scope = stack.pop();
stack.push.apply(stack, scope.childScopes);
checkForShadows(scope);
} | conditional_block |
textui_prompt_test.py | #
# $Id: build_ansi.py 9736 2011-06-20 16:49:22Z ahartvigsen $
#
# Proprietary and confidential.
# Copyright $Date:: 2011#$ Perfect Search Corporation.
# All rights reserved.
#
import unittest, os, sys, StringIO
from textui.prompt import *
from nose.tools import istest, nottest
from nose.plugins.attrib import... |
tr = unittest.TextTestRunner()
result = tr.run(suite)
sys.exit(int(not result.wasSuccessful()))
| suite = tl.loadTestsFromTestCase(AutomatedPromptTest) | conditional_block |
textui_prompt_test.py | #
# $Id: build_ansi.py 9736 2011-06-20 16:49:22Z ahartvigsen $
#
# Proprietary and confidential.
# Copyright $Date:: 2011#$ Perfect Search Corporation.
# All rights reserved.
#
import unittest, os, sys, StringIO
from textui.prompt import *
from nose.tools import istest, nottest
from nose.plugins.attrib import... |
def test_prompt(self):
self.explain('''
Answer the following question with at least a few chars. If the prompt()
function is working, we should see a non-empty answer.
''')
self.stuff('to seek the holy grail\n')
answer = prompt('What is your quest?')
self.assertTrue(answer)
... | global _explained
if not _explained:
print('''
INTERACTIVE TEST -- PLEASE FOLLOW INSTRUCTIONS
This test checks our ability to user input correctly. It depends on you typing
some simple responses. It is not particularly sensitive to typos, but you
should NOT just press Enter to get through th... | identifier_body |
textui_prompt_test.py | #
# $Id: build_ansi.py 9736 2011-06-20 16:49:22Z ahartvigsen $
#
# Proprietary and confidential.
# Copyright $Date:: 2011#$ Perfect Search Corporation.
# All rights reserved.
#
import unittest, os, sys, StringIO
from textui.prompt import *
from nose.tools import istest, nottest
from nose.plugins.attrib import... | (self):
self.explain('''
This test checks to see whether we can prompt for a password without displaying
what you type.
''')
answer = prompt('Type an imaginary password:', readline=readline_masked)
self.assertTrue(prompt_bool('Were your keystrokes masked out?'))
def test_prompt_enter(... | test_prompt_masked | identifier_name |
textui_prompt_test.py | #
# $Id: build_ansi.py 9736 2011-06-20 16:49:22Z ahartvigsen $
#
# Proprietary and confidential.
# Copyright $Date:: 2011#$ Perfect Search Corporation.
# All rights reserved.
#
import unittest, os, sys, StringIO
from textui.prompt import *
from nose.tools import istest, nottest
from nose.plugins.attrib import... | def tearDown(self):
sys.stdout = self.stdout
sys.stdin = self.stdin
def test_prompt_masked(self):
# getch can't be automatically overridden without side effects
pass
if __name__ == '__main__':
tl = unittest.TestLoader()
if '--interactive' in sys.argv:
s... | self.stdin = sys.stdin
sys.stdin = StringIO.StringIO()
| random_line_split |
suback.rs | use std::io::{self, Read, Write};
use std::error::Error;
use std::fmt;
use std::convert::From;
use byteorder::{self, WriteBytesExt, ReadBytesExt};
use control::{FixedHeader, PacketType, ControlType};
use control::variable_header::PacketIdentifier;
use packet::{Packet, PacketError};
use {Encodable, Decodable};
#[repr... | (&self) -> &[SubscribeReturnCode] {
&self.subscribes[..]
}
}
impl<'a> Encodable<'a> for SubackPacketPayload {
type Err = SubackPacketPayloadError;
fn encode<W: Write>(&self, writer: &mut W) -> Result<(), Self::Err> {
for code in self.subscribes.iter() {
try!(writer.write_u8(*co... | subscribes | identifier_name |
suback.rs | use std::io::{self, Read, Write};
use std::error::Error;
use std::fmt;
use std::convert::From;
use byteorder::{self, WriteBytesExt, ReadBytesExt};
use control::{FixedHeader, PacketType, ControlType};
use control::variable_header::PacketIdentifier;
use packet::{Packet, PacketError};
use {Encodable, Decodable};
#[repr... |
fn encoded_variable_headers_length(&self) -> u32 {
self.packet_identifier.encoded_length()
}
fn decode_packet<R: Read>(reader: &mut R, fixed_header: FixedHeader) -> Result<Self, PacketError<'a, Self>> {
let packet_identifier: PacketIdentifier = try!(PacketIdentifier::decode(reader));
... | {
try!(self.packet_identifier.encode(writer));
Ok(())
} | identifier_body |
suback.rs | use std::io::{self, Read, Write};
use std::error::Error;
use std::fmt;
use std::convert::From;
use byteorder::{self, WriteBytesExt, ReadBytesExt};
use control::{FixedHeader, PacketType, ControlType};
use control::variable_header::PacketIdentifier;
use packet::{Packet, PacketError};
use {Encodable, Decodable};
#[repr... | match self {
&SubackPacketPayloadError::IoError(ref err) => err.description(),
&SubackPacketPayloadError::InvalidSubscribeReturnCode(..) => "Invalid subscribe return code",
}
}
fn cause(&self) -> Option<&Error> {
match self {
&SubackPacketPayloadError... | fn description(&self) -> &str { | random_line_split |
ServerGroupSecurityGroups.tsx | import React from 'react';
import { FormikProps } from 'formik';
import { IWizardPageComponent } from '@spinnaker/core';
import { SecurityGroupSelector } from '../securityGroups/SecurityGroupSelector';
import { IAmazonServerGroupCommand } from '../../serverGroupConfiguration.service';
import { ServerGroupSecurityGroup... | <ServerGroupSecurityGroupsRemoved command={values} onClear={this.acknowledgeRemovedGroups} />
<SecurityGroupSelector
command={values}
availableGroups={values.backingData.filtered.securityGroups}
groupsToEdit={values.securityGroups}
onChange={this.onChange}
... | random_line_split | |
ServerGroupSecurityGroups.tsx | import React from 'react';
import { FormikProps } from 'formik';
import { IWizardPageComponent } from '@spinnaker/core';
import { SecurityGroupSelector } from '../securityGroups/SecurityGroupSelector';
import { IAmazonServerGroupCommand } from '../../serverGroupConfiguration.service';
import { ServerGroupSecurityGroup... |
return errors;
}
private onChange = (securityGroups: string[]) => {
this.props.formik.setFieldValue('securityGroups', securityGroups);
};
private acknowledgeRemovedGroups = () => {
const { viewState } = this.props.formik.values;
viewState.dirty.securityGroups = null;
this.props.formik.se... | {
errors.securityGroups = 'You must acknowledge removed security groups.';
} | conditional_block |
ServerGroupSecurityGroups.tsx | import React from 'react';
import { FormikProps } from 'formik';
import { IWizardPageComponent } from '@spinnaker/core';
import { SecurityGroupSelector } from '../securityGroups/SecurityGroupSelector';
import { IAmazonServerGroupCommand } from '../../serverGroupConfiguration.service';
import { ServerGroupSecurityGroup... | (values: IAmazonServerGroupCommand) {
const errors = {} as any;
if (values.viewState.dirty.securityGroups) {
errors.securityGroups = 'You must acknowledge removed security groups.';
}
return errors;
}
private onChange = (securityGroups: string[]) => {
this.props.formik.setFieldValue('se... | validate | identifier_name |
routes.js | var debug = require('debug')('keystone:core:routes');
/**
* Adds bindings for the keystone routes
*
* ####Example:
*
* var app = express();
* app.use(...); // middleware, routes, etc. should come before keystone is initialised
* keystone.routes(app);
*
* @param {Express()} app
* @api public
*/
f... |
debug('setting keystone Admin Route');
app.all('/keystone', require('../../admin/routes/home'));
// Email test routes
if (this.get('email tests')) {
debug('setting email test routes');
this.bindEmailTestRoutes(app, this.get('email tests'));
}
// Cloudinary API for selecting an existing image / upload a ne... | {
return function(req, res, next) {
req.list = keystone.list(req.params.list);
if (!req.list || (respectHiddenOption && req.list.get('hidden'))) {
debug('could not find list ', req.params.list);
req.flash('error', 'List ' + req.params.list + ' could not be found.');
return res.redirect('/keystone')... | identifier_body |
routes.js | var debug = require('debug')('keystone:core:routes');
/**
* Adds bindings for the keystone routes
*
* ####Example:
*
* var app = express();
* app.use(...); // middleware, routes, etc. should come before keystone is initialised
* keystone.routes(app);
*
* @param {Express()} app
* @api public
*/
f... | app.all('/keystone*', this.get('auth'));
}
function initList(respectHiddenOption) {
return function(req, res, next) {
req.list = keystone.list(req.params.list);
if (!req.list || (respectHiddenOption && req.list.get('hidden'))) {
debug('could not find list ', req.params.list);
req.flash('error', 'L... | }
app.all('/keystone/signin', require('../../admin/routes/signin'));
app.all('/keystone/signout', require('../../admin/routes/signout'));
app.all('/keystone*', this.session.keystoneAuth);
} else if ('function' === typeof this.get('auth')) { | random_line_split |
routes.js | var debug = require('debug')('keystone:core:routes');
/**
* Adds bindings for the keystone routes
*
* ####Example:
*
* var app = express();
* app.use(...); // middleware, routes, etc. should come before keystone is initialised
* keystone.routes(app);
*
* @param {Express()} app
* @api public
*/
f... |
res.status(statusCode);
res.json({ err: err, key: key });
};
next();
});
// Generic Lists API
app.all('/keystone/api/counts', require('../../admin/api/counts'));
app.all('/keystone/api/:list/:action(autocomplete|order|create|fetch)', initList(), require('../../admin/api/list'));
app.post('/keystone/api... | {
err = err.message;
} | conditional_block |
routes.js | var debug = require('debug')('keystone:core:routes');
/**
* Adds bindings for the keystone routes
*
* ####Example:
*
* var app = express();
* app.use(...); // middleware, routes, etc. should come before keystone is initialised
* keystone.routes(app);
*
* @param {Express()} app
* @api public
*/
f... | (app) {
this.app = app;
var keystone = this;
// ensure keystone nav has been initialised
if (!this.nav) {
debug('setting up nav');
this.nav = this.initNav();
}
// Cache compiled view templates if we are in Production mode
this.set('view cache', this.get('env') === 'production');
// Session API
// TODO: ... | routes | identifier_name |
details_dialog.py | # Created By: Virgil Dupras
# Created On: 2010-02-05
# Copyright 2015 Hardcoded Software (http://www.hardcoded.net)
#
# This software is licensed under the "GPLv3" License as described in the "LICENSE" file, | # which should be included with this package. The terms are also available at
# http://www.gnu.org/licenses/gpl-3.0.html
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QDialog
from .details_table import DetailsModel
class DetailsDialog(QDialog):
def __init__(self, parent, app, **kwargs):
super(... | random_line_split | |
details_dialog.py | # Created By: Virgil Dupras
# Created On: 2010-02-05
# Copyright 2015 Hardcoded Software (http://www.hardcoded.net)
#
# This software is licensed under the "GPLv3" License as described in the "LICENSE" file,
# which should be included with this package. The terms are also available at
# http://www.gnu.org/licenses/g... | self._shown_once = True
super().show()
#--- Events
def appWillSavePrefs(self):
if self._shown_once:
self.app.prefs.saveGeometry('DetailsWindowRect', self)
#--- model --> view
def refresh(self):
self.tableModel.beginResetModel()
self.tableModel.en... | def __init__(self, parent, app, **kwargs):
super().__init__(parent, Qt.Tool, **kwargs)
self.app = app
self.model = app.model.details_panel
self._setupUi()
# To avoid saving uninitialized geometry on appWillSavePrefs, we track whether our dialog
# has been shown. If it has... | identifier_body |
details_dialog.py | # Created By: Virgil Dupras
# Created On: 2010-02-05
# Copyright 2015 Hardcoded Software (http://www.hardcoded.net)
#
# This software is licensed under the "GPLv3" License as described in the "LICENSE" file,
# which should be included with this package. The terms are also available at
# http://www.gnu.org/licenses/g... | (self): # Virtual
pass
def show(self):
self._shown_once = True
super().show()
#--- Events
def appWillSavePrefs(self):
if self._shown_once:
self.app.prefs.saveGeometry('DetailsWindowRect', self)
#--- model --> view
def refresh(self):
self... | _setupUi | identifier_name |
details_dialog.py | # Created By: Virgil Dupras
# Created On: 2010-02-05
# Copyright 2015 Hardcoded Software (http://www.hardcoded.net)
#
# This software is licensed under the "GPLv3" License as described in the "LICENSE" file,
# which should be included with this package. The terms are also available at
# http://www.gnu.org/licenses/g... |
#--- model --> view
def refresh(self):
self.tableModel.beginResetModel()
self.tableModel.endResetModel()
| self.app.prefs.saveGeometry('DetailsWindowRect', self) | conditional_block |
test_sound_formats.py | import sys
from unittest import TestCase, expectedFailure, skipIf
import pygame
from pgzero.loaders import sounds, set_root, UnsupportedFormat
pygame.init()
class SoundFormatsTest(TestCase):
"""Test that sound formats we cannot open show an appropriate message."""
@classmethod
def setUpClass(s... | self):
self.assert_errmsg('wav8kmp316', 'WAV audio encoded as MP3')
@skipIf(sys.platform == "win32", "This will crash on Windows")
def test_load_8kmp38(self):
self.assert_errmsg('wav8kmp38', 'WAV audio encoded as MP3')
def test_load_vorbis1(self):
"""Load OGG Vorbis with .o... | est_load_8kmp316( | identifier_name |
test_sound_formats.py | import sys
from unittest import TestCase, expectedFailure, skipIf
import pygame
from pgzero.loaders import sounds, set_root, UnsupportedFormat
pygame.init()
class SoundFormatsTest(TestCase):
| self.assert_loadable('wav22k8bitpcm')
def test_load_22kadpcm(self):
self.assert_loadable('wav22kadpcm')
@expectedFailure # See issue #22 - 8Khz files don't open correctly
def test_load_8k16bitpcm(self):
self.assert_loadable('wav8k16bitpcm')
@expectedFailure # See is... | """Test that sound formats we cannot open show an appropriate message."""
@classmethod
def setUpClass(self):
set_root(__file__)
def assert_loadable(self, name):
s = sounds.load(name)
l = s.get_length()
assert 0.85 < l < 1.0, \
"Failed to correctly load... | identifier_body |
test_sound_formats.py | import sys
from unittest import TestCase, expectedFailure, skipIf
import pygame
from pgzero.loaders import sounds, set_root, UnsupportedFormat
pygame.init()
class SoundFormatsTest(TestCase):
"""Test that sound formats we cannot open show an appropriate message."""
@classmethod
def setUpClass(s... | self.assert_errmsg('wav8kmp316', 'WAV audio encoded as MP3')
@skipIf(sys.platform == "win32", "This will crash on Windows")
def test_load_8kmp38(self):
self.assert_errmsg('wav8kmp38', 'WAV audio encoded as MP3')
def test_load_vorbis1(self):
"""Load OGG Vorbis with .ogg exten... | self.assert_errmsg('wav22kulaw', 'WAV audio encoded as .* µ-law')
@skipIf(sys.platform == "win32", "This will crash on Windows")
def test_load_8kmp316(self):
| random_line_split |
sqlite.rs | /*
* database/handle.rs
*
* markov-music - A music player that uses Markov chains to choose songs
* Copyright (c) 2017-2018 Ammon Smith
*
* markov-music 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, ... | {
conn: SqliteConnection,
}
impl SqliteDatabase {
pub fn new<S: AsRef<str>>(url: S) -> Result<Self> {
let conn = SqliteConnection::establish(url.as_ref())?;
Ok(SqliteDatabase { conn: conn })
}
}
impl Database for SqliteDatabase {
type Error = Error;
fn modify_weight(
&mut... | SqliteDatabase | identifier_name |
sqlite.rs | /*
* database/handle.rs
*
* markov-music - A music player that uses Markov chains to choose songs
* Copyright (c) 2017-2018 Ammon Smith
*
* markov-music 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, ... | Ok(())
})
}
fn clear(&mut self, song: &str) -> Result<()> {
self.conn.transaction::<(), Error, _>(|| {
use self::associations::dsl;
diesel::delete(associations::table.filter(dsl::song.eq(song)))
.execute(&self.conn)?;
Ok(())
... | diesel::replace_into(starters::table)
.values(&[new_assoc])
.execute(&self.conn)?;
| random_line_split |
sqlite.rs | /*
* database/handle.rs
*
* markov-music - A music player that uses Markov chains to choose songs
* Copyright (c) 2017-2018 Ammon Smith
*
* markov-music 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, ... | Ok(())
})
}
fn clear(&mut self, song: &str) -> Result<()> {
self.conn.transaction::<(), Error, _>(|| {
use self::associations::dsl;
diesel::delete(associations::table.filter(dsl::song.eq(song)))
.execute(&self.conn)?;
Ok(())
... | {
self.conn.transaction::<(), Error, _>(|| {
use self::associations::dsl;
let row = associations::table
.find((song, next))
.first::<Association>(&self.conn)
.optional()?;
let weight = row.map(|assoc| assoc.weight).unwrap_or(0... | identifier_body |
GeoJSON.js | /*
* L.GeoJSON turns any GeoJSON data into a Leaflet layer.
*/
L.GeoJSON = L.FeatureGroup.extend({
initialize: function (geojson, options) {
L.setOptions(this, options);
this._layers = {};
if (geojson) {
this.addData(geojson);
}
},
addData: function (geojson) {
var features = L.U... |
}
});
L.extend(L.GeoJSON, {
geometryToLayer: function (geojson, options) {
var geometry = geojson.type === 'Feature' ? geojson.geometry : geojson,
coords = geometry.coordinates,
layers = [],
coordsToLatLng = options.coordsToLatLng || this.coordsToLatLng,
latlng, latlngs, i, len;
... | {
layer.setStyle(style);
} | conditional_block |
GeoJSON.js | /*
* L.GeoJSON turns any GeoJSON data into a Leaflet layer.
*/
L.GeoJSON = L.FeatureGroup.extend({
initialize: function (geojson, options) {
L.setOptions(this, options);
this._layers = {};
if (geojson) {
this.addData(geojson);
}
},
addData: function (geojson) {
var features = L.U... | }
});
if (isGeometryCollection) {
return L.GeoJSON.getFeature(this, {
geometries: jsons,
type: 'GeometryCollection'
});
}
return {
type: 'FeatureCollection',
features: jsons
};
}
});
L.geoJson = function (geojson, options) {
return new L.GeoJSON(geojson, options);... | var json = layer.toGeoJSON();
jsons.push(isGeometryCollection ? json.geometry : L.GeoJSON.asFeature(json));
| random_line_split |
local-inlining-but-not-all.rs | //
// We specify incremental here because we want to test the partitioning for
// incremental compilation
// incremental
// compile-flags:-Zprint-mono-items=lazy
// compile-flags:-Zinline-in-all-cgus=no
#![allow(dead_code)]
#![crate_type="lib"]
mod inline {
//~ MONO_ITEM fn inline::inlined_function @@ local_inli... |
}
pub mod user1 {
use super::inline;
//~ MONO_ITEM fn user1::foo @@ local_inlining_but_not_all-user1[External]
pub fn foo() {
inline::inlined_function();
}
}
pub mod user2 {
use super::inline;
//~ MONO_ITEM fn user2::bar @@ local_inlining_but_not_all-user2[External]
pub fn bar()... | {
} | identifier_body |
local-inlining-but-not-all.rs | //
// We specify incremental here because we want to test the partitioning for
// incremental compilation | #![allow(dead_code)]
#![crate_type="lib"]
mod inline {
//~ MONO_ITEM fn inline::inlined_function @@ local_inlining_but_not_all-inline[External]
#[inline]
pub fn inlined_function()
{
}
}
pub mod user1 {
use super::inline;
//~ MONO_ITEM fn user1::foo @@ local_inlining_but_not_all-user1[Ex... | // incremental
// compile-flags:-Zprint-mono-items=lazy
// compile-flags:-Zinline-in-all-cgus=no
| random_line_split |
local-inlining-but-not-all.rs | //
// We specify incremental here because we want to test the partitioning for
// incremental compilation
// incremental
// compile-flags:-Zprint-mono-items=lazy
// compile-flags:-Zinline-in-all-cgus=no
#![allow(dead_code)]
#![crate_type="lib"]
mod inline {
//~ MONO_ITEM fn inline::inlined_function @@ local_inli... | ()
{
}
}
pub mod user1 {
use super::inline;
//~ MONO_ITEM fn user1::foo @@ local_inlining_but_not_all-user1[External]
pub fn foo() {
inline::inlined_function();
}
}
pub mod user2 {
use super::inline;
//~ MONO_ITEM fn user2::bar @@ local_inlining_but_not_all-user2[External]
... | inlined_function | identifier_name |
types.ts | import BigNumber from 'bignumber.js'
import Bristle from './sweep.js'
export interface EthereumTransaction {
to: string
from: string
value: any
gas: number
hash: number
contractAddress?: string
}
export interface Block {
transactions: EthereumTransaction[]
}
export interface AddressManager {
hasAddre... | export interface GenericEthereumManager<EthereumTransaction> extends AddressManager {
saveTransaction(transaction: EthereumTransaction, blockIndex: number)
getLastBlock(): Promise<number>
setLastBlock(lastblock: number): Promise<void>
getResolvedTransactions(confirmedBlockNumber: number): Promise<EthereumTransa... | random_line_split | |
param_utils.py | .services.keyvalues import KeyValueLookup
from st2common.util.casts import get_cast
from st2common.util.compat import to_unicode
LOG = logging.getLogger(__name__)
__all__ = [
'get_resolved_params',
'get_rendered_params',
'get_finalized_params',
]
def _split_params(runner_parameters, action_parameters, ... |
dep_chain = []
dep_chain.append(k)
if not _check_cyclic(dep_chain, dependencies):
msg = 'Cyclic dependecy found - %s.' % dep_chain
raise actionrunner.ActionRunnerException(msg)
def _do_render_params(renderable_params, context):
'''
Will render the params per th... | msg = 'Dependecy unsatisfied - %s: %s.' % (k, v)
raise actionrunner.ActionRunnerException(msg) | conditional_block |
param_utils.py | .services.keyvalues import KeyValueLookup
from st2common.util.casts import get_cast
from st2common.util.compat import to_unicode
LOG = logging.getLogger(__name__)
__all__ = [
'get_resolved_params',
'get_rendered_params',
'get_finalized_params',
]
def _split_params(runner_parameters, action_parameters, ... |
def _validate_dependencies(renderable_params, context):
'''
Validates dependencies between the parameters.
e.g.
{
'a': '{{b}}',
'b': '{{a}}'
}
In this example 'a' requires 'b' for template rendering and vice-versa. There is no way for
these templates to be rendered and wil... | last_idx = len(dep_chain) - 1
last_value = dep_chain[last_idx]
for dependency in dependencies.get(last_value, []):
if dependency in dep_chain:
dep_chain.append(dependency)
return False
dep_chain.append(dependency)
if not _check_cyclic(dep_chain, dependencies):
... | identifier_body |
param_utils.py | .services.keyvalues import KeyValueLookup
from st2common.util.casts import get_cast
from st2common.util.compat import to_unicode
LOG = logging.getLogger(__name__)
__all__ = [
'get_resolved_params',
'get_rendered_params',
'get_finalized_params',
]
def _split_params(runner_parameters, action_parameters, ... | rendered_params[k] = rendered
if k in parameter_render_exceptions:
del parameter_render_exceptions[k]
except Exception as e:
# Note: This sucks, but because we support multi level and out of order
# rendering, we can't thro... | template = env.from_string(v)
try:
rendered = template.render(rendered_params) | random_line_split |
param_utils.py | .services.keyvalues import KeyValueLookup
from st2common.util.casts import get_cast
from st2common.util.compat import to_unicode
LOG = logging.getLogger(__name__)
__all__ = [
'get_resolved_params',
'get_rendered_params',
'get_finalized_params',
]
def _split_params(runner_parameters, action_parameters, ... | (action_parameters, runner_parameters, base_context=None):
# To render the params it is necessary to combine the params together so that cross
# parameter category references are resolved.
renderable_params = {}
# shallow copy since this will be updated
context_params = copy.copy(base_context) if ba... | _renderable_context_param_split | identifier_name |
helper.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
help_txt = """
:help, show this help menu. :help [command] for detail
:dict [word], only find translation on dict.cn
:google [sentence], only find translation on google api
:lan2lan [sentence], translate from one language to another language
:add [word], add new word to yo... | """
help_google = """
help on google:
[usage] :google word
[intro] translate your word only use google api
[eg] :google google is a bitch
more on http://mardict.appspot.com/help/#google
"""
help_lan2lan = """
help on lan2lan:
[usage] :lan2lan word
[intro] translate from one language to another language by google tra... | random_line_split | |
compile_query.ts | import {isPresent, isBlank} from 'angular2/src/facade/lang';
import {ListWrapper} from 'angular2/src/facade/collection';
import * as o from '../output/output_ast';
import {Identifiers} from '../identifiers';
import {
CompileQueryMetadata,
CompileIdentifierMetadata,
CompileTokenMap
} from '../compile_metadata';
... |
}
function createQueryValues(viewValues: ViewQueryValues): o.Expression[] {
return ListWrapper.flatten(viewValues.values.map((entry) => {
if (entry instanceof ViewQueryValues) {
return mapNestedViews(entry.view.declarationElement.appElement, entry.view,
createQueryValues(entry)... | {
var values = createQueryValues(this._values);
var updateStmts = [this.queryList.callMethod('reset', [o.literalArr(values)]).toStmt()];
if (isPresent(this.ownerDirectiveExpression)) {
var valueExpr = this.meta.first ? this.queryList.prop('first') : this.queryList;
updateStmts.push(
th... | identifier_body |
compile_query.ts | import {isPresent, isBlank} from 'angular2/src/facade/lang';
import {ListWrapper} from 'angular2/src/facade/collection';
import * as o from '../output/output_ast';
import {Identifiers} from '../identifiers';
import {
CompileQueryMetadata,
CompileIdentifierMetadata,
CompileTokenMap
} from '../compile_metadata';
... |
var queryListForDirtyExpr = getPropertyInView(this.queryList, view, this.view);
var viewValues = this._values;
elPath.forEach((el) => {
var last =
viewValues.values.length > 0 ? viewValues.values[viewValues.values.length - 1] : null;
if (last instanceof ViewQueryValues && last.view =... | {
var parentEl = currentView.declarationElement;
elPath.unshift(parentEl);
currentView = parentEl.view;
} | conditional_block |
compile_query.ts | import {isPresent, isBlank} from 'angular2/src/facade/lang';
import {ListWrapper} from 'angular2/src/facade/collection';
import * as o from '../output/output_ast';
import {Identifiers} from '../identifiers';
import {
CompileQueryMetadata,
CompileIdentifierMetadata,
CompileTokenMap
} from '../compile_metadata';
... | (targetMethod: CompileMethod) {
var values = createQueryValues(this._values);
var updateStmts = [this.queryList.callMethod('reset', [o.literalArr(values)]).toStmt()];
if (isPresent(this.ownerDirectiveExpression)) {
var valueExpr = this.meta.first ? this.queryList.prop('first') : this.queryList;
... | afterChildren | identifier_name |
compile_query.ts | import {isPresent, isBlank} from 'angular2/src/facade/lang';
import {ListWrapper} from 'angular2/src/facade/collection';
import * as o from '../output/output_ast';
import {Identifiers} from '../identifiers';
import {
CompileQueryMetadata,
CompileIdentifierMetadata,
CompileTokenMap
} from '../compile_metadata';
... | var values = createQueryValues(this._values);
var updateStmts = [this.queryList.callMethod('reset', [o.literalArr(values)]).toStmt()];
if (isPresent(this.ownerDirectiveExpression)) {
var valueExpr = this.meta.first ? this.queryList.prop('first') : this.queryList;
updateStmts.push(
this... | afterChildren(targetMethod: CompileMethod) { | random_line_split |
sensor_legacy.py | """Support for Nest Thermostat sensors for the legacy API."""
import logging
from homeassistant.const import (
CONF_MONITORED_CONDITIONS,
DEVICE_CLASS_HUMIDITY,
DEVICE_CLASS_TEMPERATURE,
PERCENTAGE,
STATE_OFF,
TEMP_CELSIUS,
TEMP_FAHRENHEIT,
)
from . import CONF_SENSORS, DATA_NEST, DATA_NES... |
class NestTempSensor(NestSensorDevice):
"""Representation of a Nest Temperature sensor."""
@property
def state(self):
"""Return the state of the sensor."""
return self._state
@property
def device_class(self):
"""Return the device class of the sensor."""
return DE... | """Retrieve latest state."""
self._unit = SENSOR_UNITS.get(self.variable)
if self.variable in VARIABLE_NAME_MAPPING:
self._state = getattr(self.device, VARIABLE_NAME_MAPPING[self.variable])
elif self.variable in VALUE_MAPPING:
state = getattr(self.device, self.variable)
... | identifier_body |
sensor_legacy.py | """Support for Nest Thermostat sensors for the legacy API."""
import logging
from homeassistant.const import (
CONF_MONITORED_CONDITIONS,
DEVICE_CLASS_HUMIDITY,
DEVICE_CLASS_TEMPERATURE,
PERCENTAGE,
STATE_OFF,
TEMP_CELSIUS,
TEMP_FAHRENHEIT,
)
from . import CONF_SENSORS, DATA_NEST, DATA_NES... |
elif self.variable in PROTECT_SENSOR_TYPES and self.variable != "color_status":
# keep backward compatibility
state = getattr(self.device, self.variable)
self._state = state.capitalize() if state is not None else None
else:
self._state = getattr(self.devi... | state = getattr(self.device, self.variable)
self._state = VALUE_MAPPING[self.variable].get(state, state) | conditional_block |
sensor_legacy.py | """Support for Nest Thermostat sensors for the legacy API."""
import logging
from homeassistant.const import (
CONF_MONITORED_CONDITIONS,
DEVICE_CLASS_HUMIDITY,
DEVICE_CLASS_TEMPERATURE,
PERCENTAGE,
STATE_OFF,
TEMP_CELSIUS,
TEMP_FAHRENHEIT,
)
from . import CONF_SENSORS, DATA_NEST, DATA_NES... | (self):
"""Retrieve latest state."""
self._unit = SENSOR_UNITS.get(self.variable)
if self.variable in VARIABLE_NAME_MAPPING:
self._state = getattr(self.device, VARIABLE_NAME_MAPPING[self.variable])
elif self.variable in VALUE_MAPPING:
state = getattr(self.device,... | update | identifier_name |
sensor_legacy.py | """Support for Nest Thermostat sensors for the legacy API."""
import logging
from homeassistant.const import (
CONF_MONITORED_CONDITIONS,
DEVICE_CLASS_HUMIDITY,
DEVICE_CLASS_TEMPERATURE,
PERCENTAGE,
STATE_OFF,
TEMP_CELSIUS,
TEMP_FAHRENHEIT,
)
from . import CONF_SENSORS, DATA_NEST, DATA_NES... | all_sensors += [
NestBasicSensor(structure, None, variable)
for variable in conditions
if variable in STRUCTURE_SENSOR_TYPES
]
for structure, device in nest.thermostats():
all_sensors += [
NestBasicSensor(struct... | all_sensors = []
for structure in nest.structures(): | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.