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
routes.go
StackListener.AddListenerWithAddr(utils.GetListenAddr(a.addr, a.port)); err != nil { return err } logger.Infow("listening for requests and metrics", "address", addr) if a.addrIPv6 != "" && a.addrIPv6 != a.addr { v6Addr := utils.GetListenAddr(a.addrIPv6, a.port) if err := dualStackListener.AddListenerWithAddr(...
equest) { w.Header(
identifier_name
routes.go
files "github.com/swaggo/files" ginSwagger "github.com/swaggo/gin-swagger" _ "github.com/Tencent/bk-bcs/bcs-services/bcs-monitor/docs" // docs xxx "github.com/Tencent/bk-bcs/bcs-services/bcs-monitor/pkg/api/logrule" "github.com/Tencent/bk-bcs/bcs-services/bcs-monitor/pkg/api/metrics" "github.com/Tencent/bk-bcs/bc...
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...
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
files "github.com/swaggo/files" ginSwagger "github.com/swaggo/gin-swagger" _ "github.com/Tencent/bk-bcs/bcs-services/bcs-monitor/docs" // docs xxx "github.com/Tencent/bk-bcs/bcs-services/bcs-monitor/pkg/api/logrule" "github.com/Tencent/bk-bcs/bcs-services/bcs-monitor/pkg/api/metrics" "github.com/Tencent/bk-bcs/bc...
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
.board.get((i, j), self.BLANK) def delch(self, pos, ch): if self.gettile(pos) == ch: self.addch(pos, self.BLANK) def _update(self, row, col): ch1 = self.board.get((2*row, col), self.BLANK) ch2 = self.board.get((2*row+1, col), self.BLANK) if ch1 != self.BLANK and ch2...
d = d * r p += d res.append(d) break
conditional_block
pysnake.py
= int(pos.imag) j = int(pos.real) return self.board.get((i, j), self.BLANK) def delch(self, pos, ch): if self.gettile(pos) == ch: self.addch(pos, self.BLANK) def _update(self, row, col): ch1 = self.board.get((2*row, col), self.BLANK) ch2 = self.board.get((2...
w = max(1, math.ceil(math.log(len(snakes[i].tail), 2))) n[i] += w 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: ...
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
_rect(self, w, h): pos = self.random_rect(w, h) while not self.free_rect(pos, w, h): pos = self.random_rect(w, h) return pos def add_rect(self, pos, ch, w, h): for i in range(h): for j in range(w): self.screen.addch(pos + i + j*1j, ch) de...
msg = 'Thanks for playing!'
random_line_split
pysnake.py
= int(pos.imag) j = int(pos.real) return self.board.get((i, j), self.BLANK) def delch(self, pos, ch): if self.gettile(pos) == ch: self.addch(pos, self.BLANK) def _update(self, row, col): ch1 = self.board.get((2*row, col), self.BLANK) ch2 = self.board.get((2...
(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
static: false }) chart: ElementRef; lineChartData$: Observable<ChartData<'line'>>; lineChartOptions$: Observable<ChartOptions>; communityLabel$: Observable<string>; yourLabel$: Observable<string>; @Input() communityTooltip: string; @Input() yourTooltip: string; @Input() turnLabel = 'Turn'; @Input() statLabel...
(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
Size$$ = new BehaviorSubject<number>(null); private showYAxis$$ = new BehaviorSubject<boolean>(true); private communityLabel$$ = new BehaviorSubject<string>('Community'); private yourLabel$$ = new BehaviorSubject<string>('You'); private communityValues$$ = new BehaviorSubject<readonly NumericTurnInfo[]>(null); pr...
`; const tableRoot = tooltipEl.querySelector('.content'); tableRoot.innerHTML = innerHtml;
random_line_split
graph-with-comparison-new.component.ts
static: false }) chart: ElementRef; lineChartData$: Observable<ChartData<'line'>>; lineChartOptions$: Observable<ChartOptions>; communityLabel$: Observable<string>; yourLabel$: Observable<string>; @Input() communityTooltip: string; @Input() yourTooltip: string; @Input() turnLabel = 'Turn'; @Input() statLabel...
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
::ISOL, }, } } } impl From<&ArabicGlyph> for RawGlyph<()> { fn from(arabic_glyph: &ArabicGlyph) -> RawGlyph<()> { RawGlyph { unicodes: arabic_glyph.unicodes.clone(), glyph_index: arabic_glyph.glyph_index, liga_component_pos: arabic_glyph.liga_comp...
#[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
}
random_line_split
arabic.rs
::ISOL, }, } } } impl From<&ArabicGlyph> for RawGlyph<()> { fn from(arabic_glyph: &ArabicGlyph) -> RawGlyph<()> { RawGlyph { unicodes: arabic_glyph.unicodes.clone(), glyph_index: arabic_glyph.glyph_index, liga_component_pos: arabic_glyph.liga_comp...
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
::ISOL, }, } } } impl From<&ArabicGlyph> for RawGlyph<()> { fn from(arabic_glyph: &ArabicGlyph) -> RawGlyph<()> { RawGlyph { unicodes: arabic_glyph.unicodes.clone(), glyph_index: arabic_glyph.glyph_index, liga_component_pos: arabic_glyph.liga_comp...
() { let cs = vec![ '\
test_artificial
identifier_name
arabic.rs
} impl From<&RawGlyph<()>> for ArabicGlyph { fn from(raw_glyph: &RawGlyph<()>) -> ArabicGlyph { // Since there's no `Char` to work out the `ArabicGlyph`s joining type when the glyph's // `glyph_origin` is `GlyphOrigin::Direct`, we fallback to `JoiningType::NonJoining` as // the safest appr...
{ self.extra_data.feature_tag = feature_tag }
identifier_body
kv.rs
let new_pos = stream.byte_offset() as u64; match cmd? { Command::Set { key, .. } => { if let Some(old_cmd) = index.insert(key, (gen, pos..new_pos).into()) { uncompacted += old_cmd.len; } } // 删除 Command::Remove ...
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
let new_pos = stream.byte_offset() as u64; match cmd? { Command::Set { key, .. } => { if let Some(old_cmd) = index.insert(key, (gen, pos..new_pos).into()) { uncompacted += old_cmd.len; } } // 删除 Command::Remove ...
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
new_pos = stream.byte_offset() as u64; match cmd? { Command::Set { key, .. } => { if let Some(old_cmd) = index.insert(key, (gen, pos..new_pos).into()) { uncompacted += old_cmd.len; } } // 删除 Command::Remove { ke...
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
for this output pub subpixel: Subpixel, /// The current transformation applied to this output /// /// You can pre-render your buffers taking this information /// into account and advertising it via `wl_buffer.set_tranform` /// for better performances. pub transform: Transform, /// The s...
(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
layout for this output pub subpixel: Subpixel, /// The current transformation applied to this output /// /// You can pre-render your buffers taking this information /// into account and advertising it via `wl_buffer.set_tranform` /// for better performances. pub transform: Transform, //...
/// 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
for this output pub subpixel: Subpixel, /// The current transformation applied to this output /// /// You can pre-render your buffers taking this information /// into account and advertising it via `wl_buffer.set_tranform` /// for better performances. pub transform: Transform, /// The s...
}); } fn notify_status_listeners( output: &Attached
{ false }
conditional_block
memberweekactrank.py
(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
undir = 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,0777) if not os.path.exists(tmpdir): os.mkdir(tmpdir,0777) logfile = '%(dir)s%(sep)s%(fi...
rid) r
conditional_block
memberweekactrank.py
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
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
KeyCode::Up, .. } | Key { code: KeyCode::K, .. } | Key { code: KeyCode::NumPad8, .. } => Command::Move(Direction::N), Key { code: KeyCode::Down, .. } | Key { code: KeyCode::J, .. } | Key { code: KeyCode::NumPad2, .. } => Command::Move(Direction::S), ...
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
(context: &mut GameContext, dir: Direction) -> CommandResult<()> { // Check if we're bumping into something interactive, and if so don't consume a turn. let position = player_pos(context)?; let new_pos = position + dir; let npc_opt = context.state.world.find_entity( new_pos, |e| context....
use renderer::ui::layers::ChoiceLayer;
random_line_split
command.rs
Move(Direction::S), Key { code: KeyCode::B, .. } | Key { code: KeyCode::NumPad1, .. } => Command::Move(Direction::SW), Key { code: KeyCode::N, .. } | Key { code: KeyCode::NumPad3, .. } => Command::Move(Direction::SE), Key { code: KeyCode::Y, .. } | ...
draw_line
identifier_name
vanilla.py
the most basic operations (generic) from . import ConceptDonor import csv, json import numpy, pandas import socket import traceback from io import StringIO import traceback # sklearn from sklearn import preprocessing # local from preproc.aux import serialize, deserialize import preproc.negotiate as negotiate import...
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
the most basic operations (generic) from . import ConceptDonor import csv, json import numpy, pandas import socket import traceback from io import StringIO import traceback # sklearn from sklearn import preprocessing # local from preproc.aux import serialize, deserialize import preproc.negotiate as negotiate import...
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
the most basic operations (generic) from . import ConceptDonor import csv, json import numpy, pandas import socket import traceback from io import StringIO import traceback # sklearn from sklearn import preprocessing # local from preproc.aux import serialize, deserialize import preproc.negotiate as negotiate import...
(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
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 # sklearn from sklearn import preprocessing # local from preproc.aux import serialize, deserialize import preproc.negotiate as negotia...
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
json:"host_name"` CreateTime time.Time `json:"create_time"` InternalIP string `json:"internal_ip"` ExternalIP string `json:"external_ip"` RootPass string `json:"root_pass,omitempty"` KeyPath string `json:"key_path,omitempty"` //Manag...
GetCondition
identifier_name
node.go
status.NodeInfo.MachineID, SystemUUID: status.NodeInfo.SystemUUID, BootID: status.NodeInfo.BootID, KernelVersion: status.NodeInfo.KernelVersion, OSImage: status.NodeInfo.OSImage, OperatingSystem: status.NodeInfo.OperatingSystem, ...
{ 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
R: a.PodCIDR, //node default unscheduler Unschedulable: true, } return hn } //HostNode - kato node entity type HostNode struct { ID string `json:"uuid"` HostName string `json:"host_name"` CreateTime time.Time `json:"create_time"` InternalIP str...
} 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
CIDR: a.PodCIDR, //node default unscheduler Unschedulable: true, } return hn } //HostNode - kato node entity type HostNode struct { ID string `json:"uuid"` HostName string `json:"host_name"` CreateTime time.Time `json:"create_time"` InternalIP ...
//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
1")] const WORD_SQUARE_WIDTH:usize = 11; #[cfg(feature = "width-12")] const WORD_SQUARE_WIDTH:usize = 12; #[cfg(feature = "width-13")] const WORD_SQUARE_WIDTH:usize = 13; #[cfg(feature = "width-14")] const WORD_SQUARE_WIDTH:usize = 14; #[cfg(feature = "width-15")] const WORD_SQUARE_WIDTH:usize = 15; #[cfg(feature = "h...
.arg(Arg::with_name("wordlist") .required(true) .help("the wordlist file path, a plain-text UTF-8 file with each word separated by a newline") ) .arg(Arg::with_name("ignore-empty-wordlist") .long("ignore-empty-wordlist") ...
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
11")] const WORD_SQUARE_WIDTH:usize = 11; #[cfg(feature = "width-12")] const WORD_SQUARE_WIDTH:usize = 12; #[cfg(feature = "width-13")] const WORD_SQUARE_WIDTH:usize = 13; #[cfg(feature = "width-14")] const WORD_SQUARE_WIDTH:usize = 14; #[cfg(feature = "width-15")] const WORD_SQUARE_WIDTH:usize = 15; #[cfg(feature = "...
.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
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
, } } pub
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
thread::JoinHandle<()>>, } impl Worker { pub fn new(hsprt_sender: hsprt::Sender) -> (Self, Sender) { let (sender, request_receiver) = mpsc::channel::<Action>(); let app_sender = Sender { sender }; let (connection_worker, connection_sender) = connection::Worker::new(app_sender.clone()); ...
{ warn!("[app] リクエストではない DAP メッセージを無視"); } Action::AfterStopped(file_name, line) => { let file_path = self.resolve_file_path(&file_name); self.state = RuntimeState
identifier_body
app.rs
前。 BeforeTerminating, AfterDebugInfoLoaded(hsp_ext::debug_info::DebugInfo<hsp_ext::debug_info::HspConstantMap>), AfterGetVar { seq: i64, variables: Vec<dap::Variable>, }, } /// `Worker` に処理を依頼するもの。 #[derive(Clone, Debug)] pub(crate) struct Sender { sender: mpsc::Sender<Action>, } i...
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
(canvas, null)['paddingTop'], 10) || 0; this.styleBorderLeft = parseInt(document.defaultView.getComputedStyle(canvas, null)['borderLeftWidth'], 10) || 0; this.styleBorderTop = parseInt(document.defaultView.getComputedStyle(canvas, null)['borderTopWidth'], 10) || 0; } this.border ...
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
this.htmlLeft = html.offsetLeft; this.handleParentScroll = false ; // **** Keep track of state! **** this.valid = false; // when set to false, the canvas will redraw everything this.shapes = []; // the collection of things to be drawn this.dragging = false; // Keep tra...
{ // **** 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
(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
. //! //! This function is an unstable module because this scheme for stack overflow //! detection is not guaranteed to continue in the future. Usage of this module //! is discouraged unless absolutely necessary. // iOS related notes // // It is possible to implement it using idea from // http://www.opensource.apple.c...
(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
. //! //! This function is an unstable module because this scheme for stack overflow //! detection is not guaranteed to continue in the future. Usage of this module //! is discouraged unless absolutely necessary. // iOS related notes // // It is possible to implement it using idea from // http://www.opensource.apple.c...
asm!("mov $0, %fs:0x08" :: "r"(stack_lo) :: "volatile"); } #[cfg(all(windows, target_arch = "x86_64"))] #[inline(always)] unsafe fn target_record_stack_bounds(stack_lo: uint, stack_hi: uint) { // stack range is at TIB: %gs:0x08 (top) and %gs:0x10 (bottom) asm!("mov $0, %gs:0x08" :: "...
{ // 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
. //! //! This function is an unstable module because this scheme for stack overflow //! detection is not guaranteed to continue in the future. Usage of this module //! is discouraged unless absolutely necessary. // iOS related notes // // It is possible to implement it using idea from // http://www.opensource.apple.c...
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
"getAddressShard error" errGetAccountAndAddressIndexFromUser = "invalid account or address index provided by user" ) type networkConfig struct { Data struct { Config struct { ChainID string `json:"erd_chain_id"` Denomination int `json:"erd_denomination"` GasPerDataByte ...
(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
_data_byte"` LatestTagSoftwareVersion string `json:"erd_latest_tag_software_version"` MetaConsensusGroupSize uint32 `json:"erd_meta_consensus_group_size"` MinGasLimit uint64 `json:"erd_min_gas_limit"` MinGasPrice uint64 `json:"erd_min_gas_price"` MinTransactionVersion uint3...
{ 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
"getAddressShard error" errGetAccountAndAddressIndexFromUser = "invalid account or address index provided by user" ) type networkConfig struct { Data struct { Config struct { ChainID string `json:"erd_chain_id"` Denomination int `json:"erd_denomination"` GasPerDataByte ...
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
"getAddressShard error" errGetAccountAndAddressIndexFromUser = "invalid account or address index provided by user" ) type networkConfig struct { Data struct { Config struct { ChainID string `json:"erd_chain_id"` Denomination int `json:"erd_denomination"` GasPerDataByte ...
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
} 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
Symbols(symbols []*Symbol, ranges []pcRange, coverPoints [2][]uint64) []*Symbol { // Assign coverage point PCs to symbols. // Both symbols and coverage points are sorted, so we do it one pass over both. selectPCs := func(u *ObjectUnit, typ int) *[]uint64 { return [2]*[]uint64{&u.PCs, &u.CMPs}[typ] } for pcType :...
(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
Symbols(symbols []*Symbol, ranges []pcRange, coverPoints [2][]uint64) []*Symbol { // Assign coverage point PCs to symbols. // Both symbols and coverage points are sorted, so we do it one pass over both. selectPCs := func(u *ObjectUnit, typ int) *[]uint64 { return [2]*[]uint64{&u.PCs, &u.CMPs}[typ] } for pcType :...
symbolizerC := make(chan symbolizerResult, procs) pcchan := make(chan []uint64, procs) for p := 0; p < procs; p++ { go func() { symb := symbolizer.NewSymbolizer(target) defer symb.Close() var res symbolizerResult for pcs := range pcchan { frames, err := symb.SymbolizeArray(obj, pcs) if err != n...
{ 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
Unit, pcType) = pcs[firstSymbolPC:i] firstSymbolPC = -1 } curSymbol = symb if symb != nil && firstSymbolPC == -1 { firstSymbolPC = i } } if curSymbol != nil { *selectPCs(&curSymbol.ObjectUnit, pcType) = pcs[firstSymbolPC:] } } // Assign compile units to symbols based on unit pc ranges. /...
{ break }
conditional_block
warwick.go
open a spot that may be immediately filled from the draw, discard or hand, 2: refill that spot, 3: add another, 4: refill both Discard vs. Trash There are two face up piles where cards go after they're used. When building, cards go into the discard. The Market buildings allow you to draw from the discard pile (you...
// initialize the players for id := range players { players[id].Hand = &card.Hand{} players[id].Hand.Limit = 5 players[id].Hand.Max = 7 // create the hand with an extra 2 slots beyond the limit, which could happen // if you use a soldier and then do an exchange players[id].Hand.Cards = make([]*card.Card,...
{ 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
parameter testStockId := -1 var permutation []int if testStockId != -1 { /* rather than having to specify the whole deck, I allow you to only specify the top of the deck */ fillSize := stockSize - len(card.TestStock[testStockId]) fillOut := rand.Perm(fillSize) // for easier reading I specify the TestStock i...
{ // 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
open a spot that may be immediately filled from the draw, discard or hand, 2: refill that spot, 3: add another, 4: refill both Discard vs. Trash There are two face up piles where cards go after they're used. When building, cards go into the discard. The Market buildings allow you to draw from the discard pile (you...
(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
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
< -8kbt) to a random site?""" return mean([score(matrix,random_site(10)) < -8 for i in xrange(n)]) def predict_mean_prop(matrix,ns=True): """estimate <exp(-beta*score(matrix,site))> ns: non-specific binding""" return (product([mean([exp(-beta*ep) for ep in col]) for col in matrix]) + (...
# 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
-8kbt) to a random site?""" return mean([score(matrix,random_site(10)) < -8 for i in xrange(n)]) def predict_mean_prop(matrix,ns=True): """estimate <exp(-beta*score(matrix,site))> ns: non-specific binding""" return (product([mean([exp(-beta*ep) for ep in col]) for col in matrix]) + (ex...
(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
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
-8kbt) to a random site?""" return mean([score(matrix,random_site(10)) < -8 for i in xrange(n)]) def predict_mean_prop(matrix,ns=True): """estimate <exp(-beta*score(matrix,site))> ns: non-specific binding""" return (product([mean([exp(-beta*ep) for ep in col]) for col in matrix]) + (ex...
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
of 10 clusters (each with a different genetic mean size) goes through. number_of_stdevs=5 #this name is a bit confusing, but this is the number of different st_devs to be run in the iteration replicates=10 #use these lists for running multiple iterations of cell and group stdevs group_stdev_iterator=np.linspace(...
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
of 10 clusters (each with a different genetic mean size) goes through. number_of_stdevs=5 #this name is a bit confusing, but this is the number of different st_devs to be run in the iteration replicates=10 #use these lists for running multiple iterations of cell and group stdevs group_stdev_iterator=np.linspace(...
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
Global Var Unset Isset Empty HaltCompiler Class Trait Interface Extends Implements ObjectOperator List Array Callable Line File Dir ClassC TraitC MethodC FuncC Comment DocComment OpenTag OpenTagWithEcho CloseTag Whitespace StartHeredoc EndHeredoc DollarOpenCurlyBraces CurlyOpen Paamayi...
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
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
"Clone", Noelse: "Noelse", Elseif: "Elseif", Else: "Else", Endif: "Endif", Static: "Static", Abstract: "Abstract", Final: "Final", Private: "Private", Protected: "Prote...
{ return t }
conditional_block
token.go
of Global Var Unset Isset Empty HaltCompiler Class Trait Interface Extends Implements ObjectOperator List Array Callable Line File Dir ClassC TraitC MethodC FuncC Comment DocComment OpenTag OpenTagWithEcho CloseTag Whitespace StartHeredoc EndHeredoc DollarOpenCurlyBraces CurlyOpen Paama...
() 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
of synchronizing with the homeserver (i.e. getting all the latest //! events), use the `Client::sync`: //! //! ```no_run //! # use futures::{Future, Stream}; //! # use ruma_client::Client; //! # let homeserver_url = "https://example.com".parse().unwrap(); //! # let client = Client::https(homeserver_url, None).unwrap()...
} #[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
let homeserver_url = "https://example.com".parse().unwrap(); //! # let client = Client::https(homeserver_url, None).unwrap(); //! let work = client.sync(None, None, true).map(|response| { //! // Do something with the data in the response... //! # Ok::<(), ruma_client::Error>(()) //! }); //! //! // Start `work` o...
since: Option<String>,
random_line_split
lib.rs
Request` type. `call` will return a future that will //! resolve to the relevant `Response` type. //! //! For example: //! //! ```no_run //! # use futures::Future; //! # use ruma_client::Client; //! # let homeserver_url = "https://example.com".parse().unwrap(); //! # let client = Client::https(homeserver_url, None).unw...
request
identifier_name
lib.rs
f893n9:example.com").unwrap()); //! # Ok::<(), ruma_client::Error>(()) //! }); //! //! // Start `work` on a futures runtime... //! ``` #![deny( missing_copy_implementations, missing_debug_implementations, missing_docs, warnings )] #![warn( clippy::empty_line_after_outer_attr, clippy::expl_i...
{ 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
(stable, self.wantToShuffle) # remove some data for reshaping trainDataMissing = trainData.shape[0] % self.windowSize validationDataMissing = validationData.shape[0] % self.windowSize if trainDataMissing != 0: trainData = trainData[: -trainDataMissing] if validationD...
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
.divideData(stable, self.wantToShuffle) # remove some data for reshaping trainDataMissing = trainData.shape[0] % self.windowSize validationDataMissing = validationData.shape[0] % self.windowSize if trainDataMissing != 0: trainData = trainData[: -trainDataMissing] if ...
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
95), 'upperStd': np.percentile(stdOfTrainData, 95), 'cycle': cycle} # flatten dataset and min-max normalize trainData = minMaxScaler.transform(trainData.reshape(-1, 1)) validationData = minMaxScaler.transform(validationData.reshape(-1, 1)) # reshape inputs [...
re(self, t
identifier_name
AutoEncoderBasedEvaluation.py
trainData = trainData[: -trainDataMissing] if validationDataMissing != 0: validationData = validationData[: -validationDataMissing] # plot dataset [optional] print("data shape:", trainData.shape, validationData.shape) plt.plot(trainData, label="train") pl...
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
32>::new(); let mut ref_libIds = BTreeMap::<String, u32>::new(); let mut targets_matched = BTreeMap::<String, u32>::new(); //let mut geneIds = TreeMap::<String, u32>::new(); // first parse the reference genome from the fasta file process_fasta(&fasta_file_arg, &fasta_re, geneid_pattern, &mut gene_m...
{ for pos in mm_positions { // TODO: next line is not compiling match_string.insert_str(pos, "X"); } }
conditional_block
main.rs
() { // buffers to hold parsed arguments let mut fasta_file_arg = String::new(); let mut sam_file_arg = String::new(); let mut mapping_match_pattern = String::from("M{20,21}$"); let mut geneid_pattern = String::from("_"); let mut logfile_out = String::from("./log.out"); // TODO: change argparse ...
// alignment section - skip the header starting with @ if next_line.starts_with('@') { continue; } // ----------the basic algorithm starts here --- // now split let al_arr: Vec<&str> = next_line.trim_right().split("\t").collect(); //only count the map...
{ //-> (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
""); let mut design_out_file = BufWriter::new(File::create(format!("{}-designs.txt", out_base_name)).expect("problem opening output file")); design_out_file.write_all(b"sgRNA\tCount\n").unwrap(); // let mut uniqLibIds for (k, v) in &ref_libIds { design_out_file.write_all(k.replace("\"...
Some(v) => *v += 1, None => println!("illegal reference lib id encountered '{}'", &al_arr[2].split("_").nth(0).unwrap()) }
random_line_split
main.rs
() { // buffers to hold parsed arguments let mut fasta_file_arg = String::new(); let mut sam_file_arg = String::new(); let mut mapping_match_pattern = String::from("M{20,21}$"); let mut geneid_pattern = String::from("_"); let mut logfile_out = String::from("./log.out"); // TODO: change argparse ...
(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
TOKEN_ADJUST_PRIVILEGES = 0x0020 TOKEN_ADJUST_GROUPS = 0x0040 TOKEN_ADJUST_DEFAULT = 0x0080 TOKEN_ADJUST_SESSIONID = 0x0100 TOKEN_READ = (STANDARD_RIGHTS_READ | TOKEN_QUERY) TOKEN_ALL_ACCESS = ( STANDARD_RIGHTS_REQUIRED | TOKEN_ASSIGN_PRIMARY | TOKEN_DUPLICATE | ...
(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
TOKEN_ADJUST_PRIVILEGES = 0x0020 TOKEN_ADJUST_GROUPS = 0x0040 TOKEN_ADJUST_DEFAULT = 0x0080 TOKEN_ADJUST_SESSIONID = 0x0100 TOKEN_READ = (STANDARD_RIGHTS_READ | TOKEN_QUERY) TOKEN_ALL_ACCESS = ( STANDARD_RIGHTS_REQUIRED | TOKEN_ASSIGN_PRIMARY | TOKEN_DUPLICATE | ...
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
TOKEN_ADJUST_PRIVILEGES = 0x0020 TOKEN_ADJUST_GROUPS = 0x0040 TOKEN_ADJUST_DEFAULT = 0x0080 TOKEN_ADJUST_SESSIONID = 0x0100 TOKEN_READ = (STANDARD_RIGHTS_READ | TOKEN_QUERY) TOKEN_ALL_ACCESS = ( STANDARD_RIGHTS_REQUIRED | TOKEN_ASSIGN_PRIMARY |
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
TOKEN_ADJUST_PRIVILEGES = 0x0020 TOKEN_ADJUST_GROUPS = 0x0040 TOKEN_ADJUST_DEFAULT = 0x0080 TOKEN_ADJUST_SESSIONID = 0x0100 TOKEN_READ = (STANDARD_RIGHTS_READ | TOKEN_QUERY) TOKEN_ALL_ACCESS = ( STANDARD_RIGHTS_REQUIRED | TOKEN_ASSIGN_PRIMARY | TOKEN_DUPLICATE | ...
# [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
prob_sum', type=str, help='Specify the strategy used to compute the per wxample accuracy: (majority, prob_sum, log_prob_sum, all)') ################## augmentation parameters ##################### parser.add_argument('--aug_var', default='0.0434', type=float, help='variance of noise for data augmentation') parser.add_...
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
parser.add_argument('--aug_granularity', default='per_ex', type=str, help='granularity of fir selection for training pipelinecan be per_ex, per_batch, per_slice') args = parser.parse_args() args.cuda = not args.no_cuda and torch.cuda.is_available() if args.cuda: torch.cuda.manual_seed(args.seed) use_cuda = not arg...
masked_retrain
identifier_name
main.py
"""=====================""" """ multi-rho admm train""" """=====================""" initial_rho = args.rho if args.admm: admm_prune(initial_rho, criterion, optimizer, scheduler) """==============""" """masked retrain""" """==============""" if args.masked_retrain: m...
if name in masks: W.grad *= masks[name]
conditional_block
main.py
(): if (args.admm and args.masked_retrain): raise ValueError("can't do both masked retrain and admm") elif (not args.admm) and (not args.masked_retrain) and args.purification: print("Model Purification") post_column_prune(model,0.04) post_filter_prune(model,0.23) ...
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
get length (used for normalize) return math.sqrt((self.x**2 + self.y**2)) def normalize(self): # divides a vector by its length l = self.length() if l != 0: return (self.x / l, self.y / l) return None class Sprite(pygame.sprite.Sprite): def __init__(self): ...
(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
# get length (used for normalize) return math.sqrt((self.x**2 + self.y**2)) def normalize(self): # divides a vector by its length l = self.length() if l != 0: return (self.x / l, self.y / l) return None class Sprite(pygame.sprite.Sprite): def __init__(self)...
- 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
# get length (used for normalize) return math.sqrt((self.x**2 + self.y**2)) def normalize(self): # divides a vector by its length l = self.length() if l != 0: return (self.x / l, self.y / l) return None class Sprite(pygame.sprite.Sprite): def __init__(self)...
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
# get length (used for normalize) return math.sqrt((self.x**2 + self.y**2)) def normalize(self): # divides a vector by its length
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
exception {e}") # from, to (copies all files in from, to the to dir) def copyContents(f, t): "Copy all files in f into t dir" [shutil.copy(os.path.join(f, p), t) if os.path.isfile(os.path.join(f, p)) else shutil.copytree(os.path.join(f, p), os.path.join(t, p)) for p in os.l...
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
exception {e}") # from, to (copies all files in from, to the to dir) def copyContents(f, t): "Copy all files in f into t dir" [shutil.copy(os.path.join(f, p), t) if os.path.isfile(os.path.join(f, p)) else shutil.copytree(os.path.join(f, p), os.path.join(t, p)) for p in os.l...
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
an exception {e}") # from, to (copies all files in from, to the to dir) def copyContents(f, t): "Copy all files in f into t dir" [shutil.copy(os.path.join(f, p), t) if os.path.isfile(os.path.join(f, p)) else shutil.copytree(os.path.join(f, p), os.path.join(t, p)) for p in o...
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
an exception {e}") # from, to (copies all files in from, to the to dir) def copyContents(f, t): "Copy all files in f into t dir" [shutil.copy(os.path.join(f, p), t) if os.path.isfile(os.path.join(f, p)) else shutil.copytree(os.path.join(f, p), os.path.join(t, p)) for p in o...
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
("Failed to start Chrome: ", err) } f.cr = cr tconn, err := cr.TestAPIConn(ctx) if err != nil { s.Fatal("Creating test API connection failed: ", err) } f.tconn = tconn defer faillog.DumpUITreeWithScreenshotOnError(cleanupCtx, s.OutDir(), s.HasError, cr, "fixture") // Capture a bug report on the Android pho...
{ // 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
on")); err != nil { s.Log("Smart Lock notification did not appear after 30 seconds, proceeding anyways") } if err := phonehub.Enable(ctx, tconn, cr); err != nil { s.Fatal("Failed to enable Phone Hub: ", err) } if err := phonehub.Hide(ctx, tconn); err != nil { s.Fatal("Failed to hide Phone Hub ...
ConnectToWifi
identifier_name
fixture.go
with all Cross Device features enabled with lacros enabled", Contacts: []string{ "kyleshima@chromium.org", "chromeos-sw-engprod@google.com", }, Parent: "crossdeviceAndroidSetupPhoneHub", Impl: NewCrossDeviceOnboarded(FixtureOptions{true, true, true, false}, func(ctx context.Context, s *testing.FixtState)...
random_line_split