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
scr.py
some threshold. Ex: scr.load_pfile(pfile='ff_xp93s1sp0001.dat', filetype=['pfile' or 'matfile']) Ex: Parse the text data into numbers. scr.pfile.parse_pfile(case=[1,100]) Ex: Sync and set the run to have a timestep of 0.01 sec. scr.pfile.sync(case=[1,100], ...
(self, **kwargs): """Method to perform fft on a signal. Ex: Plot fft of several responses. scr.fft(u_out=[(1, 'SSSIEA', 'FX'), (1, 'SSSIEA', 'FY')]) Ex: Plot fft of several applied forces. scr.fft(f_in=[(1, 100012, 1), (1, 100012, 2), (1, 100012...
fft
identifier_name
unauthorized-view.component.ts
Login:String; public server = environment.server; public allAccounts=0; public orgId:String=""; public orgName:String=""; public totalLogins:Number=0; public allUsers=[]; public lastLogins=[]; public barChartOptions:any = { scaleShowVerticalLines: false, responsive: true, scales: { ...
public chartHovered(e:any):void { console.log(e); } public populateData():void { let that=this; that.org_options=[]; var url='http://'+that.server+'/'+environment.rbacRoot+'/AccountUsers.php'; var obj={}; if (this.showAccounts!=true) obj["orgId"]=this.uploadedService....
{ console.log(e); console.log(event); }
identifier_body
unauthorized-view.component.ts
ins=[]; public barChartOptions:any = { scaleShowVerticalLines: false, responsive: true, scales: { yAxes: [{ type: "linear", display: true, position: "left", id: "y-axis-1", gridLines: { display: false }, scaleLabel: { ...
fillGraphData
identifier_name
unauthorized-view.component.ts
Login:String; public server = environment.server; public allAccounts=0; public orgId:String=""; public orgName:String=""; public totalLogins:Number=0; public allUsers=[]; public lastLogins=[]; public barChartOptions:any = { scaleShowVerticalLines: false, responsive: true, scales: { ...
that.populateData(); let jQueryInstance=this; $AB(document).ready(function(){ $AB(".hamburger").off('click').on('click',function(e){ e.preventDefault(); if ($AB(".panel-body").css("padding-left")=="100px"){ $AB(".side...
} this.logger.log("LOGIN","", new Date().toUTCString(),"","SUCCESS",this.showAccounts,this.username as string,that.uploadedService.getRoleName() as string,"DASHBOARD",this.uploadedService.getOrgName() as string);
random_line_split
TestGyp.py
(self, gyp=None, *args, **kw): self.origin_cwd = os.path.abspath(os.path.dirname(sys.argv[0])) self.extra_args = sys.argv[1:] if not gyp: gyp = os.environ.get('TESTGYP_GYP') if not gyp: if sys.platform == 'win32': gyp = 'gyn-run.bat' else: gyp = 'gyn-run' ...
__init__
identifier_name
TestGyp.py
import TestCommon from TestCommon import __all__ __all__.extend([ 'TestGyp', ]) def remove_debug_line_numbers(contents): """Function to remove the line numbers from the debug output of gyp and thus reduce the extreme fragility of the stdout comparison tests. """ lines = contents.splitlines() # split e...
random_line_split
TestGyp.py
_format = self.format.split('-')[-1] excluded_formats = set([f for f in formats if f[0] == '!']) included_formats = set(formats) - excluded_formats if ('!'+real_format in excluded_formats or included_formats and real_format not in included_formats): msg = 'Invalid test for %r format; skipping ...
def copy_test_configuration(self, source_dir, dest_dir): """ Copies the test configuration from the specified source_dir (the directory in which the test script lives) to the specified dest_dir (a temporary working directory). This ignores all files and directories that begin with the strin...
""" Fails the test if the specified built file name contains the specified contents. """ return self.must_not_contain(self.built_file_path(name, **kw), contents)
identifier_body
TestGyp.py
.stderr() if stderr: print self.banner('STDERR ') print stderr def run_gyp(self, gyp_file, *args, **kw): """ Runs gyp against the specified gyp_file with the specified args. """ # When running gyp, and comparing its output we use a comparitor # that ignores the line numbers that ...
print ('Warning: Environment variable GYP_MSVS_VERSION specifies "%s" ' 'but corresponding "%s" was not found.' % (msvs_version, path))
conditional_block
table.rs
chunks: Vec<Arc<dyn Array>>, num_rows: usize, null_count: usize, } impl ChunkedArray { /// Construct a `ChunkedArray` from a list of `Array`s. /// /// There must be at least 1 array, and all arrays must have the same data type. fn from_arrays(arrays: Vec<Arc<dyn Array>>) -> Self { a...
pub struct ChunkedArray {
random_line_split
table.rs
0].data_type(); arrays.iter().for_each(|array| { assert!(&array.data_type() == data_type); num_rows += array.len(); null_count += array.null_count(); }); ChunkedArray { chunks: arrays, num_rows, null_count, } } ...
(&self, i: usize) -> &Arc<dyn Array> { &self.chunks[i] } pub fn chunks(&self) -> &Vec<Arc<dyn Array>> { &self.chunks } /// Construct a zero-copy slice of the chunked array with the indicated offset and length. /// /// The `offset` is the position of the first element in the con...
chunk
identifier_name
table.rs
0].data_type(); arrays.iter().for_each(|array| { assert!(&array.data_type() == data_type); num_rows += array.len(); null_count += array.null_count(); }); ChunkedArray { chunks: arrays, num_rows, null_count, } } ...
else if consumed_len + chunk_size > total_len { chunk_size } else { total_len - consumed_len }; let slice = indices.slice(consumed_len, bounded_len); let slice = slice.as_any().downcast_ref::<UInt32Array>().unwrap(); let taken ...
{ total_len }
conditional_block
table.rs
0].data_type(); arrays.iter().for_each(|array| { assert!(&array.data_type() == data_type); num_rows += array.len(); null_count += array.null_count(); }); ChunkedArray { chunks: arrays, num_rows, null_count, } } ...
/// Slice the table from an offset pub fn slice(&self, offset: usize, limit: usize) -> Self { Self { schema: self.schema.clone(), columns: self .columns .
{ // TODO validate that schema and columns match Self { schema, columns } }
identifier_body
client.rs
Transaction; use crate::transaction::TransactionOptions; use crate::Backoff; use crate::BoundRange; use crate::Result; // FIXME: cargo-culted value const SCAN_LOCK_BATCH_SIZE: u32 = 1024; /// The TiKV transactional `Client` is used to interact with TiKV using transactional requests. /// /// Transactions support optim...
/// Retrieve the current [`Timestamp`]. /// /// # Examples /// /// ```rust,no_run /// # use tikv_client::{Config, TransactionClient}; /// # use futures::prelude::*; /// # futures::executor::block_on(async { /// let client = TransactionClient::new(vec!["192.168.0.100"]).await.unwrap()...
Snapshot::new(self.new_transaction(timestamp, options.read_only())) }
random_line_split
client.rs
; use crate::transaction::TransactionOptions; use crate::Backoff; use crate::BoundRange; use crate::Result; // FIXME: cargo-culted value const SCAN_LOCK_BATCH_SIZE: u32 = 1024; /// The TiKV transactional `Client` is used to interact with TiKV using transactional requests. /// /// Transactions support optimistic and p...
Ok(res) } pub async fn cleanup_locks( &self
{ info!("new safepoint != user-specified safepoint"); }
conditional_block
client.rs
; use crate::transaction::TransactionOptions; use crate::Backoff; use crate::BoundRange; use crate::Result; // FIXME: cargo-culted value const SCAN_LOCK_BATCH_SIZE: u32 = 1024; /// The TiKV transactional `Client` is used to interact with TiKV using transactional requests. /// /// Transactions support optimistic and p...
/// Retrieve the current [`Timestamp`]. /// /// # Examples /// /// ```rust,no_run /// # use tikv_client::{Config, TransactionClient}; /// # use futures::prelude::*; /// # futures::executor::block_on(async { /// let client = TransactionClient::new(vec!["192.168.0.100"]).await.unwrap...
{ debug!("creating new snapshot"); Snapshot::new(self.new_transaction(timestamp, options.read_only())) }
identifier_body
client.rs
; use crate::transaction::TransactionOptions; use crate::Backoff; use crate::BoundRange; use crate::Result; // FIXME: cargo-culted value const SCAN_LOCK_BATCH_SIZE: u32 = 1024; /// The TiKV transactional `Client` is used to interact with TiKV using transactional requests. /// /// Transactions support optimistic and p...
<S: Into<String>>(pd_endpoints: Vec<S>) -> Result<Client> { // debug!("creating transactional client"); Self::new_with_config(pd_endpoints, Config::default()).await } /// Create a transactional [`Client`] with a custom configuration, and connect to the TiKV cluster. /// /// Because TiKV...
new
identifier_name
scalecontrols.js
option><option value="xlog">log</option><option disabled>y axis:</option><option value="ylinear">linear</option><option value="ylog">log</option></select>'; JS9.ScaleLimits.plotHTML='<div><center>Pixel Distribution: %s</center></div><div class="JS9ScalePlot" style="width:%spx;height:%spx"></div>'; JS9.ScaleLimits.loH...
ge < 25000000 ){ tickinc = 1000000; } else { tickinc = 10000000; } return tickinc; }; const annotate = (plot, x, color) => { const ctx = plot.getCanvas().getContext("2d"); const size = JS9.ScaleLimits.CARET; const o = plot.pointOffset({x: x, y: 0}); ctx.beginPath(); ctx.moveTo(o....
kinc = 500000; } else if( dataran
conditional_block
scalecontrols.js
; case "xlog": plugin.xscale = "log"; JS9.ScaleLimits.doplot.call(plugin, im); break; case "ylinear": plugin.yscale = "linear"; JS9.ScaleLimits.doplot.call(plugin, im); break; case "ylog": plugin.yscale = "log"; JS9.ScaleLimits.doplot.call(plugin, im); break; default: ...
h = JS9.ScaleLimits.XTEXTHEIGHT + 2;
random_line_split
DataFrameExplored_dfprep-checkpoint.py
by coerce") print(f" - Example: {before_formatting} -->> {str(data.loc[0, i])}", end="\n") else: pass return data # Function, ........................................................................................... def replace_t...
''' function to dropna with thresholds from rows and columns . method . any : row/column wiht any missing data are removed . all : row/column only wiht missing data are removed . int, >0 : keeps row/clumns wiht this or larger number of non missing data ...
identifier_body
DataFrameExplored_dfprep-checkpoint.py
(*, series, pattern): "I used that function when i don't remeber full name of a given column" res = series.loc[series.str.contains(pattern)] return res # Function, ........................................................................................... def load_csv(*, path, filename, sep="\t", verbose...
find_and_display_patter_in_series
identifier_name
DataFrameExplored_dfprep-checkpoint.py
col_names with values to replace, if col_names=="all": sel_col_names = list(df.columns) else: sel_col_names = col_names # display message header, if verbose==True: print(f"""\nReplacing Text in {len(sel_col_names)} columns: {sel_col_names}\n""") ...
pass
conditional_block
DataFrameExplored_dfprep-checkpoint.py
full csv file name * separator "\t", by default * display_head bool, True, by default, display df.head(), irrespectively when the futions was called. Returns _________________ ____________________________________________________...
# Function, ........................................................................................... def replace_numeric_values(*, df, colnames="all", lower_limit="none", upper_limit="none", equal=False, replace_with=np.nan, verbose=True): """ Replace numerical values that are outside of range of a va...
random_line_split
main.rs
, future_presentation_infos: Vec<flatland::PresentationInfo>, }, #[allow(dead_code)] OnFramePresented { frame_presented_info: fidl_fuchsia_scenic_scheduling::FramePresentedInfo, }, Relayout { width: u32, height: u32, }, } struct AppModel<'a> { flatland: &'a f...
// should be more careful (this assumes that the client expects CreateView() to be called // multiple times, which clients commonly don't). let sender = self.internal_sender.clone(); fasync::Task::spawn(async move { let mut layout_info_stream = HangingGetStrea...
// link after data from the new link, just before the old link is closed. Non-example code
random_line_split
main.rs
(h: f32, s: f32, v: f32) -> [u8; 4] { assert!(s <= 100.0); assert!(v <= 100.0); let h = pos_mod(h, 360.0); let c = v / 100.0 * s / 100.0; let x = c * (1.0 - (((h / 60.0) % 2.0) - 1.0).abs()); let m = (v / 100.0) - c; let (mut r, mut g, mut b) = match h { h if h < 60.0 => (c, x, 0.0...
hsv_to_rgba
identifier_name
main.rs
future_presentation_infos: Vec<flatland::PresentationInfo>, }, #[allow(dead_code)] OnFramePresented { frame_presented_info: fidl_fuchsia_scenic_scheduling::FramePresentedInfo, }, Relayout { width: u32, height: u32, }, } struct AppModel<'a> { flatland: &'a fla...
while let Some(result) = layout_info_stream.next().await { match result { Ok(layout_info) => { let mut width = 0; let mut height = 0; if let Some(logical_size) = layout_info.logical_size { ...
{ let (parent_viewport_watcher, server_end) = create_proxy::<fland::ParentViewportWatcherMarker>() .expect("failed to create ParentViewportWatcherProxy"); // NOTE: it isn't necessary to call maybe_present() for this to take effect, because we will // relayout when re...
identifier_body
eks.go
} type EksUtilsConfig struct { WriteKubeConfig map[string]string `yaml:"write_kubeconfig"` } type EksConfig struct { clusterName string // set after parsing the eks YAML Binary string // path to the eksctl binary Params struct { Global map[string]string GetCluster map[string]string `yaml:...
(dryRun bool) error { clusterExists, err := p.clusterExists() if err != nil { return errors.WithStack(err) } if clusterExists { log.Logger.Debugf("An EKS cluster already exists called '%s'. Won't recreate it...", p.GetStack().GetConfig().GetCluster()) return nil } templatedVars, err := p.stack.GetTemp...
Create
identifier_name
eks.go
.Cmd } type EksUtilsConfig struct { WriteKubeConfig map[string]string `yaml:"write_kubeconfig"` } type EksConfig struct { clusterName string // set after parsing the eks YAML Binary string // path to the eksctl binary Params struct { Global map[string]string GetCluster map[string]string `y...
args := []string{"delete", "cluster"} args = parameteriseValues(args, p.eksConfig.Params.Global) args = parameteriseValues(args, p.eksConfig.Params.DeleteCluster) configFilePath, err := p.writeConfigFile() if err != nil { return errors.WithStack(err) } if configFilePath != "" { args = append(args, []string...
dryRunPrefix := "" if dryRun { dryRunPrefix = "[Dry run] " } clusterExists, err := p.clusterExists() if err != nil { return errors.WithStack(err) } if !clusterExists { return errors.New("No EKS cluster exists to delete") } templatedVars, err := p.stack.GetTemplatedVars(nil, map[string]interface{}{}) ...
identifier_body
eks.go
config"` } type EksConfig struct { clusterName string // set after parsing the eks YAML Binary string // path to the eksctl binary Params struct { Global map[string]string GetCluster map[string]string `yaml:"get_cluster"` CreateCluster map[string]string `yaml:"create_cluster"` DeleteClus...
os.Stderr, "", eksCommandTimeoutSecondsLong, 0, dryRun) if err != nil {
random_line_split
eks.go
.Cmd } type EksUtilsConfig struct { WriteKubeConfig map[string]string `yaml:"write_kubeconfig"` } type EksConfig struct { clusterName string // set after parsing the eks YAML Binary string // path to the eksctl binary Params struct { Global map[string]string GetCluster map[string]string `y...
clusterExists, err := p.clusterExists() if err != nil { return errors.WithStack(err) } if !clusterExists { return errors.New("No EKS cluster exists to delete") } templatedVars, err := p.stack.GetTemplatedVars(nil, map[string]interface{}{}) if err != nil { return errors.WithStack(err) } log.Logger.Debug...
dryRunPrefix = "[Dry run] " }
conditional_block
main.rs
let data1 = compute_data(segments1); let data2 = compute_data(segments2); // Next we split each segment into horizontal and vertical // vectors, then sort them according to their horizontal component fn partition_and_sort(seg: &[ComputeData]) -> (Vec<&ComputeData>, Vec<&ComputeData>) {...
random_line_split
main.rs
(&self) -> u64 { self.x.abs() as u64 + self.y.abs() as u64 } fn flat_distance_to(&self, other: &Self) -> u64 { (self.x - other.x).abs() as u64 + (self.y - other.y).abs() as u64 } } enum Polarity { Vertical, Horizontal, } #[allow(dead_code)] impl Polarity { fn is_horizontal(&se...
manhattan_distance
identifier_name
viewModels.js
Load.error); } }, error : function(xhr, ajaxOptions, thrownError) { console.log(xhr); console.log(ajaxOptions); console.log(thrownError); }, complete : function() { self.phase("upload"); self.uploadDataAsync(); }, beforeSend : setHeader }); }, 100); }; self.u...
random_line_split
viewModels.js
parent.internal(true); parent.allchecked(allTrue); parent.internal(false); if (partialTrue && allTrue === false) { parent.linksIndeterminate(true); } else { parent.linksIndeterminate(false); } } }; self.getSearchDataAsync = function(sYear, eYear) { setTimeout(function() { console.log...
{ if (catlinks[j].checked() === true) { partialTrue = true; } else { allTrue = false; } }
conditional_block
window.go
.mu.Unlock() var ps image.Point ps.X, ps.Y = w.glw.GetPos() w.Pos = ps return ps } func (w *windowImpl) PhysicalDPI() float32 { w.mu.Lock() defer w.mu.Unlock() return w.PhysDPI } func (w *windowImpl) LogicalDPI() float32 { w.mu.Lock() defer w.mu.Unlock() return w.LogDPI } func (w *windowImpl) SetLogicalDPI...
random_line_split
window.go
z := opts.Size // note: this is already in standard window size units! win, err := glfw.CreateWindow(sz.X, sz.Y, opts.GetTitle(), nil, theApp.shareWin) if err != nil { return win, err } win.SetPos(opts.Pos.X, opts.Pos.Y) return win, err } // for sending window.Event's func (w *windowImpl) sendWindowEvent(act wi...
SetPixSize
identifier_name
window.go
windowImpl) Scale(dr image.Rectangle, src oswin.Texture, sr image.Rectangle, op draw.Op, opts *oswin.DrawOptions) { if !w.IsVisible() { return } drawer.Scale(w, dr, src, sr, op, opts) } func (w *windowImpl) Fill(dr image.Rectangle, src color.Color, op draw.Op) { if !w.IsVisible() { return } theApp.RunOnMain(...
{ sc = scc got = true if monitorDebug { log.Printf("glos window: %v getScreen(): matched pix ratio %v for screen: %v\n", w.Nm, w.DevPixRatio, sc.Name) } w.LogDPI = sc.LogicalDPI break }
conditional_block
window.go
Tex texture to the window and then // calls Publish() -- this is the typical update call. func (w *windowImpl) PublishTex() { if !w.IsVisible() { return } theApp.RunOnMain(func() { if !w.Activate() || w.winTex == nil { return } w.Copy(image.ZP, w.winTex, w.winTex.Bounds(), oswin.Src, nil) }) w.Publish()...
{ w.mu.Lock() defer w.mu.Unlock() w.closeReqFunc = fun }
identifier_body
translate.rs
pub struct CharSetCase { pub start: char, pub end: char } pub struct TaggedExpr { pub name: Option<String>, pub expr: Box<Expr>, } pub enum Expr { AnyCharExpr, LiteralExpr(String), CharSetExpr(bool, Vec<CharSetCase>), RuleExpr(String), SequenceExpr(Vec<Expr>), ChoiceExpr(Vec<Expr>), OptionalExpr(Box<Expr>...
pub exported: bool, }
random_line_split
translate.rs
{ pub name: String, pub expr: Box<Expr>, pub ret_type: String, pub exported: bool, } pub struct CharSetCase { pub start: char, pub end: char } pub struct TaggedExpr { pub name: Option<String>, pub expr: Box<Expr>, } pub enum Expr { AnyCharExpr, LiteralExpr(String), CharSetExpr(bool, Vec<CharSetCase>), R...
Rule
identifier_name
translate.rs
match *i { RustUseSimple(ref p) => ctxt.view_use_simple(DUMMY_SP, rustast::ast::Inherited, rustast::parse_path(p.as_slice())), RustUseGlob(ref p) => ctxt.view_use_glob(DUMMY_SP, rustast::ast::Inherited, rustast::parse_path_vec(p.as_slice())), RustUseList(ref p, ref v) => ctxt.view_use_list(DUMMY_SP, rustast::...
fn compile_rule_export(ctxt: &rustast::ExtCtxt, rule: &Rule) -> rustast::P<rustast::Item> { let name = rustast::str_to_ident(rule.name.as_slice()); let ret = rustast::parse_type(rule.ret_type.as_slice()); let parse_fn = rustast::str_to_ident(format!("parse_{}", rule.name).as_slice()); (quote_item!(ctxt, pub fn ...
{ let name = rustast::str_to_ident(format!("parse_{}", rule.name).as_slice()); let ret = rustast::parse_type(rule.ret_type.as_slice()); let body = compile_expr(ctxt, &*rule.expr, rule.ret_type.as_slice() != "()"); (quote_item!(ctxt, fn $name<'input>(input: &'input str, state: &mut ParseState, pos: uint) -> ParseR...
identifier_body
views.py
order_item, order, payment_details from cart.models import Cart from django.contrib.auth import update_session_auth_hash from django.contrib.auth.forms import PasswordChangeForm from django.contrib.auth.models import User, auth from .forms import productsform, profilesform from django.contrib import messages from djan...
# Create your views here. def index(request): user = request.user username = user.username category=["Electronic Devices","Electronic Accessories","TV & Home Appliances","Health & Beauty","Babies & Toys","Groceries & Pets", "Home & Lifestyle","Women's Fashion","Men's Fashion","Watches & Accessories","Sp...
random_line_split
views.py
order_item, order, payment_details from cart.models import Cart from django.contrib.auth import update_session_auth_hash from django.contrib.auth.forms import PasswordChangeForm from django.contrib.auth.models import User, auth from .forms import productsform, profilesform from django.contrib import messages from djan...
if showupload: form = productsform() return render(request, "upload.html", {"form": form}) else: messages.info(request,'You are not registered as Seller') return redirect('/') def login(request): if request.method == 'POST': user...
showupload = pro.is_seller
conditional_block
views.py
_item, order, payment_details from cart.models import Cart from django.contrib.auth import update_session_auth_hash from django.contrib.auth.forms import PasswordChangeForm from django.contrib.auth.models import User, auth from .forms import productsform, profilesform from django.contrib import messages from django.cor...
(request, slug): if request.method == 'POST': slug = request.POST['slug'] product=products.objects.get(slug=slug) product.name = request.POST['name'] product.brand = request.POST['brand'] product.price = request.POST['price'] product.description = request.POST['descri...
modify
identifier_name
views.py
from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator from django.core.mail import send_mail from django.utils.datastructures import MultiValueDictKeyError from .models import Feedback def deleteacc(request): if request.method == 'POST': username = request.user.username Cart.obje...
if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = auth.authenticate(username=username, password=password) if user is not None: auth.login(request, user) return redirect('/') else: mess...
identifier_body
lib.rs
::Result<()>{ let mut lines: Vec<String> = vec![String::new();self.cluster_ids.len()]; for i in 0..self.cluster_ids.len(){ lines[i] = format!("{},{},{}\n",self.cluster_ids[i], self.stability_scores[i],self.purity_scores[i]) } let outfile = format!("{}/{}", outpath, self.exp_...
let mut s = String::new(); gz.read_to_string(&mut s)?; Ok(s) } fn read_cluster_results( file: &str) ->ClusterResults { let mut handle = fs::File::open(file).expect("Bad file input"); let mut buffer = Vec::new(); handle.read_to_end(&mut buffer).expect("couldnt read file"); let file_string = de...
return entropy(&new_clu.grouped_barcodes, &new_clu.labels); } } fn decode_reader(bytes: Vec<u8>) -> std::io::Result<String> { let mut gz = GzDecoder::new(&bytes[..]);
random_line_split
lib.rs
Result<()>
fn write_csv_simple(&self, outfile:&str)->std::io::Result<()>{ let mut lines: Vec<String> = vec![String::new();self.cluster_ids.len()]; for i in 0..self.cluster_ids.len(){ lines[i] = format!("{},{},{}\n",self.cluster_ids[i], self.stability_scores[i],self.purity_scores[i]) } ...
{ let mut lines: Vec<String> = vec![String::new();self.cluster_ids.len()]; for i in 0..self.cluster_ids.len(){ lines[i] = format!("{},{},{}\n",self.cluster_ids[i], self.stability_scores[i],self.purity_scores[i]) } let outfile = format!("{}/{}", outpath, self.exp_param); ...
identifier_body
lib.rs
Result<()>{ let mut lines: Vec<String> = vec![String::new();self.cluster_ids.len()]; for i in 0..self.cluster_ids.len(){ lines[i] = format!("{},{},{}\n",self.cluster_ids[i], self.stability_scores[i],self.purity_scores[i]) } let outfile = format!("{}/{}", outpath, self.exp_pa...
(v:Vec<f64>) -> f64{ return v.iter().sum::<f64>() / v.len() as f64 } fn purity_k(ref_bc_set: &HashSet<i64>, query_map: &HashMap<i64, HashSet<i64>>) -> f64{ let mut max_overlap = 0; let mut max_overlap_key:i64 = -100000000; for query_key in query_map.keys(){ let q_cluster_set = query_map.get(query...
vmean
identifier_name
lib.rs
Result<()>{ let mut lines: Vec<String> = vec![String::new();self.cluster_ids.len()]; for i in 0..self.cluster_ids.len(){ lines[i] = format!("{},{},{}\n",self.cluster_ids[i], self.stability_scores[i],self.purity_scores[i]) } let outfile = format!("{}/{}", outpath, self.exp_pa...
let ns: HashSet<i64> = HashSet::new(); current_set = ns; current_set.insert(current_barcode.clone()); old_label = current_label; } } grouped_barcodes.insert(current_label.clone(), current_set); let h_tot = entropy(&grou...
{ // HashMap.insert returns None when new key is added panic!("A duplicate key was added when making a ClusterResults; input data is not sorted by label") }
conditional_block
vt-3.rs
info per framebuffer let pipeline_color_blend_attachment_infos = [vk::PipelineColorBlendAttachmentState { blend_enable: vk::FALSE, // not used because we disabled blending src_color_blend_factor: vk::BlendFactor::ONE, dst_color_blend_factor: vk::BlendFactor::ZERO, color_blen...
{ use winit::os::unix::WindowExt; let x11_display = window.get_xlib_display().unwrap(); let x11_window = window.get_xlib_window().unwrap(); let x11_create_info = vk::XlibSurfaceCreateInfoKHR { s_type: vk::StructureType::XLIB_SURFACE_CREATE_INFO_KHR, p_next: ptr::null(), flags: D...
identifier_body
vt-3.rs
support! It's possible that a separate queue with surface support exists, but the current implementation is not capable of finding one."); } // get logical device let device_queue_create_info = vk::DeviceQueueCreateInfo { s_type: vk::StructureType::DEVICE_QUEUE_CREATE_INFO, p_next: ptr::nu...
queue_family_index, queue_count: 1, p_queue_priorities: [1.0].as_ptr(), }; let device_extensions_raw = get_device_extensions_raw(); let device_create_info = vk::DeviceCreateInfo { s_type: vk::StructureType::DEVICE_CREATE_INFO, p_next: ptr::null(), flags: vk:...
flags: vk::DeviceQueueCreateFlags::empty(),
random_line_split
vt-3.rs
}) .collect(); // shaders let frag_code = read_shader_code(&relative_path("shaders/vt-3/triangle.frag.spv")); let vert_code = read_shader_code(&relative_path("shaders/vt-3/triangle.vert.spv")); let frag_module = create_shader_module(&device, frag_code); let vert_module = create_shader_mod...
vulkan_debug_utils_callback
identifier_name
hydrophoneApi.go
confirm/send/team/invite send.Handle("/team/invite", varsHandler(a.SendTeamInvite)).Methods("POST") // POST /confirm/send/team/monitoring/{teamid}/{userid} send.Handle("/team/monitoring/{teamid}/{userid}", varsHandler(a.SendMonitoringTeamInvite)).Methods("POST") // POST /confirm/send/team/role/:userid - add or remo...
{ log.Printf("trying notification with template '%s' to %s with language '%s'", conf.TemplateName, conf.Email, lang) // Get the template name based on the requested communication type templateName := conf.TemplateName if templateName == models.TemplateNameUndefined { switch conf.Type { case models.TypePassword...
identifier_body
hydrophoneApi.go
sl, perms: perms, auth: auth, seagull: seagull, medicalData: medicalData, templates: templates, LanguageBundle: nil, logger: logger, } } func (a *Api) getWebURL(req *http.Request) string { if a.Config.WebURL == "" { host := req.Header.Get("Host") return a....
{ if err = a.addProfile(ctx, results[i]); err != nil { //report and move on log.Println("Error getting profile", err.Error()) } }
conditional_block
hydrophoneApi.go
func (a *Api) SetHandlers(prefix string, rtr *mux.Router) { rtr.HandleFunc("/status", a.GetStatus).Methods("GET") rtr.Handle("/sanity_check/{userid}", varsHandler(a.sendSanityCheckEmail)).Methods("POST") // POST /confirm/send/forgot/:useremail // POST /confirm/send/invite/:userid send := rtr.PathPrefix("/send")...
log.Printf("trying notification with template '%s' to %s with language '%s'", conf.TemplateName, conf.Email, lang) // Get the template name based on the requested communication type templateName := conf.TemplateName if templateName == models.TemplateNameUndefined {
random_line_split
hydrophoneApi.go
, templates: templates, LanguageBundle: nil, logger: logger, } } func (a *Api) getWebURL(req *http.Request) string { if a.Config.WebURL == "" { host := req.Header.Get("Host") return a.Config.Protocol + "://" + host } return a.Config.WebURL } func (a *Api) SetHandlers(prefix string, rtr *mux...
createAndSendNotification
identifier_name
mod.rs
not //! guaranteed. Because the substreams are independent, there is no guarantee on the ordering //! of the message delivery either. //! 2. An DirectSend call negotiates which protocol to speak using [`protocol-select`]. This //! allows simple versioning of message delivery and negotiation of which message ...
( executor: TaskExecutor, ds_requests_rx: channel::Receiver<DirectSendRequest>, ds_notifs_tx: channel::Sender<DirectSendNotification>, peer_mgr_notifs_rx: channel::Receiver<PeerManagerNotification<TSubstream>>, peer_mgr_reqs_tx: PeerManagerRequestSender<TSubstream>, ) -> Self...
new
identifier_name
mod.rs
//! that only the dialer sends a message to the listener, but no messages or acknowledgements //! sending back on the other direction. So the message delivery is best effort and not //! guaranteed. Because the substreams are independent, there is no guarantee on the ordering //! of the message delivery eith...
random_line_split
mod.rs
not //! guaranteed. Because the substreams are independent, there is no guarantee on the ordering //! of the message delivery either. //! 2. An DirectSend call negotiates which protocol to speak using [`protocol-select`]. This //! allows simple versioning of message delivery and negotiation of which message ...
; write!( f, "Message {{ protocol: {:?}, mdata: {} }}", self.protocol, mdata_str ) } } /// The DirectSend actor. pub struct DirectSend<TSubstream> { /// A handle to a tokio executor. executor: TaskExecutor, /// Channel to receive requests from other u...
{ format!("{:?}...", self.mdata.slice_to(10)) }
conditional_block
app.go
" " + time.Now().Format("Jan 02 15:04:05.000") + " " + value + "\n") } } func App() { getFilenameFromArgs := func(args []string) string { if len(args) > 1 { return args[1] } else { return "gttp-tmp.json" } } // log file os.Remove("application.log") if logOn { logFile, _ = os.OpenFile("ap...
getOutput
identifier_name
app.go
Level()) + " " + time.Now().Format("Jan 02 15:04:05.000") + " " + value + "\n") } } func App() { getFilenameFromArgs := func(args []string) string { if len(args) > 1 { return args[1] } else { return "gttp-tmp.json" } } // log file os.Remove("application.log") if logOn { logFile, _ = os.Op...
{ treeAPICpnt.Refresh() }
identifier_body
app.go
.Contains(logLevels, level) { logFile.WriteString( strings.ToUpper(getLevel()) + " " + time.Now().Format("Jan 02 15:04:05.000") + " " + value + "\n") } } func App() { getFilenameFromArgs := func(args []string) string { if len(args) > 1 { return args[1] } else { return "gttp-tmp.json" } } ...
ctx.PrintTrace("App.refreshingContext." + key) value(output.Context) } }
random_line_split
app.go
Fixme: To delete mapFocusPrmtToShortutText[requestResponseView.ResponsePrmt] = utils.ResultShortcutsText mapFocusPrmtToShortutText[expertModeView.TitlePrmt] = utils.ExpertModeShortcutsText mapFocusPrmtToShortutText[settingsView.TitlePrmt] = utils.SettingsShortcutsText refresh("all") app.SetInputCapture(func(eve...
{ refreshingTreeAPICpn() }
conditional_block
test_1.rs
// dem granular pub use dem_rust::basic_equations::*; pub use dem_rust::dem_3d::*; pub use dem_rust::wall::*; pub use dem_rust::prelude::*; // // rigid body imports // pub use dem_rust::rb::rb_2d::Rigidbody2D; // for reading data from file (comma separated) use crate::read_xy_pairs; // external crate imports // use ...
{ flag_tf: f64, flag_dt: f64, flag_plots: bool, } pub fn main(args: &[String]) { // -------------------------------------- // GET THE COMMAND LINE VARIABLES // -------------------------------------- let args: Args = Docopt::new(USAGE) .and_then(|d| d.argv(args).deserialize()) ...
Args
identifier_name
test_1.rs
// dem granular pub use dem_rust::basic_equations::*; pub use dem_rust::dem_3d::*; pub use dem_rust::wall::*; pub use dem_rust::prelude::*; // // rigid body imports // pub use dem_rust::rb::rb_2d::Rigidbody2D; // for reading data from file (comma separated) use crate::read_xy_pairs; // external crate imports // use ...
let rho = 2600.; sand.rho = vec![rho; x.len()]; sand.m = vec![rho * PI * radius[0] * radius[0]; x.len()]; sand.m_inv = vec![1. / sand.m[0]; x.len()]; let inertia = 4. * (2. * radius[0]) * (2. * radius[0]) / 10.; sand.mi = vec![inertia; x.len()]; sand.mi_inv = vec![1. / sand.mi[0]; x.len()];...
{ // -------------------------------------- // GET THE COMMAND LINE VARIABLES // -------------------------------------- let args: Args = Docopt::new(USAGE) .and_then(|d| d.argv(args).deserialize()) .unwrap_or_else(|e| e.exit()); // println!("{:?}", args); // ---------------------...
identifier_body
test_1.rs
dem granular pub use dem_rust::basic_equations::*; pub use dem_rust::dem_3d::*; pub use dem_rust::wall::*; pub use dem_rust::prelude::*; // // rigid body imports // pub use dem_rust::rb::rb_2d::Rigidbody2D; // for reading data from file (comma separated) use crate::read_xy_pairs; // external crate imports // use gn...
; // ---------------------------------------- // SOLVER DATA ENDS // ---------------------------------------- // ---------------------------------------- // OUTPUT DIRECTORY // ---------------------------------------- let project_root = env!("CARGO_MANIFEST_DIR"); let dir_name = project...
{ total_steps / total_output_file }
conditional_block
test_1.rs
let yng = 1.; let nu = 0.2; let shr = yng / (2. * (1. + nu)); sand.young_mod = vec![yng; x.len()]; sand.poisson = vec![nu; x.len()]; sand.shear_mod = vec![shr; x.len()]; // this is nice step for debugging sand.validate_particle_array(); // ------------------------- // create an...
// &[Caption("Al oxide"), Color("blue")], // );
random_line_split
mqtt_dev.py
ot import mqtt_connection_builder from .topic_config import read_config # setup: received_count = 0 received_all_event = threading.Event() args = 0 def mqtt_pub(): """ Publish a random stream of messages to the AWS IoT Core MQTT broker """ global args args = parse_args() init(args) mqtt_...
"Connection resumed. return_code: {} session_present: {}".format( return_code, session_present, ), ) if return_code == mqtt.ConnectReturnCode.ACCEPTED and not session_present: print("Session did not persist. Resubscribing to existing topics...") resubscri...
print(
random_line_split
mqtt_dev.py
import mqtt_connection_builder from .topic_config import read_config # setup: received_count = 0 received_all_event = threading.Event() args = 0 def mqtt_pub(): """ Publish a random stream of messages to the AWS IoT Core MQTT broker """ global args args = parse_args() init(args) mqtt_co...
publish_count = 1 while (publish_count <= args.count) or (args.count == 0): # topic definition: generate a random topic to publish to, based on the established hierarchy: # ex: IOOS/<platform_type>/<ra>/<platform>/<sensor>/<variable> platform_type = random.choice(topic_data["platform_...
print(f"Sending {args.count} message(s)")
conditional_block
mqtt_dev.py
ot import mqtt_connection_builder from .topic_config import read_config # setup: received_count = 0 received_all_event = threading.Event() args = 0 def mqtt_pub():
print("Sending messages until program killed") else: print(f"Sending {args.count} message(s)") publish_count = 1 while (publish_count <= args.count) or (args.count == 0): # topic definition: generate a random topic to publish to, based on the established hierarchy: # ex: IO...
""" Publish a random stream of messages to the AWS IoT Core MQTT broker """ global args args = parse_args() init(args) mqtt_connection = setup_connection(args) connect_future = mqtt_connection.connect() # Future.result() waits until a result is available connect_future.result() ...
identifier_body
mqtt_dev.py
import mqtt_connection_builder from .topic_config import read_config # setup: received_count = 0 received_all_event = threading.Event() args = 0 def mqtt_pub(): """ Publish a random stream of messages to the AWS IoT Core MQTT broker """ global args args = parse_args() init(args) mqtt_co...
(args): """ Main setup function """ io.init_logging(getattr(io.LogLevel, args.verbosity), "stderr") # global received_count = 0 # global received_all_event = threading.Event() def setup_connection(args): """ Set up an MQTT client connection and other details """ event_loop_gr...
init
identifier_name
jisho.py
_one("span.unlinked").text if li.select_one("span.unlinked") is not None else None if furigana: kanji += unlifted kana += furigana kanaEnding = [] for i in reversed(range(len(unlifted))):
break kana += ''.join(kanaEnding[::-1]) else: kanji += unlifted kana += unlifted else: text = str(child).strip() if text: kanji += text kana += text return kanji, kan...
if not re.search(kanjiRegex, unlifted[i]): kanaEnding.append(unlifted[i]) else:
random_line_split
jisho.py
in sentenceElement.select("span.furigana"): s.extract() japanese = sentenceElement.text sentences.append({'english': english, 'japanese': japanese, 'pieces': pieces}) meanings.append({ 'seeAlsoTerms': seeAlsoTerms, 'sent...
, meanings_list):
identifier_name
jisho.py
def get_string_between_strings(data, start_string, end_string): regex = f'{re.escape(start_string)}(.*?){re.escape(end_string)}' # Need DOTALL because the HTML still has its newline characters match = re.search(regex, str(data), re.DOTALL) return match[1] if match is not None else None def parse_an...
return f'{JISHO_API}?keyword={urllib.parse.quote(phrase)}'
identifier_body
jisho.py
AlsoTerms = [] for i in reversed(range(len(supplemental))): supplementalEntry = supplemental[i] if supplementalEntry.startswith('See also'): seeAlsoTerms.append(supplementalEntry.replace('See also ', '')) supplemental.pop(i) ...
lf._extract_dictionary_information(r)) elif depth =
conditional_block
main_window_test.py
We stay at 4 because it's appropriate # Although the view index stayed the same, the view still changed, so the GUI needs to change. app.check_gui_calls(app.mainwindow_gui, ['view_closed', 'change_current_pane', 'refresh_status_line']) app.mw.close_pane(3) eq_(app.mw.current_pane_index, 2) @with_app(T...
# columns. app.show_nwview() expected = [("Account #", False), ("Start", True), ("Change", False), ("Change %", False), ("Budgeted", True)] eq_(app.mw.column_menu_items(), expected) app.mw.toggle_column_menu_item(0) expected[0] = ("Account #", True) eq_(app.mw.column_menu_items(), ex...
@with_app(TestApp) def test_column_menu_attributes(app): # The column menu depends on the selected pane and shows the display attribute of optional
random_line_split
main_window_test.py
We stay at 4 because it's appropriate # Although the view index stayed the same, the view still changed, so the GUI needs to change. app.check_gui_calls(app.mainwindow_gui, ['view_closed', 'change_current_pane', 'refresh_status_line']) app.mw.close_pane(3) eq_(app.mw.current_pane_index, 2) @with_app(T...
(app): # When a non-selected pane is moved before the selected one, update the selected index app.mw.move_pane(1, 0) eq_(app.mw.current_pane_index, 1) @with_app(TestApp) def test_move_pane_selected(app): # When the moved pane is selected, the selection follows the pane. app.mw.move_pane(0, 3) e...
test_move_pane_before_selected
identifier_name
main_window_test.py
We stay at 4 because it's appropriate # Although the view index stayed the same, the view still changed, so the GUI needs to change. app.check_gui_calls(app.mainwindow_gui, ['view_closed', 'change_current_pane', 'refresh_status_line']) app.mw.close_pane(3) eq_(app.mw.current_pane_index, 2) @with_app(T...
# we can't go further app.mw.select_next_view() eq_(app.mw.current_pane_index, 4) for index in reversed(range(5)): eq_(app.mw.current_pane_index, index) app.mw.select_previous_view() # we can't go further app.mw.select_previous_view() eq_(app.mw.current_pane_index, 0) @with...
eq_(app.mw.current_pane_index, index) app.mw.select_next_view()
conditional_block
main_window_test.py
_pane(0) app.mw.close_pane(0) # no crash eq_(app.mw.pane_count, 1) @with_app(TestApp) def test_column_menu_attributes(app): # The column menu depends on the selected pane and shows the display attribute of optional # columns. app.show_nwview() expected = [("Account #", False), ("Start", True), ...
app.show_account('first') app.show_account() app.check_current_pane(PaneType.Account, 'second')
identifier_body
cnn_model.py
.info('cnn_model: added {} Dense layer (-> {})'.format(output_activation, output_size)) # Compile if optimizer == 'adam': optimizer = Adam(lr=lr) elif optimizer == 'rmsprop': optimizer = RMSprop(lr=lr) else: logging.info('Can only handle adam or rmsprop optimizers currently') quit(1) if loss == 'custom':...
mean_inner_val_loss = inner_val_loss[-1] write_loss_report(mean_loss, mean_inner_val_loss, mean_outer_val_loss, mean_test_loss, fpath + '_loss_report.txt')
random_line_split
cnn_model.py
0, batch_size=50, lr_func='0.01', patience=10): """ inputs: model - a Keras model data - X_train, X_inner_val, X_outer_val, y_train, y_inner_val, y_outer_val, X_test, y_test nb_epoch - number of epochs to train for lr_func - string which is evaluated with 'epoch' to produce the learning ra...
""" This function saves the history returned by model.fit to a tab- delimited file, where model is a keras model """ # Open file fid = open(fpath, 'a') logging.info('trained at {}'.format(datetime.datetime.utcnow())) print('iteration\tloss\tval_loss', file=fid) try: # Iterate through for i in range(len(lo...
identifier_body
cnn_model.py
(embedding_size=512, attribute_vector_size=33, depth=5, scale_output=0.05, padding=False, mol_conv_inner_activation='tanh', mol_conv_outer_activation='softmax', hidden=50, hidden_activation='tanh', output_activation='linear', output_size=1, lr=0.01, optimizer='adam', loss='mse'): ...
build_model
identifier_name
cnn_model.py
.add(MoleculeConv(units=embedding_size, inner_dim=attribute_vector_size-1, depth=depth, scale_output=scale_output, padding=padding, activation_inner=mol_conv_inner_activation, activation_output=mol_conv_outer_activation)) logging.info('cnn_model: added MoleculeConv layer ({} -> {})'.format('mol', embed...
mean_test_loss = evaluate_mean_tst_loss(model, X_test, y_test) except KeyboardInterrupt: logging.info('User terminated training early (intentionally)') return (model, loss, inner_val_loss, mean_outer_val_loss, mean_test_loss) def evaluate_mean_tst_loss(model, X_test, y_test): """ Given final model and test...
mean_outer_val_loss = None
conditional_block
lib.rs
/// * https://docs.microsoft.com/en-us/windows/uwp/controls-and-patterns/tiles-and-notifications-toast-xml-schema /// * https://docs.microsoft.com/en-us/windows/uwp/controls-and-patterns/tiles-and-notifications-adaptive-interactive-toasts /// * https://msdn.microsoft.com/library/14a07fce-d631-4bad-ab99-305b703713e6#Se...
Call, Call2, Call3, Call4, Call5, Call6, Call7, Call8, Call9, Call10, } #[allow(dead_code)] #[derive(Clone, Copy)] pub enum IconCrop { Square, Circular, } #[doc(hidden)] impl fmt::Display for Sound { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt...
Alarm9, Alarm10,
random_line_split
lib.rs
/// * https://docs.microsoft.com/en-us/windows/uwp/controls-and-patterns/tiles-and-notifications-toast-xml-schema /// * https://docs.microsoft.com/en-us/windows/uwp/controls-and-patterns/tiles-and-notifications-adaptive-interactive-toasts /// * https://msdn.microsoft.com/library/14a07fce-d631-4bad-ab99-305b703713e6#Sen...
{ /// 7 seconds Short, /// 25 seconds Long, } #[derive(Debug, EnumString, Clone, Copy)] pub enum Sound { Default, IM, Mail, Reminder, SMS, /// Play the loopable sound only once #[strum(disabled)] Single(LoopableSound), /// Loop the loopable sound for the entire dur...
Duration
identifier_name
lib.rs
/uwp/controls-and-patterns/tiles-and-notifications-adaptive-interactive-toasts /// * https://msdn.microsoft.com/library/14a07fce-d631-4bad-ab99-305b703713e6#Sending_toast_notifications_from_desktop_apps /// for Windows 7 and older support look into Shell_NotifyIcon /// https://msdn.microsoft.com/en-us/library/windows/...
//using this to get an instance of XmlDocument let toast_xml = XmlDocument::new()?; let template_binding = if windows_check::is_newer_than_windows81() { "ToastGeneric" } else //win8 or win81 { // Need to do this or an empty placeholder will be shown i...
identifier_body
testcase.py
a new temporary HOME directory. #: #: If set, a directory will be created at test startup, and will be #: set as the home directory. #: #: Version Added: #: 3.0 needs_temp_home: bool = False @classmethod def setUpClass(cls): super(TestCase, cls).setUpClass() cl...
Raises: AssertionError: The test suite class did not mix in :py:class:`kgb.SpyAgency`. """ spy_for = getattr(self, 'spy_for', None) assert spy_for, ( '%r must mix in kgb.SpyAgency in order to call this method.' % self.__class__) ...
count (int): The number of temporary filenames to pre-create.
random_line_split
testcase.py
a new temporary HOME directory. #: #: If set, a directory will be created at test startup, and will be #: set as the home directory. #: #: Version Added: #: 3.0 needs_temp_home: bool = False @classmethod def setUpClass(cls): super(TestCase, cls).setUpClass() cl...
else: os.environ[key] = value def precreate_tempfiles(self, count): """Pre-create a specific number of temporary files. This will call :py:func:`~rbtools.utils.filesystem.make_tempfile` the specified number of times, returning the list of generated temp...
os.environ.pop(key, None)
conditional_block
testcase.py
a new temporary HOME directory. #: #: If set, a directory will be created at test startup, and will be #: set as the home directory. #: #: Version Added: #: 3.0 needs_temp_home: bool = False @classmethod def setUpClass(cls): super(TestCase, cls).setUpClass() cl...
Args: count (int): The number of temporary filenames to pre-create. Raises: AssertionError: The test suite class did not mix in :py:class:`kgb.SpyAgency`. """ spy_for = getattr(self, 'spy_for', None) assert spy_for, ( ...
"""Pre-create a specific number of temporary files. This will call :py:func:`~rbtools.utils.filesystem.make_tempfile` the specified number of times, returning the list of generated temp file paths, and will then spy that function to return those temp files. Once each pre-create...
identifier_body
testcase.py
a new temporary HOME directory. #: #: If set, a directory will be created at test startup, and will be #: set as the home directory. #: #: Version Added: #: 3.0 needs_temp_home: bool = False @classmethod def setUpClass(cls): super(TestCase, cls).setUpClass() cl...
(self, count): """Pre-create a specific number of temporary files. This will call :py:func:`~rbtools.utils.filesystem.make_tempfile` the specified number of times, returning the list of generated temp file paths, and will then spy that function to return those temp files. ...
precreate_tempfiles
identifier_name
data_loader.py
random.randint(0, 255), random.randint( 0, 255), random.randint(0, 255)) for _ in range(5000)] nprandomseed = 2019 class DataLoaderError(Exception): pass def get_pairs_from_paths(images_path, segs_path, ignore_non_matching=False): """ Find all the images from the images_path directory and the s...
return_value = True for im_fn, seg_fn in tqdm(img_seg_pairs): img = cv2.imread(im_fn) seg = cv2.imread(seg_fn) # Check dimensions match if not img.shape == seg.shape: return_value = False print("The size of image {0} and ...
print("Couldn't load any data from images_path: " "{0} and segmentations path: {1}" .format(images_path, segs_path)) return False
conditional_block
data_loader.py
5000)] nprandomseed = 2019 class DataLoaderError(Exception): pass def get_pairs_from_paths(images_path, segs_path, ignore_non_matching=False): """ Find all the images from the images_path directory and the segmentation images from the segs_path directory while checking integrity of data """...
create_pipeline
identifier_name
data_loader.py
random.randint(0, 255), random.randint( 0, 255), random.randint(0, 255)) for _ in range(5000)] nprandomseed = 2019 class DataLoaderError(Exception): pass def get_pairs_from_paths(images_path, segs_path, ignore_non_matching=False): """ Find all the images from the images_path directory and the s...
if do_augment: im, seg[:, :, 0] = augment_seg(im, seg[:, :, 0], augmentation_name) X.append(get_image_array(im, input_width, input_height, ordering=IMAGE_ORDERING)) Y.append(get_segm...
im = cv2.imread(im, 1) seg = cv2.imread(seg, 1)
random_line_split
data_loader.py
[(random.randint(0, 255), random.randint( 0, 255), random.randint(0, 255)) for _ in range(5000)] nprandomseed = 2019 class DataLoaderError(Exception): pass def get_pairs_from_paths(images_path, segs_path, ignore_non_matching=False): """ Find all the images from the images_path directory and th...
img[:, :, 1] -= 116.779 img[:, :, 2] -= 123.68 img = img[:, :, ::-1] elif imgNorm == "divide": img = cv2.resize(img, (width, height)) img = img.astype(np.float32) img = img/255.0 if ordering == 'channels_first': img = np.rollaxis(img, 2, 0) return img...
""" Load image array from input """ if type(image_input) is np.ndarray: # It is already an array, use it as it is img = image_input elif isinstance(image_input, six.string_types): if not os.path.isfile(image_input): raise DataLoaderError("get_image_array: path {0} doesn't ex...
identifier_body
authorization.rs
<'a>() -> &'a str { "sid" } } /// ## Cookie Data /// The AuthorizeCookie trait is used with a custom data structure that /// will contain the data in the cookie. This trait provides methods /// to store and retrieve a data structure from a cookie's string contents. /// /// Using a request guard a route c...
cookie_id
identifier_name
authorization.rs
&'a str { /// "asid" /// } /// } /// /// // Implement AuthorizeCookie for the AdministratorCookie /// // This code can be changed to use other serialization formats /// impl AuthorizeCookie for AdministratorCookie { /// fn store_cookie(&self) -> String { /// ...
/// // Change the return type to match your type /// fn from_request(request: &'a Request<'r>) -> ::rocket::request::Outcome<AdministratorCookie,Self::Error>{ /// let cid = AdministratorCookie::cookie_id(); /// let mut cookies = request.cookies(); /// /// mat...
/// type Error = ();
random_line_split
authorization.rs
.username, &self.password); /// if &self.username == "administrator" && &self.password != "" { /// Ok( /// AdministratorCookie { /// userid: 1, /// username: "administrator".to_string(), /// display: ...
{ pass = A::clean_password(&value.url_decode().unwrap_or(String::new())); }
conditional_block
authorization.rs
-> &'a str { /// "asid" /// } /// } /// /// // Implement AuthorizeCookie for the AdministratorCookie /// // This code can be changed to use other serialization formats /// impl AuthorizeCookie for AdministratorCookie { /// fn store_cookie(&self) -> String { /// ...
} /// ## Form Data /// The AuthorizeForm trait handles collecting a submitted login form into a /// data structure and authenticating the credentials inside. It also contains /// default methods to process the login and conditionally redirecting the user /// to the correct page depending upon successful authenticat...
{ cookies.remove_private( Cookie::named( Self::cookie_id() ) ); }
identifier_body
binder.rs
capability::{ CapabilityProvider, CapabilitySource, ComponentCapability, InternalCapability, OptionalTask, }, channel, model::{ component::{BindReason, WeakComponentInstance}, error::ModelError, hooks::{Event, EventPayload, EventType, ...
.expect("task is empty") .await; let client
{ let fixture = BinderCapabilityTestFixture::new(vec![( "root", ComponentDeclBuilder::new() .add_lazy_child("target") .add_lazy_child("unresolvable") .build(), )]) .await; let (client_end, mut server_end) = ...
identifier_body
binder.rs
capability::{ CapabilityProvider, CapabilitySource, ComponentCapability, InternalCapability, OptionalTask, }, channel, model::{ component::{BindReason, WeakComponentInstance}, error::ModelError, hooks::{Event, EventPayload, EventType, ...
#[async_trait] impl CapabilityProvider for BinderCapabilityProvider { async fn open( self: Box<Self>, _flags: u32, _open_mode: u32, _relative_path: PathBuf, server_end: &mut zx::Channel, ) -> Result<OptionalTask, ModelError> { let host = self.host.clone(); ...
}
random_line_split
binder.rs
capability::{ CapabilityProvider, CapabilitySource, ComponentCapability, InternalCapability, OptionalTask, }, channel, model::{ component::{BindReason, WeakComponentInstance}, error::ModelError, hooks::{Event, EventPayload, EventType, ...
else { Ok(capability_provider) } } } #[async_trait] impl Hook for BinderCapabilityHost { async fn on(self: Arc<Self>, event: &Event) -> Result<(), ModelError> { if let Ok(EventPayload::CapabilityRouted { source: CapabilitySource::Framework { capability, component }, ...
{ let model = self.model.upgrade().ok_or(ModelError::ModelNotAvailable)?; let target = WeakComponentInstance::new(&model.look_up(&target_moniker.to_partial()).await?); Ok(Some(Box::new(BinderCapabilityProvider::new(source, target, self.clone())) as Box...
conditional_block