file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
routes.go | /*
* Tencent is pleased to support the open source community by making Blueking Container Service available.
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except
* in compliance with the License. You may obta... | route.GET("/nodes/:node/cpu_usage", rest.RestHandlerFunc(metrics.GetNodeCPUUsage))
route.GET("/nodes/:node/cpu_request_usage", rest.RestHandlerFunc(metrics.GetNodeCPURequestUsage))
route.GET("/nodes/:node/memory_usage", rest.RestHandlerFunc(metrics.GetNodeMemoryUsage))
route.GET("/nodes/:node/memory_request_usa... | route.GET("/disk_usage", rest.RestHandlerFunc(metrics.ClusterDiskUsage))
route.GET("/diskio_usage", rest.RestHandlerFunc(metrics.ClusterDiskioUsage))
route.GET("/pod_usage", rest.RestHandlerFunc(metrics.ClusterPodUsage))
route.GET("/nodes/:node/info", rest.RestHandlerFunc(metrics.GetNodeInfo))
route.GET("/nod... | random_line_split |
routes.go | /*
* Tencent is pleased to support the open source community by making Blueking Container Service available.
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except
* in compliance with the License. You may obta... | ).Set("Content-Type", "application/json; charset=utf-8")
json.NewEncoder(w).Encode(gw.TargetGroups())
})
return router
}
// HealthyHandler 健康检查
func HealthyHandler(c *gin.Context) {
c.Data(http.StatusOK, "text/plain; charset=utf-8", []byte("OK"))
}
// ReadyHandler 健康检查
func ReadyHandler(c *gin.Context) {
c.Dat... | equest) {
w.Header( | identifier_name |
routes.go | /*
* Tencent is pleased to support the open source community by making Blueking Container Service available.
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except
* in compliance with the License. You may obta... | y/targetgroups", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
json.NewEncoder(w).Encode(gw.TargetGroups())
})
return router
}
// HealthyHandler 健康检查
func HealthyHandler(c *gin.Context) {
c.Data(http.StatusOK, "text/plain; charset=utf-8", []byt... | iddleware.ProjectAuthorization())
engine.Use(ginTracing.Middleware("bcs-monitor-api"))
// 命名规范
// usage 代表 百分比
// used 代表已使用
// overview, info 数值量
route := engine.Group("/metrics/projects/:projectCode/clusters/:clusterId")
{
route.GET("/overview", rest.RestHandlerFunc(metrics.GetClusterOverview))
route.GET... | identifier_body |
routes.go | /*
* Tencent is pleased to support the open source community by making Blueking Container Service available.
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except
* in compliance with the License. You may obta... |
return a.srv.Serve(dualStackListener)
}
// Close :
func (a *APIServer) Close() error {
return a.srv.Shutdown(a.ctx)
}
// newRoutes xxx
// @Title BCS-Monitor OpenAPI
// @BasePath /bcsapi/v4/monitor/api/projects/:projectId/clusters/:clusterId
func (a *APIServer) newRoutes(engine *gin.Engine) {
// 添加 X-Request-I... | {
v6Addr := utils.GetListenAddr(a.addrIPv6, a.port)
if err := dualStackListener.AddListenerWithAddr(v6Addr); err != nil {
return err
}
logger.Infof("api serve dualStackListener with ipv6: %s", v6Addr)
} | conditional_block |
pysnake.py | import math
import curses
import random
import asyncio
# from asyncsnake import LockstepConsumers
from asyncsnake import run_coroutines, WaitMap
# from cursessnake import CursesCharacters
from cursessnake import wrapper
class GameOver(Exception):
pass
UP = 0-1j
RIGHT = 1+0j
DOWN = 0+1j
LEFT = -1+0j
INITIAL_LE... |
else:
break
res.reverse()
return res or [0]
def route_to(self, target):
parent = {self.pos: None}
def backtrack(p):
res = []
while parent[p]:
d, p = parent[p]
... | d = d * r
p += d
res.append(d)
break | conditional_block |
pysnake.py | import math
import curses
import random
import asyncio
# from asyncsnake import LockstepConsumers
from asyncsnake import run_coroutines, WaitMap
# from cursessnake import CursesCharacters
from cursessnake import wrapper
class GameOver(Exception):
pass
UP = 0-1j
RIGHT = 1+0j
DOWN = 0+1j
LEFT = -1+0j
INITIAL_LE... |
def main(stdscr):
level = Level(stdscr)
class Snake:
def __init__(self, pos=None, dir=None, controls=None, speed=None, length=None):
self.wait = speed or 10
if pos is None:
self.pos = 0+0j
else:
self.pos = pos
if dir is ... | t = 0
n = [0] * len(snakes)
while True:
i = min(range(len(snakes)), key=lambda i: n[i])
if n[i] > t:
self.screen.refresh()
await asyncio.sleep(0.01 * (n[i] - t))
t = n[i]
try:
snakes[i].step()
... | identifier_body |
pysnake.py | import math
import curses
import random
import asyncio
# from asyncsnake import LockstepConsumers
from asyncsnake import run_coroutines, WaitMap
# from cursessnake import CursesCharacters
from cursessnake import wrapper
class GameOver(Exception):
pass
UP = 0-1j
RIGHT = 1+0j
DOWN = 0+1j
LEFT = -1+0j
INITIAL_LE... | raise SystemExit('\n'.join(
[str(msg),
# "You ate %s foods" % (len(the_snake.tail) - INITIAL_LENGTH),
# "You moved %s tiles" % the_snake.steps,
"Good job!!"]))
if __name__ == "__main__":
wrapper(main) | msg = 'Thanks for playing!'
| random_line_split |
pysnake.py | import math
import curses
import random
import asyncio
# from asyncsnake import LockstepConsumers
from asyncsnake import run_coroutines, WaitMap
# from cursessnake import CursesCharacters
from cursessnake import wrapper
class GameOver(Exception):
pass
UP = 0-1j
RIGHT = 1+0j
DOWN = 0+1j
LEFT = -1+0j
INITIAL_LE... | (self, pos):
pos = self.worm_holes.get(pos, pos)
return complex(pos.real % self.width, pos.imag % self.height)
async def play(self, snakes):
t = 0
n = [0] * len(snakes)
while True:
i = min(range(len(snakes)), key=lambda i: n[i])
if n[i] > t:
... | wrap_pos | identifier_name |
graph-with-comparison-new.component.ts | import {
AfterContentInit,
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
ElementRef,
Input,
ViewChild,
} from '@angular/core';
import { AbstractSubscriptionStoreComponent } from '@components/abstract-subscription-store.component';
import { AppUiStoreFacadeService } from '@legacy-import/src/lib/js/servic... | (value: readonly NumericTurnInfo[]) {
this.yourValues$$.next(value);
}
private maxYValue$$ = new BehaviorSubject<number>(null);
private stepSize$$ = new BehaviorSubject<number>(null);
private showYAxis$$ = new BehaviorSubject<boolean>(true);
private communityLabel$$ = new BehaviorSubject<string>('Community');
... | yourValues | identifier_name |
graph-with-comparison-new.component.ts | import {
AfterContentInit,
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
ElementRef,
Input,
ViewChild,
} from '@angular/core';
import { AbstractSubscriptionStoreComponent } from '@components/abstract-subscription-store.component';
import { AppUiStoreFacadeService } from '@legacy-import/src/lib/js/servic... |
const tooltipWidth = tooltipEl.getBoundingClientRect().width;
const tooltipHeight = tooltipEl.getBoundingClientRect().height;
const leftOffset = yourDatapoint?.parsed != null ? 0 : 50;
const tooltipLeft = Math.max(
0,
Math.min(
tooltip.caretX - tooltipWidth / 2 + leftOffs... | `;
const tableRoot = tooltipEl.querySelector('.content');
tableRoot.innerHTML = innerHtml; | random_line_split |
graph-with-comparison-new.component.ts | import {
AfterContentInit,
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
ElementRef,
Input,
ViewChild,
} from '@angular/core';
import { AbstractSubscriptionStoreComponent } from '@components/abstract-subscription-store.component';
import { AppUiStoreFacadeService } from '@legacy-import/src/lib/js/servic... |
const yourDatapoint = tooltip.dataPoints.find((dataset) => dataset.datasetIndex === 0);
const communityDatapoint = tooltip.dataPoints.find((dataset) => dataset.datasetIndex === 1);
let yourLabel: string = null;
let yourDelta: string = null;
let communityLabel: string = null;
let c... | {
tooltipEl.style.opacity = '0';
return;
} | conditional_block |
arabic.rs | //! Implementation of font shaping for Arabic scripts
//!
//! Code herein follows the specification at:
//! <https://github.com/n8willis/opentype-shaping-documents/blob/master/opentype-shaping-arabic-general.md>
use crate::error::{ParseError, ShapingError};
use crate::gsub::{self, FeatureMask, GlyphData, GlyphOrigin, ... | #[cfg(test)]
mod tests {
use super::*;
// https://www.unicode.org/reports/tr53/#Demonstrating_AMTRA.
mod reorder_marks {
use super::*;
#[test]
fn test_artificial() {
let cs = vec![
'\u{0618}', '\u{0619}', '\u{064E}', '\u{064F}', '\u{0654}', '\u{0658}', '... | }
| random_line_split |
arabic.rs | //! Implementation of font shaping for Arabic scripts
//!
//! Code herein follows the specification at:
//! <https://github.com/n8willis/opentype-shaping-documents/blob/master/opentype-shaping-arabic-general.md>
use crate::error::{ParseError, ShapingError};
use crate::gsub::{self, FeatureMask, GlyphData, GlyphOrigin, ... |
if arabic_glyphs[previous_i].is_left_joining() && arabic_glyphs[i].is_right_joining() {
arabic_glyphs[i].set_feature_tag(tag::FINA);
match arabic_glyphs[previous_i].feature_tag() {
tag::ISOL => arabic_glyphs[previous_i].set_feature_tag(tag::INIT),
... | {
continue;
} | conditional_block |
arabic.rs | //! Implementation of font shaping for Arabic scripts
//!
//! Code herein follows the specification at:
//! <https://github.com/n8willis/opentype-shaping-documents/blob/master/opentype-shaping-arabic-general.md>
use crate::error::{ParseError, ShapingError};
use crate::gsub::{self, FeatureMask, GlyphData, GlyphOrigin, ... | () {
let cs = vec![
'\u{0618}', '\u{0619}', '\u{064E}', '\u{064F}', '\u{0654}', '\u{0658}', '\u{0653}',
'\u{0654}', '\u{0651}', '\u{0656}', '\u{0651}', '\u{065C}', '\u{0655}', '\u{0650}',
];
let cs_exp = vec 实现简单的 KV 数据库
//! 为了防止 data race,将 IndexMap 用 Arc 进行包装
//! 具体实现可以参考:https://github.com/pingcap/talent-plan/blob/master/courses/rust/projects/project-2/src/kv.rs
use super::util::HandyRwLock;
use crate::{KvsError, Result};
use indexmap::IndexMap;
use serde::{Deseriali... | Err(KvsError::UnsupportCmdType)
}
} else {
Ok(None)
}
}
/// 查询 key 是否存在,如果存在,则记录 cmd 到日志,然后删除文件中的数据,再索引索引
fn delete(&mut self, k: String) -> Result<()> {
if self.index.contains_key(&k) {
let rm_cmd = Command::remove(k.clone());
... | } else { | random_line_split |
kv.rs | //! 通过 [indexmap](https://github.com/bluss/indexmap) 实现简单的 KV 数据库
//! 为了防止 data race,将 IndexMap 用 Arc 进行包装
//! 具体实现可以参考:https://github.com/pingcap/talent-plan/blob/master/courses/rust/projects/project-2/src/kv.rs
use super::util::HandyRwLock;
use crate::{KvsError, Result};
use indexmap::IndexMap;
use serde::{Deseriali... | mut entry_reader = reader.take(cmd_pos.len);
let len = std::io::copy(&mut entry_reader, &mut compaction_writer)?;
*cmd_pos = (compaction_gen, new_pos..new_pos + len).into();
new_pos += len;
}
compaction_writer.flush()?;
// 删除过期的日志文件
let stale_gens: V... | (cmd_pos.pos))?;
}
let | conditional_block |
kv.rs | //! 通过 [indexmap](https://github.com/bluss/indexmap) 实现简单的 KV 数据库
//! 为了防止 data race,将 IndexMap 用 Arc 进行包装
//! 具体实现可以参考:https://github.com/pingcap/talent-plan/blob/master/courses/rust/projects/project-2/src/kv.rs
use super::util::HandyRwLock;
use crate::{KvsError, Result};
use indexmap::IndexMap;
use serde::{Deseriali... | ult<Self> {
// 打开目录,查看目录中的日志文件列表,将其加载进 kvs
let using_path = path.into();
std::fs::create_dir_all(&using_path)?;
let mut readers = HashMap::new();
// 索引以 btree map 的形式存储在内存中
let mut index: BTreeMap<String, CommandPos> = BTreeMap::new();
let gen_list = sorted_gen_li... | Res | identifier_name |
output.rs | //! Types and functions related to graphical outputs
//!
//! This modules provides two main elements. The first is the
//! [`OutputHandler`](struct.OutputHandler.html) type, which is a
//! [`MultiGlobalHandler`](../environment/trait.MultiGlobalHandler.html) for
//! use with the [`init_environment!`](../macro.init_envir... | (info: &mut OutputInfo, event: Event) {
match event {
Event::Geometry {
x,
y,
physical_width,
physical_height,
subpixel,
model,
make,
transform,
} => {
info.location = (x, y);
info... | merge_event | identifier_name |
output.rs | //! Types and functions related to graphical outputs
//!
//! This modules provides two main elements. The first is the
//! [`OutputHandler`](struct.OutputHandler.html) type, which is a
//! [`MultiGlobalHandler`](../environment/trait.MultiGlobalHandler.html) for
//! use with the [`init_environment!`](../macro.init_envir... | /// included in [`new_default_environment!`](../macro.new_default_environment.html).
///
/// It aggregates the output information and makes it available via the
/// [`with_output_info`](fn.with_output_info.html) function.
pub struct OutputHandler {
outputs: Vec<(u32, Attached<WlOutput>)>,
status_listeners: Rc<R... | /// A handler for `wl_output`
///
/// This handler can be used for managing `wl_output` in the
/// [`init_environment!`](../macro.init_environment.html) macro, and is automatically | random_line_split |
output.rs | //! Types and functions related to graphical outputs
//!
//! This modules provides two main elements. The first is the
//! [`OutputHandler`](struct.OutputHandler.html) type, which is a
//! [`MultiGlobalHandler`](../environment/trait.MultiGlobalHandler.html) for
//! use with the [`init_environment!`](../macro.init_envir... |
});
}
fn notify_status_listeners(
output: &Attached<WlOutput>,
info: &OutputInfo,
mut ddata: DispatchData,
listeners: &RefCell<Vec<rc::Weak<RefCell<OutputStatusCallback>>>>,
) {
// Notify the callbacks listening for new outputs
listeners.borrow_mut().retain(|lst| {
if let Some(cb) ... | {
false
} | conditional_block |
memberweekactrank.py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
import sys, os, datetime, time
import logging
from optparse import OptionParser
import string, codecs
import subprocess
import MySQLdb
import json, phpserialize
import httplib, urllib, socket
from urlparse import urlparse
import re
def mklogfile(s):
if not os.path.exis... | (s):
logger.debug("sql# %s" % s)
cmd = 'hive -S -e "%(sql)s"' % {'sql':sqlEscape(s)}
proc = subprocess.Popen(cmd, shell=True, env=os.environ, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
hiveout, errmsg = proc.communicate()
retval = proc.wait()
if retval!=0:
logger.error("HiveError!!!(%d)" % retval... | runHiveQL | identifier_name |
memberweekactrank.py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
import sys, os, datetime, time
import logging
from optparse import OptionParser
import string, codecs
import subprocess
import MySQLdb
import json, phpserialize
import httplib, urllib, socket
from urlparse import urlparse
import re
def mklogfile(s):
if not os.path.exis... | esultset[userid]['topicnum'] = int(topicnum)
resultset[userid]['startopicnum'] = int(startopicnum)
resultset[userid]['isnewuser'] = 1 if userid in newusers else 0
sqlcursor.close()
dbconn.commit()
dbconn.close()
#计算活跃度得分
for item in resultset:
resultset[item]['score'] = getscore(resultset[item])
#计算排名(按活跃度得分从大... | rid)
r | conditional_block |
memberweekactrank.py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
import sys, os, datetime, time
import logging
from optparse import OptionParser
import string, codecs
import subprocess
import MySQLdb
import json, phpserialize
import httplib, urllib, socket
from urlparse import urlparse
import re
def mklogfile(s):
if not os.path.exis... |
retval = 0
##运行时变量
pid = os.getpid()
rundate = datetime.date.today().strftime("%Y%m%d")
rundir = os.path.dirname(os.path.abspath(__file__))
runfilename = os.path.splitext(os.path.split(os.path.abspath(__file__))[1])[0]
logdir = rundir + '/log'
tmpdir = rundir + '/tmp'
if not os.path.exists(logdir):
os.mkdir(logdir... | random_line_split | |
memberweekactrank.py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
import sys, os, datetime, time
import logging
from optparse import OptionParser
import string, codecs
import subprocess
import MySQLdb
import json, phpserialize
import httplib, urllib, socket
from urlparse import urlparse
import re
def mklogfile(s):
if not os.path.exis... |
reload(sys)
sys.setdefaultencoding('utf8')
retval = 0
##运行时变量
pid = os.getpid()
rundate = datetime.date.today().strftime("%Y%m%d")
rundir = os.path.dirname(os.path.abspath(__file__))
runfilename = os.path.splitext(os.path.split(os.path.abspath(__file__))[1])[0]
logdir = rundir + '/log'
tmpdir = rundir + '/tmp'
if ... | return int(t.get('topicnum',0)*WEIGHTS[c_topicnum][c_default] + \
t.get('commentnum',0)*WEIGHTS[c_commentnum][c_default] + \
t.get('startopicnum',0)*WEIGHTS[c_startopicnum][c_default] + \
t.get('isnewuser',0)*WEIGHTS[c_isnewuser][c_default]
) | identifier_body |
command.rs | use std::fmt::Display;
use GameContext;
use data::Walkability;
use engine::keys::{Key, KeyCode};
use ecs::traits::*;
use graphics::cell::{CellFeature, StairDest, StairDir};
use logic::Action;
use logic::entity::EntityQuery;
use point::{Direction, Point};
use world::traits::*;
use world::{self, World};
use super::debu... |
fn cmd_teleport(context: &mut GameContext) -> CommandResult<()> {
mes!(context.state.world, "Teleport where?");
let pos = select_tile(context, |_, _| ())?;
if context.state.world.can_walk(
pos,
Walkability::MonstersBlocking,
)
{
cmd_add_action(context, Action::Teleport(pos... | {
select_tile(context, maybe_examine_tile).map(|_| ())
} | identifier_body |
command.rs | use std::fmt::Display;
use GameContext;
use data::Walkability;
use engine::keys::{Key, KeyCode};
use ecs::traits::*;
use graphics::cell::{CellFeature, StairDest, StairDir};
use logic::Action;
use logic::entity::EntityQuery;
use point::{Direction, Point};
use world::traits::*;
use world::{self, World};
use super::debu... |
pub fn menu_choice(context: &mut GameContext, choices: Vec<String>) -> Option<usize> {
renderer::with_mut(|rc| {
rc.update(context);
rc.query(&mut ChoiceLayer::new(choices))
})
}
pub fn menu_choice_indexed<T: Display + Clone>(
context: &mut GameContext,
mut choices: Vec<T>,
) -> Comma... |
use renderer::ui::layers::ChoiceLayer; | random_line_split |
command.rs | use std::fmt::Display;
use GameContext;
use data::Walkability;
use engine::keys::{Key, KeyCode};
use ecs::traits::*;
use graphics::cell::{CellFeature, StairDest, StairDir};
use logic::Action;
use logic::entity::EntityQuery;
use point::{Direction, Point};
use world::traits::*;
use world::{self, World};
use super::debu... | (start: Point, end: Point, world: &mut World) {
world.marks.clear();
for pos in LineIter::new(start, end) {
world.marks.add(pos, Color::new(255, 255, 255));
}
world.marks.add(end, Color::new(255, 255, 255));
}
/// Allow the player to choose a tile.
pub fn select_tile<F>(context: &mut GameContex... | draw_line | identifier_name |
vanilla.py | # vanilla.py (DONOR)
# vanilla donor is the vanilla version of a donor
# that is, it uses unencrypted sockets, no SSL/TLS
# and performs the most basic operations (generic)
from . import ConceptDonor
import csv, json
import numpy, pandas
import socket
import traceback
from io import StringIO
import traceback
# sklear... |
except Exception as e:
self.expt(str(e),traceback.format_exc())
finally:
return self.hasNegotiated()
##############################################################################################
# These are common throughout almost all implementation and thus are imple... | self.verbose("Partitioned and computed the kernel",self.kernel.shape) | conditional_block |
vanilla.py | # vanilla.py (DONOR)
# vanilla donor is the vanilla version of a donor
# that is, it uses unencrypted sockets, no SSL/TLS
# and performs the most basic operations (generic)
from . import ConceptDonor
import csv, json
import numpy, pandas
import socket
import traceback
from io import StringIO
import traceback
# sklear... |
def partition_internals(self, s_point):
'''invokes a partition command to perform splitting of the data set into the train/test'''
if self._npdc is not None:
self._npdc.batch(s_point)
else:
self.error("Failed to partition. NPDC is null!")
def normalize_internal... | '''invokes a display command to display the internal content using any data controllers'''
if self._npdc is not None:
self._npdc.show()
if self._mnegform is not None:
self._mnegform.display() | identifier_body |
vanilla.py | # vanilla.py (DONOR)
# vanilla donor is the vanilla version of a donor
# that is, it uses unencrypted sockets, no SSL/TLS
# and performs the most basic operations (generic)
from . import ConceptDonor
import csv, json
import numpy, pandas
import socket
import traceback
from io import StringIO
import traceback
# sklear... | (self,ahostaddr):
'''start negotation, first sends in the donor's own prepared negform to inform the
central about the number of entries/features, it is expected that _mDmat is read
from a file/stdin before this
@params ahostaddr - a tuple ('localhost',portnumber i.e 8000)'''
_m... | negotiate | identifier_name |
vanilla.py | # vanilla.py (DONOR)
# vanilla donor is the vanilla version of a donor
# that is, it uses unencrypted sockets, no SSL/TLS
# and performs the most basic operations (generic)
from . import ConceptDonor
import csv, json
import numpy, pandas
import socket
import traceback
from io import StringIO
import traceback
# sklear... | self.error("Failed to receive ACKN from host. Terminating conntrain")
self.hasAlpha = False
else:
self.error("This donor has not synchronized the params with the central,\
please run negotiate( addr ) first !")
self.hasAlpha = False
... | self.hasAlpha = False
else:
#failed | random_line_split |
node.go | // KATO, Application Management Platform
// Copyright (C) 2021 Gridworkz Co., Ltd.
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the r... | (ctype NodeConditionType) *NodeCondition {
for _, con := range n.NodeStatus.Conditions {
if con.Type.Compare(ctype) {
return &con
}
}
return nil
}
// GetAndUpdateCondition get old condition and update it, if old condition is nil and then create it
func (n *HostNode) GetAndUpdateCondition(condType NodeConditi... | GetCondition | identifier_name |
node.go | // KATO, Application Management Platform
// Copyright (C) 2021 Gridworkz Co., Ltd.
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the r... |
//NodeConditionType
type NodeConditionType string
// These are valid conditions of node.
const (
// NodeReady means this node is working
NodeReady NodeConditionType = "Ready"
KubeNodeReady NodeConditionType = "KubeNodeReady"
NodeUp NodeConditionType = "NodeUp"
// InstallNotReady means the installati... | {
if len(h) == 0 {
return fmt.Errorf("node rule cannot be enpty")
}
for _, role := range h {
if !util.StringArrayContains(SupportNodeRule, role) {
return fmt.Errorf("node role %s can not be supported", role)
}
}
return nil
} | identifier_body |
node.go | // KATO, Application Management Platform
// Copyright (C) 2021 Gridworkz Co., Ltd.
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the r... |
}
return labels
}
// NodeSystemInfo is a set of ids/uuids to uniquely identify the node.
type NodeSystemInfo struct {
// MachineID reported by the node. For unique machine identification
// in the cluster this field is preferred. Learn more from man(5)
// machine-id: http://man7.org/linux/man-pages/man5/machine-... | {
labels[k] = v
} | conditional_block |
node.go | // KATO, Application Management Platform
// Copyright (C) 2021 Gridworkz Co., Ltd.
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the r... | //worker maintenance
Version string `json:"version"`
//worker maintenance example: unscheduler, offline
//Initiate a recommendation operation to the master based on the node state
AdviceAction []string `json:"advice_actions"`
//worker maintenance
Status string `json:"status"` //installed running offline unknown
... | type NodeStatus struct { | random_line_split |
main.rs | //#![feature(exclusive_range_pattern)]
#![feature(nll)]
extern crate fnv;
extern crate spmc;
extern crate unicode_skeleton;
#[macro_use]
extern crate clap;
use std::default::Default;
use std::vec::Vec;
use std::io::{self, BufReader, BufWriter};
use std::io::prelude::*;
use std::fs::File;
use std::thread;
use fnv::Fn... | filter_word(word:&str) -> Option<String> {
let mut success = true;
let res = Some(word.chars().map(|c| {
match encode(c) {
Some(_) => c,
None => {
let chars:Vec<char> = c.to_string().skeleton_chars().collect();
if chars.len() != 1 {
... | let matches = App::new(format!("Rust Word Rectangle Finder o{}x{}", WORD_SQUARE_WIDTH, WORD_SQUARE_HEIGHT))
.version(crate_version!())
.author(crate_authors!())
.about(crate_description!())
.setting(clap::AppSettings::SubcommandRequired)
.subcommand(SubCommand::with_name("compu... | identifier_body |
main.rs | //#![feature(exclusive_range_pattern)]
#![feature(nll)]
extern crate fnv;
extern crate spmc;
extern crate unicode_skeleton;
#[macro_use]
extern crate clap;
use std::default::Default;
use std::vec::Vec;
use std::io::{self, BufReader, BufWriter};
use std::io::prelude::*;
use std::fs::File;
use std::thread;
use fnv::Fn... | .setting(clap::AppSettings::SubcommandRequired)
.subcommand(SubCommand::with_name("compute")
.about("Does the actual computation.")
.arg(Arg::with_name("threads")
.default_value("4")
.takes_value(true)
.validator(|arg| {
... | .author(crate_authors!())
.about(crate_description!()) | random_line_split |
main.rs | //#![feature(exclusive_range_pattern)]
#![feature(nll)]
extern crate fnv;
extern crate spmc;
extern crate unicode_skeleton;
#[macro_use]
extern crate clap;
use std::default::Default;
use std::vec::Vec;
use std::io::{self, BufReader, BufWriter};
use std::io::prelude::*;
use std::fs::File;
use std::thread;
use fnv::Fn... | ernal:u32) -> CharSet {
return CharSet{internal}
}
fn add(&mut self, val:u8) {
if val > 31 {panic!("Invalid val {}", val)}
self.internal |= 2u32.pow(val as u32)
}
fn and(&self, other:&Self) -> Self {
Self{ internal: self.internal & other.internal }
}
fn has(&se... | int | identifier_name |
app.rs | use crate::connection;
use crate::debug_adapter_protocol as dap;
use crate::hsp_ext;
use crate::hsprt;
use crate::hspsdk;
use std;
use std::path::PathBuf;
use std::sync::mpsc;
use std::thread;
const MAIN_THREAD_ID: i64 = 1;
const MAIN_THREAD_NAME: &'static str = "main";
fn threads() -> Vec<dap::Thread> {
vec![dap... | r_ref(r: VarRef) -> Option<Self> {
match r {
1 => Some(VarPath::Globals),
i if i >= 2 => Some(VarPath::Static((i - 2) as usize)),
_ => None,
}
}
}
#[derive(Clone, Debug)]
pub(crate) struct RuntimeState {
file_name: Option<String>,
file_path: Option<String... | fn from_va | identifier_name |
app.rs | use crate::connection;
use crate::debug_adapter_protocol as dap;
use crate::hsp_ext;
use crate::hsprt;
use crate::hspsdk;
use std;
use std::path::PathBuf;
use std::sync::mpsc;
use std::thread;
const MAIN_THREAD_ID: i64 = 1;
const MAIN_THREAD_NAME: &'static str = "main";
fn threads() -> Vec<dap::Thread> {
vec![dap... | {
file_path,
file_name: Some(file_name),
line,
stopped: true,
};
self.send_pause_event();
}
Action::AfterConnected => {
self.is_connected = true;
self.s... | {
warn!("[app] リクエストではない DAP メッセージを無視");
}
Action::AfterStopped(file_name, line) => {
let file_path = self.resolve_file_path(&file_name);
self.state = RuntimeState | identifier_body |
app.rs | use crate::connection;
use crate::debug_adapter_protocol as dap;
use crate::hsp_ext;
use crate::hsprt;
use crate::hspsdk;
use std;
use std::path::PathBuf;
use std::sync::mpsc;
use std::thread;
const MAIN_THREAD_ID: i64 = 1;
const MAIN_THREAD_NAME: &'static str = "main";
fn threads() -> Vec<dap::Thread> {
vec![dap... | .iter()
.map(|name| name.as_str())
.collect::<Vec<&str>>(),
);
self.source_map = Some(source_map);
}
/// ファイル名を絶対パスにする。
/// FIXME: common 以下や 無修飾 include パスに対応する。
fn resolve_file_path(&self, file_name: &String) -> Option<String> {
... | let file_names = debug_info.file_names();
source_map.add_search_path(PathBuf::from(&args.program).parent());
source_map.add_file_names(
&file_names | random_line_split |
CanvasState.ts | import Shape from './Shape'
import * as $ from 'jquery'
export default class CanvasState {
canvas:any;
width:number;
height:number;
ctx:any;
stylePaddingLeft:number;
stylePaddingTop:number;
styleBorderLeft:number;
styleBorderTop:number;
ht... | myState.selection.y = mouse.y - myState.dragoffy;
myState.valid = false; // Something's dragging so we must redraw
} else if (myState.drawing) {
var mouse = myState.getMouse(e);
// Add temp shape
var _h = Math.abs(mouse.y - mySt... | // We don't want to drag the object by its top-left corner, we want to drag it
// from where we clicked. Thats why we saved the offset and use it here
myState.selection.x = mouse.x - myState.dragoffx; | random_line_split |
CanvasState.ts | import Shape from './Shape'
import * as $ from 'jquery'
export default class CanvasState {
canvas:any;
width:number;
height:number;
ctx:any;
stylePaddingLeft:number;
stylePaddingTop:number;
styleBorderLeft:number;
styleBorderTop:number;
... |
registerListeners = () => {
var myState = this;
var canvas = this.canvas;
//fixes a problem where double clicking causes text to get selected on the canvas
canvas.addEventListener('selectstart', function (e) { e.preventDefault(); return false; }, false);
// Up, down, and mo... | {
// **** First some setup! ****
this.canvas = canvas;
this.width = canvas.width;
this.height = canvas.height;
this.ctx = canvas.getContext('2d');
// This complicates things a little but but fixes mouse co-ordinate problems
// when there's a border or padding. See... | identifier_body |
CanvasState.ts | import Shape from './Shape'
import * as $ from 'jquery'
export default class CanvasState {
canvas:any;
width:number;
height:number;
ctx:any;
stylePaddingLeft:number;
stylePaddingTop:number;
styleBorderLeft:number;
styleBorderTop:number;
... | (canvas) {
// **** First some setup! ****
this.canvas = canvas;
this.width = canvas.width;
this.height = canvas.height;
this.ctx = canvas.getContext('2d');
// This complicates things a little but but fixes mouse co-ordinate problems
// when there's a border or pad... | constructor | identifier_name |
stack.rs | // Copied from:
// rust/src/librustrt/stack.rs
// git: 70cef9474a3307ec763efc01fe6969e542083823
// stack_exhausted() function deleted, no other changes.
// TODO replace with proper runtime-less native threading once Rust gains
// support for this.
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// fil... | (limit: uint) {
asm!("movl $$0x48+90*4, %eax
movl $0, %gs:(%eax)" :: "r"(limit) : "eax" : "volatile")
}
#[cfg(all(target_arch = "x86",
any(target_os = "linux", target_os = "freebsd")))]
#[inline(always)]
unsafe fn target_record_sp_limit(limit: uint) {
asm!("mo... | target_record_sp_limit | identifier_name |
stack.rs | // Copied from:
// rust/src/librustrt/stack.rs
// git: 70cef9474a3307ec763efc01fe6969e542083823
// stack_exhausted() function deleted, no other changes.
// TODO replace with proper runtime-less native threading once Rust gains
// support for this.
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// fil... |
/// Records the current limit of the stack as specified by `end`.
///
/// This is stored in an OS-dependent location, likely inside of the thread
/// local storage. The location that the limit is stored is a pre-ordained
/// location because it's where LLVM has emitted code to check.
///
/// Note that this cannot be ... | {
// When the old runtime had segmented stacks, it used a calculation that was
// "limit + RED_ZONE + FUDGE". The red zone was for things like dynamic
// symbol resolution, llvm function calls, etc. In theory this red zone
// value is 0, but it matters far less when we have gigantic stacks because
/... | identifier_body |
stack.rs | // Copied from:
// rust/src/librustrt/stack.rs
// git: 70cef9474a3307ec763efc01fe6969e542083823
// stack_exhausted() function deleted, no other changes.
// TODO replace with proper runtime-less native threading once Rust gains
// support for this.
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// fil... | unsafe fn target_record_sp_limit(limit: uint) {
asm!("movl $0, %gs:48" :: "r"(limit) :: "volatile")
}
#[cfg(all(target_arch = "x86", target_os = "windows"))] #[inline(always)]
unsafe fn target_record_sp_limit(_: uint) {
}
// mips, arm - Some brave soul can port these to inline asm, but ... | movl $0, %gs:(%eax)" :: "r"(limit) : "eax" : "volatile")
}
#[cfg(all(target_arch = "x86",
any(target_os = "linux", target_os = "freebsd")))]
#[inline(always)] | random_line_split |
main.go | package main
import (
"bufio"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"math"
"math/big"
"net/http"
"os"
"strconv"
"strings"
"github.com/ElrondNetwork/ledger-elrond/testApp/ledger"
"github.com/btcsuite/btcutil/bech32"
)
const proxyHost string = "https://api.elrond.com" // https:... | (tx transaction) error {
jsonTx, _ := json.Marshal(&tx)
resp, err := http.Post(fmt.Sprintf("%s/transaction/send", proxyHost), "",
strings.NewReader(string(jsonTx)))
if err != nil {
log.Println(errSendingTx)
return err
}
body, err := ioutil.ReadAll(resp.Body)
defer func() {
_ = resp.Body.Close()
}()
if e... | broadcastTransaction | identifier_name |
main.go | package main
import (
"bufio"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"math"
"math/big"
"net/http"
"os"
"strconv"
"strings"
"github.com/ElrondNetwork/ledger-elrond/testApp/ledger"
"github.com/btcsuite/btcutil/bech32"
)
const proxyHost string = "https://api.elrond.com" // https:... | {
log.SetFlags(0)
// opening connection with the Ledger device
var nanos *ledger.NanoS
nanos, err := ledger.OpenNanoS()
if err != nil {
log.Println(errOpenDevice, err)
waitInputAndExit()
}
err = getDeviceInfo(nanos)
if err != nil {
log.Println(err)
waitInputAndExit()
}
fmt.Println("Nano S app version... | identifier_body | |
main.go | package main
import (
"bufio"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"math"
"math/big"
"net/http"
"os"
"strconv"
"strings"
"github.com/ElrondNetwork/ledger-elrond/testApp/ledger"
"github.com/btcsuite/btcutil/bech32"
)
const proxyHost string = "https://api.elrond.com" // https:... |
addr := uint32(addressBytes[len(addressBytes)-1])
shard := addr & maskHigh
if shard > noOfShards-1 {
shard = addr & maskLow
}
return shard, nil
}
// getNetworkConfig reads the network config from the proxy and returns a networkConfig object
func getNetworkConfig() (*networkConfig, error) {
req, err := http.Ne... | {
return 0, err
} | conditional_block |
main.go | package main
import (
"bufio"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"math"
"math/big"
"net/http"
"os"
"strconv"
"strings"
"github.com/ElrondNetwork/ledger-elrond/testApp/ledger"
"github.com/btcsuite/btcutil/bech32"
)
const proxyHost string = "https://api.elrond.com" // https:... | log.Println(errSigningTx)
return err
}
sigHex := hex.EncodeToString(signature)
tx.Signature = sigHex
return nil
}
// broadcastTransaction broadcasts the transaction in the network
func broadcastTransaction(tx transaction) error {
jsonTx, _ := json.Marshal(&tx)
resp, err := http.Post(fmt.Sprintf("%s/transact... | fmt.Println("Signing transaction. Please confirm on your Ledger")
signature, err := nanos.SignTx(toSign)
if err != nil { | random_line_split |
elf.go | // Copyright 2020 syzkaller project authors. All rights reserved.
// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.
package backend
import (
"bufio"
"bytes"
"debug/dwarf"
"debug/elf"
"encoding/binary"
"fmt"
"io/ioutil"
"path/filepath"
"runtime"
"sort"
"strcon... | }
unit.Name, unit.Path = cleanPath(unit.Name, objDir, srcDir, buildDir)
units[nunit] = unit
nunit++
}
units = units[:nunit]
if len(symbols) == 0 || len(units) == 0 {
return nil, fmt.Errorf("failed to parse DWARF (set CONFIG_DEBUG_INFO=y?)")
}
impl := &Impl{
Units: units,
Symbols: symbols,
Symboli... | for _, unit := range units {
if len(unit.PCs) == 0 {
continue // drop the unit | random_line_split |
elf.go | // Copyright 2020 syzkaller project authors. All rights reserved.
// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.
package backend
import (
"bufio"
"bytes"
"debug/dwarf"
"debug/elf"
"encoding/binary"
"fmt"
"io/ioutil"
"path/filepath"
"runtime"
"sort"
"strcon... | (target *targets.Target, objDir, srcDir, buildDir, obj string, pcs []uint64) ([]Frame, error) {
procs := runtime.GOMAXPROCS(0) / 2
if need := len(pcs) / 1000; procs > need {
procs = need
}
const (
minProcs = 1
maxProcs = 4
)
// addr2line on a beefy vmlinux takes up to 1.6GB of RAM, so don't create too many ... | symbolize | identifier_name |
elf.go | // Copyright 2020 syzkaller project authors. All rights reserved.
// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.
package backend
import (
"bufio"
"bytes"
"debug/dwarf"
"debug/elf"
"encoding/binary"
"fmt"
"io/ioutil"
"path/filepath"
"runtime"
"sort"
"strcon... |
// readCoverPoints finds all coverage points (calls of __sanitizer_cov_trace_pc) in the object file.
// Currently it is amd64-specific: looks for e8 opcode and correct offset.
// Running objdump on the whole object file is too slow.
func readCoverPoints(file *elf.File, tracePC uint64, traceCmp map[uint64]bool) ([2][]... | {
procs := runtime.GOMAXPROCS(0) / 2
if need := len(pcs) / 1000; procs > need {
procs = need
}
const (
minProcs = 1
maxProcs = 4
)
// addr2line on a beefy vmlinux takes up to 1.6GB of RAM, so don't create too many of them.
if procs > maxProcs {
procs = maxProcs
}
if procs < minProcs {
procs = minProc... | identifier_body |
elf.go | // Copyright 2020 syzkaller project authors. All rights reserved.
// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.
package backend
import (
"bufio"
"bytes"
"debug/dwarf"
"debug/elf"
"encoding/binary"
"fmt"
"io/ioutil"
"path/filepath"
"runtime"
"sort"
"strcon... |
pos += i
i = pos
off := uint64(int64(int32(binary.LittleEndian.Uint32(data[pos+1:]))))
pc := text.Addr + uint64(pos)
target := pc + off + callLen
if target == tracePC {
pcs[0] = append(pcs[0], pc)
} else if traceCmp[target] {
pcs[1] = append(pcs[1], pc)
}
}
return pcs, nil
}
// objdump is an o... | {
break
} | conditional_block |
warwick.go | /*
You are building a medieval village. You win by having the most Victory Points (VP), which you get by building
particular buildings. You build by discarding cards. The game is over when one player has built one
of each kind of building (and his opponent gets one more turn), or when the deck runs out.
Buildings... | {
stock, stockSize := buildStock()
var discardPile card.Hand
discardPile.Cards = make([]*card.Card, stockSize)
discardPile.PullPos = -1
var trash card.Hand
trash.Cards = make([]*card.Card, stockSize)
// trash is never pulled from, so no pull position
players := make([]player.Player, 2);
// set up rules abo... | identifier_body | |
warwick.go | /*
You are building a medieval village. You win by having the most Victory Points (VP), which you get by building
particular buildings. You build by discarding cards. The game is over when one player has built one
of each kind of building (and his opponent gets one more turn), or when the deck runs out.
Buildings... |
// ------- TRASH --------- //
cardsTrashed := 0
// TrashBonus measures the amount of cards you can trash in order to draw a new one
if currentPlayer.Tableau.TrashBonus > 0 && currentPlayer.Hand.Count > 0 {
trashPoses := currentPlayer.ChooseTrash(phase)
cardsTrashed = currentPlayer.TrashCards(trash... | {
// log(1, fmt.Sprintf("Player %d uses %s and takes opponent's %s", id, currentPlayer.TopCard(card.Soldiers), opponent.TopCard(steal)))
if opponent.Human{
players[0].State += fmt.Sprintf("ALERT: Opponent used a %s to take your %s\n", currentPlayer.TopCard(card.Soldiers), opponent.TopCard(steal))
}
... | conditional_block |
warwick.go | /*
You are building a medieval village. You win by having the most Victory Points (VP), which you get by building
particular buildings. You build by discarding cards. The game is over when one player has built one
of each kind of building (and his opponent gets one more turn), or when the deck runs out.
Buildings... | (storePower int, stock *card.Hand, discardPile *card.Hand, player *player.Player, phase int) {
var topSpot int
switch {
case storePower == 1 || storePower == 2:
// the player may choose from hand, discard or stock to fill the storage
// if the spot is open, you may refill it
topSpot = 0
case storePower == 3 |... | store | identifier_name |
warwick.go | /*
You are building a medieval village. You win by having the most Victory Points (VP), which you get by building
particular buildings. You build by discarding cards. The game is over when one player has built one
of each kind of building (and his opponent gets one more turn), or when the deck runs out.
Buildings... | Storage reconsidered: Level 1 store one card, Level 2: + may build the stored card, Level 3: + may spend the stored card, Level 4: +1 storage spot
re2considered: 1: store card on table, 2: store 2nd card, 3: can move card back into hand, 4: fill any open storage spots at the time you build this card
re3considered: ... | Level 1 store one card, Level 2: + may build the stored card, Level 3: + may spend the stored card, Level 4: +1 storage spot | random_line_split |
energy_matrix_analysis.py | """
We wish to explore the relationship between copy number and various
energy matrix statistics, such as disorder (i.e. standard deviation of
score).
"""
from utils import *
from parse_energy_matrices import parse_energy_matrices
from scipy.stats import wilcoxon
#energy_matrices = parse_energy_matrices("energy_matric... | # product(e_of_sqs) - product(esqs), not sum...
# expectation of square
e_of_sqs = [mean([exp(-beta*ep)**2 for ep in col]) for col in matrix]
# square of expectation
esqs = [mean([exp(-beta*ep) for ep in col])**2 for col in matrix]
return product(e_of_sqs) - product(esqs)
def predict_z(matrix,... | # Page 55 of 54-60
# However, first line of equation 1 is /wrong/. Should be: | random_line_split |
energy_matrix_analysis.py | """
We wish to explore the relationship between copy number and various
energy matrix statistics, such as disorder (i.e. standard deviation of
score).
"""
from utils import *
from parse_energy_matrices import parse_energy_matrices
from scipy.stats import wilcoxon
#energy_matrices = parse_energy_matrices("energy_matric... | (matrix,n,G,alpha):
"""See blue notebook: 6/27/13"""
#constant which does not depend on sites, matrix
C = 1/beta * log(n/G*(1-alpha)/alpha)
Zb = predict_z(matrix,G)
omega = Zb/G
return C - (1/beta * log(omega))
def predict_zf(matrix,n,G,alpha):
"""Predict sum_{i=1}^n exp(-\beta*E(s))"""
... | predict_site_energy | identifier_name |
energy_matrix_analysis.py | """
We wish to explore the relationship between copy number and various
energy matrix statistics, such as disorder (i.e. standard deviation of
score).
"""
from utils import *
from parse_energy_matrices import parse_energy_matrices
from scipy.stats import wilcoxon
#energy_matrices = parse_energy_matrices("energy_matric... |
def matrix_mean(matrix):
"""Return the mean score for the energy matrix"""
return sum(map(mean,matrix))
def matrix_variance(matrix):
"""Return the variance of the scores for the energy matrix"""
return sum(map(lambda row:variance(row,correct=False),matrix))
def matrix_sd(matrix):
... | return specific_binding | conditional_block |
energy_matrix_analysis.py | """
We wish to explore the relationship between copy number and various
energy matrix statistics, such as disorder (i.e. standard deviation of
score).
"""
from utils import *
from parse_energy_matrices import parse_energy_matrices
from scipy.stats import wilcoxon
#energy_matrices = parse_energy_matrices("energy_matric... |
def sse(matrix,motif):
"""Compute sum of squared error for matrix and motif"""
return sum([site_error(matrix,site)**2
for site in motif])
def sse_optimized(matrix,motif):
"""Compute sum of squared error for matrix and motif"""
#Hoisted computation of K out of site_error
K = 1/beta... | """Compute error for site, given matrix"""
return score(matrix,site,ns=False) - C | identifier_body |
Script 1-relative heritability-plotted(Figure 2a)-2.py | # -*- coding: utf-8 -*-
"""
Created on Wed Jan 06 10:26:07 2016
@author: Will Ratcliff
"""
import numpy as np
np.set_printoptions(threshold=np.nan)
import math
from scipy.stats import linregress
import matplotlib.pyplot as plt
import pandas as pd
cell_genos=np.linspace(1,2,10)
st_dev_cell=0.3
st_... | offspring_radius=[]
for i in range(0,len(parent_size_cleaned)):
parent_radius.append((3.*parent_size_cleaned[i]/(4.*math.pi))**(1./3.)) #manual check of this calculation confirmed it is correct
for i in range(0,len(offspring_size_cleaned)):
offspri... | parent_size_cleaned=list(parent_size[len(cell_genos):])
offspring_size_cleaned=list(offspring_size[len(cell_genos):])
parent_radius=[]
| random_line_split |
Script 1-relative heritability-plotted(Figure 2a)-2.py | # -*- coding: utf-8 -*-
"""
Created on Wed Jan 06 10:26:07 2016
@author: Will Ratcliff
"""
import numpy as np
np.set_printoptions(threshold=np.nan)
import math
from scipy.stats import linregress
import matplotlib.pyplot as plt
import pandas as pd
cell_genos=np.linspace(1,2,10)
st_dev_cell=0.3
st_... |
pop=np.vstack([pop,[cell_max+i,pop[(cell_max+i)-cells_added_first][1],np.random.normal(pop[(cell_max+i)-cells_added_first][1],st_dev_cell)*cluster_variance_factor,pop[(cell_max+i)-cells_added_first][0],cluster_max+math.floor(i/cluster_size),pop[(cell_max+i)-cells_added_first][4],0,0,0,pop[(cell_ma... | cluster_variance_factor=np.random.normal(1,st_dev_group) | conditional_block |
token.go | package token
import "strings"
type Type int
const (
End Type = iota
Include
IncludeOnce
Eval
Require
RequireOnce
LogicalOr
LogicalXor
LogicalAnd
Print
Yield
DoubleArrow
YieldFrom
PlusEqual
MinusEqual
MulEqual
DivEqual
ConcatEqual
ModEqual
AndEqual
OrEqual
XorEqual
SlEqual
SrEqual
PowEqual
... |
var keywords = map[string]Type{
"abstract": Abstract,
"and": BooleanAnd,
"array": Array,
"as": As,
"break": Break,
"callable": Callable,
"case": Case,
"catch": Catch,
"class": Class,
"clone": Clone,
"const": Const,
"continue": ... | {
if n, ok := tokenName[t]; ok {
return n
}
return "Unknown"
} | identifier_body |
token.go | package token
import "strings"
type Type int
const (
End Type = iota
Include
IncludeOnce
Eval
Require
RequireOnce
LogicalOr
LogicalXor
LogicalAnd
Print
Yield
DoubleArrow
YieldFrom
PlusEqual
MinusEqual
MulEqual
DivEqual
ConcatEqual
ModEqual
AndEqual
OrEqual
XorEqual
SlEqual
SrEqual
PowEqual
... | ConstantEncapsedString
StringVarname
NumString
Exit
If
Echo
Do
While
Endwhile
For
Endfor
Foreach
Endforeach
Declare
Enddeclare
As
Switch
Endswitch
Case
Default
Break
Continue
Goto
Function
Const
Return
Try
Catch
Finally
Throw
Use
Insteadof
Global
Var
Unset
Isset
Empty
HaltCompiler
... | EncapsedAndWhitespace | random_line_split |
token.go | package token
import "strings"
type Type int
const (
End Type = iota
Include
IncludeOnce
Eval
Require
RequireOnce
LogicalOr
LogicalXor
LogicalAnd
Print
Yield
DoubleArrow
YieldFrom
PlusEqual
MinusEqual
MulEqual
DivEqual
ConcatEqual
ModEqual
AndEqual
OrEqual
XorEqual
SlEqual
SrEqual
PowEqual
... |
return String
}
func NewToken(t Type, literal string, line int) Token {
return Token{Type: t, Literal: literal, Line: line}
}
| {
return t
} | conditional_block |
token.go | package token
import "strings"
type Type int
const (
End Type = iota
Include
IncludeOnce
Eval
Require
RequireOnce
LogicalOr
LogicalXor
LogicalAnd
Print
Yield
DoubleArrow
YieldFrom
PlusEqual
MinusEqual
MulEqual
DivEqual
ConcatEqual
ModEqual
AndEqual
OrEqual
XorEqual
SlEqual
SrEqual
PowEqual
... | () string {
if n, ok := tokenName[t]; ok {
return n
}
return "Unknown"
}
var keywords = map[string]Type{
"abstract": Abstract,
"and": BooleanAnd,
"array": Array,
"as": As,
"break": Break,
"callable": Callable,
"case": Case,
"catch": Catch,
"class": ... | String | identifier_name |
lib.rs | //! Crate `ruma_client` is a [Matrix](https://matrix.org/) client library.
//!
//! # Usage
//!
//! Begin by creating a `Client` type, usually using the `https` method for a client that supports
//! secure connections, and then logging in:
//!
//! ```no_run
//! use futures::Future;
//! use ruma_client::Client;
//!
//! l... |
}
#[cfg(feature = "tls")]
impl Client<HttpsConnector<HttpConnector>> {
/// Creates a new client for making HTTPS requests to the given homeserver.
pub fn https(homeserver_url: Url, session: Option<Session>) -> Result<Self, NativeTlsError> {
let connector = HttpsConnector::new(4)?;
Ok(Self(Arc... | {
self.0
.session
.lock()
.expect("session mutex was poisoned")
.clone()
} | identifier_body |
lib.rs | //! Crate `ruma_client` is a [Matrix](https://matrix.org/) client library.
//!
//! # Usage
//!
//! Begin by creating a `Client` type, usually using the `https` method for a client that supports
//! secure connections, and then logging in:
//!
//! ```no_run
//! use futures::Future;
//! use ruma_client::Client;
//!
//! l... | set_presence: bool,
) -> impl Stream<Item = api::r0::sync::sync_events::Response, Error = Error> {
use crate::api::r0::sync::sync_events;
let client = self.clone();
let set_presence = if set_presence {
None
} else {
Some(sync_events::SetPresence::Offl... | since: Option<String>, | random_line_split |
lib.rs | //! Crate `ruma_client` is a [Matrix](https://matrix.org/) client library.
//!
//! # Usage
//!
//! Begin by creating a `Client` type, usually using the `https` method for a client that supports
//! secure connections, and then logging in:
//!
//! ```no_run
//! use futures::Future;
//! use ruma_client::Client;
//!
//! l... | <E>(
self,
request: <E as Endpoint>::Request,
) -> impl Future<Item = E::Response, Error = Error>
where
E: Endpoint,
{
let data1 = self.0.clone();
let data2 = self.0.clone();
let mut url = self.0.homeserver_url.clone();
request
.try_into()... | request | identifier_name |
lib.rs | //! Crate `ruma_client` is a [Matrix](https://matrix.org/) client library.
//!
//! # Usage
//!
//! Begin by creating a `Client` type, usually using the `https` method for a client that supports
//! secure connections, and then logging in:
//!
//! ```no_run
//! use futures::Future;
//! use ruma_client::Client;
//!
//! l... |
}
Uri::from_str(url.as_ref())
.map(move |uri| (uri, hyper_request))
.map_err(Error::from)
})
.and_then(move |(uri, mut hyper_request)| {
*hyper_request.uri_mut() = uri;
data2.hyper.request(... | {
if let Some(ref session) = *data1.session.lock().unwrap() {
url.query_pairs_mut()
.append_pair("access_token", &session.access_token);
} else {
return Err(Error(InnerError::Authentic... | conditional_block |
AutoEncoderBasedEvaluation.py | import copy
import numpy as np
import DataLoader
import torch
import seaborn as sns
import matplotlib.pyplot as plt
from scipy import signal
from scipy.signal import find_peaks
from statsmodels import api as sm
from sklearn.preprocessing import MinMaxScaler
from torch import nn
from LstmAutoEncoder import LstmAutoEncod... | if epoch >= 50 and countWithoutImprovement == earlyStopThreshold:
print('Early stopping!')
break
print(f'Epoch {epoch}: train loss {MeanOfTrainLoss} val loss {MeanOfValidLoss}')
model.load_state_dict(bestModel)
# plot result [optional]
fig, ax... | houtImprovement += 1
| conditional_block |
AutoEncoderBasedEvaluation.py | import copy
import numpy as np
import DataLoader
import torch
import seaborn as sns
import matplotlib.pyplot as plt
from scipy import signal
from scipy.signal import find_peaks
from statsmodels import api as sm
from sklearn.preprocessing import MinMaxScaler
from torch import nn
from LstmAutoEncoder import LstmAutoEncod... |
def saveModel(self, autoEncoder):
np.save('./model/' + str(self.paramIndex) + '_ae_statistics', self.statistics)
path = './model/' + str(self.paramIndex) + '_lstm_ae_model.pth'
torch.save(autoEncoder, path)
def loadModel(self):
self.statistics = np.load('./model/' + str(self.pa... | random_line_split | |
AutoEncoderBasedEvaluation.py | import copy
import numpy as np
import DataLoader
import torch
import seaborn as sns
import matplotlib.pyplot as plt
from scipy import signal
from scipy.signal import find_peaks
from statsmodels import api as sm
from sklearn.preprocessing import MinMaxScaler
from torch import nn
from LstmAutoEncoder import LstmAutoEncod... | ruth, pred, loss):
fig = plt.figure(figsize=(6, 6))
plt.plot(truth, label='true')
plt.plot(pred, label='reconstructed')
plt.title(f'loss:{np.around(loss, 2)}')
plt.legend()
plt.savefig('figures/' + str(self.paramIndex) + '_AE_eval_result.png')
def printResult(self, s... | re(self, t | identifier_name |
AutoEncoderBasedEvaluation.py | import copy
import numpy as np
import DataLoader
import torch
import seaborn as sns
import matplotlib.pyplot as plt
from scipy import signal
from scipy.signal import find_peaks
from statsmodels import api as sm
from sklearn.preprocessing import MinMaxScaler
from torch import nn
from LstmAutoEncoder import LstmAutoEncod... |
@staticmethod
def findCycle(sequence):
normalizedStable = sequence - np.mean(sequence)
# acf = sm.tsa.acf(normalizedStable, nlags=len(normalizedStable), fft=False) # auto correlation
peaks, _ = find_peaks(normalizedStable.to_numpy().flatten())
if peaks.size < 3:
re... | print('paramIndex:', self.paramIndex)
stable = self.normalData.data.x_data
# plot distribution [optional]
# sns.distplot(stable, label="train")
# plt.legend()
# plt.show()
# mix max scaler
minMaxScaler = MinMaxScaler()
minMaxScaler.fit(stable)
... | identifier_body |
main.rs | // #![feature(alloc_system)]
// extern crate alloc_system;
extern crate regex;
extern crate argparse;
use regex::Regex;
use std::fs::File;
use argparse::{ArgumentParser, Store};
use std::collections::HashSet;
use std::collections::BTreeMap;
use std::io::{BufReader, BufRead, BufWriter, Write};
// print $seqgene "Gene\... |
// now apply input mapping regex
if mapping_match_re.is_match(&match_string) {
count_matched += 1;
match gene_matches.get_mut(al_arr[2].split("_").nth(0).unwrap()) {
Some(v) => *v += 1,
None => println!("illegal gene id... | {
for pos in mm_positions {
// TODO: next line is not compiling
match_string.insert_str(pos, "X");
}
} | conditional_block |
main.rs | // #![feature(alloc_system)]
// extern crate alloc_system;
extern crate regex;
extern crate argparse;
use regex::Regex;
use std::fs::File;
use argparse::{ArgumentParser, Store};
use std::collections::HashSet;
use std::collections::BTreeMap;
use std::io::{BufReader, BufRead, BufWriter, Write};
// print $seqgene "Gene\... | {
//-> (HashMap<String, i32>, u32) {
// our buffer for the sam parser
let sam_file = BufReader::new(File::open(sam_file).expect("Problem opening fastq file"))
.lines();
let sam_mismatch_re =
Regex::new(r"MD:Z:([0-9]+)([A-Z]+)[0-9]+").expect("programmer error in mismatch regex");
let m... | identifier_body | |
main.rs | // #![feature(alloc_system)]
// extern crate alloc_system;
extern crate regex;
extern crate argparse;
use regex::Regex;
use std::fs::File;
use argparse::{ArgumentParser, Store};
use std::collections::HashSet;
use std::collections::BTreeMap;
use std::io::{BufReader, BufRead, BufWriter, Write};
// print $seqgene "Gene\... | }
}
// --------- end of basic algorithm ---
}
// (mapped_geneids, count_total)
(count_total, count_matched)
} | Some(v) => *v += 1,
None => println!("illegal reference lib id encountered '{}'", &al_arr[2].split("_").nth(0).unwrap())
} | random_line_split |
main.rs | // #![feature(alloc_system)]
// extern crate alloc_system;
extern crate regex;
extern crate argparse;
use regex::Regex;
use std::fs::File;
use argparse::{ArgumentParser, Store};
use std::collections::HashSet;
use std::collections::BTreeMap;
use std::io::{BufReader, BufRead, BufWriter, Write};
// print $seqgene "Gene\... | (fasta_file: &str, fasta_re: &Regex, geneid_pattern : String, gene_matches : &mut BTreeMap<String, u32>, ref_libIds: &mut BTreeMap<String, u32>) {
let fasta_file = BufReader::new(File::open(fasta_file).expect("Problem opening fastq file"));
for line in fasta_file.lines() {
let ln = line.expect("progr... | process_fasta | identifier_name |
09_impersonator.py | # impersonator.py
import ctypes
from ctypes.wintypes import DWORD,BOOL,HANDLE,LPWSTR,WORD,LPBYTE
# Handles
u_handle = ctypes.WinDLL("user32.dll")
k_handle = ctypes.WinDLL("kernel32.dll")
a_handle = ctypes.WinDLL("Advapi32.dll")
# Access Rights (Full Access Right Shortcut)
PROCESS_ALL_ACCESS = (0x000F0000 | 0x001000... | (ctypes.Structure):
_fields_ = [
("PrivilegeCount", DWORD),
("Control", DWORD),
("Privileges", LUID_AND_ATTRIBUTES),
]
# Token Set
class TOKEN_PRIVILEGES(ctypes.Structure):
_fields_ = [
("PrivilegeCount", DWORD),
("Privileges", LUID_AND_ATTRIBUTES),
]
# Security Attribute Set
clas... | PRIVILEGE_SET | identifier_name |
09_impersonator.py | # impersonator.py
import ctypes
from ctypes.wintypes import DWORD,BOOL,HANDLE,LPWSTR,WORD,LPBYTE
# Handles
u_handle = ctypes.WinDLL("user32.dll")
k_handle = ctypes.WinDLL("kernel32.dll")
a_handle = ctypes.WinDLL("Advapi32.dll")
# Access Rights (Full Access Right Shortcut)
PROCESS_ALL_ACCESS = (0x000F0000 | 0x001000... |
if pfResult:
print("[INFO] Privilege Enabled: {0}".format(priv))
return 0
else:
print("[INFO] Privilege Disabled: {0}".format(priv))
# Enabling the privilege if disabled
print("[INFO] Enabling the Privilege...")
requiredPrivileges.Privileges.Attributes = SE_PRIV... | print("[ERROR] PrivilegeCheck Failed! [-] Error Code: {0}".format(k_handle.GetLastError()))
return 1 | conditional_block |
09_impersonator.py | # impersonator.py
import ctypes
from ctypes.wintypes import DWORD,BOOL,HANDLE,LPWSTR,WORD,LPBYTE
# Handles
u_handle = ctypes.WinDLL("user32.dll")
k_handle = ctypes.WinDLL("kernel32.dll")
a_handle = ctypes.WinDLL("Advapi32.dll")
# Access Rights (Full Access Right Shortcut)
PROCESS_ALL_ACCESS = (0x000F0000 | 0x001000... | TOKEN_ADJUST_PRIVILEGES |
TOKEN_ADJUST_GROUPS |
TOKEN_ADJUST_DEFAULT |
TOKEN_ADJUST_SESSIONID)
# LUID Structure
class LUID(ctypes.Structure):
_fields_ = [
("LowPart", DWORD),
("HighPart", DWORD),
]
# LUID and... | TOKEN_DUPLICATE |
TOKEN_IMPERSONATION |
TOKEN_QUERY |
TOKEN_QUERY_SOURCE | | random_line_split |
09_impersonator.py | # impersonator.py
import ctypes
from ctypes.wintypes import DWORD,BOOL,HANDLE,LPWSTR,WORD,LPBYTE
# Handles
u_handle = ctypes.WinDLL("user32.dll")
k_handle = ctypes.WinDLL("kernel32.dll")
a_handle = ctypes.WinDLL("Advapi32.dll")
# Access Rights (Full Access Right Shortcut)
PROCESS_ALL_ACCESS = (0x000F0000 | 0x001000... |
# [FUNCTION] Enable Privileges
def enablePrivilege(priv, handle):
# 1) Use the LookupPrivilegeValueW API Call to get the LUID based on the String Privilege Name
# 2) Setup a PRIVILEGE_SET for the PrivilegeCheck Call to be used later - We need the LUID to be used
# BOOL PrivilegeCheck(
# HANDLE ... | _fields_ = [
("hProcess", HANDLE),
("hThread", HANDLE),
("dwProcessId", DWORD),
("dwThreadId", DWORD),
] | identifier_body |
main.py | from __future__ import print_function
import os
import sys
import logging
import argparse
import time
from time import strftime
import torch
import torch.optim as optim
from torchvision import datasets, transforms
from models.resnet_1d import ResNet18_1d, ResNet34_1d, ResNet50_1d
import admm
from admm import GradualW... | print("Testing slice-acc: {:.3f}; Testing exp-acc: {:.3f}".format(acc_slice, acc_ex))
best_prec1 = max(acc_ex, best_prec1)
print("Best Acc: {:.4f}%".format(best_prec1))
print("Saving model...\n")
torch.save(model.state_dict(), args.save_path_exp+"/prunned_{}... | train(ADMM, train_loader, criterion, optimizer, scheduler, epoch, args)
#t_loss, prec1 = test(model, criterion, test_loader)
acc_slice, acc_ex, preds = pipeline.test_model(args,model) | random_line_split |
main.py | from __future__ import print_function
import os
import sys
import logging
import argparse
import time
from time import strftime
import torch
import torch.optim as optim
from torchvision import datasets, transforms
from models.resnet_1d import ResNet18_1d, ResNet34_1d, ResNet50_1d
import admm
from admm import GradualW... | (initial_rho, criterion, optimizer, scheduler):
if args.load_mask:
'''
Load pre-mask and added to the full model
'''
print("\n>_ Loading Mask: "+ args.load_mask)
mask = torch.load(args.load_mask)
for name, W in (model.named_parameters()):
if name in m... | masked_retrain | identifier_name |
main.py | from __future__ import print_function
import os
import sys
import logging
import argparse
import time
from time import strftime
import torch
import torch.optim as optim
from torchvision import datasets, transforms
from models.resnet_1d import ResNet18_1d, ResNet34_1d, ResNet50_1d
import admm
from admm import GradualW... |
optimizer.step()
# measure elapsed time
batch_time.update(time.time() - end)
end = time.time()
# print(i)
if i % args.log_interval == 0:
for param_group in optimizer.param_groups:
current_lr = param_group['lr']
print('({0}) lr:[... | if name in masks:
W.grad *= masks[name] | conditional_block |
main.py | from __future__ import print_function
import os
import sys
import logging
import argparse
import time
from time import strftime
import torch
import torch.optim as optim
from torchvision import datasets, transforms
from models.resnet_1d import ResNet18_1d, ResNet34_1d, ResNet50_1d
import admm
from admm import GradualW... |
def test(model, criterion, test_loader):
model.eval()
losses = AverageMeter()
correct = 0
with torch.no_grad():
for data, target in test_loader:
data, target = data.cuda(), target.cuda()
output = model(data)
loss = criterion(output, target)
los... | batch_time = AverageMeter()
data_time = AverageMeter()
losses = AverageMeter()
top1 = AverageMeter()
idx_loss_dict = {}
# switch to train mode
model.train()
if args.masked_retrain and not args.combine_progressive:
print("full acc re-train masking")
masks = {}
for na... | identifier_body |
game.py | ###################################################################################
###################################################################################
# efhagame - by Bartholomaeus Dedersen
# based on:
# Sprite Movement Towards Target Example + Physics
# programed/documented by Mad Cloud Games
# conta... | (self):
if self.percentX > 0:
self.percentX -= 10
def increase_graphY(self):
if self.percentY < 100:
self.percentY += 10
def decrease_graphY(self):
if self.percentY > 0:
self.percentY -= 10
def setX(self,x):
self.percentX = x
def se... | decrease_graphX | identifier_name |
game.py | ###################################################################################
###################################################################################
# efhagame - by Bartholomaeus Dedersen
# based on:
# Sprite Movement Towards Target Example + Physics
# programed/documented by Mad Cloud Games
# conta... | - self
'''
self.dir = self.get_direction(self.target) # get direction
if self.dir: # if there is a direction to move
if self.distance_check(self.dist): # if we need to slow down
self.speedX += (self.dir[0] * (self.speed / 2)) # reduce... | ()
Parameters: | random_line_split |
game.py | ###################################################################################
###################################################################################
# efhagame - by Bartholomaeus Dedersen
# based on:
# Sprite Movement Towards Target Example + Physics
# programed/documented by Mad Cloud Games
# conta... |
self.trueX += self.speedX # store true x decimal values
self.trueY += self.speedY
self.rect.center = (round(self.trueX),round(self.trueY)) # apply values to sprite.center
class BrainSprite(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
... | self.speedX += (self.dir[0] * self.speed) # calculate speed from direction to move and speed constant
self.speedY += (self.dir[1] * self.speed)
self.speedX *= self.normal_friction # apply friction
self.speedY *= self.normal_friction | conditional_block |
game.py | ###################################################################################
###################################################################################
# efhagame - by Bartholomaeus Dedersen
# based on:
# Sprite Movement Towards Target Example + Physics
# programed/documented by Mad Cloud Games
# conta... |
class Sprite(pygame.sprite.Sprite):
def __init__(self):
'''
Class:
creates a sprite
Parameters:
- self
'''
self.image = pygame.image.load("zombie.png").convert_alpha() # load image
self.rect = self.image.get_rect()
self.reset_... | l = self.length()
if l != 0:
return (self.x / l, self.y / l)
return None | identifier_body |
mark.py | #!/bin/env python3
# Evan Wilde (c) 2017
# My big insane marking script of doom 😈
import argparse
import os
import sys
import csv
import re
import shutil
import subprocess
from subprocess import call
username_pattern = r".*\((.*)\)$"
username_expr = re.compile(username_pattern)
test_pattern = r"(100|[1-9][0-9]|[0... | ef appendToFile(fname, content):
with open(fname, 'a+') as FILE:
FILE.write(content)
# Show stuff
def viewData(content):
PAGER = os.environ.get('PAGER')
if PAGER and len(content.split('\n')) > 20:
if PAGER == 'less':
subprocess.run([os.environ.get("PAGER"), '-N'], input=content.... | os.environ.get('EDITOR'):
subprocess.run([os.environ.get("EDITOR"), fname])
else: # Rudimentary backup editor
lines = []
while True:
try:
line = input(">>>")
except EOFError:
break
lines.append(line)
contents = '\n'.... | identifier_body |
mark.py | #!/bin/env python3
# Evan Wilde (c) 2017
# My big insane marking script of doom 😈
import argparse
import os
import sys
import csv
import re
import shutil
import subprocess
from subprocess import call
username_pattern = r".*\((.*)\)$"
username_expr = re.compile(username_pattern)
test_pattern = r"(100|[1-9][0-9]|[0... | if not os.path.isdir(output_path):
os.mkdir(output_path)
shutil.copy(os.path.abspath("./comments.txt"),
os.path.join(output_path, "comments.txt"))
continue
copyContents(submission_path, tmpdir)
copyContents(assndi... | h open(os.path.abspath("./comments.txt"), 'w'):
pass # Just create it and leave
| conditional_block |
mark.py | #!/bin/env python3
# Evan Wilde (c) 2017
# My big insane marking script of doom 😈
import argparse
import os
import sys
import csv
import re
import shutil
import subprocess
from subprocess import call
username_pattern = r".*\((.*)\)$"
username_expr = re.compile(username_pattern)
test_pattern = r"(100|[1-9][0-9]|[0... | rc):
return [x for x in os.listdir(dirc) if x is not os.path.isdir(x)]
# Prompt user to select an item
def selectItems(itms):
prmt = '\t' + '\n\t'.join([f"({num+1}): {nm}"
for num, nm in enumerate(itms)]) + '\n [1] >>: '
while True:
i = input(prmt)
if i == '':
return (0,... | Files(di | identifier_name |
mark.py | #!/bin/env python3
# Evan Wilde (c) 2017
# My big insane marking script of doom 😈
import argparse
import os
import sys
import csv
import re
import shutil
import subprocess
from subprocess import call
username_pattern = r".*\((.*)\)$"
username_expr = re.compile(username_pattern)
test_pattern = r"(100|[1-9][0-9]|[0... | elif cidx == 8:
submittedFiles = getFiles(submission_path)
if len(submittedFiles) > 1:
_, fname = selectItems(submittedFiles)
else:
fname = submittedFiles[0]
viewFile(os.path.abspath("./" + fname))
... | elif cidx == 7:
appendToFile(os.path.abspath("./comments.txt"),
'\n'.join(["\n<pre>", "=== [Test Output] =============",
output, "</pre>"]) ) | random_line_split |
fixture.go | // Copyright 2021 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package crossdevice
import (
"context"
"encoding/json"
"io/ioutil"
"path/filepath"
"strconv"
"strings"
"time"
"chromiumos/tast/common/android/adb"
crossdevicecommo... | else {
crosRecordErr = uiauto.StopRecordFromKBAndSaveOnError(ctx, f.tconn, s.HasError, s.OutDir(), f.downloadsPath)
}
if crosRecordErr != nil {
s.Fatal("Failed to save CrOS screen recording: ", crosRecordErr)
}
}
if s.HasError() {
if err := BugReport(ctx, f.androidDevice.Device, s.OutDir()); err != ni... | {
// Smart Lock tests automatically stop the screen recording when they lock the screen.
// The screen recording should still exist though.
crosRecordErr = uiauto.SaveRecordFromKBOnError(ctx, f.tconn, s.HasError, s.OutDir(), f.downloadsPath)
} | conditional_block |
fixture.go | // Copyright 2021 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package crossdevice
import (
"context"
"encoding/json"
"io/ioutil"
"path/filepath"
"strconv"
"strings"
"time"
"chromiumos/tast/common/android/adb"
crossdevicecommo... | (ctx context.Context) error {
if err := testing.Poll(ctx, func(ctx context.Context) error {
out, err := testexec.CommandContext(ctx, "/usr/local/autotest/cros/scripts/wifi", "connect", "nearbysharing_1", "password").CombinedOutput(testexec.DumpLogOnError)
if err != nil {
if strings.Contains(string(out), "alread... | ConnectToWifi | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.