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 |
|---|---|---|---|---|
FileItem.tsx | import React from 'react'
import cx from 'classnames'
import {Fade} from '../ui'
import {LayerRender} from '../types'
import VisibilityButton from './VisibilityButton'
type Props = LayerRender & {showFilenames: boolean}
const TYPE_UNKNOWN = 'unknown'
const STYLE = 'flex items-center h2 mb2 pl3 br3 overflow-hidden b... | />
</li>
)
} | random_line_split | |
application.ts | /*
* Copyright (C) 2015 The Gravitee team (http://gravitee.io)
*
* 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 requi... | * limitations under the License.
*/
import * as _ from 'lodash';
export class ApplicationType {
public name: string;
public id: string;
public description: string;
public icon: string;
public oauth?: any;
public configuration: any;
public default_grant_types: Array<any>;
public requires_redirect_uri... | random_line_split | |
application.ts | /*
* Copyright (C) 2015 The Gravitee team (http://gravitee.io)
*
* 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 requi... | {
public name: string;
public id: string;
public description: string;
public icon: string;
public oauth?: any;
public configuration: any;
public default_grant_types: Array<any>;
public requires_redirect_uris: boolean;
public allowed_grant_types: Array<any>;
public mandatory_grant_types: Array<any>;... | ApplicationType | identifier_name |
application.ts | /*
* Copyright (C) 2015 The Gravitee team (http://gravitee.io)
*
* 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 requi... |
private getIcon() {
switch (this.id.toUpperCase()) {
case 'BROWSER':
return 'computer';
case 'WEB':
return 'language';
case 'NATIVE':
return 'phone_android';
case 'BACKEND_TO_BACKEND':
return 'share';
default:
return 'pan_tool';
}
}
}
| {
return this.mandatory_grant_types && _.indexOf(this.mandatory_grant_types, grantType.type) !== -1;
} | identifier_body |
main.rs | use api;
use data;
fn test<T: api::RecordMeta>(ds: &api::DataSet<T>) {
println!("{}", ds.target_count());
for record in ds.records() {
println!("{}", record.0.some_record_meta());
}
}
fn test2<T: api::RecordMeta>(ds: &api::DataSet<T>, view: &mut api::DataSetView, index: usize) {
if ds.len(... | () {
println!("Hello, API!");
let ds = data::get_data();
println!("is_empty = {}, target_count = {}", ds.is_empty(), ds.target_count());
for record in ds.records() {
println!("{:?}", record);
}
for record in ds.view_records(&api::DataSetView::new(vec![0])) {
println!("{:?}", reco... | main | identifier_name |
main.rs | use api;
use data;
fn test<T: api::RecordMeta>(ds: &api::DataSet<T>) {
println!("{}", ds.target_count());
for record in ds.records() {
println!("{}", record.0.some_record_meta());
}
}
fn test2<T: api::RecordMeta>(ds: &api::DataSet<T>, view: &mut api::DataSetView, index: usize) {
if ds.len(... |
for record in ds.view_records(view) {
println!("{}: {}", index, record.0.some_record_meta());
}
view.add_index(index);
test2(ds, view, index + 1)
}
fn main() {
println!("Hello, API!");
let ds = data::get_data();
println!("is_empty = {}, target_count = {}", ds.is_empty(), ds.tar... | {
return
} | conditional_block |
main.rs | use api;
use data;
fn test<T: api::RecordMeta>(ds: &api::DataSet<T>) |
fn test2<T: api::RecordMeta>(ds: &api::DataSet<T>, view: &mut api::DataSetView, index: usize) {
if ds.len() == index {
return
}
for record in ds.view_records(view) {
println!("{}: {}", index, record.0.some_record_meta());
}
view.add_index(index);
test2(ds, view, index + 1)
... | {
println!("{}", ds.target_count());
for record in ds.records() {
println!("{}", record.0.some_record_meta());
}
} | identifier_body |
main.rs | use api;
use data;
fn test<T: api::RecordMeta>(ds: &api::DataSet<T>) {
println!("{}", ds.target_count());
for record in ds.records() {
println!("{}", record.0.some_record_meta());
}
}
fn test2<T: api::RecordMeta>(ds: &api::DataSet<T>, view: &mut api::DataSetView, index: usize) {
if ds.len(... | test2(&ds, &mut api::DataSetView::empty(), 0);
} | random_line_split | |
ssh.py | OST_KEY_CHECKING:
self._add_args(
"ANSIBLE_HOST_KEY_CHECKING/host_key_checking disabled",
("-o", "StrictHostKeyChecking=no")
)
if self._play_context.port is not None:
self._add_args(
"ANSIBLE_REMOTE_PORT/remote_port/ansible_por... | (self, cmd, in_data, sudoable=True):
'''
Starts the command and communicates with it until it ends.
'''
display_cmd = map(to_unicode, map(pipes.quote, cmd))
display.vvv(u'SSH: EXEC {0}'.format(u' '.join(display_cmd)), host=self.host)
# Start the given command. If we don... | _run | identifier_name |
ssh.py | stdout or stderr. We
# set any flags based on examining the output in self._flags.
stdout = stderr = ''
tmp_stdout = tmp_stderr = ''
self._flags = dict(
become_prompt=False, become_success=False,
become_error=False, become_nopasswd_error=False
)
... | """
Wrapper around _exec_command to retry in the case of an ssh failure
Will retry if:
* an exception is caught
* ssh returns 255
Will not retry if
* remaining_tries is <2
* retries limit reached
"""
remaining_tries = int(C.ANSIBLE_SSH_RETRIES) +... | identifier_body | |
ssh.py |
elif binary == 'ssh':
# Older versions of ssh (e.g. in RHEL 6) don't accept sftp -q.
self._command += ['-q']
# Next, we add [ssh_connection]ssh_args from ansible.cfg.
if self._play_context.ssh_args:
args = self._split_ssh_args(self._play_context.ssh_args)
... | self._command += ['-vvv'] | conditional_block | |
ssh.py | .HOST_KEY_CHECKING:
self._add_args(
"ANSIBLE_HOST_KEY_CHECKING/host_key_checking disabled",
("-o", "StrictHostKeyChecking=no")
)
if self._play_context.port is not None:
self._add_args(
"ANSIBLE_REMOTE_PORT/remote_port/ansible_p... | Starts the command and communicates with it until it ends.
'''
display_cmd = map(to_unicode, map(pipes.quote, cmd))
display.vvv(u'SSH: EXEC {0}'.format(u' '.join(display_cmd)), host=self.host)
# Start the given command. If we don't need to pipeline data, we can try
# to... | random_line_split | |
elasticsearch_service.py | # Copyright 2015 Netflix, Inc.
#
# 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... |
else:
config['policy'] = json.loads(domain_config["DomainConfig"]["AccessPolicies"]["Options"])
config['name'] = domain
return ElasticSearchServiceItem(region=kwargs['region'], account=kwargs['account_name'], name=domain, arn=arn, config=config)
class ElasticSearchServiceItem(Cha... | config['policy'] = {} | conditional_block |
elasticsearch_service.py | # Copyright 2015 Netflix, Inc.
#
# 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... | super(ElasticSearchServiceItem, self).__init__(
index=ElasticSearchService.index,
region=region,
account=account,
name=name,
arn=arn,
new_config=config) | random_line_split | |
elasticsearch_service.py | # Copyright 2015 Netflix, Inc.
#
# 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... | (self):
"""
:returns: item_list - list of ElasticSearchService Items
:return: exception_map - A dict where the keys are a tuple containing the
location of the exception and the value is the actual exception
"""
self.prep_for_slurp()
@iter_account_region(ind... | slurp | identifier_name |
elasticsearch_service.py | # Copyright 2015 Netflix, Inc.
#
# 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... | super(ElasticSearchServiceItem, self).__init__(
index=ElasticSearchService.index,
region=region,
account=account,
name=name,
arn=arn,
new_config=config) | identifier_body | |
test.ts | import './polyfills.ts';
import 'zone.js/dist/long-stack-trace-zone';
import 'zone.js/dist/proxy.js';
import 'zone.js/dist/sync-test';
import 'zone.js/dist/jasmine-patch';
import 'zone.js/dist/async-test';
import 'zone.js/dist/fake-async-test';
// Unfortunately there's no typing for the `__karma__` variable. Just dec... |
throw e;
}
})
// Finally, start Karma to run the tests.
.then(__karma__.start, __karma__.error);
| {
console.error(e.message, e.stack);
} | conditional_block |
test.ts | import './polyfills.ts';
import 'zone.js/dist/long-stack-trace-zone';
import 'zone.js/dist/proxy.js';
import 'zone.js/dist/sync-test';
import 'zone.js/dist/jasmine-patch';
import 'zone.js/dist/async-test';
import 'zone.js/dist/fake-async-test';
// Unfortunately there's no typing for the `__karma__` variable. Just dec... |
// Prevent Karma from running prematurely.
__karma__.loaded = function () {};
Promise.all([
System.import('@angular/core/testing'),
System.import('@angular/platform-browser-dynamic/testing')
])
// First, initialize the Angular testing environment.
.then(([testing, testingBrowser]) => {
testing.getTestBed... | random_line_split | |
__init__.py | """Spike analysis software.
"""
from __future__ import division, print_function, absolute_import
__author__ = "Marek Rudnicki"
__version__ = "0.7.2"
import os
if 'THpdb' in os.environ:
import pdb
import sys
import traceback
def | (type, value, tb):
traceback.print_exception(type, value, tb)
pdb.pm()
sys.excepthook = info
if 'THlog' in os.environ:
import logging
if os.environ['THlog'] in ('d', 'debug'):
level = 'DEBUG'
else:
level = os.environ['THlog'].upper()
logger = logging.getLogger('t... | info | identifier_name |
__init__.py | """Spike analysis software.
| from __future__ import division, print_function, absolute_import
__author__ = "Marek Rudnicki"
__version__ = "0.7.2"
import os
if 'THpdb' in os.environ:
import pdb
import sys
import traceback
def info(type, value, tb):
traceback.print_exception(type, value, tb)
pdb.pm()
sys.exc... | """
| random_line_split |
__init__.py | """Spike analysis software.
"""
from __future__ import division, print_function, absolute_import
__author__ = "Marek Rudnicki"
__version__ = "0.7.2"
import os
if 'THpdb' in os.environ:
import pdb
import sys
import traceback
def info(type, value, tb):
traceback.print_exception(type, value... |
logger = logging.getLogger('thorns')
logger.setLevel(level)
import thorns.util
import thorns.waves
import thorns.io
from thorns.spikes import (
make_trains,
trains_to_array,
accumulate,
select_trains,
trim,
fold,
)
from thorns.stats import (
get_duration,
shuffled_autocorre... | level = os.environ['THlog'].upper() | conditional_block |
__init__.py | """Spike analysis software.
"""
from __future__ import division, print_function, absolute_import
__author__ = "Marek Rudnicki"
__version__ = "0.7.2"
import os
if 'THpdb' in os.environ:
import pdb
import sys
import traceback
def info(type, value, tb):
|
sys.excepthook = info
if 'THlog' in os.environ:
import logging
if os.environ['THlog'] in ('d', 'debug'):
level = 'DEBUG'
else:
level = os.environ['THlog'].upper()
logger = logging.getLogger('thorns')
logger.setLevel(level)
import thorns.util
import thorns.waves
import tho... | traceback.print_exception(type, value, tb)
pdb.pm() | identifier_body |
urls.py | # ETConf -- web-based user-friendly computer hardware configurator
# Copyright (C) 2010-2011 ETegro Technologies, PLC <http://etegro.com/>
# Sergey Matveev <sergey.matveev@etegro.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero... | # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org... | # This program is distributed in the hope that it will be useful, | random_line_split |
serial_pyboard_to_python.py | QtCore #Provides usage of PyQt4's libraries which aids in UI design
import pyqtgraph as pg #Initiation of plotting code
import serial #Communication with the serial port is done using the pySerial 2.7 package
from datetime import datetime #Allows us to look at current date and ... |
def insertionButtonClicked():
teensySerialData.write('3')
print("Insertion")
def separationButtonClicked():
teensySerialData.write('2')
print("Separation")
#Start Recording in Widget
## Create widgets to be placed inside
startBtn = QtGui.QPushButton('Start')
startBtn.setToolTip('Click to begin ... | teensySerialData.write('1')
print("HV On") | identifier_body |
serial_pyboard_to_python.py | ## Always start by initializing Qt (only once per application)
app = QtGui.QApplication([])
## Define a top-level widget to hold everything (a window)
w = QtGui.QWidget()
w.resize(1000,600)
w.setWindowTitle('Voltage Plots')
startBtnClicked = False
quitBtnClicked = False
firstupdate = 0
## This function contains the ... | if (xLeftIndex == 0):
# Remove all PlotDataItems from the PlotWidgets.
# This will effectively reset the graphs (approximately every 30000 samples)
#pmtPlotWidget.clear()
pmtPlotWidget.clear()
## pmtCurve are of the PlotDataIt... | conditional_block | |
serial_pyboard_to_python.py | QtCore #Provides usage of PyQt4's libraries which aids in UI design
import pyqtgraph as pg #Initiation of plotting code
import serial #Communication with the serial port is done using the pySerial 2.7 package
from datetime import datetime #Allows us to look at current date and ... | ():
global quitBtnClicked
quitBtnClicked = True
## Buttons to control the High Voltage
def HVoffButtonClicked():
teensySerialData.write('0')
print("HV Off")
def HVonButtonClicked():
teensySerialData.write('1')
print("HV On")
def insertionButtonClicked():
teensySerialData.write('3')
p... | quitButtonClicked | identifier_name |
serial_pyboard_to_python.py | , QtCore #Provides usage of PyQt4's libraries which aids in UI design
import pyqtgraph as pg #Initiation of plotting code
import serial #Communication with the serial port is done using the pySerial 2.7 package
from datetime import datetime #Allows us to look at current date and... |
if firstupdate == 0:
teensySerialData.flushInput()
firstupdate += 1
## The number of bytes currently waiting to be read in.
## We want to read these values as soon as possible, because
## we will lose them if the buffer fills up
bufferSize = teensySerialData.inWaiting()
runC... | global timeElapsed
global timeElapsedPrev
global firstRun
global firstupdate | random_line_split |
20190711074029-streaks-and-reached_goals.ts | export const up = async function(db: any): Promise<any> {
return db.runSql(
`
CREATE TABLE streaks (
id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
client_id CHAR(36) NOT NULL,
locale_id INT NOT NULL,
started_at DATETIME,
last_activity_at DATETIME,
FOREI... | );
};
export const down = function(): Promise<any> {
return null;
}; | UNIQUE(count, type, client_id, locale_id)
);
` | random_line_split |
config_base.py | # Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved
#
# 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 applic... | # replace LayerOutput to paddle.v2.config_base.Layer
doc = doc.replace("LayerOutput", "paddle.v2.config_base.Layer")
doc = doc.replace('ParameterAttribute',
'paddle.v2.attr.ParameterAttribute')
doc = re.sub(r'ExtraLayerAttribute[^\s]?',
'p... | def __new__(cls, name, bases, attrs):
method_name = attrs.get('METHOD_NAME', None)
if method_name is not None:
method = getattr(conf_helps, method_name)
if method.__doc__ is not None:
mapper = attrs.get("__map_docstr__", None)
if mapper is not None... | identifier_body |
config_base.py | # Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved
#
# 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 applic... | if self.use_context_name():
return context[self.context_name()]
else:
return context[self.name]
def to_proto_impl(self, **kwargs):
raise NotImplementedError()
def context_name(self):
"""
Context name means the context which stores `to_proto_impl`... | self.__contex__ = context | random_line_split |
config_base.py | # Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved
#
# 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 applic... | (self):
"""
lazy calculate size of the layer, should be called when to_proto_impl of
this layer is called.
:return:
"""
return self.__contex__[self.context_name()].size
def __convert_to_v2__(method_name, parent_names, is_default_name=True):
if is_default_name:
... | calculate_size | identifier_name |
config_base.py | # Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved
#
# 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 applic... |
else:
return context[self.name]
def to_proto_impl(self, **kwargs):
raise NotImplementedError()
def context_name(self):
"""
Context name means the context which stores `to_proto_impl` result.
If multiple layer share same context_name, the `to_proto_impl` of ... | return context[self.context_name()] | conditional_block |
utils.py | '''
This file holds globally useful utility classes and functions, i.e., classes and
functions that are generic enough not to be specific to one app.
'''
import logging
import os
import re
import sys
from datetime import tzinfo, timedelta
from django.conf import settings
# Setup logging support.
LOGGER = logging.get... |
class SimpleTimezone(tzinfo):
"""
A fixed offset timezone with an unknown name and an unknown DST adjustment.
"""
def __init__(self, offset):
self.__offset = timedelta(minutes=offset)
def utcoffset(self, dt):
return self.__offset
def tzname(self, dt):
return None
... | self.handle.close() | conditional_block |
utils.py | '''
This file holds globally useful utility classes and functions, i.e., classes and
functions that are generic enough not to be specific to one app.
'''
import logging
import os
import re
import sys
from datetime import tzinfo, timedelta
from django.conf import settings
# Setup logging support.
LOGGER = logging.get... |
def release(self):
"""
Release any lock on the name for which this `Lock` was created.
"""
if self.handle:
fcntl.flock(self.handle, fcntl.LOCK_UN)
def __del__(self):
if self.handle:
self.handle.close()
class SimpleTimezone(tzinfo):
"""
... | """
Acquire a lock on the name for which this `Lock` was created.
"""
if self.handle:
fcntl.flock(self.handle, fcntl.LOCK_EX) | identifier_body |
utils.py | '''
This file holds globally useful utility classes and functions, i.e., classes and
functions that are generic enough not to be specific to one app.
'''
import logging
import os
import re
import sys
from datetime import tzinfo, timedelta
from django.conf import settings
# Setup logging support.
LOGGER = logging.get... | ():
"""
Each instance of this class can be used to acquire an exclusive, system-wide
(multi-process) lock on a particular name.
This class will only work on Unix systems viz. systems that provide the
`fcntl` module. On other systems the class will silently do nothing.
"""
def __init__(s... | Lock | identifier_name |
utils.py | '''
This file holds globally useful utility classes and functions, i.e., classes and
functions that are generic enough not to be specific to one app.
'''
import logging
import os
import re
import sys
from datetime import tzinfo, timedelta
from django.conf import settings
# Setup logging support.
LOGGER = logging.get... | else:
self.handle = None
def acquire(self):
"""
Acquire a lock on the name for which this `Lock` was created.
"""
if self.handle:
fcntl.flock(self.handle, fcntl.LOCK_EX)
def release(self):
"""
Release any lock on the name for whic... | name.
"""
if 'fcntl' in sys.modules:
self.handle = open(os.path.join(settings.LOCK_DIR, lock_name), 'w') | random_line_split |
dependency-injection.js | /*! MVW-Injection (0.2.5). (C) 2015 Xavier Boubert. MIT @license: en.wikipedia.org/wiki/MIT_License */
(function(root) {
'use strict';
var DependencyInjection = new (function DependencyInjection() {
var _this = this,
_interfaces = {};
function _formatFactoryFunction(factoryFunction) {
if (... |
return factoryFunction;
}
function Injector(instanceName) {
function _getInjections(dependencies, name, customDependencies, noError) {
var interfaces = _interfaces[name].interfacesSupported,
injections = [],
i,
j;
for (i = 0; i < dependencies.... | {
var factoryArrayCopy = [];
for (var i = 0; i < factoryFunction.length; i++) {
factoryArrayCopy.push(factoryFunction[i]);
}
factoryFunction = factoryArrayCopy;
} | conditional_block |
dependency-injection.js | /*! MVW-Injection (0.2.5). (C) 2015 Xavier Boubert. MIT @license: en.wikipedia.org/wiki/MIT_License */
(function(root) {
'use strict';
var DependencyInjection = new (function DependencyInjection() {
var _this = this,
_interfaces = {};
function _formatFactoryFunction(factoryFunction) | .concat(factoryFunction);
}
return factoryFunction;
}
else {
var factoryArrayCopy = [];
for (var i = 0; i < factoryFunction.length; i++) {
factoryArrayCopy.push(factoryFunction[i]);
}
factoryFunction = factoryArrayCopy;
}
... | {
if (typeof factoryFunction == 'function') {
var funcString = factoryFunction
.toString()
// remove comments
.replace(/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg, '');
var matches = funcString.match(/^function\s*[^\(]*\s*\(\s*([^\)]*)\)/m);
if (matches === null || ... | identifier_body |
dependency-injection.js | /*! MVW-Injection (0.2.5). (C) 2015 Xavier Boubert. MIT @license: en.wikipedia.org/wiki/MIT_License */
(function(root) {
'use strict';
var DependencyInjection = new (function DependencyInjection() {
var _this = this,
_interfaces = {};
function _formatFactoryFunction(factoryFunction) {
if (... |
throw new Error('DependencyInjection: "' + interfaces[j] + '" interface is not registered.');
}
factory = _interfaces[interfaces[j]].factories[dependencies[i]];
if (factory) {
factory.interfaceName = interfaces[j];
break;
... | if (!_interfaces[interfaces[j]]) {
if (noError) {
return false;
} | random_line_split |
dependency-injection.js | /*! MVW-Injection (0.2.5). (C) 2015 Xavier Boubert. MIT @license: en.wikipedia.org/wiki/MIT_License */
(function(root) {
'use strict';
var DependencyInjection = new (function DependencyInjection() {
var _this = this,
_interfaces = {};
function _formatFactoryFunction(factoryFunction) {
if (... | (instanceName) {
function _getInjections(dependencies, name, customDependencies, noError) {
var interfaces = _interfaces[name].interfacesSupported,
injections = [],
i,
j;
for (i = 0; i < dependencies.length; i++) {
var factory = null;
if (... | Injector | identifier_name |
mod.rs | //! This module contains the basic RootMove structures, allowing for storage of the moves from a specific position
//! alongside information about each of the moves.
pub mod root_moves_list;
use std::cmp::Ordering as CmpOrder;
use pleco::core::score::*;
use pleco::BitMove; |
/// Keeps track of information of a move for the position to be searched.
#[derive(Copy, Clone,Eq)]
pub struct RootMove {
pub score: i32,
pub prev_score: i32,
pub bit_move: BitMove,
pub depth_reached: i16,
}
impl RootMove {
/// Creates a new `RootMove`.
#[inline]
pub fn new(bit_move: BitM... |
// 250 as this fits into 64 byte cache lines easily.
const MAX_MOVES: usize = 250; | random_line_split |
mod.rs | //! This module contains the basic RootMove structures, allowing for storage of the moves from a specific position
//! alongside information about each of the moves.
pub mod root_moves_list;
use std::cmp::Ordering as CmpOrder;
use pleco::core::score::*;
use pleco::BitMove;
// 250 as this fits into 64 byte cache lin... | (bit_move: BitMove) -> Self {
RootMove {
bit_move,
score: NEG_INFINITE as i32,
prev_score: NEG_INFINITE as i32,
depth_reached: 0,
}
}
/// Places the current score into the previous_score field, and then updates
/// the score and depth.
#[i... | new | identifier_name |
mod.rs | //! This module contains the basic RootMove structures, allowing for storage of the moves from a specific position
//! alongside information about each of the moves.
pub mod root_moves_list;
use std::cmp::Ordering as CmpOrder;
use pleco::core::score::*;
use pleco::BitMove;
// 250 as this fits into 64 byte cache lin... |
CmpOrder::Greater
}
}
impl PartialOrd for RootMove {
fn partial_cmp(&self, other: &RootMove) -> Option<CmpOrder> {
Some(self.cmp(other))
}
}
impl PartialEq for RootMove {
fn eq(&self, other: &RootMove) -> bool {
self.score == other.score && self.prev_score == other.prev_score... | {
return CmpOrder::Less;
} | conditional_block |
index.d.ts | // Type definitions for Meteor 1.4
// Project: http://www.meteor.com/
// Definitions by: Alex Borodach <https://github.com/barbatus>, Dave Allen <https://github.com/fullflavedave>, Olivier Refalo <https://github.com/orefalo>, Daniel Neveux <https://github.com/dagatsoin>, Birk Skyum <https://github.com/birkskyum>, Arda ... | /// <reference path="./ddp-rate-limiter.d.ts" />
/// <reference path="./ddp.d.ts" />
/// <reference path="./ejson.d.ts" />
/// <reference path="./email.d.ts" />
/// <reference path="./http.d.ts" />
/// <reference path="./meteor.d.ts" />
/// <reference path="./mongo.d.ts" />
/// <reference path="./random.d.ts" />
/// <r... | /// <reference path="./browser-policy-common.d.ts" />
/// <reference path="./check.d.ts" /> | random_line_split |
checkReport.sub.js | (function () {
// Get values from the substitution engine.
// We can't just pull these from the document context
// because this script is intended to be transcluded into
// another document, and we want the GET values used to request it,
// not the values for the including document
// XXX these are unenc... | // fallback on test file name if cookie name not specified
reportCookieName = location.pathname.split('/')[location.pathname.split('/').length - 1].split('.')[0];
}
var reportID = "{{GET[reportID]}}";
if (reportID == "") {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.len... | var location = window.location;
if (reportCookieName == "") { | random_line_split |
checkReport.sub.js | (function () {
// Get values from the substitution engine.
// We can't just pull these from the document context
// because this script is intended to be transcluded into
// another document, and we want the GET values used to request it,
// not the values for the including document
// XXX these are unenc... | (field, value, field_name) {
assert_true(field.indexOf(value.split(" ")[0]) != -1,
field_name + " value of \"" + field + "\" did not match " +
value.split(" ")[0] + ".");
}
reportTest.step(function () {
var report = new XMLHttpRequest();
report.onload = reportTest.step... | assert_field_value | identifier_name |
checkReport.sub.js | (function () {
// Get values from the substitution engine.
// We can't just pull these from the document context
// because this script is intended to be transcluded into
// another document, and we want the GET values used to request it,
// not the values for the including document
// XXX these are unenc... |
reportTest.step(function () {
var report = new XMLHttpRequest();
report.onload = reportTest.step_func(function () {
var data = JSON.parse(report.responseText);
if (data.error) {
assert_equals("false", reportExists, data.error);
} else {
if(reportExists != "" &&... | {
assert_true(field.indexOf(value.split(" ")[0]) != -1,
field_name + " value of \"" + field + "\" did not match " +
value.split(" ")[0] + ".");
} | identifier_body |
simplepool.py | #!/usr/bin/env python
"""simple thread pool
@author: dn13(dn13@gmail.com)
@author: Fibrizof(dfang84@gmail.com)
"""
import threading
import Queue
import new
def WorkerPoolError( Exception ):
pass
class Task(threading.Thread):
def __init__(self, queue, result_queue):
threading.Thread.__init__(self)
... |
class WorkerPool( object ):
def __init__( self, threadnum ):
self.threadnum = threadnum
self.q = Queue.Queue()
self.result_q = Queue.Queue()
self.ts = [ Task(self.q, self.result_q) for i in range(threadnum) ]
self._registfunctions = {}
... | call = self.queue.get()
if call:
try:
reslut = call()
self.result_queue.put(reslut)
except:
pass
self.queue.task_done() | conditional_block |
simplepool.py | #!/usr/bin/env python
"""simple thread pool
@author: dn13(dn13@gmail.com)
@author: Fibrizof(dfang84@gmail.com)
"""
import threading
import Queue
import new
def WorkerPoolError( Exception ):
pass
class Task(threading.Thread):
def __init__(self, queue, result_queue):
threading.Thread.__init__(self)
... |
def run(self):
while self.running:
call = self.queue.get()
if call:
try:
reslut = call()
self.result_queue.put(reslut)
except:
pass
self.queue.task_done()
class WorkerPool( obje... | self.running = False
self.queue.put(None) | identifier_body |
simplepool.py | #!/usr/bin/env python
"""simple thread pool
@author: dn13(dn13@gmail.com)
@author: Fibrizof(dfang84@gmail.com)
"""
import threading
import Queue
import new
def WorkerPoolError( Exception ):
pass
class Task(threading.Thread):
def __init__(self, queue, result_queue):
threading.Thread.__init__(self)
... | .put( lambda : _old( *args, **kwargs ) )
return _new
def registtopool( self, _old ):
if _old.__name__ in self._registfunctions :
raise WorkerPoolError, 'function name exists'
self._registfunctions[_old.__name__] = _old
return _old
... | self.q | identifier_name |
simplepool.py | #!/usr/bin/env python
"""simple thread pool
@author: dn13(dn13@gmail.com)
@author: Fibrizof(dfang84@gmail.com)
"""
import threading
import Queue
import new
def WorkerPoolError( Exception ):
pass
class Task(threading.Thread):
def __init__(self, queue, result_queue):
threading.Thread.__init__(self)
... | self.q.join()
self.is_in_join = False
return
def runwithpool( self, _old ):
def _new( *args, **kwargs ):
self.q.put( lambda : _old( *args, **kwargs ) )
return _new
def registtopool( self, _old ):
if _old.__name__ in... | random_line_split | |
testing.ts | /**
* Public Test Library for unit testing Angular2 Applications. Uses the
* Jasmine framework.
*/
import {global} from 'angular2/src/facade/lang';
import {bind} from 'angular2/src/core/di';
import {createTestInjector, FunctionWithParamTokens, inject, injectAsync} from './test_injector';
export {inject, injectAsy... | } else {
done.fail('Error: injectAsync was expected to return a promise, but the ' +
' returned value was: ' + returned);
}
});
} else {
jsmBeforeEach(() => {
if (!injector) {
injector = createTestInjector(testProviders);
}
... | random_line_split | |
testing.ts | /**
* Public Test Library for unit testing Angular2 Applications. Uses the
* Jasmine framework.
*/
import {global} from 'angular2/src/facade/lang';
import {bind} from 'angular2/src/core/di';
import {createTestInjector, FunctionWithParamTokens, inject, injectAsync} from './test_injector';
export {inject, injectAsy... | (fn: FunctionWithParamTokens | AnyTestFn): void {
if (fn instanceof FunctionWithParamTokens) {
// The test case uses inject(). ie `beforeEach(inject([ClassA], (a) => { ...
// }));`
if (fn.isAsync) {
jsmBeforeEach((done) => {
if (!injector) {
injector = createTestInjector(testProvid... | beforeEach | identifier_name |
testing.ts | /**
* Public Test Library for unit testing Angular2 Applications. Uses the
* Jasmine framework.
*/
import {global} from 'angular2/src/facade/lang';
import {bind} from 'angular2/src/core/di';
import {createTestInjector, FunctionWithParamTokens, inject, injectAsync} from './test_injector';
export {inject, injectAsy... | jsmFn(name, () => {
if (!injector) {
injector = createTestInjector(testProviders);
}
var returned = testFn.execute(injector);
if (_isPromiseLike(returned)) {
throw new Error('inject returned a promise. Did you mean to use injectAsync?');
};
});
... | {
var timeOut = testTimeOut;
if (testFn instanceof FunctionWithParamTokens) {
// The test case uses inject(). ie `it('test', inject([ClassA], (a) => { ...
// }));`
if (testFn.isAsync) {
jsmFn(name, (done) => {
if (!injector) {
injector = createTestInjector(testProviders);
... | identifier_body |
testing.ts | /**
* Public Test Library for unit testing Angular2 Applications. Uses the
* Jasmine framework.
*/
import {global} from 'angular2/src/facade/lang';
import {bind} from 'angular2/src/core/di';
import {createTestInjector, FunctionWithParamTokens, inject, injectAsync} from './test_injector';
export {inject, injectAsy... |
var returned = testFn.execute(injector);
if (_isPromiseLike(returned)) {
returned.then(done, done.fail);
} else {
done.fail('Error: injectAsync was expected to return a promise, but the ' +
' returned value was: ' + returned);
}
}, timeOut);... | {
injector = createTestInjector(testProviders);
} | conditional_block |
composedquery.py | = {}
self._rankQueries = {}
self._matches = {}
self._unites = []
self._sortKeys = []
self.resultsFrom = resultsFromCore
if query:
self.setCoreQuery(resultsFromCore, query=query)
else:
self.cores.add(resultsFromCore)
def _makeProperty... | Unite | identifier_name | |
composedquery.py | co Lucene"
#
# "Meresco Lucene" is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# "Meresco Lucene" is distributed in the hope that it... |
for uniteCoreSpec in (uniteCoreASpec, uniteCoreBSpec):
self.cores.add(uniteCoreSpec['core'])
self._unites.append(Unite(self, uniteCoreASpec, uniteCoreBSpec))
return self
def addSortKey(self, sortKey):
core = sortKey.get('core', self.resultsFrom)
self.cores.add(c... | raise ValueError("No more than 1 addUnite supported") | conditional_block |
composedquery.py | co Lucene"
#
# "Meresco Lucene" is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# "Meresco Lucene" is distributed in the hope that it... |
def otherCoreFacetFiltersFor(self, core):
return self._otherCoreFacetFilters.get(core, [])
def rankQueryFor(self, core):
return self._rankQueries.get(core)
def keyName(self, core, otherCore):
if core == otherCore: #TODO: Needed for filters/rank's in same core as queried core
... | return self._drilldownQueries.get(core, []) | identifier_body |
composedquery.py | co Lucene"
#
# "Meresco Lucene" is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# "Meresco Lucene" is distributed in the hope that it... |
def queriesFor(self, core):
return [q for q in [self.queryFor(core)] + self.filterQueriesFor(core) if q]
@property
def unites(self):
return self._unites[:]
@property
def filterQueries(self):
return self._filterQueries.items()
@property
def numberOfUsedCores(self):... | return keyNames | random_line_split |
bg.js | /*
Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'clipboard', 'bg', {
copy: 'Копирай',
copyError: 'Настройките за сигурност на вашия бразуър не разрешават на редактора да изпълни запаметяването. За ... | } ); | title: 'Вмъкни' | random_line_split |
unique.py | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# 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 applica... |
def _as_variant_tensor(self):
return gen_dataset_ops.unique_dataset(
self._input_dataset._as_variant_tensor(), # pylint: disable=protected-access
**dataset_ops.flat_structure(self))
@property
def output_classes(self):
return self._input_dataset.output_classes
@property
def output_... | raise TypeError(
"`tf.contrib.data.unique()` only supports inputs with a single "
"`tf.int32`, `tf.int64`, or `tf.string` component.") | conditional_block |
unique.py | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# 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 applica... | (self):
return gen_dataset_ops.unique_dataset(
self._input_dataset._as_variant_tensor(), # pylint: disable=protected-access
**dataset_ops.flat_structure(self))
@property
def output_classes(self):
return self._input_dataset.output_classes
@property
def output_shapes(self):
return s... | _as_variant_tensor | identifier_name |
unique.py | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# 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 applica... |
@property
def output_types(self):
return self._input_dataset.output_types
| return self._input_dataset.output_shapes | identifier_body |
unique.py | # Copyright 2017 The TensorFlow Authors. All Rights Reserved. | # http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing pe... | #
# 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
# | random_line_split |
Container.d.ts | import { Class } from './Class';
import { Notifications } from './Notifications';
import { Value } from './Value';
export interface Container_Arguments {
duration?: string | number;
unchanged?: boolean;
completeCallback?: () => void;
}
export interface Container_Params {
title: string; | instanceNumber?: number | null;
params?: Container_Params;
}
export interface Container_Deferred {
embedded: JQuery.Deferred<any>;
}
export abstract class Container extends Class {
static instanceCounter?: number;
defaultActiveArguments: Container_Arguments;
defaultExpandedArguments: Container... | description?: string;
priority?: number;
type?: string;
content?: string | null;
active?: boolean; | random_line_split |
testIndirect.js | 'use strict';
var IoTServer = require("../iot");
var inquirer = require("inquirer");
var chalk = require('chalk');
inquirer.prompt([{
type: "input",
name: "iotBaseURL",
message: "Enter the URL to the IoT Server",
default: "http://iotserver:7101"
}], function(answers) {
var iot = new IoTServer(ans... | console.log(chalk.bold("Gateway deleted."));
})
.catch(function (error) {
console.log(chalk.bold.red("*** Error ***"));
console.log(error.body || error);
console.trace();
if (device) device.delete();
});
}); | })
.then(function (gateway) { | random_line_split |
visualizer.py | # Copyright (c) 2017 Microsoft Corporation.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
# documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publis... |
class BaseVisualizer(object):
""" Provide a unified interface for observing the training progress """
def add_entry(self, index, key, result, **kwargs):
raise NotImplementedError()
def __lshift__(self, other):
if isinstance(other, tuple):
if len(other) >= 3:
... | return self._visualizer is not None | identifier_body |
visualizer.py | # Copyright (c) 2017 Microsoft Corporation.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
# documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publis... |
@property
def can_visualize(self):
return self._visualizer is not None
class BaseVisualizer(object):
""" Provide a unified interface for observing the training progress """
def add_entry(self, index, key, result, **kwargs):
raise NotImplementedError()
def __lshift__(self, other... | self._visualizer << (index, tag, value, kwargs) | conditional_block |
visualizer.py | # Copyright (c) 2017 Microsoft Corporation.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
# documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publis... |
def __exit__(self, exc_type, exc_val, exc_tb):
self.close()
return self |
def __enter__(self):
return self | random_line_split |
visualizer.py | # Copyright (c) 2017 Microsoft Corporation.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
# documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publis... | (self, visualizer=None):
if visualizer is not None:
assert isinstance(visualizer, BaseVisualizer), "visualizer should derive from BaseVisualizer"
self._visualizer = visualizer
def visualize(self, index, tag, value, **kwargs):
if self._visualizer is not None:
self._v... | __init__ | identifier_name |
inspection.py | # -*- coding: utf-8 -*-
from openerp import models, fields, api
from datetime import datetime, timedelta, date
from dateutil.relativedelta import relativedelta
class Inspection(models.Model):
_name = 'property.inspection'
_order = 'date desc'
_inherit = ['mail.thread', 'ir.needaction_mixin']
propert... | _name = 'property.inspection.request'
_order = 'date desc'
date = fields.Date(string='Date', required=True, copy=False,)
partner_id = fields.Many2one('res.partner', string='partner_id',)
request_note = fields.Text(string='request_note',)
user_id = fields.Many2one('res.users', string='user_id', req... | identifier_body | |
inspection.py | # -*- coding: utf-8 -*-
from openerp import models, fields, api
from datetime import datetime, timedelta, date
from dateutil.relativedelta import relativedelta
class Inspection(models.Model):
_name = 'property.inspection'
_order = 'date desc'
_inherit = ['mail.thread', 'ir.needaction_mixin']
propert... |
result = super(InspectionRequest, self).create(vals)
return result
| vals['name'] = self.env['ir.sequence'].next_by_code('inspection.request') or 'New' | conditional_block |
inspection.py | # -*- coding: utf-8 -*-
from openerp import models, fields, api
from datetime import datetime, timedelta, date
from dateutil.relativedelta import relativedelta
class Inspection(models.Model):
_name = 'property.inspection'
_order = 'date desc'
_inherit = ['mail.thread', 'ir.needaction_mixin']
propert... | (self, vals):
if vals.get('name', 'New') == 'New':
vals['name'] = self.env['ir.sequence'].next_by_code('inspection.request') or 'New'
result = super(InspectionRequest, self).create(vals)
return result
| create | identifier_name |
inspection.py | # -*- coding: utf-8 -*-
from openerp import models, fields, api
from datetime import datetime, timedelta, date
from dateutil.relativedelta import relativedelta
| _inherit = ['mail.thread', 'ir.needaction_mixin']
property_id = fields.Many2one('property', string='Property ID', required=True, readonly=True)
### inspection ###
date = fields.Date(string='Date', required=True,)
inspector_id = fields.Many2one('res.users', string='Inspector')
act_type = fields... | class Inspection(models.Model):
_name = 'property.inspection'
_order = 'date desc' | random_line_split |
alert-dialog.component.ts | import {
AfterViewInit,
Component,
EventEmitter,
Input,
Output,
ViewChild } from '@angular/core';
import { MatButton } from '@angular/material';
@Component({
selector: 'awb-alert-dialog',
styles: [require('./dialog.component.sass').toString()],
templateUrl: './alert-dialog.component.html',
})
// thi... | () {
// wait for MdInput to initialize; otherwise this breaks the component
setTimeout(() => this.cancel.focus(), 0);
}
}
| ngAfterViewInit | identifier_name |
alert-dialog.component.ts | import {
AfterViewInit,
Component,
EventEmitter,
Input,
Output,
ViewChild } from '@angular/core';
import { MatButton } from '@angular/material';
@Component({
selector: 'awb-alert-dialog',
styles: [require('./dialog.component.sass').toString()],
templateUrl: './alert-dialog.component.html',
})
// thi... |
public ngAfterViewInit() {
// wait for MdInput to initialize; otherwise this breaks the component
setTimeout(() => this.cancel.focus(), 0);
}
}
| {
this.valueEmitted.emit(value);
} | identifier_body |
alert-dialog.component.ts | import { | ViewChild } from '@angular/core';
import { MatButton } from '@angular/material';
@Component({
selector: 'awb-alert-dialog',
styles: [require('./dialog.component.sass').toString()],
templateUrl: './alert-dialog.component.html',
})
// this can be replaced by MdDialog when it is ready
export class AlertDialogCom... | AfterViewInit,
Component,
EventEmitter,
Input,
Output, | random_line_split |
main.js | to provide hints for
* the given editor context and, in case implicitChar is non- null,
* whether it is appropriate to do so.
*/
CssPropHints.prototype.hasHints = function (editor, implicitChar) {
this.editor = editor;
var cursor = this.editor.getCursorPos();
lastContext = n... | {
keepHints = true;
var textAfterCursor = this.info.name.substr(this.info.offset);
if (this.info.name.length === 0 || CodeHintManager.hasValidExclusion(this.exclusion, textAfterCursor)) {
// It's a new insertion, so append a colon and set keepHints
// ... | conditional_block | |
main.js | }
/**
* Get the CSS style text of the file open in the editor for this hinting session.
* For a CSS file, this is just the text of the file. For an HTML file,
* this will be only the text in the <style> tags.
*
* @return {string} the "css" text that can be sent to CSSUtils to extract a... | */
CssPropHints.prototype.getHints = function (implicitChar) {
this.cursor = this.editor.getCursorPos();
this.info = CSSUtils.getInfoAtPos(this.editor, this.cursor);
var needle = this.info.name,
valueNeedle = "",
context = this.info.context,
valueArr... | random_line_split | |
main.js | }
/**
* Get the CSS style text of the file open in the editor for this hinting session.
* For a CSS file, this is just the text of the file. For an HTML file,
* this will be only the text in the <style> tags.
*
* @return {string} the "css" text that can be sent to CSSUtils to extract all ... | (hints, query) {
var hasColorSwatch = hints.some(function (token) {
return token.color;
});
StringMatch.basicMatchSort(hints);
return hints.map(function (token) {
var $hintObj = $("<span>").addClass("brackets-css-hints");
// highlight the matched por... | formatHints | identifier_name |
main.js |
/**
* Get the CSS style text of the file open in the editor for this hinting session.
* For a CSS file, this is just the text of the file. For an HTML file,
* this will be only the text in the <style> tags.
*
* @return {string} the "css" text that can be sent to CSSUtils to extract all na... | {
this.primaryTriggerKeys = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-()";
this.secondaryTriggerKeys = ":";
this.exclusion = null;
} | identifier_body | |
cursor.rs | //! Cursor movement.
use std::fmt;
use std::io::{self, Write, Error, ErrorKind, Read};
use async::async_stdin;
use std::time::{SystemTime, Duration};
use raw::CONTROL_SEQUENCE_TIMEOUT;
derive_csi_sequence!("Hide the cursor.", Hide, "?25l");
derive_csi_sequence!("Show the cursor.", Show, "?25h");
derive_csi_sequence!... | #[derive(Copy, Clone, PartialEq, Eq)]
pub struct Up(pub u16);
impl fmt::Display for Up {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, csi!("{}A"), self.0)
}
}
/// Move cursor down.
#[derive(Copy, Clone, PartialEq, Eq)]
pub struct Down(pub u16);
impl fmt::Display for Down {
fn ... | }
}
/// Move cursor up. | random_line_split |
cursor.rs | //! Cursor movement.
use std::fmt;
use std::io::{self, Write, Error, ErrorKind, Read};
use async::async_stdin;
use std::time::{SystemTime, Duration};
use raw::CONTROL_SEQUENCE_TIMEOUT;
derive_csi_sequence!("Hide the cursor.", Hide, "?25l");
derive_csi_sequence!("Show the cursor.", Show, "?25h");
derive_csi_sequence!... | (pub u16);
impl fmt::Display for Right {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, csi!("{}C"), self.0)
}
}
/// Move cursor up.
#[derive(Copy, Clone, PartialEq, Eq)]
pub struct Up(pub u16);
impl fmt::Display for Up {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
... | Right | identifier_name |
cursor.rs | //! Cursor movement.
use std::fmt;
use std::io::{self, Write, Error, ErrorKind, Read};
use async::async_stdin;
use std::time::{SystemTime, Duration};
use raw::CONTROL_SEQUENCE_TIMEOUT;
derive_csi_sequence!("Hide the cursor.", Hide, "?25l");
derive_csi_sequence!("Show the cursor.", Show, "?25h");
derive_csi_sequence!... |
}
/// Types that allow detection of the cursor position.
pub trait DetectCursorPos {
/// Get the (1,1)-based cursor position from the terminal.
fn cursor_pos(&mut self) -> io::Result<(u16, u16)>;
}
impl<W: Write> DetectCursorPos for W {
fn cursor_pos(&mut self) -> io::Result<(u16, u16)> {
let mut... | {
write!(f, csi!("{}B"), self.0)
} | identifier_body |
cursor.rs | //! Cursor movement.
use std::fmt;
use std::io::{self, Write, Error, ErrorKind, Read};
use async::async_stdin;
use std::time::{SystemTime, Duration};
use raw::CONTROL_SEQUENCE_TIMEOUT;
derive_csi_sequence!("Hide the cursor.", Hide, "?25l");
derive_csi_sequence!("Show the cursor.", Show, "?25h");
derive_csi_sequence!... |
}
if read_chars.len() == 0 {
return Err(Error::new(ErrorKind::Other, "Cursor position detection timed out."));
}
// The answer will look like `ESC [ Cy ; Cx R`.
read_chars.pop(); // remove trailing R.
let read_str = String::from_utf8(read_chars).unwrap();
... | {
read_chars.push(buf[0]);
} | conditional_block |
dateField.js | import { lpad } from '../../utils';
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import { ControlLabel, FormControl, FormGroup, HelpBlock } from 'react-bootstrap';
/**
* Date Field - Used to create a three field component capturing the Day Month Year.
* @class
*/
export default clas... | month: PropTypes.number.isRequired,
year: PropTypes.number.isRequired
}; | placeholder: PropTypes.string.isRequired,
onChange: PropTypes.func.isRequired,
help: PropTypes.string.isRequired,
day: PropTypes.number.isRequired, | random_line_split |
dateField.js | import { lpad } from '../../utils';
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import { ControlLabel, FormControl, FormGroup, HelpBlock } from 'react-bootstrap';
/**
* Date Field - Used to create a three field component capturing the Day Month Year.
* @class
*/
export default clas... |
render () {
return (
<FormGroup data-component-name={this.displayName} controlId={this.props.fieldId} validationState={this.props.validator(this.props.getModelToValidate(this.props.value))}>
<ControlLabel aria-hidden="true">{this.props.label}</ControlLabel>
<div className="container-fluid"... | {
return function (e) {
let year = (datePart === 'year') ? e.target.value : this.props.year;
let month = (datePart === 'month') ? e.target.value : this.props.month;
let day = (datePart === 'day') ? e.target.value : this.props.day;
this.props.onChange({ target: { value: lpad(year, 4) + '-' +... | identifier_body |
dateField.js | import { lpad } from '../../utils';
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import { ControlLabel, FormControl, FormGroup, HelpBlock } from 'react-bootstrap';
/**
* Date Field - Used to create a three field component capturing the Day Month Year.
* @class
*/
export default clas... | () {
return (
<FormGroup data-component-name={this.displayName} controlId={this.props.fieldId} validationState={this.props.validator(this.props.getModelToValidate(this.props.value))}>
<ControlLabel aria-hidden="true">{this.props.label}</ControlLabel>
<div className="container-fluid" style={{ ... | render | identifier_name |
mod.clean.js | "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const q = require("smartq");
const paths = require("../npmts.paths");
const plugins = require("./mod.plugins");
/**
* removes the dist directory which will be entirely rebuild
*/
let removeDist = function () {
plugins.beautylog.ora.text... | * remove old pages
*/
let removePages = function () {
plugins.beautylog.ora.text('cleaning pages folder');
return plugins.smartfile.fs.remove(paths.pagesDir);
};
exports.run = function (configArg) {
plugins.beautylog.ora.text('cleaning up from previous builds...');
let done = q.defer();
removeDist... | return plugins.smartfile.fs.remove(paths.distDir);
};
/** | random_line_split |
union-abi.rs | // ignore-emscripten vectors passed directly
// compile-flags: -C no-prepopulate-passes
// This test that using union forward the abi of the inner type, as
// discussed in #54668
#![crate_type="lib"]
#![feature(repr_simd)]
#[derive(Copy, Clone)]
pub enum Unhab {}
#[repr(simd)]
#[derive(Copy, Clone)]
pub struct i64x... |
pub union UnionF32{a:f32}
// CHECK: define float @test_UnionF32(float %_1)
#[no_mangle]
pub fn test_UnionF32(_: UnionF32) -> UnionF32 { loop {} }
pub union UnionF32F32{a:f32, b:f32}
// CHECK: define float @test_UnionF32F32(float %_1)
#[no_mangle]
pub fn test_UnionF32F32(_: UnionF32F32) -> UnionF32F32 { loop {} }
... | { loop {} } | identifier_body |
union-abi.rs | // ignore-emscripten vectors passed directly
// compile-flags: -C no-prepopulate-passes
// This test that using union forward the abi of the inner type, as
// discussed in #54668
#![crate_type="lib"]
#![feature(repr_simd)]
#[derive(Copy, Clone)]
pub enum Unhab {}
#[repr(simd)]
#[derive(Copy, Clone)]
pub struct i64x... |
pub union UnionF32U32{a:f32, b:u32}
// CHECK: define i32 @test_UnionF32U32(i32{{( %0)?}})
#[no_mangle]
pub fn test_UnionF32U32(_: UnionF32U32) -> UnionF32U32 { loop {} }
pub union UnionU128{a:u128}
// CHECK: define i128 @test_UnionU128(i128 %_1)
#[no_mangle]
pub fn test_UnionU128(_: UnionU128) -> UnionU128 { loop {}... | #[no_mangle]
pub fn test_UnionF32F32(_: UnionF32F32) -> UnionF32F32 { loop {} } | random_line_split |
union-abi.rs | // ignore-emscripten vectors passed directly
// compile-flags: -C no-prepopulate-passes
// This test that using union forward the abi of the inner type, as
// discussed in #54668
#![crate_type="lib"]
#![feature(repr_simd)]
#[derive(Copy, Clone)]
pub enum Unhab {}
#[repr(simd)]
#[derive(Copy, Clone)]
pub struct i64x... | (b: UnionBool) -> bool { unsafe { b.b } }
// CHECK: %0 = trunc i8 %b to i1
| test_UnionBool | identifier_name |
views.py | import datetime
from django.views.generic.detail import SingleObjectMixin
from django.views.generic.list import ListView
from django.views.generic.base import View
from django.utils.translation import ugettext as _
from django.http import Http404, HttpResponseRedirect
from django.core.urlresolvers import reverse
from... | data["year"] = self.kwargs.get('date__year', None)
data["month"] = self.kwargs.get('date__month', None)
data["day"] = self.kwargs.get('date__day', None)
blogslug = self.kwargs.get('blog__slug', False)
if blogslug:
blog = Blog.objects.filter(slug=blogslug).first()
... |
def get_context_data(self, *args, **kwargs):
data = super(PostListView, self).get_context_data(*args, **kwargs)
data["range_start"] = self.range_start | random_line_split |
views.py | import datetime
from django.views.generic.detail import SingleObjectMixin
from django.views.generic.list import ListView
from django.views.generic.base import View
from django.utils.translation import ugettext as _
from django.http import Http404, HttpResponseRedirect
from django.core.urlresolvers import reverse
from... |
self.request._blogs_current_date = self.range_start
self.request._blogs_current_year = int(self.kwargs.get('date__year', 0))
self.request._blogs_current_month = int(self.kwargs.get('date__month', 0))
self.request._blogs_current_day = int(self.kwargs.get('date__day', 0))
return d... | blog = Blog.objects.filter(slug=blogslug).first()
if blog is None:
raise Http404(_("Blog not found"))
data["blog"] = blog
self.request._blogs_current_blog = blog | conditional_block |
views.py | import datetime
from django.views.generic.detail import SingleObjectMixin
from django.views.generic.list import ListView
from django.views.generic.base import View
from django.utils.translation import ugettext as _
from django.http import Http404, HttpResponseRedirect
from django.core.urlresolvers import reverse
from... | (self, *args, **kwargs):
try:
self.range_start = datetime.date(
year=int(self.kwargs.get("date__year", 1)),
month=int(self.kwargs.get("date__month", 1)),
day=int(self.kwargs.get("date__day", 1)),
)
except ValueError:
rai... | dispatch | identifier_name |
views.py | import datetime
from django.views.generic.detail import SingleObjectMixin
from django.views.generic.list import ListView
from django.views.generic.base import View
from django.utils.translation import ugettext as _
from django.http import Http404, HttpResponseRedirect
from django.core.urlresolvers import reverse
from... |
def get_object(self):
queryset = self.get_queryset()
obj = queryset.first()
if obj is None:
raise Http404(_("No %(verbose_name)s found matching the query") %
{'verbose_name': queryset.model._meta.verbose_name})
return obj
class PostListView(... | data = super(PostView, self).get_context_data(*args, **kwargs)
self.request._blogs_current_blog = self.object.blog
self.request._blogs_current_date = self.object.date
self.request._blogs_current_year = int(self.kwargs.get('date__year', 0))
self.request._blogs_current_month = int(self.kwa... | identifier_body |
config.py | # Authors: Karl MacMillan <kmacmill@redhat.com>
#
# Copyright (C) 2007 Red Hat
# see file 'COPYING' for use and warranty information
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either ver... | (self, opts):
"""
Returns all options except those with sensitive=True in the same
fashion as parse_args would
"""
all_opts_dict = {
o.dest: o for o in self._get_all_options()
if hasattr(o, 'sensitive')
}
safe_opts_dict = {}
for op... | get_safe_opts | identifier_name |
config.py | # Authors: Karl MacMillan <kmacmill@redhat.com>
#
# Copyright (C) 2007 Red Hat
# see file 'COPYING' for use and warranty information
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either ver... |
def get_server(self):
if len(self.default_server):
return self.default_server
else:
raise IPAConfigError("no default server")
def get_domain(self):
if self.default_domain:
return self.default_domain
else:
raise IPAConfigError("no... | if self.default_realm:
return self.default_realm
else:
raise IPAConfigError("no default realm") | identifier_body |
config.py | # Authors: Karl MacMillan <kmacmill@redhat.com>
#
# Copyright (C) 2007 Red Hat
# see file 'COPYING' for use and warranty information
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either ver... |
else:
raise IPAConfigError("no default realm")
def get_server(self):
if len(self.default_server):
return self.default_server
else:
raise IPAConfigError("no default server")
def get_domain(self):
if self.default_domain:
return sel... | return self.default_realm | conditional_block |
config.py | # Authors: Karl MacMillan <kmacmill@redhat.com>
#
# Copyright (C) 2007 Red Hat
# see file 'COPYING' for use and warranty information
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either ver... | else:
needed_list = []
len_need = len(needed_list)
len_have = len(args)
if len_have > len_need:
parser.error("too many arguments")
elif len_have < len_need:
parser.error("no %s specified" % needed_list[len_have])
class IPAConfig:
def __init__(self):
self.default... | if needed_args:
needed_list = needed_args.split(" ") | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.