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
attr.rs
/// SwiftBar only: separate color for dark system theme. If `None`, use `light`. pub(crate) dark: Option<css_color_parser::Color>, } impl From<css_color_parser::Color> for Color { fn from(light: css_color_parser::Color) -> Color { Color { light, dark: None } } } impl FromStr for Color { type ...
s: P) -> Command { Command { params: args.into(), terminal: false, } } } /// Used by `ContentItem::image` and `ContentItem::template_image`. #[derive
(arg
identifier_name
attr.rs
/// SwiftBar only: separate color for dark system theme. If `None`, use `light`. pub(crate) dark: Option<css_color_parser::Color>, } impl From<css_color_parser::Color> for Color { fn from(light: css_color_parser::Color) -> Color { Color { light, dark: None } } } impl FromStr for Color { type ...
type Error = Vec<T>; fn try_from(mut v: Vec<T>) -> Result<Params, Vec<T>> { match v.len() { 1..=6 => Ok(Params { cmd: v.remove(0).to_string(), params: v.into_iter().map(|x| x.to_string()).collect(), }), _ => Err(v), } } } ...
} } impl<T: ToString> TryFrom<Vec<T>> for Params {
random_line_split
smc_samplers.py
indexing:: obj[array([3, 5, 10, 10])] # returns a new instance that contains particles 3, 5 and 10 (twice) """ shared = [] # put here the name of shared attributes def __init__(self, **kwargs): for k, v in kwargs.items(): self.__dict__[k] = v self.contain...
class RandomWalkProposal(object): def __init__(self, x, scale=None, adaptive=True): if adaptive: if scale is None: scale = 2.38 / np.sqrt(x.shape[1]) cov = np.cov(x.T) try: self.L = scale * cholesky(cov, lo...
ield
conditional_block
smc_samplers.py
fancy indexing:: obj[array([3, 5, 10, 10])] # returns a new instance that contains particles 3, 5 and 10 (twice) """ shared = [] # put here the name of shared attributes def __init__(self, **kwargs): for k, v in kwargs.items(): self.__dict__[k] = v self.c...
self.proposal = model.prior if proposal is None else proposal self.model = model def run(self, N=100): """ Parameter --------- N: int number of particles Returns ------- wgts: Weights object The importance weights (wi...
""" def __init__(self, model=None, proposal=None):
random_line_split
smc_samplers.py
self, key, value): self.l[key] = value def copy(self): return cp.deepcopy(self) def copyto(self, src, where=None): """ Same syntax and functionality as numpy.copyto """ for n, _ in enumerate(self.l): if where[n]: self.l[n] = src.l[n]...
_setitem__(
identifier_name
smc_samplers.py
must be copied. src: (N,) `ThetaParticles` object source for each n such that where[n] is True, copy particle n in src into self (at location n) """ for k in self.containers: v = self.__dict__[k] if isinstance(v, np.ndarray): np....
eturn self.model.T
identifier_body
main.go
() { err := godotenv.Load() if err != nil { color.HiRed("[!] Could not load .env file; it might be missing. Add it to your project root.") return } for _, v := range [4]string{ OAuthConsumerKey, OAuthConsumerSecret, OAuthToken, OAuthTokenSecret, } { if os.Getenv(v) == "" { color.HiRed("[!] %s is m...
main
identifier_name
main.go
httpClient := config.Client(oauth1.NoContext, token) client := twitter.NewClient(httpClient) latPtr := flag.Float64("lat", 0.0, "The latitude of the tweet") longPtr := flag.Float64("long", 0.0, "The longitude of the tweet") replyToPtr := flag.Int64("replyto", 0, "If you are replying to a tweet, specify its ID her...
{ err := godotenv.Load() if err != nil { color.HiRed("[!] Could not load .env file; it might be missing. Add it to your project root.") return } for _, v := range [4]string{ OAuthConsumerKey, OAuthConsumerSecret, OAuthToken, OAuthTokenSecret, } { if os.Getenv(v) == "" { color.HiRed("[!] %s is miss...
identifier_body
main.go
list of media files following the format 1,2,3,4. Needs to be an image, video, or GIF. Note that you can either: use 4 images OR 1 video OR 1 GIF per tweet. ") debug := flag.Bool("debug", false, "Specify this to view detailed logs") placeIDPtr := flag.String("placeid", "", "If you have places.json in your folder, sp...
random_line_split
main.go
return } var replyToUsername string if *replyToPtr != 0 { if *debug { color.HiBlack("[debug] user will reply to tweet with id %d", *replyToPtr) color.HiBlack("[debug] fetching tweet to make sure it exists...") } t, _, err := client.Statuses.Show(*replyToPtr, nil) if err != nil { color.HiRed("[!] E...
{ color.HiBlack("[debug] completed upload of all files") }
conditional_block
train.py
f) # img_value=cv2.imread(self.data_path + f) # x[i,] = cv2.resize(img_value,\ # (self.resize_shape[1], self.resize_shape[0]),\ # interpolation=cv2.INTER_AREA) # # x[i,]...
os.makedirs(path)
conditional_block
train.py
50) # parser.add_argument('--batch_size', default = 16) # parser.add_argument('--shape', default = (256,256)) # parser.add_argument('--augument',default = True) # # parser.add_argument('--') # return parser # class DataGenerator(keras.utils.Sequence): # def __init__(self, df, ...
(df): df_copy = df.copy() df_copy['Class'] = df_copy.apply(lambda x : label_concat(x, df.columns[3:].tolist() ), axis=1) train_idx, valid_idx = train_test_split(df_copy.index.values, test_size =0.2, stratify = df_copy['C...
train_split
identifier_name
train.py
50) # parser.add_argument('--batch_size', default = 16) # parser.add_argument('--shape', default = (256,256)) # parser.add_argument('--augument',default = True) # # parser.add_argument('--') # return parser # class DataGenerator(keras.utils.Sequence): # def __init__(self, df, ...
def train_split(df): df_copy = df.copy() df_copy['Class'] = df_copy.apply(lambda x : label_concat(x, df.columns[3:].tolist() ), axis=1) train_idx, valid_idx = train_test_split(df_copy.index.values, test_size =0.2, stra...
df = df[labels] label_list = df[df!=''].keys().values.tolist() return label_list
identifier_body
train.py
50) # parser.add_argument('--batch_size', default = 16) # parser.add_argument('--shape', default = (256,256)) # parser.add_argument('--augument',default = True) # # parser.add_argument('--') # return parser # class DataGenerator(keras.utils.Sequence): # def __init__(self, df,...
# # self.data_path = path +'train_images/' # self.data_path = train_path + '/' # elif self.subset =='test': # # self.data_path = path + 'test_images/' # self.data_path = test_path + '/' # self.on_epoch_end() # def __len__(self): # ...
# if self.subset =='train':
random_line_split
lmerge_ins.py
_i_R CIPOS95=str(ninefive_i_L_start) + ',' + str(ninefive_i_L_end) CIEND95=str(ninefive_i_R_start) + ',' + str(ninefive_i_R_end) return [CIPOS95, CIEND95] def combine_pdfs(BP, c, use_product, weighting_scheme): L = [] R = [] for b_i in c: b = BP[b_i] L.append([b.left.start, b...
sum_L = sum(p_L) sum_R = sum(p_R) p_L = [x/sum_L for x in p_L] p_R = [x/sum_L for x in p_R] [clip_start_L, clip_end_L] = l_bp.trim(p_L) [clip_start_R, clip_end_R] = l_bp.trim(p_R) [ new_start_L, new_end_L ] = [ start_L + clip_start_L, end_L - clip_end_L ] [ new_start_R, new_end_R ] ...
p_R.append(ls.get_p(ls.ls_divide(ls_p, ls_sum_R)))
conditional_block
lmerge_ins.py
(BP, sample_order, v_id, use_product, vcf, vcf_out, include_genotypes): A = BP[0].l.rstrip().split('\t') var = Variant(A,vcf) try: sname = var.get_info('SNAME') var.set_info('SNAME', sname + ':' + var.var_id) except KeyError: pass var.var_id=str(v_id) if use_product: ...
merge_single_bp
identifier_name
lmerge_ins.py
str(new_pos_R) + '[' elif BP0.strands[:2] == '--': ALT = '[' + BP0.right.chrom + ':' + str(new_pos_R) + '[N' else: ALT = '<' + BP0.sv_type + '>' var_list=[ BP0.left.chrom, new_pos_L, str(v_id), 'N', ALT, 0....
v_id+=1 var=merge_single_bp(BP, sample_order, v_id, use_product, vcf, vcf_out, include_genotypes) write_var(var, vcf_out, include_genotypes)
random_line_split
lmerge_ins.py
1]])) var.set_info('PRPOS', ','.join([str(x) for x in p_L])) var.set_info('PREND', ','.join([str(x) for x in p_R])) return var def combine_var_support(var, BP, c, include_genotypes, sample_order): strand_map = {} qual = 0.0 [ SU, PE, SR ] = [0,0,0] s_name_list = [] s1_name_list = [...
BP_l.sort(key=lambda x: x.right.start) BP_l.sort(key=lambda x: x.right.chrom) BP_r = [] BP_max_end_r = -1 BP_chr_r = '' for b in BP_l: if (len(BP_r) == 0) or \ ((b.right.start <= BP_max_end_r) and \ (b.right.chrom == BP_chr_r)): BP_r.append(b) ...
identifier_body
Popup.ts
onselectstart = returnFalse; let btnSets = $('<div class="dg-title-buttons"></div>').appendTo(tb); if (cfg.btnMax) { this.btnMax = $("<b class='dg-btn-max'></b>"); btnSets.append(this.btnMax); this.btnMax.on('click', function () { self.toggle(); }); } if (cfg.btnClose) { this.btnClose = $("<b class='...
$('<div class="row tb-row" />').prependTo(this.boxy).append(tb); } function setDraggable(self) { let tb = self.titleBar; tb.on('mousedown', function (evt) { self.toTop(); if (evt.target.tagName === 'B') return; if (evt.button < 2 && self.state !== "max") { tb.on('mousemove.boxy', function (e) { ...
if (cfg.drag) { setDraggable.call(this, this, cfg); }
random_line_split
Popup.ts
class="dg-title-buttons"></div>').appendTo(tb); if (cfg.btnMax) { this.btnMax = $("<b class='dg-btn-max'></b>"); btnSets.append(this.btnMax); this.btnMax.on('click', function () { self.toggle(); }); } if (cfg.btnClose) { this.btnClose = $("<b class='dg-btn-x'></b>"); btnSets.append(this.btnClose); ...
restore
identifier_name
Popup.ts
onselectstart = returnFalse; let btnSets = $('<div class="dg-title-buttons"></div>').appendTo(tb); if (cfg.btnMax) { this.btnMax = $("<b class='dg-btn-max'></b>"); btnSets.append(this.btnMax); this.btnMax.on('click', function () { self.toggle(); }); } if (cfg.btnClose) { this.btnClose = $("<b class='...
that.destroy.call(that); else{ that.visible = false; that.boxy.css({top: css.top + 40}); that.mask.css({display: 'none'}); } }); return this; } max() { //resize window entity this.boxy.stop(true, true).css({ left: 0, top: 0, width: '100%', height: '100%' }); if (th...
{ let that = this; let css = this.getPosition(); css.opacity = 0; css.top = Math.max(css.top - 40, 0); this.mask.animate({opacity: 0}, 200); this.boxy.stop(true, true).animate(css, 300, function () { if (typeof that.cfg.onClose === 'function') that.cfg.onClose.call(that); if (typeof fn === '...
identifier_body
Popup.ts
onselectstart = returnFalse; let btnSets = $('<div class="dg-title-buttons"></div>').appendTo(tb); if (cfg.btnMax) { this.btnMax = $("<b class='dg-btn-max'></b>"); btnSets.append(this.btnMax); this.btnMax.on('click', function () { self.toggle(); }); } if (cfg.btnClose) { this.btnClose = $("<b class='...
this.mask.css({display: "block", opacity: 1}); let topPx = this.boxy.position().top; //console.warn(this.boxy[0], topPx); this.boxy.css({top: topPx - 20, opacity: 0}).animate({opacity: 1, top: topPx}, 200); this.visible = true; return this; } close(fn?: Function) { let that = this; let css = t...
{ return this.toTop(); }
conditional_block
quasar.ts
receive a publication we are interested in this._groups[topic] = callback; } // Update our ABF with our subscription information, add our negative // information, then update our neighbors with our bloom filters if (Array.isArray(topic)) { topic.forEach(_addTopicToBloomFilter); } else ...
{ reject(new Error('Invalid response received')); }
conditional_block
quasar.ts
log:any; private _protocol:{ [method:string]: (params:any, callback:(...args:any[])=>void)=>void; }; constructor(router, options = {}) { if (!(router instanceof kad.Router)) throw new Error('Invalid router supplied'); this._router = router; this._options = Object.create(Quasar.DEFAULTS); Obj...
(neighbors, params):Promise<any> { var nodeID = this._router._self.nodeID; let _relayToRandomNeighbor = () => { var randNeighbor = this._getRandomOverlayNeighbor(nodeID, params.topic); this._sendPublish(randNeighbor, params); } if (this._options.randomRelay) { _relayToRandomNeighbor(...
_relayPublication
identifier_name
quasar.ts
log:any; private _protocol:{ [method:string]: (params:any, callback:(...args:any[])=>void)=>void; }; constructor(router, options = {}) { if (!(router instanceof kad.Router)) throw new Error('Invalid router supplied'); this._router = router; this._options = Object.create(Quasar.DEFAULTS); Obj...
* @param {Object} options * @param {String} options.key - Use neighbors close to this key (optional) */ publish(topic:string, data:any, options?:{ key?:string }):Promise<any> { let nodeID = this._router._self.nodeID; let limit = kad.constants.ALPHA; let key = options ? (options.key || nodeID) : n...
/** * Publish some data for the given topic * @param {String} topic - The publication identifier * @param {Object} data - Arbitrary publication contents
random_line_split
quasar.ts
:any; private _protocol:{ [method:string]: (params:any, callback:(...args:any[])=>void)=>void; }; constructor(router, options = {})
/** * Publish some data for the given topic * @param {String} topic - The publication identifier * @param {Object} data - Arbitrary publication contents * @param {Object} options * @param {String} options.key - Use neighbors close to this key (optional) */ publish(topic:string, data:any, options...
{ if (!(router instanceof kad.Router)) throw new Error('Invalid router supplied'); this._router = router; this._options = Object.create(Quasar.DEFAULTS); Object.assign(this._options, options); this._protocol = {}; this._seen = new LRUCache(this._options.lruCacheSize); this._log = this._opti...
identifier_body
state.rs
pub image_data: web_sys::ImageData, pub config: shared::Config, pub history: Vec<shared::Config>, pub history_index: usize, pub last_rendered_config: Option<shared::Config>, pub buffer: Vec<u32>, pub ui: crate::ui::UiState, pub hist_canvas: Option<web_sys::HtmlCanvasElement>, pub on_...
if id > self.last_rendered { self.reset_buffer(); self.last_rendered = id; } let mut bright = vec![0_u32; self.config.rendering.width * self.config.rendering.height]; array.copy_to(&mut bright); for i in 0..bright.len() { self.buffer[i] += br...
{ let (worker, busy, queued) = &mut self.workers[worker]; match queued { None => { // log!("Finished a thread"); *busy = false } Some(message) => { // log!("Sending a new config to render"...
conditional_block
state.rs
_rendered: 0, ctx: crate::ui::init(&config).expect("Unable to setup canvas"), image_data: web_sys::ImageData::new_with_sw( config.rendering.width as u32, config.rendering.height as u32, ) .expect("Can't make an imagedata"), buff...
has_state
identifier_name
state.rs
pub image_data: web_sys::ImageData, pub config: shared::Config, pub history: Vec<shared::Config>, pub history_index: usize, pub last_rendered_config: Option<shared::Config>, pub buffer: Vec<u32>, pub ui: crate::ui::UiState, pub hist_canvas: Option<web_sys::HtmlCanvasElement>, pub on_...
pub fn add_worker(&mut self, worker: web_sys::Worker) { self.workers.push((worker, false, None)) } pub fn invalidate_past_renders(&mut self) { self.render_id += 1; self.last_rendered = self.render_id; } pub fn undo(&mut self) -> Result<(), JsValue> { log!("Undo {}...
{ self.buffer = vec![0_u32; self.config.rendering.width * self.config.rendering.height]; self.invalidate_past_renders(); }
identifier_body
state.rs
pub image_data: web_sys::ImageData, pub config: shared::Config, pub history: Vec<shared::Config>, pub history_index: usize, pub last_rendered_config: Option<shared::Config>, pub buffer: Vec<u32>, pub ui: crate::ui::UiState, pub hist_canvas: Option<web_sys::HtmlCanvasElement>, pub on_...
pub fn handle_render( &mut self, worker: usize, id: usize, array: js_sys::Uint32Array, ) -> Result<(), JsValue> { if id < self.last_rendered { let (worker, busy, queued) = &mut self.workers[worker]; match queued { None => { ...
// } }
random_line_split
health.pb.go
HealthCheckRequest) Reset() { *m = HealthCheckRequest{} } func (m *HealthCheckRequest) String() string { return proto.CompactTextString(m) } func (*HealthCheckRequest) ProtoMessage() {} func (*HealthCheckRequest) Descriptor() ([]byte, []int) { return fileDescriptor_65380b3b807a73ad, []int{0} } func (m *Hea...
func (m *HealthCheckRequest) XXX_DiscardUnknown() { xxx_messageInfo_HealthCheckRequest.DiscardUnknown(m) } var xxx_messageInfo_HealthCheckRequest proto.InternalMessageInfo func (m *HealthCheckRequest) GetService() string { if m != nil { return m.Service } return "" } type HealthCheckResponse struct { Status ...
{ return xxx_messageInfo_HealthCheckRequest.Size(m) }
identifier_body
health.pb.go
HealthCheckRequest) Reset() { *m = HealthCheckRequest{} } func (m *HealthCheckRequest) String() string { return proto.CompactTextString(m) } func (*HealthCheckRequest) ProtoMessage() {} func (*HealthCheckRequest) Descriptor() ([]byte, []int) { return fileDescriptor_65380b3b807a73ad, []int{0} } func (m *Hea...
() string { if m != nil { return m.Service } return "" } type HealthCheckResponse struct { Status HealthCheckResponse_ServingStatus `protobuf:"varint,1,opt,name=status,proto3,enum=health.HealthCheckResponse_ServingStatus" json:"status,omitempty"` XXX_NoUnkeyedLiteral struct{} ...
GetService
identifier_name
health.pb.go
*HealthCheckRequest) Reset() { *m = HealthCheckRequest{} } func (m *HealthCheckRequest) String() string { return proto.CompactTextString(m) } func (*HealthCheckRequest) ProtoMessage() {} func (*HealthCheckRequest) Descriptor() ([]byte, []int) { return fileDescriptor_65380b3b807a73ad, []int{0} } func (m *H...
func (m *HealthCheckRequest) GetService() string { if m != nil { return m.Service } return "" } type HealthCheckResponse struct { Status HealthCheckResponse_ServingStatus `protobuf:"varint,1,opt,name=status,proto3,enum=health.HealthCheckResponse_ServingStatus" json:"status,omitempty"` XXX_NoUnkey...
func (m *HealthCheckRequest) XXX_DiscardUnknown() { xxx_messageInfo_HealthCheckRequest.DiscardUnknown(m) } var xxx_messageInfo_HealthCheckRequest proto.InternalMessageInfo
random_line_split
health.pb.go
0xbc, 0xfc, 0x92, 0xc4, 0x92, 0xcc, 0xfc, 0xbc, 0x62, 0x88, 0x2a, 0x25, 0x3d, 0x2e, 0x21, 0x0f, 0xb0, 0x3a, 0xe7, 0x8c, 0xd4, 0xe4, 0xec, 0xa0, 0xd4, 0xc2, 0xd2, 0xd4, 0xe2, 0x12, 0x21, 0x09, 0x2e, 0xf6, 0xe2, 0xd4, 0xa2, 0xb2, 0xcc, 0xe4, 0x54, 0x09, 0x46, 0x05, 0x46, 0x0d, 0xce, 0x20, 0x18, 0x57, 0x69, 0x25, 0x23...
{ return srv.(HealthServer).Ready(ctx, in) }
conditional_block
lib.rs
) -> &OMatrix<R, SS, SS>; /// Get the transpose of the state transition model. fn transition_model_transpose(&self) -> &OMatrix<R, SS, SS>; /// Get the transition noise covariance. fn transition_noise_covariance(&self) -> &OMatrix<R, SS, SS>; /// Predict new state from old state. fn predict(&sel...
( &self, prior: &StateAndCovariance<R, SS>, observation: &OVector<R, OS>, covariance_method: CoverianceUpdateMethod, ) -> Result<StateAndCovariance<R, SS>, Error> { // Use conventional (e.g. wikipedia) names for these variables let h = self.observation_matrix(); ...
update
identifier_name
lib.rs
R: RealField, SS: DimName, OS: DimName, { transition_model: &'a dyn TransitionModelLinearNoControl<R, SS>, observation_matrix: &'a dyn ObservationModelLinear<R, SS, OS>, } impl<'a, R, SS, OS> KalmanFilterNoControl<'a, R, SS, OS> where R: RealField, SS: DimName, OS: DimName + DimMin<OS, ...
Ok(StateAndCovariance::new(state, covariance)) } }
random_line_split
10162017.js
"Object Added" } if (Message==''){ sMessage = "Hover over any object to continue..." } jq('<div class="spy-BoldPop ignrPopUp" id="spyAlert" style="font-family:sans-serif;margin: 0px auto;width: 240px;height: 90px;box-shadow: 1px 2px 8px 2px rgba(0,0,0,0.25);border-radius: 10px;border: 1px solid #888;z...
{ if (element.id.indexOf('-') > -1) { selector += '[id = "' + element.id + '"]'; } else { selector += '#' + element.id; } path.unshift(selector); break; }
conditional_block
10162017.js
(); //jq("#ATOMspyPopUpDiv").attr('obj-prop') //showAlert("Message","Object Added to Repository"); }); //Attach Event listner on in and out from a given element if (document.addEventListener) { document.addEventListener("mouseover", spyMouseOver, true); document.addEventListene...
() { //jq(".ignrPopUp").detach(); jq("#ATOMspyPopUpDiv").hide(); } function spyMouseOut(e) { var element = e.target; e.stopPropagation(); //jq("#ATOMspyPopUpDiv").hide(); element.style.outline = '' } function getObjectType(object) { var title = jq(object).get(0).tagName.toLowerCase()...
removeSpyPanel
identifier_name
10162017.js
//jq("#ATOMspyPopUpDiv").attr('obj-prop') //showAlert("Message","Object Added to Repository"); }); //Attach Event listner on in and out from a given element if (document.addEventListener) { document.addEventListener("mouseover", spyMouseOver, true); document.addEventListener("m...
function spyMouseOut(e) { var element = e.target; e.stopPropagation(); //jq("#ATOMspyPopUpDiv").hide(); element.style.outline = '' } function getObjectType(object) { var title = jq(object).get(0).tagName.toLowerCase(); switch (title) { case "a": return ('Link'); ...
{ //jq(".ignrPopUp").detach(); jq("#ATOMspyPopUpDiv").hide(); }
identifier_body
10162017.js
(); //jq("#ATOMspyPopUpDiv").attr('obj-prop') //showAlert("Message","Object Added to Repository"); }); //Attach Event listner on in and out from a given element if (document.addEventListener) { document.addEventListener("mouseover", spyMouseOver, true); document.addEventListene...
function getObjectType(object) { var title = jq(object).get(0).tagName.toLowerCase(); switch (title) { case "a": return ('Link'); break; case "button": return ('Button'); break; case "caption": case "table": case "caption...
}
random_line_split
utils.ts
('focus', focusHandler, true); // } } /** * Sets the selected item in the dropdown menu * of available loadedListItems. * * @param {object} list * @param {object} item */ export function scrollActiveOption(list, item) { let y, height_menu, height_item, scroll, scroll_top, scroll_bottom; if (item) { ...
docElem = doc.documentElement; win = getWindow(doc); return { top: box.top + win.pageYOffset - docElem.clientTop, left: box.left + win.pageXOffset - docElem.clientLeft }; } function getWindow(elem) { return elem != null && elem === elem.window ? elem : elem.nodeType === 9 && elem...
{ return; }
conditional_block
utils.ts
); } else { output3.push(item); } } output = output2.concat(output3); } } else { output = [].concat(items); } if (sort) { output = output.sort((A, B) => toString(getLabel(A)).localeCompare(toString(getLabel...
{ // Remove duplicates, remove all except '' this.cache = this.cache.filter(cacheItem => cacheItem.q !== query && cacheItem.q === ''); this.cache.unshift({q: query, v: value, t: (new Date().getTime())}) }
identifier_body
utils.ts
/[-\/\\^$*+?.()|[\]{}]/g; // cache escape + match String const sEscapeMatch = '\\$&'; /** * Escape special chars * @param string * @returns {string} */ function escapeCharacters(string: string) { return string.replace(rEscapableCharacters, sEscapeMatch); } /** * Filter items by comparison label (=getLabel(...
for (i = 0; i < paths.length; ++i) { if (current[paths[i]] == undefined) { return undefined;
random_line_split
utils.ts
.removeEventListener('focus', focusHandler, true); // } } /** * Sets the selected item in the dropdown menu * of available loadedListItems. * * @param {object} list * @param {object} item */ export function scrollActiveOption(list, item) { let y, height_menu, height_item, scroll, scroll_top, scroll_botto...
(groups) { for (let k in groups) { if (groups.hasOwnProperty(k) && groups[k].length) { return false; } } return true; } /** * Find array intersections * Equal of lodash _.intersection + getter + invert * * @param {any[]} xArr * @param {any[]} yArr * @param {Function} gette...
groupsIsEmpty
identifier_name
tarea8.py
""" Grafica una muestra normal bivriada de tamaño n con parámetros m y sigma usando el metodo de MH con kerneles híbridos de parametro w1, junto con los contornos de nivel de la densidad correspondiente. Input: array, array, float, int (media, matriz de covarianza, probabiidad de to...
m,sigma,w1,n):
identifier_name
tarea8.py
area = 50*np.ones(n) plt.scatter(x, y, s=area, c=colors, alpha=0.8) grafBivariada(m,sigma) plt.savefig('bivariadaMH'+str(ro)+'-'+str(n)+'.png') plt.title('Muestra de tamano '+str(n)+ ' con rho = '+ str(ro)) plt.show() def densidad2(a,l,T,b,c): n=len(T) r1=1.0 for t in T: ...
lp)/(a*l)) + (ap-a)*log(r1)- lp*sap + l*sa c=min(0,aux) return ap,lp,exp(c) else: ap=a + normal(0,sigma) lp= l suma=0 for t in T: suma = suma + log(t) sap=0 for t in T: sap = sap + t**ap sa=0 ...
log((ap*
conditional_block
tarea8.py
) #rho sap=0.0 for t in T: sap = sap + t**ap sa=0.0 for t in T: sa = sa + t**a r1=1.0 for t in T: r1= r1*t aux = n*log((ap*lp)/(a*l)) + (ap-a)*log(r1)- lp*sap + l*sa c=min(0,aux) ...
s(n) plt.scatter(x, y, s=area, c=colors, alpha=0.8) plt.show() if __name__ == "__main__": """ 1. Aplique el algoritmo de Metropolis-Hastings considerando c
identifier_body
tarea8.py
area = 50*np.ones(n) plt.scatter(x, y, s=area, c=colors, alpha=0.8) grafBivariada(m,sigma) plt.savefig('bivariadaMH'+str(ro)+'-'+str(n)+'.png') plt.title('Muestra de tamano '+str(n)+ ' con rho = '+ str(ro)) plt.show() def densidad2(a,l,T,b,c): n=len(T) r1=1.0 for t in T: ...
Propuesta 1: λp|α,t ̄∼ Gamaα + n , b +Xni=1tαi! Propuesta 2: αp|λ,t ̄ ∼ Gama (n + 1 , −log(b) − log(r1) + c) Propuesta 3: αp ∼ exp(c) y λp|αp ∼ Gama(αp, b) Propuesta 4 (RWMH): αp = α + , con ∼ N(0, σ) y dejando λ fijo. con distribuciones a priori datos ...
la distribución posterior f(α, λ|t ̄) ∝ f(t ̄|α, λ)f(α, λ), considerando las siguientes propuestas:
random_line_split
GraphAlgo.py
except Exception as e: print(e) print("load failed") flag = False finally: return flag def save_to_json(self, file_name: str) -> bool: """ Saves the graph in JSON format to a file @param file_name: The path to the out file ...
""" Loads a graph from a json file. @param file_name: The path to the json file @returns: True if the loading was successful, False o.w. """ flag = True try: with open(file_name, 'r') as jsonFile: load = json.load(jsonFile) grap...
identifier_body
GraphAlgo.py
next_node.key is not src: # Backtrack from dest to src ans.append(node_map.get(next_node.key)) next_node = node_map.get(next_node.key) if self._graph.get_node(src) not in ans: ans.append(self._graph.get_node(src)) ans.reverse() # Inserted from return ans ...
__repr__
identifier_name
GraphAlgo.py
def save_to_json(self, file_name: str) -> bool: """ Saves the graph in JSON format to a file @param file_name: The path to the out file @return: True if the save was successful, False o.w. """ flag = True with open(file_name, "w") as jsonFile: try:...
ans.reverse() # Inserted from return ans def reset_tags(self): for key in self._graph.get_all_v().keys(): node = self.get_graph().get_node(key) node.tag = 0 def set_weights_infinity(self): for key in self._graph.get_all_v().keys(): node = ...
ans.append(self._graph.get_node(src))
conditional_block
GraphAlgo.py
def save_to_json(self, file_name: str) -> bool: """ Saves the graph in JSON format to a file @param file_name: The path to the out file @return: True if the save was successful, False o.w. """ flag = True with open(file_name, "w") as jsonFile: try:...
if self._graph is None or self._graph.get_node(id1) is None: return [] self.reset_tags() # This method executes a BFS and tag nodes so reset_tags() must be called. # Traverse the original graph, from node id1, and tag all reachable nodes ans = [] src = id1 # alias...
* Notes: If the graph is None or id1 is not in the graph, the function should return an empty list [] @param id1: The node id @return: The list of nodes in the SCC """
random_line_split
cvssV3.controller.js
Factory, PlotService, $sce, $filter, $log) { var vm = this; // these variables hold the Final computed scores that will be displayed // on the page, the Model if you will vm.showAlert = false; vm.impactScore = 'NA'; vm.exploitScore = 'NA'; vm.baseScore = 'NA'...
/** * Only used during Testing to test the calculations. This function can be activated via * some button click on a page using ng-click */ vm.testScores = function() { vm.testData = BaseCalcService.testCombs(); }; /** * Utilizes a filte...
{ vm.impactScore = 'NA'; vm.exploitScore = 'NA'; vm.baseScore = 'NA'; vm.temporalScore = 'NA'; vm.environScore = 'NA'; vm.modImpactScore = 'NA'; vm.overallScore = 'NA'; vm.cvssString = $sce.trustAsHtml('NA'); }
identifier_body
cvssV3.controller.js
Factory, PlotService, $sce, $filter, $log) { var vm = this; // these variables hold the Final computed scores that will be displayed // on the page, the Model if you will vm.showAlert = false; vm.impactScore = 'NA'; vm.exploitScore = 'NA'; vm.baseScore = 'NA'...
() { console.log('setScore()'); // do we have all the Base selections? if (!(vm.baseSelect.isReady())) { vm.showAlert = true; // show alert message stating Base selections must be made return; } // We are ready to com...
setScore
identifier_name
cvssV3.controller.js
vm.temporalData = TemporalDataFactory.temporalData; vm.temporalSelect = TemporalDataFactory.temporalSelect; vm.environData = EnvironDataFactory.environData; vm.environSelect = EnvironDataFactory.environSelect; // Scope functions vm.setScore = setScore; vm.changeBase = ...
TemporalDataFactory.setValues(vectorStr); EnvironDataFactory.setValues(vectorStr); vm.setScore(); // call 'main' function to compute scores and display console.log('baseSelect', vm.baseSelect);
random_line_split
svg.go
func New(sp *svg.SVG, width, height int, font string, fontsize int, background color.RGBA) *SvgGraphics { if font == "" { font = "Helvetica" } if fontsize == 0 { fontsize = 12 } s := SvgGraphics{svg: sp, w: width, h: height, font: font, fs: fontsize, bg: background} return &s } // AddTo returns a new ImageGr...
random_line_split
svg.go
.Font) (fw float32, fh int, mono bool) { if font.Name == "" { font.Name = sg.font } fh = sg.fontheight(font) switch font.Name { case "Arial": fw, mono = 0.5*float32(fh), false case "Helvetica": fw, mono = 0.5*float32(fh), false case "Times": fw, mono = 0.51*float32(fh), false case "Courier": fw, mono...
const n = 5 // default size a := int(n*f + 0.5) // standard b := int(n/2*f + 0.5) // smaller c := int(1.155*n*f + 0.5) // triangel long sist d := int(0.577*n*f + 0.5) // triangle short dist e := int(0.866*n*f + 0.5) // diagonal sg.svg.Gstyle(fmt.Sprintf("%s; stroke-width: %d", st, lw))...
{ lw = style.LineWidth }
conditional_block
svg.go
.Font) (fw float32, fh int, mono bool) { if font.Name == "" { font.Name = sg.font } fh = sg.fontheight(font) switch font.Name { case "Arial": fw, mono = 0.5*float32(fh), false case "Helvetica": fw, mono = 0.5*float32(fh), false case "Times": fw, mono = 0.51*float32(fh), false case "Courier": fw, mono...
(x, y int, t string, align string, rot int, f chart.Font) { if len(align) == 1 { align = "c" + align } _, fh, _ := sg.FontMetrics(f) trans := "" if rot != 0 { trans = fmt.Sprintf("transform=\"rotate(%d %d %d)\"", -rot, x, y) } // Hack because baseline alignments in svg often broken switch align[0] { case...
Text
identifier_name
svg.go
.Font) (fw float32, fh int, mono bool) { if font.Name == "" { font.Name = sg.font } fh = sg.fontheight(font) switch font.Name { case "Arial": fw, mono = 0.5*float32(fh), false case "Helvetica": fw, mono = 0.5*float32(fh), false case "Times": fw, mono = 0.51*float32(fh), false case "Courier": fw, mono...
func (sg *SvgGraphics) Scatter(points []chart.EPoint, plotstyle chart.PlotStyle, style chart.Style) { chart.GenericScatter(sg, points, plotstyle, style) /*********************************************** // First pass: Error bars ebs := style ebs.LineColor, ebs.LineWidth, ebs.Line
{ lw := style.LineWidth if style.LineColor != nil { s = fmt.Sprintf("stroke:%s; ", hexcol(style.LineColor)) } s += fmt.Sprintf("stroke-width: %d; fill:none; ", lw) s += fmt.Sprintf("opacity: %s; ", alpha(style.LineColor)) if style.LineStyle != chart.SolidLine { s += fmt.Sprintf("stroke-dasharray:") for _, d...
identifier_body
transport_test.go
Option { return func(options *transportOptions) { options.jitter = func(n int64) int64 { return n } } } type peerExpectation struct { id string subscribers []string } func createPeerIdentifierMap(ids []string) map[string]peer.Identifier { pids := make(map[string]peer.Identifier, len(ids)) for _,...
(t *testing.T) { type testStruct struct { msg string // identifiers defines all the Identifiers that will be used in // the actions up from so they can be generated and passed as deps identifiers []string // subscriberDefs defines all the Subscribers that will be used in // the actions up from so they ca...
TestTransport
identifier_name
transport_test.go
string{"i1"}, subscriberDefs: []SubscriberDefinition{ {ID: "s1"}, }, actions: []TransportAction{ RetainAction{InputIdentifierID: "i1", InputSubscriberID: "s1", ExpectedPeerID: "i1"}, ReleaseAction{InputIdentifierID: "i1", InputSubscriberID: "s1"}, }, }, { msg: "three retains", ...
{ t.Run(tt.msg, func(t *testing.T) { mockCtrl := gomock.NewController(t) defer mockCtrl.Finish() transport := NewTransport() defer transport.Stop() deps := TransportDeps{ PeerIdentifiers: createPeerIdentifierMap(tt.identifiers), Subscribers: CreateSubscriberMap(mockCtrl, tt.subscriberDefs...
conditional_block
transport_test.go
Option { return func(options *transportOptions) { options.jitter = func(n int64) int64 { return n } } } type peerExpectation struct { id string subscribers []string } func createPeerIdentifierMap(ids []string) map[string]peer.Identifier
func TestTransport(t *testing.T) { type testStruct struct { msg string // identifiers defines all the Identifiers that will be used in // the actions up from so they can be generated and passed as deps identifiers []string // subscriberDefs defines all the Subscribers that will be used in // the action...
{ pids := make(map[string]peer.Identifier, len(ids)) for _, id := range ids { pids[id] = &testIdentifier{id} } return pids }
identifier_body
transport_test.go
Option { return func(options *transportOptions) { options.jitter = func(n int64) int64 { return n } } } type peerExpectation struct { id string subscribers []string } func createPeerIdentifierMap(ids []string) map[string]peer.Identifier { pids := make(map[string]peer.Identifier, len(ids)) for _,...
InputSubscriberID: "s1", ExpectedErrType: peer.ErrTransportHasNoReferenceToPeer{}, }, }, }, { msg: "one retains, one release (from different subscriber)", identifiers: []string{"i1"}, subscriberDefs: []SubscriberDefinition{ {ID: "s1"}, {ID: "s2"}, }, actions: []Tran...
ReleaseAction{ InputIdentifierID: "i1",
random_line_split
data_feature_engineering.py
drop_index): # labels为空直接返回无需操作 if type(labels) != str: return np.NaN # 确保不要出现连续的标签以第一个出现标签的文本为准 try: if drop_index > 1 and type(group_datas.loc[drop_index - 1, 'labels']) == str: return np....
identifier_name
data_feature_engineering.py
标签文本则保留下文中有对应关键词出现的文本 if len(datas.loc[index]['labels'].split(',')) >= 2: labels = labels.split(',') # 将下文四行文本连接 text = datas.loc[index:(index + 4), 'text'].values.sum() new_labels = [] for label in labels: i...
# 找到并将多标签文本单独拎出来
conditional_block
data_feature_engineering.py
'count_pos_word']], on=['id'], how='left') # 连接 针对原始训练文本处理 # datas['labels'].fillna("remove", inplace=True) if fit: datas['solve'].fillna(-1, inplace=True) datas_labels = datas.dropna(subset=['labels']) datas_labels['index'] = datas_labels.index.values ...
else: error_labels_index = list(datas.dropna(subset=['labels']).index.values) labels_keywords = pd.read_excel('../test_data/label_keywords.xlsx') mark_words = ['没问题', '不客气', '仅限', '有的', '是的', '好的', '可以', '不了', '不到', '谢谢', '对的', '没空', '不错', '没车', '...
dex index = index - 1 index = indexs + 1 while end_index == -1.0: if datas.iloc[index].solve != -1.0: end_index = index index = index + 1 text = '' for i in range(start_index, end_index + 1): ...
identifier_body
data_feature_engineering.py
}) id_count_words.columns = ['count_pos_word'] id_count_words.reset_index(inplace=True) id_count_words = pd.DataFrame(id_count_words) datas = pd.merge(datas, id_count_words[['id', 'count_pos_word']], on=['id'], how='left') # 连接 针对原始训练文本处理 # datas['labels'].fillna("remo...
# 以文本id为维度, 获取文本中出了几次 正向词
random_line_split
Menu.ts
OMBlock"; import { Renderer as LabelRenderer } from "./Renderers/Controls/Label"; /** Mouse hover timeout after which to show/hide sub menu */ const HOVER_TIMEOUT = 200; /** Current hover timeout ID */ var _hoverTimer: number | undefined; /** Item height, in pixels, of one menu item; used for calculating whether the...
LabelRenderer.renderInto(a, option.icon, iw, option.label); if (hasIcon) a.style.paddingLeft = ".5rem"; // render far side icon if (option.sideIcon) { var r = document.createElement("span"); r.className = "bidi_floa...
{ // create a text option, add click handler var a = document.createElement("a"); a.className = "dropdown-item"; a.href = "#"; if (option.disabled) { a.className += " disabled"; a.style.cursor = "defa...
conditional_block
Menu.ts
OMBlock"; import { Renderer as LabelRenderer } from "./Renderers/Controls/Label"; /** Mouse hover timeout after which to show/hide sub menu */ const HOVER_TIMEOUT = 200; /** Current hover timeout ID */ var _hoverTimer: number | undefined; /** Item height, in pixels, of one menu item; used for calculating whether the...
(options: Menu.Option[] = []) { super(); this.options = options; // create UL node var menu = document.createElement("ul"); menu.style.cssFloat = "none"; menu.style.position = "static"; menu.style.boxShadow = "none"; menu.style.margin = "0"; menu....
constructor
identifier_name
Menu.ts
OMBlock"; import { Renderer as LabelRenderer } from "./Renderers/Controls/Label"; /** Mouse hover timeout after which to show/hide sub menu */ const HOVER_TIMEOUT = 200; /** Current hover timeout ID */ var _hoverTimer: number | undefined; /** Item height, in pixels, of one menu item; used for calculating whether the...
super(); this.options = options; // create UL node var menu = document.createElement("ul"); menu.style.cssFloat = "none"; menu.style.position = "static"; menu.style.boxShadow = "none"; menu.style.margin = "0"; menu.className = "dropdown-menu show"...
constructor(options: Menu.Option[] = []) {
random_line_split
Menu.ts
OMBlock"; import { Renderer as LabelRenderer } from "./Renderers/Controls/Label"; /** Mouse hover timeout after which to show/hide sub menu */ const HOVER_TIMEOUT = 200; /** Current hover timeout ID */ var _hoverTimer: number | undefined; /** Item height, in pixels, of one menu item; used for calculating whether the...
private _addLinkHoverHandler(elt: HTMLAnchorElement, i: number) { var option = this.options[i]; elt.onmouseover = () => { // clear timer to show/hide (other) sub menu if (_hoverTimer) { window.clearTimeout(_hoverTimer); _hoverTimer = undefine...
{ var option = this.options[i]; elt.onclick = event => { event.preventDefault(); if (this._isBase) Screen.remove(this); this._resolver(option.key || (i + 1)); } }
identifier_body
wallpaper.rs
we need to adjust them */ map_window_rect(wallpaper, wnd).unwrap(); let prev_parent = SetParent(wnd, wallpaper); if prev_parent.is_null() { panic!("SetParent failed, GetLastError says: '{}'", GetLastError()); } ShowWindow(wnd, SW_SHOW); return true; } unsafe fn remove_window_from_wa...
{ break; }
conditional_block
wallpaper.rs
fn to_wide(s: &str) -> Vec<u16> { OsStr::new(s).encode_wide().chain(once(0)).collect() } pub fn get_window_name(hwnd: HWND) -> String { use winapi::um::winuser::{GetWindowTextLengthW, GetWindowTextW}; if hwnd.is_null() { panic!("Invalid HWND"); } let text = unsafe { let text_len...
{ use winapi::um::winuser::FindWindowW; unsafe { FindWindowW(to_wide(class).as_ptr(), null_mut()) } }
identifier_body
wallpaper.rs
shell_class: to_wide("SHELLDLL_DefView"), worker_class: to_wide("WorkerW"), worker: null_mut(), parent: null_mut(), }; SetLastError(0); EnumWindows(Some(find_worker), &mut user_data as *mut UserData as LPARAM); if GetLastError() != 0 { panic!("EnumWindows failed,...
let wnd_class = { let wnd_class: &mut [u16] = &mut [0; 512]; GetClassNameW(wnd, wnd_class.as_mut_ptr(), wnd_class.len() as i32 - 1); OsString::from_wide(&wnd_class[..wnd_class.iter().position(|&c| c == 0).unwrap()]) }; if wallpaper == wnd || wnd_class == "Shell_TrayWnd" { ep...
WS_EX_DLGMODALFRAME, WS_EX_COMPOSITED, WS_EX_WINDOWEDGE, WS_EX_CLIENTEDGE, WS_EX_LAYERED, WS_EX_STATICEDGE, WS_EX_TOOLWINDOW, WS_EX_APPWINDOW, };
random_line_split
wallpaper.rs
.worker.is_null() { eprintln!("W: couldn't spawn WorkerW window, trying old method"); SendMessageW(progman, 0x052C, 0, 0); SetLastError(0); EnumWindows(Some(find_worker), &mut user_data as *mut UserData as LPARAM); if GetLastError() != 0 { ...
enum_windows
identifier_name
tile.rs
-> Color { match name.to_lowercase().as_str() { "ground" => GROUND, "yellow" => YELLOW, "green" => GREEN, "russet" => RUSSET, "grey" => GREY, "brown" => BROWN, "red" => RED, "blue" => BLUE, ...
} impl TileSpec for TileDefinition { fn paths(&self) -> Vec<Path> { self.paths.clone() } fn cities(&self) -> Vec<City> { self.cities.clone() } fn stops(&self) -> Vec<Stop> { self.stops.clone() } fn is_lawson(&self) -> bool { self.is_lawson } fn color(&self) -> colors::Color { colors::GROUND } f...
TileDefinition { name: "NoName".to_string(), paths: vec![], cities: vec![], stops: vec![], is_lawson: false, text: vec![], } }
identifier_body
tile.rs
::new(), text: HashMap::new(), definition: None, } } } impl TileSpec for Tile { fn color(&self) -> colors::Color { colors::name_to_color(&self.color) } /// The number of the tile, should be the first text specified fn name(&self) -> &str { self.text....
errainType
identifier_name
tile.rs
//! * `C`: center of hexagon //! //! ![Coordinate system](../../../../axes.svg) extern crate nalgebra as na; extern crate serde_yaml; use std::collections::HashMap; use std::f64::consts::PI; use std::fs; use std::path::PathBuf; use std::fs::File; use std::process; /// Standard colors that can be used pub mod colors...
random_line_split
noxAlarmProcess.py
import EmailAlarmAlert from utils.sms import SmsAlarmAlert from web import create_app from web.models import DBLog """ import socket to thread gateway """ from nox_alarm import zmq_socket_config """ UniPi IO config file """ UNIPI_IO_CONFIG = join(conf_path, 'software', 'nox_...
nt = 'stop' logger.info('state is %s' % (event)) self.push_socket_event(event) color = NoxAlarm.colors[NoxAlarm.events.index(event)] self.make_DBLog("event", event, color) def detection(self): event = 'detection' logger.info('state is %s' % (event)) self.push...
eve
identifier_name
noxAlarmProcess.py
s import EmailAlarmAlert from utils.sms import SmsAlarmAlert from web import create_app from web.models import DBLog """ import socket to thread gateway """ from nox_alarm import zmq_socket_config """ UniPi IO config file """ UNIPI_IO_CONFIG = join(conf_path, 'software', 'nox...
signal.signal(signal.SIGTERM, self.exit_from_signals) # Supervisor Exit code (15) self.init_socket() self.init_config() self.init_statemachine() self.init_state() # Read inputs and Set state after init def __str__(self): out = '' out ...
# KeyboardInterrupt (SIGINT) managed directly in main loop
random_line_split
noxAlarmProcess.py
. le socket est passé en paramètre à l'init. Un programme externe (appli web) appel la fonction push_socket_state() à intervalle régulier pour connaitre l'état de la machine (on, off, etc). """ states = ['init' , 'off' , 'on' , 'alert' , 'was_alert' ] colors = ['info' , 'suc...
alue == 0): self.any_to_off() def receive_r
conditional_block
noxAlarmProcess.py
try: # Socket SUB_COMMAND Receive Commands (start stop) from Flask (ThreadExtAlarm) self.SUB_COMMAND = context.socket(zmq.SUB) self.SUB_COMMAND.connect ("tcp://localhost:%s" % zmq_socket_config.port_socket_noxalarm_command) self.SUB_COMMAND.setsockopt_string(zmq.SUBSCRIB...
est is received and process it Request can be Command (start, stop) Request can be "Status update" requested by web app """ try: payload = self.SUB_COMMAND.recv_string(flags=zmq.NOBLOCK) topic, command = payload.split() if (topic == zmq_socket_config...
identifier_body
account_transform.rs
{ TypedDataField::from_path(bytes_to_path(b"stake")) } /// Account public key field. pub fn field_public_key() -> TypedDataField<ed25519_dalek::PublicKey> { TypedDataField::from_path(bytes_to_path(b"public_key")) } /// Field for a `SendInfo` stored in the sender's data. pub fn field_send(send: Hash<SendInfo>...
let recipient: HashCode = get_arg(&action.args, 0)?; let send_amount: u128 = get_arg(&action.args, 1)?; let initialize_spec: Option<Hash<Vec<u8>>> = get_arg(&action.args, 2)?; let message: Vec<u8> = get_arg(&action.args, 3)?; verify_signature_argument(at.this_account, action, 4)...
{ bail!("send can't initialize an account"); }
conditional_block
account_transform.rs
pub fn from_path(path: HexPath) -> TypedDataField<T> { TypedDataField { path, phantom: PhantomData, } } } /// Account balance field. pub fn field_balance() -> TypedDataField<u128> { TypedDataField::from_path(bytes_to_path(b"balance")) } /// Account stake field. pub ...
impl<T> TypedDataField<T> { /// Creates a `TypedDataField` given a path.
random_line_split
account_transform.rs
{ TypedDataField::from_path(bytes_to_path(b"stake")) } /// Account public key field. pub fn field_public_key() -> TypedDataField<ed25519_dalek::PublicKey> { TypedDataField::from_path(bytes_to_path(b"public_key")) } /// Field for a `SendInfo` stored in the sender's data. pub fn field_send(send: Hash<SendInfo>...
/// A context providing operations related to transforming an account (e.g. /// running actions). pub struct AccountTransform<'a, HL: HashLookup> { /// The `HashLookup` used to look up previous account data. pub hl: &'a HL, /// Whether this account is initializing. pub is_initializing: bool, /// T...
{ let mut path = bytes_to_path(b"received"); path.0.extend(&bytes_to_path(&send.code).0); TypedDataField::from_path(path) }
identifier_body
account_transform.rs
> { TypedDataField::from_path(bytes_to_path(b"stake")) } /// Account public key field. pub fn field_public_key() -> TypedDataField<ed25519_dalek::PublicKey> { TypedDataField::from_path(bytes_to_path(b"public_key")) } /// Field for a `SendInfo` stored in the sender's data. pub fn field_send(send: Hash<SendInfo...
<'a, HL: HashLookup> { /// The `HashLookup` used to look up previous account data. pub hl: &'a HL, /// Whether this account is initializing. pub is_initializing: bool, /// The account being transformed. pub this_account: HashCode, /// The hash code of the last main block. pub last_main: ...
AccountTransform
identifier_name
runsex_final_VIDEO_Aug2018.py
(pos_ver, pos_hor, img, lado): #if verbose: print 'Radius %i' % radius counts=np.sum(img[pos_ver : pos_ver + lado, pos_hor : pos_hor + lado]) numpix=lado**2 return counts,numpix def get_error_model(img,seg,apmin,apmax,numap): hdufits_ima = fits.open(img) imag_data = hdufits_ima[0].data ...
get_flux
identifier_name
runsex_final_VIDEO_Aug2018.py
empty_ap=np.array(empty_ap) #plt.hist(empty_ap,50) #plt.savefig(image+'_hist_'+str(lado)+'.png') #plt.close('all') empty_ap2=empty_ap[np.where((empty_ap<(np.mean(empty_ap)+3*np.std(empty_ap))) & (empty_ap>(np.mean(empty_ap)-3*np.std(empty_ap))))] return (np.median(empty_ap2),np.mean(empty_...
counts,npix=get_flux(random_center[0], random_center[1], imag_data, int(lado)) empty_ap.append(counts) n += 1 matrix_used[random_center[0]:random_center[0]+lado, random_center[1]:random_center[1] + lado ]=22
conditional_block
runsex_final_VIDEO_Aug2018.py
00.0,33000.0,35000.0,34000.0,34000.0] SAT=np.array(SAT) SAT=SAT*0.9 ################################################################### #se crea un archivo que contiene informacion de cada imagen, como el dia juliano, el zp y el error en el zp. arch2=open("../stat/datos_cat_"+field+"_"+filt+".txt","w") arch3=open("../...
random_line_split
runsex_final_VIDEO_Aug2018.py
random_center = np.random.random_integers(350 ,np.amin(np.array([ver_max,hor_max]))-350, 2) #segm_mask = (segm_data > 0) if (all((~segm_mask[random_center[0]:random_center[0]+lado, random_center[1]:random_center[1] + lado]).flat)) and (np.sum(matrix_used[random_center[0]:random_center[0]+lado, r...
hdufits_ima = fits.open(image) imag_data = hdufits_ima[0].data ver_max,hor_max = imag_data.shape hdufits_seg = fits.open(seg) segm_data = hdufits_seg[0].data filtered_segm_data=ndimage.gaussian_filter(segm_data, 2) segm_mask = (filtered_segm_data > 0) #segm_mask = (segm_data > 0) n...
identifier_body
github.go
Assignees(ctx context.Context, repo repository, newPR scm.NewPullRequest, createdPR *github.PullRequest) error { if len(newPR.Assignees) == 0 { return nil } _, _, err := retry(ctx, func() (*github.Issue, *github.Response, error) { return g.ghClient.Issues.AddAssignees(ctx, repo.ownerName, repo.name, createdPR.Ge...
{ return err }
conditional_block
github.go
([]*github.Repository, *github.Response, error) { return g.ghClient.Repositories.List(ctx, user, &github.RepositoryListOptions{ ListOptions: github.ListOptions{ Page: i, PerPage: 100, }, }) }) if err != nil { return nil, err } repos = append(repos, rr...) if len(rr) != 100 { ...
GetOpenPullRequest
identifier_name
github.go
log.Debug("Skipping repository since it's a fork") continue } if g.checkPermissions { switch { case !permissions["pull"]: log.Debug("Skipping repository since the token does not have pull permissions") continue case !g.Fork && !g.ReadOnly && !permissions["push"]: log.Debug("Skipping repo...
repos = append(repos, newRepo) } return repos, nil } func (g *Github) getRepositories(ctx context.Context) ([]*github.Repository, error) { allRepos := []*github.Repository{} for _, org := range g.Organizations { repos, err := g.getOrganizationRepositories(ctx, org) if err != nil { return nil, errors.Wra...
if err != nil { return nil, err }
random_line_split
github.go
*github.Response, error) { return g.ghClient.Issues.AddAssignees(ctx, repo.ownerName, repo.name, createdPR.GetNumber(), newPR.Assignees) }) return err } func (g *Github) addLabels(ctx context.Context, repo repository, newPR scm.NewPullRequest, createdPR *github.PullRequest) error { if len(newPR.Labels) == 0 { ...
{ pr := pullReq.(pullRequest) g.modLock() defer g.modUnlock() _, _, err := retry(ctx, func() (*github.PullRequest, *github.Response, error) { return g.ghClient.PullRequests.Edit(ctx, pr.ownerName, pr.repoName, pr.number, &github.PullRequest{ State: &[]string{"closed"}[0], }) }) if err != nil { return e...
identifier_body
server.rs
::error::ErrorExt; use mz_ore::halt; use mz_ore::metrics::MetricsRegistry; use mz_ore::tracing::TracingHandle; use mz_persist_client::cache::PersistClientCache; use mz_service::client::{GenericClient, Partitionable, Partitioned}; use mz_service::local::LocalClient; use timely::communication::initialize::WorkerGuards; u...
async fn build_timely( user_worker_config: Worker, config: TimelyConfig, epoch: ClusterStartupEpoch, persist_clients: Arc<PersistClientCache>, tracing_handle: Arc<TracingHandle>, tokio_executor: Handle, ) -> Result<TimelyContainer<C, R, Worker::Activatable>, Error...
worker: worker_config, } }
random_line_split
server.rs
::error::ErrorExt; use mz_ore::halt; use mz_ore::metrics::MetricsRegistry; use mz_ore::tracing::TracingHandle; use mz_persist_client::cache::PersistClientCache; use mz_service::client::{GenericClient, Partitionable, Partitioned}; use mz_service::local::LocalClient; use timely::communication::initialize::WorkerGuards; u...
<Worker, C, R>( config: ClusterConfig, worker_config: Worker, ) -> Result< ( TimelyContainerRef<C, R, Worker::Activatable>, impl Fn() -> Box<ClusterClient<PartitionedClient<C, R, Worker::Activatable>, Worker, C, R>>, ), Error, > where C: Send + 'static, R: Send + 'static, ...
serve
identifier_name
model.ts
this.cid = _.uniqueId(this.cidPrefix); if (options.parse) attrs = this.parse(attrs, options) || <A> {}; let defaults = _.result(this, 'defaults'); attrs = _.defaults(_.extend({}, defaults, attrs), defaults); this.set(attrs, options); } // Attributes protected attributes: A = <A> {}; protect...
super(options); // For clearing status when destroy model on collection this.event$.filter(e => e.topic == 'destroy') .subscribe(e => this._resetStatus());
random_line_split
model.ts
return base.replace(/[^\/]$/, '$&/') + encodeURIComponent(id); } get(attr: string) : any { return this.attributes[attr]; } // Get the HTML-escaped value of an attribute. escape(attr) { return _.escape(this.get(attr)); } // Returns `true` if the attribute contains a value that is not null // ...
{ return resp; }
identifier_body
model.ts
{}; let defaults = _.result(this, 'defaults'); attrs = _.defaults(_.extend({}, defaults, attrs), defaults); this.set(attrs, options); } // Attributes protected attributes: A = <A> {}; protected defaults: A; protected _previousAttributes: A; protected changed: A = <A> {}; public $attributes =...
else { (attrs = {})[key] = val; } // Run validation. if (!this._validate(attrs, options)) return this; // Extract attributes and options. var unset = options.unset; var silent = options.silent; var changes = []; var changing = this._changing; this._changing = t...
{ attrs = key; options = val; }
conditional_block
model.ts
) != null; } // Special-cased proxy to underscore's `_.matches` method. matches(attrs) { return !!_.iteratee(attrs, this)(this.attributes); } set(key: any, val: any, options: any = {}) : Model<A> { if (key == null) return this; // Handle both `"key", value` and `{key: value}` -style arguments. ...
isValid
identifier_name