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 |
|---|---|---|---|---|
lib.rs | (test)]
pub fn new(argv: Vec<String>) -> Process {
Process {
argv,
env: BTreeMap::new(),
working_directory: None,
input_digests: InputDigests::default(),
output_files: BTreeSet::new(),
output_directories: BTreeSet::new(),
timeout: None,
description: "".to_string(),
... | {
let directory_digests = vec![response.output_directory.clone()];
let file_digests = vec![response.stdout_digest, response.stderr_digest];
in_workunit!(
"eager_validate_action_cache",
Level::Trace,
|_workunit| async move {
store
.exists_recursive(director... | conditional_block | |
lib.rs | "successful" => Ok(ProcessCacheScope::Successful),
"per_restart_always" => Ok(ProcessCacheScope::PerRestartAlways),
"per_restart_successful" => Ok(ProcessCacheScope::PerRestartSuccessful),
"per_session" => Ok(ProcessCacheScope::PerSession),
other => Err(format!("Unknown Process cache scope... | pub env: BTreeMap<String, String>,
///
/// A relative path to a directory existing in the `input_files` digest to execute the process | random_line_split | |
lib.rs | (&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::MissingDigest(s, d) => {
write!(f, "{s}: {d:?}")
}
Self::Unclassified(s) => write!(f, "{s}"),
}
}
}
impl From<StoreError> for ProcessError {
fn from(err: StoreError) -> Self {
match err {
StoreError:... | fmt | identifier_name | |
lib.rs | immutable_inputs: merged_immutable_inputs,
use_nailgun: Itertools::concat(
from
.iter()
.map(|input_digests| input_digests.use_nailgun.clone()),
)
.into_iter()
.collect(),
})
}
pub fn with_input_files(input_files: DirectoryDigest) -> Self {
Self {
... | {
self.append_only_caches = append_only_caches;
self
} | identifier_body | |
ptycho-fig5.py | return self.beta.shape
@property
def complexform(self):
return self.delta + 1j * self.beta
class Detector(object):
"""A planar area detector.
Attributes
----------
numx : int
Number of horizontal pixels.
numy : int
Number of vertical pixels.... | (self, shape, sx, sy, margin=[0, 0], offset=[0, 0]):
self.shape = shape
self.sx = sx
self.sy = sy
self.margin = margin
self.offset = offset
@property
def x(self):
return np.arange(self.offset[0], self.shape[0]-self.margin[0]+1, self.sx)
@property
... | __init__ | identifier_name |
ptycho-fig5.py | import scipy as sp
import pyfftw
import shutil
import warnings
warnings.filterwarnings("ignore")
PLANCK_CONSTANT = 6.58211928e-19 # [keV*s]
SPEED_OF_LIGHT = 299792458e+2 # [cm/s]
def wavelength(energy):
"""Calculates the wavelength [cm] given energy [keV].
Parameters
----------
ener... |
import dxchange
import tomopy
import xraylib as xl
import numpy as np
| random_line_split | |
ptycho-fig5.py | return self.beta.shape
@property
def complexform(self):
return self.delta + 1j * self.beta
class Detector(object):
"""A planar area detector.
Attributes
----------
numx : int
Number of horizontal pixels.
numy : int
Number of vertical pixels.... | _upd = np.true_divide(num, denum)
upd[scan.x[m]:scan.x[m]+prb.size,
scan.y[n]:scan.y[n]+prb.size] += _upd
a += 1
# psi += upd.copy()
# _psi = psi + (gamma / 2) * upd.copy()
_psi = (1 - rho*gamma) * psi + rho*gamma * \... | for n in range(len(scan.y)):
# Near-plane.
phi = np.multiply(
prb.complex, psi[scan.x[m]:scan.x[m] + prb.size, scan.y[n]:scan.y[n] + prb.size])
# Go far-plane & Replace the amplitude with the measured amplitude.
phi = np.pad(
... | conditional_block |
ptycho-fig5.py | return self.beta.shape
@property
def complexform(self):
return self.delta + 1j * self.beta
class Detector(object):
"""A planar area detector.
Attributes
----------
numx : int
Number of horizontal pixels.
numy : int
Number of vertical pixels.... |
@property
def x(self):
return np.arange(self.offset[0], self.shape[0]-self.margin[0]+1, self.sx)
@property
def y(self):
return np.arange(self.offset[1], self.shape[1]-self.margin[1]+1, self.sy)
def scanner3(theta, shape, sx, sy, margin=[0, 0], offset=[0, 0], spiral=0):
... | self.shape = shape
self.sx = sx
self.sy = sy
self.margin = margin
self.offset = offset | identifier_body |
ec2_vol_management.py | % (volume['VolumeId'], volume['AvailabilityZone']))
# Create snapshot
result = ec2.create_snapshot(
VolumeId=volume['VolumeId'],
Description='Created by Lambda function %s for backup from %s' % (context.function_name, volume['VolumeId'])
)
# Get snapshot resour... |
else:
logger.info(" skipped as dry_run is true")
# Takes a list of EC2 instances with tag 'ami-creation': true - IDs and creates AMIs
# Copy from one of my work mate into here with small modification
def create_amis(ec2, cycle_tag='daily'):
ec2_filter = [{'Name':'tag:ami-creation',... | r = re.match(r".*for (ami-.*) from.*", snapshot.description)
if r:
#r.groups()[0] will contain the ami id
if r.groups()[0] == image.id:
logger.info("found snapshot belonging to %s. snapshot with image_id %s will be deleted",... | conditional_block |
ec2_vol_management.py | " % (volume['VolumeId'], volume['AvailabilityZone']))
# Create snapshot
result = ec2.create_snapshot(
VolumeId=volume['VolumeId'],
Description='Created by Lambda function %s for backup from %s' % (context.function_name, volume['VolumeId'])
)
# Get snapshot resou... | 'Values': ['java']
}
]
]
ami_deregister_filters = ast.literal_eval( os.environ.get('AMI_DEREGISTER_FILTER', "None"))
| 'Name': 'tag:Platform', | random_line_split |
ec2_vol_management.py | " % (volume['VolumeId'], volume['AvailabilityZone']))
# Create snapshot
result = ec2.create_snapshot(
VolumeId=volume['VolumeId'],
Description='Created by Lambda function %s for backup from %s' % (context.function_name, volume['VolumeId'])
)
# Get snapshot resou... | utc_now.minute,
utc_now.second)
#AMIs names cannot contain ','
name = name.replace(',', '_').replace(':', '_')
image = instance.create_image(
DryRun=False,
... | ec2_filter = [{'Name':'tag:ami-creation', 'Values':['true']}]
instances = list(ec2.instances.filter(Filters=ec2_filter))
logger.info("create AMIs with cycle_tag: '%s'", cycle_tag)
#creat image for each instance
for instance in instances:
for tag in instance.tags:
if tag['Key'] == '... | identifier_body |
ec2_vol_management.py | % (volume['VolumeId'], volume['AvailabilityZone']))
# Create snapshot
result = ec2.create_snapshot(
VolumeId=volume['VolumeId'],
Description='Created by Lambda function %s for backup from %s' % (context.function_name, volume['VolumeId'])
)
# Get snapshot resour... | (ec2, aws_account_id, filters=[], retention_days=14, dry_run=True):
"""Deregister ami if:
- No (running/stopped) ec2 instances use it
- Matching the filters condition
- creation time older than retention_days
- Retain at least one ami for safety
"""
instances = ec2.instances.all()
image... | deregister_ami | identifier_name |
page.js | ") //清空cur
for (var i = 0; i <= d; i++) {
$(".innavi_1 a").eq(i).addClass("cur").siblings().removeClass("cur") //每个ID添加cur样式
}
}
$(".innavi_1 a").click(function () {
if (isScroll == true) {
isScroll = false;
var id = $(".innavi_1 a").index($(this)) + 2; //声明ID等于当前值
... | if (curPage < 0) {
curPage = 0;
return;
}
if (curPage > pageNum) {
curPage = pageNum;
return;
}
Page_inout(curPage, Original)
isScroll = false;
}
... | identifier_name | |
page.js | ") //清空cur
for (var i = 0; i <= d; i++) {
$(".innavi_1 a").eq(i).addClass("cur").siblings().removeClass("cur") //每个ID添加cur样式
}
}
$(".innavi_1 a").click(function () {
if (isScroll == true) {
isScroll = false;
var id = $(".innavi_1 a").index($(this)) + 2; //声明ID等于当前值
... | }
function Touch_end(e) {
if (touch.move) {
touch.move = false;
var oy = touch.oy;
var y = touch.dy;
if (y - oy > 40) Win_wheel(e, 1, 0, 0);
else if (oy - y > 40) Win_wheel(e, -1, 0, 0);
}
}
/*鼠标滚动事件 delta=-1下 delta=1上*/
function Win_wheel(e, delta, deltaX, deltaY) {
... | touch.move = true;
touch.dy = e.pageY; | random_line_split |
page.js | Original) {
//$("#shuzitext").text("坑爹的!!!")
} else {
if (id > Original) {
dir = 1;
} else {
dir = -1;
}
curPage = menu_cur[id];
//$("#shuzitext").text("curPage"+curPage+"上一次值"+Original)
Page_ino... | alert(n)
$("#menu ul li").removeClass("cur")
$("#menu ul li").eq(n).addClass("cur")
for (var i = 0; i < 5; i++) { //导航添加背景置顶
$("#menu ul li").eq(i).css({"background-position": "right bottom"})
}
}
$("#menu ul li").click(function () {
//isScroll 防止点击过快
if (isScroll == true) {
... | identifier_body | |
page.js | //清空cur
for (var i = 0; i <= d; i++) {
$(".innavi_1 a").eq(i).addClass("cur").siblings().removeClass("cur") //每个ID添加cur样式
}
}
$(".innavi_1 a").click(function () {
if (isScroll == true) {
isScroll = false;
var id = $(".innavi_1 a").index($(this)) + 2; //声明ID等于当前值
Or... | //页面切换方法+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function Page_inout(page_index, page_out) {
//page_inde:下页数值,page_out:前面一个
//fun_out[page_out](); //动画出场数组里面放方法
var h = $(window).height() / 900;
var dir = page_index > page... | }
if (curPage > pageNum) {
curPage = pageNum;
return;
}
Page_inout(curPage, Original)
isScroll = false;
}
//延迟滚动。防止滚动很多次
$this.data('timeoutId', setTimeout(function () {
... | conditional_block |
index.js | var questionElems = $('#questions').children();
var noWildcardQuestions = [];
var wildcardQuestions = [];
questionElems.each(function () {
var qid = $(this).find('.col-md-12').attr('data-qid');
if (qid === "NUMBER") {
return;
}
var text = $(this).find('#questio... | (quiz, doc, qid, name, text, mark, genFeed, format, reqText, boxSize, graderInfo, responseTemplate) {
console.log(qid, name, text, mark, genFeed, format, reqText, boxSize, graderInfo, responseTemplate);
var q = doc.createElement('question');
q.setAttribute('type', 'essay');
// Question Name.
var ... | createXmlForQuestion | identifier_name |
index.js | lems.each(function () {
var qid = $(this).find('.col-md-12').attr('data-qid');
if (qid === "NUMBER") {
return;
}
var text = $(this).find('#question-text-' + qid).data('editor').getContents();
// If it has wildcards...
if (/{.*}/gi.test(text)) {
wi... | template.removeAttr('id');
template.html(function() { | random_line_split | |
index.js | var questionElems = $('#questions').children();
var noWildcardQuestions = [];
var wildcardQuestions = [];
questionElems.each(function () {
var qid = $(this).find('.col-md-12').attr('data-qid');
if (qid === "NUMBER") {
return;
}
var text = $(this).find('#questio... | } else {
var orWildcards = Array.from(text.matchAll(/{.*?[\|].*?}/gi));
var rangeWildcards = Array.from(text.matchAll(/{[\d-]+}/gi));
var orWildcardsFiltered = [];
// Filter out duplicate wildcard matches (when a user uses multiple of the same wildcard we treat them as one).... | {
// Takes in the XML creator and adds to it for the question.
var qid = qElem.find('.col-md-12').attr('data-qid');
if (qid === 'NUMBER') {
return;
}
var name = qElem.find('#question-name-' + qid).val();
var text = qElem.find('#question-text-' + qid).data('editor').getContents();
va... | identifier_body |
index.js | var questionElems = $('#questions').children();
var noWildcardQuestions = [];
var wildcardQuestions = [];
questionElems.each(function () {
var qid = $(this).find('.col-md-12').attr('data-qid');
if (qid === "NUMBER") {
return;
}
var text = $(this).find('#questio... | else {
noWildcardQuestions.push($(this));
}
});
// Concat the wildcard at the end.
noWildcardQuestions.concat(wildcardQuestions).forEach(function(elem) { getQuestion(quiz, doc, $(elem)) });
doc.appendChild(quiz);
var serializer = new XMLSerializer();
var xmlString = seria... | {
wildcardQuestions.push($(this));
} | conditional_block |
main.rs | ::cpu_id() == 0 {
// boot11::start_cpu(1, _start);
// loop {}
// }
common::start();
busy_sleep(1000);
let fb_top = core::slice::from_raw_parts_mut::<[u8; 3]>(0x18000000 as *mut _, SCREEN_TOP_FBSIZE / 3);
init_screens(fb_top);
{
for (pixel, ferris_pixel) in fb_top.ite... |
if pad.down_once() {
self.decrement();
}
}
fn set_value(&mut self, value: u32) {
self.value = value;
}
fn value(&self) -> u32 {
self.value
}
}
pub unsafe fn init_screens(top_fb: &mut [[u8; 3]]) {
let brightness_level = 0xFEFE;
(*(0x10141200 a... | {
self.increment();
} | conditional_block |
main.rs | = core::slice::from_raw_parts_mut::<[u8; 3]>(0x18000000 as *mut _, SCREEN_TOP_FBSIZE / 3);
init_screens(fb_top);
{
for (pixel, ferris_pixel) in fb_top.iter_mut().zip(FERRIS.chunks(3)) {
write_volatile(&mut pixel[0], ferris_pixel[2]);
write_volatile(&mut pixel[1], ferris_pixel[... | top_fb_conf.set_buffer_stride(0x2D0);
top_fb_conf.reg(0x9C).write(0); | random_line_split | |
main.rs | ::cpu_id() == 0 {
// boot11::start_cpu(1, _start);
// loop {}
// }
common::start();
busy_sleep(1000);
let fb_top = core::slice::from_raw_parts_mut::<[u8; 3]>(0x18000000 as *mut _, SCREEN_TOP_FBSIZE / 3);
init_screens(fb_top);
{
for (pixel, ferris_pixel) in fb_top.ite... | (&mut self, f: impl FnOnce(&mut u32)) {
let pos = self.cursor_pos * 4;
// Extract digit
let mut digit = (self.value >> pos) & 0xF;
f(&mut digit);
digit &= 0xF;
// Clear digit
self.value &= !(0xF << pos);
// Insert digit
self.value |= digit << p... | modify | identifier_name |
main.rs | impl FnOnce(&mut u32)) {
let pos = self.cursor_pos * 4;
// Extract digit
let mut digit = (self.value >> pos) & 0xF;
f(&mut digit);
digit &= 0xF;
// Clear digit
self.value &= !(0xF << pos);
// Insert digit
self.value |= digit << pos;
}
... | {
let c = n.to_be_bytes();
[c[0], c[1], c[2]]
} | identifier_body | |
call.rs | (fd: usize) -> Result<usize> {
unsafe { syscall1(SYS_CLOSE, fd) }
}
/// Get the current system time
pub fn clock_gettime(clock: usize, tp: &mut TimeSpec) -> Result<usize> {
unsafe { syscall2(SYS_CLOCK_GETTIME, clock, tp as *mut TimeSpec as usize) }
}
/// Copy and transform a file descriptor
pub fn dup(fd: usi... | close | identifier_name | |
call.rs | Result<usize> {
syscall3(SYS_FMAP, fd, map as *const Map as usize, mem::size_of::<Map>())
}
/// Unmap whole (or partial) continous memory-mapped files
pub unsafe fn funmap(addr: usize, len: usize) -> Result<usize> {
syscall2(SYS_FUNMAP, addr, len)
}
/// Retrieve the canonical path of a file
pub fn fpath(fd: ... | {
unsafe { syscall2(SYS_SETRENS, rns, ens) }
} | identifier_body | |
call.rs | unsafe { syscall2(SYS_CLOCK_GETTIME, clock, tp as *mut TimeSpec as usize) }
}
/// Copy and transform a file descriptor
pub fn dup(fd: usize, buf: &[u8]) -> Result<usize> {
unsafe { syscall3(SYS_DUP, fd, buf.as_ptr() as usize, buf.len()) }
}
/// Copy and transform a file descriptor
pub fn dup2(fd: usize, newfd... | }
/// Get the current system time
pub fn clock_gettime(clock: usize, tp: &mut TimeSpec) -> Result<usize> { | random_line_split | |
frame_info.rs | > = Default::default();
}
#[derive(Default)]
pub struct GlobalFrameInfo {
/// An internal map that keeps track of backtrace frame information for
/// each module.
///
/// This map is morally a map of ranges to a map of information for that
/// module. Each module is expected to reside in a disjoint... |
}
};
// In debug mode for now assert that we found a mapping for `pc` within
// the function, because otherwise something is buggy along the way and
// not accounting for all the instructions. This isn't super critical
// though so we can omit this check in release ... | {
None
} | conditional_block |
frame_info.rs | > = Default::default();
}
#[derive(Default)]
pub struct GlobalFrameInfo {
/// An internal map that keeps track of backtrace frame information for
/// each module.
///
/// This map is morally a map of ranges to a map of information for that
/// module. Each module is expected to reside in a disjoint... |
/// Process the frame info in case is not yet processed
pub fn maybe_process_frame(&mut self, pc: usize) -> Option<()> {
let module = self.module_info_mut(pc)?;
let func = module.function_info(pc)?;
let func_local_index = func.local_index;
module.process_function_debug_info(fun... | {
let module = self.module_info(pc)?;
let func = module.function_info(pc)?;
let extra_func_info = module.function_debug_info(func.local_index);
Some(extra_func_info.is_unprocessed())
} | identifier_body |
frame_info.rs | .range(pc..).next()?;
if pc < func.start || *end < pc {
return None;
}
Some(func)
}
}
struct FunctionInfo {
start: usize,
local_index: LocalFunctionIndex,
}
impl GlobalFrameInfo {
/// Fetches frame information about a program counter in a backtrace.
///
/// ... | random_line_split | ||
frame_info.rs | > = Default::default();
}
#[derive(Default)]
pub struct | {
/// An internal map that keeps track of backtrace frame information for
/// each module.
///
/// This map is morally a map of ranges to a map of information for that
/// module. Each module is expected to reside in a disjoint section of
/// contiguous memory. No modules can overlap.
///
... | GlobalFrameInfo | identifier_name |
simpletree.component.ts | .declareTreeLayout();
this.assignRootPositions();
this.updateTree(this.root);
}
getWorkflowMeta() {
this.workflowService.getWorkflowMeta()
.subscribe(
meta => { this.meta = meta; },
error => this.errorMessage = <any>error);
}
getStates() {
this.workflowService.getStates()... |
/* Sets new dimensions for tree
* Params: (all optional) height and width of window and node object after window resize */
setDimensions(newHeight?, newWidth?, nodeH?, nodeW?) {
// this.margin = {top: 20, right: 20, bottom: 20, left: 20};
newHeight != null ? this.height = newHeight - this.margin.top... | {
this.margin = {top: 20, right: 20, bottom: 20, left: 20};
this.height = window.innerHeight - 50 - this.margin.top - this.margin.bottom;
this.width = window.innerWidth - this.margin.right - this.margin.left;
// this.nHeight = 40;
// this.nWidth = 220;
this.nHeight = window.innerHeight / 18;
... | identifier_body |
simpletree.component.ts | this.nHeight = nodeH;
}
onResize(event) {
const d3 = this.d3;
let nodeH = 0, nodeW;
const newHeight = event.target.innerHeight - 50;
console.log('newHeight %i', newHeight);
const newWidth = event.target.innerWidth - 50;
console.log('newWidth %i', newWidth);
(newHeight < 740) ? nodeH... | let link = this.svg.selectAll('.link') | random_line_split | |
simpletree.component.ts | .declareTreeLayout();
this.assignRootPositions();
this.updateTree(this.root);
}
getWorkflowMeta() {
this.workflowService.getWorkflowMeta()
.subscribe(
meta => { this.meta = meta; },
error => this.errorMessage = <any>error);
}
getStates() {
this.workflowService.getStates()... | (source, destination) {
console.log(source);
console.log(destination);
var x = destination.x + 150 / 2;
var y = destination.y;
var px = source.x + 40 / 2;
var py = source.y + 40;
return 'M' + x + ',' + y
+ 'C' + x + ',' + (y + py) / 2
+ ' ' + x + ',' + (y + py) / 2
+ ' ' + ... | diagonal | identifier_name |
dataCreationHelpers.js |
* @param {Direction} direction Direction or Direction id for the Trip (from -> to vs to -> from)
* @param {callback} direction.resolveTripSymbol Takes the route to create a directional Trip symbol
* (e.g. to->[(via)]->from or from->[(via)]->to
* @param {Service|String} service The Service or Service id of the Trip... | * @returns {Duration} The calculated arrival Duration relative to 00:00:00
*/
const calculateArrivalDuration = (stop, previousStopTime, distanceFromPreviousStop) => {
if (stop.arrivalTime) { | random_line_split | |
dataCreationHelpers.js | param {Service|String} service The Service or Service id of the Trip
* @returns {String} The trip id
*/
export const createTripId = (route, direction, service) => {
return [
direction.resolveTripSymbol(route),
service.label
].join(' ');
};
/**
* @typedef {Object} Trip
* @property {Route} ro... | {
return moment.duration(endDuration);
} | conditional_block | |
config.go | .funcs
return fn
}
// Parse 方法执行全部配置解析函数,如果其中解析函数返回err,则停止解析并返回err。
func (c *configMap) Parse() (err error) {
for _, fn := range c.funcs {
err = fn(c)
if err != nil {
c.Print(err)
return
}
}
return nil
}
// MarshalJSON 实现json.Marshaler接口,试json序列化直接操作保存的数据。
func (c *configMap) MarshalJSON() ([]byte, er... | ch iValue.Kind() {
ca | conditional_block | |
config.go | type ConfigParseFunc func(Config) error
/*
Config defines configuration management and uses configuration read-write and analysis functions.
Get/Set read and write data implementation:
Use custom map or struct as data storage
Support Lock concurrency safety
Access attributes based on string path hierarchy
The def... | )
// ConfigParseFunc 定义配置解析函数。
//
// Config 默认解析函数为eudore.ConfigAllParseFunc | random_line_split | |
config.go | RLock()
RUnlock()
}
// NewConfigMap 创建一个ConfigMap,如果传入参数为map[string]interface{},则作为初始化数据。
//
// ConfigMap将使用传入的map作为配置存储去Get/Set一个键值。
//
// ConfigMap已实现json.Marshaler和json.Unmarshaler接口.
func NewConfigMap(arg interface{}) Config {
var keys map[string]interface{}
if ks, ok := arg.(map[string]interface{}); ok {
ke... | ParseArgs 函数使用参数设置配置,参数使用'--'为前缀。
//
// 如果结构体存在flag tag将作为该路径的缩写,tag长度小于5使用'-'为前缀。
func ConfigParseArgs(c Config) (err error) {
flag := &eachTags{tag: "flag", Repeat: make(map[uintptr]string)}
flag.Each("", reflect.ValueOf(c.Get("")))
short := make(map[string][]string)
for i, tag := range flag.Tags {
short[flag.V... | onfig | identifier_name |
config.go | RLock()
RUnlock()
}
// NewConfigMap 创建一个ConfigMap,如果传入参数为map[string]interface{},则作为初始化数据。
//
// ConfigMap将使用传入的map作为配置存储去Get/Set一个键值。
//
// ConfigMap已实现json.Marshaler和json.Unmarshaler接口.
func NewConfigMap(arg interface{}) Config {
var keys map[string]interface{}
if ks, ok := arg.(map[string]interface{}); ok {
ke... | a []byte) error {
c.Lock()
defer c.Unlock()
return json.Unmarshal(data, &c.Keys)
}
func configPrint(c Config, args ...interface{}) {
c.Set("print", fmt.Sprint(args...))
}
// ConfigParseJSON 方法解析json文件配置。
func ConfigParseJSON(c Config) error {
configPrint(c, "config read paths: ", c.Get("config"))
for _, path :=... | UnmarshalJSON 实现json.Unmarshaler接口,试json反序列化直接操作保存的数据。
func (c *configEudore) UnmarshalJSON(dat | identifier_body |
f3_modeling_report2.py | name(d6)
target = d6['RowMedian_FertilityRate'];target.head()
d7 = d6.drop(['RowMedian_FertilityRate', 'RowMean_FertilityRate',
'RowStd_FertilityRate','RowIQR_FertilityRate'], axis=1)
printrowname(d7)
"""Step 11_0: Apply PCA """
"""------------------------------------------------------------------------... |
plt.figure(figsize=(12, 6))
plt.subplot(1, 2, 1)
plt.title('Deviance of Gradient Boosting Regression Model')
plt.plot(np.arange(params['n_estimators']) + 1, clf.train_score_, 'b-',
label='Training Set Deviance')
plt.plot(np.arange(params['n_estimators']) + 1, test_score, 'r-',
label='Test Set Devian... | test_score[i] = clf.loss_(y_test, y_pred) | conditional_block |
f3_modeling_report2.py | rowname(d6)
target = d6['RowMedian_FertilityRate'];target.head()
d7 = d6.drop(['RowMedian_FertilityRate', 'RowMean_FertilityRate',
'RowStd_FertilityRate','RowIQR_FertilityRate'], axis=1)
printrowname(d7)
"""Step 11_0: Apply PCA """
"""---------------------------------------------------------------------... | label='Test Set Deviance')
plt.legend(loc='upper right')
plt.xlabel('Boosting Iterations')
plt.ylabel('Deviance')
"""ML 2: Extra Trees Regressor """
forest = ExtraTreesRegressor(n_estimators=250,random_state=0)
forest.fit(X_train,y_train)
"""ML 3: Random Forest Regressor """
rforest = RandomForestRegressor... | plt.plot(np.arange(params['n_estimators']) + 1, clf.train_score_, 'b-',
label='Training Set Deviance')
plt.plot(np.arange(params['n_estimators']) + 1, test_score, 'r-', | random_line_split |
lib.rs | Validator,
publisher_name: String,
message_router: MessageRouter<T>,
publisher: P,
}
impl<T, P> Hedwig<T, P>
where
P: Publisher,
{
/// Creates a new Hedwig instance
///
/// # Arguments
///
/// * `schema`: The JSON schema content. It's up to the caller to read the schema;
/// * ... | {
Ok(ValidatedMessage {
id: self.id.unwrap_or_else(Uuid::new_v4),
metadata: Metadata {
timestamp: self.timestamp.as_millis(),
publisher: publisher_name,
headers: self.headers.unwrap_or_else(HashMap::new),
},
schema,
... | identifier_body | |
lib.rs | serializer.serialize_str(format!("{}.{}", self.0, self.1).as_ref())
}
}
/// Mapping of message types to Hedwig topics
///
/// # Examples
/// ```
/// # use serde::Serialize;
/// # use strum_macros::IntoStaticStr;
/// use hedwig::{MajorVersion, MessageRouter};
///
/// # #[derive(Clone, Copy, IntoStaticStr, Hash, Pa... | {
hdrs.insert(header.into(), value.into());
} | conditional_block | |
lib.rs |
.resolve(&msg_schema_url)
.ok_or_else(|| Error::SchemaUrlResolve(msg_schema_url))?;
let msg_data = serde_json::to_value(&message.data).map_err(Error::MessageSerialize)?;
let validation_state = msg_schema.validate(&msg_data);
if !validation_state.is_strictly_valid() {
... | }
}
}
| random_line_split | |
lib.rs | , Hash, PartialEq, serde::Serialize)]
pub struct MajorVersion(pub u8);
impl fmt::Display for MajorVersion {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.0)
}
}
/// Minor part component in semver
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Serialize)]
pub str... | new | identifier_name | |
bundler.py | to talk to the LTA DB
lta_rc = ClientCredentialsAuth(address=self.lta_rest_url,
token_url=self.lta_auth_openid_url,
client_id=self.client_id,
client_secret=self.client_secret,
... | count = count + 1
file_catalog_uuid = metadata_record["file_catalog_uuid"]
fc_response = await fc_rc.request('GET', f'/api/files/{file_catalog_uuid}')
self.logger.info(f"Writing File Catalog record {file_catalog_uuid} to '{metadata_file_path}'")
... | conditional_block | |
bundler.py | :
"""
Create a Bundler component.
config - A dictionary of required configuration values.
logger - The object the bundler should use for logging.
"""
super(Bundler, self).__init__("bundler", config, logger)
self.file_catalog_client_id = config["FILE_CATALOG_CLIEN... | num_files = len(lta_response["results"])
done = (num_files == 0)
skip = skip + num_files
self.logger.info(f'LTA returned {num_files} Metadata documents to process.')
# for each Metadata record returned by the LTA DB
for met... | Path(bundle_file_path).unlink(missing_ok=True)
# 2. Create a ZIP bundle by writing constituent files to it
bundle_uuid = bundle["uuid"]
request_path = bundle["path"]
count = 0
done = False
limit = CREATE_CHUNK_SIZE
skip = 0
self.logger.info(f"Creating bun... | identifier_body |
bundler.py | :
"""
Create a Bundler component.
config - A dictionary of required configuration values.
logger - The object the bundler should use for logging.
"""
super(Bundler, self).__init__("bundler", config, logger)
self.file_catalog_client_id = config["FILE_CATALOG_CLIEN... | (self) -> Dict[str, Optional[str]]:
"""Bundler provides our expected configuration dictionary."""
return EXPECTED_CONFIG
@wtt.spanned()
async def _do_work(self) -> None:
"""Perform a work cycle for this component."""
self.logger.info("Starting work on Bundles.")
work_cla... | _expected_config | identifier_name |
bundler.py | :
"""
Create a Bundler component.
config - A dictionary of required configuration values.
logger - The object the bundler should use for logging.
"""
super(Bundler, self).__init__("bundler", config, logger)
self.file_catalog_client_id = config["FILE_CATALOG_CLIEN... | @wtt.spanned()
async def _do_work(self) -> None:
"""Perform a work cycle for this component."""
self.logger.info("Starting work on Bundles.")
work_claimed = True
while work_claimed:
work_claimed = await self._do_work_claim()
# if we are configured to run o... |
def _expected_config(self) -> Dict[str, Optional[str]]:
"""Bundler provides our expected configuration dictionary."""
return EXPECTED_CONFIG
| random_line_split |
lib.rs | pub plugin_data: P::DocumentData,
}
/// Information needed to configure a document page.
#[derive(Debug)]
pub struct PageInfo<P: ZathuraPlugin + ?Sized> {
pub width: f64,
pub height: f64,
pub plugin_data: P::PageData,
}
/// Trait to be implemented by Zathura plugins.
pub trait ZathuraPlugin {
/// ... | <P: ZathuraPlugin>(
document: *mut zathura_document_t,
_data: *mut c_void,
) -> zathura_error_t {
wrap(|| {
let doc = DocumentRef::from_raw(document);
let doc_data = &mut *(doc.plugin_data() as *mut P::DocumentData);
let result = P::document_free(doc, doc_... | document_free | identifier_name |
lib.rs | pub plugin_data: P::DocumentData,
}
/// Information needed to configure a document page.
#[derive(Debug)]
pub struct PageInfo<P: ZathuraPlugin + ?Sized> {
pub width: f64,
pub height: f64,
pub plugin_data: P::PageData,
}
/// Trait to be implemented by Zathura plugins.
pub trait ZathuraPlugin {
/// ... |
/// Render a page to a Cairo context.
pub unsafe extern "C" fn page_render_cairo<P: ZathuraPlugin>(
page: *mut zathura_page_t,
_data: *mut c_void,
cairo: *mut sys::cairo_t,
printing: bool,
) -> zathura_error_t {
wrap(|| {
let mut p = PageRef::from_raw(pa... | {
wrap(|| {
let result = {
let mut p = PageRef::from_raw(page);
let doc_data = &mut *(p.document().plugin_data() as *mut P::DocumentData);
let page_data = &mut *(p.plugin_data() as *mut P::PageData);
P::page_free(p, doc_data, page_data)... | identifier_body |
lib.rs | //! # use zathura_plugin::*;
//! struct PluginType {}
//!
//! impl ZathuraPlugin for PluginType {
//! type DocumentData = ();
//! type PageData = ();
//!
//! fn document_open(doc: DocumentRef<'_>) -> Result<DocumentInfo<Self>, PluginError> {
//! unimplemented!()
//! }
//!
//! fn page_init(pa... | //!
//! # Examples
//!
//! ``` | random_line_split | |
threads.go | (selg)
if stepInto {
for _, instr := range text {
if instr.Loc.File != topframe.Current.File || instr.Loc.Line != topframe.Current.Line || !instr.IsCall() {
continue
}
if instr.DestLoc != nil && instr.DestLoc.Fn != nil {
if err := setStepIntoBreakpoint(dbp, []AsmInstruction{instr}, cond); err != n... | {
loc, err := thread.Location()
if err != nil {
return false
}
return loc.Fn != nil && loc.Fn.Name == "runtime.breakpoint"
} | identifier_body | |
threads.go | Breakpoint is set on the CALL instruction,
// Continue will take care of setting a breakpoint to the destination
// once the CALL is reached.
func next(dbp Process, stepInto bool) error {
selg := dbp.SelectedGoroutine()
curthread := dbp.CurrentThread()
topframe, err := topframe(selg, curthread)
if err != nil {
re... | ThreadScope | identifier_name | |
threads.go | thread
// is blocked in the scheduler.
type ThreadBlockedError struct{}
func (tbe ThreadBlockedError) Error() string {
return ""
}
// returns topmost frame of g or thread if g is nil
func topframe(g *G, thread Thread) (Stackframe, error) {
var frames []Stackframe
var err error
if g == nil {
if thread.Blocked(... | }
}
}
if !csource {
deferreturns := []uint64{}
// Find all runtime.deferreturn locations in the function
// See documentation of Breakpoint.DeferCond for why this is necessary
for _, instr := range text {
if instr.IsCall() && instr.DestLoc != nil && instr.DestLoc.Fn != nil && instr.DestLoc.Fn.Name =... | if _, err := dbp.SetBreakpoint(instr.Loc.PC, StepBreakpoint, cond); err != nil {
if _, ok := err.(BreakpointExistsError); !ok {
return err
}
} | random_line_split |
threads.go | pointExistsError); !ok {
return err
}
}
}
}
}
if !csource {
deferreturns := []uint64{}
// Find all runtime.deferreturn locations in the function
// See documentation of Breakpoint.DeferCond for why this is necessary
for _, instr := range text {
if instr.IsCall() && instr.DestLoc != ni... | {
// we just want to check the condition on the goroutine id here
bp.Kind = NextBreakpoint
defer func() {
bp.Kind = NextDeferBreakpoint
}()
} | conditional_block | |
utxo_scanner_task.rs | ConnectingToBaseNode(peer.clone()));
debug!(
target: LOG_TARGET,
"Attempting UTXO sync with seed peer {} ({})", self.peer_index, peer,
);
match self.resources.comms_connectivity.dial_peer(peer.clone()).await {
Ok(conn) => Ok(conn),
Err(e) => {
... | (&self, client: &mut BaseNodeSyncRpcClient) -> Result<BlockHeader, UtxoScannerError> {
let chain_metadata = client.get_chain_metadata().await?;
let chain_height = chain_metadata.height_of_longest_chain();
let end_header = client.get_header_by_height(chain_height).await?;
let end_header =... | get_chain_tip_header | identifier_name |
utxo_scanner_task.rs | ) = {
let start = Instant::now();
let utxo_stream_next = utxo_stream.next().await;
utxo_next_await_profiling.push(start.elapsed());
utxo_stream_next
} {
if self.shutdown_signal.is_triggered() {
// if running is set to false, we know its... | {
let peer = self.peer_seeds.get(self.peer_index).map(NodeId::from_public_key);
self.peer_index += 1;
peer
} | identifier_body | |
utxo_scanner_task.rs | illis()),
);
self.update_scanning_progress_in_db(last_utxo_index, total_amount, num_recovered, end_header_hash)
.await?;
self.publish_event(UtxoScannerEvent::Progress {
current_index: (output_mmr_size - 1),
total_index: (output_mmr_size - 1),
});
... | let current_utxo_index = response
// Assumes correct ordering which is otherwise not required for this protocol
.last()
.ok_or_else(|| { | random_line_split | |
app.js | .then((snapshot) => {
console.log("ONCE SNAPSHOT", snapshot);
});
// We want to keep an eye on data that is constantly changing
var adminRef = firebase.database().ref("/packtpub/tweets");
adminRef.on("value", (snapshot) => {
console.log("REALTIME SNAPSHOT", snapshot);
});
// Can we add a reference to somethi... | })
.catch((err) => console.log(err));
}
};
input.addEventListener("change", uploadToFirebase);
}
// Downloading files from Firebase
// the filename and its extension need to be grabbed from a custom logic of your own.
// That is done by using a local database that holds a small metadata finger... | fileRef
.put(file)
.then(() => {
console.log("your images was uploaded !"); | random_line_split |
app.js | .then((snapshot) => {
console.log("ONCE SNAPSHOT", snapshot);
});
// We want to keep an eye on data that is constantly changing
var adminRef = firebase.database().ref("/packtpub/tweets");
adminRef.on("value", (snapshot) => {
console.log("REALTIME SNAPSHOT", snapshot);
});
// Can we add a reference to somethi... |
console.log("IMAGE URL TO FILE: ", url);
})
.catch((err) => console.log(err));
// Deleting a file
// just call imageRef.delete() ---> Returns a promise
// Getting file meta data
//No let's get the file metadata.
imageRef
.getMetadata()
.then((meta) => {
//Meta function parameter represent our file me... | {
imageTag.src = url;
} | conditional_block |
cli.rs | #[clap(long, default_value = "5", value_name = "secs")]
reload: ReloadStrategy,
/// Use verbose output (-vv for very verbose output)
#[clap(long = "verbose", short, parse(from_occurrences))]
verbosity: u32,
/// Kill this server once stdin is closed
///
/// While this server is running,... | {
info!("Failed to write error to {:?}: {}", p, e);
} | conditional_block | |
cli.rs | ::Server;
use crate::commit::Commit;
use crate::logdir::LogdirLoader;
use crate::proto::tensorboard::data;
use crate::server::DataProviderHandler;
use crate::types::PluginSamplingHint;
use data::tensor_board_data_provider_server::TensorBoardDataProviderServer;
pub mod dynamic_logdir;
use dynamic_logdir::DynLogdir;
... |
}
/// Exit code for failure of [`DynLogdir::new`].
// Keep in sync with docs on `Opts::logdir`.
const EXIT_BAD_LOGDIR: i32 = 8;
const EXIT_FAILED_TO_BIND: i32 = 9;
#[tokio::main]
pub async fn main() -> Result<(), Box<dyn std::error::Error>> {
let opts = Opts::parse();
init_logging(match opts.verbosity {
... | {
if s == "once" {
Ok(ReloadStrategy::Once)
} else {
Ok(ReloadStrategy::Loop {
delay: Duration::from_secs(s.parse()?),
})
}
} | identifier_body |
cli.rs | transport::Server;
use crate::commit::Commit;
use crate::logdir::LogdirLoader;
use crate::proto::tensorboard::data;
use crate::server::DataProviderHandler;
use crate::types::PluginSamplingHint;
use data::tensor_board_data_provider_server::TensorBoardDataProviderServer;
pub mod dynamic_logdir;
use dynamic_logdir::Dyn... | delay: Duration::from_secs(s.parse()?),
})
}
}
}
/// Exit code for failure of [`DynLogdir::new`].
// Keep in sync with docs on `Opts::logdir`.
const EXIT_BAD_LOGDIR: i32 = 8;
const EXIT_FAILED_TO_BIND: i32 = 9;
#[tokio::main]
pub async fn main() -> Result<(), Box<dyn std::error... | random_line_split | |
cli.rs | scan for event files (files matching the `*tfevents*` glob). This
/// directory, its descendants, and its event files will be periodically polled for new data.
///
/// If this log directory is invalid or unsupported, exits with status 8.
#[clap(long, setting(clap::ArgSettings::AllowEmptyValues))]
l... | init_logging | identifier_name | |
client.js | only");
} else {
$("#editContainer").hide();
$("#editView").html("Edit plot")
}
draw(lastData);
}
function aggregate(data) {
var aggregateFunc = Aggregate.id;
if (options["group"] == "week")
aggregateFunc = Aggregate.toYearWeek;
else if (options["group"] == "month")
a... | saveOptions | identifier_name | |
client.js | var parts = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for (var i = 0; i < parts.length; i++) {
if (parts[i].indexOf("=") >= 0) {
kv = parts[i].split('=');
vars[kv[0]] = decodeURIComponent(kv[1]);
} else {
if (parts[i].ind... |
}
var metricFunc = null;
if (options["metric"] == "count")
metricFunc = Aggregate.count;
else if (options["metric"] == "min")
metricFunc = Aggregate.min;
else if (options["metric"] == "max")
metricFunc = Aggregate.max;
else if (options["metric"] == "sum")
metric... | {
var val = data[j][i];
if (j == 0)
key = aggregateFunc(val)
else {
var multiValues = aggregate[key] || []; // default is []
var values = multiValues[j - 1] || []; // default is []
values.push(val);
multi... | conditional_block |
client.js | var parts = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for (var i = 0; i < parts.length; i++) {
if (parts[i].indexOf("=") >= 0) {
kv = parts[i].split('=');
vars[kv[0]] = decodeURIComponent(kv[1]);
} else {
if (parts[i].ind... | var row = [];
var sum = 0;
for (var j = 0; j < Object.keys(data).length; j++) {
val = data[j][i];
if (j == 0) {
if (typeof val == "number")
;
... | random_line_split | |
client.js | key = aggregateFunc(val)
else {
var multiValues = aggregate[key] || []; // default is []
var values = multiValues[j - 1] || []; // default is []
values.push(val);
multiValues[j - 1] = values;
aggregate[key] = multiValues;
... | {
var data = Format.parse(fileContents);
if (!Model.verify(data))
return;
lastData = data;
var drawData = lastData;
if (options["group"])
drawData = lastAggregateData = aggregate(data);
drawPlot(drawData);
} | identifier_body | |
tcp_client.go | .
package client
import (
"errors"
"fmt"
"math"
"time"
"github.com/uber-go/tally"
"github.com/m3db/m3/src/aggregator/sharding"
"github.com/m3db/m3/src/cluster/placement"
"github.com/m3db/m3/src/cluster/shard"
"github.com/m3db/m3/src/metrics/metadata"
"github.com/m3db/m3/src/metrics/metric/aggregated"
"gi... | c.metrics.shardNotOwned.Inc(1)
continue
}
if !c.shouldWriteForShard(timeNanos, shard) {
c.metrics.shardNotWriteable.Inc(1)
continue
}
if err = c.writerMgr.Write(instance, shardID, payload); err != nil {
multiErr = multiErr.Add(err)
continue
}
one | if !ok {
err = fmt.Errorf("instance %s does not own shard %d", instance.ID(), shardID)
multiErr = multiErr.Add(err) | random_line_split |
tcp_client.go | .
package client
import (
"errors"
"fmt"
"math"
"time"
"github.com/uber-go/tally"
"github.com/m3db/m3/src/aggregator/sharding"
"github.com/m3db/m3/src/cluster/placement"
"github.com/m3db/m3/src/cluster/shard"
"github.com/m3db/m3/src/metrics/metadata"
"github.com/m3db/m3/src/metrics/metric/aggregated"
"gi... | () (int, error) {
placement, err := c.placementWatcher.Get()
if err != nil {
return 0, err
}
if placement == nil {
return 0, errNilPlacement
}
return placement.Version(), nil
}
// Flush flushes any remaining data buffered by the client.
func (c *TCPClient) Flush() error {
c.metrics.flush.Inc(1)
return c.w... | ActivePlacementVersion | identifier_name |
tcp_client.go | .
package client
import (
"errors"
"fmt"
"math"
"time"
"github.com/uber-go/tally"
"github.com/m3db/m3/src/aggregator/sharding"
"github.com/m3db/m3/src/cluster/placement"
"github.com/m3db/m3/src/cluster/shard"
"github.com/m3db/m3/src/metrics/metadata"
"github.com/m3db/m3/src/metrics/metric/aggregated"
"gi... |
var (
instrumentOpts = opts.InstrumentOptions()
writerMgr instanceWriterManager
placementWatcher placement.Watcher
)
writerMgrScope := instrumentOpts.MetricsScope().SubScope("writer-manager")
writerMgrOpts := opts.SetInstrumentOptions(instrumentOpts.SetMetricsScope(writerMgrScope))
writerMgr, err... | {
return nil, err
} | conditional_block |
tcp_client.go | .
package client
import (
"errors"
"fmt"
"math"
"time"
"github.com/uber-go/tally"
"github.com/m3db/m3/src/aggregator/sharding"
"github.com/m3db/m3/src/cluster/placement"
"github.com/m3db/m3/src/cluster/shard"
"github.com/m3db/m3/src/metrics/metadata"
"github.com/m3db/m3/src/metrics/metric/aggregated"
"gi... |
// ActivePlacementVersion returns a copy of the currently active placement version. It is a far less expensive call
// than ActivePlacement, as it does not clone the placement.
func (c *TCPClient) ActivePlacementVersion() (int, error) {
placement, err := c.placementWatcher.Get()
if err != nil {
return 0, err
}
... | {
placement, err := c.placementWatcher.Get()
if err != nil {
return nil, 0, err
}
if placement == nil {
return nil, 0, errNilPlacement
}
return placement.Clone(), placement.Version(), nil
} | identifier_body |
functions.js | firstOffset) {
case 0:
return true;
default:
move(1, true);
return false;
}
default:
switch (lastOffset) {
case 0:
return true;
default:
move(-1, true);
return false;
}
}
default:
... | contains | identifier_name | |
functions.js | }
setCounter = function() {$bl(counter).text(getCurrentCell() + 1 + "/" + w.size());}
getCellOffset = function(i) { return parseInt($bl(w).eq(i).css("left"));}
getCurrentCell = function() {
var index = -1;
$bl(w).each(function(i, el) {
if (getCellOffset(i)==0) index = i;
});
re... | {
var objNameRoot = this.name;
var relatedObjs = $bl("." + objNameRoot + "_related");
relatedObjs.each(function(i) { //find which objects are related to the control the user just clicked on
var isVisible = [];
var classNames = $bl(relatedObjs[i]).attr("class").split(" ");
$bl(classNames).each(function... | identifier_body | |
functions.js | .init = function() {
w.each(function(i) {
switch (i) {
case 0:
$(this).css("left", 0);
break;
case w.size() - 1:
$(this).css("left", parseInt(w.eq(0).css("left")) - w.eq(0).width() - parseInt(w.eq(0).css("marginRight")));
break;
default:
$(this).css("left", ... |
$(".btnReplaced").not(".norm").eq(i).click(function(){
$(this).parents('form').append('<input type="hidden" name="' + $(this).find('a').attr('rel') + '" value="' + $(this).find('span').text() + '"');
$(this).parents("form").submit();
return false;
});
$(".btnReplaced").not(".norm").eq(i).bind(... | }
else {
thisSubmit.after('<span class="btn clearfix btnReplaced"><a rel="' + submitName + '" class="' + submitClass + '" href="' + formAction + '"><span>' + submitValue + '</span></a></span>');
}
| random_line_split |
wamrobot.py | PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
import logging, openravepy, numpy
from .. ... | the \tt blend_radius group to the input trajectory.
@param traj input trajectory
@return blended trajectory
"""
with self:
return self.trajectory_module.blendtrajectory(traj=traj, execute=False,
maxsmoothiter=maxsmoothiter, resolution=resolution,
... | zero and the controller must come to a stop at each waypoint. This adds | random_line_split |
wamrobot.py | ; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
import logging, openravepy, numpy
from .. import u... | (self, traj, timeout=None, blend=True, retime=True, limit_tolerance=1e-3, synchronize=True, **kw_args):
"""Execute a trajectory.
By default, this function retimes, blends, and adds the stop_on_stall
flag to all trajectories. This behavior can be overriden using the \tt
blend and \tt reti... | ExecuteTrajectory | identifier_name |
wamrobot.py | ; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
import logging, openravepy, numpy
from .. import u... |
cspec = traj.GetConfigurationSpecification()
return (has_group(cspec, 'affine_transform')
or has_group(cspec, 'affine_velocities')
or has_group(cspec, 'affine_accelerations'))
needs_arms = bool(active_manipulators)
needs_base = has_affine_dofs... | try:
cspec.GetGroupFromName(group_name)
return True
except openravepy.openrave_exception:
return False | identifier_body |
wamrobot.py | number of
num_waypoints = traj.GetNumWaypoints()
if num_waypoints < 2:
logging.warn('RetimeTrajectory received trajectory with less than 2 waypoints. Skipping retime.')
return traj
# Create a MacTrajectory with timestamps, joint values, velocities,
# accelerati... | manipulator.controller.Reset() | conditional_block | |
VerificationCtrl.js | 'Denmark',
'Djibouti',
'Dominica',
'Dominican Republic (the)',
'Ecuador',
'Egypt',
'El Salvador',
'Equatorial Guinea',
'Eritrea',
'Estonia',
'Ethiopia',
'Falkland Islands (the) [Malvinas]',
'Faroe Islands (the)',
'Fiji',
... | VerifiedStatus() {
| identifier_name | |
VerificationCtrl.js | input error object is empty (file input is valid)
// it will show a green checkmark. Otherwise hides the checkmark
function showUploadSuccess(formInputErrorObject, elementIdToAdjust) {
if (jQuery.isEmptyObject(formInputErrorObject)) {
$('#' + elementIdToAdjust).parent().children('md-icon').... | $('.trade1').show();
$('.trade2').show();
}else{ | conditional_block | |
VerificationCtrl.js | 'Chile',
'China',
'Christmas Island',
'Cocos (Keeling) Islands (the)',
'Colombia',
'Comoros (the)',
'Congo (the)',
'Congo (the Democratic Republic of the)',
'Cook Islands (the)',
'Costa Rica',
'Côte d\'Ivoire',
'Croatia',
'Cuba',
... | 'Seychelles',
'Sierra Leone',
'Singapore',
'Sint Maarten (Dutch part)',
'Slovakia',
'Slovenia',
'Solomon Islands',
'Somalia',
'South Africa',
'South Georgia and the South Sandwich Islands',
'South Sudan ',
'Spain',
'Sri Lanka',
... | 'Saudi Arabia',
'Senegal',
'Serbia',
| random_line_split |
VerificationCtrl.js | 'Chile',
'China',
'Christmas Island',
'Cocos (Keeling) Islands (the)',
'Colombia',
'Comoros (the)',
'Congo (the)',
'Congo (the Democratic Republic of the)',
'Cook Islands (the)',
'Costa Rica',
'Côte d\'Ivoire',
'Croatia',
'Cuba',
... |
vm.getLevelOneDetails = getLevelOneDetails;
function getLevelOneDetails() {
verificationService.getLevelOneDetails(function successBlock(data) {
console.log(data);
vm.verificationOne = {
firstName: | var data = {'test': 'true'};
verificationService.getVerification(data,function successBlock(data) {
vm.getVerificationData = data;
// console.log(data.verification_level)
if(data.verification_level == 1) {
};
}, function failureBlock(error) {
... | identifier_body |
runner.rs | 2 * thread_count`.
/// To override this behavior, call [`connection_count`](Self::connection_count)
pub fn connection_pool_builder<S: Into<String>>(
self,
database_url: S,
builder: r2d2::Builder<r2d2::ConnectionManager<PgConnection>>,
) -> Builder<Env, R2d2Builder> {
self.con... | <Env: 'static, ConnectionPool> {
connection_pool: ConnectionPool,
thread_pool: ThreadPool,
environment: Arc<Env>,
registry: Arc<Registry<Env>>,
job_start_timeout: Duration,
}
impl<Env> Runner<Env, NoConnectionPoolGiven> {
/// Create a builder for a job runner
///
/// This method takes t... | Runner | identifier_name |
runner.rs | 2 * thread_count`.
/// To override this behavior, call [`connection_count`](Self::connection_count)
pub fn connection_pool_builder<S: Into<String>>(
self,
database_url: S,
builder: r2d2::Builder<r2d2::ConnectionManager<PgConnection>>,
) -> Builder<Env, R2d2Builder> {
self.con... |
}
Ok(())
});
match job_run_result {
Ok(_) | Err(RollbackTransaction) => {}
Err(e) => {
panic!("Failed to update job: {:?}", e);
}
}
})
}
fn connection(&self) -> Resu... | {
eprintln!("Job {} failed to run: {}", job_id, e);
storage::update_failed_job(&conn, job_id);
} | conditional_block |
runner.rs |
/// The amount of time to wait for a job to start before assuming an error
/// has occurred.
///
/// Defaults to 10 seconds.
pub fn job_start_timeout(mut self, timeout: Duration) -> Self {
self.job_start_timeout = Some(timeout);
self
}
/// Provide a connection pool to be u... | {
self.thread_count.unwrap_or(5)
} | identifier_body | |
runner.rs | 2 * thread_count`.
/// To override this behavior, call [`connection_count`](Self::connection_count)
pub fn connection_pool_builder<S: Into<String>>(
self,
database_url: S,
builder: r2d2::Builder<r2d2::ConnectionManager<PgConnection>>,
) -> Builder<Env, R2d2Builder> {
self.con... | environment: Arc<Env>,
registry: Arc<Registry<Env>>,
job_start_timeout: Duration,
}
impl<Env> Runner<Env, NoConnectionPoolGiven> {
/// Create a builder for a job runner
///
/// This method takes the two required configurations, the database
/// connection pool, and the environment to pass t... | random_line_split | |
tool.ts | return result;
}
export const dealUpLowFirst: IDealUpLowFirst = (
res: Array<Array<string>> | Array<string>,
args: Array<SpellArg>
): void => {
if (_cnchar._.poly) {
dealResCase(res, low);
// 当启用了 多音词时 需要强制默认小写
// 因为会被覆盖
}
if (has(args, arg.first)) {
dealResCase(res... | } | random_line_split | |
tool.ts | = cnchar;
}
export function getCnChar () {
return _cnchar;
}
const NOT_CNCHAR: string = 'NOT_CNCHAR';
export function spell (dict: Json<string>, originArgs: Array<string>): string | Array<string> {
const strs = originArgs[0].split('');
const args = (originArgs.splice(1)) as Array<SpellArg>;
chec... | _cnchar | identifier_name | |
tool.ts | if (ssp.poly) { // 多音字模式 且 当前汉字是多音字
if (!res[i]) res[i] = [];
addIntoPolyRes(ssp.res);
let dsNew = ds;
const n = (dsNew.match(new RegExp(ch, 'g')) as Array<string>).length;
for (le... | n): {
spell: string, tone?: ToneType, index?: number
} => {
if (tone) {
return {spell};
}
for (let i = 0; i < spell.length; i++) {
const index: number = tones.indexOf(spell[i]);
if (index !== -1) { // 命中
return {
spell: spell.substr(0, i) + noTones[Mat... | ;
}
}
if (isTone) {
res.res = setTone(spell, pos, tone as ToneType);
}
return res;
}
function isDefaultSpell (word: string, spell: string) {
const def = Dict.spellDefault[word];
if (!def) return false;
return def === spell || (shapeSpell(def, true).replace(/[0-4]/, '') === s... | identifier_body |
tool.ts | res: Array<Array<string>> | Array<string>,
func:(str: string) => string
): void {
res.forEach((item: Array<string> | string, index: number) => {
if (typeof item !== 'string') {
if (item[0] !== NOT_CNCHAR) {
item.forEach((s, j) => {item[j] = func(s);});
}
... | let mes: string = `以下参数${txt}:${JSON.stringify(arr)};`;
if (txt === '被忽略' && type === 'stroke' && !has(args, 'order')) {
mes += ' 要启用笔顺模式必须使用 order 参数';
} else {
mes += ` 可选值 | conditional_block | |
lib.rs | - - - - - - | - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//! Frontend |
//! |
//! pikelet_concrete::parse::lexer
//! |
//! v
//! .---------------------------------------.
//! | pikelet_concrete::parse::lexer::Tok... | () -> Driver {
let context = Context::default();
let desugar_env = DesugarEnv::new(context.mappings());
Driver {
context,
desugar_env,
code_map: CodeMap::new(),
}
}
/// Create a new Pikelet environment, with the prelude loaded as well
pub... | new | identifier_name |
lib.rs | - - - - - | - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//! Frontend |
//! |
//! pikelet_concrete::parse::lexer
//! |
//! v
//! .---------------------------------------.
//! | pikelet_concrete::parse::lexer::Token... |
let raw_term = self.desugar(&concrete_term)?;
self.infer_term(&raw_term)
}
/// Normalize the contents of a file
pub fn normalize_file(
&mut self,
name: FileName,
src: String,
) -> Result<domain::RcValue, Vec<Diagnostic>> {
use pikelet_concrete::elaborate... | {
return Err(errors.iter().map(|error| error.to_diagnostic()).collect());
} | conditional_block |
lib.rs | - - - - - - | - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//! Frontend |
//! |
//! pikelet_concrete::parse::lexer
//! |
//! v
//! .---------------------------------------.
//! | pikelet_concrete::parse::lexer::Tok... | pub fn infer_file(
&mut self,
name: FileName,
src: String,
) -> Result<(core::RcTerm, domain::RcType), Vec<Diagnostic>> {
let file_map = self.code_map.add_filemap(name, src);
// TODO: follow import paths
let (concrete_term, _import_paths, errors) = pikelet_concret... | /// Infer the type of a file | random_line_split |
Histo.js | TabPane;
var DropdownButton = require('react-bootstrap').DropdownButton;
var MenuItem = require('react-bootstrap').MenuItem;
var Table = require('react-bootstrap').Table;
var Promise = require('es6-promise').Promise;
var Utils = require('./Utils');
var $ = require('jquery');
var d3 = require('d3');
require('../libs/d... |
} catch(error) {
console.log(error);
}
var path = svg.append("path")
.datum(values)
.attr("class", "line")
.attr("d", line);
path.each(function(d) { d.totalLength = this.getTotalLength(); }); // Add total length per path, needed for animating ov... | {
var withoutNull = _.without(values, 'NULL');
svg.append('circle')
.attr('class', 'sparkcircle')
.attr('cx', x(parseDate(withoutNull[withoutNull.length - 1].Date)))
.attr('cy', y(Number(withoutNull[withoutNull.length - 1].Score)))
... | conditional_block |
Histo.js | Value;
var line, lastValue;
var tooltipString = 'PI';
// if(values[values.length - 1].Value === 'NULL') {
// // Last value is NULL... do not draw this chart!
// return <div style={{display:'none'}} />;
// }
if(chartType === 'real') {
lastValu... | random_line_split | ||
Histo.js | TabPane;
var DropdownButton = require('react-bootstrap').DropdownButton;
var MenuItem = require('react-bootstrap').MenuItem;
var Table = require('react-bootstrap').Table;
var Promise = require('es6-promise').Promise;
var Utils = require('./Utils');
var $ = require('jquery');
var d3 = require('d3');
require('../libs/d... |
var max = d3.max(values, function(d) { return Number(d.Abs); });
if(self.state.referenceValue && chartType === 'real') {
svg.append('line')
.attr({
x1: xAxis.scale()(0),
y1: yAxis.scale()((self.state.referenceValue * max) / 100),
... | {
var x0 = x.invert(d3.mouse(this)[0]),
i = bisectDate(values, x0, 1),
d0 = values[i - 1],
d1 = values[i],
d = x0 - d0.Date > d1.Date - x0 ? d1 : d0;
if(chartType === 'pi') {
focus.attr("transform", "translate(" + x... | identifier_body |
Histo.js | TabPane;
var DropdownButton = require('react-bootstrap').DropdownButton;
var MenuItem = require('react-bootstrap').MenuItem;
var Table = require('react-bootstrap').Table;
var Promise = require('es6-promise').Promise;
var Utils = require('./Utils');
var $ = require('jquery');
var d3 = require('d3');
require('../libs/d... | () {
var x0 = x.invert(d3.mouse(this)[0]),
i = bisectDate(values, x0, 1),
d0 = values[i - 1],
d1 = values[i],
d = x0 - d0.Date > d1.Date - x0 ? d1 : d0;
if(chartType === 'pi') {
focus.attr("transform", "translate(" ... | mousemove | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.