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 |
|---|---|---|---|---|
modlog.js | await checkRoomModlog(fileName, searchStringRegex, results);
}
}
const resultData = results.getListClone();
return resultData;
}
async function checkRoomModlog(path, regex, results) {
const fileStream = await FS(path).createReadStream();
let line;
while ((line = await fileStream.readLine()) !== null) {
if (... | return results;
}
function prettifyResults(resultArray, roomid, searchString, exactSearch, addModlogLinks, hideIps, maxLines, onlyPunishments) {
if (resultArray === null) {
return "|popup|The modlog query has crashed.";
}
let roomName;
switch (roomid) {
case 'all':
roomName = "all rooms";
break;
case 'pu... | {
let output;
try {
const options = [
'-i',
'-m', '' + lines,
'--pre', 'tac',
'-e', regexString,
'--no-filename',
'--no-line-number',
...paths,
'-g', '!modlog_global.txt', '-g', '!README.md',
];
output = await execFile('rg', options, {cwd: path.normalize(`${__dirname}/../../`)});
} catc... | identifier_body |
modlog.js | regexString,
'--no-filename',
'--no-line-number',
...paths,
'-g', '!modlog_global.txt', '-g', '!README.md',
];
output = await execFile('rg', options, {cwd: path.normalize(`${__dirname}/../../`)});
} catch (error) {
return results;
}
for (const fileName of output.stdout.split('\n').reverse()) {
i... | const foe = toID(data.p1) === userid ? toID(data.p2) : toID(data.p1);
if (!results[foe]) results[foe] = 0;
results[foe]++;
} | random_line_split | |
modlog.js | human: true}).split(' ');
if (date !== curDate) {
curDate = date;
date = `</p><p>[${date}]<br />`;
} else {
date = ``;
}
if (!line) {
return `${date}<small>[${timestamp}] \u2190 current server time</small>`;
}
let parenIndex = line.indexOf(')');
let thisRoomID = line.slice(bracketIndex + 3, pa... | modlog | identifier_name | |
structured_data_annotator.py | #!/usr/bin/env python
from __future__ import absolute_import
from .annotator import Annotator, AnnoTier, AnnoSpan
import re
import pyparsing as pypar
def word_token_regex(disallowed_delimiter):
return pypar.Regex(r"[^\s\n" + re.escape(disallowed_delimiter) + r"]+")
pypar.ParserElement.setDefaultWhitespaceChars(... |
elif any(re.match(r"\d*$", value.text) for value in new_value_spans):
continue
# Skip tables with differing numbers of columns in each row
else:
row_lengths = sorted([len(row) for row in data])
# Determine the min and max diffe... | continue | conditional_block |
structured_data_annotator.py | #!/usr/bin/env python
from __future__ import absolute_import
from .annotator import Annotator, AnnoTier, AnnoSpan
import re
import pyparsing as pypar
def word_token_regex(disallowed_delimiter):
|
pypar.ParserElement.setDefaultWhitespaceChars(" \t")
table_parser = pypar.NoMatch()
table_cell_separators = ["|", "/", ","]
for separator in table_cell_separators:
value = pypar.Combine(
word_token_regex(separator) * (0, 10),
joinString=' ',
adjacent=False)
value.setParseAction(lambda... | return pypar.Regex(r"[^\s\n" + re.escape(disallowed_delimiter) + r"]+") | identifier_body |
structured_data_annotator.py | #!/usr/bin/env python
from __future__ import absolute_import
from .annotator import Annotator, AnnoTier, AnnoSpan
import re
import pyparsing as pypar
def word_token_regex(disallowed_delimiter):
return pypar.Regex(r"[^\s\n" + re.escape(disallowed_delimiter) + r"]+")
pypar.ParserElement.setDefaultWhitespaceChars(... | (Annotator):
"""
Annotates tables and key value lists embedded in documents.
"""
def annotate(self, doc):
doc_text_len = len(doc.text)
def create_trimmed_annospan_for_doc(start, end, label=None, metadata=None):
return AnnoSpan(
start,
min(doc... | StructuredDataAnnotator | identifier_name |
structured_data_annotator.py | #!/usr/bin/env python
from __future__ import absolute_import
from .annotator import Annotator, AnnoTier, AnnoSpan
import re
import pyparsing as pypar
def word_token_regex(disallowed_delimiter):
return pypar.Regex(r"[^\s\n" + re.escape(disallowed_delimiter) + r"]+")
| table_cell_separators = ["|", "/", ","]
for separator in table_cell_separators:
value = pypar.Combine(
word_token_regex(separator) * (0, 10),
joinString=' ',
adjacent=False)
value.setParseAction(lambda start, tokens: (start, tokens[0]))
empty = pypar.Empty()
empty.setParseAction(... | pypar.ParserElement.setDefaultWhitespaceChars(" \t")
table_parser = pypar.NoMatch() | random_line_split |
codeFixNoPropertyAccessFromIndexSignature_fixAll.ts | /// <reference path='fourslash.ts'/>
// @noPropertyAccessFromIndexSignature: true
//// interface A {
//// foo: string
//// }
//// interface B {
//// [k: string]: string
//// }
//// interface C {
//// foo: string
//// [k: string]: string
//// }
//// declare const a: A;
//// declare const b... | newFileContent:
`interface A {
foo: string
}
interface B {
[k: string]: string
}
interface C {
foo: string
[k: string]: string
}
declare const a: A;
declare const b: B;
declare const c: C;
declare const d: C | undefined;
a.foo;
a["foo"];
b["foo"];
b["foo"];
c.foo;
c["foo"];
c["b... |
verify.codeFixAll({
fixId: 'fixNoPropertyAccessFromIndexSignature',
fixAllDescription: ts.Diagnostics.Use_element_access_for_all_undeclared_properties.message,
| random_line_split |
Layout.tsx | import React from 'react';
import { createSelector } from 'reselect';
import block from 'bem-cn';
import { withRouter, RouteComponentProps } from 'react-router-dom';
import { autobind } from 'core-decorators';
import { LanguageSelector, withTranslation, ITranslationProps, tKeys } from 'services/i18n';
import { withAsy... | const { history } = this.props;
history.push(routes.profile.getRoutePath());
}
}
const wrappedComponent = withTranslation()(withRouter(LayoutComponent));
const Layout = withAsyncFeatures({
profileFeatureEntry: features.profile.loadEntry,
})(wrappedComponent);
export { Layout, LayoutComponent, IProps as IL... |
@autobind
private handleEditProfileClick() { | random_line_split |
maas.py | # Copyright (C) 2013 Adam Stokes <adam.stokes@ubuntu.com>
#
# 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 version 2 of the License, or
# (at your option) any later version.
# This prog... |
def _remote_api_login(self):
ret = self.call_ext_prog("maas login %s %s %s" % (
self.get_option("profile-name"),
self.get_option("url"),
self.get_option("credentials")))
return ret['status'] == 0
def setup(self):
self.add_copy_spec([
"/... | return self.get_option("url") and self.get_option("credentials") \
and self.get_option("profile-name") | identifier_body |
maas.py | # Copyright (C) 2013 Adam Stokes <adam.stokes@ubuntu.com>
#
# 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 version 2 of the License, or
# (at your option) any later version.
# This prog... | "/var/log/maas*",
"/var/log/upstart/maas-*",
])
self.add_cmd_output([
"apt-cache policy maas-*",
"apt-cache policy python-django-*",
])
if self.is_installed("maas-region-controller"):
self.add_cmd_output([
"maas... | "/var/lib/maas/dhcp*",
"/var/log/apache2*", | random_line_split |
maas.py | # Copyright (C) 2013 Adam Stokes <adam.stokes@ubuntu.com>
#
# 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 version 2 of the License, or
# (at your option) any later version.
# This prog... |
# vim: set et ts=4 sw=4 :
| if self._remote_api_login():
self.add_cmd_output("maas %s commissioning-results list" %
self.get_option("profile-name"))
else:
self._log_error(
"Cannot login into MAAS remote API with provided creds.") | conditional_block |
maas.py | # Copyright (C) 2013 Adam Stokes <adam.stokes@ubuntu.com>
#
# 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 version 2 of the License, or
# (at your option) any later version.
# This prog... | (self):
ret = self.call_ext_prog("maas login %s %s %s" % (
self.get_option("profile-name"),
self.get_option("url"),
self.get_option("credentials")))
return ret['status'] == 0
def setup(self):
self.add_copy_spec([
"/etc/squid-deb-proxy",
... | _remote_api_login | identifier_name |
add-project-popover.controller.ts | /*
* Copyright (c) 2015-2018 Red Hat, Inc.
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Red Hat, Inc. - initial API a... | (projectTemplates: Array<che.IProjectTemplate>): void {
this.projectOnAdd({templates: projectTemplates});
// close popover
this.isOpen = false;
}
}
| projectTemplateOnAdd | identifier_name |
add-project-popover.controller.ts | /*
* Copyright (c) 2015-2018 Red Hat, Inc.
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Red Hat, Inc. - initial API a... | /* tslint:enable */
/**
* Callback which is called when project templates are added to the list of ready-to-import projects.
* Provided by parent controller.
*/
private projectOnAdd: (data: {templates: Array<che.IProjectTemplate>}) => void;
/**
* Default constructor that is using resource injection... | * Callback to check uniqueness of project name.
* Provided by parent controller.
*/
/* tslint:disable */
private isProjectNameUnique: (data: {name: string}) => boolean; | random_line_split |
CascadeSelect.d.ts | import * as React from 'react';
declare namespace CascadeSelect { |
interface ChangeParams {
originalEvent: React.SyntheticEvent;
value: any;
}
interface GroupChangeParams extends ChangeParams { }
interface CascadeSelectProps {
id?: string;
inputRef?: React.Ref<HTMLInputElement>;
style?: object;
className?: string;
... |
type ItemTemplateType = React.ReactNode | ((option: any) => React.ReactNode); | random_line_split |
CascadeSelect.d.ts | import * as React from 'react';
declare namespace CascadeSelect {
type ItemTemplateType = React.ReactNode | ((option: any) => React.ReactNode);
interface ChangeParams {
originalEvent: React.SyntheticEvent;
value: any;
}
interface GroupChangeParams extends ChangeParams { }
interf... | extends React.Component<CascadeSelect.CascadeSelectProps, any> { }
| CascadeSelect | identifier_name |
make-cert.py | #!/usr/bin/python
# Copyright 2015 Rackspace, 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 or... |
def _get_public_ip():
return requests.get(PUBLIC_IP_URL).text
def _build_subject_alt_names(config):
subject_alt_names = [
'IP:%s' % _get_public_ip(),
'IP:%s' % config['SWARM_NODE_IP'],
'IP:127.0.0.1'
]
return ','.join(subject_alt_names)
def write_ca_cert(config):
bay_c... | os.makedirs(CERT_CONF_DIR) | identifier_body |
make-cert.py | #!/usr/bin/python
# Copyright 2015 Rackspace, 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 or... |
return parsed_value[1:-1]
def load_config():
config = dict()
with open(HEAT_PARAMS_PATH, 'r') as fp:
for line in fp.readlines():
key, value = line.split('=', 1)
config[key] = _parse_config_value(value)
return config
def create_dirs():
os.makedirs(CERT_CONF_DIR)
... | parsed_value = parsed_value[:-1] | conditional_block |
make-cert.py | #!/usr/bin/python
# Copyright 2015 Rackspace, 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 or... | (config):
subject_alt_names = [
'IP:%s' % _get_public_ip(),
'IP:%s' % config['SWARM_NODE_IP'],
'IP:127.0.0.1'
]
return ','.join(subject_alt_names)
def write_ca_cert(config):
bay_cert_url = '%s/certificates/%s' % (config['MAGNUM_URL'],
... | _build_subject_alt_names | identifier_name |
make-cert.py | #!/usr/bin/python
# Copyright 2015 Rackspace, 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 or... | '-reqexts', 'req_ext',
'-extensions', 'req_ext',
'-config', SERVER_CONF_PATH])
with open(SERVER_CSR_PATH, 'r') as fp:
return {'bay_uuid': config['BAY_UUID'], 'csr': fp.read()}
def write_server_cert(config, csr_req):
cert_url = '%s/certifi... | '-days', '1000',
'-key', SERVER_KEY_PATH,
'-out', SERVER_CSR_PATH, | random_line_split |
chatsService.js | appService.factory('Chats', function() {
// Might use a resource here that returns a JSON array
// Some fake testing data
var chats = [{
id: 0,
name: 'Ben Sparrow',
lastText: 'You on your way?',
face: 'app/view/common/img/ben.png'
}, {
id: 1,
name: 'Max Lynx',
lastText: ... |
return null;
}
};
}); | {
if (chats[i].id === parseInt(chatId)) {
return chats[i];
}
} | conditional_block |
chatsService.js | appService.factory('Chats', function() {
// Might use a resource here that returns a JSON array
// Some fake testing data
var chats = [{
id: 0,
name: 'Ben Sparrow',
lastText: 'You on your way?',
face: 'app/view/common/img/ben.png'
}, {
id: 1,
name: 'Max Lynx',
lastText: ... | face: 'app/view/common/img/adam.jpg'
}, {
id: 3,
name: 'Perry Governor',
lastText: 'Look at my mukluks!',
face: 'app/view/common/img/perry.png'
}, {
id: 4,
name: 'Mike Harrington',
lastText: 'This is wicked good ice cream.',
face: 'app/view/common/img/mike.png'
}];
... | }, {
id: 2,
name: 'Adam Bradleyson',
lastText: 'I should buy a boat',
| random_line_split |
test-child-process-fork-stdio.js | 'use strict';
const common = require('../common');
const assert = require('assert');
const cp = require('child_process');
const net = require('net');
if (process.argv[2] === 'child') {
process.stdout.write('this should be ignored');
process.stderr.write('this should not be ignored');
const pipe = new net.Socket... | });
child.stderr.on('data', (chunk) => {
stderr += chunk;
});
child.on('exit', common.mustCall((code, signal) => {
assert.strictEqual(code, 0);
assert.strictEqual(signal, null);
assert.strictEqual(stderr, 'this should not be ignored');
}));
child.stdio[4].write(buf);
}
| {
assert.throws(() => {
cp.fork(__filename, {stdio: ['pipe', 'pipe', 'pipe', 'pipe']});
}, /Forked processes must have an IPC channel/);
let ipc = '';
let stderr = '';
const buf = Buffer.from('data to send via pipe');
const child = cp.fork(__filename, ['child'], {
stdio: [0, 'ignore', 'pipe', 'ipc'... | conditional_block |
test-child-process-fork-stdio.js | 'use strict';
const common = require('../common');
const assert = require('assert');
const cp = require('child_process');
const net = require('net');
if (process.argv[2] === 'child') { | process.on('disconnect', () => {
pipe.unref();
});
pipe.setEncoding('utf8');
pipe.on('data', (data) => {
process.send(data);
});
} else {
assert.throws(() => {
cp.fork(__filename, {stdio: ['pipe', 'pipe', 'pipe', 'pipe']});
}, /Forked processes must have an IPC channel/);
let ipc = '';
l... | process.stdout.write('this should be ignored');
process.stderr.write('this should not be ignored');
const pipe = new net.Socket({ fd: 4 });
| random_line_split |
errors.js | 'use strict';
var util = require('util'),
errors = module.exports = {};
errors.BaseError = function() {
var tmp = Error.apply(this, arguments);
tmp.name = this.name = 'QMFError';
this.message = tmp.message;
if (Error.captureStackTrace)
Error.captureStackTrace(this, this.constructor);
};
util.inherits(... |
errors.InvalidResponseError = function(opcode) {
errors.BaseError.call(this, opcode);
this.name = 'QMFInvalidResponseError';
this.opcode = opcode;
};
util.inherits(errors.InvalidResponseError, errors.BaseError);
errors.TimeoutError = function() {
errors.BaseError.call(this, 'request timed out');
this.name =... | random_line_split | |
inventory.component.ts | import { Component, Input, OnInit } from '@angular/core';
import { Select } from '@ngxs/store';
import { Observable } from 'rxjs';
import { IPlayer } from '../../../../interfaces';
import { GameState } from '../../../../stores';
import { UIService } from '../../../services/ui.service';
@Component({
selector: 'app-in... | () {
return Array(this.size).fill(null).map((v, i) => i);
}
constructor(public uiService: UIService) { }
ngOnInit() {
}
}
| slots | identifier_name |
inventory.component.ts | import { Component, Input, OnInit } from '@angular/core'; | import { UIService } from '../../../services/ui.service';
@Component({
selector: 'app-inventory',
templateUrl: './inventory.component.html',
styleUrls: ['./inventory.component.scss']
})
export class InventoryComponent implements OnInit {
@Select(GameState.player) player$: Observable<IPlayer>;
@Input() publ... | import { Select } from '@ngxs/store';
import { Observable } from 'rxjs';
import { IPlayer } from '../../../../interfaces';
import { GameState } from '../../../../stores'; | random_line_split |
inventory.component.ts | import { Component, Input, OnInit } from '@angular/core';
import { Select } from '@ngxs/store';
import { Observable } from 'rxjs';
import { IPlayer } from '../../../../interfaces';
import { GameState } from '../../../../stores';
import { UIService } from '../../../services/ui.service';
@Component({
selector: 'app-in... |
ngOnInit() {
}
}
| { } | identifier_body |
to_str.rs | use ::ffi;
use ::libc::c_char;
use std::ffi::CStr;
// To-string converters
// See http://www.libnfc.org/api/group__string-converter.html | pub fn modulation_type(pnd: ffi::nfc_modulation_type) -> &'static str {
unsafe {
let modulation_type = CStr::from_ptr(ffi::str_nfc_modulation_type(pnd)).to_str().unwrap();
modulation_type
}
}
/// Converts nfc_baud_rate value to string
pub fn baud_rate(baud_rate: ffi::nfc_baud_rate) -> &'static... |
/// Converts nfc_modulation_type value to string | random_line_split |
to_str.rs | use ::ffi;
use ::libc::c_char;
use std::ffi::CStr;
// To-string converters
// See http://www.libnfc.org/api/group__string-converter.html
/// Converts nfc_modulation_type value to string
pub fn modulation_type(pnd: ffi::nfc_modulation_type) -> &'static str {
unsafe {
let modulation_type = CStr::from_ptr(f... |
/// Returns the number of characters printed
pub fn target(buf: *mut *mut c_char, pnt: *mut ffi::nfc_target, verbose: u8) -> i32 {
unsafe { ffi::str_nfc_target(buf, pnt, verbose) }
} | {
unsafe {
let baud_rate = CStr::from_ptr(ffi::str_nfc_baud_rate(baud_rate)).to_str().unwrap();
baud_rate
}
} | identifier_body |
to_str.rs | use ::ffi;
use ::libc::c_char;
use std::ffi::CStr;
// To-string converters
// See http://www.libnfc.org/api/group__string-converter.html
/// Converts nfc_modulation_type value to string
pub fn modulation_type(pnd: ffi::nfc_modulation_type) -> &'static str {
unsafe {
let modulation_type = CStr::from_ptr(f... | (baud_rate: ffi::nfc_baud_rate) -> &'static str {
unsafe {
let baud_rate = CStr::from_ptr(ffi::str_nfc_baud_rate(baud_rate)).to_str().unwrap();
baud_rate
}
}
/// Returns the number of characters printed
pub fn target(buf: *mut *mut c_char, pnt: *mut ffi::nfc_target, verbose: u8) -> i32 {
u... | baud_rate | identifier_name |
kendo.culture.nn.js | /*
* Kendo UI Web v2014.1.318 (http://kendoui.com)
* Copyright 2014 Telerik AD. All rights reserved.
*
* Kendo UI Web commercial licenses may be obtained at
* http://www.telerik.com/purchase/license-agreement/kendo-ui-web
* If you do not own a commercial license, this file shall be governed by the
* GNU General Public ... | days: {
names: ["søndag","måndag","tysdag","onsdag","torsdag","fredag","laurdag"],
namesAbbr: ["sø","må","ty","on","to","fr","la"],
namesShort: ["sø","må","ty","on","to","fr","la"]
},
months: {
... | },
calendars: {
standard: { | random_line_split |
tapGesture.ts | import { BaseGestureConfig, BaseGesture } from './gesture';
import {
TapGestureConfig,
TapGestureHandlerEventPayload,
} from '../TapGestureHandler';
export class TapGesture extends BaseGesture<TapGestureHandlerEventPayload> {
public config: BaseGestureConfig & TapGestureConfig = {};
constructor() {
super(... |
maxDeltaY(delta: number) {
this.config.maxDeltaY = delta;
return this;
}
}
export type TapGestureType = InstanceType<typeof TapGesture>;
| {
this.config.maxDeltaX = delta;
return this;
} | identifier_body |
tapGesture.ts | import { BaseGestureConfig, BaseGesture } from './gesture';
import {
TapGestureConfig,
TapGestureHandlerEventPayload,
} from '../TapGestureHandler';
export class TapGesture extends BaseGesture<TapGestureHandlerEventPayload> {
public config: BaseGestureConfig & TapGestureConfig = {};
constructor() {
super(... | maxDeltaX(delta: number) {
this.config.maxDeltaX = delta;
return this;
}
maxDeltaY(delta: number) {
this.config.maxDeltaY = delta;
return this;
}
}
export type TapGestureType = InstanceType<typeof TapGesture>; | }
| random_line_split |
tapGesture.ts | import { BaseGestureConfig, BaseGesture } from './gesture';
import {
TapGestureConfig,
TapGestureHandlerEventPayload,
} from '../TapGestureHandler';
export class TapGesture extends BaseGesture<TapGestureHandlerEventPayload> {
public config: BaseGestureConfig & TapGestureConfig = {};
constructor() {
super(... | (maxDist: number) {
this.config.maxDist = maxDist;
return this;
}
maxDuration(duration: number) {
this.config.maxDurationMs = duration;
return this;
}
maxDelay(delay: number) {
this.config.maxDelayMs = delay;
return this;
}
maxDeltaX(delta: number) {
this.config.maxDeltaX = de... | maxDistance | identifier_name |
name.rs | use std;
/// Represents a name.
#[derive(Clone,Debug)]
pub enum Name
{
/// The value is unnamed.
Unnamed,
/// The value has a name.
Named(String),
}
impl Name
{
/// Create an unspecified name.
pub fn unnamed() -> Name {
Name::Unnamed
} |
Name::Named(name.into())
}
pub fn is_named(&self) -> bool {
match *self {
Name::Unnamed => false,
Name::Named(..) => true,
}
}
}
impl Into<String> for Name
{
fn into(self) -> String {
match self {
Name::Unnamed => unimplemented!(),
... |
pub fn named<S>(name: S) -> Name
where S: Into<String> { | random_line_split |
name.rs | use std;
/// Represents a name.
#[derive(Clone,Debug)]
pub enum Name
{
/// The value is unnamed.
Unnamed,
/// The value has a name.
Named(String),
}
impl Name
{
/// Create an unspecified name.
pub fn unnamed() -> Name {
Name::Unnamed
}
pub fn named<S>(name: S) -> Name
... | (&self, other: &Name) -> bool {
match (self,other) {
(&Name::Named(ref n1),
&Name::Named(ref n2)) => n1 == n2,
_ => false, // unnamed values are always unique
}
}
}
impl std::cmp::Eq for Name { }
| eq | identifier_name |
name.rs | use std;
/// Represents a name.
#[derive(Clone,Debug)]
pub enum Name
{
/// The value is unnamed.
Unnamed,
/// The value has a name.
Named(String),
}
impl Name
{
/// Create an unspecified name.
pub fn unnamed() -> Name {
Name::Unnamed
}
pub fn named<S>(name: S) -> Name
... |
}
impl std::cmp::Eq for Name { }
| {
match (self,other) {
(&Name::Named(ref n1),
&Name::Named(ref n2)) => n1 == n2,
_ => false, // unnamed values are always unique
}
} | identifier_body |
traits.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... | (&mut self) -> Result<u32, UtilError> {
let mut batch = self.backing().transaction();
let res = self.inject(&mut batch)?;
self.backing().write(batch).map(|_| res).map_err(Into::into)
}
}
| inject_batch | identifier_name |
traits.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... |
/// Get the latest era in the DB. None if there isn't yet any data in there.
fn latest_era(&self) -> Option<u64>;
/// Journal recent database operations as being associated with a given era and id.
// TODO: give the overlay to this function so journaldbs don't manage the overlays themeselves.
fn ... | {
None
} | identifier_body |
traits.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... |
let result = self.backing().write(batch).map(|_| ops).map_err(Into::into);
self.flush();
result
}
/// Inject all changes in a single batch.
#[cfg(test)]
fn inject_batch(&mut self) -> Result<u32, UtilError> {
let mut batch = self.backing().transaction();
let res... | {
ops += self.mark_canonical(&mut batch, end_era, &canon_id)?;
} | conditional_block |
traits.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... | let res = self.inject(&mut batch)?;
self.backing().write(batch).map(|_| res).map_err(Into::into)
}
} | #[cfg(test)]
fn inject_batch(&mut self) -> Result<u32, UtilError> {
let mut batch = self.backing().transaction(); | random_line_split |
SideBar.tsx | import * as React from 'react';
interface IProps {
siteUrl: string;
mail: string;
github: string;
}
const SideBar: React.FunctionComponent<IProps> = ({ siteUrl, mail, github }) => {
return (
<div className="sidebar-wrapper">
<div className="profile-container">
<img
className="profi... | <li className="github">
<i className="fa fa-github" />
<a href={github} target="_blank">
github.com/jicjjang
</a>
</li>
</ul>
</div>
<div className="education-container container-block">
<h2 className="container-block-tit... | </li> | random_line_split |
workqueue.rs | Start(Worker<WorkUnit<QueueData, WorkData>>, *mut AtomicUsize, *const QueueData),
/// Tells the worker to stop. It can be restarted again with a `WorkerMsg::Start`.
Stop,
/// Tells the worker thread to terminate.
Exit,
}
unsafe impl<QueueData: 'static, WorkData: 'static> Send for WorkerMsg<QueueDat... | {
let deque = &mut self.workers[0].deque;
match *deque {
None => {
panic!("tried to push a block but we don't have the deque?!")
}
Some(ref mut deque) => deque.push(work_unit),
}
self.work_count += 1
} | identifier_body | |
workqueue.rs | Msg<QueueData: 'static, WorkData: 'static> {
/// Tells the worker to start work.
Start(Worker<WorkUnit<QueueData, WorkData>>, *mut AtomicUsize, *const QueueData),
/// Tells the worker to stop. It can be restarted again with a `WorkerMsg::Start`.
Stop,
/// Tells the worker thread to terminate.
Ex... | {
panic!("tried to push a block but we don't have the deque?!")
} | conditional_block | |
workqueue.rs | atomic::{AtomicUsize, Ordering};
use std::sync::mpsc::{channel, Sender, Receiver};
/// A unit of work.
///
/// # Type parameters
///
/// - `QueueData`: global custom data for the entire work queue.
/// - `WorkData`: custom data specific to each unit of work.
pub struct WorkUnit<QueueData, WorkData> {
/// The funct... | <QueueData: 'static, WorkData: 'static> {
/// Tells the worker to start work.
Start(Worker<WorkUnit<QueueData, WorkData>>, *mut AtomicUsize, *const QueueData),
/// Tells the worker to stop. It can be restarted again with a `WorkerMsg::Start`.
Stop,
/// Tells the worker thread to terminate.
Exit,... | WorkerMsg | identifier_name |
workqueue.rs | atomic::{AtomicUsize, Ordering};
use std::sync::mpsc::{channel, Sender, Receiver};
/// A unit of work.
///
/// # Type parameters
///
/// - `QueueData`: global custom data for the entire work queue.
/// - `WorkData`: custom data specific to each unit of work.
pub struct WorkUnit<QueueData, WorkData> {
/// The funct... |
/// Information that the supervisor thread keeps about the worker threads.
struct WorkerInfo<QueueData: 'static, WorkData: 'static> {
/// The communication channel to the workers.
chan: Sender<WorkerMsg<QueueData, WorkData>>,
/// The worker end of the deque, if we have it.
deque: Option<Worker<WorkUnit... | ReturnDeque(usize, Worker<WorkUnit<QueueData, WorkData>>),
}
unsafe impl<QueueData: 'static, WorkData: 'static> Send for SupervisorMsg<QueueData, WorkData> {} | random_line_split |
index.ts | /// <reference path="typings/tsd.d.ts" />
'use strict';
var gutil = require('gulp-util');
var path = require("path");
var through = require('through2');
var beautylog = require("beautylog");
module.exports = function (options, logBool:boolean = false) {
//handle options
options = options ? options : {};
o... | initialBase = file.base;
}
return cb();
};
/**
* gets executed on end of stream, pipes the build json down the pipeline
* @param cb the callback to let gulp know that we are finished here
*/
var pipeJson = function (cb) {
if (filesInPipeline) {
... | filesInPipeline = true; | random_line_split |
index.ts | /// <reference path="typings/tsd.d.ts" />
'use strict';
var gutil = require('gulp-util');
var path = require("path");
var through = require('through2');
var beautylog = require("beautylog");
module.exports = function (options, logBool:boolean = false) {
//handle options
options = options ? options : {};
o... |
//create a new param on file with the String of the current Buffer as content
constructObject[file.relative] = String(file.contents);
//get base of first file
if(!firstFileProcessed) {
filesInPipeline = true;
initialBase = file.base;
}
return c... | {
this.emit('error', new gutil.PluginError('gulp-to-json', 'Streaming not supported'));
return cb();
} | conditional_block |
ioport.rs | // Copyright Dan Schatzberg, 2015. This file is part of Genesis.
// Genesis is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
... | } | random_line_split | |
ioport.rs | // Copyright Dan Schatzberg, 2015. This file is part of Genesis.
// Genesis is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
... | <T>(port: u16, val: T) {
asm!("out $0, $1"
: // no output
: "{al}" (val), "{dx}" (port)
: // no clobber
: "volatile");
}
pub unsafe fn inb(port: u16) -> u8 {
let val: u8;
asm!("in $1, $0"
: "={al}" (val)
: "{dx}" (port)
... | out | identifier_name |
ioport.rs | // Copyright Dan Schatzberg, 2015. This file is part of Genesis.
// Genesis is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
... | {
let val: u8;
asm!("in $1, $0"
: "={al}" (val)
: "{dx}" (port)
: // no clobber
: "volatile");
val
} | identifier_body | |
base.ts | /**
* @license
* Copyright 2016 Google 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 or... |
export const VECTOR_GRAPHICS_RPC_ID = 'vectorgraphics';
export const VECTOR_GRAPHICS_RENDERLAYER_RPC_ID = 'vectorgraphics/RenderLayer'; | toObject(): SliceViewChunkSpecificationOptions {
return super.toObject();
}
} | random_line_split |
base.ts | /**
* @license
* Copyright 2016 Google 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 or... | extends SliceViewChunkSpecification {
constructor(options: VectorGraphicsChunkSpecificationOptions) {
super(options);
}
static make(options: VectorGraphicsChunkSpecificationOptions&
{vectorGraphicsSourceOptions: VectorGraphicsSourceOptions}) {
return new VectorGraphicsChunkSpecification(Ob... | VectorGraphicsChunkSpecification | identifier_name |
base.ts | /**
* @license
* Copyright 2016 Google 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 or... |
static make(options: VectorGraphicsChunkSpecificationOptions&
{vectorGraphicsSourceOptions: VectorGraphicsSourceOptions}) {
return new VectorGraphicsChunkSpecification(Object.assign(
{}, options,
{transform: getCombinedTransform(options.transform, options.vectorGraphicsSourceOption... | {
super(options);
} | identifier_body |
vocabs.rs | extern crate rand;
use bahasa::bimap::Bimap;
pub struct Vocabs<'a> {
vocabs: Bimap<&'a str, &'a str>,
vocab_vector: Vec<&'a str>,
}
impl<'b> Vocabs<'b> {
pub fn new<'c> () -> Vocabs<'c> {
Vocabs { vocabs: Bimap::new(), vocab_vector: vec![] }
}
pub fn insert(&mut self, first: &'static st... | let index = (r * self.vocab_vector.len() as f64) as usize;
self.vocab_vector[index]
}
} | random_line_split | |
vocabs.rs | extern crate rand;
use bahasa::bimap::Bimap;
pub struct Vocabs<'a> {
vocabs: Bimap<&'a str, &'a str>,
vocab_vector: Vec<&'a str>,
}
impl<'b> Vocabs<'b> {
pub fn new<'c> () -> Vocabs<'c> |
pub fn insert(&mut self, first: &'static str, second: &'static str) {
self.vocabs.insert(first, second);
self.vocab_vector.push(first);
}
pub fn get<'a>(&'a self, string: &'a str) -> Option<&&str> {
self.vocabs.get(&string)
}
pub fn get_random(&self) -> &str {
let... | {
Vocabs { vocabs: Bimap::new(), vocab_vector: vec![] }
} | identifier_body |
vocabs.rs | extern crate rand;
use bahasa::bimap::Bimap;
pub struct Vocabs<'a> {
vocabs: Bimap<&'a str, &'a str>,
vocab_vector: Vec<&'a str>,
}
impl<'b> Vocabs<'b> {
pub fn new<'c> () -> Vocabs<'c> {
Vocabs { vocabs: Bimap::new(), vocab_vector: vec![] }
}
pub fn insert(&mut self, first: &'static st... | <'a>(&'a self, string: &'a str) -> Option<&&str> {
self.vocabs.get(&string)
}
pub fn get_random(&self) -> &str {
let r = rand::random::<f64>();
let index = (r * self.vocab_vector.len() as f64) as usize;
self.vocab_vector[index]
}
}
| get | identifier_name |
ceph-osd.service.js | /**
*
* @source: http://bitbucket.org/openattic/openattic
*
* @licstart The following is the entire license notice for the
* JavaScript code in this page.
*
* Copyright (C) 2011-2016, it-novum GmbH <community@openattic.org>
*
*
* The JavaScript code in this page is free software: you can
* redistribute it ... | {
constructor ($resource) {
const res = $resource(globalConfig.API.URL + "ceph/:fsid/osds", {
fsid: "@fsid",
osdid: "@osdid"
}, {
scrub: {
method: "POST",
url: globalConfig.API.URL + "ceph/:fsid/osds/:osdid/scrub"
}
});
Object.assign(this, res);
}
}
| CephOsdService | identifier_name |
ceph-osd.service.js | /**
*
* @source: http://bitbucket.org/openattic/openattic
*
* @licstart The following is the entire license notice for the
* JavaScript code in this page.
*
* Copyright (C) 2011-2016, it-novum GmbH <community@openattic.org>
*
*
* The JavaScript code in this page is free software: you can | * Foundation; version 2.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* As additional permission under GNU GPL ... | * redistribute it and/or modify it under the terms of the GNU
* General Public License as published by the Free Software | random_line_split |
monitor.rs | son_object_size: i64,
pub max_message_size_bytes: i64,
pub local_time: Option<DateTime<UTC>>,
pub min_wire_version: i64,
pub max_wire_version: i64,
/// Shard-specific. mongos instances will add this field to the
/// isMaster reply, and it will contain the value "isdbgrid".
pub msg: String,
... | let ismaster_result = IsMasterResult::new(doc);
let mut server_description = self.server_description.write(). | random_line_split | |
monitor.rs | _object_size: i64,
pub max_message_size_bytes: i64,
pub local_time: Option<DateTime<UTC>>,
pub min_wire_version: i64,
pub max_wire_version: i64,
/// Shard-specific. mongos instances will add this field to the
/// isMaster reply, and it will contain the value "isdbgrid".
pub msg: String,
... |
// Updates the server description associated with this monitor using an isMaster server response.
fn update_server_description(&self, doc: bson::Document,
round_trip_time: i64) -> Result<ServerDescription> {
let ismaster_result = IsMasterResult::new(doc);
let ... | {
self.condvar.notify_one();
} | identifier_body |
monitor.rs | ServerDescription>>,
// Client reference.
client: Client,
// Owned, single-threaded pool.
personal_pool: Arc<ConnectionPool>,
// Owned copy of the topology's heartbeat frequency.
heartbeat_frequency_ms: AtomicUsize,
// Used for condvar functionality.
dummy_lock: Mutex<()>,
// To allo... | execute_update | identifier_name | |
form_arrayrun.js | if (typeof FormTarget === 'undefined') {
FormTarget = {};
}
FormTarget.arrayrun = (function($) {
/*
* Expected config {
* isAdmin: boolean,
* instruments: array
* }
*/
return {
getUserManualUrl: function() {
return Urls.external.userManual('array_runs');
},
getSaveUrl: funct... | (label) {
return Utils.array.findUniqueOrThrow(function(item) {
return item.label === label;
}, Constants.healthTypes);
}
function updateSamplesTable(array) {
$('#listingSamplesTable').empty();
var data = [];
var lengthOptions = [50, 25, 10];
if (array) {
data = array.samples.ma... | getStatus | identifier_name |
form_arrayrun.js | if (typeof FormTarget === 'undefined') {
FormTarget = {};
}
FormTarget.arrayrun = (function($) {
/*
* Expected config {
* isAdmin: boolean,
* instruments: array
* }
*/
return {
getUserManualUrl: function() {
return Urls.external.userManual('array_runs');
},
getSaveUrl: funct... |
function updateSamplesTable(array) {
$('#listingSamplesTable').empty();
var data = [];
var lengthOptions = [50, 25, 10];
if (array) {
data = array.samples.map(function(sample) {
return [sample.coordinates, Box.utils.hyperlinkifyBoxable(sample.name, sample.id, sample.name),
... | {
return Utils.array.findUniqueOrThrow(function(item) {
return item.label === label;
}, Constants.healthTypes);
} | identifier_body |
form_arrayrun.js | if (typeof FormTarget === 'undefined') {
FormTarget = {};
}
FormTarget.arrayrun = (function($) {
/*
* Expected config {
* isAdmin: boolean,
* instruments: array
* }
*/
return {
getUserManualUrl: function() {
return Urls.external.userManual('array_runs');
},
getSaveUrl: funct... |
})];
}
}, {
title: 'Status',
data: 'status',
type: 'dropdown',
required: true,
source: Constants.healthTypes,
getItemLabel: function(item) {
return item.label;
},
getItemValue: function(item) {
... | {
Utils.showOkDialog('Remove Array', ['No array set']);
} | conditional_block |
form_arrayrun.js | if (typeof FormTarget === 'undefined') {
FormTarget = {};
}
FormTarget.arrayrun = (function($) {
/*
* Expected config {
* isAdmin: boolean,
* instruments: array
* }
*/
return {
getUserManualUrl: function() {
return Urls.external.userManual('array_runs');
},
getSaveUrl: funct... | return item.label;
},
onChange: function(newValue, form) {
var status = getStatus(newValue);
var updates = {
required: status.isDone,
// Editable if run is done and either there's no value set or user is admin
disabled: !s... | },
getItemValue: function(item) { | random_line_split |
index.js | var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
fetchRegisteredUsersAndRender(req, res);
});
router.get('/landingPageData', function(req, res, next) {
/*
var RegisteredUsers1 = {
"user-name": "Manu Mathew",
"d... |
module.exports = router; | {
var records;
var db = req.dbObject;
var registeredUsersCollection = db.get('RegisteredUsers');
registeredUsersCollection.find({}, function(err, registeredUsers) {
//Render
res.render('index', { title: 'Registered Users', RegisteredUsers: registeredUsers });
});
} | identifier_body |
index.js | var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
fetchRegisteredUsersAndRender(req, res);
});
router.get('/landingPageData', function(req, res, next) {
/*
var RegisteredUsers1 = {
"user-name": "Manu Mathew",
"d... | (req, res) {
var records;
var db = req.dbObject;
var registeredUsersCollection = db.get('RegisteredUsers');
registeredUsersCollection.find({}, function(err, registeredUsers) {
//Render
res.render('index', { title: 'Registered Users', RegisteredUsers: registeredUsers });
});... | fetchRegisteredUsersAndRender | identifier_name |
index.js | var express = require('express'); | /* GET home page. */
router.get('/', function(req, res, next) {
fetchRegisteredUsersAndRender(req, res);
});
router.get('/landingPageData', function(req, res, next) {
/*
var RegisteredUsers1 = {
"user-name": "Manu Mathew",
"date-of-birth" : "14-06-1982",
"gender" : "Male",
"... | var router = express.Router();
| random_line_split |
command.js | const command = () => ({
method: 'GET',
endpoint: '/session/:sessionId/element',
body: {using: 'css selector', value: 'img'},
result: {value: {x: 75, y: 11, width: 160, height: 160}},
cid: '0-0',
sessionId: '4d1707ae-820f-1645-8485-5a820b2a40da',
capabilities: {}
})
const screenShotCommand =... | () {
return command()
}
export function commandEnd() {
return command()
}
export function commandStartScreenShot() {
return screenShotCommand()
}
export function commandEndScreenShot() {
return screenShotCommand()
}
| commandStart | identifier_name |
command.js | body: {using: 'css selector', value: 'img'},
result: {value: {x: 75, y: 11, width: 160, height: 160}},
cid: '0-0',
sessionId: '4d1707ae-820f-1645-8485-5a820b2a40da',
capabilities: {}
})
const screenShotCommand = () => ({
method: 'GET',
body: {using: 'css selector', value: 'img'},
endpoin... | const command = () => ({
method: 'GET',
endpoint: '/session/:sessionId/element', | random_line_split | |
command.js | const command = () => ({
method: 'GET',
endpoint: '/session/:sessionId/element',
body: {using: 'css selector', value: 'img'},
result: {value: {x: 75, y: 11, width: 160, height: 160}},
cid: '0-0',
sessionId: '4d1707ae-820f-1645-8485-5a820b2a40da',
capabilities: {}
})
const screenShotCommand =... |
export function commandEndScreenShot() {
return screenShotCommand()
}
| {
return screenShotCommand()
} | identifier_body |
chemistry.py | # -*- coding: utf-8 -*-
"""
chemreac.chemistry
==================
This module collects classes useful for describing substances,
reactions and reaction systems. The classes have methods to help
with consistent low-level conversion to numerical parameters of
the model. The classes are from the
`chempy <https://pypi.pyt... | >>> d['A'].name
'A'
"""
kwargs_list = []
for i in range(len(names)):
d = {}
data = {}
for k, v in kwargs.items():
if k in Substance.attrs:
d[k] = v[i]
else:
data[k] = v[i]
d['data'] = data
kwargs_list.app... | """
Convenience function to generate a OrderedDict of Substance
instances from a sequence of names and corresponding sequences
of kwargs to Substance class.
Parameters
----------
names: sequence of strings
names of substances
**kwargs:
sequences of corresponding keyword argu... | identifier_body |
chemistry.py | # -*- coding: utf-8 -*-
"""
chemreac.chemistry
==================
This module collects classes useful for describing substances,
reactions and reaction systems. The classes have methods to help
with consistent low-level conversion to numerical parameters of
the model. The classes are from the
`chempy <https://pypi.pyt... | (names, **kwargs):
"""
Convenience function to generate a OrderedDict of Substance
instances from a sequence of names and corresponding sequences
of kwargs to Substance class.
Parameters
----------
names: sequence of strings
names of substances
**kwargs:
sequences of cor... | mk_sn_dict_from_names | identifier_name |
chemistry.py | # -*- coding: utf-8 -*-
"""
chemreac.chemistry
==================
This module collects classes useful for describing substances,
reactions and reaction systems. The classes have methods to help
with consistent low-level conversion to numerical parameters of
the model. The classes are from the
`chempy <https://pypi.pyt... |
else:
data[k] = v[i]
d['data'] = data
kwargs_list.append(d)
return OrderedDict([(s, Substance(s, **kwargs_list[i])) for i, s
in enumerate(names)])
| d[k] = v[i] | conditional_block |
chemistry.py | # -*- coding: utf-8 -*-
"""
chemreac.chemistry
==================
This module collects classes useful for describing substances,
reactions and reaction systems. The classes have methods to help
with consistent low-level conversion to numerical parameters of
the model. The classes are from the
`chempy <https://pypi.pyt... | for i in range(len(names)):
d = {}
data = {}
for k, v in kwargs.items():
if k in Substance.attrs:
d[k] = v[i]
else:
data[k] = v[i]
d['data'] = data
kwargs_list.append(d)
return OrderedDict([(s, Substance(s, **kwargs... | random_line_split | |
test.rs | _attr = attr::contains_name(&i.attrs, "test");
fn has_test_signature(i: &ast::Item) -> HasTestSignature {
match &i.node {
&ast::ItemFn(ref decl, _, _, _, ref generics, _) => {
let no_output = match decl.output {
ast::DefaultReturn(..) => true,
ast::Retu... | is_test_crate | identifier_name | |
test.rs | ignore: is_ignored(&*i),
should_panic: should_panic(&*i)
};
self.cx.testfns.push(test);
self.tests.push(i.ident);
// debug!("have {} test/bench functions",
// cx.tes... | {
let ident = i.ident;
if ident.name != token::special_idents::invalid.name {
self.cx.path.push(ident);
}
debug!("current path: {}",
ast_util::path_name_i(&self.cx.path));
let i = if is_test_fn(&self.cx, &*i) || is_bench_fn(&self.cx, &*i) {
... | identifier_body | |
test.rs | testfns: Vec<Test>,
reexport_test_harness_main: Option<InternedString>,
is_test_crate: bool,
config: ast::CrateConfig,
// top-level re-export submodule, filled out after folding is finished
toplevel_reexport: Option<ast::Ident>,
}
// Traverse the crate, collecting all the test functions, elidi... | sess: &'a ParseSess,
span_diagnostic: &'a diagnostic::SpanHandler,
path: Vec<ast::Ident>,
ext_cx: ExtCtxt<'a>, | random_line_split | |
Form.js | apply: "_applyTarget",
event: "changeTarget",
nullable: true,
init: null,
dereference: true
}
},
members :
{
__objectController : null,
__bindingOptions : null,
/**
* The form controller uses for setting up the bindings the fundamental
* binding layer, the {@... | {
this.__objectController.dispose();
} | conditional_block | |
Form.js | the model are handled by an internal
* {@link qx.data.controller.Object}.
*
* *Features*
*
* * Connect a form to a model (bidirectional)
* * Create a model for a given form
*
* *Usage*
*
* The controller only works if both a controller and a model are set.
* Creating a model will automatically set the creat... | nullable: true,
init: null,
dereference: true
}
},
members :
{
__objectController : null,
__bindingOptions : null,
/**
* The form controller uses for setting up the bindings the fundamental
* binding layer, the {@link qx.data.SingleValueBinding}. To achieve a
*... | {
check: "qx.ui.form.Form",
apply: "_applyTarget",
event: "changeTarget", | random_line_split |
issue-54462-mutable-noalias-correctness.rs | row * 1 + col * 3
}
fn main() {
let mut mat = [1.0f32, 5.0, 9.0, 2.0, 6.0, 10.0, 3.0, 7.0, 11.0, 4.0, 8.0, 12.0];
for i in 0..2 {
for j in i+1..3 {
if mat[linidx(j, 3)] > mat[linidx(i, 3)] {
for k in 0..4 {
let (x, rest) = mat.split_at_mu... | // run-pass
//
// compile-flags: -Ccodegen-units=1 -O
fn linidx(row: usize, col: usize) -> usize { | random_line_split | |
issue-54462-mutable-noalias-correctness.rs | // run-pass
//
// compile-flags: -Ccodegen-units=1 -O
fn linidx(row: usize, col: usize) -> usize {
row * 1 + col * 3
}
fn main() | {
let mut mat = [1.0f32, 5.0, 9.0, 2.0, 6.0, 10.0, 3.0, 7.0, 11.0, 4.0, 8.0, 12.0];
for i in 0..2 {
for j in i+1..3 {
if mat[linidx(j, 3)] > mat[linidx(i, 3)] {
for k in 0..4 {
let (x, rest) = mat.split_at_mut(linidx(i, k) + 1);
... | identifier_body | |
issue-54462-mutable-noalias-correctness.rs | // run-pass
//
// compile-flags: -Ccodegen-units=1 -O
fn | (row: usize, col: usize) -> usize {
row * 1 + col * 3
}
fn main() {
let mut mat = [1.0f32, 5.0, 9.0, 2.0, 6.0, 10.0, 3.0, 7.0, 11.0, 4.0, 8.0, 12.0];
for i in 0..2 {
for j in i+1..3 {
if mat[linidx(j, 3)] > mat[linidx(i, 3)] {
for k in 0..4 {
... | linidx | identifier_name |
issue-54462-mutable-noalias-correctness.rs | // run-pass
//
// compile-flags: -Ccodegen-units=1 -O
fn linidx(row: usize, col: usize) -> usize {
row * 1 + col * 3
}
fn main() {
let mut mat = [1.0f32, 5.0, 9.0, 2.0, 6.0, 10.0, 3.0, 7.0, 11.0, 4.0, 8.0, 12.0];
for i in 0..2 {
for j in i+1..3 {
if mat[linidx(j, 3)] > mat[linidx(i, 3... |
}
}
assert_eq!([9.0, 5.0, 1.0, 10.0, 6.0, 2.0, 11.0, 7.0, 3.0, 12.0, 8.0, 4.0], mat);
}
| {
for k in 0..4 {
let (x, rest) = mat.split_at_mut(linidx(i, k) + 1);
let a = x.last_mut().unwrap();
let b = rest.get_mut(linidx(j, k) - linidx(i, k) - 1).unwrap();
::std::mem::swap(a, b);... | conditional_block |
InputElementBuilder.js | var textDivTopIndex = -1;
/**
* Creates a div that contains a textfiled, a plus and a minus button
* @param {String | undefined} textContent string to be added to the given new textField as value
* @returns new div
*/
function createTextDiv( textContent ) {
textDivTopIndex++;
var newTextDiv = document.create... | if ( isLastField(event.target) && currentInputUriCount < 10 ) {
var addedTextDiv = createTextDiv();
formElement.insertBefore(addedTextDiv, sendButtonDiv);
event.stopPropagation();
}
}
function isLastField(field) {
textDivTopIndex = 0;
$(".inputTextDiv").each(function(index) {
te... | return newTextDiv
}
function addOnFocus(event) { | random_line_split |
InputElementBuilder.js | var textDivTopIndex = -1;
/**
* Creates a div that contains a textfiled, a plus and a minus button
* @param {String | undefined} textContent string to be added to the given new textField as value
* @returns new div
*/
function | ( textContent ) {
textDivTopIndex++;
var newTextDiv = document.createElement("DIV");
newTextDiv.className = "inputTextDiv form-group row";
newTextDiv.id = "uriArray"+textDivTopIndex;
newTextDiv.setAttribute("index", textDivTopIndex);
//newTextDiv.innerHTML = "hasznaltauto.hu url:";
//textfield ... | createTextDiv | identifier_name |
InputElementBuilder.js | var textDivTopIndex = -1;
/**
* Creates a div that contains a textfiled, a plus and a minus button
* @param {String | undefined} textContent string to be added to the given new textField as value
* @returns new div
*/
function createTextDiv( textContent ) | textFieldAlignerDiv.className = "col-xs-10 col-sm-10 col-sm-10";
textFieldAlignerDiv.appendChild(textField);
//add a new input field, or remove current
var inputButtonMinus = document.createElement("BUTTON");
inputButtonMinus.className = "btn btn-default btn-sm col-xs-1 col-sm-1 col-md-1 form-control... | {
textDivTopIndex++;
var newTextDiv = document.createElement("DIV");
newTextDiv.className = "inputTextDiv form-group row";
newTextDiv.id = "uriArray"+textDivTopIndex;
newTextDiv.setAttribute("index", textDivTopIndex);
//newTextDiv.innerHTML = "hasznaltauto.hu url:";
//textfield that asks for a ... | identifier_body |
InputElementBuilder.js | var textDivTopIndex = -1;
/**
* Creates a div that contains a textfiled, a plus and a minus button
* @param {String | undefined} textContent string to be added to the given new textField as value
* @returns new div
*/
function createTextDiv( textContent ) {
textDivTopIndex++;
var newTextDiv = document.create... |
}
function isLastField(field) {
textDivTopIndex = 0;
$(".inputTextDiv").each(function(index) {
textDivTopIndex = ( $(this).attr("index") > textDivTopIndex ) ? $(this).attr("index") : textDivTopIndex;
});
return textDivTopIndex == field.parentElement.parentElement.getAttribute("index") || curren... | {
var addedTextDiv = createTextDiv();
formElement.insertBefore(addedTextDiv, sendButtonDiv);
event.stopPropagation();
} | conditional_block |
preview.ts | import { ICommandParameter, ICommand } from "../common/definitions/commands";
import { IErrors } from "../common/declarations";
import { injector } from "../common/yok";
export class PreviewCommand implements ICommand {
allowedParameters: ICommandParameter[] = [];
constructor(private $errors: IErrors) {}
async | (args: string[]): Promise<void> {
this.$errors.fail(
`The Preview service has been disabled until further notice.\n\n` +
`Configure local builds and use "ns run ${args.join(" ")}" instead.`
);
}
async canExecute(args: string[]): Promise<boolean> {
return true;
}
}
// export class PreviewCommand implem... | execute | identifier_name |
preview.ts | import { ICommandParameter, ICommand } from "../common/definitions/commands";
import { IErrors } from "../common/declarations";
import { injector } from "../common/yok";
export class PreviewCommand implements ICommand {
allowedParameters: ICommandParameter[] = [];
constructor(private $errors: IErrors) {}
async ex... | // env: this.$options.env,
// });
//
// await this.$previewQrCodeService.printLiveSyncQrCode({
// projectDir: this.$projectData.projectDir,
// useHotModuleReload: this.$options.hmr,
// link: this.$options.link,
// });
// }
//
// public async canExecute(args: string[]): Promise<boolean> {
// if (ar... | // await this.$previewAppController.startPreview({
// projectDir: this.$projectData.projectDir,
// useHotModuleReload: this.$options.hmr, | random_line_split |
preview.ts | import { ICommandParameter, ICommand } from "../common/definitions/commands";
import { IErrors } from "../common/declarations";
import { injector } from "../common/yok";
export class PreviewCommand implements ICommand {
allowedParameters: ICommandParameter[] = [];
constructor(private $errors: IErrors) |
async execute(args: string[]): Promise<void> {
this.$errors.fail(
`The Preview service has been disabled until further notice.\n\n` +
`Configure local builds and use "ns run ${args.join(" ")}" instead.`
);
}
async canExecute(args: string[]): Promise<boolean> {
return true;
}
}
// export class Previ... | {} | identifier_body |
recycle_items.py | import json
import os
from pokemongo_bot import inventory
from pokemongo_bot.base_dir import _base_dir
from pokemongo_bot.base_task import BaseTask
from pokemongo_bot.human_behaviour import action_delay
from pokemongo_bot.services.item_recycle_worker import ItemRecycler
from pokemongo_bot.tree_config_builder import Co... | (BaseTask):
"""
Recycle undesired items if there is less than five space in inventory.
You can use either item's name or id. For the full list of items see ../../data/items.json
It's highly recommended to put this task before move_to_fort and spin_fort task in the config file so you'll most likely be a... | RecycleItems | identifier_name |
recycle_items.py | import json
import os
from pokemongo_bot import inventory
from pokemongo_bot.base_dir import _base_dir
from pokemongo_bot.base_task import BaseTask
from pokemongo_bot.human_behaviour import action_delay
from pokemongo_bot.services.item_recycle_worker import ItemRecycler
from pokemongo_bot.tree_config_builder import Co... | # Make the bot appears more human
action_delay(self.bot.config.action_wait_min, self.bot.config.action_wait_max)
# If at any recycling process call we got an error, we consider that the result of this task is error too.
if ItemRecycler(self... | for item_in_inventory in inventory.items().all():
if self.item_should_be_recycled(item_in_inventory): | random_line_split |
recycle_items.py | import json
import os
from pokemongo_bot import inventory
from pokemongo_bot.base_dir import _base_dir
from pokemongo_bot.base_task import BaseTask
from pokemongo_bot.human_behaviour import action_delay
from pokemongo_bot.services.item_recycle_worker import ItemRecycler
from pokemongo_bot.tree_config_builder import Co... |
def _validate_item_filter(self):
"""
Validate user's item filter config
:return: Nothing.
:rtype: None
:raise: ConfigException: When an item doesn't exist in ../../data/items.json
"""
item_list = json.load(open(os.path.join(_base_dir, 'data', 'items.json')))... | self.items_filter = self.config.get('item_filter', {})
self.min_empty_space = self.config.get('min_empty_space', None)
self._validate_item_filter() | identifier_body |
recycle_items.py | import json
import os
from pokemongo_bot import inventory
from pokemongo_bot.base_dir import _base_dir
from pokemongo_bot.base_task import BaseTask
from pokemongo_bot.human_behaviour import action_delay
from pokemongo_bot.services.item_recycle_worker import ItemRecycler
from pokemongo_bot.tree_config_builder import Co... | item_filter_config = self.items_filter.get(str(item.id), 0)
if item_filter_config is not 0:
return item_filter_config.get('keep', 20) | conditional_block | |
routes.py | from application import app
from flask import Response, request
import json
import logging
import requests
import traceback
import kombu
import re
import uuid
import getpass
from datetime import datetime
from jsonschema import Draft4Validator
name_schema = {
"type": "object",
"properties": {
"forename... | (error):
hostname = app.config['AMQP_URI']
connection = kombu.Connection(hostname=hostname)
producer = connection.SimpleQueue('errors')
producer.put(error)
logging.warning('Error successfully raised.')
| raise_error | identifier_name |
routes.py | from application import app
from flask import Response, request
import json
import logging
import requests
import traceback
import kombu
import re
import uuid
import getpass
from datetime import datetime
from jsonschema import Draft4Validator
name_schema = {
"type": "object",
"properties": {
"forename... |
result['dependencies'][dependency['name']] = str(response.status_code) + ' ' + response.reason
data = json.loads(response.content.decode('utf-8'))
for key in data['dependencies']:
result['dependencies'][key] = data['dependencies'][key]
return Response(json.dumps(result), statu... | status = 500 | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.