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
planner.go
planner) ExtendedEvalContext() *extendedEvalContext { return &p.extendedEvalCtx } func (p *planner) ExtendedEvalContextCopy() *extendedEvalContext { return p.extendedEvalCtx.copy() } // CurrentDatabase is part of the resolver.SchemaResolver interface. func (p *planner) CurrentDatabase() string { return p.SessionDa...
{ typed := make(map[string]tree.TypedExpr, len(opts)) for _, opt := range opts { k := string(opt.Key) validate, ok := optValidate[k] if !ok { return nil, errors.Errorf("invalid option %q", k) } if opt.Value == nil { if validate == KVStringOptRequireValue { return nil, errors.Errorf("option %q req...
identifier_body
planner.go
Manager() } func (p *planner) Txn() *kv.Txn { return p.txn } func (p *planner) User() security.SQLUsername { return p.SessionData().User() } func (p *planner) TemporarySchemaName() string { return temporarySchemaName(p.ExtendedEvalContext().SessionID) } // DistSQLPlanner returns the DistSQLPlanner func (p *plann...
{ typedE, err := tree.TypeCheckAndRequire(ctx, exprs[i], &p.semaCtx, types.String, op) if err != nil { return nil, err } typedExprs[i] = typedE }
conditional_block
builder.go
// Validation tags are based on country codes, hence it's easy to differentiate and // also trivial to set the validator tag as country code is the core attribute of account builder. ////// essentialAttributes struct { ID string `validate:"uuid,required"` OrganizationID string `validate:"uuid,require...
// SetBaseCurrency - ISO 4217 code used to identify the base currency of the account, e.g. 'GBP', 'EUR' // Provide currency unit object from golang text library. func (opt *optionalAttributes) SetBaseCurrency(unit currency.Unit) *Builder { opt.Builder.optional.BaseCurrency = unit.String() return opt.Builder } // S...
{ opt.Builder.optional.VersionIndex = version return opt.Builder }
identifier_body
builder.go
len=11"` Iban string `AU:"len=0" CA:"len=0" HK:"len=0" US:"len=0"` } /////// // Chose not to add all attributes on the same builder level. // Having a structure and separating optional attributes from essential ones lowers cognitive load for client user. /////// optionalAttributes struct { Builder ...
}
random_line_split
builder.go
// Validation tags are based on country codes, hence it's easy to differentiate and // also trivial to set the validator tag as country code is the core attribute of account builder. ////// essentialAttributes struct { ID string `validate:"uuid,required"` OrganizationID string `validate:"uuid,require...
return &Account{ id: b.essential.ID, organizationID: b.essential.OrganizationID, versionIndex: b.optional.VersionIndex, country: b.essential.Country, bankIDCode: b.essential.BankIDCode, bankID: b.essential.BankID, bic...
{ return nil, err }
conditional_block
builder.go
// Validation tags are based on country codes, hence it's easy to differentiate and // also trivial to set the validator tag as country code is the core attribute of account builder. ////// essentialAttributes struct { ID string `validate:"uuid,required"` OrganizationID string `validate:"uuid,requir...
(accountNumber string) *Builder { opt.Builder.optional.AccountNumber = accountNumber return opt.Builder } // SetVersion - version number of account object. Needs to be incremented when Patching an existing account. func (opt *optionalAttributes) SetVersion(version int) *Builder { opt.Builder.optional.VersionIndex =...
SetAccountNumber
identifier_name
mod.rs
gl::BindBuffer(gl::ARRAY_BUFFER, buffer); let size = data.get_size() as gl::types::GLsizeiptr; let raw = data.get_address() as *const gl::types::GLvoid; let usage = match usage { super::UsageStatic => gl::STATIC_DRAW, super::UsageDynamic => gl::DYNAMIC_DRAW, ...
{ assert_eq!(Version::parse("1"), Err("1")); assert_eq!(Version::parse("1."), Err("1.")); assert_eq!(Version::parse("1 h3l1o. W0rld"), Err("1 h3l1o. W0rld")); assert_eq!(Version::parse("1. h3l1o. W0rld"), Err("1. h3l1o. W0rld")); assert_eq!(Version::parse("1.2.3"), Ok(Version(1, ...
identifier_body
mod.rs
deriving(Eq, PartialEq, Show)] pub struct PlatformName { /// The company responsible for the OpenGL implementation pub vendor: &'static str, /// The name of the renderer pub renderer: &'static str, } impl PlatformName { fn get() -> PlatformName { PlatformName { vendor: get_strin...
} else {
random_line_split
mod.rs
(src: &'static str) -> Result<Version, &'static str> { let (version, vendor_info) = match src.find(' ') { Some(i) => (src.slice_to(i), src.slice_from(i + 1)), None => (src, ""), }; // TODO: make this even more lenient so that we can also accept // `<major> "." <m...
parse
identifier_name
xform_anno.py
mers (chris.sommers@keysight.com) # from __future__ import print_function import p4.config.p4info_pb2 as p4info_pb2 import argparse import sys import google.protobuf.json_format as json_format import google.protobuf.text_format as text_format import textwrap # Conditionally print a verbose message def log_verbose(msg)...
(): parser = argparse.ArgumentParser(description='P4info transform utility', formatter_class=argparse.RawDescriptionHelpFormatter, epilog=textwrap.dedent('''\ Either or both of infile, outfile can be omitted; a hyphen signifies stdin and stdout, respectively. Using -i none o...
get_arg_parser
identifier_name
xform_anno.py
.preamble.annotations): xform_doc_annotation(message.preamble.name, message.preamble.doc, message.preamble.annotations, anno) # Transform match_field annotations (doc) def xform_table_match_field_annotations(table): for matchfield in table.match_fields: #reverse iterate so deleting elements doesn't...
outfile.close()
random_line_split
xform_anno.py
mers (chris.sommers@keysight.com) # from __future__ import print_function import p4.config.p4info_pb2 as p4info_pb2 import argparse import sys import google.protobuf.json_format as json_format import google.protobuf.text_format as text_format import textwrap # Conditionally print a verbose message def log_verbose(msg)...
# Set document.description def set_doc_description(doc, value): doc.description = value; # Extract the string value embedded in an annotation # Asssumes just one string, surrounded by escaped quotes e.g. "\"string\"" def get_anno_value(anno): return anno.split('(\"')[1].split('\")')[0] # Detect @brief() and...
doc.brief = value;
identifier_body
xform_anno.py
anno): return anno.split('(\"')[1].split('\")')[0] # Detect @brief() and @description() annotations and transform into document.brief, document.description def xform_doc_annotation(container_name, doc, anno_list, anno): if '@brief' in anno: log_verbose( "*** %sTransform doc anno in %s: %s => doc.brief"...
log_verbose("=== process indirect counter %s" % counter.preamble.name) xform_preamble_doc_annotations(counter)
conditional_block
admin.py
Class, used with admin special functions. Used the env for adminList to see people with permission to run these commands class AdminCog(commands.Cog): def __init__(self, bot): self.bot = bot self.adminList = ADMIN_LIST # Functions ###############################################################...
print("[AdminCog.findPermission] Forbidden: authorID (" + str(authorID) + ") not found in adminList\n") for admin in ADMIN_LIST: print(admin) return False # Commands Methods ########################################################################################################...
print("[AdminCog.findPermission] Accepted") return True
conditional_block
admin.py
, used with admin special functions. Used the env for adminList to see people with permission to run these commands class AdminCog(commands.Cog):
module = "cogs." + module try: self.bot.reload_extension(module) print("[AdminCog.reloadLoadExtension] Reloading " + str(module)) except commands.ExtensionNotLoaded: print("[AdminCog.reloadLoadExtension] Loading " + str(module)) self.bot.load_ext...
def __init__(self, bot): self.bot = bot self.adminList = ADMIN_LIST # Functions ########################################################################################################################################################### # runProcess: Used to run a terminal command async def ...
identifier_body
admin.py
Class, used with admin special functions. Used the env for adminList to see people with permission to run these commands class AdminCog(commands.Cog): def __init__(self, bot): self.bot = bot self.adminList = ADMIN_LIST # Functions ###############################################################...
(self, ctx): print("[AdminCog.adminHelpCommand] Generating embed") # If it is, we use the generic help function to generate a embed # First we generate all needed fields cogName = "admin" cogDescription = "Admin
adminHelpCommand
identifier_name
admin.py
try: self.bot.reload_extension(module) print("[AdminCog.reloadLoadExtension] Reloading " + str(module)) except commands.ExtensionNotLoaded: print("[AdminCog.reloadLoadExtension] Loading " + str(module)) self.bot.load_extension(module) # unloadExten...
] print("[AdminCog.adminHelpCommand] Sending embed\n") await helpFunction.generateHelpEmbed(ctx, cogName, cogDescription, helpList, cogEmbed) return
random_line_split
edit_ops.rs
<BT, AT>( base: &Rope, regions: &[SelRegion], before_text: BT, after_text: AT, ) -> RopeDelta where BT: Into<Rope>, AT: Into<Rope>, { let mut builder = DeltaBuilder::new(base.len()); let before_rope = before_text.into(); let after_rope = after_text.into(); for region in regions {...
surround
identifier_name
edit_ops.rs
pe = after_text.into(); for region in regions { let before_iv = Interval::new(region.min(), region.min()); builder.replace(before_iv, before_rope.clone()); let after_iv = Interval::new(region.max(), region.max()); builder.replace(after_iv, after_rope.clone()); } builder.buil...
else { None }; (delete_sel_regions(base, &deletions), kill_ring) } /// Deletes the given regions. pub(crate) fn delete_sel_regions(base: &Rope, sel_regions: &[SelRegion]) -> RopeDelta { let mut builder = DeltaBuilder::new(base.len()); for region in sel_regions { let iv = Interval::new...
{ let saved = extract_sel_regions(base, &deletions).unwrap_or_default(); Some(Rope::from(saved)) }
conditional_block
edit_ops.rs
pe = after_text.into(); for region in regions { let before_iv = Interval::new(region.min(), region.min()); builder.replace(before_iv, before_rope.clone()); let after_iv = Interval::new(region.max(), region.max()); builder.replace(after_iv, after_rope.clone()); } builder.buil...
(delete_sel_regions(base, &deletions), kill_ring) } /// Deletes the given regions. pub(crate) fn delete_sel_regions(base: &Rope, sel_regions: &[SelRegion]) -> RopeDelta { let mut builder = DeltaBuilder::new(base.len()); for region in sel_regions { let iv = Interval::new(region.min(), region.max()...
{ // We compute deletions as a selection because the merge logic // is convenient. Another possibility would be to make the delta // builder able to handle overlapping deletions (with union semantics). let mut deletions = Selection::new(); for &r in regions { if r.is_caret() { le...
identifier_body
edit_ops.rs
pe = after_text.into(); for region in regions { let before_iv = Interval::new(region.min(), region.min()); builder.replace(before_iv, before_rope.clone()); let after_iv = Interval::new(region.max(), region.max()); builder.replace(after_iv, after_rope.clone()); } builder.buil...
fn outdent(base: &Rope, lines: BTreeSet<usize>, tab_text: &str) -> RopeDelta { let mut builder = DeltaBuilder::new(base.len()); for line in lines { let offset = LogicalLines.line_col_to_offset(base, line, 0); let tab_offset = LogicalLines.line_col_to_offset(base, line, tab_text.len()); ...
random_line_split
utils.py
download.pytorch.org/models/resnet101-5d3b4d8f.pth', 'resnet152': 'https://download.pytorch.org/models/resnet152-b121ed2d.pth', } label_colours = [(0, 0, 0), # 0=background (148, 65, 137), (255, 116, 69), (86, 156, 137), (202, 179, 158), (155, 99, 235), (161, 107,...
def depthImage2ptcloud(self, depth_img): [ifocal_length_x, ifocal_length_y, center_x, center_y, Rtilt] = self.getCameraInfo() ptCloud = np.zeros(shape=(int(depth_img.shape[0]), int(depth_img.shape[1]), 3), dtype=np.float32) for y in xrange(0, depth_img.shape[0]): for x ...
depthVisData = np.asarray(depthImage, np.uint16) depthInpaint = np.bitwise_or(np.right_shift(depthVisData, 3), np.left_shift(depthVisData, 16 - 3)) depthInpaint = depthInpaint.astype(np.single) / 1000 depthInpaint[depthInpaint > 8] = 8 return depthInpaint
identifier_body
utils.py
, 65, 137), (255, 116, 69), (86, 156, 137), (202, 179, 158), (155, 99, 235), (161, 107, 108), (133, 160, 103), (76, 152, 126), (84, 62, 35), (44, 80, 130), (31, 184, 157), (101, 144, 77), (23, 197, 62), (141, 168, 145), (142, 151, 136), ...
for x in range(0, depth_img.shape[1]-winsize, winsize): windowDepths = depth_img[y:(y + winsize + 1), x:(x + winsize + 1)] # print(windowDepths) numValidPoints = np.count_nonzero(~np.isnan(windowDepths)) # print(numValidPoints) if (numValid...
conditional_block
utils.py
Download trained weights from previous training on depth images or rgbd images. """ # depth_model_path: local path of depth trained weights if verbose > 0: print("Downloading pretrained model to " + model_path + " ...") if model_name == 'depth': with contextlib.closing(request.u...
def forward(self, inputs_scales, targets_scales): losses = [] for inputs, targets in zip(inputs_scales, targets_scales): mask = targets > 1e-3 # should be larger than 0 but tensor seems to treat 0 as a very small number like 2e-9 then targets_m = targets.clone() # when we s...
random_line_split
utils.py
79), (163, 221, 160), (31, 146, 98), (99, 121, 30), (49, 89, 240), (116, 108, 9), (161, 176, 169), (80, 29, 135), (177, 105, 197), (139, 110, 246)] ''' def download_trained_weights(model_name, model_path, verbose=1): """ Download trained weights from previous ...
__init__
identifier_name
app.component.ts
// console.log(p); // }); // But we can get the URL // If routeGuard hinders navigation, the event will contain redirect route, and not the hindered route! If no redirect route, event will not fire. this.router.events .filter(event => event instanceof NavigationEnd) .subscribe(event => {...
return Observable.of(null);
random_line_split
app.component.ts
AppComponent implements OnInit, OnDestroy { userSubscription: Subscription; user: UserModel = null; pageTitle = 'Acme Product Management'; constructor( private router: Router, private authService: AuthService, public messageService: MessageService, private fooPipe: FooPipe ) { }
() { // Can we get to the data property from this not routable component? No! // console.log(this.activatedRoute.snapshot.data['pageTitle']); // Can we subscribe to a resolve from this not routable component? No! // this.activatedRouteSubscription = this.activatedRoute.data.subscribe((data) => { //...
ngOnInit
identifier_name
app.component.ts
AppComponent implements OnInit, OnDestroy { userSubscription: Subscription; user: UserModel = null; pageTitle = 'Acme Product Management'; constructor( private router: Router, private authService: AuthService, public messageService: MessageService, private fooPipe: FooPipe ) { } ngOnIni...
.filter(event => event instanceof NavigationEnd) .subscribe(event => { // console.log(event); }); this.userSubscription = this.authService.user$.subscribe(user => this.user = user); console.log(this.fooPipe.transform('pipe')); } ngOnDestroy() { this.userSubscription.unsubsc...
{ // Can we get to the data property from this not routable component? No! // console.log(this.activatedRoute.snapshot.data['pageTitle']); // Can we subscribe to a resolve from this not routable component? No! // this.activatedRouteSubscription = this.activatedRoute.data.subscribe((data) => { // ...
identifier_body
generate.rs
███EARNS█ACE HORNSWOGGLED█ANTS ███TEABAG█SIAM███ DOB██HIS███GRACED OVERDO█BAMBOOZLED LATINO█AGAR█MOOLA LLAMAS█GAGA█ANTSY"; fn write_impl() { let mut rows = vec![]; for line in GRID.split('\n') { let mut row = vec![]; for c in line.chars() { if c == '█' { row.push(Cel...
clues.insert("CHEAP", "Overpowered, in the 90's"); clues.insert("RAG", "with \"on\", tease"); clues.insert("OVA", "Largest human cells"); clues.insert("RALLY", "Make a comeback, as a military force"); clues.insert("ANTS", "Pants' contents?"); clues.insert("EDIT", "Amend"); clues.insert("AGAR...
clues.insert("ICETEA", "???"); clues.insert("DOB", "Important date: abbr");
random_line_split
generate.rs
███EARNS█ACE HORNSWOGGLED█ANTS ███TEABAG█SIAM███ DOB██HIS███GRACED OVERDO█BAMBOOZLED LATINO█AGAR█MOOLA LLAMAS█GAGA█ANTSY"; fn write_impl() { let mut rows = vec![]; for line in GRID.split('\n') { let mut r
]; for c in line.chars() { if c == '█' { row.push(Cell::Black); } else { row.push(Cell::White(Letter::from_unicode(c))); } } rows.push(row); } let grid = Grid::new((rows[0].len(), rows.len()), |x, y| rows[y][x]); pri...
ow = vec![
identifier_name
generate.rs
, as pasta"); clues.insert("ADD", "More: abbr."); clues.insert("BETA", "Advice, in climbing jargon"); clues.insert("ARK", "Couple's cruise ship?"); clues.insert("AIL", "Bedevil"); clues.insert("EGG", "Urge (on)"); clues.insert("BREATH", "Form of investiture on Nalthis"); clues.insert("GRACED...
RT); let mut rows = vec![]; for line in reader.records() { let mut row = vec![]; for cell in line?.iter() { row.push(match cell { "!" => Cell::Black, "" => Cell::White(None), letter => Cell::White(Some(Letter::from_unicode(letter.chars(...
identifier_body
Translatable.js
pointer */ registerTranslatableElement(element, html){ var isTextFromEditor = false; //Element has been registered already if ( element.hasPointer && element.hasPointer.indexOf('translatable') > -1 || element._isInEditorElement || (isTextFromEditor ...
} }, /* * Change translates and HTML dom into same format * ig. we need sort all attributes by name order, because VueJS sorts attributes... then translates are not same with innerHTML */ domPreparer: { prepared : {}, prepareTranslateHTML(html, e){ //We ne...
this.maxTranslateLength = translate.length; }
conditional_block
Translatable.js
this.events.onPointerHide.bind(this), }); }, /* * We want build tree with keys as translations and values as original texts. * For better performance for searching elements. */ getTranslationsTree(){ //Debug given texts var debugText = []; //Build translates...
nPointerClick(
identifier_name
Translatable.js
} }, /* * Change translates and HTML dom into same format * ig. we need sort all attributes by name order, because VueJS sorts attributes... then translates are not same with innerHTML */ domPreparer: { prepared : {}, prepareTranslateHTML(html, e){ //We ne...
//Because propably this elements has been hidden if ( element.isContentEditable !== true ){ return;
random_line_split
Translatable.js
pointer */ registerTranslatableElement(element, html){ var isTextFromEditor = false; //Element has been registered already if ( element.hasPointer && element.hasPointer.indexOf('translatable') > -1 || element._isInEditorElement || (isTextFromEditor ...
e.removeAttribute(item.name); }); //Add attributes aggain in correct order defaultAttributes.forEach(item => { item = this.updateAttribute(item); e.setAttribute(item.name, item.value); }); ...
let defaultAttributes = []; //If childnode has attributes, we need sort them if ( e.attributes && e.attributes.length > 0 ){ //Build attributes tree for ( let i = 0; i < e.attributes.length; i++ ){ defaultAttributes.push({ ...
identifier_body
index.b4f5078c.js
: ParcelRequire, ...}; declare var HMR_HOST: string; declare var HMR_PORT: string; declare var HMR_ENV_HASH: string; declare var HMR_SECURE: boolean; */ var OVERLAY_ID = '__parcel__error__overlay__'; var OldModule = module.bundle.Module; function Module(moduleName) { OldModule.call(this, moduleName); this.hot = { ...
console.log('[parcel] ✨ Error resolved'); } } function createErrorOverlay(diagnostics) { var overlay = document.createElement('div'); overlay.id = OVERLAY_ID; let errorHTML = '<div style="background: black; opacity: 0.85; font-size: 16px; color: white; position: fixed; height: 100%; width: 100%; top: 0px; l...
if (overlay) { overlay.remove();
random_line_split
index.b4f5078c.js
(name, jumped) { if (!cache[name]) { if (!modules[name]) { // if we cannot find the module within our internal map or // cache jump to the current global require ie. the last bundle // that was added to the page. var currentRequire = typeof globalObject[parcelRequireN...
newRequire
identifier_name
index.b4f5078c.js
ParcelRequire, ...}; declare var HMR_HOST: string; declare var HMR_PORT: string; declare var HMR_ENV_HASH: string; declare var HMR_SECURE: boolean; */ var OVERLAY_ID = '__parcel__error__overlay__'; var OldModule = module.bundle.Module; function Module(moduleName) { OldModule.call(this, moduleName); this.hot = { ...
n createErrorOverlay(diagnostics) { var overlay = document.createElement('div'); overlay.id = OVERLAY_ID; let errorHTML = '<div style="background: black; opacity: 0.85; font-size: 16px; color: white; position: fixed; height: 100%; width: 100%; top: 0px; left: 0px; padding: 30px; font-family: Menlo, Consolas, mono...
r overlay = document.getElementById(OVERLAY_ID); if (overlay) { overlay.remove(); console.log('[parcel] ✨ Error resolved'); } } functio
identifier_body
index.b4f5078c.js
string; declare var HMR_SECURE: boolean; */ var OVERLAY_ID = '__parcel__error__overlay__'; var OldModule = module.bundle.Module; function Module(moduleName) { OldModule.call(this, moduleName); this.hot = { data: module.bundle.hotData, _acceptCallbacks: [], _disposeCallbacks: [], accept: function (f...
d.hot._disposeCallbacks.forEach(function (cb) { cb(bundle.hotData); }); } delete b
conditional_block
Simple-Linear-Regression.py
c + m_1x_1 + m_2x_2 + ... + m_nx_n$ # # - $y$ is the response # - $c$ is the intercept # - $m_1$ is the coefficient for the first feature # - $m_n$ is the coefficient for the nth feature<br> # # In our case: # # $y = c + m_1 \times TV$ # # The $m$ values are called the model **coefficients** or **model paramet...
# # # # In[45]:
random_line_split
ctl.rs
action: NtpCtlAction, } impl NtpDaemonOptions { const TAKES_ARGUMENT: &[&'static str] = &["--config", "--format"]; const TAKES_ARGUMENT_SHORT: &[char] = &['c', 'f']; /// parse an iterator over command line arguments pub fn try_parse_from<I, T>(iter: I) -> Result<Self, String> where I: ...
() -> std::io::Result<ExitCode> { let options = match NtpDaemonOptions::try_parse_from(std::env::args()) { Ok(options) => options, Err(msg) => return Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, msg)), }; match options.action { NtpCtlAction::Help => { printl...
main
identifier_name
ctl.rs
, action: NtpCtlAction, } impl NtpDaemonOptions { const TAKES_ARGUMENT: &[&'static str] = &["--config", "--format"]; const TAKES_ARGUMENT_SHORT: &[char] = &['c', 'f']; /// parse an iterator over command line arguments pub fn try_parse_from<I, T>(iter: I) -> Result<Self, String> where I...
let observation = config .observability .observe .observation_path .unwrap_or_else(|| PathBuf::from("/run/ntpd-rs/observe")); match options.format { Format::Plain => print_state(Format::Plain, observation).await, ...
let config = config.unwrap_or_default();
random_line_split
ctl.rs
action: NtpCtlAction, } impl NtpDaemonOptions { const TAKES_ARGUMENT: &[&'static str] = &["--config", "--format"]; const TAKES_ARGUMENT_SHORT: &[char] = &['c', 'f']; /// parse an iterator over command line arguments pub fn try_parse_from<I, T>(iter: I) -> Result<Self, String> where I: ...
}, CliArg::Argument(option, value) => match option.as_str() { "-c" | "--config" => { options.config = Some(PathBuf::from(value)); } "-f" | "--format" => match value.as_str() { "pl...
{ Err(format!("invalid option provided: {option}"))?; }
conditional_block
MRGnodeHFS.py
D': 10, 'n_na': 200, 'HFSreferenceNode': 25, 'HFSdur': 50.0, 'HFSfrequency': 200, 'HFSpolarity': 1.0, 'HFSdelay': 0, 'HFSpulsewidth':0.09, 'HFSamp': 1.154, 'HFSwaveform': 0, 'HFSx': 0.0, 'HFSy': 0.0, 'HFSz': 1000.0, 'intrinsicNode': 0, 'intrinsicDur': 0.1, 'in...
rec['spiketimes'],rec['apcount'] = record_node_spikes(k) if verbose: print('Now recording from '+str(k)) return rec def resetRecorder(rec,verbose=False): ''' Clears hoc vectors in spiketimes and voltage and resets apcounts. ''' for k,o in rec['spiketimes'].iteritems(): ...
rec['voltage'] = record_node_voltage(k)
conditional_block
MRGnodeHFS.py
=None): ''' Inserts recorders for NEURON state variables. Use one per segment. "labels" is a dictionary. Example {'v': '_ref_v'}. Specify 'rec' to append to previous recorders. Records also time if 'rec' is 'None' (default). (Aknowledgements: Daniele Linaro) ''' if rec is None:...
'''
random_line_split
MRGnodeHFS.py
D': 10, 'n_na': 200, 'HFSreferenceNode': 25, 'HFSdur': 50.0, 'HFSfrequency': 200, 'HFSpolarity': 1.0, 'HFSdelay': 0, 'HFSpulsewidth':0.09, 'HFSamp': 1.154, 'HFSwaveform': 0, 'HFSx': 0.0, 'HFSy': 0.0, 'HFSz': 1000.0, 'intrinsicNode': 0, 'intrinsicDur': 0.1, 'in...
def createMRGaxon(par, verbose): ''' Initializes the model. Creates the axon and stimulation according to the parameters. ''' h('{load_file("stdgui.hoc")}') fix_patternLag_vector(par) pass_parameters_to_nrn(par,['pattern','patternLag'],verb=verbose) h('{load_file("MRGnodeHFS.hoc")}') ...
''' Records the membrane potential of a particular set of nodes. ''' rec = None segments = [] for n in nodenumber: segments.append(h.node[n](0.5)) for seg,n in zip(segments,nodenumber): rec = insert_nrn_recorders(seg,{'v_node'+str(n):'_ref_v'},rec) return rec
identifier_body
MRGnodeHFS.py
y': 0.0, 'HFSz': 1000.0, 'intrinsicNode': 0, 'intrinsicDur': 0.1, 'intrinsicAmp': 2.0, 'pattern': np.array([40.0]), 'patternLag': np.array([39.9]) } g_recpar = { 'record': True, 'plot': False, 'nodes':np.array(range(0,g_par['axonnodes'])), 'filename': 'data/simulation.h5', ...
runMRGaxon
identifier_name
template_tool.py
}之间的)会原样输出, 但是被mark_safe修饰过就能被浏览器翻译成html语言 默认机制的好处是: 如果黑客在可输入框中输入html语句,提交后存到数据库,再次拿到时不会被翻译成html语句,html代码就无法植入 如果不这么做,那么他想要插入什么语句就是什么语句,会被植入任何广告等等 ''' return mark_safe("".join(ret_html)) @register.simple_tag def make_url(path_info, filter_dict, action): ''' 对已有的url和get进...
identifier_name
template_tool.py
: choice = None if choice: value = getattr(obj, "get_%s_display" % field)() else: value = getattr(obj, field) return value @register.filter def get_model_value(obj, field): value = get_depth_value(obj, field) return value @register...
get_model_value(table_obj, field) ret_html.append("<td>%s</td>" % (get_model_value(table_obj, field))) return mark_safe("".join(ret_html)) @register.simple_tag def get_filter_options(table, field): """ 拿到该字段的对象,找get_choices 如果有__ 如:group__groupname 列出所有gr...
= admin_class.list_editable form_obj = admin_class.model_change_form(instance=table_obj) ret_html = [] ret_html.append('''<td> <div class="checkbox check-transparent"> <input type="checkbox" class="magic-checkbox" id="check_%s" name="check_item" value="%s" onclick="check_comp...
identifier_body
template_tool.py
: choice = None if choice: value = getattr(obj, "get_%s_display" % field)() else: value = getattr(obj, field) return value @register.filter def get_model_value(obj, field): value = get_depth_value(obj, field) return value @register...
@register.simple_tag def make_url(path_info, filter_dict, action): ''' 对已有的url和get进行重构 :param path_info: :return: ''' param_dict = {} for k, v in filter_dict.items(): param_dict[k] = "%s=%s" % (k, v) url = "%s%s?%s" % (path_info, action, "&".join(param_dict.values()...
''' return mark_safe("".join(ret_html))
random_line_split
template_tool.py
else: verbose_name = model_class._meta.get_field(field).verbose_name return verbose_name def get_depth_value(obj, field): """ 递归读取 aa__bb__cc 如果有__说明是外键,往里面走 如果找到最里面的,看是否是choice,如果是,get_该字段_display找值,如果不是,直接按照该字段找值 a__b__c """ fields = field.split("__", 1...
verbose_name = get_field_verbose_name(field_obj.related_model, fields[1])
conditional_block
updateDeps.js
*/ const _nextPreHighestVersion = (latestTag, lastVersion, pkgPreRelease) => { const bumpFromTags = latestTag ? semver.inc(latestTag, "prerelease", pkgPreRelease) : null; const bumpFromLast = semver.inc(lastVersion, "prerelease", pkgPreRelease); return bumpFromTags ? getHighestVersion(bumpFromLast, bumpFromTags) :...
getPreReleaseTag, updateManifestDeps,
random_line_split
train.py
bs:] # target = torch.ones(bs, requires_grad=True).to(device) loss = loss_fn(pos_sim, neg_sim, target) total_loss.append(loss.item()) pbar.set_postfix(batch_loss=loss.item()) loss.backward() optimizer.step() return np.mean(total_loss) def evaluate(date_loader, mode...
if isinstance(topk, int): accuracy = get_accuracy(qids, predictions, true_labels, 1) return accuracy elif isinstance(topk, list): accuracies = {} for i in topk: accuracy = get_accuracy(qids, predictions, true_labels, i) accuracies[i] = accuracy ret...
random_line_split
train.py
:] # target = torch.ones(bs, requires_grad=True).to(device) loss = loss_fn(pos_sim, neg_sim, target) total_loss.append(loss.item()) pbar.set_postfix(batch_loss=loss.item()) loss.backward() optimizer.step() return np.mean(total_loss) def evaluate(date_loader, model,...
cies = {} for i in topk: accuracy = get_accuracy(qids, predictions, true_labels, i) accuracies[i] = accuracy return accuracies else: raise ValueError('Error topk') def run(): args = parse_args() # 初始化随机数种子,以便于复现实验结果 start_epoch = 1 random.seed(args.s...
labels, 1) return accuracy elif isinstance(topk, list): accura
conditional_block
train.py
bs:] # target = torch.ones(bs, requires_grad=True).to(device) loss = loss_fn(pos_sim, neg_sim, target) total_loss.append(loss.item()) pbar.set_postfix(batch_loss=loss.item()) loss.backward() optimizer.step() return np.mean(total_loss) def evaluate(date_loader, mode...
output_dir = os.path.join(args.out_dir, base_dir) model_dir = os.path.join(output_dir, 'save_model') os.makedirs(output_dir) # 创建输出根目录 os.makedirs(model_dir) # 输出参数 logger = get_logger(output_dir) logger.info(pprint.pformat(vars(args))) logger.info(f'output dir is {outpu...
start_epoch = 1 random.seed(args.seed) np.random.seed(args.seed) torch.manual_seed(args.seed) if args.device != -1: torch.cuda.manual_seed(args.seed) device = torch.device(f'cuda:{args.device}' if torch.cuda.is_available() and args.device >= 0 else 'cpu') if torch.cuda.is_available() an...
identifier_body
train.py
(epoch, data_loader, model, optimizer, loss_fn, device): """ 进行一次迭代 """ model.train() pbar = tqdm(data_loader, desc='Train Epoch {}'.format(epoch)) total_loss = [] for batch_idx, batch in enumerate(pbar): optimizer.zero_grad() target = torch.ones(batch.batch_size, requires_g...
train_epoch
identifier_name
util.rs
match file.write_all(data) { Ok(()) => Ok(data.len()), Err(_) => Ok(0), // signals to cURL that the writing failed } })?; transfer.perform()?; Ok(()) } //////////////////////////////////////////////////////////////////////////////// // PathExt trait /////////////////...
fn _submodule_update(repo: &Repository, todo: &mut Vec<Repository>) -> Result<(), Error> { for mut submodule in repo.submodules()? { submodule.update(true, None)?; todo.push(submodule.open()?); } Ok(()) } let mut repos = Vec::ne...
} /// Recursively update Git submodules. pub fn submodule_update(repo: &Repository) -> Result<(), Error> {
random_line_split
util.rs
match file.write_all(data) { Ok(()) => Ok(data.len()), Err(_) => Ok(0), // signals to cURL that the writing failed } })?; transfer.perform()?; Ok(()) } //////////////////////////////////////////////////////////////////////////////// // PathExt trait ////////////////////////...
{ /// The temporary directory or file path. path: Option<PathBuf>, } impl TempPath { /// Create a new `TempPath` based on an original path, the temporary /// filename will be placed in the same directory with a deterministic name. /// /// # Errors /// /// If the temporary path already ...
TempPath
identifier_name
util.rs
match file.write_all(data) { Ok(()) => Ok(data.len()), Err(_) => Ok(0), // signals to cURL that the writing failed } })?; transfer.perform()?; Ok(()) } //////////////////////////////////////////////////////////////////////////////// // PathExt trait ////////////////////////...
/// Fetch a Git repository. pub fn fetch(repo: &Repository) -> anyhow::Result<()> { with_fetch_options(|mut opts| { repo.find_remote("origin") .context("failed to find remote `origin`")? .fetch(&DEFAULT_REFSPECS, Some(&mut opts), None)?; Ok(()) ...
{ with_fetch_options(|mut opts| { let repo = Repository::init(dir)?; repo.remote("origin", url.as_str())? .fetch(&DEFAULT_REFSPECS, Some(&mut opts), None)?; Ok(repo) }) .with_context(s!("failed to git clone `{}`", url)) }
identifier_body
Main.py
.players + 1): link_entrances(world, player) mark_light_world_regions(world) else: for player in range(1, world.players + 1): link_inverted_entrances(world, player) mark_dark_world_regions(world) logger.info('Generating Item Pool.') for player in range(1, ...
elif args.algorithm == 'vt25': distribute_items_restrictive(world, 0) elif args.algorithm == 'vt26': distribute_items_restrictive(world, gt_filler(world), shuffled_locations) elif args.algorithm == 'balanced': distribute_items_restrictive(world, gt_filler(world)) if world.play...
distribute_items_staleness(world)
conditional_block
Main.py
# ToDo: Not good yet ret = World(world.players, world.shuffle, world.logic, world.mode, world.swords, world.difficulty, world.difficulty_adjustments, world.timer, world.progressive, world.goal, world.algorithm, world.place_dungeon_items, world.accessibility, world.shuffle_ganon, world.quickswap, world.fastmenu,...
get_path
identifier_name
Main.py
if world.mode != 'inverted': for player in range(1, world.players + 1): create_regions(world, player) create_dungeons(world, player) else: for player in range(1, world.players + 1): create_inverted_regions(world, player) create_dungeons(world, pla...
start = time.perf_counter() # initialize the world world = World(args.multi, args.shuffle, args.logic, args.mode, args.swords, args.difficulty, args.item_functionality, args.timer, args.progressive, args.goal, args.algorithm, not args.nodungeonitems, args.accessibility, args.shuffleganon, args.quickswap, args....
identifier_body
Main.py
.copy() ret.treasure_hunt_count = world.treasure_hunt_count ret.treasure_hunt_icon = world.treasure_hunt_icon ret.sewer_light_cone = world.sewer_light_cone ret.light_world_light_cone = world.light_world_light_cone ret.dark_world_light_cone = world.dark_world_light_cone ret.seed = world.seed ...
if any(exit == 'Pyramid Fairy' for (_, exit) in path):
random_line_split
misc.go
502 StatusServiceUnavailable = 503 StatusGatewayTimeout = 504 StatusHTTPVersionNotSupported = 505 ) var statusText = map[int]string{ StatusContinue: "Continue", StatusSwitchingProtocols: "Switching Protocols", StatusOK: "OK", S...
MaxAge
identifier_name
misc.go
Value can be used to store credentials in a cookie: // // var secret string // Initialized by application // const uidCookieMaxAge = 3600 * 24 * 30 // // // uidCookieValue returns the Set-Cookie header value containing a // // signed and timestamped user id. // func uidCookieValue(uid string) string { // s :...
{ actualToken = req.Header.Get(HeaderXXSRFToken) req.Param.Set(paramName, expectedToken) }
conditional_block
misc.go
1 StatusPaymentRequired = 402 StatusForbidden = 403 StatusNotFound = 404 StatusMethodNotAllowed = 405 StatusNotAcceptable = 406 StatusProxyAuthenticationRequired = 407 StatusRequestTimeout = 408 StatusConflict ...
{ return &Cookie{name: name, value: value, path: "/", httpOnly: true} }
identifier_body
misc.go
401 StatusPaymentRequired = 402 StatusForbidden = 403 StatusNotFound = 404 StatusMethodNotAllowed = 405 StatusNotAcceptable = 406 StatusProxyAuthenticationRequired = 407 StatusRequestTimeout = 408 StatusConflict ...
StatusNotModified: "Not Modified", StatusUseProxy: "Use Proxy", StatusTemporaryRedirect: "Temporary Redirect", StatusBadRequest: "Bad Request", StatusUnauthorized: "Unauthorized", StatusPaymentRequired: "Payment Require...
StatusMovedPermanently: "Moved Permanently", StatusFound: "Found", StatusSeeOther: "See Other",
random_line_split
ABCA_topK.py
""" returns the vertices of a graph """ return list(self.__graph_dict.keys()) def edges(self): """ returns the edges of a graph """ return self.__generate_edges() def num_vertices(self): """ returns the number of vertices of a graph """ return len(self...
return self.__bfs_dict def vertices(self):
random_line_split
ABCA_topK.py
graph_dict[vertex]: self.__graph_dict[node].remove(vertex) self.__graph_dict.pop(vertex) def add_edge(self, edge): """ assumes that edge is of type set, tuple or list; between two vertices can be multiple edges! """ edge = set(edge) ...
def set_m(graph, eta): m = int(math.log2((graph.num_vertices()**2)/(eta**2))) print("m = %d" %m) return m #@jit def cal_bc(graph, m, s_list, t_list): # m must be much smaller than the number of edges nd_list = list(graph.vertices()) bc_dict = dict((node, 0) for node in nd_...
total_count[current_node.name] = 0 if current_node.name not in tree_map.keys(): return children = tree_map[current_node.name] for child in children: child_node = Node(child) current_node.add_child(child_node) add_branch(tree_map, child_node, total_count) return
identifier_body
ABCA_topK.py
graph_dict[vertex]: self.__graph_dict[node].remove(vertex) self.__graph_dict.pop(vertex) def add_edge(self, edge): """ assumes that edge is of type set, tuple or list; between two vertices can be multiple edges! """ edge = set(edge) ...
(self, s, t): #current_bfs = dict() pre_map = self.bfs(s) if t in pre_map: return [True, pre_map] return[False, pre_map] def __str__(self): res = "vertices: " for k in self.__graph_dict: res += str(k) + " " res += "\nedges: ...
is_connect
identifier_name
ABCA_topK.py
graph_dict[vertex]: self.__graph_dict[node].remove(vertex) self.__graph_dict.pop(vertex) def add_edge(self, edge): """ assumes that edge is of type set, tuple or list; between two vertices can be multiple edges! """ edge = set(edge) ...
else: parents[node].append(s) # record 'parents' of this node pre_dict[node].append(s) node_count_dict.pop('fake_root') return [pre_dict, node_count_dict] # two returns: 1) tree; 2) node count dictionary def dfs(root, total_count): ...
nq.append(node) # let 'node' in queue pre_dict[node] = [s] # the 'parent' (in terms of shortest path from 'root') of 'node' is 's' dist[node] = dist[s] + 1 # shortest path to 'root' visited[node]=1 # 'node' is visted parents[node]=[s] # record 'parents...
conditional_block
zbdsqr.go
.Off(n-1), u); err != nil { panic(err) } } if ncc > 0 { if err = Zlasr(Left, 'V', 'F', n, ncc, rwork.Off(0), rwork.Off(n-1), c); err != nil { panic(err) } } } // Compute singular values to relative accuracy TOL // (By setting TOL to be negative, algorithm will compute // singular...
shift = zero
random_line_split
zbdsqr.go
} else if ncvt < 0 { err = fmt.Errorf("ncvt < 0: ncvt=%v", ncvt) } else if nru < 0 { err = fmt.Errorf("nru < 0: nru=%v", nru) } else if ncc < 0 { err = fmt.Errorf("ncc < 0: ncc=%v", ncc) } else if (ncvt == 0 && vt.Rows < 1) || (ncvt > 0 && vt.Rows < max(1, n)) { err = fmt.Errorf("(ncvt == 0 && vt.Rows < 1) ...
{ var lower, rotate bool var abse, abss, cosl, cosr, cs, eps, f, g, h, hndrd, hndrth, meigth, mu, negone, oldcs, oldsn, one, r, shift, sigmn, sigmx, sinl, sinr, sll, smax, smin, sminl, sminoa, sn, ten, thresh, tol, tolmul, unfl, zero float64 var i, idir, isub, iter, j, ll, lll, m, maxit, maxitr, nm1, nm12, nm13, old...
identifier_body
zbdsqr.go
(uplo mat.MatUplo, n, ncvt, nru, ncc int, d, e *mat.Vector, vt, u, c *mat.CMatrix, rwork *mat.Vector) (info int, err error) { var lower, rotate bool var abse, abss, cosl, cosr, cs, eps, f, g, h, hndrd, hndrth, meigth, mu, negone, oldcs, oldsn, one, r, shift, sigmn, sigmx, sinl, sinr, sll, smax, smin, sminl, sminoa, s...
Zbdsqr
identifier_name
zbdsqr.go
64(maxitr*n*n)*unfl) } // Prepare for main iteration loop for the singular values // (MAXIT is the maximum number of passes through the inner // loop permitted before nonconvergence signalled.) maxit = maxitr * n * n iter = 0 oldll = -1 oldm = -1 // M points to last element of unconverged par...
{ if err = Zlasr(Right, 'V', 'F', nru, m-ll+1, rwork.Off(nm12), rwork.Off(nm13), u.Off(0, ll-1)); err != nil { panic(err) } }
conditional_block
bignum.rs
5).unwrap(); assert_eq!(six.cmp(&five), ::std::cmp::Ordering::Greater); assert_eq!(five.cmp(&five), ::std::cmp::Ordering::Equal); assert_eq!(five.cmp(&six), ::std::cmp::Ordering::Less); let bigger = Mpi::new(0x2a2f5dce).unwrap(); assert_eq!(bigger.byte_length().unwrap(), 4); assert_eq!(bigger....
() { use std::str::FromStr; fn mod_sqrt_test(a: &str, n: &str, expected: &str) { let a = Mpi::from_str(a).unwrap(); let n = Mpi::from_str(n).unwrap(); let expected = Mpi::from_str(expected).unwrap(); let mut computed = a.mod_sqrt(&n).unwrap(); /* If x = (a*a) mo...
test_mod_sqrt_fn
identifier_name
bignum.rs
::from_str(a).unwrap(); let n = Mpi::from_str(n).unwrap(); let expected = Mpi::from_str(expected).unwrap(); let mut computed = a.mod_sqrt(&n).unwrap(); /* If x = (a*a) mod p then also x = (-a*-a) mod p, ie if a square root exists then there are two square roots related b...
{ let radix: i64 = 58; let mut n = Mpi::new(0)?; fn base58_val(b: u8) -> mbedtls::Result<usize> { for (i, c) in BASE58_ALPHABET.iter().enumerate() { if *c == b { return Ok(i); } } Err(mbedtls::Error::Base64InvalidCharacter) } for c i...
identifier_body
bignum.rs
(5).unwrap(); assert_eq!(six.cmp(&five), ::std::cmp::Ordering::Greater); assert_eq!(five.cmp(&five), ::std::cmp::Ordering::Equal); assert_eq!(five.cmp(&six), ::std::cmp::Ordering::Less); let bigger = Mpi::new(0x2a2f5dce).unwrap(); assert_eq!(bigger.byte_length().unwrap(), 4); assert_eq!(bigger...
#[cfg(feature = "std")] #[test] fn test_jacobi_fn() { use std::str::FromStr; fn jacobi_symbol_test(a: &str, n: &str, expected: i32) { let a = Mpi::from_str(a).unwrap(); let n = Mpi::from_str(n).unwrap(); let j = a.jacobi(&n).unwrap(); //println!("a={} n={} J={}", a, n, j); ...
}
random_line_split
bignum.rs
assert_eq!(five.cmp(&five), ::std::cmp::Ordering::Equal); assert_eq!(five.cmp(&six), ::std::cmp::Ordering::Less); let bigger = Mpi::new(0x2a2f5dce).unwrap(); assert_eq!(bigger.byte_length().unwrap(), 4); assert_eq!(bigger.bit_length().unwrap(), 30); let b_bytes = bigger.to_binary().unwrap(); ...
{ computed = (&n - &computed).unwrap(); }
conditional_block
warc.py
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. """ Classes writing data to WARC files """ import json, threading from io import BytesIO from w...
random_line_split
warc.py
IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTI...
_addRefersTo (self, headers, url): refersTo = self.documentRecords.get (url) if refersTo: headers['WARC-Refers-To'] = refersTo else: self.logger.error ('No document record found for {}'.format (url)) return headers def _writeDomSnapshot (self, item): ...
iled: # should have been handled by the logger already return concurrentTo = self._writeRequest (item) self._writeResponse (item, concurrentTo) def
identifier_body
warc.py
IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTI...
if payload: payload = BytesIO (payload) warcHeaders['X-Chrome-Base64Body'] = str (payloadBase64Encoded) record = self.writeRecord (req['url'], 'request', payload=payload, http_headers=httpHeaders, warc_headers_dict=warcHeaders) return recor...
rcHeaders['WARC-Truncated'] = bodyTruncated payload = None
conditional_block
warc.py
PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION ...
em): writer = self.writer encoding = 'utf-8' self.writeRecord (packageUrl ('script/{}'.format (item.path)), 'metadata', payload=BytesIO (str (item).encode (encoding)), warc_headers_dict={'Content-Type': 'application/javascript; charset={}'.format (encoding)}) ...
pt (self, it
identifier_name
api_op_UpdateItem.go
For the complete list of reserved words, see // Reserved Words (https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ReservedWords.html) // in the Amazon DynamoDB Developer Guide.) To work around this, you could specify // the following for ExpressionAttributeNames : // - {"#P":"Percentile"} // You c...
// One or more values that can be substituted in an expression. Use the : (colon) // character in an expression to dereference an attribute value. For example, // suppose that you wanted to check whether the value of the ProductStatus // attribute was one of the following: Available | Backordered | Discontinued You...
ExpressionAttributeNames map[string]string
random_line_split
api_op_UpdateItem.go
them, and new values for them. The following action values are // available for UpdateExpression . // - SET - Adds one or more attributes and values to an item. If any of these // attributes already exist, they are replaced by the new values. You can also use // SET to add or subtract from an attribute that ...
{ return err }
conditional_block
api_op_UpdateItem.go
// Value is mathematically added to the existing attribute. If Value is a // negative number, then it is subtracted from the existing attribute. If you use // ADD to increment or decrement a number value for an item that doesn't exist // before the update, DynamoDB uses 0 as the initial value. Similarly, if ...
{ in, ok := input.(*UpdateItemInput) if !ok { return internalEndpointDiscovery.WeightedAddress{}, fmt.Errorf("unknown input type %T", input) } _ = in identifierMap := make(map[string]string, 0) key := fmt.Sprintf("DynamoDB.%v", identifierMap) if v, ok := c.endpointCache.Get(key); ok { return v, nil } d...
identifier_body
api_op_UpdateItem.go
// - list_append (operand, operand) - evaluates to a list with a new element // added to it. You can append the new element to the start or the end of the list // by reversing the order of the operands. These function names are // case-sensitive. // - REMOVE - Removes one or more attributes from an item....
fetchOpUpdateItemDiscoverEndpoint
identifier_name
lib.rs
allow_sgx_debug_mode): bool; } } decl_module! { pub struct Module<T: Config> for enum Call where origin: T::Origin { type Error = Error<T>; fn deposit_event() = default; // the integritee-service wants to register his enclave #[weight = (<T as Config>::WeightInfo::register_encl...
{ let enclaves_count = Self::enclave_count() .checked_add(1) .ok_or("[Teerex]: Overflow adding new enclave to registry")?; <EnclaveIndex<T>>::insert(sender, enclaves_count); <EnclaveCount>::put(enclaves_count); enclaves_count }
conditional_block
lib.rs
()); <WorkerForShard>::insert(shard, sender_index); log::debug!("call confirmed with shard {:?}, call hash {:?}, ipfs_hash {:?}", shard, call_hash, ipfs_hash); Self::deposit_event(RawEvent::CallConfirmed(sender, call_hash)); Self::deposit_event(RawEvent::UpdatedIpfsHash(s...
{ use sp_runtime::traits::CheckedSub; let elapsed_time = <timestamp::Pallet<T>>::get() .checked_sub(&T::Moment::saturated_from(report_timestamp)) .ok_or("Underflow while calculating elapsed time since report creation")?; if elapsed_time < T::MomentsPerDay::get() { ...
identifier_body
lib.rs
map(|report| Enclave::new(sender.clone(), report.mr_enclave, report.timestamp, worker_url.clone(), report.build_mode))?; #[cfg(not(feature = "skip-ias-check"))] if !<AllowSGXDebugMode>::get() && enclave.sgx_mode == SgxBuildMode::Debug { log::error!("substraTEE_registry: debug mo...
swap_and_pop
identifier_name
lib.rs
uate associated types pub type AccountId<T> = <T as frame_system::Config>::AccountId; pub type BalanceOf<T> = <<T as Config>::Currency as Currency<AccountId<T>>>::Balance; #[derive(Encode, Decode, Default, Clone, PartialEq, Eq, sp_core::RuntimeDebug)] pub struct Request { pub shard: ShardIdentifier, pub cypher...
CallConfirmed(AccountId, H256), BlockConfirmed(AccountId, H256), } ); decl_storage! { trait Store for Module<T: Config> as Teerex { // Simple lists are not supported in runtime modules as theoretically O(n) // operations can be executed while only being charged O(1), see substra...
random_line_split
mod.rs
pub trait ChangeSet { fn as_ref(&self) -> Option<&ViewChanges>; /// Provides mutable reference to changes. The implementation for a `RawAccessMut` type /// should always return `Some(_)`. fn as_mut(&mut self) -> Option<&mut ViewChanges>; } /// No-op implementation used in `Snapshot`. impl ChangeSet for...
random_line_split
mod.rs
fn as_mut(&mut self) -> Option<&mut ViewChanges> { None } } impl ChangeSet for ChangesRef { fn as_ref(&self) -> Option<&ViewChanges> { Some(&*self) } fn as_mut(&mut self) -> Option<&mut ViewChanges> { None } } impl ChangeSet for ChangesMut<'_> { fn as_ref(&self) ->...
{ None }
identifier_body
mod.rs
Key + ?Sized> From<(&'a str, &'a K)> for IndexAddress { fn from((name, key): (&'a str, &'a K)) -> Self { Self { name: name.to_owned(), bytes: Some(key_bytes(key)), } } } macro_rules! impl_snapshot_access { ($typ:ty) => { impl RawAccess for $typ { ...
{ self.ended = true; None }
conditional_block
mod.rs
concat_keys!(key) } impl<T: RawAccess> View<T> { /// Creates a new view for an index with the specified address. #[doc(hidden)] // ^-- This method is used in the testkit to revert blocks. It should not be used // in the user-facing code; use more high-level abstractions instead (e.g., indexes or /...
peek
identifier_name
fitters.py
result of a fit. :param fit_result: The output from fit :param axes: The Matplotlib axes to add the fit to :param x: The values of X at which to visualize the model :returns: A list of matplotlib artists. **This is important:** plots will not be properly cleared if t...
return np.exp(-(x - mean) ** 2 / (2 * stddev ** 2)) * amplitude @staticmethod def fit_deriv(x, amplitude, mean, stddev): """ Gaussian1D model function derivatives. """ d_amplitude = np.exp(-0.5 / stddev ** 2 * (x - mean) ** 2) d_mean = amplitude * d_amplitude * ...
@staticmethod def eval(x, amplitude, mean, stddev):
random_line_split
fitters.py
of a fit. :param fit_result: The output from fit :param axes: The Matplotlib axes to add the fit to :param x: The values of X at which to visualize the model :returns: A list of matplotlib artists. **This is important:** plots will not be properly cleared if this isn...
(self, x, y, dy): """ Provide initial guesses for each model parameter. **The base implementation does nothing, and should be overridden** :param x: X - values of the data :type x: :class:`numpy.ndarray` :param y: Y - values of the data :type y: :class:`numpy.nd...
parameter_guesses
identifier_name
fitters.py
def plot(self, fit_result, axes, x, linewidth=None, alpha=None, color=None, normalize=None): """ Plot the result of a fit. :param fit_result: The output from fit :param axes: The Matplotlib axes to add the fit to :param x: The values of X at which to visualize the model ...
setattr(self, k, v)
conditional_block
fitters.py
of a fit. :param fit_result: The output from fit :param axes: The Matplotlib axes to add the fit to :param x: The values of X at which to visualize the model :returns: A list of matplotlib artists. **This is important:** plots will not be properly cleared if this isn...
def _gaussian_parameter_estimates(x, y, dy): amplitude = np.percentile(y, 95) y = np.maximum(y / y.sum(), 0) mean = (x * y).sum() stddev = np.sqrt((y * (x - mean) ** 2).sum()) return dict(mean=mean, stddev=stddev, amplitude=amplitude) class BasicGaussianFitter(BaseFitter1D): """ Fallb...
""" Provide initial guesses for each model parameter. **The base implementation does nothing, and should be overridden** :param x: X - values of the data :type x: :class:`numpy.ndarray` :param y: Y - values of the data :type y: :class:`numpy.ndarray` :param dy: ...
identifier_body
kmp.py
if iter>=self.em_num_min_steps: if LL[iter]-LL[iter-1]<self.em_max_diffLL or iter==self.em_num_max_steps-1: print('EM converged after ',str(iter),' iterations.') return print('Max no. of iterations reached') return def computeGamma(self,data...
min_dist = dist # print("min_dist: ", min_dist) replace_ind = i
conditional_block