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
regexp.go
number of unclosed lpars pos int; ch int; } const endOfFile = -1 func (p *parser) c() int { return p.ch } func (p *parser) nextc() int { if p.pos >= len(p.re.expr) { p.ch = endOfFile } else { c, w := utf8.DecodeRuneInString(p.re.expr[p.pos:len(p.re.expr)]); p.ch = c; p.pos += w; } return p.ch; } func...
{ for i := 0; i < len(re.inst); i++ { inst := re.inst[i]; if inst.kind() == _END { continue } inst.setNext(unNop(inst.next())); if inst.kind() == _ALT { alt := inst.(*_Alt); alt.left = unNop(alt.left); } } }
identifier_body
regexp.go
.ranges[n] = a; n++; cclass.ranges[n] = b; n++; } func (cclass *_CharClass)
(c int) bool { for i := 0; i < len(cclass.ranges); i = i + 2 { min := cclass.ranges[i]; max := cclass.ranges[i+1]; if min <= c && c <= max { return !cclass.negate } } return cclass.negate; } func newCharClass() *_CharClass { c := new(_CharClass); c.ranges = make([]int, 0, 20); return c; } // --- ANY ...
matches
identifier_name
mod.rs
<usize>)> { Ingredient::parent_columns(&**self, column) } /// Resolve where the given field originates from. If the view is materialized, or the value is /// otherwise created by this view, None should be returned. pub fn resolve(&self, i: usize) -> Option<Vec<(NodeIndex, usize)>> { Ing...
f) -> b
identifier_name
mod.rs
usize)>> { Ingredient::resolve(&**self, i) } /// Returns true if this operator requires a full materialization pub fn requires_full_materialization(&self) -> bool { Ingredient::requires_full_materialization(&**self) } pub fn can_query_through(&self) -> bool { Ingredient::c...
let NodeType::Internal(NodeOperator::Union(_)) = self.inner { true } else { false } } pub fn
identifier_body
mod.rs
children: Vec::new(), inner: inner.into(), taken: false, purge: false, sharded_by: Sharding::None, } } pub fn mirror<NT: Into<NodeType>>(&self, n: NT) -> Node { Self::new(&*self.name, &self.fields, n) } pub fn named_mirror<N...
index: None, domain: None, fields: fields.into_iter().map(|s| s.to_string()).collect(), parents: Vec::new(),
random_line_split
gdb_stub.rs
attached to a process self.send(b"1") } b"HostInfo" => { const MACH_O_ARM: u32 = 12; const MACH_O_ARM_V4T: u32 = 5; self.send_fmt(format_args!("cputype:{};cpusubtype:{};ostype:none;vendor:none;endian:little;ptrsize:4;", MACH_O_ARM,...
#[derive(Debug)] enum StopReason { ReadWatchpoint(u32),
random_line_split
gdb_stub.rs
psr.into() } else if reg_index == REG_PC { self.gba.arm.current_pc() } else if reg_index < 16 { self.gba.arm.regs[reg_index] } else { return self.send(b"E00"); }; self.send(&int_to_hex_le(reg)) } fn write_gpr(&mut self, msg: &[u8]) -> ...
read16
identifier_name
gdb_stub.rs
6 { self.gba.arm.regs[reg_index] } else { return self.send(b"E00"); }; self.send(&int_to_hex_le(reg)) } fn write_gpr(&mut self, msg: &[u8]) -> GResult { let (reg_index_str, value_str) = split_at(msg, b'=')?; let reg_index = hex_to_int(reg_index_st...
{ self.check_read(addr); self.delegate.read16(addr) }
identifier_body
install.js
cp.execSync('npm install', { cwd: __dirname, }); console.log('[info] Please enter the command again. Sorry!'); process.exit(15); } const chalk = require('chalk'); const redis = require('ioredis'); const rl = require('prompt-sync')() const log = console.log; const info = (...args) => { log(chal...
JSON.parse(file); } catch (err) {
// Confirm it's valid let file = fs.readFileSync(confDir).toString(); try {
random_line_split
install.js
cp.execSync('npm install', { cwd: __dirname, }); console.log('[info] Please enter the command again. Sorry!'); process.exit(15); } const chalk = require('chalk'); const redis = require('ioredis'); const rl = require('prompt-sync')() const log = console.log; const info = (...args) => { log(chal...
else { // Ok conf.redis = { host: add, port, keyPrefix: prefix, enableOfflineQueue: true, password: pass, }...
{ // Ask for pass err(rErr) pass = rl('It looks like your redis server requires a password. Please enter it and press enter.\n'); if (!pass) { err('Exiting due to no pass.'); ...
conditional_block
declare.rs
_decl_impl!(); method_decl_impl!(A); method_decl_impl!(A, B); method_decl_impl!(A, B, C); method_decl_impl!(A, B, C, D); method_decl_impl!(A, B, C, D, E); method_decl_impl!(A, B, C, D, E, F); method_decl_impl!(A, B, C, D, E, F, G); method_decl_impl!(A, B, C, D, E, F, G, H); method_decl_impl!(A, B, C, D, E, F, G, H, I);...
{ self.add_method_description_common::<Args, Ret>(sel, is_required, false) }
identifier_body
declare.rs
} ``` */ use std::ffi::CString; use std::mem; use std::ptr; use runtime::{BOOL, Class, Imp, NO, Object, Protocol, Sel, self}; use {Encode, EncodeArguments, Encoding, Message}; /// Types that can be used as the implementation of an Objective-C method. pub trait MethodImplementation { /// The callee type of the m...
else { Some(ClassDecl { cls }) } } /// Constructs a `ClassDecl` with the given name and superclass. /// Returns `None` if the class couldn't be allocated. pub fn new(name: &str, superclass: &Class) -> Option<ClassDecl> { ClassDecl::with_superclass(name, Some(superclass)) ...
{ None }
conditional_block
declare.rs
} ``` */ use std::ffi::CString; use std::mem; use std::ptr; use runtime::{BOOL, Class, Imp, NO, Object, Protocol, Sel, self}; use {Encode, EncodeArguments, Encoding, Message}; /// Types that can be used as the implementation of an Objective-C method. pub trait MethodImplementation { /// The callee type of the m...
let size = mem::size_of::<T>(); let align = log2_align_of::<T>(); let success = unsafe { runtime::class_addIvar(self.cls, c_name.as_ptr(), size, align, encoding.as_ptr()) }; assert!(success != NO, "Failed to add ivar {}", name); } /// Adds a p...
let encoding = CString::new(T::encode().as_str()).unwrap();
random_line_split
declare.rs
} ``` */ use std::ffi::CString; use std::mem; use std::ptr; use runtime::{BOOL, Class, Imp, NO, Object, Protocol, Sel, self}; use {Encode, EncodeArguments, Encoding, Message}; /// Types that can be used as the implementation of an Objective-C method. pub trait MethodImplementation { /// The callee type of the m...
<F>(&mut self, sel: Sel, func: F) where F: MethodImplementation<Callee=Object> { let encs = F::Args::encodings(); let encs = encs.as_ref(); let sel_args = count_args(sel); assert!(sel_args == encs.len(), "Selector accepts {} arguments, but function accepts {}", ...
add_method
identifier_name
annealing3.rs
, 0xe4, 0xaa, 0x35, 0x07, 0x99, 0xe3, 0x2b, 0x9d, 0xc6, ]; fn tscore(solution: &Vec<Point>, input: &Input) -> (f64, f64)
( dislike / (input.hole.exterior().coords_count() as f64), -(vx + vy), ) } fn ascore(value: (f64, f64), progress: f64) -> f64 { value.0 * progress + (1.0 - progress) * value.1 } pub fn solve( input: &Input, mut solution: Vec<Point>, time_limit: Duration, fix_seed: bool, ...
{ let dislike = calculate_dislike(&solution, &input.hole); let mut gx: f64 = 0.0; let mut gy: f64 = 0.0; for p in solution.iter() { gx += p.x(); gy += p.y(); } gx /= solution.len() as f64; gy /= solution.len() as f64; let mut vx: f64 = 0.0; let mut vy: f64 = 0.0; ...
identifier_body
annealing3.rs
, 0xe4, 0xaa, 0x35, 0x07, 0x99, 0xe3, 0x2b, 0x9d, 0xc6, ]; fn tscore(solution: &Vec<Point>, input: &Input) -> (f64, f64) { let dislike = calculate_dislike(&solution, &input.hole); let mut gx: f64 = 0.0; let mut gy: f64 = 0.0; for p in solution.iter() { gx += p.x(); gy += p.y(); } ...
temperature = initial_temperature * (1.0 - progress) * (-progress).exp2(); } // move to neighbor let r = rng.gen::<f64>(); if r > progress { let mut i = 0; { let r = rng.gen::<usize>() % distance_total; let mut sum = 0;...
// tweak temperature progress = elapsed.as_secs_f64() / time_limit.as_secs_f64();
random_line_split
annealing3.rs
, 0xe4, 0xaa, 0x35, 0x07, 0x99, 0xe3, 0x2b, 0x9d, 0xc6, ]; fn tscore(solution: &Vec<Point>, input: &Input) -> (f64, f64) { let dislike = calculate_dislike(&solution, &input.hole); let mut gx: f64 = 0.0; let mut gy: f64 = 0.0; for p in solution.iter() { gx += p.x(); gy += p.y(); } ...
return p; } return solution[i]; } unreachable!() } fn is_valid_point_move( index: usize, p: &Point, solution: &[Point], original_vertices: &[Point], out_edges: &[Vec<usize>], hole: &Polygon, epsilon: i64, ) -> bool { let ok1 = out_edges[index].iter()...
{ continue; }
conditional_block
annealing3.rs
, 0xe4, 0xaa, 0x35, 0x07, 0x99, 0xe3, 0x2b, 0x9d, 0xc6, ]; fn tscore(solution: &Vec<Point>, input: &Input) -> (f64, f64) { let dislike = calculate_dislike(&solution, &input.hole); let mut gx: f64 = 0.0; let mut gy: f64 = 0.0; for p in solution.iter() { gx += p.x(); gy += p.y(); } ...
( from: usize, w: usize, solution: &Vec<Point>, input: &Input, rng: &mut SmallRng, out_edges: &Vec<Vec<usize>>, orders: &Vec<Vec<usize>>, ) -> Option<Vec<Point>> { let mut gx: f64 = 0.0; let mut gy: f64 = 0.0; for p in solution.iter() { gx += p.x(); gy += p.y(); ...
random_move_one_point
identifier_name
mod.rs
, }; use tokio::io::AsyncReadExt; mod hash_writer; use hash_writer::HashWriter; mod error{ use snafu::Snafu; #[derive(Debug,Snafu)] #[snafu(visibility(pub))] pub enum Error{ #[snafu(display("Invalid uri: {}", source))] BadUri{ source: http::uri::InvalidUri, }, ...
(&self, repo_uri: Uri) -> ResolvedArtifact { ResolvedArtifact { artifact: self.clone(), repo: repo_uri, } } pub fn download_from( &self, location: &Path, repo_uri: Uri, manager: download::Manager, log: Logger, ) -> impl Future<...
resolve
identifier_name
mod.rs
, }; use tokio::io::AsyncReadExt; mod hash_writer; use hash_writer::HashWriter; mod error{ use snafu::Snafu; #[derive(Debug,Snafu)] #[snafu(visibility(pub))] pub enum Error{ #[snafu(display("Invalid uri: {}", source))] BadUri{ source: http::uri::InvalidUri, }, ...
if let Some(ref ext) = self.extension { strn.push('@'); strn.push_str(ext); } strn } } impl FromStr for Artifact { type Err = ArtifactParseError; fn from_str(s: &str) -> ::std::result::Result<Self, Self::Err> { let parts: Vec<&str> = s.split('@').col...
{ strn.push(':'); strn.push_str(classifier); }
conditional_block
mod.rs
::*, }; use tokio::io::AsyncReadExt; mod hash_writer; use hash_writer::HashWriter; mod error{ use snafu::Snafu; #[derive(Debug,Snafu)] #[snafu(visibility(pub))] pub enum Error{ #[snafu(display("Invalid uri: {}", source))] BadUri{ source: http::uri::InvalidUri, }, ...
classifier = classifier_fmt, extension = extension_fmt ) } pub fn resolve(&self, repo_uri: Uri) -> ResolvedArtifact { ResolvedArtifact { artifact: self.clone(), repo: repo_uri, } } pub fn download_from( &self, loca...
random_line_split
mod.rs
, }; use tokio::io::AsyncReadExt; mod hash_writer; use hash_writer::HashWriter; mod error{ use snafu::Snafu; #[derive(Debug,Snafu)] #[snafu(visibility(pub))] pub enum Error{ #[snafu(display("Invalid uri: {}", source))] BadUri{ source: http::uri::InvalidUri, }, ...
pub fn get_uri_on(&self, base: &Uri) -> Result<Uri,error::Error> { let base = crate::util::uri_to_url(base).context(error::BadUrl)?; let path = self.to_path(); let url = base.join(path.to_str().expect("non unicode path encountered")).context(error::BadUrl)?; crate::util::url_to_uri...
{ let mut p = PathBuf::new(); p.push(&self.group_path()); p.push(&self.artifact); p.push(&self.version); p.push(&self.artifact_filename()); p }
identifier_body
plots.py
group: List of the demogrpahics to adjust for. quant: a list of event time quantiles at which the models are to be evaluated. strat: Specifies how the bins are computed. One of: "quantile": Equal sized bins. "uniform": Uniformly stratified. adj (str): Determines if IP...
"""Function to plot Calibration Curve at a specified time horizon. Accepts a matplotlib figure instance, risk scores from a trained survival analysis model, and quantiles of event interest and generates an IPCW adjusted calibration curve. Args: ax: a matplotlib subfigure object. scores: ri...
identifier_body
plots.py
subfigure object. scores: risk scores P(T>t) issued by a trained survival analysis model (output of deep_cox_mixtures.models.predict_survival). e: a numpy array of event indicators. t: a numpy array of event/censoring times. a: a numpy vector of protected attributes. f...
# Finally the interpolated curves are averaged over to compute AUC. mean_tpr = np.mean(mean_tprs, axis=0) std_tpr = 1.96 * np.std(mean_tprs, axis=0) / np.sqrt(10) fprs[group]['macro'] = all_fpr tprs[group]['macro'] = mean_tpr tprs_std[group] = std_tpr roc_auc[group] = auc(fprs[group]['ma...
mean_tprs.append(np.interp(all_fpr, fprs[group][i], tprs[group][i]))
conditional_block
plots.py
matplotlib subfigure object. scores: risk scores P(T>t) issued by a trained survival analysis model (output of deep_cox_mixtures.models.predict_survival). e: a numpy array of event indicators. t: a numpy array of event/censoring times. a: a numpy vector of protected attrib...
mean_tpr = np.mean(mean_tprs, axis=0) std_tpr = 1.96 * np.std(mean_tprs, axis=0) / np.sqrt(10) fprs[group]['macro'] = all_fpr tprs[group]['macro'] = mean_tpr tprs_std[group] = std_tpr roc_auc[group] = auc(fprs[group]['macro'], tprs[group]['macro']) ctds_mean[group] = np.mean([ctds[group]...
mean_tprs = [] for i in set(folds): mean_tprs.append(np.interp(all_fpr, fprs[group][i], tprs[group][i])) # Finally the interpolated curves are averaged over to compute AUC.
random_line_split
plots.py
subfigure object. scores: risk scores P(T>t) issued by a trained survival analysis model (output of deep_cox_mixtures.models.predict_survival). e: a numpy array of event indicators. t: a numpy array of event/censoring times. a: a numpy vector of protected attributes. f...
(ax, scores, e, t, a, folds, groups, quant, plot=True): """Function to plot ROC at a specified time horizon. Accepts a matplotlib figure instance, risk scores fro...
plot_roc_curve
identifier_name
main.rs
} fn bar() -> Result<i32, String> { Ok(2) } fn foo_bar() -> Result<i32, String> { let res = foo(2)? + bar()?; Ok(res) } let fb = foo_bar(); assert!(fb.is_ok()); } fn _apuntadores_a_funcion() { fn mas_uno(i: i32) -> i32 { i + 1 } let f: fn(i32) ->...
}; } } fn _multiples_patrones() {
random_line_split
main.rs
, number); } fn _result_funciones() { enum Error { Tecnico } let f: fn(i32) -> Result<i32, Error> = |num: i32| match num { 1 => Ok(num + 1), _ => Err(Error::Tecnico) }; /*fn f(num: i32) -> Result<i32, Error> { match num { 1 => Ok(num + 1), _...
punto.x + punto.y }
identifier_body
main.rs
fn bar() -> Result<i32, String> { Ok(2) } fn foo_bar() -> Result<i32, String> { let res = foo(2)? + bar()?; Ok(res) } let fb = foo_bar(); assert!(fb.is_ok()); } fn _apuntadores_a_funcion() { fn mas_uno(i: i32) -> i32 { i + 1 } let f: fn(i32) -> i32...
tiples_patrones() {
identifier_name
main.rs
Some(x) => x, None => 0, }; assert_eq!(5, number); } fn _result_funciones() { enum Error { Tecnico } let f: fn(i32) -> Result<i32, Error> = |num: i32| match num { 1 => Ok(num + 1), _ => Err(Error::Tecnico) }; /*fn f(num: i32) -> Result<i32, Error> {...
continua el ciclo por encima de y println!("x: {}, y: {}", x, y); } } } fn _enumerate() { for (i,j) in (5..10).enumerate() { println!("i = {} y j = {}", i, j); } let lineas = "hola\nmundo".lines(); for (numero_linea, linea) in lineas.enumerate() { println!("{}: ...
ntinue 'interior; } //
conditional_block
main.go
() { player := NewPlayer() treasure := NewTreasure() treasureMap := NewTreasureMap(mapSize) treasureMap.createMap(listCustomObstacle) treasureMap.setEntity(entity_player, player.Position) for true { treasure.randomizePosition(mapSize[0], mapSize[1]) if treasureMap.setEntity(entity_treasure, treasure.Position...
main
identifier_name
main.go
(entity_treasure, treasure.Position) { break } } treasureMap.render() // display initial condition with treasure fmt.Println("Initial Condition, treasure hid in:", treasure.Position, "Wait for it..") time.Sleep(pause_time * time.Millisecond) treasureMap.setPossibleTreasure() treasureMap.render() // display...
p.FoundTreasure = true } // check possibility of path intersection with best probability to get the most explored map if p.DirectionTaken == up && p.Range[right] > p.Range[up] { p.DirectionTaken = right } else if p.DirectionTaken == right && p.Range[down] > p.Range[right] { p.DirectionTaken = down } retur...
if treasureMap.OriginalMapping[treasureFound] == entity_treasure {
random_line_split
main.go
_treasure, treasure.Position) { break } } treasureMap.render() // display initial condition with treasure fmt.Println("Initial Condition, treasure hid in:", treasure.Position, "Wait for it..") time.Sleep(pause_time * time.Millisecond) treasureMap.setPossibleTreasure() treasureMap.render() // display map wi...
// move the player into new position, put path on the older position treasureMap.setEntity(entity_path, oldPosition) treasureMap.setEntity(entity_player, newPosition) treasureMap.render() // update player position player.setPosition(newPosition) } else { treasureMap.clearPossibleTreasureLocati...
{ break }
conditional_block
main.go
_treasure, treasure.Position) { break } } treasureMap.render() // display initial condition with treasure fmt.Println("Initial Condition, treasure hid in:", treasure.Position, "Wait for it..") time.Sleep(pause_time * time.Millisecond) treasureMap.setPossibleTreasure() treasureMap.render() // display map wi...
listPathPosition = append(listPathPosition, pathFound...) p.Range[left] = len(pathFound) // see all entity in y axis with same x axis / up direction ^ treasurePosition, pathFound = checkMap(treasureMap, startY+1, startX, 1, axis_y) if treasureMap.OriginalMapping[treasurePosition] == entity_treasure { treasureFo...
{ var ( startX, startY = p.Position[0], p.Position[1] treasurePosition, treasureFound [2]int listPathPosition, pathFound [][2]int ) // see all entity in x axis with same y axis / right direction -> treasurePosition, pathFound = checkMap(treasureMap, startX+1, startY, 1, axis_x) if treas...
identifier_body
vessel.pb.go
Info_Vessel.Marshal(b, m, deterministic) } func (m *Vessel) XXX_Merge(src proto.Message) { xxx_messageInfo_Vessel.Merge(m, src) } func (m *Vessel) XXX_Size() int { return xxx_messageInfo_Vessel.Size(m) } func (m *Vessel) XXX_DiscardUnknown() { xxx_messageInfo_Vessel.DiscardUnknown(m) } var xxx_messageInfo_Vessel pr...
serviceName = "vessel" } return &vesselServiceClient{ c: c, serviceName: serviceName, } } func (c *vesselServiceClient) FindAvailable(ctx context.Context, in *Specification, opts ...client.CallOption) (*Response, error) { req := c.c.NewRequest(c.serviceName, "VesselService.FindAvailable", in) out ...
if c == nil { c = client.NewClient() } if len(serviceName) == 0 {
random_line_split
vessel.pb.go
Info_Vessel.Marshal(b, m, deterministic) } func (m *Vessel) XXX_Merge(src proto.Message) { xxx_messageInfo_Vessel.Merge(m, src) } func (m *Vessel) XXX_Size() int { return xxx_messageInfo_Vessel.Size(m) } func (m *Vessel) XXX_DiscardUnknown() { xxx_messageInfo_Vessel.DiscardUnknown(m) } var xxx_messageInfo_Vessel pr...
func (m *Specification) XXX_Size() int { return xxx_messageInfo_Specification.Size(m) } func (m *Specification) XXX_DiscardUnknown() { xxx_messageInfo_Specification.DiscardUnknown(m) } var xxx_messageInfo_Specification proto.InternalMessageInfo func (m *Specification) GetCapacity() int32 { if m != nil { return ...
{ xxx_messageInfo_Specification.Merge(m, src) }
identifier_body
vessel.pb.go
Info_Vessel.Marshal(b, m, deterministic) } func (m *Vessel) XXX_Merge(src proto.Message) { xxx_messageInfo_Vessel.Merge(m, src) } func (m *Vessel) XXX_Size() int { return xxx_messageInfo_Vessel.Size(m) } func (m *Vessel) XXX_DiscardUnknown() { xxx_messageInfo_Vessel.DiscardUnknown(m) } var xxx_messageInfo_Vessel pr...
return out, nil } func (c *vesselServiceClient) Create(ctx context.Context, in *Vessel, opts ...client.CallOption) (*Response, error) { req := c.c.NewRequest(c.serviceName, "VesselService.Create", in) out := new(Response) err := c.c.Call(ctx, req, out, opts...) if err != nil { return nil, err } return out, n...
{ return nil, err }
conditional_block
vessel.pb.go
Info_Vessel.Marshal(b, m, deterministic) } func (m *Vessel) XXX_Merge(src proto.Message) { xxx_messageInfo_Vessel.Merge(m, src) } func (m *Vessel) XXX_Size() int { return xxx_messageInfo_Vessel.Size(m) } func (m *Vessel) XXX_DiscardUnknown() { xxx_messageInfo_Vessel.DiscardUnknown(m) } var xxx_messageInfo_Vessel pr...
(src proto.Message) { xxx_messageInfo_Response.Merge(m, src) } func (m *Response) XXX_Size() int { return xxx_messageInfo_Response.Size(m) } func (m *Response) XXX_DiscardUnknown() { xxx_messageInfo_Response.DiscardUnknown(m) } var xxx_messageInfo_Response proto.InternalMessageInfo func (m *Response) GetVessel() *...
XXX_Merge
identifier_name
download.go
etheus.GaugeOpts{ Name: "last_data_refresh_failure", Help: "Unix timestamp of the most recent failure to refresh data", }, []string{"source"}) lastDataRefreshCount = prometheus.NewGaugeVec(prometheus.GaugeOpts{ Name: "last_data_refresh_count", Help: "Count of records for a given sanction or entity list", },...
alts := precomputeAlts(results.AlternateIdentities) deniedPersons, err := dplRecords(s.logger, initialDir) if err != nil { lastDataRefreshFailure.WithLabelValues("DPs").Set(float64(time.Now().Unix())) return nil, fmt.Errorf("DPL records: %v", err) } dps := precomputeDPs(deniedPersons, s.pipe) consolidatedL...
sdns := precomputeSDNs(results.SDNs, results.Addresses, s.pipe) adds := precomputeAddresses(results.Addresses)
random_line_split
download.go
etheus.GaugeOpts{ Name: "last_data_refresh_failure", Help: "Unix timestamp of the most recent failure to refresh data", }, []string{"source"}) lastDataRefreshCount = prometheus.NewGaugeVec(prometheus.GaugeOpts{ Name: "last_data_refresh_count", Help: "Count of records for a given sanction or entity list", },...
updates <- stats // send stats for re-search and watch notifications } } } func ofacRecords(logger log.Logger, initialDir string) (*ofac.Results, error) { files, err := ofac.Download(logger, initialDir) if err != nil { return nil, fmt.Errorf("download: %v", err) } if len(files) == 0 { return nil, errors...
{ s.logger.Log( "main", fmt.Sprintf("data refreshed %v ago", time.Since(stats.RefreshedAt)), "SDNs", stats.SDNs, "AltNames", stats.Alts, "Addresses", stats.Addresses, "SSI", stats.SectoralSanctions, "DPL", stats.DeniedPersons, "BISEntities", stats.BISEntities, ) }
conditional_block
download.go
etheus.GaugeOpts{ Name: "last_data_refresh_failure", Help: "Unix timestamp of the most recent failure to refresh data", }, []string{"source"}) lastDataRefreshCount = prometheus.NewGaugeVec(prometheus.GaugeOpts{ Name: "last_data_refresh_count", Help: "Count of records for a given sanction or entity list", },...
func getLatestDownloads(logger log.Logger, repo downloadRepository) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { w = wrapResponseWriter(logger, w, r) limit := extractSearchLimit(r) downloads, err := repo.latestDownloads(limit) if err != nil { moovhttp.Problem(w, err) return...
{ r.Methods("GET").Path("/downloads").HandlerFunc(getLatestDownloads(logger, repo)) }
identifier_body
download.go
{ Timestamp time.Time `json:"timestamp"` // US Office of Foreign Assets Control (OFAC) SDNs int `json:"SDNs"` Alts int `json:"altNames"` Addresses int `json:"addresses"` SectoralSanctions int `json:"sectoralSanctions"` // US Bureau of Industry and Security (BIS) DeniedPerson...
recordStats
identifier_name
basics.py
# print('Hello World') # myName = input("Whats your name?\n") # print("It is good to meet you, " + myName) # print('The length of your name is: ') # print(len(myName)) # myAge = input("Whats age?\n") # print('you will be ' + str(int(myAge) + 1) + ' in a year.') # Flow Controls # example 1 # name = 'Msry' # password =...
random_line_split
profile.pb.go
images" json:"images,omitempty"` } func (m *Hotel) Reset() { *m = Hotel{} } func (m *Hotel) String() string { return proto.CompactTextString(m) } func (*Hotel) ProtoMessage() {} func (*Hotel) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} } func (m *Hotel) ...
(cc *grpc.ClientConn) ProfileClient { return &profileClient{cc} } func (c *profileClient) GetProfiles(ctx context.Context, in *Request, opts ...grpc.CallOption) (*Result, error) { out := new(Result) err := grpc.Invoke(ctx, "/profile.Profile/GetProfiles", in, out, c.cc, opts...) if err != nil { return nil, err }...
NewProfileClient
identifier_name
profile.pb.go
images" json:"images,omitempty"` } func (m *Hotel) Reset() { *m = Hotel{} } func (m *Hotel) String() string { return proto.CompactTextString(m) } func (*Hotel) ProtoMessage() {} func (*Hotel) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} } func (m *Hotel) ...
return &profileClient{cc} } func (c *profileClient) GetProfiles(ctx context.Context, in *Request, opts ...grpc.CallOption) (*Result, error) { out := new(Result) err := grpc.Invoke(ctx, "/profile.Profile/GetProfiles", in, out, c.cc, opts...) if err != nil { return nil, err } return out, nil } // Server API for...
type profileClient struct { cc *grpc.ClientConn } func NewProfileClient(cc *grpc.ClientConn) ProfileClient {
random_line_split
profile.pb.go
images" json:"images,omitempty"` } func (m *Hotel) Reset() { *m = Hotel{} } func (m *Hotel) String() string { return proto.CompactTextString(m) } func (*Hotel) ProtoMessage() {} func (*Hotel) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} } func (m *Hotel) ...
return "" } func (m *Hotel) GetName() string { if m != nil { return m.Name } return "" } func (m *Hotel) GetPhoneNumber() string { if m != nil { return m.PhoneNumber } return "" } func (m *Hotel) GetDescription() string { if m != nil { return m.Description } return "" } func (m *Hotel) GetAddress()...
{ return m.Id }
conditional_block
profile.pb.go
images" json:"images,omitempty"` } func (m *Hotel) Reset() { *m = Hotel{} } func (m *Hotel) String() string { return proto.CompactTextString(m) } func (*Hotel) ProtoMessage() {} func (*Hotel) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} } func (m *Hotel) ...
func (m *Address) GetState() string { if m != nil { return m.State } return "" } func (m *Address) GetCountry() string { if m != nil { return m.Country } return "" } func (m *Address) GetPostalCode() string { if m != nil { return m.PostalCode } return "" } type Image struct { Url string `protob...
{ if m != nil { return m.City } return "" }
identifier_body
default.py
True """ publicaciones = LOAD(r=request,c='default',f='publicaciones.load',args=request.args,ajax=True,content='Cargando bloques...') return dict(publicaciones=publicaciones) #return dict() #@cache(request.env.path_info, time_expire=150, cache_model=cache.disk) def publicaciones(): i
.ajax: return '' from gluon.tools import prettydate from datetime import datetime if request.args: catslug_data = db(db.categoria.slug == request.args(0)).select(db.categoria.slug) for cat in catslug_data: catslug = cat.slug else: catslug = 'notic...
f not request
identifier_name
default.py
jQuery("#filtrado").text(count); }); } jQuery(document).ready(filtro); ''') d = dict(publicaciones=publicaciones) return response.render(d) #return dict(publicaciones=publicaciones) def elimina_tildes(s): """ Esta función sirve para eliminar las tildes del string que se le pase como par...
TAG.loc(prefix,URL(c='default',f='blog',args=[noti.slug,noti.id],extension='')), TAG.lastmod(noti.created_on.date()), TAG.changefreq('always') ))) sm.append('</urlset>')
conditional_block
default.py
else: cat = request.args(0) return redirect('http://feeds.feedburner.com/blogchile%s' % cat) # verificamos si pasó por c=default f=mobile y activó el bit de sesión if session.mobile: response.view = 'default/index.mobi' response.files.append(URL('static','css/blogchi...
cat = ''
random_line_split
default.py
True """ publicaciones = LOAD(r=request,c='default',f='publicaciones.load',args=request.args,ajax=True,content='Cargando bloques...') return dict(publicaciones=publicaciones) #return dict() #@cache(request.env.path_info, time_expire=150, cache_model=cache.disk) def publicaciones(): if not re...
e.headers['Cache-Control'] del response.headers['Pragma'] del response.headers['Expires'] response.headers['Cache-Control'] = 'max-age=300' if request.extension == 'xml': sm = [str('<?xml version="1.0" encoding="UTF-8" ?> <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">')] ...
/[app]/default/user/login http://..../[app]/default/user/logout http://..../[app]/default/user/register http://..../[app]/default/user/profile http://..../[app]/default/user/retrieve_password http://..../[app]/default/user/change_password use @auth.requires_login() @auth.requires_members...
identifier_body
fixed.rs
() -> Vec<Route> { routes![ get_index, resume::get, links::get, contacts::get, projects::get, projects::project::get, ] } /// Functions generating my home page. pub mod htmlgen { use maud::{html, Markup, Render}; use page_client::{data, partials}; //...
routes
identifier_name
fixed.rs
. pub mod htmlgen { use maud::{html, Markup, Render}; use page_client::{data, partials}; /// Create a basic menu. pub fn menu() -> Option<data::Menu<'static>> { Some(data::Menu(&[data::MenuItem { text: "Blog", link: Some("/blog"), children: None, }]))...
/// Returns the first slide as [`Markup`]. fn my_intro() -> Markup { slide( "Nice to meet you", html! { p { "My name is Ben. I am a developer, but I am also:" } ul { li { "a reader; I love to read. But t...
{ html! { div id = { "slide-marker-"(idx) } class={"slide-marker" @if idx == 0 { (" active-slide-marker") }} {} } }
identifier_body
fixed.rs
page. pub mod htmlgen { use maud::{html, Markup, Render}; use page_client::{data, partials}; /// Create a basic menu. pub fn menu() -> Option<data::Menu<'static>> { Some(data::Menu(&[data::MenuItem { text: "Blog", link: Some("/blog"), children: None, ...
@for i in 0..slide_cnt { (slide_marker(i)) } } } /// Returns the slide_marker as [`Markup`]. fn slide_marker(idx: u8) -> Markup { html! { div id = { "slide-marker-"(idx) } class={"slide-marker" @if idx == 0 { (" active-slide-marker") }} {}...
/// Returns the slide_markers as [`Markup`]. fn slide_markers(slide_cnt: u8) -> Markup { html! {
random_line_split
attention_refine.py
context_c = tf.reduce_sum(tf.multiply(tf.expand_dims(attention_weight, axis=2), encoder_output), axis=1) step_in = tf.concat((step_in, context_c), axis=-1) in_concat = tf.concat((step_in, last_state), axis=-1) gate_inputs = tf.sigmoid(tf.matmul(in_concat, self.de_w_r_z) + self.de_b_r_z) ...
# saver.save(sess, model_path + "ner.model", global_step=int(loss_value * 1000))
random_line_split
attention_refine.py
0000) self.en_b_r_z = tf.Variable(tf.truncated_normal(shape=[units * 2, ]) / 10000) self.en_w_h = tf.Variable(tf.truncated_normal(shape=[step_dimension + self.units, self.units]) / 10000) self.en_b_h = tf.Variable(tf.truncated_normal(shape=[units, ]) / 10000) def en_cond(self, i, en_embeded...
Variable( tf.truncated_normal(shape=[step_dimension + self.units * 2, self.units * 2]) / 10000) self.de_b_r_z = tf.Variable(tf.truncated_normal(shape=[self.units * 2, ]) / 10000) self.de_w_h = tf.Variable(tf.truncated_normal(shape=[step_dimension + self.units * 2, self.units]) / 10000) ...
_z = tf.
identifier_name
attention_refine.py
(tf.expand_dims(attention_weight, axis=2), encoder_output), axis=1) step_in = tf.concat((step_in, context_c), axis=-1) in_concat = tf.concat((step_in, last_state), axis=-1) gate_inputs = tf.sigmoid(tf.matmul(in_concat, self.de_w_r_z) + self.de_b_r_z) r, z = tf.split(value=gate_inputs, nu...
f_lengths, axis=-1)] l_max_len = l_lengths[np.argmax(l_lengths, axis=-1)] loss_value, _ = sess.run((loss, optimizer), feed_dict={en_input: features[:, :f_max_len + 1], de_in_label: np.concatenate( ...
conditional_block
attention_refine.py
0000) self.en_b_r_z = tf.Variable(tf.truncated_normal(shape=[units * 2, ]) / 10000) self.en_w_h = tf.Variable(tf.truncated_normal(shape=[step_dimension + self.units, self.units]) / 10000) self.en_b_h = tf.Variable(tf.truncated_normal(shape=[units, ]) / 10000) def en_cond(self, i, en_embeded...
last_state = de_gru_output[:, i] attention_weight = tf.nn.softmax(tf.squeeze(tf.matmul(encoder_output, tf.expand_dims(last_state, axis=2)))) context_c = tf.reduce_sum(tf.multiply(tf.expand_dims(attention_weight, axis=2), encoder_output), axis=1) step_in = tf.concat((step_in, context_c), axis=-1)...
al(shape=[step_dimension + self.units * 2, self.units * 2]) / 10000) self.de_b_r_z = tf.Variable(tf.truncated_normal(shape=[self.units * 2, ]) / 10000) self.de_w_h = tf.Variable(tf.truncated_normal(shape=[step_dimension + self.units * 2, self.units]) / 10000) self.de_b_h = tf.Variable(tf.truncat...
identifier_body
client.go
-collector-docker/fs" "github.com/intelsdi-x/snap-plugin-collector-docker/network" "github.com/intelsdi-x/snap-plugin-collector-docker/wrapper" "github.com/opencontainers/runc/libcontainer/cgroups" ) const ( endpoint string = "unix:///var/run/docker.sock" dockerVersionKey string = "Version" ) // DockerCl...
// GetShortID returns short container ID (12 chars) func GetShortID(dockerID string) (string, error) { if len(dockerID) < 12 { return "", fmt.Errorf("Docker id %v is too short (the length of id should equal at least 12)", dockerID) } return dockerID[:12], nil } // GetStatsFromContainer returns docker containers...
{ return cgroups.FindCgroupMountpoint(subsystem) }
identifier_body
client.go
-collector-docker/fs" "github.com/intelsdi-x/snap-plugin-collector-docker/network" "github.com/intelsdi-x/snap-plugin-collector-docker/wrapper" "github.com/opencontainers/runc/libcontainer/cgroups" ) const ( endpoint string = "unix:///var/run/docker.sock" dockerVersionKey string = "Version" ) // DockerCl...
func (dc *DockerClient) GetStatsFromContainer(id string, collectFs bool) (*wrapper.Statistics, error) { var ( err error pid int workingSet uint64 container = &docker.Container{} groupWrap = wrapper.Cgroups2Stats // wrapper for cgroup name and interface for stats extraction stats = wrappe...
// notes that incoming container id has to be full-length to be able to inspect container
random_line_split
client.go
-collector-docker/fs" "github.com/intelsdi-x/snap-plugin-collector-docker/network" "github.com/intelsdi-x/snap-plugin-collector-docker/wrapper" "github.com/opencontainers/runc/libcontainer/cgroups" ) const ( endpoint string = "unix:///var/run/docker.sock" dockerVersionKey string = "Version" ) // DockerCl...
dc.inspectCache[id] = info return info, nil } // ListContainersAsMap returns list of all available docker containers and base information about them (status, uptime, etc.) func (dc *DockerClient) ListContainersAsMap() (map[string]docker.APIContainers, error) { containers := make(map[string]docker.APIContainers) ...
{ return nil, err }
conditional_block
client.go
() (map[string]docker.APIContainers, error) GetStatsFromContainer(string, bool) (*wrapper.Statistics, error) InspectContainer(string) (*docker.Container, error) FindCgroupMountpoint(string) (string, error) } // DockerClient holds fsouza go-dockerclient instance ready for communication with the server endpoint `unix...
isRunningSystemd
identifier_name
M130104.py
= 1 else: flagp = 0 if i == '<': flag = flag + 1 elif i == '>': flag = flag - 1 else: if flag == 0: s = s+i if flagp == 1: if newline: s = s + '\n' ...
# print(type(href)) collectiondict = {} collectiondict["CRM_In"] = ID Id = re.findall(r'http.*/(.*?).aspx', url) # print(Id) collectiondict["C_ID"] = ID + '-' + str(Id[0]) item = soup.find("ul", class_="infolist") ...
.find("div", class_="rightcon").find("ul",class_="falllist animated").find_all("li"): href0 = item.find("a",class_="pic")["href"] href.append(href0) # print(href) # exit() n = len(href) for href1 in href: url = href1 html = askURL(url) soup = BeautifulS...
identifier_body
M130104.py
= 1 else: flagp = 0 if i == '<': flag = flag + 1 elif i == '>': flag = flag - 1 else: if flag == 0: s = s+i if flagp == 1: if newline: s = s + '\n' ...
"] = "130104" datadict["M_CName"] = "中国闽台缘博物馆" datadict["M_EName"] = "China Museum for Fujian Taiwan kinship" datadict["M_Batch"] = 1 datadict["M_Address"] = "福建泉州北清东路212号" #官网主页相关内容 baseurl = "http://www.mtybwg.org.cn/" #要爬取的网页链接 datadict["M_Web"] = baseurl html = askURL(bas...
atadict["M_ID
identifier_name
M130104.py
= 1 else: flagp = 0 if i == '<': flag = flag + 1 elif i == '>': flag = flag - 1 else: if flag == 0: s = s+i if flagp == 1: if newline: s = s + '\n' ...
html = askURL(index) soup = BeautifulSoup(html,"html.parser") # print(soup) # exit() href = [] for item in soup.find("div", class_="rightcon").find("ul",class_="falllist animated").find_all("li"): href0 = item.find("a",class_="pic")["href"] href.append(href0) # prin...
# 展览 index = "http://www.mtybwg.org.cn/zhanlan.aspx"
random_line_split
M130104.py
_Pictures"] = p # print(p) # 博物馆介绍 src.clear() for item in soup.find("ul", class_="detailcon").find_all("p",class_="MsoNormal"): # print("===========") item = getText(item.text) src.append(item) # print(src) p = [] for pi in src: if len(pi) >= 10: ...
conditional_block
routes.rs
Preferences, TimeSlotRating}; use config; use db::Db; use dict::{self, Locale}; use errors::*; use state::PreparationState; use template::{NavItem, Page}; use user::{AuthUser, Role, User}; use timeslot::Rating; fn
(locale: Locale) -> Vec<NavItem> { // TODO: pass `Dict` once possible let dict = dict::new(locale).prep; vec![ NavItem::new(dict.nav_overview_title(), "/prep"), NavItem::new(dict.nav_timeslots_title(), "/prep/timeslots"), ] } #[get("/prep")] pub fn overview( auth_user: AuthUser, ...
nav_items
identifier_name
routes.rs
StudentPreferences, TimeSlotRating}; use config; use db::Db; use dict::{self, Locale}; use errors::*; use state::PreparationState; use template::{NavItem, Page}; use user::{AuthUser, Role, User}; use timeslot::Rating; fn nav_items(locale: Locale) -> Vec<NavItem> { // TODO: pass `Dict` once possible let dict ...
").get_result::<f64>(conn)?; let avg_ok_rating_per_student = sql(" select cast(avg(count) as float) from ( select count(*) as count, user_id from timeslot_ratings inner join users ...
where rating = 'good' and role = 'student' group by user_id ) as counts
random_line_split
handlers.go
, request *http.Request) { ctx, cancel := context.WithTimeout(request.Context(), timeout) defer cancel() delegate.ServeHTTP(response, request.WithContext(ctx)) }) } } // IDFromRequest is a strategy type for extracting the device identifier from an HTTP request type IDFromRequest func(*http.Request) (ID, er...
code = http.StatusNotFound case ErrorNonUniqueID: code = http.StatusBadRequest case ErrorInvalidTransactionKey: code = http.StatusBadRequest case ErrorTransactionAlreadyRegistered: code = http.StatusBadRequest } httperror.Formatf( httpResponse, code, "Could not process device request: %s...
{ deviceRequest, err := mh.decodeRequest(httpRequest) if err != nil { httperror.Formatf( httpResponse, http.StatusBadRequest, "Could not decode WRP message: %s", err, ) return } // deviceRequest carries the context through the routing infrastructure if deviceResponse, err := mh.Router.Route(dev...
identifier_body
handlers.go
request *http.Request) { ctx, cancel := context.WithTimeout(request.Context(), timeout) defer cancel() delegate.ServeHTTP(response, request.WithContext(ctx)) }) } } // IDFromRequest is a strategy type for extracting the device identifier from an HTTP request type IDFromRequest func(*http.Request) (ID, err...
return } func (mh *MessageHandler) ServeHTTP(httpResponse http.ResponseWriter, httpRequest *http.Request) { deviceRequest, err := mh.decodeRequest(httpRequest) if err != nil { httperror.Formatf( httpResponse, http.StatusBadRequest, "Could not decode WRP message: %s", err, ) return } // devic...
{ deviceRequest = deviceRequest.WithContext(httpRequest.Context()) }
conditional_block
handlers.go
strategy F func(IDFromRequest) func(http.Handler) http.Handler // FromHeader uses the device name header to extract the device identifier. // This constructor isn't configurable, and is used as-is: device.UseID.FromHeader. FromHeader func(http.Handler) http.Handler // FromPath is a configurable constructor that...
random_line_split
handlers.go
, request *http.Request) { ctx, cancel := context.WithTimeout(request.Context(), timeout) defer cancel() delegate.ServeHTTP(response, request.WithContext(ctx)) }) } } // IDFromRequest is a strategy type for extracting the device identifier from an HTTP request type IDFromRequest func(*http.Request) (ID, er...
(httpRequest *http.Request) (deviceRequest *Request, err error) { deviceRequest, err = DecodeRequest(httpRequest.Body, mh.Decoders) if err == nil { deviceRequest = deviceRequest.WithContext(httpRequest.Context()) } return } func (mh *MessageHandler) ServeHTTP(httpResponse http.ResponseWriter, httpRequest *http....
decodeRequest
identifier_name
server.py
.dba.engine.begin () as conn: res = execute (conn, r""" SELECT id, webkeyword, no FROM keyword ORDER BY sortkeyword, n, no LIMIT :limit OFFSET :offset """, { 'offset' : offset, 'limit' : limit }) return make_headwords_response ...
app.config['APPLICATION_ROOT'] : app, })
random_line_split
server.py
_cnf = { 'host' : section.get ('host', 'localhost').strip ('"'), 'port' : section.get ('port', '3306').strip ('"'), 'database' : section.get ('database', '').strip ('"'), 'user' : section.get ('user', '').strip ('"'), 'password' : secti...
return arg cpd_iso_trans = str.maketrans ('âêîôû', 'aeiou') def normalize_iso (text): """Normalize to ISO 15919 CPD transliteration is almost ISO 15919, but uses uppercase for proper names and 'â' instead of 'a' to signal a syncope 'a' + 'a'. We have to replace all 'â's because they definitely do n...
g is None: msg = 'Invalid %s parameter' % name flask.abort (msg)
conditional_block
server.py
ect): """ Database Interface """ def __init__ (self, **kwargs): args = self.get_connection_params (kwargs) self.url = 'mysql+pymysql://{user}:{password}@{host}:{port}/{database}'.format (**args) logger.log (logging.INFO, 'MySQLEngine: Connecting to mysql+pymysql://...
Engine (obj
identifier_name
server.py
nf = { 'host' : section.get ('host', 'localhost').strip ('"'), 'port' : section.get ('port', '3306').strip ('"'), 'database' : section.get ('database', '').strip ('"'), 'user' : section.get ('user', '').strip ('"'), 'password' : section...
oint ('articles_id') def articles_id (_id = None): """ Endpoint. Retrieve an article. """ with current_app.config.dba.engine.begin () as conn: res = execute (conn, r""" SELECT no FROM article WHERE no = :id """, { 'id' : _id }) return make_articles_response (re...
. Retrieve a list of articles. """ offset = int (arg ('offset', '0', re_integer_arg)) limit = clip (arg ('limit', str (MAX_RESULTS), re_integer_arg), 1, MAX_RESULTS) with current_app.config.dba.engine.begin () as conn: res = execute (conn, r""" SELECT no FROM article ORDER...
identifier_body
Train.py
rb') as f: img = Image.open(f) return img.convert('RGB') def load_labels(path): with open(path, newline='') as csvfile:
headers = next(reader) return [{ headers[column_index]: row[column_index] for column_index in range(len(row)) } for row in reader] class CustomDataset(Dataset): def __init__(self, root, split='train', incr=None, transform=None): self.root = ...
reader = csv.reader(csvfile)
random_line_split
Train.py
rb') as f: img = Image.open(f) return img.convert('RGB') def load_labels(path): with open(path, newline='') as csvfile: reader = csv.reader(csvfile) headers = next(reader) return [{ headers[column_index]: row[column_index] for column_index in range(l...
def forward(self, x): out = F.relu(self.bn1(self.conv1(x))) out = self.bn2(self.conv2(out)) out += self.shortcut(x) out = F.relu(out) return out class ResNet(nn.Module): def __init__(self, block, num_blocks, num_classes=4246): super(ResNet, self).__init__() ...
if option == 'A': """ For CIFAR10 ResNet paper uses option A. """ self.shortcut = LambdaLayer(lambda x: F.pad(x[:, :, ::2, ::2], (0, 0, 0, 0, planes//4, planes//4), "constant", 0)) elif option == 'B':...
conditional_block
Train.py
else: labels = load_labels(os.path.join(root, split+str(incr)+'.csv')) self.entries = [ (label_entry['Image'], int(label_entry[category])) for label_entry in labels if os.path.exists( os.path.join(self.root, f'{split}/{split}', label_entry['...
""" Train a neural network and print statistics of the training :param net: (PyTorch Neural Network) :param batch_size: (int) :param n_epochs: (int) Number of iterations on the training set :param learning_rate: (float) learning rate used by the optimizer """ print("===== HYPERPARAMETE...
identifier_body
Train.py
rb') as f: img = Image.open(f) return img.convert('RGB') def load_labels(path): with open(path, newline='') as csvfile: reader = csv.reader(csvfile) headers = next(reader) return [{ headers[column_index]: row[column_index] for column_index in range(l...
(net, batch_size, n_epochs,
train
identifier_name
PAD.py
bound_orbitals : list of callables `bound_orbitals[b](x,y,z)` should evaluate the `b`-th orbital on a cartesian grid pke : np.1darray (shape (npke,)) photokinetic energies (in Hartree) for which the PADs shou...
""" Parameters ---------- muffin : instance of `MuffinTinPotential` muffin tin potential, which provides the continuum orbitals """ def __init__(self, muffin): self.muffin = muffin def compute_pads(self, bound_orbitals, pke, ...
identifier_body
PAD.py
the continuum at energy `pke[k]`. """ print( " " ) print( " *******************" ) print( " * PADs *" ) print( " *******************" ) print( " " ) # number of bound orbitals norb = len(bound_or...
# last extremum is a minimum, which is not bracketed # by two maxima maxima = maxima + [-1] # After appending last point, we have # maxima[i ] < minima[i] < maxima[i+1] # for all minima assert len(minima) == le...
# maxima[j ] < minima[j] < maxima[j+1] if pke[minima[-1]] > pke[maxima[-1]]:
random_line_split
PAD.py
the continuum at energy `pke[k]`. """ print( " " ) print( " *******************" ) print( " * PADs *" ) print( " *******************" ) print( " " ) # number of bound orbitals norb = len(bound_or...
(energy): # compute (-1) x photoionization cross section for initial orbital # with index `i` at energy `energy` pad_i = self.muffin.photoelectron_distribution(energy, grid, orbs[i:i+1,:], pol=pol) ...
func
identifier_name
PAD.py
the continuum at energy `pke[k]`. """ print( " " ) print( " *******************" ) print( " * PADs *" ) print( " *******************" ) print( " " ) # number of bound orbitals norb = len(bound_or...
print( "" ) return resonances def save_pads(pke,pad, pol, tbl_file, units="eV-Mb"): """ A table with the PAD is written to `tbl_file`. It contains the 4 columns PKE SIGMA BETA1 BETA_2 which define the PAD(th) at each energy according to .. code-block:...
print( " %4.1d %4.1d %12.8f %12.8f %6.4e" % (i+1, j+1, res.energy, res.energy * AtomicData.hartree_to_eV, res.tags["sigma"] * AtomicData.bohr2_to_megabarn) )
conditional_block
IssuanceHelpers.ts
SignatureToken.encode(header, claims); return new ClaimToken(TokenType.selfIssued, jwt, ''); } /** * Create a verifiable credential * @param claims Token claims */ public static async createVc(setup: TestSetup, credentialSubject: TokenPayload, configuration: string, jwkPrivate: any, jwkPublic: any):...
{ attestations = { presentations: {} }; attestations.presentations['DrivingLicense'] = vp.rawToken; }
conditional_block
IssuanceHelpers.ts
contract, attestations, iss: 'https://self-issued.me', aud: setup.AUDIENCE, jti: IssuanceHelpers.jti, sub_jwk: key, sub: createJwkThumbprint(key), did: setup.defaultUserDid } if(setup.siopMutator){ siop = setup.siopMutator(siop); } return Issuance...
}; const vc = await IssuanceHelpers.createVc( setup, vcPayload, vcConfiguration,
random_line_split
IssuanceHelpers.ts
, '', key); return claimToken; } /** * Create siop request */ public static async createSiopRequest(setup: TestSetup, key: any, contract: string | undefined, nonce: string, attestations: any): Promise<ClaimToken> { let siop: TokenPayload = { nonce, contract, attestations, is...
public static async createRequest( setup: TestSetup, tokenDescription: TokenType, issuance: boolean, idTokenIssuer?: string, idTokenAudience?: string, idTokenExp?: number): Promise<[ClaimToken, ValidationOptions, any]> { const options = new ValidationOptions(setup.validatorOptions, token...
{ const keyId = new KeyReference(jwkPrivate.kid); await setup.keyStore.save(keyId, <any>jwkPrivate); setup.validatorOptions.crypto.builder.useSigningKeyReference(keyId); setup.validatorOptions.crypto.signingProtocol(JoseBuilder.JWT).builder.useKid(keyId.keyReference); const signature = await setup.v...
identifier_body
IssuanceHelpers.ts
, '', key); return claimToken; } /** * Create siop request */ public static async createSiopRequest(setup: TestSetup, key: any, contract: string | undefined, nonce: string, attestations: any): Promise<ClaimToken> { let siop: TokenPayload = { nonce, contract, attestations, is...
(setup: TestSetup, payload: object, configuration: string, jwkPrivate: any): Promise<ClaimToken> { const keyId = new KeyReference(jwkPrivate.kid); await setup.keyStore.save(keyId, <any>jwkPrivate); setup.validatorOptions.crypto.builder.useSigningKeyReference(keyId); setup.validatorOptions.crypto.signing...
signAToken
identifier_name
ui.rs
_pair()`. InitPair, /// Describes a possible error during call to `noecho()`. Noecho, /// Describes a possible error during call to `start_color()`. StartColor, /// Describes a possible error during call to `use_default_colors()`. UseDefaultColors, /// Describes a possible error during c...
Change::Clear => write!(f, "Clear"), Change::Format(n, color) => write!(f, "Format {} cells to {}", n, color), Change::Insert(input) => write!(f, "Insert '{}'", input), Change::Nothing => write!(f, "Nothing"), Change::Row(row_str) => write!(f, "Write row '{}'"...
#[inline] fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { match self { Change::Backspace => write!(f, "Backspace"),
random_line_split
ui.rs
()`. InitPair, /// Describes a possible error during call to `noecho()`. Noecho, /// Describes a possible error during call to `start_color()`. StartColor, /// Describes a possible error during call to `use_default_colors()`. UseDefaultColors, /// Describes a possible error during call t...
} /// Signifies a [`Change`] to make to an [`Address`]. /// /// [`Change`]: enum.Change.html /// [`Address`]: struct.Address.html #[derive(Clone, Debug, Default, Eq, Hash, PartialEq)] pub struct Edit { /// The [`Change`] to be made. change: Change, /// The [`Address`] on which the [`Change`] is intended. ...
{ match self { Color::Default => write!(f, "Default"), Color::Red => write!(f, "Red"), Color::Green => write!(f, "Green"), Color::Yellow => write!(f, "Yellow"), Color::Blue => write!(f, "Blue"), } }
identifier_body
ui.rs
`. UseDefaultColors, /// Describes a possible error during call to `waddch()`. Waddch, /// Describes a possible error during call to `waddstr()`. Waddstr, /// Describes a possible error during call to `wchgat()`. Wchgat, /// Describes a possible error during call to `wclear()`. Wclea...
delete_char
identifier_name
command.py
User from ZeroBot.common.enums import HelpType from ZeroBot.exceptions import CommandAlreadyRegistered, CommandParseError from ZeroBot.module import Module from ZeroBot.util import gen_repr __all__ = ["CommandHelp", "CommandParser", "ParsedCommand"] class _NoExitArgumentParser(ArgumentParser): """Modified `argp...
return subparser.name.split()[-1] except (IndexError, KeyError, TypeError): return None @dataclass class CommandHelp: """Encapsulates the result of a command help request. ZeroBot's `Core` will create and pass these to `core_command_help` callbacks. Attributes --...
action = subparser._actions[0] if isinstance(action, _SubParsersAction): subparser = action.choices[self.args[action.dest]] current += 1 else: return None
conditional_block
command.py
ArgumentParser(ArgumentParser): """Modified `argparse.ArgumentParser` that doesn't exit on errors.""" # NOTE: Python 3.9 will add an `exit_on_error` parameter that will stop # argparse from exiting instead of having to override exit and error. def exit(self, status=0, message=None): pass ...
get_subcmd
identifier_name
command.py
User from ZeroBot.common.enums import HelpType from ZeroBot.exceptions import CommandAlreadyRegistered, CommandParseError from ZeroBot.module import Module from ZeroBot.util import gen_repr __all__ = ["CommandHelp", "CommandParser", "ParsedCommand"] class _NoExitArgumentParser(ArgumentParser): """Modified `argp...
except (KeyError, IndexError): self._subcmd = None @property def invoker(self) -> User: """The User that invoked the command.""" return self.msg.source @property def source(self) -> Union[User, Channel]: """Where the command was sent from. Can be ei...
name_map = action.choices canon_parser = name_map[self.args[action.dest]] self._subcmd = canon_parser.name.split()[-1] else: self._subcmd = None
random_line_split
command.py
User from ZeroBot.common.enums import HelpType from ZeroBot.exceptions import CommandAlreadyRegistered, CommandParseError from ZeroBot.module import Module from ZeroBot.util import gen_repr __all__ = ["CommandHelp", "CommandParser", "ParsedCommand"] class _NoExitArgumentParser(ArgumentParser): """Modified `argp...
def nested_subcmd(self, depth: int = 2) -> Optional[str]: """Get the name of a nested subcommand. Like the `subcmd` property, the name returned is always the canonical name for the subcommand. The `depth` parameter determines how many levels of nesting to traverse; the default of ...
"""The invoked subcommand name, if one was invoked. For subcommands with aliases, the name returned is always the canonical name that the aliases are associated with. For this reason, this attribute should be preferred to extracting the subcommand name from `ParsedCommand.args`. ...
identifier_body
store.go
_SOURCE_UPLOAD: if dbginfo.Upload == nil { return nil, status.Error(codes.Internal, "metadata inconsistency: upload is nil") } switch dbginfo.Upload.State { case debuginfopb.DebuginfoUpload_STATE_UPLOADING: if s.uploadIsStale(dbginfo.Upload) { return &debuginfopb.ShouldInitiateUploadResponse{ ...
{ if err := validateInput(buildID); err != nil { return status.Errorf(codes.InvalidArgument, "invalid build ID: %q", err) } dbginfo, err := s.metadata.Fetch(ctx, buildID, typ) if err != nil { if errors.Is(err, ErrMetadataNotFound) { return status.Error(codes.FailedPrecondition, "metadata not found, this ind...
identifier_body
store.go
nil || !dbginfo.Quality.NotValidElf { if req.Force { return &debuginfopb.ShouldInitiateUploadResponse{ ShouldInitiateUpload: true, Reason: ReasonDebuginfoAlreadyExistsButForced, }, nil } return &debuginfopb.ShouldInitiateUploadResponse{ ShouldInitiateUpload...
objectPath
identifier_name
store.go
odInvalid = "Debuginfo is available from debuginfod already but is marked as invalid, therefore a new upload is needed." ) // ShouldInitiateUpload returns whether an upload should be initiated for the // given build ID. Checking if an upload should even be initiated allows the // parca-agent to avoid ext...
{ return nil, status.Error(codes.InvalidArgument, "upload id mismatch") }
conditional_block
store.go
debuginfodClients DebuginfodClients signedUpload SignedUpload maxUploadDuration time.Duration maxUploadSize int64 timeNow func() time.Time } type SignedUploadClient interface { SignedPUT(ctx context.Context, objectKey string, size int64, expiry time.Time) (signedURL string, err error) } type SignedUpload...
if err != nil { return nil, err } if !shouldInitiateResp.ShouldInitiateUpload { if shouldInitiateResp.Reason == ReasonDebuginfoEqual { return nil, status.Error(codes.AlreadyExists, ReasonDebuginfoEqual) } return nil, status.Errorf(codes.FailedPrecondition, "upload should not have been attempted to be init...
})
random_line_split
server.go
.Code() != codes.Unavailable || errStatus.Message() != "transport is closing" { errs <- xerrors.Errorf("failed to stop agent on host %s : %w", conn.Hostname, err) } }() } wg.Wait() close(errs) var multiErr *multierror.Error for err := range errs { multiErr = multierror.Append(multiErr, err) } retur...
MakeTargetClusterMessage
identifier_name