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
routex.go
pubsub: pubsub.New(20), quit: make(chan int), } go ret.tutorialGenerator() return ret, nil } func (m RouteMap)
(ctx rest.Context, identity model.Identity) { id := rmodel.Identity{ Identity: identity, Type: "identity", Action: "update", } m.pubsub.Publish(m.identityName(identity), id) } func (m RouteMap) UpdateExfee(ctx rest.Context, invitations model.Invitation) { var crossId int64 var action string ctx.Bind(...
UpdateIdentity
identifier_name
routex.go
pubsub: pubsub.New(20), quit: make(chan int), } go ret.tutorialGenerator() return ret, nil } func (m RouteMap) UpdateIdentity(ctx rest.Context, identity model.Identity) { id := rmodel.Identity{ Identity: identity, Type: "identity", Action: "update", } m.pubsub.Publish(m.identityNam...
if err := ctx.BindError(); err != nil { ctx.Return(http.StatusBadRequest, err) return } endAt, err := m.breadcrumbsRepo.GetWindowEnd(userId, crossId) if err != nil { logger.ERROR("get user %d cross %d routex failed: %s", userId, crossId, err) ctx.Return(http.StatusInternalServerError, err) return } ret ...
random_line_split
routex.go
pubsub: pubsub.New(20), quit: make(chan int), } go ret.tutorialGenerator() return ret, nil } func (m RouteMap) UpdateIdentity(ctx rest.Context, identity model.Identity)
func (m RouteMap) UpdateExfee(ctx rest.Context, invitations model.Invitation) { var crossId int64 var action string ctx.Bind("cross_id", &crossId) ctx.Bind("action", &action) if err := ctx.BindError(); err != nil { ctx.Return(http.StatusBadRequest, err) return } if action != "join" && action != "remove" { ...
{ id := rmodel.Identity{ Identity: identity, Type: "identity", Action: "update", } m.pubsub.Publish(m.identityName(identity), id) }
identifier_body
Checker_ruleunit_test.js
", "HAAC_Aria_ImgAlt": "1128", "HAAC_BackgroundImg_HasTextOrTitle": "1132", "HAAC_Accesskey_NeedLabel": "1140", "HAAC_Aria_Or_HTML5_Attr": "1141", "HAAC_Canvas": "1143", "HAAC_Figure_label": "1144", "HAAC_Input_Placeholder": "1145", "HAAC_Aria_Native_Host_Sematics": "1146", "RPT_Form...
{ let filtReport = []; for (const issue of report.results) { delete issue.node; delete issue.ruleTime; delete issue.bounds; if (expectedInfo.ruleIds.includes(is...
conditional_block
Checker_ruleunit_test.js
": "1195", "HAAC_Combobox_Autocomplete": "1196", "HAAC_Combobox_Autocomplete_Invalid": "1197", "HAAC_Combobox_Expanded": "1198", "HAAC_Combobox_Popup": "1199", "WCAG21_Style_Viewport": "1200", "WCAG21_Label_Accessible": "1202", "WCAG21_Input_Autocomplete": "1203", "WCAG20_Input_VisibleLa...
// expect(typeof (actualMap[expected.ruleId])).toEqual('undefined', "\nShould trigger NO violations, but triggered for rule: " + expected.ruleId + " with " + actualMap[expected.ruleId]);
random_line_split
shows_data.js
. Indoor concerts held in the largest venues are sometimes called arena concerts or amphitheatre concerts. Informal names for a concert include show and gig.", "description": "Concert", "photos": [ "https://ichef.bbci.co.uk/news/1024/cpsprodpb/16441/production/_109910219_massiveattack2.jpg",...
name: "Wicked", price: 32.50, hotelPoints: 470, photo: "https://image.nuevayork.es/wp-content/uploads/2014/11/Wicked-on-Broadway-Tickets.png.webp", description: "Wicked, the Broadway sensation, looks at what happened in the Land of Oz…but from a different angle. Long before Dorot...
random_line_split
tool.js
.body.ontouchmove = function(event) { var el = document.getElementsByClassName('scroll'); if (el.length == 0) { return; } var y = event.originalEvent.changedTouches[0].clientY; var st = el[0].scrollTop; //滚动条高度 if (y >= window.lastY && st <= 10) { //如果滚动条高度小于0,可以理解为到顶了,且是下拉情况下,阻止touchmove事件。 window.la...
on() { // 获取当前时间戳(以s为单位) var timestamp = Date.parse(new Date()) / 1000; var jsapi_ticket = window.jsapi_ticket; var nonceStr = createNonceStr(); function createNonceStr() { var chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; var str = ""; for (var i = 0; i < 16; i++) { var rando...
签名的方法 util.getJssdkSign = functi
conditional_block
tool.js
.ui.showLoading(); return config; }, function(error) { // 对请求错误做些什么 window.ui && window.ui.showLoading(); return Promise.reject(error); }); // 为axios添加响应拦截器 ajax.interceptors.response.use(function(response) { // 对响应数据做点什么 window.ui && window.ui.hideLoading(); if ( response.data.code !=...
identifier_name
tool.js
.body.ontouchmove = function(event) { var el = document.getElementsByClassName('scroll'); if (el.length == 0) { return; } var y = event.originalEvent.changedTouches[0].clientY; var st = el[0].scrollTop; //滚动条高度 if (y >= window.lastY && st <= 10) { //如果滚动条高度小于0,可以理解为到顶了,且是下拉情况下,阻止touchmove事件。 window.la...
on.nonceStr = nonceStr; json.signature = signature; return json; } // 禁止微信分享 util.shareDeny = function() { //禁止分享配置 wx.config({ debug: false, appId: 'wx0cad77c43b1d74ce', timestamp: 123123213, nonceStr: '123123123', signature: '123123123', jsApiList: [ 'hideOptionMenu', ] }); wx.ready(function()...
a = new Uint8Array(encodeUTF8(string)); var result = sha1(data); var signature = Array.prototype.map.call(result, function(e) { return (e < 16 ? "0" : "") + e.toString(16); }).join(""); // return出去 var json = {} json.timestamp = timestamp; js
identifier_body
tool.js
null) { let AISessionToken = window.sessionStorage.getItem('AISessionToken'); if (AISessionToken == null) { AISessionToken = ''; // window.ui && window.ui.showQrcode(); // return; // 无token时阻止此次ajax请求 } let config = { baseURL: baseURL, timeout: 20000, responseType: "json", crossDomain: true, header...
return input;
random_line_split
tf.js
(false); console.log(o); if(o.isDetail != undefined){ if(o.isDetail == '1') o.isDetail = true; else if(o.isDetail == '0') o.isDetail = false; } if (!params.limit) params.limit = this.pageSize; params[dataProxy.loadArgsKey] = [ o, params ]; ...
gridConfigEx : this.gridConfigEx, store : this.store,
random_line_split
tf.js
(grid) { var tableStr = '<table cellpadding="0" cellspacing="0" width="100%" id="statisticByDay">'; var cm = grid.getColumnModel(); var colCount = cm.getColumnCount(); var temp_obj = new Array(); // 只下载没有隐藏的列(isHidden()为true表示隐藏,其他都为显示) // 临时数组,存放所有当前显示列的下标 for ( var i = 0; i < colCount; i++) {// 从第三列开始,因为我的第1、2...
printPage
identifier_name
tf.js
}, contextmenu : function(grid, rowIndex, e) { e.preventDefault(); e.stopEvent(); var updateMenu = new Ext.menu.Item({ iconCls : 'edit', id : 'updateMenu', text : '修改', handler : this.edit.createDelegate(this) }); var deleteMenu = new Ext.menu.Item({ iconCls : 'delete', id : 'deleteMen...
t.tf.PopSelect = Ext.extend(Ext.form.TriggerField, { triggerClass : 'x-form-date-trigger', readOnly : true, initComponent : function() { Ext.tf.PopSelect.superclass.initComponent(this); }, /** * Find ref element, set value */ setRefName : function(v) { var refName = this.refName || ''; // If not refNam...
conditional_block
tf.js
var store = grid.getStore(); var recordCount = store.getCount(); tableStr = tableStr + '<tbody>' for ( var i = 0; i < recordCount; i++) { var r = store.getAt(i); tableStr = tableStr + '<tr>'; for ( var j = 0; j < temp_obj.length; j++) { var dataIndex = cm.getDataIndex(temp_obj[j]); var tdValue = r.get(d...
{ var tableStr = '<table cellpadding="0" cellspacing="0" width="100%" id="statisticByDay">'; var cm = grid.getColumnModel(); var colCount = cm.getColumnCount(); var temp_obj = new Array(); // 只下载没有隐藏的列(isHidden()为true表示隐藏,其他都为显示) // 临时数组,存放所有当前显示列的下标 for ( var i = 0; i < colCount; i++) {// 从第三列开始,因为我的第1、2列是分别是ro...
identifier_body
index.go
} for _, field := range i.fields { indexValue := input.Get(field) key = append(key, field.tupleElement(indexValue)) } } } return } func (i *Index) needValueStore() bool { if i.handle != nil { return true } return false } // getOldKey is just an wrapper around getKey, except case when index has ...
{ start, end := i.dir.FDBRangeKeys() tr.ClearRange(fdb.KeyRange{Begin: start, End: end}) }
identifier_body
index.go
if i.handle != nil { keyTuple := i.handle(input.value.Interface()) // Would not index object if key is empty if keyTuple == nil || len(keyTuple) == 0 { return nil } tmpTuple := tuple.Tuple{} for _, element := range keyTuple { tmpTuple = append(tmpTuple, element) } // embedded tuple cause problem...
hash = hash[0:i.Geo] // Cutting hash to needed precision } key = append(key, hash) } else { //key = tuple.Tuple{indexValue} for _, field := range i.fields { indexValue := input.Get(field) key = append(key, field.tupleElement(indexValue)) } } } return } func (i *Index) needValueStore() ...
hash := geohash.Encode(lat, long) if i.Geo < 12 {
random_line_split
index.go
i.handle != nil { keyTuple := i.handle(input.value.Interface()) // Would not index object if key is empty if keyTuple == nil || len(keyTuple) == 0 { return nil } tmpTuple := tuple.Tuple{} for _, element := range keyTuple { tmpTuple = append(tmpTuple, element) } // embedded tuple cause problems w...
() bool { if i.handle != nil { return true } return false } // getOldKey is just an wrapper around getKey, except case when index has handle, when it can be dynamically changed func (i *Index) getOldKey(tr fdb.Transaction, primaryTuple tuple.Tuple, oldObject *Struct) (tuple.Tuple, error) { if i.needValueStore() ...
needValueStore
identifier_name
index.go
i.handle != nil { keyTuple := i.handle(input.value.Interface()) // Would not index object if key is empty if keyTuple == nil || len(keyTuple) == 0 { return nil } tmpTuple := tuple.Tuple{} for _, element := range keyTuple { tmpTuple = append(tmpTuple, element) } // embedded tuple cause problems w...
// nil means should not index this object if key == nil { return nil } if i.Unique { previousPromise := tr.Get(i.dir.Pack(key)) tr.Set(i.dir.Pack(key), primaryTuple.Pack()) // will be cancelled in case of error previousBytes, err := previousPromise.Get() if err != nil { return err } if len(prev...
{ // no need to delete any inex than return nil }
conditional_block
main.go
); err == nil { mgr.logger.Log(fmt.Sprintf("successfully joined cluster at %s", mgr.targetCluster)) } } default: err = fmt.Errorf("unsupported cluster-op specified \"%s\"", mgr.operation) } return err } func (mgr *etcdManager) getMemberID(ctx context.Context) (uint64, error) { var memberID uint64 // ...
forwardConfig.Server = manager.server forwardConfig.Client = manager.client forwardConfig.ClusterName = loadedConfig.ClusterName forwardConfig.AdditionalDimensions = datapoint.AddMaps(loadedConfig.AdditionalDimensions, forwardConfig.AdditionalDimensions) forwarder, err := loader.Forwarder(forwardConfig) if ...
for idx, forwardConfig := range loadedConfig.ForwardTo { logCtx := log.NewContext(logger).With(logkey.Protocol, forwardConfig.Type, logkey.Direction, "forwarder")
random_line_split
main.go
key.TotalPipeline, totalPipeline, "Waking up for graceful shutdown") if totalPipeline > 0 { p.logger.Log(logkey.TotalPipeline, totalPipeline, "Items are still draining") startingTimeGood = now continue } if now.Sub(startingTimeGood) >= *p.config.SilentGracefulTimeDuration { p.logger.Log(logkey....
{ for _, err := range errs { if err != nil { return err } } return nil }
identifier_body
main.go
case "join": mgr.logger.Log(fmt.Sprintf("joining cluster with etcd server name: %s", mgr.ServerConfig.Name)) if mgr.client, err = etcd.NewClient(mgr.targetCluster, etcd.SecurityConfig{}, true); err == nil { mgr.logger.Log(fmt.Sprintf("joining etcd cluster @ %s", mgr.client.Endpoints())) if err = mgr.server...
{ if !isStringInSlice(mgr.AdvertisedClientAddress(), mgr.targetCluster) { mgr.targetCluster = append(mgr.targetCluster, mgr.AdvertisedClientAddress()) } mgr.client, err = etcd.NewClient(mgr.targetCluster, etcd.SecurityConfig{}, true) }
conditional_block
main.go
ups: logMaxBackups, } p.logger.Log(logkey.Filename, lumberjackLogger.Filename, logkey.Dir, os.TempDir(), "Logging redirect setup") return lumberjackLogger } func (p *gateway) getLogger(loadedConfig *config.GatewayConfig) log.Logger { out := p.getLogOutput(loadedConfig) useJSON := *loadedConfig.LogFormat == "json"...
setupGoMaxProcs
identifier_name
ntd_utils.py
_feat_te,l_idx_te,y_te,X_test,y_test,X_idx): """ Goal: to replace the indicies with setIDs associated with the datasets in the "test" section of the mixed dataset from the "train" to the "test" features testIndex: the index from the yIndicies: a python dictionary; {"setID": list of indicies a...
X_train, X_test, y_train, y_test, X_idx = roidbToSVMData(roidbTr,roidbTe, ntdGameInfo['trainSize'], ntdGameInfo['testSize'], loaderSettin...
identifier_body
ntd_utils.py
,X_test,y_test,X_idx): """ Goal: to replace the indicies with setIDs associated with the datasets in the "test" section of the mixed dataset from the "train" to the "test" features testIndex: the index from the yIndicies: a python dictionary; {"setID": list of indicies associated with the set...
genConfDl
identifier_name
ntd_utils.py
# zero the parameter gradients optimizer.zero_grad() # forward outputs = model(inputs) _, preds = torch.max(outputs.data, 1) loss = criterion(outputs, labels) # backward + optimize only if in training phas...
if phase == 'train': scheduler.step() model.train(True) # Set model to training mode else: model.train(False) # Set model to evaluate mode running_loss = 0.0 running_corrects = 0 # Iterate over data. for data...
conditional_block
ntd_utils.py
preds = torch.max(outputs.data, 1) loss = criterion(outputs, labels) # backward + optimize only if in training phase if phase == 'train': loss.backward() optimizer.step() # statistics running_loss ...
print("{}: {}".format(setID,len(yIndicies[setID]))) if len(yIndicies[setID]) == 0: continue dsIdx = dsIndicies[setID] # index for l_feat_te testIndex = yIndicies[setID][0] # index for x_test X_test[testIndex] = l_feat_te[setID][dsIdx] # replace sample content X_idx[te...
yIndicies[setID] = list(np.where(y_test == setID)[0]) # find where the setID's are
random_line_split
spacetime.rs
pub fn attributes_did_change(&self) -> bool { !(self.attributes_installed.is_empty() && self.attributes_altered.is_empty()) } } /// Update an 'AttributeMap' in place given two sets of causetid and attribute retractions, which /// together contain enough information to reason about a "schemaRepli...
(attribute_id: SolitonId, existing: &AttributeMap) -> AttributeBuilder { existing.get(&attribute_id) .map(AttributeBuilder::to_modify_attribute) .unwrap_or_else(AttributeBuilder::default) } // Group mutations by impacted solitonId. let mut builders: BTreeMap<SolitonI...
attribute_builder_to_modify
identifier_name
spacetime.rs
pub fn attributes_did_change(&self) -> bool { !(self.attributes_installed.is_empty() && self.attributes_altered.is_empty()) } } /// Update an 'AttributeMap' in place given two sets of causetid and attribute retractions, which /// together contain enough information to reason about a "schemaRepli...
fn attribute_builder_to_modify(attribute_id: SolitonId, existing: &AttributeMap) -> AttributeBuilder { existing.get(&attribute_id) .map(AttributeBuilder::to_modify_attribute) .unwrap_or_else(AttributeBuilder::default) } // Group mutations by impacted solitonId. l...
/// This is suiBlock for producing a `AttributeMap` from the `schemaReplicant` materialized view, which does not /// contain install and alter markers. /// /// Returns a report summarizing the mutations that were applied. pub fn update_attribute_map_from_causetid_triples(attribute_map: &mut AttributeMap, assertions: Ve...
random_line_split
spacetime.rs
fn attributes_did_change(&self) -> bool { !(self.attributes_installed.is_empty() && self.attributes_altered.is_empty()) } } /// Update an 'AttributeMap' in place given two sets of causetid and attribute retractions, which /// together contain enough information to reason about a "schemaReplicant...
builder.component(false); }, v => { bail!(DbErrorKind::BadSchemaReplicantAssertion(format!("Attempted to retract :edb/isComponent with the wrong value {:?}.", v))); }, } }, ...
{ fn attribute_builder_to_modify(attribute_id: SolitonId, existing: &AttributeMap) -> AttributeBuilder { existing.get(&attribute_id) .map(AttributeBuilder::to_modify_attribute) .unwrap_or_else(AttributeBuilder::default) } // Group mutations by impacted solitonId. ...
identifier_body
spacetime.rs
.contains(&causetids::DB_CARDINALITY) && attributes.contains(&causetids::DB_VALUE_TYPE) { // Ensure that corresponding :edb/causetid is also being retracted at the same time. if causetId_retractions.contains_key(&e) { // Remove attributes corresponding to retracted attribute. ...
builder.validate_alter_attribute().context(DbErrorKind::BadSchemaReplicantAssertion(format!("SchemaReplicant alteration for existing attribute with solitonId {} is not valid", solitonId)))?; let mutations = builder.mutate(entry.get_mut()); attributes_altered.insert(solitonI...
conditional_block
make.py
size, --device=paper, 2 pages per sheet * screen: normal pages size, --device=screen If a separate ptex2tex step is wanted, fill in all necessary commands in the ptex2tex string. """ if name.endswith('.do.txt'): name = name.replace('.do.txt', '') system('rm -f %(name)s.aux' % vars())...
options += ' --keep_pygments_html_bg' options += ' --html_output="%(name)s-%(postfi)s' cmd = 'doconce format html %(name)s %(options)s ' % vars() system(cmd) cmd = 'doconce slides_html %(name)s-%(postfi)s reveal --html_slide_theme=%(theme)s' system(cmd) def deck_slides(name, options='', postf...
ygment_styles combinations = recommended_html_styles_and_pygment_styles() options += ' --pygments_html_style=%s' % combinations['reveal'][theme][0] if '--keep_pygments_html_bg' not in options:
conditional_block
make.py
(cmd) system(cmd_latex) system(cmd_latex) if latex_program == 'latex': cmd = 'dvipdf %(name)s' % vars() system(cmd) # Could instead of dvipdf run the old-fashioned dvips and ps2pdf if version in ('2up', 'A4-2up'): # Use pdfnup to make two pages per sheet cmd = 'p...
ocon
identifier_name
make.py
def spellcheck(): for filename in glob.glob('*.do.txt'): if not filename.startswith('tmp'): cmd = 'doconce spellcheck -d .dict4spell.txt %(filename)s' % vars() system(cmd) def latex(name, latex_program='pdflatex', # or 'latex' options='--latex_code_style=vrb...
"""Run system command cmd using subprocess module.""" print cmd try: output = subprocess.check_output(cmd, shell=True, stderr=subprocess.STDOUT) except subprocess.CalledProcessError as e: print """Command %s failed""" % cmd print 'Return cod...
identifier_body
make.py
page size, --device=paper, 2 pages per sheet * screen: normal pages size, --device=screen If a separate ptex2tex step is wanted, fill in all necessary commands in the ptex2tex string. """ if name.endswith('.do.txt'): name = name.replace('.do.txt', '') system('rm -f %(name)s.aux' % va...
system(cmd) for filename in [name, '._%s000' % name]: print(filename) cmd = u"doconce replace 'Read' 'Перейти к первой главе' %s.html".encode('utf-8') % filename system(cmd) cmd = u"doconce subst '.*Next.*' '' %s.html".encode('utf-8') % filename...
cmd = u"doconce replace '&larr; Prev' '&larr; Предыдущая глава' %s".encode('utf-8') % filename system(cmd) cmd = u"doconce replace 'Next &rarr;' ' Следующая глава &rarr;' %s".encode('utf-8') % filename
random_line_split
init.rs
= Vec::new(); for arg in args { let path = PathBuf::from(&arg); if path.exists() { let absolute_path = util::prefix_path(&current_dir, path); build_args.push(absolute_path.to_string_lossy().into_owned()); continue; } build_args.push(arg.to_string_lossy().into_owned()); if arg ==...
path( helpe
identifier_name
init.rs
Option<(&mut AndroidEnv, &AndroidConfig)>, ) -> Result<()> { if let Some((env, config)) = android { for target in AndroidTarget::all().values() { let config = target.generate_cargo_config(config, env)?; let target_var_name = target.triple.replace('-', "_").to_uppercase(); if let Some(linker) = ...
#[allow(unused_variables)] non_interactive: bool, #[allow(unused_variables)] reinstall_deps: bool, skip_targets_install: bool, ) -> Result<App> { let current_dir = current_dir()?; let tauri_config = get_tauri_config(None)?; let tauri_config_guard = tauri_config.lock().unwrap(); let tauri_config_ = tauri_...
pub fn exec( target: Target, wrapper: &TextWrapper,
random_line_split
init.rs
Option<(&mut AndroidEnv, &AndroidConfig)>, ) -> Result<()> { if let Some((env, config)) = android { for target in AndroidTarget::all().values() { let config = target.generate_cargo_config(config, env)?; let target_var_name = target.triple.replace('-', "_").to_uppercase(); if let Some(linker) = ...
build_args.insert(0, var("npm_lifecycle_event").unwrap()); } if is_npm { build_args.insert(0, "run".into()); } } } map.insert("tauri-binary", binary.to_string_lossy()); map.insert("tauri-binary-args", &build_args); map.insert("tauri-binary-args-str", build_args.join(" "))...
{ if let Some(npm_execpath) = var_os("npm_execpath").map(PathBuf::from) { let manager_stem = npm_execpath.file_stem().unwrap().to_os_string(); let is_npm = manager_stem == "npm-cli"; let is_npx = manager_stem == "npx-cli"; binary = if is_npm { "npm".into() } else if is_npx { ...
conditional_block
init.rs
Option<(&mut AndroidEnv, &AndroidConfig)>, ) -> Result<()> { if let Some((env, config)) = android { for target in AndroidTarget::all().values() { let config = target.generate_cargo_config(config, env)?; let target_var_name = target.triple.replace('-', "_").to_uppercase(); if let Some(linker) = ...
( helper: &Helper, _: &Handlebars, _: &Context, _: &mut RenderContext, out: &mut dyn Output, ) -> HelperResult { out .write( &get_str_array(helper, |s| s.to_string()) .ok_or_else(|| RenderError::new("`join` helper wasn't given an array"))? .join(", "), ) .map_err(Into::into...
.write(&handlebars::html_escape(get_str(helper))) .map_err(Into::into) } fn join
identifier_body
consensus.rs
40_000; /// Fork every 6 months. pub const HARD_FORK_INTERVAL: u64 = YEAR_HEIGHT / 2; /// Testnet first hard fork height, set to happen around 2019-06-20 pub const TESTNET_FIRST_HARD_FORK: u64 = 185_040; /// Testnet second hard fork height, set to happen around 2019-12-19 pub const TESTNET_SECOND_HARD_FORK: u64 = 2...
let difficulty = max(MIN_DMA_DIFFICULTY, diff_sum * BLOCK_TIME_SEC / adj_ts); HeaderInfo::from_diff_scaling(Difficulty::from_num(difficulty), sec_pow_scaling)
random_line_split
consensus.rs
_bits to compute difficulty factors for higher /// Cuckoo graph sizes, changing this would hard fork pub const BASE_EDGE_BITS: u8 = 24; /// Default number of blocks in the past when cross-block cut-through will start /// happening. Needs to be long enough to not overlap with a long reorg. /// Rational /// behind the v...
damp
identifier_name
consensus.rs
== 4 { 5_424_600 } else if num == 5 { 7_524_600 } else if num == 6 { 9_624_600 } else if num == 7 { 11_724_600 } else if num == 8 { 13_824_600 } else if num == 9 { 539_424_600 } else { // shouldn't get here. 0 } } /// Calculate block reward based on height pub fn calc_block_reward(height: u64) ...
else { // should not get here 1 } } /// Calculate block overage based on height and claimed BTCUtxos pub fn calc_block_overage(height: u64) -> u64 { if height == 0 { 0 } else if height <= get_epoch_start(2) { (REWARD1 * height) + get_overage_offset_start_epoch(1) } else if height <= get_epoch_start(3) { ...
{ get_epoch_start(9) * REWARD8 + get_epoch_start(8) * REWARD7 + get_epoch_start(7) * REWARD6 + get_epoch_start(6) * REWARD5 + get_epoch_start(5) * REWARD4 + get_epoch_start(4) * REWARD3 + get_epoch_start(3) * REWARD2 + get_epoch_start(2) * REWARD1 + REWARD0 }
conditional_block
consensus.rs
{ get_epoch_start(6) * REWARD5 + get_epoch_start(5) * REWARD4 + get_epoch_start(4) * REWARD3 + get_epoch_start(3) * REWARD2 + get_epoch_start(2) * REWARD1 + REWARD0 } else if num == 7 { get_epoch_start(7) * REWARD6 + get_epoch_start(6) * REWARD5 + get_epoch_start(5) * REWARD4 + get_epoch_s...
{ version == header_version(height) }
identifier_body
lib.rs
let ty = try!(parser.parse_ty()); let value = try!(L::parse_arg_value(ecx, parser, ident)); Ok(ArgSpec { ident: ident, ty: ty, value: value, }) } pub fn cxx_type<'a>(&self, handler: &'a Handler) -> PResult<'a, Cow<'st...
// Pad the code such that the token remains on the same column while column < pos.col.0 {
random_line_split
lib.rs
Eq) { let mut tokens = Vec::new(); while !parser.check(&token::Comma) && !parser.check(&token::CloseDelim(token::Paren)) { tokens.push(try!(parser.parse_token_tree())); } Ok(flatten_tts(&tokens)) } else { Ok(vec![respa...
<'a>(ecx: &ExtCtxt<'a>, span: Span, tts: &[TokenTree]) -> PResult<'a, Function<L>> { let mut parser = ecx.new_parser_from_tts(tts); let args = if parser.check(&token::OpenDelim(token::Paren)) { Some(try!(Self::parse_args(ecx, &mut parser))) ...
parse
identifier_name
server.rs
{ fn to_json(&self) -> Json { match *self { Value::Null => panic!("Cannot allow the client to see nulls"), Value::Bool(bool) => Json::Boolean(bool), Value::String(ref string) => Json::String(string.clone()), Value::Float(float) => Json::F64(float), ...
(json: &Json) -> Self { json.as_string().unwrap().to_owned() } } impl<T: FromJson> FromJson for Vec<T> { fn from_json(json: &Json) -> Self { json.as_array().unwrap().iter().map(|t| FromJson::from_json(t)).collect() } } #[derive(Debug, Clone)] pub struct Event { pub changes: Changes, ...
from_json
identifier_name
server.rs
{ fn to_json(&self) -> Json { match *self { Value::Null => panic!("Cannot allow the client to see nulls"), Value::Bool(bool) => Json::Boolean(bool), Value::String(ref string) => Json::String(string.clone()), Value::Float(float) => Json::F64(float), ...
} #[derive(Debug, Clone)] pub struct Event { pub changes: Changes, pub session: String, } impl ToJson for Event { fn to_json(&self) -> Json { Json::Object(vec![ ("changes".to_string(), Json::Array( self.changes.iter().map(|&(ref view_id, ref view_changes)| { ...
{ json.as_array().unwrap().iter().map(|t| FromJson::from_json(t)).collect() }
identifier_body
server.rs
{ fn to_json(&self) -> Json { match *self { Value::Null => panic!("Cannot allow the client to see nulls"), Value::Bool(bool) => Json::Boolean(bool), Value::String(ref string) => Json::String(string.clone()), Value::Float(float) => Json::F64(float), ...
("changes".to_string(), Json::Array( self.changes.iter().map(|&(ref view_id, ref view_changes)| { Json::Array(vec![ view_id.to_json(), view_changes.fields.to_json(), view_changes.insert.to_json(), ...
Json::Object(vec![
random_line_split
index.js
StartOrStop', function (event, arg) { let id = Number.parseInt(arg); if(globalCond[id] == null) { console.log("不存在此任务") return; } globalCond[id] = !globalCond[id]; if(globalCond[id] == true) { configVideos.forEach(Element=>{ if(Element.id==id) { if(Element.isLiving == true) { startDownlo...
, timeout: htt
identifier_name
index.js
(Element.dir,{recursive :true}) } var nIdx = configVideos.indexOf(Element); if( nIdx > -1) { configVideos.splice(nIdx,1); fs.writeFileSync(globalConfigVideoPath,JSON.stringify(configVideos)); } event.sender.send("delvideo-reply",Element); } catch (error) { console.log(error) ...
else { key_uri = partent_uri + segment.key.uri; } } await download (key_uri, that.dir, { filename: "aes.key" }).catch(console.error); } if(fs.existsSync( aes_path )) { try { let key_ = fs.readFileSync( aes_path ); let iv_ = segment.key.iv != n...
random_line_split
index.js
} catch (error) { console.log(error) } } }); }); ipcMain.on('StartOrStop', function (event, arg) { let id = Number.parseInt(arg); if(globalCond[id] == null) { console.log("不存在此任务") return; } globalCond[id] = !globalCond[id]; if(globalCond[id] == true) { configVideos.forEach(Element=>{ if(E...
[]; if(!fs.existsSync(dir)) { fs
conditional_block
state.go
// Tag() string Engine() *StateEngine Activate() Deactivate() UseActivator(StateResponse) States UseDeactivator(StateResponse) States OverrideValidator(StateValidator) States acceptable(string, string) bool } // State represents a single state of with a specific tag and address // where the address is a single...
() States { co := se.curr if co == nil { // return se.owner return nil } return co.Engine().State() } // Partial renders the partial of the last state of the state address func (se *StateEngine) Partial(addr string) error { points, err := se.prepare(addr) if err != nil { return err } return se.trajec...
State
identifier_name
state.go
// Tag() string Engine() *StateEngine Activate() Deactivate() UseActivator(StateResponse) States UseDeactivator(StateResponse) States OverrideValidator(StateValidator) States acceptable(string, string) bool } // State represents a single state of with a specific tag and address // where the address is a single...
atomic.StoreInt64(&s.active, 0) s.do.Lock() if s.deactivator != nil { s.deactivator() } s.do.Unlock() } // acceptable checks if the state matches the current point func (s *State) acceptable(addr string, point string) bool { if s.optionalValidator == nil { if addr == point { return true } return fal...
{ return }
conditional_block
state.go
// Tag() string Engine() *StateEngine Activate() Deactivate() UseActivator(StateResponse) States UseDeactivator(StateResponse) States OverrideValidator(StateValidator) States acceptable(string, string) bool } // State represents a single state of with a specific tag and address // where the address is a single...
// UseActivator assigns the state a new active respone handler func (s *State) UseActivator(so StateResponse) States { s.ro.Lock() s.activator = so s.ro.Unlock() return s } // OverrideValidator assigns an validator to perform custom matching of the state func (s *State) OverrideValidator(so StateValidator) State...
{ s.do.Lock() s.deactivator = so s.do.Unlock() return s }
identifier_body
state.go
// Tag() string Engine() *StateEngine Activate() Deactivate() UseActivator(StateResponse) States UseDeactivator(StateResponse) States OverrideValidator(StateValidator) States acceptable(string, string) bool } // State represents a single state of with a specific tag and address // where the address is a single...
func (se *StateEngine) getAddr(s States) string { se.rw.RLock() defer se.rw.RUnlock() return se.states[s] } func (se *StateEngine) get(addr string) States { se.rw.RLock() defer se.rw.RUnlock() for sm, ao := range se.states { if ao != addr { continue } return sm } return nil } func (se *StateEngin...
stop = true }) } }
random_line_split
mpsc.rs
let shared = match self.shared.upgrade() { Some(shared) => shared, None => return Err(SendError(msg)), // receiver was dropped }; let mut shared = shared.borrow_mut(); match shared.capacity { Some(capacity) if shared.buffer.len() == capacity => { ...
(&mut self, msg: T) -> StartSend<T, SendError<T>> { self.do_send(msg) } fn poll_complete(&mut self) -> Poll<(), SendError<T>> { Ok(Async::Ready(())) } fn close(&mut self) -> Poll<(), SendError<T>> { Ok(Async::Ready(())) } } impl<T> Drop for Sender<T> { fn drop(&mut sel...
start_send
identifier_name
mpsc.rs
receive more messages) /// or we're closed with a list of messages we have left to receive. #[derive(Debug)] enum State<T> { Open(Rc<RefCell<Shared<T>>>), Closed(VecDeque<T>), } impl<T> Receiver<T> { /// Closes the receiving half /// /// This prevents any further messages from being sent on the ch...
/// When `stream` has additional items available, then the `SpawnHandle` /// will have those same items available.
random_line_split
mpsc.rs
let shared = match self.shared.upgrade() { Some(shared) => shared, None => return Err(SendError(msg)), // receiver was dropped }; let mut shared = shared.borrow_mut(); match shared.capacity { Some(capacity) if shared.buffer.len() == capacity => { ...
} impl<T> Stream for UnboundedReceiver<T> { type Item = T; type Error = (); fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> { self.0.poll() } } /// Creates an unbounded in-memory channel with buffered storage. /// /// Identical semantics to `channel`, except with no limit to buff...
{ self.0.close(); }
identifier_body
drafts.go
toml.Unmarshal(rawTOML, pkg); err != nil { return nil, fmt.Errorf("unable to parse package TOML\n%w", err) } return pkg, nil } func loadBuilderTOML(buildpackPath string) (*Builder, error) { rawTOML, err := ioutil.ReadFile(filepath.Join(buildpackPath, "builder.toml")) if err != nil && os.IsNotExist(err) { ret...
random_line_split
drafts.go
[j].ID) }) if deps, found := bp.Metadata["dependencies"]; found { if depList, ok := deps.([]map[string]interface{}); ok { for _, dep := range depList { bpDep := libpak.BuildpackDependency{ ID: asString(dep, "id"), Name: asString(dep, "name"), Version: asString(dep, "version"), UR...
{ paths := []string{ "/buildpack.toml", } org = strings.ToUpper(strings.ReplaceAll(org, "-", "_")) repo = strings.ToUpper(strings.ReplaceAll(repo, "-", "_")) if p, found := os.LookupEnv(fmt.Sprintf("BP_TOML_PATH_%s_%s", org, repo)); found { if !strings.HasSuffix(p, "/buildpack.toml") { p = fmt.Sprintf("%s...
identifier_body
drafts.go
("unable to parse package TOML\n%w", err) } return pkg, nil } func loadBuilderTOML(buildpackPath string) (*Builder, error) { rawTOML, err := ioutil.ReadFile(filepath.Join(buildpackPath, "builder.toml")) if err != nil && os.IsNotExist(err) { return nil, nil } else if err != nil { return nil, fmt.Errorf("unabl...
loadBuildpackImage
identifier_name
drafts.go
, err := template.New("draft").Parse(templateContents) if err != nil { return fmt.Errorf("unable to parse template %q\n%w", templateContents, err) } err = tmpl.Execute(output, context) if err != nil { return fmt.Errorf("unable to execute template %q\n%w", templateContents, err) } return nil } func (d Draft...
} } return Buildpack{}, fmt.Errorf("unable to load buildpack.toml for %s", imgUri) } func (g Github
{ tomlBytes, err := g.fetchTOMLFile(org, repo, version, path) if err != nil { var apiErr *github.ErrorResponse if errors.As(err, &apiErr) && apiErr.Response.StatusCode == 404 { fmt.Println("skipping 404", apiErr) continue } return Buildpack{}, fmt.Errorf("unable to fetch toml\n%w", err) ...
conditional_block
utility.js
; }, error: (XMLHttpRequest, textStatus, errorThrown) => { return errorThrown; } } $.ajax(ajaxConfig) } //............................................................................Send AjaxRequest With Object/parameter //.....................................................
return true; } //..........................Contact validation let contact_validate = (value) => { let contact = value var regexPattern = new RegExp(/^\d{4}[- ]?\d{7}$/); // regular expression pattern let isValid = regexPattern.test(contact); if (!isValid) { return false; } return...
return false; }
conditional_block
utility.js
}, error: (XMLHttpRequest, textStatus, errorThrown) => { return errorThrown; } } $.ajax(ajaxConfig) } //............................................................................Send AjaxRequest With Object/parameter //...................................................R...
ableName, itemsPerPage) { this.tableName = tableName; this.itemsPerPage = itemsPerPage; this.currentPage = 1; this.pages = 0; this.inited = false; this.showRecords = function (from, to) { var rows = document.getElementById(tableName).rows; // i starts from 1 to skip table...
ger(t
identifier_name
utility.js
; }, error: (XMLHttpRequest, textStatus, errorThrown) => { return errorThrown; } } $.ajax(ajaxConfig) } //............................................................................Send AjaxRequest With Object/parameter //.....................................................
}, error: (XMLHttpRequest, textStatus, errorThrown) => { return errorThrown; } } $.ajax(ajaxConfig) } //............................................................................Section Textbox/Labels/div handling //..................return Textbox Value let getTextboxV...
random_line_split
utility.js
}, error: (XMLHttpRequest, textStatus, errorThrown) => { return errorThrown; } } $.ajax(ajaxConfig) } //............................................................................Send AjaxRequest With Object/parameter //...................................................R...
rows[i].style.display = 'none'; else rows[i].style.display = ''; } } this.showPage = function (pageNumber) { if (!this.inited) { alert("not inited"); return; } var oldPageAnchor = document.getElementBy...
this.tableName = tableName; this.itemsPerPage = itemsPerPage; this.currentPage = 1; this.pages = 0; this.inited = false; this.showRecords = function (from, to) { var rows = document.getElementById(tableName).rows; // i starts from 1 to skip table header row for (...
identifier_body
Server.go
s.HandleDisconnect s.RegisterDefaultProtocols() s.PackManager = packs.NewManager(serverPath) s.PermissionManager = permissions.NewManager() s.PluginManager = NewPluginManager(s) s.QueryManager = query.NewManager() if config.UseEncryption { var curve = elliptic.P384() var err error s.private...
if server.tick%20 == 0 { server.QueryManager.SetQueryResult(server.GenerateQueryResult()) server.NetworkAdapter.GetRakLibManager().PongData = server.GeneratePongData()
random_line_split
Server.go
var err error s.privateKey, err = ecdsa.GenerateKey(curve, rand.Reader) text.DefaultLogger.LogError(err) if !curve.IsOnCurve(s.privateKey.X, s.privateKey.Y) { text.DefaultLogger.Error("Invalid private key generated") } var token = make([]byte, 128) rand.Read(token) s.token = token } r...
Tick
identifier_name
Server.go
tick int64 logger *utils.Logger pluginPath string playersPath string themePath string worldsPath string behaviorPacksPath string resourecePackPath string serverPath string config *utils.Config network networkapi.NetWork ip ...
func (server *Server) GetLevel(name string) *level.Level { return server.levels[name] } func (server *Server) GetDefaultLevel() *level.Level { return server.GetLevel(server.defaultLevel) } func (server *Server) GetPath() string { return server.serverPath } func (server *Server) ScheduleRepeatingTask(fn func(), ...
{ return server.levels }
identifier_body
Server.go
tick int64 logger *utils.Logger pluginPath string playersPath string themePath string worldsPath string behaviorPacksPath string resourecePackPath string serverPath string config *utils.Config network networkapi.NetWork ip ...
}() return ticker } func (server *Server) ScheduleDelayedTask(fn func(), d time.Duration) *time.Timer { return time.AfterFunc(d, fn) } /* // GetMinecraftVersion returns the latest Minecraft game version. // It is prefixed with a 'v', for example: "v1.2.10.1" func (server *Server) GetMinecraftVersion() string { r...
{ fn() }
conditional_block
stopwords.rs
"])), ("cross-platform", Some(&["windows", "winsdk", "macos", "mac", "osx", "linux", "unix", "gnu"])), ("portable", Some(&["windows", "winsdk", "macos", "mac", "osx", "linux", "unix", "gnu"])), ("winapi", Some(&["target", "windows", "gnu", "x86", "i686", "64", "pc"])), ("windows", Some(&...
].iter().copied().collect();
random_line_split
rasterbackend.rs
: u32, aspect_ratio: f32, } impl RasterBackend { pub fn new(width: u32, height: u32) -> Self { Self { render_options: RenderOptions::default(), width, height, aspect_ratio: width as f32 / height as f32, } } fn view_projection(&self, zoom:...
w0 * v0.y + w1 * v1.y + w2 * v2.y, w0 * v0.z + w1 * v1.z + w2 * v2.z, ); // fragment position in world space let fp = Vec3::new( w0 * v0m.x + w1 * v1m.x + w2 * v2m...
random_line_split
rasterbackend.rs
: u32, aspect_ratio: f32, } impl RasterBackend { pub fn new(width: u32, height: u32) -> Self
fn view_projection(&self, zoom: f32) -> Mat4 { // calculate view projection matrix let proj = glm::ortho( zoom * 0.5 * self.aspect_ratio, -zoom * 0.5 * self.aspect_ratio, -zoom * 0.5, zoom * 0.5, 0.0, 1.0, ); l...
{ Self { render_options: RenderOptions::default(), width, height, aspect_ratio: width as f32 / height as f32, } }
identifier_body
rasterbackend.rs
: u32, aspect_ratio: f32, } impl RasterBackend { pub fn new(width: u32, height: u32) -> Self { Self { render_options: RenderOptions::default(), width, height, aspect_ratio: width as f32 / height as f32, } } fn view_projection(&self, zoom:...
( &self, mesh: impl IntoIterator<Item = Triangle> + Copy, model_scale: f32, aabb: &AABB, timeout: Option<Duration>, ) -> Picture { let start_time = Instant::now(); let mut pic = Picture::new(self.width, self.height); let mut zbuf = ZBuffer::new(self.w...
render
identifier_name
rasterbackend.rs
: u32, aspect_ratio: f32, } impl RasterBackend { pub fn new(width: u32, height: u32) -> Self { Self { render_options: RenderOptions::default(), width, height, aspect_ratio: width as f32 / height as f32, } } fn view_projection(&self, zoom:...
pic.stroke_string( margin, pic.height() - text_size - margin, &text, text_size as f32, &"FFFFFFFF".into(), ); } pic
{ let margin = 3; let text_to_height_ratio = 16; let text = format!( "{}x{}x{}", aabb.size().x as i32, aabb.size().y as i32, aabb.size().z as i32 ); let text_size = pic.height() / text_to_height...
conditional_block
mod.rs
inline] fn put( &self, cf_name: impl AsRef<str>, key: impl AsRef<[u8]>, value: impl AsRef<[u8]>, ) -> Result<()> { let cf = self.get_cf_handle(cf_name)?; Ok(self .db() .put_cf_opt(cf, key, value, &default_write_opts())?) } #[inline...
(&self, cf_name: &str, opts: Options) -> Result<()> { if self.db().cf_handle(cf_name).is_none() { self.db_mut().create_cf(cf_name, &opts)?; } Ok(()) } } fn common_options<IK, N>() -> Options where IK: Metakey, N: Metakey, { let prefix_size = IK::SIZE + N::SIZE; ...
create_column_family
identifier_name
mod.rs
inline] fn put( &self, cf_name: impl AsRef<str>, key: impl AsRef<[u8]>, value: impl AsRef<[u8]>, ) -> Result<()> { let cf = self.get_cf_handle(cf_name)?; Ok(self .db() .put_cf_opt(cf, key, value, &default_write_opts())?) } #[inline...
checkpointer.create_checkpoint(checkpoint_path)?; Ok(()) } fn register_value_handle<'s, T: Value, IK: Metakey, N: Metakey>( &'s self, handle: &'s mut Handle<ValueState<T>, IK, N>, ) { handle.registered = true; let opts = common_options::<IK, N>(); s...
{ // TODO: add a warning log here // warn!(logger, "Checkpoint path {:?} exists, deleting"); fs::remove_dir_all(checkpoint_path)? }
conditional_block
mod.rs
inline] fn put( &self, cf_name: impl AsRef<str>, key: impl AsRef<[u8]>, value: impl AsRef<[u8]>, ) -> Result<()> { let cf = self.get_cf_handle(cf_name)?; Ok(self .db() .put_cf_opt(cf, key, value, &default_write_opts())?) } #[inline...
impl Backend for Rocks { fn name(&self) -> &str { self.name.as_str() } fn create(path: &Path, name: String) -> Result<Self> where Self: Sized, { let mut opts = Options::default(); opts.create_if_missing(true); let path: PathBuf = path.into(); if !p...
{ let prefix_size = IK::SIZE + N::SIZE; let mut opts = Options::default(); // for map state to work properly, but useful for all the states, so the bloom filters get // populated opts.set_prefix_extractor(SliceTransform::create_fixed_prefix(prefix_size as usize)); opts }
identifier_body
mod.rs
#[inline] fn put( &self, cf_name: impl AsRef<str>, key: impl AsRef<[u8]>, value: impl AsRef<[u8]>, ) -> Result<()> { let cf = self.get_cf_handle(cf_name)?; Ok(self .db() .put_cf_opt(cf, key, value, &default_write_opts())?) } #[inl...
} checkpointer.create_checkpoint(checkpoint_path)?; Ok(()) } fn register_value_handle<'s, T: Value, IK: Metakey, N: Metakey>( &'s self, handle: &'s mut Handle<ValueState<T>, IK, N>, ) { handle.registered = true; let opts = common_options::<IK, N>(); ...
// TODO: add a warning log here // warn!(logger, "Checkpoint path {:?} exists, deleting"); fs::remove_dir_all(checkpoint_path)?
random_line_split
index.ts
debug?: boolean // default: false transport?: { requestTimeout?: number // milliseconds to wait for rokka server response (default: 30000) retries?: number // number of retries when API response is 429 (default: 10)
maxTimeout?: number // maximum milliseconds between retries (default: 10000) randomize?: boolean // randomize time between retries (default: true) agent?: any } } interface RequestOptions { headers?: object noAuthHeaders?: boolean fallBackToText?: boolean form?: boolean multipart?: boolean fo...
minTimeout?: number // minimum milliseconds between retries (default: 1000)
random_line_split
index.ts
debug?: boolean // default: false transport?: { requestTimeout?: number // milliseconds to wait for rokka server response (default: 30000) retries?: number // number of retries when API response is 429 (default: 10) minTimeout?: number // minimum milliseconds between retries (default: 1000) maxTime...
if (options.noAuthHeaders !== true) { if (!options.forceUseApiKey && state.apiTokenGetCallback) { let apiToken = state.apiTokenGetCallback() // fill apiTokenPayload, if not set, this happens when you load a page, for example if (!state.apiTokenPayload) { state.api...
{ let uri = [options.host || state.apiHost, path].join('/') if ( queryParams && !( Object.entries(queryParams).length === 0 && queryParams.constructor === Object ) ) { uri += '?' + stringify(queryParams) } const headers: { 'Api-V...
identifier_body
index.ts
debug?: boolean // default: false transport?: { requestTimeout?: number // milliseconds to wait for rokka server response (default: 30000) retries?: number // number of retries when API response is 429 (default: 10) minTimeout?: number // minimum milliseconds between retries (default: 1000) maxTime...
( method: string, path: string, payload: any | null = null, queryParams: { [key: string]: string | number | boolean } | null = null, options: RequestOptions = { noAuthHeaders: false, fallBackToText: false, forceUseApiKey: false, noTokenRefresh:...
request
identifier_name
index.ts
://{organization}.rokka.io', apiVersion: 1, transport: { requestTimeout: 30000, retries: 10, minTimeout: 1000, maxTimeout: 10000, randomize: true, factor: 2, debug: false, }, } const getResponseBody = async (response: Response, fallbackToText = false) => { if (response.headers && re...
{ const formData = payload.formData || {} const requestData = new FormData() requestData.append(payload.name, payload.contents, payload.filename) Object.keys(formData).forEach(function (meta) { requestData.append(meta, JSON.stringify(formData[meta])) }) reque...
conditional_block
test-checkpoint.py
"source": [ "# Retrieve the parent divs for all headlines and preview text\n", "results = soup.find_all(\"div\", class_=\"list_text\")" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ ...
random_line_split
app.component.ts
this.script.src = "https://maps.googleapis.com/maps/api/js?key=AIzaSyDz7iXxtwOMovXzKaaWLzStFo1tDLP5PEg&libraries=places"; this.script.onload = () => { this.map = new google.maps.Map(document.getElementById('map'), { center: {lat: -33.8688, lng: 151.2195}, zoom: 13, mapTypeId: 'roadmap', ...
}); me.markers = []; var bounds = new google.maps.LatLngBounds(); service.textSearch(request, function(results, status, pagination) { if (status == google.maps.places.PlacesServiceStatus.OK) { results.forEach(function(place) { i++; var icon = { url:"https://cdn.mapma...
{ var me = this; var pyrmont = new google.maps.LatLng(this.currentLat, this.currentLng); var request = { location: pyrmont, radius: this.radius, type: ['fitness'], query: this.additionalFilter + ' ' + this.searchFitnessService }; // this.isLoading = true; this.searchresults = []; var ...
identifier_body
app.component.ts
this.input = document.getElementById('pac-input'); this.searchBox = new google.maps.places.SearchBox(this.input); var me = this; this.map.addListener('bounds_changed', function() { me.searchBox.setBounds(me.map.getBounds()); }); var bounds = new google.maps.LatLngBounds(); if (navigator.geolo...
onChangeAdditionalFilter
identifier_name
app.component.ts
.map.getBounds()); }); var bounds = new google.maps.LatLngBounds(); if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(position) { bounds = new google.maps.LatLngBounds(new google.maps.LatLng(position.coords.latitude, position.coords.longitude)); me.map.fitBounds(bo...
if(value == "") {return;} this.search(); }
random_line_split
reading.rs
use crate::{protocols::ReturnableConnection, Pea2Pea}; use async_trait::async_trait; use tokio::{ io::{AsyncRead, AsyncReadExt}, sync::mpsc, time::sleep, }; use tracing::*; use std::{io, net::SocketAddr, time::Duration}; /// Can be used to specify and enable reading, i.e. receiving inbound messages. /// ...
}
{ // don't do anything by default Ok(()) }
identifier_body
reading.rs
use crate::{protocols::ReturnableConnection, Pea2Pea}; use async_trait::async_trait; use tokio::{ io::{AsyncRead, AsyncReadExt}, sync::mpsc, time::sleep, }; use tracing::*; use std::{io, net::SocketAddr, time::Duration}; /// Can be used to specify and enable reading, i.e. receiving inbound messages. /// ...
(&self, source: SocketAddr, message: Self::Message) -> io::Result<()> { // don't do anything by default Ok(()) } }
process_message
identifier_name
reading.rs
use crate::{protocols::ReturnableConnection, Pea2Pea}; use async_trait::async_trait; use tokio::{ io::{AsyncRead, AsyncReadExt}, sync::mpsc, time::sleep, }; use tracing::*; use std::{io, net::SocketAddr, time::Duration}; /// Can be used to specify and enable reading, i.e. receiving inbound messages. /// ...
buffer: &[u8], ) -> io::Result<Option<(Self::Message, usize)>>; /// Processes an inbound message. Can be used to update state, send replies etc. #[allow(unused_variables)] async fn process_message(&self, source: SocketAddr, message: Self::Message) -> io::Result<()> { // don't do anythin...
&self, source: SocketAddr,
random_line_split
reading.rs
use crate::{protocols::ReturnableConnection, Pea2Pea}; use async_trait::async_trait; use tokio::{ io::{AsyncRead, AsyncReadExt}, sync::mpsc, time::sleep, }; use tracing::*; use std::{io, net::SocketAddr, time::Duration}; /// Can be used to specify and enable reading, i.e. receiving inbound messages. /// ...
else { node.disconnect(addr); break; } } }); conn.tasks.push(inbound_processing_task); // the task for reading messages from a stream ...
{ if let Err(e) = processing_clone.process_message(addr, msg).await { error!(parent: node.span(), "can't process an inbound message: {}", e); node.known_peers().register_failure(addr); ...
conditional_block
lib.rs
` files do //! not contain a header, the header is a dummy object. //! //! //! ### Adding support for new file types //! //! To add new file types, you need to add types that implement the //! `ReadLhe` and `WriteLhe` traits for the additional information //! stored in the file type. //! The type signature of the `read...
fn cause(&self) -> Option<&error::Error> { match *self { ReadError::Io(ref err) => Some(err), ReadError::Nom(_) => None, } } } /// A struct for process information /// /// This is the per process information contained in the `init` section /// of `lhe` files. /// When r...
{ match *self { ReadError::Io(..) => &"Failed to read the lhe file with an IO error", ReadError::Nom(..) => &"Failed to read the lhe file with a parse error", } }
identifier_body
lib.rs
hef::{ProcInfo, ReadLhe}; /// use lhef::plain::LheFile; /// /// let bytes = b"\ /// <LesHouchesEvents version=\"1.0\"> /// <init> /// 2212 2212 6500 6500 0 0 13100 13100 3 2 /// 2.1 3.2E-03 1.0E+00 1 /// 4.0 7.4E-03 1.0E+00 2 /// </init> /// </LesHouchesEvents>"; /// let lhe = LheFile::read_lhe(bytes).to_full_result()....
self.mother_2_id,
random_line_split
lib.rs
::Formatter) -> fmt::Result { match *self { ReadError::Io(ref err) => { write!(f, "Failed to read the lhe file with an IO error: {}", err) } ReadError::Nom(ref err) => write!( f, "Failed to read the lhe file with a parse error: ...
read_lhe
identifier_name
TEST.py
_list(fileOrDir) for path in fileName_list: # w, h = getWH(path) # imgY = getYdata(path, [w, h]) imgY = c_getYdata(path) imgY = normalize(imgY) imgY = np.resize(imgY, (1, imgY.shape[0], imgY.shape[1], 1)) original_ycbcr.append([imgY, imgCb...
# else: # while numFrames>0: # or_imgY =getOneFrameY(pair[0]) # gt_imgY =getOneFrameY(pair[1]) # # normalize # or_imgY = normalize(or_imgY) # # or_imgY = np.resize(or_imgY, (1, or_...
_list = load_file_list(fileOrDir[0]) test_list = get_train_list(load_file_list(fileOrDir[0]), load_file_list(fileOrDir[1])) for pair in test_list: filesize = os.path.getsize(pair[0]) picsize = getWH(pair[0])[0]*getWH(pair[0])[0] * 3 // 2 numFrames = filesize // picsiz...
conditional_block
TEST.py
_list(fileOrDir) for path in fileName_list: # w, h = getWH(path) # imgY = getYdata(path, [w, h]) imgY = c_getYdata(path) imgY = normalize(imgY) imgY = np.resize(imgY, (1, imgY.shape[0], imgY.shape[1], 1)) original_ycbcr.append([imgY, imgCb...
n17, cnn27, cnn37, cnn47, cnn7, cnn57 if QP < 17: R = cnn7.predict(file) elif 17 <= QP < 27: R = cnn17.predict(file) elif 27 <= QP < 37: R = cnn27.predict(file) elif 37 <= QP < 47: R = cnn37.predict(file) elif 47 <= QP < 57: R = cnn47.predict(file) else: ...
dict(model,model_set["CNN_I_QP7"]) cnn17=Predict(model,model_set["CNN_I_QP17"]) cnn27=Predict(model,model_set["CNN_I_QP27"]) cnn37=Predict(model,model_set["CNN2_I_QP37"]) cnn47=Predict(model,model_set["CNN_I_QP47"]) cnn57 = Predict(model, model_set["CNN_I_QP57"]) def predict(file, QP, frame_t...
identifier_body
TEST.py
_file_list(fileOrDir) for path in fileName_list: # w, h = getWH(path) # imgY = getYdata(path, [w, h]) imgY = c_getYdata(path) imgY = normalize(imgY) imgY = np.resize(imgY, (1, imgY.shape[0], imgY.shape[1], 1)) original_ycbcr.append([imgY, ...
self.graph = tf.Graph() # 为每个类(实例)单独创建一个graph self.model = model with self.graph.as_default(): self.input_tensor = tf.placeholder(tf.float32, shape=(1, None, None, 1)) #self.output_tensor = tf.make_template('input_scope', self.model)(self.input_tensor) self.o...
model = None def __init__(self, model, modelpath):
random_line_split
TEST.py
_list(fileOrDir) for path in fileName_list: # w, h = getWH(path) # imgY = getYdata(path, [w, h]) imgY = c_getYdata(path) imgY = normalize(imgY) imgY = np.resize(imgY, (1, imgY.shape[0], imgY.shape[1], 1)) original_ycbcr.append([imgY, imgCb...
if (isinstance(fileOrDir, str)): original_ycbcr, gt_y, fileName_list = prepare_test_data(fileOrDir) imgY = original_ycbcr[0][0] elif type(fileOrDir) is np.ndarray: imgY = fileOrDir imgY = normalize(np.reshape(fileOrDir, (1, len(fileOrDir), len(fileOrDir[0]), 1)...
identifier_name
lib.rs
Err { fn type_of() -> &'static str { "Dice Error" } } // Instruction data pub struct Dice { pub roll_type: u8, pub threshold: u8, pub bet_amount: u32, } impl Sealed for Dice {} impl Pack for Dice { const LEN: usize = 6; fn unpack_from_slice(src: &[u8]) -> Result<Self, ProgramErr...
if bet_amount == 0 { msg!("Inavalid Bet"); return Err(DiceErr::InvalidBet.into()); } let lucky_number:u8 = 20; println!("Result {}", lucky_number); let mut win_amount:u32 = 0; if (1 == roll_type && lucky_number <= threshold) || (2 == roll_type && lucky_number >= threshold) { ...
{ msg!("Not Enough Balance"); return Err(DiceErr::NotEnoughBalance.into()); }
conditional_block
lib.rs
DiceErr { fn type_of() -> &'static str { "Dice Error" } } // Instruction data pub struct Dice { pub roll_type: u8, pub threshold: u8, pub bet_amount: u32, } impl Sealed for Dice {} impl Pack for Dice { const LEN: usize = 6; fn unpack_from_slice(src: &[u8]) -> Result<Self, Progr...
let sysvar_account = next_account_info(accounts_iter)?; let rent = &Rent::from_account_info(sysvar_account)?; if !sysvar::rent::check_id(sysvar_account.key) { msg!("Rent system account is not rent system account"); return Err(ProgramError::InvalidAccountData); } if !rent.is_exempt(pl...
} // The account must be rent exempt, i.e. live forever
random_line_split
lib.rs
{ #[error("Unexpected Roll Mode")] UnexpectedRollMode, #[error("Incrrect Threshold")] IncorrectThreshold, #[error("Incorrect Owner")] IncorrectOwner, #[error("Account Not Rent Exempt")] AccountNotRentExempt, #[error("Account Not Balance Account")] AccountNotBalanceAccount, #...
DiceErr
identifier_name