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 |
|---|---|---|---|---|
index.tsx | import "babel-polyfill";
import "isomorphic-fetch";
import * as injectTapEventPlugin from "react-tap-event-plugin";
injectTapEventPlugin();
import "@accounts/react-material-ui";
import thunk from "redux-thunk";
import { bootstrap } from "@redux-bootstrap/bootstrap";
import { createLogger } from "redux-logger... |
if (process.env.NODE_ENV !== "production") {
middleware.push(createLogger({level: "log"}));
//middleware.push(immutableStateInvariant());
}
let preloadedState: any = null;
if (typeof __PRELOADED_STATE__ === 'undefined') {
// use state from server side
preloadedState = loadState();
} else {... |
declare var __PRELOADED_STATE__: any;
let middleware: any[] = [thunk];
| random_line_split |
_fetch.py | """
RPC / REST client implementation module
"""
import re
import requests
from twentyc.rpc import RestClient
from twentyc.rpc.client import (
InvalidRequestException,
NotFoundException,
PermissionDeniedException,
)
import peeringdb
class CompatibilityError(Exception):
pass
class Fetcher(RestClient... | for k, v in params.items()
}
return self._req(lambda: self.all(R.tag, depth=depth, **params))
def fetch_all_latest(self, R, depth, params={}, since=None):
backend = peeringdb.get_backend()
if since is None:
since = backend.last_change(backend.get_concrete(R)... | def fetch_all(self, R, depth, params={}):
params = {
k: ",".join(map(str, v)) if isinstance(v, (list, tuple)) else v | random_line_split |
_fetch.py | """
RPC / REST client implementation module
"""
import re
import requests
from twentyc.rpc import RestClient
from twentyc.rpc.client import (
InvalidRequestException,
NotFoundException,
PermissionDeniedException,
)
import peeringdb
class CompatibilityError(Exception):
pass
class Fetcher(RestClient... |
return requests.request(
method, url, params=params, data=data, auth=auth, headers=headers
)
| if id:
url = "{}/{}/{}".format(self.url, typ, id)
else:
url = "{}/{}".format(self.url, typ) | conditional_block |
_fetch.py | """
RPC / REST client implementation module
"""
import re
import requests
from twentyc.rpc import RestClient
from twentyc.rpc.client import (
InvalidRequestException,
NotFoundException,
PermissionDeniedException,
)
import peeringdb
class CompatibilityError(Exception):
pass
class Fetcher(RestClient... |
def fetch_all_latest(self, R, depth, params={}, since=None):
backend = peeringdb.get_backend()
if since is None:
since = backend.last_change(backend.get_concrete(R))
if since:
since = since + 1
params = {
k: ",".join(map(str, v)) if isinstance(... | params = {
k: ",".join(map(str, v)) if isinstance(v, (list, tuple)) else v
for k, v in params.items()
}
return self._req(lambda: self.all(R.tag, depth=depth, **params)) | identifier_body |
_fetch.py | """
RPC / REST client implementation module
"""
import re
import requests
from twentyc.rpc import RestClient
from twentyc.rpc.client import (
InvalidRequestException,
NotFoundException,
PermissionDeniedException,
)
import peeringdb
class CompatibilityError(Exception):
pass
class Fetcher(RestClient... | (self, R, pk, depth):
return self._req(lambda: self.get(R.tag, pk, depth=depth))
def fetch_latest(self, R, pk, depth, since=None):
backend = peeringdb.get_backend()
if since is None:
since = backend.last_change(backend.get_concrete(R))
if since:
since = since... | fetch | identifier_name |
0002_auto_20160403_1645.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2016-04-03 16:45
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('player', '0001_initial'),
]
operations = [
... | migrations.AddField(
model_name='playerfeedback',
name='to_player',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='to_player', to='player.Player'),
),
] | field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='owner', to='player.Player'),
), | random_line_split |
0002_auto_20160403_1645.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2016-04-03 16:45
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class | (migrations.Migration):
dependencies = [
('player', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='PlayerFeedback',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
... | Migration | identifier_name |
0002_auto_20160403_1645.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2016-04-03 16:45
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
| field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.Faction'),
),
migrations.AlterField(
model_name='race',
name='game',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.Game'),
),
migr... | dependencies = [
('player', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='PlayerFeedback',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('message', models.Tex... | identifier_body |
changeDetectionService.ts |
import {Column} from "../entities/column";
import {RowNode} from "../entities/rowNode";
import {Autowired, Bean, PostConstruct} from "../context/context";
import {GridOptionsWrapper} from "../gridOptionsWrapper";
import {ChangedPath} from "../rowModels/inMemory/changedPath";
import {IRowModel} from "../interfaces/iRow... |
// step 2 of change detection is to refresh the cells
this.rowRenderer.refreshCells();
}
} | {
let changedPath: ChangedPath;
if (rowNode.parent) {
let onlyChangedColumns = this.gridOptionsWrapper.isAggregateOnlyChangedColumns();
changedPath = new ChangedPath(onlyChangedColumns);
changedPath.addParentNode(rowNode.parent, [column]);
... | conditional_block |
changeDetectionService.ts |
import {Column} from "../entities/column";
import {RowNode} from "../entities/rowNode";
import {Autowired, Bean, PostConstruct} from "../context/context";
import {GridOptionsWrapper} from "../gridOptionsWrapper";
import {ChangedPath} from "../rowModels/inMemory/changedPath";
import {IRowModel} from "../interfaces/iRow... | (): void {
if (this.rowModel.getType()===Constants.ROW_MODEL_TYPE_IN_MEMORY) {
this.inMemoryRowModel = <InMemoryRowModel> this.rowModel;
}
this.addDestroyableEventListener(this.eventService, Events.EVENT_CELL_VALUE_CHANGED, this.onCellValueChanged.bind(this));
}
private onC... | init | identifier_name |
changeDetectionService.ts |
import {Column} from "../entities/column";
import {RowNode} from "../entities/rowNode";
import {Autowired, Bean, PostConstruct} from "../context/context";
import {GridOptionsWrapper} from "../gridOptionsWrapper";
import {ChangedPath} from "../rowModels/inMemory/changedPath";
import {IRowModel} from "../interfaces/iRow... |
private onCellValueChanged(event: any): void {
this.doChangeDetection(event.node, event.column);
}
private doChangeDetection(rowNode: RowNode, column: Column): void {
if (this.gridOptionsWrapper.isSuppressChangeDetection()) { return; }
// step 1 of change detection is to update t... | {
if (this.rowModel.getType()===Constants.ROW_MODEL_TYPE_IN_MEMORY) {
this.inMemoryRowModel = <InMemoryRowModel> this.rowModel;
}
this.addDestroyableEventListener(this.eventService, Events.EVENT_CELL_VALUE_CHANGED, this.onCellValueChanged.bind(this));
} | identifier_body |
changeDetectionService.ts | import {Column} from "../entities/column";
import {RowNode} from "../entities/rowNode";
import {Autowired, Bean, PostConstruct} from "../context/context";
import {GridOptionsWrapper} from "../gridOptionsWrapper";
import {ChangedPath} from "../rowModels/inMemory/changedPath";
import {IRowModel} from "../interfaces/iRowM... | }
this.addDestroyableEventListener(this.eventService, Events.EVENT_CELL_VALUE_CHANGED, this.onCellValueChanged.bind(this));
}
private onCellValueChanged(event: any): void {
this.doChangeDetection(event.node, event.column);
}
private doChangeDetection(rowNode: RowNode, column: ... |
@PostConstruct
private init(): void {
if (this.rowModel.getType()===Constants.ROW_MODEL_TYPE_IN_MEMORY) {
this.inMemoryRowModel = <InMemoryRowModel> this.rowModel; | random_line_split |
invert.py | # Invert gray image
import cv2
from . import print_image
from . import plot_image
def | (img, device, debug=None):
"""Inverts grayscale images.
Inputs:
img = image object, grayscale
device = device number. Used to count steps in the pipeline
debug = None, print, or plot. Print = save to file, Plot = print to screen.
Returns:
device = device number
img_inv = invert... | invert | identifier_name |
invert.py | # Invert gray image
import cv2
from . import print_image
from . import plot_image
def invert(img, device, debug=None):
| if debug == 'print':
print_image(img_inv, (str(device) + '_invert.png'))
elif debug == 'plot':
plot_image(img_inv, cmap='gray')
return device, img_inv
| """Inverts grayscale images.
Inputs:
img = image object, grayscale
device = device number. Used to count steps in the pipeline
debug = None, print, or plot. Print = save to file, Plot = print to screen.
Returns:
device = device number
img_inv = inverted image
:param img: numpy... | identifier_body |
invert.py | # Invert gray image
import cv2
from . import print_image
from . import plot_image
def invert(img, device, debug=None):
"""Inverts grayscale images.
Inputs:
img = image object, grayscale
device = device number. Used to count steps in the pipeline
debug = None, print, or plot. Print = save ... |
return device, img_inv
| plot_image(img_inv, cmap='gray') | conditional_block |
invert.py | # Invert gray image
import cv2
from . import print_image
from . import plot_image
def invert(img, device, debug=None):
"""Inverts grayscale images.
Inputs:
img = image object, grayscale
device = device number. Used to count steps in the pipeline
debug = None, print, or plot. Print = save ... | :param img: numpy array
:param device: int
:param debug: str
:return device: int
:return img_inv: numpy array
"""
device += 1
img_inv = cv2.bitwise_not(img)
if debug == 'print':
print_image(img_inv, (str(device) + '_invert.png'))
elif debug == 'plot':
plot_image(... | img_inv = inverted image
| random_line_split |
main.rs | extern crate typed_arena;
use typed_arena::Arena;
fn | () {
// Memory is allocated using the default allocator (currently jemalloc). The memory is
// allocated in chunks, and when one chunk is full another is allocated. This ensures that
// references to an arena don't become invalid when the original chunk runs out of space. The
// chunk size is configu... | main | identifier_name |
main.rs | extern crate typed_arena;
use typed_arena::Arena;
fn main() {
// Memory is allocated using the default allocator (currently jemalloc). The memory is
// allocated in chunks, and when one chunk is full another is allocated. This ensures that
// references to an arena don't become invalid when the original... | // TypedArena returns a mutable reference
let v2 = arena.alloc(3);
*v2 += 38;
println!("{}", *v1 + *v2);
// The arena's destructor is called as it goes out of scope, at which point it deallocates
// everything stored within it at once.
} | // can allocate only objects of one type. The type is determined by type inference--if you try
// to allocate an integer, then Rust's compiler knows it is an integer arena.
let v1 = arena.alloc(1i32);
| random_line_split |
main.rs | extern crate typed_arena;
use typed_arena::Arena;
fn main() | {
// Memory is allocated using the default allocator (currently jemalloc). The memory is
// allocated in chunks, and when one chunk is full another is allocated. This ensures that
// references to an arena don't become invalid when the original chunk runs out of space. The
// chunk size is configurab... | identifier_body | |
lib.rs | //! A wonderful, fast, safe, generic radix trie implementation.
//!
//! To get started, see the docs for `Trie` below.
// #![warn(missing_docs)]
extern crate nibble_vec;
extern crate endian_type;
#[cfg(test)]
extern crate quickcheck;
#[cfg(test)]
extern crate rand; | #[macro_use]
mod macros;
mod keys;
pub mod iter;
mod traversal;
mod trie;
mod subtrie;
mod trie_node;
mod trie_common;
#[cfg(feature = "serde")]
mod serde;
#[cfg(test)]
mod test;
#[cfg(test)]
mod qc_test;
const BRANCH_FACTOR: usize = 16;
/// Data-structure for storing and querying string-like keys and associated val... |
pub use nibble_vec::NibbleVec;
pub use keys::TrieKey;
pub use trie_common::TrieCommon;
| random_line_split |
lib.rs | //! A wonderful, fast, safe, generic radix trie implementation.
//!
//! To get started, see the docs for `Trie` below.
// #![warn(missing_docs)]
extern crate nibble_vec;
extern crate endian_type;
#[cfg(test)]
extern crate quickcheck;
#[cfg(test)]
extern crate rand;
pub use nibble_vec::NibbleVec;
pub use keys::TrieKe... | <K, V> {
/// Key fragments/bits associated with this node, such that joining the keys from all
/// parent nodes and this node is equal to the bit-encoding of this node's key.
key: NibbleVec,
/// The key and value stored at this node.
key_value: Option<Box<KeyValue<K, V>>>,
/// The number of ch... | TrieNode | identifier_name |
view.py | # Copyright (c) 2019-2022, Manfred Moitzi
# License: MIT License
from typing import TYPE_CHECKING
import logging
from ezdxf.lldxf import validator
from ezdxf.lldxf.attributes import (
DXFAttr,
DXFAttributes,
DefSubclass,
XType,
RETURN_DEFAULT,
group_code_mapping,
)
from ezdxf.lldxf.const import... | tagwriter,
[
"name",
"flags",
"height",
"width",
"center",
"direction",
"target",
"focal_length",
"front_clipping",
"back_clipping",
... | """DXF VIEW entity"""
DXFTYPE = "VIEW"
DXFATTRIBS = DXFAttributes(base_class, acdb_symbol_table_record, acdb_view)
def load_dxf_attribs(
self, processor: SubclassProcessor = None
) -> "DXFNamespace":
dxf = super().load_dxf_attribs(processor)
if processor:
processor.... | identifier_body |
view.py | # Copyright (c) 2019-2022, Manfred Moitzi
# License: MIT License
from typing import TYPE_CHECKING
import logging
from ezdxf.lldxf import validator
from ezdxf.lldxf.attributes import (
DXFAttr,
DXFAttributes,
DefSubclass,
XType,
RETURN_DEFAULT,
group_code_mapping,
)
from ezdxf.lldxf.const import... | )
acdb_view_group_codes = group_code_mapping(acdb_view)
@register_entity
class View(DXFEntity):
"""DXF VIEW entity"""
DXFTYPE = "VIEW"
DXFATTRIBS = DXFAttributes(base_class, acdb_symbol_table_record, acdb_view)
def load_dxf_attribs(
self, processor: SubclassProcessor = None
) -> "DXFName... | random_line_split | |
view.py | # Copyright (c) 2019-2022, Manfred Moitzi
# License: MIT License
from typing import TYPE_CHECKING
import logging
from ezdxf.lldxf import validator
from ezdxf.lldxf.attributes import (
DXFAttr,
DXFAttributes,
DefSubclass,
XType,
RETURN_DEFAULT,
group_code_mapping,
)
from ezdxf.lldxf.const import... | (self, tagwriter: "TagWriter") -> None:
super().export_entity(tagwriter)
if tagwriter.dxfversion > DXF12:
tagwriter.write_tag2(SUBCLASS_MARKER, acdb_symbol_table_record.name)
tagwriter.write_tag2(SUBCLASS_MARKER, acdb_view.name)
self.dxf.export_dxf_attribs(
t... | export_entity | identifier_name |
view.py | # Copyright (c) 2019-2022, Manfred Moitzi
# License: MIT License
from typing import TYPE_CHECKING
import logging
from ezdxf.lldxf import validator
from ezdxf.lldxf.attributes import (
DXFAttr,
DXFAttributes,
DefSubclass,
XType,
RETURN_DEFAULT,
group_code_mapping,
)
from ezdxf.lldxf.const import... |
return dxf
def export_entity(self, tagwriter: "TagWriter") -> None:
super().export_entity(tagwriter)
if tagwriter.dxfversion > DXF12:
tagwriter.write_tag2(SUBCLASS_MARKER, acdb_symbol_table_record.name)
tagwriter.write_tag2(SUBCLASS_MARKER, acdb_view.name)
... | processor.simple_dxfattribs_loader(dxf, acdb_view_group_codes) # type: ignore | conditional_block |
RelayReaderTestCreatesFragmentPointersWithVariableArgumentsUserQuery.graphql.js | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @generated SignedSource<<713bfba9717046b5de96c3132c59fb0c>>
* @flow
* @lightSyntaxTransform
* @nogrep
*/
/* eslint-disable ... | {
"args": null,
"kind": "FragmentSpread",
"name": "RelayReaderTestCreatesFragmentPointersWithVariableArgumentsUserProfile"
}
],
"storageKey": null
}
],
"type": "Query",
"abstractKey": null
},
"kind": "Request",
"operation": ... | random_line_split | |
RelayReaderTestCreatesFragmentPointersWithVariableArgumentsUserQuery.graphql.js | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @generated SignedSource<<713bfba9717046b5de96c3132c59fb0c>>
* @flow
* @lightSyntaxTransform
* @nogrep
*/
/* eslint-disable ... |
module.exports = node;
| {
(node/*: any*/).hash = "7a9eaa1476798159533ae048a3ff048a";
} | conditional_block |
issue-23037.rs | // Copyright 2015 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 ... | () {
let foo = i32x4(1,2,3,4);
let bar = i32x4(40,30,20,10);
let baz = foo + bar;
assert!(baz.0 == 41 && baz.1 == 32 && baz.2 == 23 && baz.3 == 14);
}
| main | identifier_name |
issue-23037.rs | // Copyright 2015 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 ... | {
let foo = i32x4(1,2,3,4);
let bar = i32x4(40,30,20,10);
let baz = foo + bar;
assert!(baz.0 == 41 && baz.1 == 32 && baz.2 == 23 && baz.3 == 14);
} | identifier_body | |
issue-23037.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT | // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(core)]
use std::simd::i32x4;
fn main() {
let foo = i32x4(1,2,3,4);
l... | // 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 | random_line_split |
bitmap.rs | // http://rosettacode.org/wiki/Basic_bitmap_storage
use std::default::Default;
use std::io::{Write, BufWriter, Error};
use std::fs::File;
use std::ops::{Index, IndexMut};
#[derive(Copy, Clone, Default, PartialEq, Debug)]
pub struct Color {
pub red: u8,
pub green: u8,
pub blue: u8
}
pub struct Image {
... |
for y in 0..10 {
for x in 5..10 {
image[(x,y)] = Color { red: 255, green: 255, blue: 255 };
}
}
for y in 0..10 {
for x in 0..10 {
if image[(x,y)].red + image[(x,y)].green + image[(x,y)].blue == 0 {
print!("#");
} else {
... | #[cfg(not(test))]
#[allow(dead_code)]
pub fn main() {
let mut image = Image::new(10, 10); | random_line_split |
bitmap.rs | // http://rosettacode.org/wiki/Basic_bitmap_storage
use std::default::Default;
use std::io::{Write, BufWriter, Error};
use std::fs::File;
use std::ops::{Index, IndexMut};
#[derive(Copy, Clone, Default, PartialEq, Debug)]
pub struct Color {
pub red: u8,
pub green: u8,
pub blue: u8
}
pub struct Image {
... |
}
impl Index<(usize, usize)> for Image {
type Output=Color;
fn index<'a>(&'a self, (x, y): (usize, usize)) -> &'a Color {
&self.data[x + y*self.width]
}
}
impl IndexMut<(usize, usize)> for Image {
fn index_mut<'a>(&'a mut self, (x, y): (usize, usize)) -> &'a mut Color {
& mut self.da... | {
let file = try!(File::create(filename));
let mut writer = BufWriter::new(file);
try!(writeln!(&mut writer,"P6"));
try!(write!(&mut writer, "{} {} {}\n", self.width, self.height, 255));
for color in &(self.data) {
for channel in &[color.red, color.green, color.blue] ... | identifier_body |
bitmap.rs | // http://rosettacode.org/wiki/Basic_bitmap_storage
use std::default::Default;
use std::io::{Write, BufWriter, Error};
use std::fs::File;
use std::ops::{Index, IndexMut};
#[derive(Copy, Clone, Default, PartialEq, Debug)]
pub struct Color {
pub red: u8,
pub green: u8,
pub blue: u8
}
pub struct Image {
... |
}
println!("");
}
}
#[cfg(test)]
mod test {
use super::{Color, Image};
use std::default::Default;
#[test]
#[should_panic]
#[ignore(unused_variable)]
fn out_of_bounds() {
let image = Image::new(10, 10);
let _ = image[(10, 11)];
assert!(false);
}
... | {
print!(".");
} | conditional_block |
bitmap.rs | // http://rosettacode.org/wiki/Basic_bitmap_storage
use std::default::Default;
use std::io::{Write, BufWriter, Error};
use std::fs::File;
use std::ops::{Index, IndexMut};
#[derive(Copy, Clone, Default, PartialEq, Debug)]
pub struct Color {
pub red: u8,
pub green: u8,
pub blue: u8
}
pub struct Image {
... | () {
let mut image = Image::new(10, 10);
for y in 0..10 {
for x in 5..10 {
image[(x,y)] = Color { red: 255, green: 255, blue: 255 };
}
}
for y in 0..10 {
for x in 0..10 {
if image[(x,y)].red + image[(x,y)].green + image[(x,y)].blue == 0 {
... | main | identifier_name |
dtos.py | # ##############################################################################
#
# OSIS stands for Open Student Information System. It's an application
# designed to manage the core business of higher education institutions,
# such as universities, faculties, institutes and professional schools.
# The cor... | igle = attr.ib(type=str)
intitule = attr.ib(type=str)
| identifier_body | |
dtos.py | # ##############################################################################
#
# OSIS stands for Open Student Information System. It's an application
# designed to manage the core business of higher education institutions,
# such as universities, faculties, institutes and professional schools.
# The cor... | interface.DTO):
sigle = attr.ib(type=str)
intitule = attr.ib(type=str)
| ntiteUclDTO( | identifier_name |
dtos.py | # ############################################################################## | # The core business involves the administration of students, teachers,
# courses, programs and so on.
#
# Copyright (C) 2015-2021 Université catholique de Louvain (http://www.uclouvain.be)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Pub... | #
# OSIS stands for Open Student Information System. It's an application
# designed to manage the core business of higher education institutions,
# such as universities, faculties, institutes and professional schools. | random_line_split |
utils.py | 81-9a93-aa048022c1ca"):
raise nova_ex.NotFound("")
return 'OK'
def _get_fl_ip_pool_list():
return [FakeNetwork("d9a3bebc-f788-4b81-9a93-aa048022c1ca")]
def _get_availability_zone_list(detailed=True):
return [FakeAvailabilityZone('nova')]
def _get_heat_stack_list(**kwargs):
if (kwargs.get('... |
return ast.literal_eval(s[start:end+1]), s[0:start+1] + s[end]
@mock.patch("sahara.utils.api.request_data")
@mock.patch("sahara.utils.api.bad_request")
def _assert_create_object_validation(
self, bad_req=None, request_data=None,
data=None, bad_req_i=None):
request... | return None, s | conditional_block |
utils.py | 81-9a93-aa048022c1ca"):
raise nova_ex.NotFound("")
return 'OK'
def _get_fl_ip_pool_list():
return [FakeNetwork("d9a3bebc-f788-4b81-9a93-aa048022c1ca")]
def _get_availability_zone_list(detailed=True):
return [FakeAvailabilityZone('nova')]
def _get_heat_stack_list(**kwargs):
if (kwargs.get('... | "sahara.service.api.get_node_group_template")
if patch_templates:
get_cl_templates_p = mock.patch(
"sahara.service.api.get_cluster_templates")
get_cl_template_p = mock.patch(
"sahara.service.api.get_cluster_template")
nova_p = mock.patch("sahara.utils.openstac... | if patch_templates:
get_ng_templates_p = mock.patch(
"sahara.service.api.get_node_group_templates")
get_ng_template_p = mock.patch( | random_line_split |
utils.py | 81-9a93-aa048022c1ca"):
raise nova_ex.NotFound("")
return 'OK'
def _get_fl_ip_pool_list():
return [FakeNetwork("d9a3bebc-f788-4b81-9a93-aa048022c1ca")]
def _get_availability_zone_list(detailed=True):
return [FakeAvailabilityZone('nova')]
def _get_heat_stack_list(**kwargs):
if (kwargs.get('... |
def _get_security_groups_list():
return [FakeSecurityGroup("1", "default"),
FakeSecurityGroup("2", "group1"),
FakeSecurityGroup("3", "group2")]
def start_patch(patch_templates=True):
get_clusters_p = mock.patch("sahara.service.api.get_clusters")
get_cluster_p = mock.patch("sahar... | return [FakeFlavor("42")] | identifier_body |
utils.py | 1-9a93-aa048022c1ca"):
raise nova_ex.NotFound("")
return 'OK'
def _get_fl_ip_pool_list():
return [FakeNetwork("d9a3bebc-f788-4b81-9a93-aa048022c1ca")]
def _get_availability_zone_list(detailed=True):
return [FakeAvailabilityZone('nova')]
def _get_heat_stack_list(**kwargs):
if (kwargs.get('f... | (self):
if self.name == 'test':
return ['vanilla', '1.2.1']
else:
return ['vanilla', 'wrong_tag']
def _get_image(id):
if id == '550e8400-e29b-41d4-a716-446655440000':
return Image()
else:
return Image('wrong_test')
... | tags | identifier_name |
tree.py | """Creates a supervision tree which splits the jobs into buckets.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import logging
import os
import shutil
from treadmill import fs
from treadmill import spawn
from t... | """Exec into the tree."""
s6_envdir = subproc.resolve('s6_envdir')
utils.sane_execvp(s6_envdir, [
s6_envdir,
self.paths.env_dir,
subproc.resolve('s6_svscan'),
self.paths.svscan_tree_dir
]) | identifier_body | |
tree.py | """Creates a supervision tree which splits the jobs into buckets.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import logging
import os
import shutil
from treadmill import fs
from treadmill import spawn
from t... | class Tree:
"""Treadmill spawn tree."""
__slots__ = (
'paths',
'buckets',
'max_per_bucket'
)
def __init__(self, root, buckets=spawn.BUCKETS,
max_per_bucket=spawn.MAX_PER_BUCKET):
self.buckets = buckets
self.paths = spawn.SpawnPaths(root, buckets... |
_LOGGER = logging.getLogger(__name__)
| random_line_split |
tree.py | """Creates a supervision tree which splits the jobs into buckets.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import logging
import os
import shutil
from treadmill import fs
from treadmill import spawn
from t... |
def run(self):
"""Exec into the tree."""
s6_envdir = subproc.resolve('s6_envdir')
utils.sane_execvp(s6_envdir, [
s6_envdir,
self.paths.env_dir,
subproc.resolve('s6_svscan'),
self.paths.svscan_tree_dir
])
| path = os.path.join(self.paths.running_dir, run_dir)
_LOGGER.debug('Removing bucket (%r)) %r.',
spawn.RUNNING_DIR, path)
shutil.rmtree(path, ignore_errors=True) | conditional_block |
tree.py | """Creates a supervision tree which splits the jobs into buckets.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import logging
import os
import shutil
from treadmill import fs
from treadmill import spawn
from t... | (self):
"""Exec into the tree."""
s6_envdir = subproc.resolve('s6_envdir')
utils.sane_execvp(s6_envdir, [
s6_envdir,
self.paths.env_dir,
subproc.resolve('s6_svscan'),
self.paths.svscan_tree_dir
])
| run | identifier_name |
rule.py | # Copyright 2015 Rafe Kaplan
#
# 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 writing, s... | (self):
return self.__parser
@parser.setter
def parser(self, value):
if self.__expected_attr_type and self.__expected_attr_type != value.attr_type:
raise ValueError('Unexpected attribute type')
self.__parser = parser.as_parser(value)
def _parse(self, state, *args, **kwa... | parser | identifier_name |
rule.py | # Copyright 2015 Rafe Kaplan
#
# 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 writing, s... | kwargs = {k: state.invoke(v) for k, v in self.__kwargs.items()}
self.parser._parse(state, *args, **kwargs) | def _parse(self, state):
args = [state.invoke(a) for a in self.__args] | random_line_split |
rule.py | # Copyright 2015 Rafe Kaplan
#
# 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 writing, s... |
else:
try:
inner_parser = self.__parser
except AttributeError:
raise NotImplementedError
else:
return inner_parser.attr_type
@property
def parser(self):
return self.__parser
@parser.setter
def parser(s... | return self.__expected_attr_type | conditional_block |
rule.py | # Copyright 2015 Rafe Kaplan
#
# 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 writing, s... |
@property
def args(self):
return self.__args
@property
def kwargs(self):
return dict(self.__kwargs)
def _parse(self, state):
args = [state.invoke(a) for a in self.__args]
kwargs = {k: state.invoke(v) for k, v in self.__kwargs.items()}
self.parser._parse(st... | if not isinstance(rule, Rule):
raise TypeError('Expected rule to be type Rule, was {}'.format(type(rule).__name__))
super(RuleCall, self).__init__(rule)
self.__args = args
self.__kwargs = kwargs | identifier_body |
array_builder.py | (ArithBuilder):
"""
Builder for constructing arrays and getting their properties
"""
def elt_type(self, x):
if isinstance(x, Type):
try:
return x.elt_type
except:
return x
elif self.is_array(x):
return x.type.elt_type
else:
return x.type
def alloc_arra... | (self, arr, axis, idx):
"""
Pull out a slice if the array has the given axis,
otherwise just return the array
"""
r = self.rank(arr)
if isinstance(axis, Expr):
axis = unwrap_constant(axis)
idx = wrap_if_constant(idx)
if r == 1 and (axis is None or axis == 0):
retu... | slice_along_axis | identifier_name |
array_builder.py | Builder(ArithBuilder):
"""
Builder for constructing arrays and getting their properties
"""
def elt_type(self, x):
if isinstance(x, Type):
try:
return x.elt_type
except:
return x
elif self.is_array(x):
return x.type.elt_type
else:
return x.type
def all... |
if isinstance(arr_t, ScalarT):
# even though it's not correct externally, it's
# often more convenient to treat indexing
# into scalars as the identity function.
# Just be sure to catch this as an error in
# the user's code earlier in the pipeline.
return arr
if isinsta... | temp = temp or name is not None
arr_t = arr.type | random_line_split |
array_builder.py | Builder(ArithBuilder):
"""
Builder for constructing arrays and getting their properties
"""
def elt_type(self, x):
if isinstance(x, Type):
try:
return x.elt_type
except:
return x
elif self.is_array(x):
return x.type.elt_type
else:
return x.type
def all... |
assert isinstance(idx, int), \
"Index into tuple must be an integer, got %s" % idx
if isinstance(idx, Const):
idx = idx.value
proj = self.tuple_proj(arr, idx)
if temp:
return self.assign_name(proj, "tuple_elt%d" % idx if name is None else name)
else:
ret... | idx = idx.value | conditional_block |
array_builder.py | (ArithBuilder):
"""
Builder for constructing arrays and getting their properties
"""
def elt_type(self, x):
if isinstance(x, Type):
try:
return x.elt_type
except:
return x
elif self.is_array(x):
return x.type.elt_type
else:
return x.type
def alloc_arra... |
def size_along_axis(self, value, axis):
return self.shape(value, axis)
def check_equal_sizes(self, sizes):
pass
def index(self, arr, idx, temp = False, name = None):
"""Index into array or tuple differently depending on the type"""
temp = temp or name is not None
arr_t = arr... | """
Create an expression which acts as an LHS output location
for a slice throught the variable 'output' along the given axis
"""
r = self.rank(output)
if r > 1:
output_indices = self.build_slice_indices(r, axis, idx)
elif r == 1:
output_idx = self.slice_value(idx, self.none, self.i... | identifier_body |
info.py | # Copyright 2013 Daniel Richman
#
# This file is part of The Snowball Ticketing System.
#
# The Snowball Ticketing System 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 (... |
with app.test_request_context():
for endpoint in pages:
filename = os.path.join(output_dir, endpoint + ".html")
template = "theme/pages/{0}.html".format(endpoint)
logger.debug("Rendering endpoint %r -> %r", endpoint, filename)
with open(filename, "w") as f:
... | if filename != '.gitignore':
logger.debug("Cleaning %s", filename)
os.unlink(os.path.join(output_dir, filename))
else:
logger.debug("Keeping .gitignore") | random_line_split |
info.py | # Copyright 2013 Daniel Richman
#
# This file is part of The Snowball Ticketing System.
#
# The Snowball Ticketing System 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 (... | (pages_dir):
for page in os.listdir(pages_dir):
match = page_filename_re.match(page)
assert match
yield match.groups()[0]
def setup(bp, pages):
for endpoint in pages:
if endpoint == 'index':
url = "/"
else:
url = "/" + endpoint.replace("_", "-")
... | find_pages | identifier_name |
info.py | # Copyright 2013 Daniel Richman
#
# This file is part of The Snowball Ticketing System.
#
# The Snowball Ticketing System 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 (... |
def find_pages(pages_dir):
for page in os.listdir(pages_dir):
match = page_filename_re.match(page)
assert match
yield match.groups()[0]
def setup(bp, pages):
for endpoint in pages:
if endpoint == 'index':
url = "/"
else:
url = "/" + endpoint.rep... | data = {}
for filename in os.listdir(data_dir):
key, = data_filename_re.match(filename).groups()
with open(os.path.join(data_dir, filename)) as f:
data[key] = yaml.safe_load(f)
return data | identifier_body |
info.py | # Copyright 2013 Daniel Richman
#
# This file is part of The Snowball Ticketing System.
#
# The Snowball Ticketing System 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 (... |
else:
logger.debug("Keeping .gitignore")
with app.test_request_context():
for endpoint in pages:
filename = os.path.join(output_dir, endpoint + ".html")
template = "theme/pages/{0}.html".format(endpoint)
logger.debug("Rendering endpoint %r -> %r", e... | logger.debug("Cleaning %s", filename)
os.unlink(os.path.join(output_dir, filename)) | conditional_block |
until_any_or_whitespace.rs | use read_token::ReadToken;
use range::Range;
use std::sync::Arc;
use super::{
ParseResult,
};
use {
DebugId,
MetaData,
ParseError,
};
use tokenizer::{ read_data, TokenizerState };
/// Stores information about reading until whitespace or any of some character.
#[derive(Clone, Debug, PartialEq)]
pub str... | () {
let text = "fn foo()";
let mut tokens = vec![];
let s = TokenizerState::new();
let function_name: Arc<String> = Arc::new("function_name".into());
let name = UntilAnyOrWhitespace {
debug_id: 0,
any_characters: Arc::new("(".into()),
optional... | successful | identifier_name |
until_any_or_whitespace.rs | use read_token::ReadToken;
use range::Range;
use std::sync::Arc;
use super::{
ParseResult,
};
use { | };
use tokenizer::{ read_data, TokenizerState };
/// Stores information about reading until whitespace or any of some character.
#[derive(Clone, Debug, PartialEq)]
pub struct UntilAnyOrWhitespace {
/// The characters to stop at.
pub any_characters: Arc<String>,
/// Whether empty data is accepted or not.
... | DebugId,
MetaData,
ParseError, | random_line_split |
until_any_or_whitespace.rs | use read_token::ReadToken;
use range::Range;
use std::sync::Arc;
use super::{
ParseResult,
};
use {
DebugId,
MetaData,
ParseError,
};
use tokenizer::{ read_data, TokenizerState };
/// Stores information about reading until whitespace or any of some character.
#[derive(Clone, Debug, PartialEq)]
pub str... |
}
}
}
#[cfg(test)]
mod tests {
use all::*;
use all::tokenizer::*;
use meta_rules::UntilAnyOrWhitespace;
use range::Range;
use read_token::ReadToken;
use std::sync::Arc;
#[test]
fn required() {
let text = "fn ()";
let mut tokenizer = vec![];
let s = ... | {
Ok((range, state.clone(), None))
} | conditional_block |
Memory.js | /**
* @author Ed Spencer
*
* In-memory proxy. This proxy simply uses a local variable for data storage/retrieval, so its contents are lost on
* every page refresh.
*
* Usually this Proxy isn't used directly, serving instead as a helper to a {@link Ext.data.Store Store} where a reader
* is required to load data. ... | read: function(operation, callback, scope) {
var me = this;
operation.resultSet = me.getReader().read(me.data);
operation.setCompleted();
operation.setSuccessful();
Ext.callback(callback, scope || me, [operation]);
},
clear: Ext.emptyFn
}); | * Reads data from the configured {@link #data} object. Uses the Proxy's {@link #reader}, if present.
* @param {Ext.data.Operation} operation The read Operation
* @param {Function} callback The callback to call when reading has completed
* @param {Object} scope The scope to call the callback function... | random_line_split |
Memory.js | /**
* @author Ed Spencer
*
* In-memory proxy. This proxy simply uses a local variable for data storage/retrieval, so its contents are lost on
* every page refresh.
*
* Usually this Proxy isn't used directly, serving instead as a helper to a {@link Ext.data.Store Store} where a reader
* is required to load data. ... |
operation.setCompleted();
operation.setSuccessful();
Ext.callback(callback, scope || this, [operation]);
},
/**
* Currently this is a hard-coded method that simply commits any records and sets the operation to successful,
* then calls the callback function, if pr... | {
recs[i].commit();
} | conditional_block |
test_rnaseq.py | import pytest
from bcbio.pipeline import rnaseq
@pytest.yield_fixture
def ericscript_run(mocker):
|
@pytest.fixture
def sample():
return {
'config': {
'algorithm': {
'fusion_mode': True,
'fusion_caller': 'ericscript'
}
}
}
def test_detect_fusion_callers_calls_for_each_sample(ericscript_run, sample):
samples = [[sample], [sample]]... | yield mocker.patch('bcbio.pipeline.rnaseq.ericscript.run', autospec=True) | identifier_body |
test_rnaseq.py | import pytest
from bcbio.pipeline import rnaseq
@pytest.yield_fixture
def | (mocker):
yield mocker.patch('bcbio.pipeline.rnaseq.ericscript.run', autospec=True)
@pytest.fixture
def sample():
return {
'config': {
'algorithm': {
'fusion_mode': True,
'fusion_caller': 'ericscript'
}
}
}
def test_detect_fusion_ca... | ericscript_run | identifier_name |
test_rnaseq.py | import pytest
from bcbio.pipeline import rnaseq
@pytest.yield_fixture
def ericscript_run(mocker):
yield mocker.patch('bcbio.pipeline.rnaseq.ericscript.run', autospec=True)
@pytest.fixture
def sample():
return {
'config': {
'algorithm': {
'fusion_mode': True,
... | assert ericscript_run.call_count == len(samples)
def test_detect_fusions_returns_updated_samples(ericscript_run, sample):
samples = [[sample]]
result = rnaseq.detect_fusions(samples)
assert result == [[ericscript_run.return_value]]
def test_detect_fusions_calls_caller_with_sample_dict(ericscript_run... | random_line_split | |
style.rs | //! Code for applying CSS styles to the DOM.
//!
//! This is not very interesting at the moment. It will get much more
//! complicated if I add support for compound selectors.
use dom::{Node, NodeType, ElementData};
use css::{Stylesheet, Rule, Selector, SimpleSelector, Value, Specificity};
use std::collections::HashM... | {
Inline,
Block,
None,
}
impl<'a> StyledNode<'a> {
/// Return the specified value of a property if it exists, otherwise `None`.
pub fn value(&self, name: &str) -> Option<Value> {
self.specified_values.get(name).map(|v| v.clone())
}
/// Return the specified value of property `name`... | Display | identifier_name |
style.rs | //! Code for applying CSS styles to the DOM.
//!
//! This is not very interesting at the moment. It will get much more
//! complicated if I add support for compound selectors.
use dom::{Node, NodeType, ElementData};
use css::{Stylesheet, Rule, Selector, SimpleSelector, Value, Specificity};
use std::collections::HashM... | if selector.tag_name.iter().any(|name| elem.tag_name != *name) {
return false;
}
// Check ID selector
if selector.id.iter().any(|id| elem.id() != Some(id)) {
return false;
}
// Check class selectors
let elem_classes = elem.classes();
if selector.class.iter().any(|class|... | fn matches_simple_selector(elem: &ElementData, selector: &SimpleSelector) -> bool {
// Check type selector | random_line_split |
keyboard.js | ++){
if(srcArr[i] == "")
this.checkLoaded();
else
this.requestSound(i, srcArr, soundArr, chain);
}
}
// makes request for sounds
// if offline version, gets from local files
// if online version, gets from public folder
Keyboard.pr... |
else{
var kcInd = this.getKeyInd(kc);
if(currentSounds[currentSoundPack][kcInd] != null){
currentSounds[currentSoundPack][kcInd].stop();
currentSounds[currentSoundPack][kcInd].play();
// go through all linked Areas in curr... | {
// do nothing
} | conditional_block |
keyboard.js |
for(var i = 0; i < srcArr.length; i++){
if(srcArr[i] == "")
this.checkLoaded();
else
this.requestSound(i, srcArr, soundArr, chain);
}
}
// makes request for sounds
// if offline version, gets from local files
// if online ... | for(var i = 0; i < srcArr.length; i++)
soundArr.push(null); | random_line_split | |
VtxSegment.js | 'use strict';
/**
* Vertex segment.
* @exception {Error} Messages.CONSTRUCT_ERROR
*
* @class VtxSegment
*
* @param {Vertex} startVertex Optional. start vertex.
* @param {Vertex} endVertex Optional. end vertex.
*/
var VtxSegment = function(startVertex, endVertex)
{
if (!(this instanceof VtxSegment))
{
t... |
if (Math.abs(distA + distB - distTotal) < error)
{ return Constant.INTERSECTION_INSIDE; }
};
| {
return Constant.INTERSECTION_OUTSIDE;
} | conditional_block |
VtxSegment.js | 'use strict';
/**
* Vertex segment.
* @exception {Error} Messages.CONSTRUCT_ERROR
*
* @class VtxSegment
*
* @param {Vertex} startVertex Optional. start vertex.
* @param {Vertex} endVertex Optional. end vertex.
*/
var VtxSegment = function(startVertex, endVertex)
{
if (!(this instanceof VtxSegment))
{
t... | this.startVertex;
/**
* end vertex.
* @type {Vertex}
*/
this.endVertex;
if (startVertex)
{ this.startVertex = startVertex; }
if (endVertex)
{ this.endVertex = endVertex; }
};
/**
* set start, end vertex.
* @param {Vertex} startVertex
* @param {Vertex} endVertex
*/
VtxSegment.prototype.setVertice... | */ | random_line_split |
test_block_known.rs | // Copyright 2021 The Grin Developers
//
// 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 agree... | let (latest, genesis) = {
let chain = mine_chain(chain_dir, 3);
let genesis = chain
.get_block(&chain.get_header_by_height(0).unwrap().hash())
.unwrap();
let head = chain.head().unwrap();
let latest = chain.get_block(&head.last_block_h).unwrap();
(latest, genesis)
};
// attempt to reprocess latest b... | util::init_test_logger();
clean_output_dir(chain_dir);
// mine some blocks | random_line_split |
test_block_known.rs | // Copyright 2021 The Grin Developers
//
// 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 agree... | assert_eq!(
res.unwrap_err().kind(),
ErrorKind::Unfit("duplicate block".to_string()).into()
);
}
// attempt to reprocess genesis block
{
let chain = init_chain(chain_dir, genesis.clone());
let res = chain.process_block(genesis.clone(), chain::Options::NONE);
assert_eq!(
res.unwrap_err().kind(),
... | {
let chain_dir = ".grin.check_known";
util::init_test_logger();
clean_output_dir(chain_dir);
// mine some blocks
let (latest, genesis) = {
let chain = mine_chain(chain_dir, 3);
let genesis = chain
.get_block(&chain.get_header_by_height(0).unwrap().hash())
.unwrap();
let head = chain.head().unwrap();
... | identifier_body |
test_block_known.rs | // Copyright 2021 The Grin Developers
//
// 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 agree... | () {
let chain_dir = ".grin.check_known";
util::init_test_logger();
clean_output_dir(chain_dir);
// mine some blocks
let (latest, genesis) = {
let chain = mine_chain(chain_dir, 3);
let genesis = chain
.get_block(&chain.get_header_by_height(0).unwrap().hash())
.unwrap();
let head = chain.head().unwrap(... | check_known | identifier_name |
pydev_runfiles_pytest2.py | load_filters():
global py_test_accept_filter
if py_test_accept_filter is None:
py_test_accept_filter = os.environ.get('PYDEV_PYTEST_SKIP')
if py_test_accept_filter:
py_test_accept_filter = pickle.loads(
zlib.decompress(base64.b64decode(py_test_accept_filter)))
... |
def get_curr_output():
buf_out = State.buf_out
buf_err = State.buf_err
return buf_out.getvalue() if buf_out is not None else '', buf_err.getvalue() if buf_err is not None else ''
def pytest_unconfigure():
if is_in_xdist_node():
return
# Only report that it finished when on t... | if State.buf_out is not None:
return
from _pydevd_bundle import pydevd_io
State.buf_err = pydevd_io.start_redirect(keep_original_redirection=True, std='stderr')
State.buf_out = pydevd_io.start_redirect(keep_original_redirection=True, std='stdout') | identifier_body |
pydev_runfiles_pytest2.py | _filters():
global py_test_accept_filter
if py_test_accept_filter is None:
py_test_accept_filter = os.environ.get('PYDEV_PYTEST_SKIP')
if py_test_accept_filter:
py_test_accept_filter = pickle.loads(
zlib.decompress(base64.b64decode(py_test_accept_filter)))
... | ():
if is_in_xdist_node():
return
# Only report that it finished when on the main node (we don't want to report
# the finish on each separate node).
pydev_runfiles_xml_rpc.notifyTestRunFinished(
'Finished in: %.2f secs.' % (time.time() - State.start_time,))
def pytest_collecti... | pytest_unconfigure | identifier_name |
pydev_runfiles_pytest2.py | _filters():
global py_test_accept_filter
if py_test_accept_filter is None:
py_test_accept_filter = os.environ.get('PYDEV_PYTEST_SKIP')
if py_test_accept_filter:
py_test_accept_filter = pickle.loads(
zlib.decompress(base64.b64decode(py_test_accept_filter)))
... |
else:
pydev_runfiles_xml_rpc.initialize_server(int(port), daemon=True)
PY2 = sys.version_info[0] <= 2
PY3 = not PY2
class State:
start_time = time.time()
buf_err = None
buf_out = None
def start_redirect():
if State.buf_out is not None:
return
from... | sys.stderr.write(
'Error: no PYDEV_PYTEST_SERVER environment variable defined.\n') | conditional_block |
pydev_runfiles_pytest2.py | _filters():
global py_test_accept_filter
if py_test_accept_filter is None:
py_test_accept_filter = os.environ.get('PYDEV_PYTEST_SKIP')
if py_test_accept_filter:
py_test_accept_filter = pickle.loads(
zlib.decompress(base64.b64decode(py_test_accept_filter)))
... | if exc:
if error_contents:
error_contents = append_strings(error_contents, '----------------------------- Exceptions -----------------------------\n')
error_contents = append_strings(error_contents, exc)
report_test(status, filename, test, captured_output, error... | if report_outcome != 'skipped':
# On skipped, we'll have a traceback for the skip, which is not what we
# want.
exc = _get_error_contents_from_report(report)
| random_line_split |
ResponsiveFlowLayoutRenderer-dbg.js | /*!
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2016 SAP SE or an SAP affiliate company. | */
sap.ui.define(['jquery.sap.global'],
function(jQuery) {
"use strict";
/**
* ResponsiveFlowLayout renderer.
* @namespace
*/
var ResponsiveFlowLayoutRenderer = {};
/**
* Renders the HTML for the given control, using the provided
* {@link sap.ui.core.RenderManager}.
*
* @param {sap.ui.core.Render... | * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. | random_line_split |
ResponsiveFlowLayoutRenderer-dbg.js | /*!
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2016 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
sap.ui.define(['jquery.sap.global'],
function(jQuery) {
"use strict";
/**
* ResponsiveFlowLayout renderer.
* @namespace
*/
... |
oRm.writeAccessibilityState(oControl, mAriaProps);
oRm.write(">"); // div element
// rendering of content happens in oControl.fnRenderContent
oRm.write("</div>");
};
}());
return ResponsiveFlowLayoutRenderer;
}, /* bExport= */ true);
| {
mAriaProps = {role: sRole};
} | conditional_block |
lib.rs | PatchCall.html), [*search*](struct.AnnotationSetSearchCall.html) and [*update*](struct.AnnotationSetUpdateCall.html)
//! * [annotations](struct.Annotation.html)
//! * [*batch create*](struct.AnnotationBatchCreateCall.html), [*create*](struct.AnnotationCreateCall.html), [*delete*](struct.AnnotationDeleteCall.html), [*g... | //! read by you to obtain the media.
//! If such a method | //! If a method supports downloads, the response body, which is part of the [Result](enum.Result.html), should be | random_line_split |
codeEditorBase.py | wx.stc.STC_MARK_BOXMINUSCONNECTED, "white", "#808080")
self.MarkerDefine(wx.stc.STC_MARKNUM_FOLDERMIDTAIL,
wx.stc.STC_MARK_TCORNER, "white", "#808080")
# Set what kind of events will trigger a modified event
self.SetModEventMask(wx.stc.STC_MOD... | (self, event):
"""For context menu Delete"""
foc = self.FindFocus()
if hasattr(foc, 'DeleteBack'):
foc.DeleteBack()
def OnKeyPressed(self, event):
pass
def HashtagCounter(self, text, nTags=0):
# Hashtag counter - counts lines beginning with hashtags in selec... | onDelete | identifier_name |
codeEditorBase.py | wx.MenuItem(menu, self.CutID, _translate("Cut"))
copyItem = wx.MenuItem(menu, self.CopyID, _translate("Copy"))
pasteItem = wx.MenuItem(menu, self.PasteID, _translate("Paste"))
deleteItem = wx.MenuItem(menu, self.DeleteID, _translate("Delete"))
selectItem = wx.MenuItem(menu, self.SelectA... | newIndent = 0 | conditional_block | |
codeEditorBase.py | wx.stc.STC_MARK_BOXMINUSCONNECTED, "white", "#808080")
self.MarkerDefine(wx.stc.STC_MARKNUM_FOLDERMIDTAIL,
wx.stc.STC_MARK_TCORNER, "white", "#808080")
# Set what kind of events will trigger a modified event
self.SetModEventMask(wx.stc.STC_MOD... |
def toggleCommentLines(self):
codeType = "Py"
if hasattr(self, "codeType"):
codeType = self.codeType
startText, endText = self._GetPositionsBoundingSelectedLines()
nLines = len(self._GetSelectedLineNumbers())
nHashtags = self.HashtagCounter(self.GetTextRange(s... | for lines in text.splitlines():
if lines.startswith('#'):
nTags += 1
elif lines.startswith('//'):
nTags += 2
return nTags | identifier_body |
codeEditorBase.py | wx.stc.STC_MARK_BOXMINUSCONNECTED, "white", "#808080")
self.MarkerDefine(wx.stc.STC_MARKNUM_FOLDERMIDTAIL,
wx.stc.STC_MARK_TCORNER, "white", "#808080")
# Set what kind of events will trigger a modified event
self.SetModEventMask(wx.stc.STC_MOD... | codeType = "Py"
if hasattr(self, "codeType"):
codeType = self.codeType
startLineNum = self.LineFromPosition(self.GetSelectionStart())
endLineNum = self.LineFromPosition(self.GetSelectionEnd())
prevLine = self.GetLine(startLineNum - 1)
prevIndent = self.GetLin... | random_line_split | |
system.py | is running or not.
:param str command: process name to be checked
:returns: **True** if the process is running, **False** if it's not among ps
results, and **None** if ps can't be queried
"""
# Linux and the BSD families have different variants of ps. Guess based on
# the is_bsd() check which to... |
# attempts to resolve using pidof, failing if:
# - we're running on bsd (command unavailable)
#
# example output:
# atagar@morrigan:~$ pidof vim
# 3392 3283
if is_available("pidof"):
results = call(GET_PID_BY_NAME_PIDOF % process_name)
if results and len(results) == 1 and len(resul... | return int(pid) | conditional_block |
system.py | tcp6 0 0 ::1:631 :::* LISTEN -
# udp 0 0 0.0.0.0:5353 0.0.0.0:* -
# udp6 0 0 fe80::7ae4:ff:fe2f::123 :::* -
if is_available("netstat"):
results = call(GET_PID_BY_PORT_NETSTAT)
if... | get_bsd_jail_id | identifier_name | |
system.py | name is running or not.
:param str command: process name to be checked
:returns: **True** if the process is running, **False** if it's not among ps
results, and **None** if ps can't be queried
"""
# Linux and the BSD families have different variants of ps. Guess based on
# the is_bsd() check whi... |
::
1. netstat -npltu | grep 127.0.0.1:<port>
2. sockstat -4l -P tcp -p <port>
3. lsof -wnP -iTCP -sTCP:LISTEN | grep ":<port>"
Most queries limit results to listening TCP connections. This function likely
won't work on Mac OSX.
:param int port: port where the process we're looking for is... | Attempts to determine the process id for a process with the given port,
using... | random_line_split |
system.py | len(results) == 2:
pid = results[1].strip()
if pid.isdigit(): return int(pid)
if is_bsd():
# bsd variant of ps
results = call(GET_PID_BY_NAME_PS_BSD)
if results:
# filters results to those with our process name
results = [r for r in results if r.endswit... | """
Attempts to determine the process id for a process with the given open file,
using...
::
lsof -w <path>
:param str path: location of the socket file to query against
:returns: **int** with the process id, **None** if it can't be determined
"""
# resolves using lsof which works on bo... | identifier_body | |
selection-list.ts | AfterContentInit,
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
ContentChildren,
ElementRef,
EventEmitter,
forwardRef,
Inject,
Input,
OnDestroy,
Optional,
Output,
QueryList,
Renderer2,
ViewEncapsulation,
} from '@angular/core';
import {
CanDisable,
CanDisableRipple,
MATERI... |
ngOnDestroy(): void {
this._optionDestroyStream.unsubscribe();
this._optionFocusSubscription.unsubscribe();
}
/** Focus the selection-list. */
focus() {
this._element.nativeElement.focus();
}
/** Selects all of the options. */
selectAll() {
this.options.forEach(option => {
if (!o... | {
this._keyManager = new FocusKeyManager<MdListOption>(this.options).withWrap();
if (this.disabled) {
this._tabIndex = -1;
}
this._optionFocusSubscription = this._onFocusSubscription();
this._optionDestroyStream = this._onDestroySubscription();
} | identifier_body |
selection-list.ts | AfterContentInit,
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
ContentChildren,
ElementRef,
EventEmitter,
forwardRef,
Inject,
Input,
OnDestroy,
Optional,
Output,
QueryList,
Renderer2,
ViewEncapsulation,
} from '@angular/core';
import {
CanDisable,
CanDisableRipple,
MATERI... |
}
e.option.destroyed.unsubscribe();
});
}
/** Map all the options' onFocus event subscriptions and merge them into one stream. */
private _onFocusSubscription(): Subscription {
return RxChain.from(this.options.changes)
.call(startWith, this.options)
.call(switchMap, (option... | {
this._keyManager.setActiveItem(optionIndex - 1);
} | conditional_block |
selection-list.ts | AfterContentInit,
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
ContentChildren,
ElementRef,
EventEmitter,
forwardRef,
Inject,
Input,
OnDestroy,
Optional,
Output,
QueryList,
Renderer2,
ViewEncapsulation,
} from '@angular/core';
import {
CanDisable,
CanDisableRipple,
MATERI... | });
}
/** Passes relevant key presses to our key manager. */
| .call(switchMap, (options: MdListOption[]) => {
return merge(...options.map(option => option.onFocus));
}).subscribe((e: MdSelectionListOptionEvent) => {
let optionIndex: number = this.options.toArray().indexOf(e.option);
this._keyManager.updateActiveItemIndex(optionIndex); | random_line_split |
selection-list.ts | AfterContentInit,
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
ContentChildren,
ElementRef,
EventEmitter,
forwardRef,
Inject,
Input,
OnDestroy,
Optional,
Output,
QueryList,
Renderer2,
ViewEncapsulation,
} from '@angular/core';
import {
CanDisable,
CanDisableRipple,
MATERI... | () {
this.options.forEach(option => {
if (option.selected) {
option.toggle();
}
});
}
/** Map all the options' destroy event subscriptions and merge them into one stream. */
private _onDestroySubscription(): Subscription {
return RxChain.from(this.options.changes)
.call(star... | deselectAll | identifier_name |
setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: borja@libcrack.so
# Date: Wed Jan 28 16:35:57 CET 2015
import re
import os
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
def | (relpath):
"""
Return string containing the contents of the file at *relpath* relative to
this file.
"""
cwd = os.path.dirname(__file__)
abspath = os.path.join(cwd,os.path.normpath(relpath))
with open(abspath) as f:
return f.read()
PACKAGE = os.path.basename(os.getcwd())
PACKAGES = ... | read | identifier_name |
setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: borja@libcrack.so
# Date: Wed Jan 28 16:35:57 CET 2015
import re
import os
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
def read(relpath):
"""
Return string containing the contents of the file at *relpat... | 'package_dir': PACKAGE_DIR,
#'scripts': SCRIPTS,
'entry_points': ENTRY_POINTS,
'provides': PROVIDES,
'requires': INSTALL_REQUIRES,
'install_requires': INSTALL_REQUIRES,
'classifiers': CLASSIFIERS,
}
setup(**PARAMS)
# vim:ts=4 sts=4 tw=79 expandtab: | 'url': WEBSITE,
'license': LICENSE,
'packages': PACKAGES, | random_line_split |
setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: borja@libcrack.so
# Date: Wed Jan 28 16:35:57 CET 2015
import re
import os
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
def read(relpath):
"""
Return string containing the contents of the file at *relpat... |
else:
LONG_DESCRIPTION = None
CLASSIFIERS = [
'Development Status :: 3 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: GPL',
'Operating System :: OS Independent',
'Operating System :: POSIX :: Linux',
'Natural Language :: English',
'Programming La... | DESCRIPTION, LONG_DESCRIPTION = DESCRIPTION.split('\n\n', 1) | conditional_block |
setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: borja@libcrack.so
# Date: Wed Jan 28 16:35:57 CET 2015
import re
import os
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
def read(relpath):
|
PACKAGE = os.path.basename(os.getcwd())
PACKAGES = [PACKAGE]
PROVIDES = [PACKAGE]
PACKAGE_DIR = {PACKAGE: PACKAGE}
SCRIPT_FILE = PACKAGE_DIR[PACKAGE] + '/__init__.py'
# SCRIPTS=['scripts/' + PACKAGE]
ENTRY_POINTS = {
# 'console_scripts': [PACKAGE + '=' + PACKAGE + '.' + PACKAGE + ':main'],
'console_scripts': ... | """
Return string containing the contents of the file at *relpath* relative to
this file.
"""
cwd = os.path.dirname(__file__)
abspath = os.path.join(cwd,os.path.normpath(relpath))
with open(abspath) as f:
return f.read() | identifier_body |
vision.py | + (i,),depth+1,fm)
else:
if max_value < fm.full_matrix[index][x][y]:
global_index = index
max_value = fm.full_matrix[index][x][y]
def complexity(full_matrix):
global global_index
global max_value
"""This function expects as an input a object of... |
def phase_preference_scatter_plot(sheet_name,diameter=0.39):
r = UniformRandom(seed=1023)
preference_map = topo.sim[sheet_name].sheet_views['PhasePreference']
offset_magnitude = 0.03
datax = []
datay = []
(v,bb) = preference_map.view()
for z in zeros(66):
x = (r() - 0.5)*2*d... | s_w = zeros(full_matrix.matrix_shape)
for x in range(rows):
for y in range(cols):
or_response=[]
for p in xrange(size(full_matrix.features[phase_index].values)):
index = [0,0,0]
index[phase_index] = p
index[... | conditional_block |
vision.py | (i,),depth+1,fm)
else:
if max_value < fm.full_matrix[index][x][y]:
global_index = index
max_value = fm.full_matrix[index][x][y]
def complexity(full_matrix):
global global_index
global max_value
"""This function expects as an input a object of t... | (sheet_name,diameter=0.39):
r = UniformRandom(seed=1023)
preference_map = topo.sim[sheet_name].sheet_views['PhasePreference']
offset_magnitude = 0.03
datax = []
datay = []
(v,bb) = preference_map.view()
for z in zeros(66):
x = (r() - 0.5)*2*diameter
y = (r() - 0.5)*2*diameter... | phase_preference_scatter_plot | identifier_name |
vision.py | + (i,),depth+1,fm)
else:
if max_value < fm.full_matrix[index][x][y]:
global_index = index
max_value = fm.full_matrix[index][x][y]
def complexity(full_matrix):
global global_index
global max_value
"""This function expects as an input a object of... | iindex = array(global_index)
sum = 0.0
for i in range(size(full_matrix.features[phase_index].values)):
iindex[phase_index] = i
sum = sum + full_matrix.full_matrix[tuple(iindex.tolist())][x][y]
#average
average =... | _complexity_rec(x,y,(),0,full_matrix)
#compute the sum of the responses over phases given the found index of highest response
| random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.