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 |
|---|---|---|---|---|
permission.rs | use std::{error::Error as StdError, fmt, io::Write, str::FromStr};
use diesel::{backend::Backend, deserialize, serialize, sql_types::Text};
#[derive(AsExpression, Clone, Copy, Debug, Eq, FromSqlRow, Hash, PartialEq)]
#[sql_type = "Text"]
pub enum Permission {
MakePost,
MakeMediaPost,
MakeComment,
Foll... |
impl fmt::Display for Permission {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Permission::MakePost => write!(f, "make-post"),
Permission::MakeMediaPost => write!(f, "make-media-post"),
Permission::MakeComment => write!(f, "make-comment"),
... | BlockInstance,
GrantRole,
RevokeRole,
} | random_line_split |
spectrometers.py | ### import ####################################################################
import pycmds.project.classes as pc
import pycmds.hardware.hardware as hw
import pathlib
import appdirs
import toml
import yaqc
### driver ####################################################################
class Driver(hw.Driver):
... |
# turret index on ActiveX call starts from zero
destination_index_zero_based = int(destination_index) - 1
self.ctrl.set_turret(destination_index_zero_based)
self.grating_index.write(destination_index)
self.wait_until_still()
self.limits.write(*self.ctrl.get_limits(), sel... | destination_index = destination_index[0] | conditional_block |
spectrometers.py | ### import ####################################################################
import pycmds.project.classes as pc
import pycmds.hardware.hardware as hw |
### driver ####################################################################
class Driver(hw.Driver):
def __init__(self, *args, **kwargs):
self._yaqd_port = kwargs.pop("yaqd_port")
super().__init__(*args, **kwargs)
self.grating_index = pc.Combo(
name="Grating",
... | import pathlib
import appdirs
import toml
import yaqc | random_line_split |
spectrometers.py | ### import ####################################################################
import pycmds.project.classes as pc
import pycmds.hardware.hardware as hw
import pathlib
import appdirs
import toml
import yaqc
### driver ####################################################################
class Driver(hw.Driver):
... | (hw.Hardware):
def __init__(self, *args, **kwargs):
self.kind = "spectrometer"
hw.Hardware.__init__(self, *args, **kwargs)
### import ####################################################################
conf = pathlib.Path(appdirs.user_config_dir("pycmds", "pycmds")) / "config.toml"
conf = toml.... | Hardware | identifier_name |
spectrometers.py | ### import ####################################################################
import pycmds.project.classes as pc
import pycmds.hardware.hardware as hw
import pathlib
import appdirs
import toml
import yaqc
### driver ####################################################################
class Driver(hw.Driver):
... | self.ctrl = yaqc.Client(self._yaqd_port)
# import some information from control
id_dict = self.ctrl.id()
self.serial_number = id_dict["serial"]
self.position.write(self.ctrl.get_position())
# recorded
self.recorded[self.name] = [self.position, self.native_units, 1... | def __init__(self, *args, **kwargs):
self._yaqd_port = kwargs.pop("yaqd_port")
super().__init__(*args, **kwargs)
self.grating_index = pc.Combo(
name="Grating",
allowed_values=[1, 2],
section=self.name,
option="grating_index",
display=Tr... | identifier_body |
Utils.ts | /// <reference path='../ts/typings/tsd.d.ts' />
import IUser = require('./interfaces/IUser');
class Utils {
private static NOT_FOUND: number = -1;
public static idxInList(element, list, comp?) {
var idx = Utils.NOT_FOUND;
var comp = comp ? comp : this._defaultComp;
angular.forEach(lis... |
});
return idx;
}
public static removeFromList(element, list, comp?) {
var idx = Utils.idxInList(element, list, comp);
return list.splice(idx, 1);
}
public static _defaultComp(a, b): boolean {
return a == b;
}
public static userComp(a: IUser, b: IUser... | {
idx = key;
return;
} | conditional_block |
Utils.ts | /// <reference path='../ts/typings/tsd.d.ts' />
import IUser = require('./interfaces/IUser');
class Utils {
private static NOT_FOUND: number = -1;
public static idxInList(element, list, comp?) {
var idx = Utils.NOT_FOUND;
var comp = comp ? comp : this._defaultComp;
angular.forEach(lis... |
public static _defaultComp(a, b): boolean {
return a == b;
}
public static userComp(a: IUser, b: IUser): boolean {
return a.netid == b.netid;
}
public static isInList(element, list, comp?): boolean {
return this.idxInList(element, list, comp) != Utils.NOT_FOUND;
}
... | {
var idx = Utils.idxInList(element, list, comp);
return list.splice(idx, 1);
} | identifier_body |
Utils.ts | /// <reference path='../ts/typings/tsd.d.ts' />
import IUser = require('./interfaces/IUser');
class Utils {
private static NOT_FOUND: number = -1;
public static idxInList(element, list, comp?) {
var idx = Utils.NOT_FOUND;
var comp = comp ? comp : this._defaultComp;
angular.forEach(lis... | (a: IUser, b: IUser): boolean {
return a.netid == b.netid;
}
public static isInList(element, list, comp?): boolean {
return this.idxInList(element, list, comp) != Utils.NOT_FOUND;
}
public static isVisible(element): boolean {
return element && element.is(":visible");
}
}
e... | userComp | identifier_name |
ui.popup.js | (function($, $$) {
var _ = Mavo.UI.Popup = $.Class({
constructor: function(primitive) {
this.primitive = primitive;
// Need to be defined here so that this is what expected
this.position = evt => {
var bounds = this.primitive.element.getBoundingClientRect();
var x = bounds.left;
var y = bounds.bottom;... |
}
});
if (!this.element.contains(this.editor)) {
// This can happen if edit type changes from popup to inline
this.element.append(this.editor);
}
},
close: function() {
this.hide();
$.unbind(this.primitive.element, ".mavo:edit .mavo:preedit .mavo:showpopup");
},
proxy: {
"editor": "primitiv... | { // Enter or F2
this.show();
this.editor.focus();
} | conditional_block |
ui.popup.js | (function($, $$) {
var _ = Mavo.UI.Popup = $.Class({
constructor: function(primitive) {
this.primitive = primitive;
// Need to be defined here so that this is what expected
this.position = evt => {
var bounds = this.primitive.element.getBoundingClientRect();
var x = bounds.left;
var y = bounds.bottom;... | show: function() {
$.unbind([this.primitive.element, this.element], ".mavo:showpopup");
this.shown = true;
this.element.style.transition = "none";
this.element.removeAttribute("hidden");
this.position();
this.element.setAttribute("hidden", "");
this.element.style.transition = "";
document.body.app... | random_line_split | |
work.js | import React from 'react';
import PageLayout from 'layouts/PageLayout/PageLayout';
import { connect } from 'react-redux';
import WorkItems from 'components/work-items';
import styles from './work-view.css';
const mapStateToProps = (state) => ({
work: state.work,
routerState: state.router
});
export class WorkView ... | <div className={styles.work_view_header}>
<h1 className='page-title'>our work</h1>
<h4 className={styles.page_subtitle}>yeah, we get paid to do this.</h4>
</div>
<div className={styles.work_view_content}>
<WorkItems workpage actions={this.actions} locati... |
render () {
return (
<div className='page-outer'>
<div className={styles.work_view} ref='page'> | random_line_split |
work.js | import React from 'react';
import PageLayout from 'layouts/PageLayout/PageLayout';
import { connect } from 'react-redux';
import WorkItems from 'components/work-items';
import styles from './work-view.css';
const mapStateToProps = (state) => ({
work: state.work,
routerState: state.router
});
export class WorkView ... |
componentWillMount () {
this.setupPageInfo('Our Work');
}
componentDidMount () {
this.animatePageContentIn();
this.checkBodyVisibility();
}
render () {
return (
<div className='page-outer'>
<div className={styles.work_view} ref='page'>
<div className={styles.work_v... | {
super(props);
} | identifier_body |
work.js | import React from 'react';
import PageLayout from 'layouts/PageLayout/PageLayout';
import { connect } from 'react-redux';
import WorkItems from 'components/work-items';
import styles from './work-view.css';
const mapStateToProps = (state) => ({
work: state.work,
routerState: state.router
});
export class WorkView ... | (props) {
super(props);
}
componentWillMount () {
this.setupPageInfo('Our Work');
}
componentDidMount () {
this.animatePageContentIn();
this.checkBodyVisibility();
}
render () {
return (
<div className='page-outer'>
<div className={styles.work_view} ref='page'>
... | constructor | identifier_name |
round-progress.service.ts | import {Injectable, Inject, Optional} from '@angular/core';
import {DOCUMENT} from '@angular/common';
const DEGREE_IN_RADIANS: number = Math.PI / 180;
@Injectable({providedIn: 'root'})
export class RoundProgressService {
private base: HTMLBaseElement;
private hasPerf: boolean;
public supportsSvg: boolean;
co... | (elementRadius: number, pathRadius: number, angleInDegrees: number): string {
const angleInRadians = (angleInDegrees - 90) * DEGREE_IN_RADIANS;
const x = elementRadius + pathRadius * Math.cos(angleInRadians);
const y = elementRadius + pathRadius * Math.sin(angleInRadians);
return x + ' ' + y;
}
}
| _polarToCartesian | identifier_name |
round-progress.service.ts | import {Injectable, Inject, Optional} from '@angular/core';
import {DOCUMENT} from '@angular/common';
const DEGREE_IN_RADIANS: number = Math.PI / 180;
@Injectable({providedIn: 'root'})
export class RoundProgressService {
private base: HTMLBaseElement;
private hasPerf: boolean;
public supportsSvg: boolean;
co... |
/**
* Generates a timestamp.
*/
getTimestamp(): number {
return this.hasPerf ? window.performance.now() : Date.now();
}
/**
* Generates the value for an SVG arc.
* @param current Current value.
* @param total Maximum value.
* @param pathRadius Radius of the SVG path.
... | {
if (this.base && this.base.href) {
const hashIndex = color.indexOf('#');
if (hashIndex > -1 && color.indexOf('url') > -1) {
return color.slice(0, hashIndex) + location.href + color.slice(hashIndex);
}
}
return color;
} | identifier_body |
round-progress.service.ts | import {Injectable, Inject, Optional} from '@angular/core';
import {DOCUMENT} from '@angular/common';
const DEGREE_IN_RADIANS: number = Math.PI / 180; | export class RoundProgressService {
private base: HTMLBaseElement;
private hasPerf: boolean;
public supportsSvg: boolean;
constructor(@Optional() @Inject(DOCUMENT) document: any) {
this.supportsSvg = !!(
document &&
document.createElementNS &&
document.createElementNS('http://www.w3.org/2... |
@Injectable({providedIn: 'root'}) | random_line_split |
round-progress.service.ts | import {Injectable, Inject, Optional} from '@angular/core';
import {DOCUMENT} from '@angular/common';
const DEGREE_IN_RADIANS: number = Math.PI / 180;
@Injectable({providedIn: 'root'})
export class RoundProgressService {
private base: HTMLBaseElement;
private hasPerf: boolean;
public supportsSvg: boolean;
co... |
return color;
}
/**
* Generates a timestamp.
*/
getTimestamp(): number {
return this.hasPerf ? window.performance.now() : Date.now();
}
/**
* Generates the value for an SVG arc.
* @param current Current value.
* @param total Maximum value.
* @param pathRadius Rad... | {
const hashIndex = color.indexOf('#');
if (hashIndex > -1 && color.indexOf('url') > -1) {
return color.slice(0, hashIndex) + location.href + color.slice(hashIndex);
}
} | conditional_block |
SurveyClass.ts | : Date = new Date();//盘左的测量时间
public time2: Date = new Date();//盘右的测量时间
/**
* 计算测量点盘左盘右合并后的水平和垂直角,做2c和指标差矫正
*/
public calibrate(method?: ObserveMethod): void {
(!method) && (method = ObserveMethod.FullCircle);
if (method === ObserveMethod.FullCircle) {
//这是盘左盘右都测量... | : number {
return Math.PI / 2 * (2 - Math.sign(this.de + 1.0E-30)) - Math.atan(this.dn / (this.de + 1.0E-30));
}
/**
* 获取垂直角,垂直角是以水平线为0度计算
* @return {number} 以弧度为单位的垂直角
*/
public get verticalAngle(): number {
return Math.atan(this.dh / (this.distance + 1.0E-30));
}
... | }
public de: number;
public dn: number;
public dh: number;
/**
* 获取全站仪坐标系下的水平角,即从N开始为0度,顺时针角度增加
* @return {number} 以弧度为单位的水平角
*/
public get horizontalAngle() | conditional_block |
SurveyClass.ts | ));
}
/**
* 获取垂直角,垂直角是以水平线为0度计算
* @return {number} 以弧度为单位的垂直角
*/
public get verticalAngle(): number {
return Math.atan(this.dh / (this.distance + 1.0E-30));
}
/**
* 获取水平距离
* @return {number} 获取水平距离
*/
public get distance(): number {
return pa... | /**
* 判断是否需要计算归零差,判断标准是测回第一点和最后一点是否为同一点
* 当测回点数超过4个的时候就需要增加定向点归零的判断 | random_line_split | |
SurveyClass.ts | : Date = new Date();//盘左的测量时间
public time2: Date = new Date();//盘右的测量时间
/**
* 计算测量点盘左盘右合并后的水平和垂直角,做2c和指标差矫正
*/
public calibrate(method?: ObserveMethod): void {
(!method) && (method = ObserveMethod.FullCircle);
if (method === ObserveMethod.FullCircle) {
//这是盘左盘右都测量... | lic geDist(point?: StudyPoint): number {
if (!point) return 0;
var v = new SurveyVector(this.center, point);
return v.distance;
}
/**
* 获取点所在的垂直角,该垂直角是相对于全站仪的坐标系而言,即天顶方向为0度.
*/
public getHv(point?: StudyPoint): number {
if (!point) return 0;
var v = ne... | pub | identifier_name |
SurveyClass.ts | : Date = new Date();//盘左的测量时间
public time2: Date = new Date();//盘右的测量时间
/**
* 计算测量点盘左盘右合并后的水平和垂直角,做2c和指标差矫正
*/
public calibrate(method?: ObserveMethod): void {
(!method) && (method = ObserveMethod.FullCircle);
if (method === ObserveMethod.FullCircle) {
//这是盘左盘右都测量... | }
else {
hv = Math.PI / 2 - (2 * Math.PI - hv);
hz = hz - Math.PI;
}
var dist = slope * Math.cos(hv);
var K = 0.13;
var deltaH = 0;
if (dist > 1000) deltaH = dist * dist * (1 - K) / 2 / 6378000;
var point = new SurveyPoint(
th... | * @prop {number} N
* @prop {number} H
*/
public convertToXYZ(hz: number, hv: number, slope: number): Coor {
if (this._curFace == Face.Face1) {
hv = Math.PI / 2 - hv;
| identifier_body |
spawn.rs | //extern crate scoped_threadpool;
extern crate threadpool;
extern crate thread_local;
extern crate hwloc;
use matrix::{Scalar,Mat};
use core::marker::{PhantomData};
use thread_comm::{ThreadComm,ThreadInfo};
use composables::{GemmNode,AlgorithmStep};
use std::sync::{Arc,Mutex};
use std::cell::{RefCell};
use self::thre... | (&mut self, n_threads: usize){
//Create new thread pool
self.n_threads = n_threads;
if n_threads > 1 {
self.pool = ThreadPool::new(n_threads-1);
} else {
self.pool = ThreadPool::new(1);
}
//Clear the control tree cache
Arc::get_mut(&mut s... | set_n_threads | identifier_name |
spawn.rs | //extern crate scoped_threadpool;
extern crate threadpool;
extern crate thread_local;
extern crate hwloc;
use matrix::{Scalar,Mat};
use core::marker::{PhantomData};
use thread_comm::{ThreadComm,ThreadInfo};
use composables::{GemmNode,AlgorithmStep};
use std::sync::{Arc,Mutex};
use std::cell::{RefCell};
use self::thre... |
}
| {
S::hierarchy_description()
} | identifier_body |
spawn.rs | //extern crate scoped_threadpool;
extern crate threadpool;
extern crate thread_local;
extern crate hwloc;
use matrix::{Scalar,Mat};
use core::marker::{PhantomData};
use thread_comm::{ThreadComm,ThreadInfo};
use composables::{GemmNode,AlgorithmStep};
use std::sync::{Arc,Mutex};
use std::cell::{RefCell};
use self::thre... |
//Clear the control tree cache
Arc::get_mut(&mut self.cntl_cache).expect("").clear();
//Bind threads to cores
self.bind_threads();
}
fn bind_threads(&mut self) {
//Get topology
let topo = Arc::new(Mutex::new(Topology::new()));
let comm : Arc<Thre... | if n_threads > 1 {
self.pool = ThreadPool::new(n_threads-1);
} else {
self.pool = ThreadPool::new(1);
} | random_line_split |
execution.js | /*!
* Usher
* Copyright(c) 2014 meltmedia <mike@meltmedia.com>
*/
'use strict';
var async = require('async'),
winston = require('winston'),
STATUS = require('./tasks/status');
module.exports = WorkflowExecution;
function WorkflowExecution(tasks) |
WorkflowExecution.prototype.execute = function execute(context, done) {
done = done || function () {};
async.eachSeries(this.tasks, function (task, next) {
// Check to see if the task's dependencies have been resolved first
if (!context.isResolved(task)) {
var mask = STATUS.mask('pending');
... | {
if (!(this instanceof WorkflowExecution)) {
return new WorkflowExecution(tasks);
}
this.tasks = tasks;
} | identifier_body |
execution.js | /*!
* Usher
* Copyright(c) 2014 meltmedia <mike@meltmedia.com>
*/
'use strict';
var async = require('async'),
winston = require('winston'),
STATUS = require('./tasks/status');
module.exports = WorkflowExecution;
function | (tasks) {
if (!(this instanceof WorkflowExecution)) {
return new WorkflowExecution(tasks);
}
this.tasks = tasks;
}
WorkflowExecution.prototype.execute = function execute(context, done) {
done = done || function () {};
async.eachSeries(this.tasks, function (task, next) {
// Check to see if the task... | WorkflowExecution | identifier_name |
execution.js | /*!
* Usher
* Copyright(c) 2014 meltmedia <mike@meltmedia.com>
*/ | STATUS = require('./tasks/status');
module.exports = WorkflowExecution;
function WorkflowExecution(tasks) {
if (!(this instanceof WorkflowExecution)) {
return new WorkflowExecution(tasks);
}
this.tasks = tasks;
}
WorkflowExecution.prototype.execute = function execute(context, done) {
done = done ... |
'use strict';
var async = require('async'),
winston = require('winston'), | random_line_split |
execution.js | /*!
* Usher
* Copyright(c) 2014 meltmedia <mike@meltmedia.com>
*/
'use strict';
var async = require('async'),
winston = require('winston'),
STATUS = require('./tasks/status');
module.exports = WorkflowExecution;
function WorkflowExecution(tasks) {
if (!(this instanceof WorkflowExecution)) |
this.tasks = tasks;
}
WorkflowExecution.prototype.execute = function execute(context, done) {
done = done || function () {};
async.eachSeries(this.tasks, function (task, next) {
// Check to see if the task's dependencies have been resolved first
if (!context.isResolved(task)) {
var mask = STATU... | {
return new WorkflowExecution(tasks);
} | conditional_block |
asset-loader.js | /**
* Created by Dean Panayotov Local on 25.1.2015 г..
*/ | a_i_highlights.src = 'assets/canvas/highlights.png';
var a_i_house_cut = new Image();
a_i_house_cut.src = 'assets/canvas/house_cut.png';
var a_i_avatars = [new Image(), new Image(), new Image(), new Image()];
a_i_avatars[0].src = 'assets/canvas/players/1.png';
a_i_avatars[1].src = 'assets/canvas/players/2.png';
a_i_av... | var a_i_background = new Image();
a_i_background.src = 'assets/canvas/bg.png';
var a_i_highlights = new Image(); | random_line_split |
EarthState.ts | import { CatmullRomCurve3, MathUtils, Quaternion, Vector3 } from "three";
import { StateBase } from "./StateBase";
import { EulerRotation } from "../interfaces/EulerRotation";
import { IStateBase } from "../interfaces/IStateBase";
export class EarthState extends StateBase {
private _transition: number = 0;
pr... | (direction: number[]): void {
if (this._isTransitioning) {
return;
}
const camera = this._camera;
camera.position
.add(new Vector3().fromArray(direction));
camera.lookat
.add(new Vector3().fromArray(direction));
}
public update(delta:... | truck | identifier_name |
EarthState.ts | import { CatmullRomCurve3, MathUtils, Quaternion, Vector3 } from "three";
import { StateBase } from "./StateBase";
import { EulerRotation } from "../interfaces/EulerRotation";
import { IStateBase } from "../interfaces/IStateBase";
export class EarthState extends StateBase {
private _transition: number = 0;
pr... | }
public orbit(rotation: EulerRotation): void {
if (this._isTransitioning) {
return;
}
const camera = this._camera;
const q = new Quaternion()
.setFromUnitVectors(
camera.up,
new Vector3(0, 0, 1));
const qInverse ... | {
if (this._isTransitioning) {
return;
}
const camera = this._camera;
const offset = camera.position
.clone()
.sub(camera.lookat);
const length = offset.length();
const scaled = length * Math.pow(2, -delta);
const clipped = Ma... | identifier_body |
EarthState.ts | import { CatmullRomCurve3, MathUtils, Quaternion, Vector3 } from "three";
import { StateBase } from "./StateBase";
import { EulerRotation } from "../interfaces/EulerRotation";
import { IStateBase } from "../interfaces/IStateBase";
export class EarthState extends StateBase {
private _transition: number = 0;
pr... | else {
// Target a point on invented ground and keep forward direction
const l0 = eye.clone();
const n = new Vector3(0, 0, 1);
const p0 = new Vector3(0, 0, -2);
const d = new Vector3().subVectors(p0, l0).dot(n) / forward.dot(n);
const maxDistance ... | {
lookat.copy(eye);
eye.add(new Vector3(forward.x, forward.y, 0)
.multiplyScalar(-50));
eye.z = 30;
} | conditional_block |
EarthState.ts | import { CatmullRomCurve3, MathUtils, Quaternion, Vector3 } from "three";
import { StateBase } from "./StateBase";
import { EulerRotation } from "../interfaces/EulerRotation";
import { IStateBase } from "../interfaces/IStateBase";
export class EarthState extends StateBase {
private _transition: number = 0;
pr... | if (angle > -Math.PI / 45) {
lookat.copy(eye);
eye.add(new Vector3(forward.x, forward.y, 0)
.multiplyScalar(-50));
eye.z = 30;
} else {
// Target a point on invented ground and keep forward direction
const l0 = eye.clone();
... | .normalize();
const xy = Math.sqrt(forward.x * forward.x + forward.y * forward.y);
const angle = Math.atan2(forward.z, xy);
const lookat = new Vector3(); | random_line_split |
results.py | # Copyright 2015-2016 ARM Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in w... | (path=".", name=None):
"""Return a pd.DataFrame with the results
The DataFrame's rows are the scores. The first column is the
benchmark name and the second the id within it. For benchmarks
that have a score result, that's what's used. For benchmarks with
FPS_* result, that's the score. E.g. glb... | get_results | identifier_name |
results.py | # Copyright 2015-2016 ARM Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in w... |
update_axis = False
if data_min <= plot_y_min:
plot_y_min = data_min - margin
update_axis = True
if data_max >= plot_y_max:
plot_y_max = data_max + margin
update_axis = True
if update_axis:
self.ax.set_ylim(plot_y_min, plot... | margin = 1 | conditional_block |
results.py | # Copyright 2015-2016 ARM Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in w... |
def init_fig(self):
_, self.ax = plt.subplots()
def enlarge_axis(self, data):
"""Make sure that the axis don't clobber some of the data"""
(_, _, plot_y_min, plot_y_max) = plt.axis()
concat_data = pd.concat(data[s] for s in data)
data_min = min(concat_data)
d... | super(Result, self).__init__(*args, **kwargs)
self.ax = None | identifier_body |
results.py | # Copyright 2015-2016 ARM Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in w... | if match:
run_number = int(match.group(2))
if match.group(1) == "Overall_Score":
run_number -= 1
else:
run_number = 0
return (found, run_number)
def get_results(path=".", name=None):
"""Return a pd.DataFrame with the results
The DataFram... | if re.match("Overall_Score|score|FPS", metric):
found = True
match = re.search(r"(.+)[ _](\d+)", metric) | random_line_split |
metrics.ts | // source: components/metrics.ts
/// <reference path="../../bower_components/mithriljs/mithril.d.ts" />
/// <reference path="../../typings/browser.d.ts" />
/// <reference path="../util/types.ts" />
/// <reference path="../util/querycache.ts" />
/// <reference path="../models/metrics.ts" />
/**
* Components defines re... | (): boolean {
return this.vm.query.result.Epoch() > 0;
}
}
export function controller(model: ViewModel): Controller {
return new Controller(model);
}
export function view(ctrl: Controller): _mithril.MithrilVirtualElement {
let g: _mithril.MithrilVirtualElement... | hasData | identifier_name |
metrics.ts | // source: components/metrics.ts
/// <reference path="../../bower_components/mithriljs/mithril.d.ts" />
/// <reference path="../../typings/browser.d.ts" />
/// <reference path="../util/types.ts" />
/// <reference path="../util/querycache.ts" />
/// <reference path="../models/metrics.ts" />
/**
* Components defines re... |
export function view(ctrl: Controller): _mithril.MithrilVirtualElement {
let g: _mithril.MithrilVirtualElement = null;
if (ctrl.hasData()) {
g = m(".linegraph", m("svg.graph", { config: ctrl.drawGraph }));
} else {
g = m("", "loading...");
}
return m(
... | {
return new Controller(model);
} | identifier_body |
metrics.ts | // source: components/metrics.ts
/// <reference path="../../bower_components/mithriljs/mithril.d.ts" />
/// <reference path="../../typings/browser.d.ts" />
/// <reference path="../util/types.ts" />
/// <reference path="../util/querycache.ts" />
/// <reference path="../models/metrics.ts" />
/**
* Components defines re... | // chart margins are set to
.margin(CHART_MARGINS);
// Set xAxis ticks to properly format.
this.chart.xAxis
.tickFormat(function(t: string|Date): string { return typeof t === "string" ? t : d3.time.format("%H:%M:%S")(t); })
.showMaxMin(false);
... | .xScale(d3.time.scale()) | random_line_split |
method-on-enum.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | () {
let stack = Enum::Variant2(117901063);
let _ = stack.self_by_ref(-1, -2);
let _ = stack.self_by_val(-3, -4);
let owned: Box<_> = box Enum::Variant1{ x: 1799, y: 1799 };
let _ = owned.self_by_ref(-5, -6);
let _ = owned.self_by_val(-7, -8);
let _ = owned.self_owned(-9, -10);
}
fn zzz() ... | main | identifier_name |
method-on-enum.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
impl Enum {
fn self_by_ref(&self, arg1: isize, arg2: isize) -> isize {
zzz(); // #break
arg1 + arg2
}
fn self_by_val(self, arg1: isize, arg2: isize) -> isize {
zzz(); // #break
arg1 + arg2
}
fn self_owned(self: Box<Enum>, arg1: isize, arg2: isize) -> isize {
... | Variant2 (u32)
} | random_line_split |
method-on-enum.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
}
fn main() {
let stack = Enum::Variant2(117901063);
let _ = stack.self_by_ref(-1, -2);
let _ = stack.self_by_val(-3, -4);
let owned: Box<_> = box Enum::Variant1{ x: 1799, y: 1799 };
let _ = owned.self_by_ref(-5, -6);
let _ = owned.self_by_val(-7, -8);
let _ = owned.self_owned(-9, -10);
}... | {
zzz(); // #break
arg1 + arg2
} | identifier_body |
Binding.ts | /// <reference path="../../../../declarations/jquery/jquery.d.ts" />
/// <reference path="selectoption.ts" />
namespace A7.Forms {
export class Binding {
static BindToForm<T>($form: JQuery, entity: T, customMapping?: {}): void {
for (var prop in entity) {
var matchingFormEls;
... | ($el: JQuery) {
if (this._isCheckBox($el)) {
return $el.is(":checked");
} else {
return $el.val();
}
}
private static _isCheckBox($el: JQuery): boolean {
return $el.attr("type") == "checkbox";
}
}
} | _getFormValue | identifier_name |
Binding.ts | /// <reference path="../../../../declarations/jquery/jquery.d.ts" />
/// <reference path="selectoption.ts" />
namespace A7.Forms {
export class Binding {
static BindToForm<T>($form: JQuery, entity: T, customMapping?: {}): void {
for (var prop in entity) {
var matchingFormEls;
... | });
} else {
for (var prop in entity) {
var matchingFormEls, propertyVal;
matchingFormEls = $form.find('input[name="' + prop + '"], textarea[name="' + prop + '"], select[name="' + prop + '"]');
if (matchingFormEls... | var $element = $(element);
entity[$element.attr('name')] = A7.Forms.Binding._getFormValue($element); | random_line_split |
Binding.ts | /// <reference path="../../../../declarations/jquery/jquery.d.ts" />
/// <reference path="selectoption.ts" />
namespace A7.Forms {
export class Binding {
static BindToForm<T>($form: JQuery, entity: T, customMapping?: {}): void {
for (var prop in entity) {
var matchingFormEls;
... |
private static _isCheckBox($el: JQuery): boolean {
return $el.attr("type") == "checkbox";
}
}
} | {
if (this._isCheckBox($el)) {
return $el.is(":checked");
} else {
return $el.val();
}
} | identifier_body |
UnauthenticatedProfile.tsx | import * as React from 'react';
import { Platform, StyleSheet, View } from 'react-native';
import url from 'url';
import DevMenuContext from '../../DevMenuContext';
import * as DevMenuWebBrowser from '../../DevMenuWebBrowser';
import Colors from '../../constants/Colors';
import Endpoints from '../../constants/Endpoint... | },
errorText: {
textAlign: 'center',
marginHorizontal: 15,
marginTop: 20,
...Platform.select({
ios: {
fontSize: 15,
lineHeight: 20,
},
android: {
fontSize: 16,
lineHeight: 24,
},
}),
},
}); | }), | random_line_split |
UnauthenticatedProfile.tsx | import * as React from 'react';
import { Platform, StyleSheet, View } from 'react-native';
import url from 'url';
import DevMenuContext from '../../DevMenuContext';
import * as DevMenuWebBrowser from '../../DevMenuWebBrowser';
import Colors from '../../constants/Colors';
import Endpoints from '../../constants/Endpoint... |
}
};
const _handleSignInPress = async () => {
await _handleAuthentication('login');
};
const _handleSignUpPress = async () => {
await _handleAuthentication('signup');
};
const title = 'Sign in to Continue';
const description = 'Sign in or create an Expo account to view your projects.';
... | {
setIsAuthenticating(false);
} | conditional_block |
package.py | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class | (Package):
"""Prokka is a software tool to annotate bacterial, archaeal and viral
genomes quickly and produce standards-compliant output files."""
homepage = "https://github.com/tseemann/prokka"
url = "https://github.com/tseemann/prokka/archive/v1.14.5.tar.gz"
version('1.14.6', sha256='f73... | Prokka | identifier_name |
package.py | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details. |
from spack import *
class Prokka(Package):
"""Prokka is a software tool to annotate bacterial, archaeal and viral
genomes quickly and produce standards-compliant output files."""
homepage = "https://github.com/tseemann/prokka"
url = "https://github.com/tseemann/prokka/archive/v1.14.5.tar.gz"... | #
# SPDX-License-Identifier: (Apache-2.0 OR MIT) | random_line_split |
package.py | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Prokka(Package):
"""Prokka is a software tool to annotate bacterial, archaeal and viral
... | install_tree('bin', prefix.bin)
install_tree('binaries', prefix.binaries)
install_tree('db', prefix.db)
install_tree('doc', prefix.doc) | identifier_body | |
react_native_xcode.rs | short("f").help(
"Force the script to run, even in debug configuration.{n}This rarely \
does what you want because the default build script does not actually \
produce any information that the sentry build tool could pick up on.",
))
.arg(Arg::with_name("allow_fetch... | (matches: &ArgMatches<'_>) -> Result<(), Error> {
let config = Config::current();
let (org, project) = config.get_org_and_project(matches)?;
let should_wrap = matches.is_present("force")
|| match env::var("CONFIGURATION") {
Ok(config) => !&config.contains("Debug"),
Err(_) => ... | execute | identifier_name |
react_native_xcode.rs | short("f").help(
"Force the script to run, even in debug configuration.{n}This rarely \
does what you want because the default build script does not actually \
produce any information that the sentry build tool could pick up on.",
))
.arg(Arg::with_name("allow_fetch... | sourcemap_url = format!(
"~/{}",
sourcemap_path.file_name().unwrap().to_string_lossy()
);
}
// now that we have all the data, we can now process and upload the
// sourcemaps.
println!("Processing react-native sourcemaps for Sentry ... | }
bundle_path = report.bundle_path.unwrap();
bundle_url = format!("~/{}", bundle_path.file_name().unwrap().to_string_lossy());
sourcemap_path = report.sourcemap_path.unwrap(); | random_line_split |
compileResponseHandler.ts | import * as CompileResultParser from './parsers/compileResultParser';
import { getPathEnd } from '../../workspace/componentPath';
import * as vscode from 'vscode';
import path = require('path');
import Bluebird = require('bluebird');
import { MavensMateDiagnostics } from '../../vscode/mavensMateDiagnostics';
import * a... |
});
conflictPromises.push(conflictPromise);
}
return Promise.all(conflictPromises);
}
function forceCompileConflictFile(conflict){
let fileName = conflict.local.fileName;
let pathEnd = getPathEnd(fileName);
let workspaceRoot = vscode.workspace.rootPath;
let documentUri = v... | {
return forceCompileConflictFile(conflict);
} | conditional_block |
compileResponseHandler.ts | import * as CompileResultParser from './parsers/compileResultParser';
import { getPathEnd } from '../../workspace/componentPath';
import * as vscode from 'vscode';
import path = require('path');
import Bluebird = require('bluebird');
import { MavensMateDiagnostics } from '../../vscode/mavensMateDiagnostics';
import * a... | (conflict){
let fileName = conflict.local.fileName;
let pathEnd = getPathEnd(fileName);
let workspaceRoot = vscode.workspace.rootPath;
let documentUri = vscode.Uri.file(path.join(workspaceRoot, 'src', pathEnd));
return vscode.commands.executeCommand('mavensmate.forceCompileFile', documentUri);
}
fu... | forceCompileConflictFile | identifier_name |
compileResponseHandler.ts | import * as CompileResultParser from './parsers/compileResultParser';
import { getPathEnd } from '../../workspace/componentPath';
import * as vscode from 'vscode';
import path = require('path');
import Bluebird = require('bluebird');
import { MavensMateDiagnostics } from '../../vscode/mavensMateDiagnostics';
import * a... |
function handleSuccess(result): Promise<any>{
let componentSuccesses = CompileResultParser.getSuccessesFromDetails(result);
let componentFailures = CompileResultParser.getFailuresFromDetails(result);
return promiseClearDiagnosticsForSuccesses(componentSuccesses)
.then(() => {
return p... | {
let fileName = conflict.local.fileName;
let pathEnd = getPathEnd(fileName);
let workspaceRoot = vscode.workspace.rootPath;
let documentUri = vscode.Uri.file(path.join(workspaceRoot, 'src', pathEnd));
return vscode.commands.executeCommand('mavensmate.forceCompileFile', documentUri);
} | identifier_body |
compileResponseHandler.ts | import * as CompileResultParser from './parsers/compileResultParser';
import { getPathEnd } from '../../workspace/componentPath';
import * as vscode from 'vscode';
import path = require('path');
import Bluebird = require('bluebird');
import { MavensMateDiagnostics } from '../../vscode/mavensMateDiagnostics'; |
let mavensMateDiagnostics: MavensMateDiagnostics = MavensMateDiagnostics.getInstance();
export function handleCompileResponse(compileResponse): Promise<any>{
let result = compileResponse.result;
let handlePromise: Promise<any>;
if(result){
if(result.status && result.status === 'Conflict'){
... | import * as DiagnosticFactory from '../../vscode/diagnosticFactory'; | random_line_split |
views.py | from django.db.models import Count
from dcim.models import Device, Interface
from extras.api.views import CustomFieldModelViewSet
from utilities.api import FieldChoicesViewSet, ModelViewSet
from utilities.utils import get_subquery
from virtualization import filters
from virtualization.models import Cluster, ClusterGro... |
elif 'config_context' in request.query_params.get('exclude', []):
return serializers.VirtualMachineSerializer
return serializers.VirtualMachineWithConfigContextSerializer
class InterfaceViewSet(ModelViewSet):
queryset = Interface.objects.filter(
virtual_machine__isnull=False... | return serializers.NestedVirtualMachineSerializer | conditional_block |
views.py | from django.db.models import Count
from dcim.models import Device, Interface
from extras.api.views import CustomFieldModelViewSet
from utilities.api import FieldChoicesViewSet, ModelViewSet
from utilities.utils import get_subquery
from virtualization import filters | #
# Field choices
#
class VirtualizationFieldChoicesViewSet(FieldChoicesViewSet):
fields = (
(VirtualMachine, ['status']),
)
#
# Clusters
#
class ClusterTypeViewSet(ModelViewSet):
queryset = ClusterType.objects.annotate(
cluster_count=Count('clusters')
)
serializer_class = serial... | from virtualization.models import Cluster, ClusterGroup, ClusterType, VirtualMachine
from . import serializers
| random_line_split |
views.py | from django.db.models import Count
from dcim.models import Device, Interface
from extras.api.views import CustomFieldModelViewSet
from utilities.api import FieldChoicesViewSet, ModelViewSet
from utilities.utils import get_subquery
from virtualization import filters
from virtualization.models import Cluster, ClusterGro... | (ModelViewSet):
queryset = Interface.objects.filter(
virtual_machine__isnull=False
).select_related('virtual_machine').prefetch_related('tags')
serializer_class = serializers.InterfaceSerializer
filterset_class = filters.InterfaceFilter
def get_serializer_class(self):
request = self... | InterfaceViewSet | identifier_name |
views.py | from django.db.models import Count
from dcim.models import Device, Interface
from extras.api.views import CustomFieldModelViewSet
from utilities.api import FieldChoicesViewSet, ModelViewSet
from utilities.utils import get_subquery
from virtualization import filters
from virtualization.models import Cluster, ClusterGro... | queryset = Interface.objects.filter(
virtual_machine__isnull=False
).select_related('virtual_machine').prefetch_related('tags')
serializer_class = serializers.InterfaceSerializer
filterset_class = filters.InterfaceFilter
def get_serializer_class(self):
request = self.get_serializer_cont... | identifier_body | |
SearchContainer.js | import React from 'react';
import { Icon } from 'design-react-kit';
import { createUseStyles } from 'react-jss';
import { SearchProvider } from '../../contexts/searchContext.js';
import { ALL_SITE } from '../../utils/constants.js';
import { useModal } from '../../hooks/useModal.js';
import { l10NLabels } from '../../ut... | backgroundColor: 'var(--white)',
borderRadius: '100%',
fill: 'var(--primary)',
height: '2.6rem',
padding: '0.8rem',
width: '2.6rem',
},
});
export const SearchContainer = () => {
const classes = useStyles();
const [isModalOpen, closeModal, openModal] = useModal();
return (
<>
... | icon: {
composes: 'd-none d-lg-inline', | random_line_split |
karma.conf.js | // Karma configuration file, see link for more information
// https://karma-runner.github.io/1.0/config/configuration-file.html
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', '@angular-devkit/build-angular'],
plugins: [
require('karma-jasmine'),
requir... | });
}; | random_line_split | |
issue-46604.rs | // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
write(&buf);
buf[0]=2; //[ast]~ ERROR E0389
//[mir]~^ ERROR E0594
} | identifier_body | |
issue-46604.rs | // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | static buf: &mut [u8] = &mut [1u8,2,3,4,5,7]; //[ast]~ ERROR E0017
//[mir]~^ ERROR E0017
fn write<T: AsRef<[u8]>>(buffer: T) { }
fn main() {
write(&buf);
buf[0]=2; //[ast]~ ERROR E0389
... |
// revisions: ast mir
//[mir]compile-flags: -Z borrowck=mir
| random_line_split |
issue-46604.rs | // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | <T: AsRef<[u8]>>(buffer: T) { }
fn main() {
write(&buf);
buf[0]=2; //[ast]~ ERROR E0389
//[mir]~^ ERROR E0594
}
| write | identifier_name |
main.rs | extern crate futures;
extern crate tokio_proto;
extern crate tokio_service;
extern crate hyper;
#[macro_use] | extern crate serde_json;
extern crate num_cpus;
extern crate mime;
use tokio_proto::TcpServer;
use futures::future;
use hyper::Method::Get;
use hyper::header::{ContentLength, ContentType, Server};
use hyper::StatusCode::NotFound;
use hyper::server::{Http, Service, Request, Response};
use std::net::SocketAddr;
static ... | extern crate serde_derive; | random_line_split |
main.rs | extern crate futures;
extern crate tokio_proto;
extern crate tokio_service;
extern crate hyper;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
extern crate num_cpus;
extern crate mime;
use tokio_proto::TcpServer;
use futures::future;
use hyper::Method::Get;
use hyper::header::{ContentLength, ContentT... | (&self, req: Request) -> Self::Future {
let response = match (req.method(), req.path()) {
(&Get, "/plaintext") => {
Response::new()
.with_header(ContentLength(HELLOWORLD.len() as u64))
.with_header(ContentType(mime::TEXT_PLAIN))
... | call | identifier_name |
main.rs | extern crate futures;
extern crate tokio_proto;
extern crate tokio_service;
extern crate hyper;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
extern crate num_cpus;
extern crate mime;
use tokio_proto::TcpServer;
use futures::future;
use hyper::Method::Get;
use hyper::header::{ContentLength, ContentT... | {
let addr: SocketAddr = "0.0.0.0:8080".parse().unwrap();
let mut srv = TcpServer::new(Http::new(), addr);
println!("Listening on http://{} using {} threads",
addr,
num_cpus::get());
srv.threads(num_cpus::get());
srv.serve(move || Ok(TechEmpower))
} | identifier_body | |
task.js | function | (subTask) {
var cellSide = 60;
subTask.gridInfos = {
hideSaveOrLoad: true,
cellSide: cellSide,
actionDelay: 200,
itemTypes: {
green_robot: { img: "green_robot.png", side: 80, nbStates: 9, isObstacle: true, offsetX: -14, category: "robot", team: 0, zOrder: 2 },
paint: { i... | initTask | identifier_name |
task.js | function initTask(subTask) {
var cellSide = 60;
subTask.gridInfos = {
hideSaveOrLoad: true,
cellSide: cellSide,
actionDelay: 200,
itemTypes: {
green_robot: { img: "green_robot.png", side: 80, nbStates: 9, isObstacle: true, offsetX: -14, category: "robot", team: 0, zOrder: 2 },
... | [1, 1, 1, 1, 2, 2, 1, 1, 1, 1],
[1, 1, 1, 2, 1, 1, 2, 1, 1, 1],
[1, 1, 2, 1, 1, 1, 1, 2, 1, 1],
[1, 2, 1, 1, 1, 1, 1, 1, 2, 1],
[1, 2, 1, 1, 1, 1, 1, 1, 2, 1],
[1, 2, 1, 1, 2, 2, 1, 1, 2, 1],
... | easy: [
{
tiles: [
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1], | random_line_split |
task.js | function initTask(subTask) | wholeCategories: [],
singleBlocks: ["controls_repeat", "controls_if"]
}
},
ignoreInvalidMoves: false,
checkEndEveryTurn: false,
checkEndCondition: robotEndConditions.checkMarkersPainted
};
subTask.data = {
easy: [
{
tiles: [
... | {
var cellSide = 60;
subTask.gridInfos = {
hideSaveOrLoad: true,
cellSide: cellSide,
actionDelay: 200,
itemTypes: {
green_robot: { img: "green_robot.png", side: 80, nbStates: 9, isObstacle: true, offsetX: -14, category: "robot", team: 0, zOrder: 2 },
paint: { img: "paint... | identifier_body |
logdog_wrapper.py | #!/usr/bin/env vpython
# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Wrapper for adding logdog streaming support to swarming tasks."""
import argparse
import contextlib
import logging
import os
impor... | (popen):
try:
yield popen
finally:
if popen is not None:
try:
if popen.poll() is None:
popen.kill()
except OSError:
logging.warning('Failed to kill %s. Process may be leaked.',
str(popen.pid))
def main():
parser = CommandParser()
args, extr... | NoLeakingProcesses | identifier_name |
logdog_wrapper.py | #!/usr/bin/env vpython
# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Wrapper for adding logdog streaming support to swarming tasks."""
import argparse
import contextlib
import logging
import os
impor... | 'Logdog binary %s unavailable. Unable to create logdog client',
args.logdog_bin_cmd)
else:
streamserver_uri = 'unix:%s' % os.path.join(temp_directory,
'butler.sock')
prefix = os.path.join('android', 'swarming', 'logcats',
... | if not os.path.exists(args.logdog_bin_cmd):
logging.error( | random_line_split |
logdog_wrapper.py | #!/usr/bin/env vpython
# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Wrapper for adding logdog streaming support to swarming tasks."""
import argparse
import contextlib
import logging
import os
impor... |
else:
streamserver_uri = 'unix:%s' % os.path.join(temp_directory,
'butler.sock')
prefix = os.path.join('android', 'swarming', 'logcats',
os.environ.get('SWARMING_TASK_ID'))
logdog_cmd = [
args.logdog_bin_cmd,... | logging.error(
'Logdog binary %s unavailable. Unable to create logdog client',
args.logdog_bin_cmd) | conditional_block |
logdog_wrapper.py | #!/usr/bin/env vpython
# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Wrapper for adding logdog streaming support to swarming tasks."""
import argparse
import contextlib
import logging
import os
impor... |
def main():
parser = CommandParser()
args, extra_cmd_args = parser.parse_known_args(sys.argv[1:])
logging.basicConfig(level=logging.INFO)
if args.target:
test_cmd = [os.path.join('bin', 'run_%s' % args.target), '-v']
test_cmd += extra_cmd_args
elif args.script:
test_cmd = [args.script]
tes... | try:
yield popen
finally:
if popen is not None:
try:
if popen.poll() is None:
popen.kill()
except OSError:
logging.warning('Failed to kill %s. Process may be leaked.',
str(popen.pid)) | identifier_body |
test_scene.py | """The tests for the litejet component."""
import logging
import unittest
from unittest import mock
from homeassistant import setup
from homeassistant.components import litejet
from tests.common import get_test_home_assistant
from tests.components.scene import common
_LOGGER = logging.getLogger(__name__)
ENTITY_SCE... | self.mock_lj.all_switches.return_value = range(0)
self.mock_lj.scenes.return_value = range(1, 3)
self.mock_lj.get_scene_name.side_effect = get_scene_name
assert setup.setup_component(
self.hass, litejet.DOMAIN, {"litejet": {"port": "/tmp/this_will_be_mocked"}}
)
... | random_line_split | |
test_scene.py | """The tests for the litejet component."""
import logging
import unittest
from unittest import mock
from homeassistant import setup
from homeassistant.components import litejet
from tests.common import get_test_home_assistant
from tests.components.scene import common
_LOGGER = logging.getLogger(__name__)
ENTITY_SCE... |
def other_scene(self):
"""Get the other scene."""
return self.hass.states.get(ENTITY_OTHER_SCENE)
def test_activate(self):
"""Test activating the scene."""
common.activate(self.hass, ENTITY_SCENE)
self.hass.block_till_done()
self.mock_lj.activate_scene.assert_c... | """Get the current scene."""
return self.hass.states.get(ENTITY_SCENE) | identifier_body |
test_scene.py | """The tests for the litejet component."""
import logging
import unittest
from unittest import mock
from homeassistant import setup
from homeassistant.components import litejet
from tests.common import get_test_home_assistant
from tests.components.scene import common
_LOGGER = logging.getLogger(__name__)
ENTITY_SCE... | (self, method):
"""Stop everything that was started."""
self.hass.stop()
def scene(self):
"""Get the current scene."""
return self.hass.states.get(ENTITY_SCENE)
def other_scene(self):
"""Get the other scene."""
return self.hass.states.get(ENTITY_OTHER_SCENE)
... | teardown_method | identifier_name |
django_orm.py | # Copyright (C) 2010 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 agreed to in writ... |
return pickle.loads(base64.b64decode(value))
def from_db_value(self, value, expression, connection):
if value is None:
return None
return base64.b64encode(pickle.dumps(value))
def get_db_prep_value(self, value, connection, prepared=False):
if value is None:
return None
ret... | return value | conditional_block |
django_orm.py | # Copyright (C) 2010 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 agreed to in writ... |
def deconstruct(self):
name, path, args, kwargs = super().deconstruct()
del kwargs['null']
return name, path, args, kwargs
class Storage(BaseStorage):
"""Store and retrieve a single credential to and from
the datastore.
This Storage helper presumes the Credentials
have been stored as a Credeni... | if value is None:
return None
return base64.b64encode(pickle.dumps(value)) | identifier_body |
django_orm.py | # Copyright (C) 2010 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 agreed to in writ... | (self, value, connection, prepared=False):
if value is None:
return None
return base64.b64encode(pickle.dumps(value))
def deconstruct(self):
name, path, args, kwargs = super().deconstruct()
del kwargs['null']
return name, path, args, kwargs
class Storage(BaseStorage):
"""Store and retrie... | get_db_prep_value | identifier_name |
django_orm.py | # Copyright (C) 2010 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 agreed to in writ... | oauth2client.Credentials
"""
credential = None
query = {self.key_name: self.key_value}
entities = self.model_class.objects.filter(**query)
if len(entities) > 0:
credential = getattr(entities[0], self.property_name)
if credential and hasattr(credential, 'set_store'):
creden... | def locked_get(self):
"""Retrieve Credential from datastore.
Returns: | random_line_split |
errors.py | #!/usr/bin/env python
# Copyright 2007 The Closure Linter 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
#
#... | (name):
"""Get the error code for the given error name.
Args:
name: The name of the error
Returns:
The error code
"""
return globals()[name]
# "File-fatal" errors - these errors stop further parsing of a single file
FILE_NOT_FOUND = -1
FILE_DOES_NOT_PARSE = -2
# Spacing
EXTRA_SPACE = 1
MISSING_SP... | ByName | identifier_name |
errors.py | #!/usr/bin/env python
# Copyright 2007 The Closure Linter 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
#
#... |
# "File-fatal" errors - these errors stop further parsing of a single file
FILE_NOT_FOUND = -1
FILE_DOES_NOT_PARSE = -2
# Spacing
EXTRA_SPACE = 1
MISSING_SPACE = 2
EXTRA_LINE = 3
MISSING_LINE = 4
ILLEGAL_TAB = 5
WRONG_INDENTATION = 6
WRONG_BLANK_LINE_COUNT = 7
# Semicolons
MISSING_SEMICOLON = 10
MISSING_SEMICOLON_... | """Get the error code for the given error name.
Args:
name: The name of the error
Returns:
The error code
"""
return globals()[name] | identifier_body |
errors.py | #!/usr/bin/env python
# Copyright 2007 The Closure Linter 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
#
#... |
# Interfaces
INTERFACE_CONSTRUCTOR_CANNOT_HAVE_PARAMS = 400
INTERFACE_METHOD_CANNOT_HAVE_CODE = 401
# Comments
MISSING_END_OF_SCOPE_COMMENT = 500
MALFORMED_END_OF_SCOPE_COMMENT = 501
# goog.scope - Namespace aliasing
# TODO(nnaze) Add additional errors here and in aliaspass.py
INVALID_USE_OF_GOOG_SCOPE = 600
EXTRA_G... | FILE_IN_BLOCK = 301 | random_line_split |
input_process.rs | extern crate glutin;
extern crate state;
use state::{GraphicsState, CoreState};
use glutin::Event::{Closed, KeyboardInput};
use glutin::ElementState::{Pressed};
use glutin::VirtualKeyCode as VK;
pub fn execute(graphics_state: &mut GraphicsState, core_state: &mut CoreState) -> () {
for event in graphics_state.displ... | KeyboardInput(Pressed, _, Some(VK::F3)) => {
graphics_state.reload_shaders = true;
}
KeyboardInput(Pressed, _, Some(VK::F4)) => {
core_state.reload = true
}
KeyboardInput(Pressed, _, Some(VK::F5)) => {
core_state... | } | random_line_split |
input_process.rs | extern crate glutin;
extern crate state;
use state::{GraphicsState, CoreState};
use glutin::Event::{Closed, KeyboardInput};
use glutin::ElementState::{Pressed};
use glutin::VirtualKeyCode as VK;
pub fn | (graphics_state: &mut GraphicsState, core_state: &mut CoreState) -> () {
for event in graphics_state.display.poll_events() {
match event {
Closed => {
core_state.quit = true
}
KeyboardInput(Pressed, _, Some(VK::Escape)) => {
core_state.quit... | execute | identifier_name |
input_process.rs | extern crate glutin;
extern crate state;
use state::{GraphicsState, CoreState};
use glutin::Event::{Closed, KeyboardInput};
use glutin::ElementState::{Pressed};
use glutin::VirtualKeyCode as VK;
pub fn execute(graphics_state: &mut GraphicsState, core_state: &mut CoreState) -> () | }
}
| {
for event in graphics_state.display.poll_events() {
match event {
Closed => {
core_state.quit = true
}
KeyboardInput(Pressed, _, Some(VK::Escape)) => {
core_state.quit = true
}
KeyboardInput(Pressed, _, Some(VK::F3... | identifier_body |
input_process.rs | extern crate glutin;
extern crate state;
use state::{GraphicsState, CoreState};
use glutin::Event::{Closed, KeyboardInput};
use glutin::ElementState::{Pressed};
use glutin::VirtualKeyCode as VK;
pub fn execute(graphics_state: &mut GraphicsState, core_state: &mut CoreState) -> () {
for event in graphics_state.displ... |
_ => ()
}
}
}
| {
core_state.reset = true
} | conditional_block |
version.rs | /*!
Querying SDL Version
*/
use std::ffi::CStr;
use std::fmt;
use sys::version as ll;
/// A structure that contains information about the version of SDL in use.
#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
pub struct | {
/// major version
pub major: u8,
/// minor version
pub minor: u8,
/// update version (patchlevel)
pub patch: u8,
}
impl Version {
/// Convert a raw *SDL_version to Version.
pub fn from_ll(v: ll::SDL_version) -> Version {
Version { major: v.major, minor: v.minor, patch: v.patc... | Version | identifier_name |
version.rs | /*!
Querying SDL Version
*/
use std::ffi::CStr;
use std::fmt;
use sys::version as ll;
/// A structure that contains information about the version of SDL in use.
#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
pub struct Version {
/// major version
pub major: u8,
/// minor version
pub minor: u8,
... | pub fn version() -> Version {
unsafe {
let mut cver = ll::SDL_version { major: 0, minor: 0, patch: 0};
ll::SDL_GetVersion(&mut cver);
Version::from_ll(cver)
}
}
/// Get the code revision of SDL that is linked against your program.
pub fn revision() -> String {
unsafe {
let r... | }
/// Get the version of SDL that is linked against your program. | random_line_split |
version.rs | /*!
Querying SDL Version
*/
use std::ffi::CStr;
use std::fmt;
use sys::version as ll;
/// A structure that contains information about the version of SDL in use.
#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
pub struct Version {
/// major version
pub major: u8,
/// minor version
pub minor: u8,
... |
}
/// Get the version of SDL that is linked against your program.
pub fn version() -> Version {
unsafe {
let mut cver = ll::SDL_version { major: 0, minor: 0, patch: 0};
ll::SDL_GetVersion(&mut cver);
Version::from_ll(cver)
}
}
/// Get the code revision of SDL that is linked against yo... | {
write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
} | identifier_body |
address.py | """Contains the :code:`Address` class, representing a collection of reverse
geocoding results. Primarily, this functions as a container for a set of
:code:`errorgeopy.Location` objects after a successful reverse geocode, and
exposes methods that operate on this set of results, including:
- de-duplication
- extracting ... | (object):
"""Represents a collection of parsed reverse geocoder responses (parsed with
geopy). Each member of the :code:`address` property (which is iterable) is a
:code:`geopy.address` object. The raw respones can therefore be obtained
with:
>>> [a.raw for a in Address.addresses]
:code:`e... | Address | identifier_name |
address.py | """Contains the :code:`Address` class, representing a collection of reverse
geocoding results. Primarily, this functions as a container for a set of
:code:`errorgeopy.Location` objects after a successful reverse geocode, and
exposes methods that operate on this set of results, including:
- de-duplication
- extracting ... |
@check_addresses_exist
def regex(self):
"""regex()
Returns a regular expression that matches all of the reverse geocoded
addresses... well it would if I had written this code.
Raises:
NotImplementedError
"""
raise NotImplementedError
@check_add... | """longest_common_sequence(separator='')
Returns the longest common sequence of the reverse geocoded
addresses... or it would, if I had written this code.
Raises:
NotImplementedError
"""
# return utils.longest_common_sequence([str(a) for a in self.addresses],
... | identifier_body |
address.py | """Contains the :code:`Address` class, representing a collection of reverse
geocoding results. Primarily, this functions as a container for a set of
:code:`errorgeopy.Location` objects after a successful reverse geocode, and
exposes methods that operate on this set of results, including:
- de-duplication
- extracting ... | string address).
Returns:
list. Return value is a list of tuples, where each tuple contains a
geopy Location, and a matching score based on an extension of the
Levenshtien distance between the expectation and the Location's
address (a higher score is ... | Kwargs:
limit (int): The maximum number of match candidates to retrieve
from fuzzywuzzy. The length of the returned array may be longer, if
the set of addresses has identical addresses that are good matches
for the expected address (i.e. if two geocoders resolve t... | random_line_split |
address.py | """Contains the :code:`Address` class, representing a collection of reverse
geocoding results. Primarily, this functions as a container for a set of
:code:`errorgeopy.Location` objects after a successful reverse geocode, and
exposes methods that operate on this set of results, including:
- de-duplication
- extracting ... |
return result
@check_addresses_exist
def parse(self):
"""parse()
Raises:
NotImplementedError
"""
# return [usaddress.parse(str(a)) for a in self.addresses]
raise NotImplementedError
@check_addresses_exist
def tag(self, summarise=True):
... | result.extend([(x, extraction[1]) for x in self.addresses
if str(x) == extraction[0]]) | conditional_block |
BraitenbergVehicle2b.py | """
Braitenberg Vehicle2b
The more light sensed on the left side the faster the right motor moves.
The more light sensed on the right side the faster the left motor moves.
This causes the robot to turn towards a light source.
"""
from pyrobot.brain import Brain, avg
class | (Brain):
def setup(self):
self.robot.light[0].units = "SCALED"
def step(self):
leftSpeed = max([s.value for s in self.robot.light[0]["right"]])
rightSpeed = max([s.value for s in self.robot.light[0]["left"]])
print "leftSpeed, rightSpeed:", leftSpeed, rightSpeed
self.motors(leftSpee... | Vehicle | identifier_name |
BraitenbergVehicle2b.py | """
Braitenberg Vehicle2b
The more light sensed on the left side the faster the right motor moves.
The more light sensed on the right side the faster the left motor moves.
This causes the robot to turn towards a light source.
"""
from pyrobot.brain import Brain, avg
class Vehicle(Brain):
def setup(self):
sel... |
return Vehicle('Braitenberg2a', engine)
| raise "Robot should have light sensors!" | conditional_block |
BraitenbergVehicle2b.py | """
Braitenberg Vehicle2b
The more light sensed on the left side the faster the right motor moves.
The more light sensed on the right side the faster the left motor moves.
This causes the robot to turn towards a light source.
"""
from pyrobot.brain import Brain, avg
class Vehicle(Brain):
|
def INIT(engine):
if engine.robot.type not in ['K-Team', 'Pyrobot']:
raise "Robot should have light sensors!"
return Vehicle('Braitenberg2a', engine)
| def setup(self):
self.robot.light[0].units = "SCALED"
def step(self):
leftSpeed = max([s.value for s in self.robot.light[0]["right"]])
rightSpeed = max([s.value for s in self.robot.light[0]["left"]])
print "leftSpeed, rightSpeed:", leftSpeed, rightSpeed
self.motors(leftSpeed, rightSpe... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.