file_name large_stringlengths 4 140 | prefix large_stringlengths 0 12.1k | suffix large_stringlengths 0 12k | middle large_stringlengths 0 7.51k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
main.js | (function() {
// Creating application
var app = {};
var parseData = function(data) {
var result = {};
// TODO: Get better performance here
var years = _.groupBy(data, 'year');
for (var key in years) {
result[key] = _.groupBy(years[key], 'cartodb_id');
}
return result;
};
var M... | this.input.oninput();
};
this.setText = function(text) {
this.label.textContent = text;
};
this.init = (function() {
this.timer = null;
this.el = document.getElementById('slider');
this.input = document.getElementById('sliderRange');
this.label = document.getElement... | this.input.setAttribute('max', max);
};
this.setValue = function(value) {
this.input.value = value; | random_line_split |
main.js | (function() {
// Creating application
var app = {};
var parseData = function(data) {
var result = {};
// TODO: Get better performance here
var years = _.groupBy(data, 'year');
for (var key in years) {
result[key] = _.groupBy(years[key], 'cartodb_id');
}
return result;
};
var M... |
return style;
});
}
};
this.setColors = function(min, max, buckets) {
this.getColor = d3.scale.quantize()
.domain([min, max])
.range(colorbrewer.GnBu[buckets]);
};
this.init = (function() {
this.el = document.getElementById('map');
this.cr... | {
style.fillColor = self.options.featureStyle.fillColor;
} | conditional_block |
count.py | """
count number of reads mapping to features of transcripts
"""
import os
import sys
import itertools
import pandas as pd
import gffutils
from bcbio.utils import file_exists
from bcbio.distributed.transaction import file_transaction
from bcbio.log import logger
from bcbio import bam
import bcbio.pipeline.datadict as... | df = df.join(pd.io.parsers.read_table(f, sep="\t", index_col=0,
header=None,
names=[col_names[i]]))
df.to_csv(out_file, sep="\t", index_label="id")
return out_file
def annotate_combined_count_file(... | """
combine a set of count files into a single combined file
"""
assert all([file_exists(x) for x in files]), \
"Some count files in %s do not exist." % files
for f in files:
assert file_exists(f), "%s does not exist or is empty." % f
col_names = [os.path.basename(x.replace(ext, ""))... | identifier_body |
count.py | """
count number of reads mapping to features of transcripts
"""
import os
import sys
import itertools
import pandas as pd
import gffutils
from bcbio.utils import file_exists
from bcbio.distributed.transaction import file_transaction
from bcbio.log import logger
from bcbio import bam
import bcbio.pipeline.datadict as... |
if not gffutils:
return None
db = gffutils.FeatureDB(dbfn, keep_order=True)
if not out_file:
out_dir = os.path.dirname(count_file)
out_file = os.path.join(out_dir, "annotated_combined.counts")
# if the genes don't have a gene_id or gene_name set, bail out
try:
sy... | return None | conditional_block |
count.py | """
count number of reads mapping to features of transcripts
"""
import os
import sys
import itertools
import pandas as pd
import gffutils
from bcbio.utils import file_exists
from bcbio.distributed.transaction import file_transaction
from bcbio.log import logger
from bcbio import bam
import bcbio.pipeline.datadict as... | # if the genes don't have a gene_id or gene_name set, bail out
try:
symbol_lookup = {f['gene_id'][0]: f['gene_name'][0] for f in
db.features_of_type('exon')}
except KeyError:
return None
df = pd.io.parsers.read_table(count_file, sep="\t", index_col=0, header=0)
... | random_line_split | |
count.py | """
count number of reads mapping to features of transcripts
"""
import os
import sys
import itertools
import pandas as pd
import gffutils
from bcbio.utils import file_exists
from bcbio.distributed.transaction import file_transaction
from bcbio.log import logger
from bcbio import bam
import bcbio.pipeline.datadict as... | (count_file, gtf_file, out_file=None):
dbfn = gtf_file + ".db"
if not file_exists(dbfn):
return None
if not gffutils:
return None
db = gffutils.FeatureDB(dbfn, keep_order=True)
if not out_file:
out_dir = os.path.dirname(count_file)
out_file = os.path.join(out_dir, ... | annotate_combined_count_file | identifier_name |
ZaServerController.ts | /*
* T4Z - TypeScript 4 Zimlet
* Copyright (C) 2017 ZeXtras S.r.l.
*
* This file is part of T4Z - TypeScript 4 Zimlet.
*
* 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, version 2 of
* t... | export class ZaServerController extends ZaXFormViewController {
} |
import {ZaXFormViewController} from "../../common/ZaXFormViewController";
| random_line_split |
ZaServerController.ts | /*
* T4Z - TypeScript 4 Zimlet
* Copyright (C) 2017 ZeXtras S.r.l.
*
* This file is part of T4Z - TypeScript 4 Zimlet.
*
* 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, version 2 of
* t... | extends ZaXFormViewController {
}
| ZaServerController | identifier_name |
test_refresh.py | # vim: fileencoding=utf-8 et sw=4 ts=4 tw=80:
# python-quilt - A Python implementation of the quilt patch system
#
# See LICENSE comming with the source of python-quilt for details.
import os
from helpers import make_file
from unittest import TestCase
import quilt.refresh
from quilt.db import Db, Patch
from quilt.... | (self):
with TmpDirectory() as dir:
old_dir = os.getcwd()
try:
os.chdir(dir.get_name())
db = Db(".pc")
db.create()
backup = os.path.join(".pc", "patch")
os.mkdir(backup)
make_file(b"", backup,... | test_refresh | identifier_name |
test_refresh.py | # vim: fileencoding=utf-8 et sw=4 ts=4 tw=80:
# python-quilt - A Python implementation of the quilt patch system
#
# See LICENSE comming with the source of python-quilt for details.
import os
from helpers import make_file
from unittest import TestCase
import quilt.refresh
from quilt.db import Db, Patch
from quilt.... | with TmpDirectory() as dir:
old_dir = os.getcwd()
try:
os.chdir(dir.get_name())
db = Db(".pc")
db.create()
backup = os.path.join(".pc", "patch")
os.mkdir(backup)
make_file(b"", backup, "file")
... | identifier_body | |
test_refresh.py | # vim: fileencoding=utf-8 et sw=4 ts=4 tw=80:
# python-quilt - A Python implementation of the quilt patch system
#
# See LICENSE comming with the source of python-quilt for details.
import os |
from helpers import make_file
from unittest import TestCase
import quilt.refresh
from quilt.db import Db, Patch
from quilt.utils import TmpDirectory
class Test(TestCase):
def test_refresh(self):
with TmpDirectory() as dir:
old_dir = os.getcwd()
try:
os.chdir(dir... | random_line_split | |
main.js | /**
* Implementa el método fecha() que devuelva una fecha válida. Lanzará una excepción en caso contrario.
* @author Jesús Mejías Leiva
*/
{
function init() | try {
date();
} catch (e) {
console.log(e.message);
}
}
// creo mi exception personalizada
let dateNotValid = function(msg, name) {
this.message = msg;
this.name = name;
};
let date = function() {
let date = new Date("Diciembre 17, 1995 03:24:00");
if (date == "Invali... | {
| identifier_name |
main.js | /**
* Implementa el método fecha() que devuelva una fecha válida. Lanzará una excepción en caso contrario.
* @author Jesús Mejías Leiva
*/
{
function init() {
try {
date();
} catch (e) {
console.log(e.message);
}
}
// creo mi exception personalizada
let dateNotValid = function(msg, n... | } | return date;
}
};
window.addEventListener("load", init); | random_line_split |
main.js | /**
* Implementa el método fecha() que devuelva una fecha válida. Lanzará una excepción en caso contrario.
* @author Jesús Mejías Leiva
*/
{
function init() {
try {
date();
} catch (e) {
console.log(e.message);
}
}
// creo mi exception personalizada
let dateNotValid = function(msg, n... | window.addEventListener("load", init);
}
| return date;
}
};
| conditional_block |
main.js | /**
* Implementa el método fecha() que devuelva una fecha válida. Lanzará una excepción en caso contrario.
* @author Jesús Mejías Leiva
*/
{
function init() {
| creo mi exception personalizada
let dateNotValid = function(msg, name) {
this.message = msg;
this.name = name;
};
let date = function() {
let date = new Date("Diciembre 17, 1995 03:24:00");
if (date == "Invalid Date") {
// creo mi un objeto con mi exception personalizada
let dNotVal... | try {
date();
} catch (e) {
console.log(e.message);
}
}
// | identifier_body |
client.rs | use connection::Connection;
use error::{Error, ErrorKind, Result};
use frame::settings::{SettingsFrame, Setting};
use frame::{FrameKind, WriteFrame, ReadFrame};
use {Settings, WindowSize};
pub struct Client<C> {
conn: C,
settings: Settings,
window_in: WindowSize,
window_out: WindowSize,
}
impl<C: Conn... |
#[test]
fn test_client_receive_preface() {
let (mut sconn, cconn) = MockStream::new();
let mut client = Client::new(cconn);
// server preface
let frame = SettingsFrame::default();
sconn.write_frame(frame).unwrap();
client.receive_preface().unwrap();
}
}
| {
let (mut sconn, cconn) = MockStream::new();
let mut client = Client::new(cconn);
client.send_preface().unwrap();
let mut buf = [0; 24];
sconn.read(&mut buf).unwrap();
let preface = b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n";
assert_eq!(&buf, preface);
// settin... | identifier_body |
client.rs | use connection::Connection;
use error::{Error, ErrorKind, Result};
use frame::settings::{SettingsFrame, Setting};
use frame::{FrameKind, WriteFrame, ReadFrame};
use {Settings, WindowSize};
pub struct Client<C> {
conn: C,
settings: Settings,
window_in: WindowSize,
window_out: WindowSize,
}
impl<C: Conn... | (&mut self, frame: SettingsFrame) {
self.settings.update(frame)
}
}
#[cfg(test)]
mod test {
use std::io::Read;
use mock::MockStream;
use super::Client;
use frame::{FrameKind, ReadFrame, WriteFrame};
use frame::settings::SettingsFrame;
#[test]
fn test_client_send_preface() {
... | handle_settings_frame | identifier_name |
client.rs | use connection::Connection;
use error::{Error, ErrorKind, Result};
use frame::settings::{SettingsFrame, Setting};
use frame::{FrameKind, WriteFrame, ReadFrame};
use {Settings, WindowSize};
pub struct Client<C> {
conn: C,
settings: Settings,
window_in: WindowSize,
window_out: WindowSize,
}
impl<C: Conn... | fn test_client_receive_preface() {
let (mut sconn, cconn) = MockStream::new();
let mut client = Client::new(cconn);
// server preface
let frame = SettingsFrame::default();
sconn.write_frame(frame).unwrap();
client.receive_preface().unwrap();
}
} | #[test] | random_line_split |
client.rs | use connection::Connection;
use error::{Error, ErrorKind, Result};
use frame::settings::{SettingsFrame, Setting};
use frame::{FrameKind, WriteFrame, ReadFrame};
use {Settings, WindowSize};
pub struct Client<C> {
conn: C,
settings: Settings,
window_in: WindowSize,
window_out: WindowSize,
}
impl<C: Conn... | else {
return Err(Error::new(ErrorKind::Protocol, "Invalid Preface, bad frame"));
}
Ok(())
}
fn handle_next(&mut self) -> Result<()> {
match try!(self.conn.read_frame(100)) {
FrameKind::Settings(frame) => println!("Settings"),
// Unknown
... | {
if frame.is_ack() {
return Err(Error::new(ErrorKind::Protocol, "Invalid Preface, received ACK"));
}
} | conditional_block |
basic-demo.ts | /* tslint:disable:no-any no-magic-numbers prefer-function-over-method */
import { Component } from '@angular/core';
import { getBasicData } from './data';
@Component({
selector: 'basic-demo',
template: require('./basic-demo.html')
})
export class BasicDemoComponent {
private data: any[] = getBasicData(10);
pri... |
private afterOnCellMouseDown(e: any) {
// tslint:disable-next-line:no-console
console.log(e);
}
}
| {
// tslint:disable-next-line:no-console
console.log(e);
} | identifier_body |
basic-demo.ts | /* tslint:disable:no-any no-magic-numbers prefer-function-over-method */
import { Component } from '@angular/core';
import { getBasicData } from './data';
@Component({
selector: 'basic-demo',
template: require('./basic-demo.html')
})
export class BasicDemoComponent {
private data: any[] = getBasicData(10);
pri... | console.log(e);
}
} | private afterOnCellMouseDown(e: any) {
// tslint:disable-next-line:no-console | random_line_split |
basic-demo.ts | /* tslint:disable:no-any no-magic-numbers prefer-function-over-method */
import { Component } from '@angular/core';
import { getBasicData } from './data';
@Component({
selector: 'basic-demo',
template: require('./basic-demo.html')
})
export class | {
private data: any[] = getBasicData(10);
private colHeaders: string[] = ['ID', 'First Name', 'Last Name', 'Address',
'Favorite food', 'Price', 'Is active'];
private columns: any[] = [
{
data: 'id'
},
{
data: 'name.first',
renderer: 'text',
readOnly: true
},
{
... | BasicDemoComponent | identifier_name |
conftest.py | import pytest
from tests.base import Author, Post, Comment, Keyword, fake
|
def make_author():
return Author(
id=fake.random_int(),
first_name=fake.first_name(),
last_name=fake.last_name(),
twitter=fake.domain_word(),
)
def make_post(with_comments=True, with_author=True, with_keywords=True):
comments = [make_comment() for _ in range(2)] if with_co... | random_line_split | |
conftest.py | import pytest
from tests.base import Author, Post, Comment, Keyword, fake
def make_author():
return Author(
id=fake.random_int(),
first_name=fake.first_name(),
last_name=fake.last_name(),
twitter=fake.domain_word(),
)
def make_post(with_comments=True, with_author=True, with_... | ():
return make_post(with_comments=False)
@pytest.fixture()
def post_with_null_author():
return make_post(with_author=False)
@pytest.fixture()
def posts():
return [make_post() for _ in range(3)]
| post_with_null_comment | identifier_name |
conftest.py | import pytest
from tests.base import Author, Post, Comment, Keyword, fake
def make_author():
return Author(
id=fake.random_int(),
first_name=fake.first_name(),
last_name=fake.last_name(),
twitter=fake.domain_word(),
)
def make_post(with_comments=True, with_author=True, with_... |
@pytest.fixture()
def author():
return make_author()
@pytest.fixture()
def authors():
return [make_author() for _ in range(3)]
@pytest.fixture()
def comments():
return [make_comment() for _ in range(3)]
@pytest.fixture()
def post():
return make_post()
@pytest.fixture()
def post_with_null_comm... | return Keyword(keyword=fake.domain_word()) | identifier_body |
link-item-template-content-editor.component.ts | import { ChangeDetectionStrategy, Component, Input } from '@angular/core';
import { IFormGroup } from '@rxweb/types';
import { LinkItemContent, LinkItemSource } from '../homescreen';
import { HomeScreenService } from '../home-screen.service';
@Component({
selector: 'rcc-link-item-template-content-editor',
template... | (source: LinkItemSource) {
let content: LinkItemContent;
switch (source) {
case LinkItemSource.NONE:
content = { source, url: '', external: false, request_user_link: false };
break;
case LinkItemSource.SERVICE_INFO_PHONE:
case LinkItemSource.SERVICE_INFO_EMAIL:
case LinkI... | sourceTypeChanged | identifier_name |
link-item-template-content-editor.component.ts | import { ChangeDetectionStrategy, Component, Input } from '@angular/core';
import { IFormGroup } from '@rxweb/types';
import { LinkItemContent, LinkItemSource } from '../homescreen';
import { HomeScreenService } from '../home-screen.service';
@Component({
selector: 'rcc-link-item-template-content-editor',
template... | ];
@Input() formGroup: IFormGroup<LinkItemContent>;
SOURCE_NONE = LinkItemSource.NONE;
SOURCE_ADDRESS = LinkItemSource.SERVICE_INFO_ADDRESS;
SOURCE_MENU_ITEM = LinkItemSource.SERVICE_MENU_ITEM;
constructor(private formService: HomeScreenService) {
}
sourceTypeChanged(source: LinkItemSource) {
let ... | { value: LinkItemSource.SERVICE_INFO_WEBSITE, label: 'Service website' },
{ value: LinkItemSource.SERVICE_INFO_ADDRESS, label: 'Service address' },
{ value: LinkItemSource.SERVICE_MENU_ITEM, label: 'Service menu item' }, | random_line_split |
link-item-template-content-editor.component.ts | import { ChangeDetectionStrategy, Component, Input } from '@angular/core';
import { IFormGroup } from '@rxweb/types';
import { LinkItemContent, LinkItemSource } from '../homescreen';
import { HomeScreenService } from '../home-screen.service';
@Component({
selector: 'rcc-link-item-template-content-editor',
template... |
sourceTypeChanged(source: LinkItemSource) {
let content: LinkItemContent;
switch (source) {
case LinkItemSource.NONE:
content = { source, url: '', external: false, request_user_link: false };
break;
case LinkItemSource.SERVICE_INFO_PHONE:
case LinkItemSource.SERVICE_INFO_EM... | {
} | identifier_body |
unreachable-locals.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 diverge() -> ! {
panic!();
}
| {
after_return();
after_panic();
after_diverging_function();
after_break();
after_continue();
} | identifier_body |
unreachable-locals.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... | match (20i32, 'c') {
(a, ref b) => {}
}
for a in &[111i32] {}
}
}
fn after_continue() {
for _ in 0..10i32 {
break;
let x = "0";
let (ref y,z) = (1i32, 2u32);
match (20i32, 'c') {
(a, ref b) => {}
}
for a in &[111i32... | loop {
break;
let x = "0";
let (ref y,z) = (1i32, 2u32); | random_line_split |
unreachable-locals.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... | () {
diverge();
let x = "0";
let (ref y,z) = (1i32, 2u32);
match (20i32, 'c') {
(a, ref b) => {}
}
for a in &[111i32] {}
}
fn after_break() {
loop {
break;
let x = "0";
let (ref y,z) = (1i32, 2u32);
match (20i32, 'c') {
(a, ref b) => {}
... | after_diverging_function | identifier_name |
index.ts | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... | const {expression, name} = sinkNode;
// Verify that the property is indeed 'innerHTML'
if (name.getText() !== 'innerHTML') {
return undefined;
}
replacement = `${expression.getText()}.textContent = ${replaced}`;
}
// this case shouldn't ever happen
if (!replacement) {
... | random_line_split | |
index.ts | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... |
replacement = `${expression.getText()}.textContent = ${replaced}`;
}
// this case shouldn't ever happen
if (!replacement) {
return undefined;
}
return {
changes: [{
start: node.getStart(),
end: node.getEnd(),
replacement,
sourceFile: node.getSourc... | {
return undefined;
} | conditional_block |
index.ts | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... | (node: ts.Node):
asserts node is ts.BinaryExpression {
if (!ts.isBinaryExpression(node)) {
throw new Error(
`Matched node \`${node.getText()}\` is not a BinaryExpression; ` +
`probably an upstream bug or a configuration error`);
}
}
/**
* Fixer which suggest using assignment to Element.tex... | assertBinaryExpression | identifier_name |
index.ts | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... |
/**
* Fixer which suggest using assignment to Element.textContent instead of
* Element.innerHTML.
*
* There are two ways how you can assign to innerHTML:
* 1) element.innerHTML = value
* 2) element['innerHTML'] = value
* We will suggest a fix `element.textContent = value` for both of these cases.
*
* Thi... | {
if (!ts.isBinaryExpression(node)) {
throw new Error(
`Matched node \`${node.getText()}\` is not a BinaryExpression; ` +
`probably an upstream bug or a configuration error`);
}
} | identifier_body |
weekly.js | d3.json('/data/weekly.json', function(data) {
nv.addGraph(function() {
var chart = nv.models.stackedAreaChart()
.margin({right: 100})
.x(function(d) { return d[0] }) //We can modify the data accessor functions...
.y(function(d) { return d[1]*100 }) //...in... | return d3.time.format('%b-%Y')(new Date(d))
});
chart.yAxis
.tickFormat(d3.format('$,f'));
d3.select('#chart4 svg')
.datum(data)
.call(chart);
nv.utils.windowResize(chart.update);
return chart;
});
}) | random_line_split | |
point.js | import F2 from '@antv/f2';
fetch('https://gw.alipayobjects.com/os/antfincdn/N81gEpw2Ef/income.json')
.then(res => res.json())
.then(data => {
const chart = new F2.Chart({
id: 'container',
pixelRatio: window.devicePixelRatio
});
chart.source(data, {
time: {
type: 'timeCat',
... | position: [ '2013-05-31', 2.093 ],
content: '余额宝刚成立时,并未达到\n目标资产配置,故收益率较低',
style: {
textAlign: 'left',
lineHeight: 16,
fontSize: 10
},
offsetX: 10,
offsetY: -10
});
chart.guide().point({
position: [ '2016-09-04', 2.321 ]
});
chart.guide(... |
chart.guide().point({
position: [ '2013-05-31', 2.093 ]
});
chart.guide().text({ | random_line_split |
utils.rs | Eq, AsBytes};
use math::{Scalar, Point, Vect};
// FIXME: remove that in favor of `push_xy_circle` ?
/// Pushes a discretized counterclockwise circle to a buffer.
#[inline]
pub fn push_circle<N: Scalar>(radius: N, nsubdiv: u32, dtheta: N, y: N, out: &mut Vec<Pnt3<N>>) {
let mut curr_theta: N = na::zero();
for ... |
/// Reverses the clockwising of a set of faces.
#[inline]
pub fn reverse_clockwising(indices: &mut [Pnt3<u32>]) {
for i in indices.iter_mut() {
mem::swap(&mut i.x, &mut i.y);
}
}
/// Duplicates the indices of each triangle on the given index buffer.
///
/// For example: [ (0.0, 1.0, 2.0) ] becomes: [... | {
out.push(Pnt3::new(ul.clone(), dl, dr.clone()));
out.push(Pnt3::new(dr , ur, ul));
} | identifier_body |
utils.rs | Eq, AsBytes};
use math::{Scalar, Point, Vect};
// FIXME: remove that in favor of `push_xy_circle` ?
/// Pushes a discretized counterclockwise circle to a buffer.
#[inline]
pub fn push_circle<N: Scalar>(radius: N, nsubdiv: u32, dtheta: N, y: N, out: &mut Vec<Pnt3<N>>) {
let mut curr_theta: N = na::zero();
for ... |
(out, new_coords)
}
/// Computes the normals of a set of vertices.
#[inline]
pub fn compute_normals<P>(coordinates: &[P], faces: &[Pnt3<u32>], normals: &mut Vec<P::Vect>)
where P: Point,
P::Vect: Vect + Cross<CrossProductType = <P as Point>::Vect> {
let mut divisor: Vec<<P::Vect as Vect>::Scalar... | new_coords.shrink_to_fit(); | random_line_split |
utils.rs | ` ?
/// Pushes a discretized counterclockwise circle to a buffer.
#[inline]
pub fn push_circle<N: Scalar>(radius: N, nsubdiv: u32, dtheta: N, y: N, out: &mut Vec<Pnt3<N>>) {
let mut curr_theta: N = na::zero();
for _ in 0 .. nsubdiv {
out.push(Pnt3::new(curr_theta.cos() * radius, y.clone(), curr_theta.s... |
normal = cross
}
| conditional_block | |
utils.rs | Eq, AsBytes};
use math::{Scalar, Point, Vect};
// FIXME: remove that in favor of `push_xy_circle` ?
/// Pushes a discretized counterclockwise circle to a buffer.
#[inline]
pub fn push_circle<N: Scalar>(radius: N, nsubdiv: u32, dtheta: N, y: N, out: &mut Vec<Pnt3<N>>) {
let mut curr_theta: N = na::zero();
for ... | (base_circle: u32,
point: u32,
nsubdiv: u32,
out: &mut Vec<Pnt3<u32>>) {
assert!(nsubdiv > 0);
for i in 0 .. nsubdiv - 1 {
out.push(Pnt3::new(base_cir... | push_degenerate_open_top_ring_indices | identifier_name |
setup.py | #!/usr/bin/env python
import re
from setuptools import setup, find_packages
from $PROJECT$.constants import __PROJECT__, __DESCRIPTION__, __VERSION__
| packages = f.read().splitlines()
except (IOError, OSError) as ex:
raise RuntimeError("Can't open file with requirements: %s", repr(ex))
packages = (p.strip() for p in packages if not re.match("^\s*#", p))
packages = list(filter(None, packages))
return packages
def _install_requirem... | def _get_requirements(path):
try:
with open(path) as f: | random_line_split |
setup.py | #!/usr/bin/env python
import re
from setuptools import setup, find_packages
from $PROJECT$.constants import __PROJECT__, __DESCRIPTION__, __VERSION__
def _get_requirements(path):
try:
with open(path) as f:
packages = f.read().splitlines()
except (IOError, OSError) as ex:
raise Run... | ():
requirements = _get_requirements('requirements.txt')
return requirements
setup(
name = __PROJECT__,
version = __VERSION__,
description = __DESCRIPTION__,
author = "Vaclav Pavlin",
author_email = 'vpavlin@redhat.com',
url = '',
license = "LGPL3",
entry_points = {
'con... | _install_requirements | identifier_name |
setup.py | #!/usr/bin/env python
import re
from setuptools import setup, find_packages
from $PROJECT$.constants import __PROJECT__, __DESCRIPTION__, __VERSION__
def _get_requirements(path):
try:
with open(path) as f:
packages = f.read().splitlines()
except (IOError, OSError) as ex:
raise Run... |
setup(
name = __PROJECT__,
version = __VERSION__,
description = __DESCRIPTION__,
author = "Vaclav Pavlin",
author_email = 'vpavlin@redhat.com',
url = '',
license = "LGPL3",
entry_points = {
'console_scripts': ['%s=%s.cli.main:main' % (__PROJECT__, __PROJECT__)],
},
pack... | requirements = _get_requirements('requirements.txt')
return requirements | identifier_body |
urls.py | """code_for_good URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Cla... | ] | url(r'^admin/', admin.site.urls), | random_line_split |
generateDoc.ts | import { isEmpty } from '../src/dependencies/ramda.ts';
import { fromFileUrl, resolve } from '../src/dependencies/path.ts';
import { Command, ExtraPermissions, YargsOptions } from '../src/dependencies/yargs.ts';
import * as audit from '../src/commands/simple/audit.ts';
import * as burgeon from '../src/commands/simple/... | const readmePath = resolve(appRootPath, 'README.md');
const initialReadmeContent = await Deno.readTextFile(readmePath);
const updatedReadmeContent = initialReadmeContent
.replace(/<!-- START CLI DOC -->.*<!-- END CLI DOC -->/s, fullMarkdownContent);
const markdownFormatterPath = resolve(appRootPath, 'node... |
const currentScriptFilePath = fromFileUrl(import.meta.url);
const appRootPath = resolve(currentScriptFilePath, '..', '..'); | random_line_split |
generateDoc.ts | import { isEmpty } from '../src/dependencies/ramda.ts';
import { fromFileUrl, resolve } from '../src/dependencies/path.ts';
import { Command, ExtraPermissions, YargsOptions } from '../src/dependencies/yargs.ts';
import * as audit from '../src/commands/simple/audit.ts';
import * as burgeon from '../src/commands/simple/... |
};
main()
.catch(async (error) => {
await Deno.stdout.write(new TextEncoder().encode(error.stack));
Deno.exit(1);
});
| { throw Error(`Markdown formatting ended in status ${code}`); } | conditional_block |
inputMgr.py | # ========================== Start Copyright Notice ========================== #
# #
# Copyright 2014 F.D.I.S. #
# This file is part of Kinetic Gunner: Gunner of Angst ... | paramList = [("WINDOW", str(windowHandle))]
if os.name == "nt":
#t = [("w32_mouse","DISCL_FOREGROUND"), ("w32_mouse", "DISCL_NONEXCLUSIVE")]
t = [("w32_mouse","DISCL_FOREGROUND"), ("w32_mouse", "DISCL_EXCLUSIVE")]
else:
t = [("x11_mouse_grab", "true"), ("x11_... | ''' Manages keyboard and mouse, with buffered and unbuffered input. '''
def __init__(self, engine):
''' Creates Input Listeners and Initializes Variables. '''
self.engine = engine
OIS.KeyListener.__init__(self)
OIS.MouseListener.__init__(self)
OIS.JoyStickListener.__init... | identifier_body |
inputMgr.py | # ========================== Start Copyright Notice ========================== #
# #
# Copyright 2014 F.D.I.S. #
# This file is part of Kinetic Gunner: Gunner of Angst ... |
paramList.extend(t)
self.inputManager = OIS.createPythonInputSystem(paramList)
# Now InputManager is initialized for use. Keyboard and Mouse objects
# must still be initialized separately
self.keyboard = None
self.mouse = None
try:
self.keyboar... | t = [("x11_mouse_grab", "true"), ("x11_mouse_hide", "true")]
#t = [("x11_mouse_grab", "false"), ("x11_mouse_hide", "true")] | conditional_block |
inputMgr.py | # ========================== Start Copyright Notice ========================== #
# #
# Copyright 2014 F.D.I.S. #
# This file is part of Kinetic Gunner: Gunner of Angst ... | class InputMgr(OIS.KeyListener, OIS.MouseListener, OIS.JoyStickListener):
''' Manages keyboard and mouse, with buffered and unbuffered input. '''
def __init__(self, engine):
''' Creates Input Listeners and Initializes Variables. '''
self.engine = engine
OIS.KeyListener.__init__(self... | random_line_split | |
inputMgr.py | # ========================== Start Copyright Notice ========================== #
# #
# Copyright 2014 F.D.I.S. #
# This file is part of Kinetic Gunner: Gunner of Angst ... | (self, evt, axis):
return True
def windowResized (self, rw):
temp = 0
width, height, depth, left, top= rw.getMetrics(temp,temp,temp, temp, temp) # Note the wrapped function as default needs unsigned int's
ms = self.mouse.getMouseState()
ms.width = width
ms.height = ... | axisMoved | identifier_name |
Header.tsx | import { useRef, useEffect, useState } from 'react'
import NextLink from 'next/link'
import {
Box,
chakra,
Flex,
HTMLChakraProps,
useDisclosure, | import { Logo, LogoIcon } from '@components/Logo'
import { SponsorButton } from '@components/SponsorButton'
import { MobileNavButton, MobileNavContent } from '@components/MobileNav'
import { HeaderIconButtons } from '@components/HeaderIconButtons'
function HeaderContent () {
const mobileNav = useDisclosure()
const... | useUpdateEffect,
useColorModeValue
} from '@chakra-ui/react'
import { useViewportScroll } from 'framer-motion'
| random_line_split |
role.js | /**
Role:
title -> String (required)
owner -> User_id (required) //this has to be an admin or developer??
users -> List of User_ids
* Prerequisite: - only users with admin, or developer roles can create other roles
* - admin and developer roles come as default
* - normal users do'... | (title, owner, description) {
this.title = title;
this.owner = owner;
this.description = description;
this.users = [];
}
Role.prototype = {
get : function Group_get(key){
return this[key];
},
set : function Group_set(key, value){
//only allow defined properties to be ... | Role | identifier_name |
role.js | /**
Role:
title -> String (required)
owner -> User_id (required) //this has to be an admin or developer??
users -> List of User_ids
* Prerequisite: - only users with admin, or developer roles can create other roles
* - admin and developer roles come as default
* - normal users do'... |
Role.prototype = {
get : function Group_get(key){
return this[key];
},
set : function Group_set(key, value){
//only allow defined properties to be set
if((typeof value === "object") && (key === "users")){
this[key] = value;
}else if(typeof value === "string" && (key === "... | {
this.title = title;
this.owner = owner;
this.description = description;
this.users = [];
} | identifier_body |
role.js | /**
Role:
title -> String (required)
owner -> User_id (required) //this has to be an admin or developer??
users -> List of User_ids
* Prerequisite: - only users with admin, or developer roles can create other roles
* - admin and developer roles come as default
* - normal users do'... |
//do nothing
},
addUser: function Group_addUser(userObject) {
var roleObject = this;
throw new NotImplementedException();
},
deleteRole: function Role_delete() {
return null;
},
saveRole: function Role_save() {
var roleObject = this;
var role = {title: this... | {
this[key] = value;
} | conditional_block |
role.js | /**
Role:
title -> String (required)
owner -> User_id (required) //this has to be an admin or developer??
users -> List of User_ids | */
Role = (function RoleClosure() {
function Role(title, owner, description) {
this.title = title;
this.owner = owner;
this.description = description;
this.users = [];
}
Role.prototype = {
get : function Group_get(key){
return this[key];
},
set : function Group_set(key,... |
* Prerequisite: - only users with admin, or developer roles can create other roles
* - admin and developer roles come as default
* - normal users do'n have any roles | random_line_split |
home_action.py | #------------------------------------------------------------------------------
# Copyright (C) 2009 Richard W. Lincoln
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restrictio... | image = ImageResource("home_folder", search_path=[IMAGE_LOCATION])
#--------------------------------------------------------------------------
# "UpAction" interface:
#--------------------------------------------------------------------------
window = Instance(WorkbenchWindow)
#-------------... | """ An action for moving the workspace to the user's home directory.
"""
#--------------------------------------------------------------------------
# "Action" interface:
#--------------------------------------------------------------------------
# A longer description of the action:
descript... | identifier_body |
home_action.py | #------------------------------------------------------------------------------
# Copyright (C) 2009 Richard W. Lincoln
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restrictio... | view.tree_viewer.refresh(workspace)
# EOF ------------------------------------------------------------------------- | random_line_split | |
home_action.py | #------------------------------------------------------------------------------
# Copyright (C) 2009 Richard W. Lincoln
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restrictio... |
# EOF -------------------------------------------------------------------------
| view.tree_viewer.refresh(workspace) | conditional_block |
home_action.py | #------------------------------------------------------------------------------
# Copyright (C) 2009 Richard W. Lincoln
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restrictio... | (self, event):
""" Perform the action.
"""
# Note that we always offer the service via its name, but look it up
# via the actual protocol.
from puddle.resource.i_workspace import IWorkspace
workspace = self.window.application.get_service(IWorkspace)
workspace.pat... | perform | identifier_name |
331_srtp_prefer_rtp_avp.py | # $Id: 331_srtp_prefer_rtp_avp.py 2081 2008-06-27 21:59:15Z bennylp $
import inc_sip as sip
import inc_sdp as sdp
# When SRTP is NOT enabled in pjsua, it should prefer to use
# RTP/AVP media line if there are multiple m=audio lines
sdp = \
""" | v=0
o=- 0 0 IN IP4 127.0.0.1
s=-
c=IN IP4 127.0.0.1
t=0 0
m=audio 5000 RTP/SAVP 0
a=crypto:1 aes_cm_128_hmac_sha1_80 inline:WnD7c1ksDGs+dIefCEo8omPg4uO8DYIinNGL5yxQ
m=audio 4000 RTP/AVP 0
"""
pjsua_args = "--null-audio --auto-answer 200 --use-srtp 0"
extra_headers = ""
include = ["Content-Type: application/sdp", # res... | random_line_split | |
string_to_hash_bucket_op_test.py | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | test.main() | conditional_block | |
string_to_hash_bucket_op_test.py | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | (self):
with self.test_session():
input_string = constant_op.constant(['a', 'b', 'c'])
output = string_ops.string_to_hash_bucket_strong(
input_string, 1, key=[123, 345])
self.assertAllEqual([0, 0, 0], output.eval())
def testStringToHashBucketsStrong(self):
with self.test_session()... | testStringToOneHashBucketStrongOneHashBucket | identifier_name |
string_to_hash_bucket_op_test.py | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
def testStringToHashBucketsFast(self):
with self.test_session():
input_string = array_ops.placeholder(dtypes.string)
output = string_ops.string_to_hash_bucket_fast(input_string, 10)
result = output.eval(feed_dict={input_string: ['a', 'b', 'c', 'd']})
# Fingerprint64('a') -> 129178041108... | with self.test_session():
input_string = array_ops.placeholder(dtypes.string)
output = string_ops.string_to_hash_bucket_fast(input_string, 1)
result = output.eval(feed_dict={input_string: ['a', 'b', 'c']})
self.assertAllEqual([0, 0, 0], result) | identifier_body |
string_to_hash_bucket_op_test.py | # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
def testStringToHashBucketsStrongInvalidKey(self):
with self.test_session():
input_string = constant_op.constant(['a', 'b', 'c'])
with self.assertRaisesOpError('Key must have 2 elements'):
string_ops.string_to_hash_bucket_strong(
input_string, 10, key=[98765]).eval()
if __name__... | self.assertAllEqual([4, 2, 8], output.eval()) | random_line_split |
notification.ts | /**
* quantimodo
* We make it easy to retrieve and analyze normalized user data from a wide array of devices and applications. Check out our [docs and sdk's](https://github.com/QuantiModo/docs) or [contact us](https://help.quantimo.do).
*
* OpenAPI spec version: 5.8.112511
*
*
* NOTE: This class is auto generat... | */
id: number;
/**
* What do you expect?
*/
userId: number;
/**
* What do you expect?
*/
itemId: number;
/**
* What do you expect?
*/
secondaryItemId: number;
/**
* What do you expect?
*/
componentName: string;
/**
* What do you e... |
export interface Notification {
/**
* What do you expect? | random_line_split |
glyphMargin.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | (): void {
this._context.removeEventHandler(this);
this._context = null;
this._renderResult = null;
}
// --- begin event handlers
public onConfigurationChanged(e: viewEvents.ViewConfigurationChangedEvent): boolean {
if (e.lineHeight) {
this._lineHeight = this._context.configuration.editor.lineHeight;
... | dispose | identifier_name |
glyphMargin.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | else {
prevClassName = className;
prevEndLineIndex = endLineIndex;
}
for (let i = startLineIndex; i <= prevEndLineIndex; i++) {
output[i].push(prevClassName);
}
}
return output;
}
}
export class GlyphMarginOverlay extends DedupOverlay {
private _context: ViewContext;
private _lineHeight... | {
startLineIndex = Math.max(prevEndLineIndex + 1, startLineIndex);
prevEndLineIndex = Math.max(prevEndLineIndex, endLineIndex);
} | conditional_block |
glyphMargin.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
public onScrollChanged(e: viewEvents.ViewScrollChangedEvent): boolean {
return e.scrollTopChanged;
}
public onZonesChanged(e: viewEvents.ViewZonesChangedEvent): boolean {
return true;
}
// --- end event handlers
protected _getDecorations(ctx: RenderingContext): DecorationToRender[] {
let decorations = ct... | {
return false;
} | identifier_body |
glyphMargin.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | }
public onDecorationsChanged(e: viewEvents.ViewDecorationsChangedEvent): boolean {
return true;
}
public onFlushed(e: viewEvents.ViewFlushedEvent): boolean {
return true;
}
public onLinesChanged(e: viewEvents.ViewLinesChangedEvent): boolean {
return true;
}
public onLinesDeleted(e: viewEvents.ViewLinesDe... | public onCursorPositionChanged(e: viewEvents.ViewCursorPositionChangedEvent): boolean {
return false;
}
public onCursorSelectionChanged(e: viewEvents.ViewCursorSelectionChangedEvent): boolean {
return false; | random_line_split |
index.js | /*
* nodekit.io
* | * 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 writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT W... | * Copyright (c) 2016 OffGrid Networks. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); | random_line_split |
index.js | /*
* nodekit.io
*
* Copyright (c) 2016 OffGrid Networks. 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
*
... | else {
response.writeHead(200, { 'Content-Type': 'text/html' });
response.end(content, 'utf-8');
}
});
... | {
console.log(err);
response.writeHead(500, { 'Content-Type': 'text/html' });
response.end('<html><body>An internal server error occurred</body>', 'utf-8');
... | conditional_block |
ExplosionTemplate.ts | module example.templates {
import Point = PIXI.Point;
import Container = PIXI.Container;
import Position = example.components.Position;
import Sprite = example.components.Sprite;
import Velocity = example.components.Velocity;
import Bounds = example.components.Bounds;
import Player = example.components.... | (entity:artemis.Entity, world:artemis.World, x:number, y:number):artemis.Entity {
super.buildEntity(entity, world, x, y, 0.5);
var sf:SoundEffect = new SoundEffect();
sf.effect = EFFECT.ASPLODE;
entity.addComponent(sf);
return entity;
}
}
} | buildEntity | identifier_name |
ExplosionTemplate.ts | module example.templates {
import Point = PIXI.Point;
import Container = PIXI.Container;
import Position = example.components.Position;
import Sprite = example.components.Sprite;
import Velocity = example.components.Velocity;
import Bounds = example.components.Bounds;
import Player = example.components.... |
}
}
/**
* Big Explosion
*/
@EntityTemplate('big')
export class BigExplosionTemplate extends ExplosionTemplate {
public buildEntity(entity:artemis.Entity, world:artemis.World, x:number, y:number):artemis.Entity {
super.buildEntity(entity, world, x, y, 0.5);
var sf:SoundEffect = new ... | random_line_split | |
vscode-mock.ts | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
'use strict';
import * as TypeMoq from 'typemoq';
import * as vscode from 'vscode';
import * as vscodeMocks from './mocks/vsc';
import { vscMockTelemetryReporter } from './mocks/vsc/telemetryReporter';
const Module = requi... |
public async writeText(value: string): Promise<void> {
this.text = value;
}
}
export function initialize() {
generateMock('workspace');
generateMock('window');
generateMock('commands');
generateMock('languages');
generateMock('env');
generateMock('debug');
generateMock('scm'... | {
return Promise.resolve(this.text);
} | identifier_body |
vscode-mock.ts | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
'use strict';
import * as TypeMoq from 'typemoq';
import * as vscode from 'vscode';
import * as vscodeMocks from './mocks/vsc';
import { vscMockTelemetryReporter } from './mocks/vsc/telemetryReporter';
const Module = requi... | mockedVSCode.Diagnostic = vscodeMocks.vscMockExtHostedTypes.Diagnostic;
mockedVSCode.DiagnosticSeverity = vscodeMocks.vscMockExtHostedTypes.DiagnosticSeverity;
mockedVSCode.SnippetString = vscodeMocks.vscMockExtHostedTypes.SnippetString;
mockedVSCode.ConfigurationTarget = vscodeMocks.vscMockExtHostedTypes.Configuration... | random_line_split | |
vscode-mock.ts | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
'use strict';
import * as TypeMoq from 'typemoq';
import * as vscode from 'vscode';
import * as vscodeMocks from './mocks/vsc';
import { vscMockTelemetryReporter } from './mocks/vsc/telemetryReporter';
const Module = requi... |
// less files need to be in import statements to be converted to css
// But we don't want to try to load them in the mock vscode
if (/\.less$/.test(request)) {
return;
}
return originalLoad.apply(this, arguments);
};
}
mockedVSCode.MarkdownString = vscodeMocks.M... | {
return { default: vscMockTelemetryReporter as any };
} | conditional_block |
vscode-mock.ts | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
'use strict';
import * as TypeMoq from 'typemoq';
import * as vscode from 'vscode';
import * as vscodeMocks from './mocks/vsc';
import { vscMockTelemetryReporter } from './mocks/vsc/telemetryReporter';
const Module = requi... | {
private text: string = '';
public readText(): Promise<string> {
return Promise.resolve(this.text);
}
public async writeText(value: string): Promise<void> {
this.text = value;
}
}
export function initialize() {
generateMock('workspace');
generateMock('window');
generate... | MockClipboard | identifier_name |
image.js | define(function (require) {
'use strict';
var p5 = require('core');
var frames = [];
/**
* Save the current canvas as an image. In Safari, will open the
* image in the window and the user must provide their own
* filename on save-as. Other browsers will either save the
* file immediately, or ... |
p5.prototype._makeFrame = function(filename, extension, _cnv) {
var cnv;
if (this) {
cnv = this._curElement.elt;
} else {
cnv = _cnv;
}
var mimeType;
if (!extension) {
extension = 'png';
mimeType = 'image/png';
}
else {
switch(extension.toLowerCase()){
... | }
}
frames = []; // clear frames
}, duration + 0.01);
}; | random_line_split |
image.js | define(function (require) {
'use strict';
var p5 = require('core');
var frames = [];
/**
* Save the current canvas as an image. In Safari, will open the
* image in the window and the user must provide their own
* filename on save-as. Other browsers will either save the
* file immediately, or ... |
var downloadMime = 'image/octet-stream';
var imageData = cnv.toDataURL(mimeType);
imageData = imageData.replace(mimeType, downloadMime);
p5.prototype.downloadFile(imageData, filename, extension);
}
};
/**
* Capture a sequence of frames that can be used to create a movie.
* Acc... | {
switch(extension){
case 'png':
mimeType = 'image/png';
break;
case 'jpeg':
mimeType = 'image/jpeg';
break;
case 'jpg':
mimeType = 'image/jpeg';
break;
default:
mimeType = 'image/png';
break;
... | conditional_block |
freebsd.py | # This file is part of Ansible
#
# Ansible 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 later version.
#
# Ansible is distributed in the hope that ... | continue
fields = re.sub(r'\s+', ' ', line).split()
size_total, size_available = get_mount_size(fields[1])
mount_facts['mounts'].append({
'mount': fields[1],
'device': fields[0],
'fstype': fie... | random_line_split | |
freebsd.py | # This file is part of Ansible
#
# Ansible 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 later version.
#
# Ansible is distributed in the hope that ... |
s = slices.match(device)
if s:
device_facts['devices'][d.group(1)].append(s.group(1))
return device_facts
def get_dmi_facts(self):
''' learn dmi facts from system
Use dmidecode executable if available'''
dmi_facts = {}
... | device_facts['devices'][d.group(1)] = [] | conditional_block |
freebsd.py | # This file is part of Ansible
#
# Ansible 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 later version.
#
# Ansible is distributed in the hope that ... | device_facts = self.get_device_facts()
mount_facts = {}
try:
mount_facts = self.get_mount_facts()
except TimeoutError:
pass
hardware_facts.update(cpu_facts)
hardware_facts.update(memory_facts)
hardware_facts.update(dmi_facts)
hard... | """
FreeBSD-specific subclass of Hardware. Defines memory and CPU facts:
- memfree_mb
- memtotal_mb
- swapfree_mb
- swaptotal_mb
- processor (a list)
- processor_cores
- processor_count
- devices
"""
platform = 'FreeBSD'
DMESG_BOOT = '/var/run/dmesg.boot'
def popula... | identifier_body |
freebsd.py | # This file is part of Ansible
#
# Ansible 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 later version.
#
# Ansible is distributed in the hope that ... | (self):
''' learn dmi facts from system
Use dmidecode executable if available'''
dmi_facts = {}
# Fall back to using dmidecode, if available
dmi_bin = self.module.get_bin_path('dmidecode')
DMI_DICT = dict(
bios_date='bios-release-date',
bios_ver... | get_dmi_facts | identifier_name |
luci_auth.py | # Copyright 2018 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.
import re
import subprocess
import sys
import six
_RE_INFO_USER_EMAIL = r'Logged in as (?P<email>\S+)\.$'
class AuthorizationError(Exception):
pass
d... | """
try:
GetAccessToken()
except AuthorizationError as exc:
sys.exit(str(exc))
def GetAccessToken():
"""Get an access token to make requests on behalf of the logged in user."""
return _RunCommand('token').rstrip()
def GetUserEmail():
"""Get the email address of the currently logged in user."""
... | random_line_split | |
luci_auth.py | # Copyright 2018 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.
import re
import subprocess
import sys
import six
_RE_INFO_USER_EMAIL = r'Logged in as (?P<email>\S+)\.$'
class AuthorizationError(Exception):
pass
d... | """Get the email address of the currently logged in user."""
output = _RunCommand('info')
m = re.match(_RE_INFO_USER_EMAIL, output, re.MULTILINE)
assert m, 'Failed to parse luci-auth info output.'
return m.group('email') | identifier_body | |
luci_auth.py | # Copyright 2018 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.
import re
import subprocess
import sys
import six
_RE_INFO_USER_EMAIL = r'Logged in as (?P<email>\S+)\.$'
class AuthorizationError(Exception):
pass
d... | ():
"""Get an access token to make requests on behalf of the logged in user."""
return _RunCommand('token').rstrip()
def GetUserEmail():
"""Get the email address of the currently logged in user."""
output = _RunCommand('info')
m = re.match(_RE_INFO_USER_EMAIL, output, re.MULTILINE)
assert m, 'Failed to pa... | GetAccessToken | identifier_name |
keyboard.rs | #[cfg(not(any(test, rustdoc)))]
use alloc::prelude::v1::*;
#[cfg(any(test, rustdoc))]
use std::prelude::v1::*;
use crate::event::Event;
use crate::util::UnsafeContainer;
use crate::KERNEL_EVENTEMITTER;
#[derive(Debug)]
pub enum SpecialKey {
Enter,
}
#[derive(Debug)]
pub enum KeyCode {
Unicode(char),
Spec... | }
lazy_static! {
pub static ref KEYBOARD_HANDLER: UnsafeContainer<KeyboardHandler> =
UnsafeContainer::new(KeyboardHandler::new());
}
#[cfg(all(target_os = "polymorphos", target_arch = "x86_64"))]
pub fn kbd_write_to_screen(c: char) {
vga_print!("{}", c);
}
#[cfg(test)]
pub fn kbd_write_to_screen(c: c... | }
} | random_line_split |
keyboard.rs | #[cfg(not(any(test, rustdoc)))]
use alloc::prelude::v1::*;
#[cfg(any(test, rustdoc))]
use std::prelude::v1::*;
use crate::event::Event;
use crate::util::UnsafeContainer;
use crate::KERNEL_EVENTEMITTER;
#[derive(Debug)]
pub enum SpecialKey {
Enter,
}
#[derive(Debug)]
pub enum KeyCode {
Unicode(char),
Spec... | {
KEYBOARD_HANDLER.get().process();
} | identifier_body | |
keyboard.rs | #[cfg(not(any(test, rustdoc)))]
use alloc::prelude::v1::*;
#[cfg(any(test, rustdoc))]
use std::prelude::v1::*;
use crate::event::Event;
use crate::util::UnsafeContainer;
use crate::KERNEL_EVENTEMITTER;
#[derive(Debug)]
pub enum SpecialKey {
Enter,
}
#[derive(Debug)]
pub enum KeyCode {
Unicode(char),
Spec... |
KeyCode::SpecialKey(sp) => match sp {
SpecialKey::Enter => {
kbd_write_to_screen('\n');
let ev = Event::new("console", "input", "keypress", vec!['\n' as u32]);
KERNEL_EVENTEMITTER.get().push_event(ev);
... | {
kbd_write_to_screen(c);
let ev = Event::new("console", "input", "keypress", vec![c as u32]);
KERNEL_EVENTEMITTER.get().push_event(ev);
} | conditional_block |
keyboard.rs | #[cfg(not(any(test, rustdoc)))]
use alloc::prelude::v1::*;
#[cfg(any(test, rustdoc))]
use std::prelude::v1::*;
use crate::event::Event;
use crate::util::UnsafeContainer;
use crate::KERNEL_EVENTEMITTER;
#[derive(Debug)]
pub enum SpecialKey {
Enter,
}
#[derive(Debug)]
pub enum KeyCode {
Unicode(char),
Spec... | () {
KEYBOARD_HANDLER.get().process();
}
| process_keyboard | identifier_name |
mainCtrl.js | var myApp = angular.module('myApp', []);
myApp.controller('AppCtrl', ['$scope', '$http', function($scope, $http) {
//set 'this' to the variable self
var self = this;
//is set to true when editing a contact
self.editModeActive = false;
//get data from server
$http.get("/contactList")
.then(function(dataRe... | }
});
//turn off edit mode
self.editModeActive = false;
});
}
//switch contact to edit mode
self.editContact = function(contact){
console.log("contact ", contact);
self.editModeActive = true;
self.contact = {
name : contact.name,
email : contact.ema... | //splice out the old one and put in the new
self.contactList.map(function(item,index){
if(item._id === response._id){
self.contactList.splice(index, 1, response); | random_line_split |
mainCtrl.js | var myApp = angular.module('myApp', []);
myApp.controller('AppCtrl', ['$scope', '$http', function($scope, $http) {
//set 'this' to the variable self
var self = this;
//is set to true when editing a contact
self.editModeActive = false;
//get data from server
$http.get("/contactList")
.then(function(dataRe... |
})
self.contactList = updatedArray;
//make this more efficient with splice method or sumn
});
}
//update existing people in db
self.updateContact = function(contact){
console.log("contact to update is ", contact);
console.log("contact id is ", contact.id);
//send c... | {
updatedArray.push(item)
} | conditional_block |
testSceneList.py | #!/usr/bin/python
import sys
sys.path.append("../../")
#import pyRay as ra
import pyRay.scene as scn
# TODO : how to pass arguments from function header?
object1 = ("obj1",(), [( "U","sdBox" ,"%s",((1.0,1.0,1.0),) ),( "S","sdSphere","%s",(1.2,) )])
object2 = ("obj1",("f","f3"),[( "U","sdBox" ,"%s",(... | ( "S","sdSphere","%s",(1.2,) ),
]
scene_src = scn.parseSceneList(scene)
print scene_src |
scene = [
( "U","sdBox" ,"%s",((1.0,1.0,1.0),) ), | random_line_split |
builtin.rs | // Copyright 2015, 2016 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 la... | }
struct BuiltinDapp<T: WebApp + 'static> {
app: Arc<T>,
}
impl<T: WebApp + 'static> BuiltinDapp<T> {
fn new(app: Arc<T>) -> Self {
BuiltinDapp {
app: app,
}
}
}
impl<T: WebApp + 'static> handler::Dapp for BuiltinDapp<T> {
type DappFile = BuiltinDappFile<T>;
fn file(&self, path: &str) -> Option<Self::Da... | author: info.author.into(),
icon_url: info.icon_url.into(),
version: info.version.into(),
}
} | random_line_split |
builtin.rs | // Copyright 2015, 2016 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 la... | (&self) -> &File {
self.app.file(&self.path).expect("Check is done when structure is created.")
}
}
impl<T: WebApp + 'static> handler::DappFile for BuiltinDappFile<T> {
fn content_type(&self) -> &str {
self.file().content_type
}
fn is_drained(&self) -> bool {
self.write_pos == self.file().content.len()
}
... | file | identifier_name |
builtin.rs | // Copyright 2015, 2016 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 la... |
fn bytes_written(&mut self, bytes: usize) {
self.write_pos += bytes;
}
}
| {
&self.file().content[self.write_pos..]
} | identifier_body |
connectivity.test.ts | import Client from '@bugsnag/core/client'
import _NetInfo, { NetInfoState } from '@react-native-community/netinfo'
import plugin from '../'
jest.mock('@react-native-community/netinfo', () => ({
addEventListener: jest.fn()
}))
const NetInfo = _NetInfo as jest.Mocked<typeof _NetInfo>
describe('plugin: react native c... | expect(client._breadcrumbs[1].message).toBe('Connectivity changed')
expect(client._breadcrumbs[1].metadata).toEqual({ type: 'none', isConnected: false, isInternetReachable: false })
})
it('should be enabled when enabledBreadcrumbTypes=null', () => {
const client = new Client({ apiKey: 'aaaa-aaaa-aaaa-a... | random_line_split | |
table6.py | from parameter import *
from parse_digit import *
from os import system
cmd = "make -C tools >/dev/null 2>/dev/null;mkdir log model 2>/dev/null"
system(cmd)
#remove those method/data you are not interested in its result
methodlist = ['random-forest','gbdt']
data = ['MQ2007','MQ2008','MSLR','YAHOO_SET1','YAHOO_SET2',... | if '(YAHOO)' in l:
ndcg = l.split(' ')[-2].strip()
digit = "$%1.4f$"%float(ndcg)
o.append(digit)
else:
if 'Mean' in l:
if d == 'MQ2007-list' or d == 'MQ2008-list':
digit = "NA"
else:
ndcg = l.split(' ')[-2].strip()
digit = "$%1.4f$"%float(ndcg)
o.append(digit... | random_line_split | |
table6.py | from parameter import *
from parse_digit import *
from os import system
cmd = "make -C tools >/dev/null 2>/dev/null;mkdir log model 2>/dev/null"
system(cmd)
#remove those method/data you are not interested in its result
methodlist = ['random-forest','gbdt']
data = ['MQ2007','MQ2008','MSLR','YAHOO_SET1','YAHOO_SET2',... |
else:
if 'Mean' in l:
if d == 'MQ2007-list' or d == 'MQ2008-list':
digit = "NA"
else:
ndcg = l.split(' ')[-2].strip()
digit = "$%1.4f$"%float(ndcg)
o.append(digit)
print output_name[d],
for l in o:
print "& %s "%l,
print "\\\\"
print "\\end{tabular}"
| if '(YAHOO)' in l:
ndcg = l.split(' ')[-2].strip()
digit = "$%1.4f$"%float(ndcg)
o.append(digit) | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.