file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
scr.py
from PyLnD.loads.rf_functions import rf_mdof from PyLnD.loads.pfile import modal_p from PyLnD.loads.phi import PHI from PyLnD.loads.hwlist import HWLIST from PyLnD.loads.ltm import LTM from PyLnD.loads.eig import EIG from PyLnD.loads.pfile import PFILE from pylab import * class SCR: """Screening Class ...
(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
import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http'; import { AuthService } from '../auth.service'; import { NgxSpinnerService } from 'ngx-spinner'; import { UploadedFloorPlanService } from '../uploaded-f...
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
import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http'; import { AuthService } from '../auth.service'; import { NgxSpinnerService } from 'ngx-spinner'; import { UploadedFloorPlanService } from '../uploaded-f...
(orgId){ var that=this; that.lastLogins=[]; that.allUsers=[]; that.http.post('http://'+that.server+'/'+environment.rbacRoot+'/listUsers.php?org_id='+orgId, JSON.stringify({}), { responseType: 'json' }).map(response => { that.spinner.hide(); var no_of_times={}; ...
fillGraphData
identifier_name
unauthorized-view.component.ts
import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http'; import { AuthService } from '../auth.service'; import { NgxSpinnerService } from 'ngx-spinner'; import { UploadedFloorPlanService } from '../uploaded-f...
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
# Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ TestGyp.py: a testing framework for GYP integration tests. """ from contextlib import contextmanager import os import shutil import subprocess import sys imp...
(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
# Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ TestGyp.py: a testing framework for GYP integration tests. """ from contextlib import contextmanager import os import shutil import subprocess import sys imp...
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
# Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ TestGyp.py: a testing framework for GYP integration tests. """ from contextlib import contextmanager import os import shutil import subprocess import sys imp...
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
# Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ TestGyp.py: a testing framework for GYP integration tests. """ from contextlib import contextmanager import os import shutil import subprocess import sys imp...
# Neither GYP_MSVS_VERSION nor the path help us out. Iterate through # the choices looking for a match. for version in sorted(possible_paths, reverse=True): path = possible_paths[version] for r in possible_roots: build_tool = os.path.join(r, path) if os.path.exists(build_tool): uses_...
print ('Warning: Environment variable GYP_MSVS_VERSION specifies "%s" ' 'but corresponding "%s" was not found.' % (msvs_version, path))
conditional_block
table.rs
use std::sync::Arc; use arrow::array::*; use arrow::datatypes::*; use arrow::record_batch::RecordBatch; use crate::error::*; #[derive(Clone)]
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
use std::sync::Arc; use arrow::array::*; use arrow::datatypes::*; use arrow::record_batch::RecordBatch; use crate::error::*; #[derive(Clone)] pub struct ChunkedArray { chunks: Vec<Arc<dyn Array>>, num_rows: usize, null_count: usize, } impl ChunkedArray { /// Construct a `ChunkedArray` from a list of...
(&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
use std::sync::Arc; use arrow::array::*; use arrow::datatypes::*; use arrow::record_batch::RecordBatch; use crate::error::*; #[derive(Clone)] pub struct ChunkedArray { chunks: Vec<Arc<dyn Array>>, num_rows: usize, null_count: usize, } impl ChunkedArray { /// Construct a `ChunkedArray` from a list of...
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
use std::sync::Arc; use arrow::array::*; use arrow::datatypes::*; use arrow::record_batch::RecordBatch; use crate::error::*; #[derive(Clone)] pub struct ChunkedArray { chunks: Vec<Arc<dyn Array>>, num_rows: usize, null_count: usize, } impl ChunkedArray { /// Construct a `ChunkedArray` from a list of...
/// Slice the table from an offset pub fn slice(&self, offset: usize, limit: usize) -> Self { Self { schema: self.schema.clone(), columns: self .columns .clone() .into_iter() .map(|col| col.slice(offset, Some(limit...
{ // TODO validate that schema and columns match Self { schema, columns } }
identifier_body
client.rs
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0. use std::sync::Arc; use log::debug; use log::info; use crate::backoff::DEFAULT_REGION_BACKOFF; use crate::config::Config; use crate::pd::PdClient; use crate::pd::PdRpcClient; use crate::proto::pdpb::Timestamp; use crate::request::plan::CleanupLocksRe...
/// 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
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0. use std::sync::Arc; use log::debug; use log::info; use crate::backoff::DEFAULT_REGION_BACKOFF; use crate::config::Config; use crate::pd::PdClient; use crate::pd::PdRpcClient; use crate::proto::pdpb::Timestamp; use crate::request::plan::CleanupLocksRe...
Ok(res) } pub async fn cleanup_locks( &self, range: impl Into<BoundRange>, safepoint: &Timestamp, options: ResolveLocksOptions, ) -> Result<CleanupLocksResult> { debug!("invoking cleanup async commit locks"); // scan all locks with ts <= safepoint ...
{ info!("new safepoint != user-specified safepoint"); }
conditional_block
client.rs
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0. use std::sync::Arc; use log::debug; use log::info; use crate::backoff::DEFAULT_REGION_BACKOFF; use crate::config::Config; use crate::pd::PdClient; use crate::pd::PdRpcClient; use crate::proto::pdpb::Timestamp; use crate::request::plan::CleanupLocksRe...
/// 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
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0. use std::sync::Arc; use log::debug; use log::info; use crate::backoff::DEFAULT_REGION_BACKOFF; use crate::config::Config; use crate::pd::PdClient; use crate::pd::PdRpcClient; use crate::proto::pdpb::Timestamp; use crate::request::plan::CleanupLocksRe...
<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
/* * scale clipping limits plugin (August 17, 2018) */ /*global $, JS9, sprintf */ "use strict"; // create our namespace, and specify some meta-information and params JS9.ScaleLimits = {}; JS9.ScaleLimits.CLASS = "JS9"; // class of plugins (1st part of div class) JS9.ScaleLimits.NAME = "Scale"; // name of...
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
/* * scale clipping limits plugin (August 17, 2018) */ /*global $, JS9, sprintf */ "use strict"; // create our namespace, and specify some meta-information and params JS9.ScaleLimits = {}; JS9.ScaleLimits.CLASS = "JS9"; // class of plugins (1st part of div class) JS9.ScaleLimits.NAME = "Scale"; // name of...
x = this.plotWidth * JS9.ScaleLimits.XTEXTFRAC; y = this.plotHeight * JS9.ScaleLimits.YTEXTFRAC; ctx.clearRect(x, y, w, h); ctx.fillText(s, x, y); ctx.restore(); this.lastTextWidth = w; }); this.timeout = window.setTimeout( () => { this.plot = $.plot(el, [pobj], popts); this.timeout = null; annotate(t...
h = JS9.ScaleLimits.XTEXTHEIGHT + 2;
random_line_split
DataFrameExplored_dfprep-checkpoint.py
# ********************************************************************************** # # # # Project: Data Frame Explorer # # Author: Pawel Rosikiewicz ...
# Function, ........................................................................................... def drop_columns(*, df, columns_to_drop, verbose=True): """ Small function to quickly remove columns from, by column names stored in the list - created to give in...
''' 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
# ********************************************************************************** # # # # Project: Data Frame Explorer # # Author: Pawel Rosikiewicz ...
(*, 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
# ********************************************************************************** # # # # Project: Data Frame Explorer # # Author: Pawel Rosikiewicz ...
# info and return if verbose==True: print(df.shape) else: pass return df # Function, ........................................................................................... def drop_columns(*, df, columns_to_drop, verbose=True): """ Small fun...
pass
conditional_block
DataFrameExplored_dfprep-checkpoint.py
# ********************************************************************************** # # # # Project: Data Frame Explorer # # Author: Pawel Rosikiewicz ...
# 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
// Copyright 2021 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use { async_utils::hanging_get::client::HangingGetStream, fidl::endpoints::create_proxy, fidl_fuchsia_math as fmath, fidl_fuchsia_sysmem as fsy...
// 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
// Copyright 2021 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use { async_utils::hanging_get::client::HangingGetStream, fidl::endpoints::create_proxy, fidl_fuchsia_math as fmath, fidl_fuchsia_sysmem as fsy...
(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
// Copyright 2021 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use { async_utils::hanging_get::client::HangingGetStream, fidl::endpoints::create_proxy, fidl_fuchsia_math as fmath, fidl_fuchsia_sysmem as fsy...
fn draw(&mut self, expected_presentation_time: zx::Time) { trace::duration!("gfx", "FlatlandViewProvider::draw"); let time_since_last_draw_in_seconds = ((expected_presentation_time.into_nanos() - self.last_expected_presentation_time.into_nanos()) as f32) / 1_000...
{ 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
/* * Copyright 2019 The Sugarkube Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agre...
(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
/* * Copyright 2019 The Sugarkube Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agre...
// Returns a boolean indicating whether the cluster is already online func (p EksProvisioner) IsAlreadyOnline(dryRun bool) (bool, error) { // todo - test access by running kubectl get ns if dryRun { // say we'll check but don't actually check log.Logger.Debug("[Dry run] Checking whether a cluster config already...
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
/* * Copyright 2019 The Sugarkube Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agre...
return errors.WithStack(err) } } else { log.Logger.Infof("%sNo way to test deleting EKS clusters with eksctl. Pass --yes to actually delete it", dryRunPrefix) } if approved { log.Logger.Infof("%sEKS cluster deleted...", dryRunPrefix) } else { log.Logger.Infof("%sEKS cluster deletions cannot be tested. R...
os.Stderr, "", eksCommandTimeoutSecondsLong, 0, dryRun) if err != nil {
random_line_split
eks.go
/* * Copyright 2019 The Sugarkube Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agre...
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
use std::{ collections::HashMap, fmt::{self, Debug, Formatter}, fs::File, io::{prelude::*, BufReader}, num::ParseIntError, str::FromStr, }; #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)] struct Point { x: i64, y: i64, } impl Point { fn manhattan_distance(&self) -> u64 { ...
} macro_rules! route_vec { (@route R $num:expr) => { Route::Right($num) }; (@route L $num:expr) => { Route::Left($num) }; (@route U $num:expr) => { Route::Up($num) }; (@route D $num:expr) => { Route::Down($n...
random_line_split
main.rs
use std::{ collections::HashMap, fmt::{self, Debug, Formatter}, fs::File, io::{prelude::*, BufReader}, num::ParseIntError, str::FromStr, }; #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)] struct Point { x: i64, y: i64, } impl Point { fn
(&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
var setHeader = function(xhr) { xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); xhr.setRequestHeader('Accept', 'application/sparql-results+json'); xhr.withCredentials = true; }; var setUploadHeader = function(xhr) { xhr.withCredentials = true; }; var setTextHeader = function(xhr) { xhr...
}; self.updateSearch = function(paramstext) { var params = JSON.parse(paramstext); var i24; for (i24 = 0; self.journals().length; i24++) { self.journals.pop(); } var i25; for (i25 = 0; i25 < params.journals.length; i25++) { var journal = params.journals[i25]; self.journals.push(new JournalVM(jour...
random_line_split
viewModels.js
var setHeader = function(xhr) { xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); xhr.setRequestHeader('Accept', 'application/sparql-results+json'); xhr.withCredentials = true; }; var setUploadHeader = function(xhr) { xhr.withCredentials = true; }; var setTextHeader = function(xhr) { xhr...
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
// Copyright 2019 The GoKi Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // originally based on golang.org/x/exp/shiny: // Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style //...
wsz.X, wsz.Y = w.glw.GetSize() // fmt.Printf("win size: %v\n", wsz) w.WnSize = wsz // todo: this doesn't work on mac -- ignores the size -- uses glw directly probably // if curDevPixRatio != w.DevPixRatio && curDevPixRatio > 0 { // rr := w.DevPixRatio / curDevPixRatio // w.WnSize.X = int(float32(w.WnSize.X) * ...
random_line_split
window.go
// Copyright 2019 The GoKi Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // originally based on golang.org/x/exp/shiny: // Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style //...
(sz image.Point) { if w.IsClosed() { return } sc := w.getScreen() sz.X = int(float32(sz.X) / sc.DevicePixelRatio) sz.Y = int(float32(sz.Y) / sc.DevicePixelRatio) w.SetSize(sz) } func (w *windowImpl) SetPos(pos image.Point) { if w.IsClosed() { return } // note: anything run on main only doesn't need lock -...
SetPixSize
identifier_name
window.go
// Copyright 2019 The GoKi Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // originally based on golang.org/x/exp/shiny: // Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style //...
} if !got { sc = theApp.screens[0] w.LogDPI = sc.LogicalDPI if monitorDebug { log.Printf("glos window: %v getScreen(): reverting to first screen %v\n", w.Nm, sc.Name) } } } } w.scrnName = sc.Name w.PhysDPI = sc.PhysicalDPI w.DevPixRatio = sc.DevicePixelRatio if w.LogDPI == 0 { w....
{ 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
// Copyright 2019 The GoKi Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // originally based on golang.org/x/exp/shiny: // Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style //...
func (w *windowImpl) SetCloseCleanFunc(fun func(win oswin.Window)) { w.mu.Lock() defer w.mu.Unlock() w.closeCleanFunc = fun } func (w *windowImpl) CloseReq() { if theApp.quitting { w.Close() } if w.closeReqFunc != nil { w.closeReqFunc(w) } else { w.Close() } } func (w *windowImpl) CloseClean() { if w...
{ w.mu.Lock() defer w.mu.Unlock() w.closeReqFunc = fun }
identifier_body
translate.rs
use rustast; use rustast::DUMMY_SP; use rustast::AstBuilder; pub use self::RustUse::*; pub use self::Expr::*; pub struct Grammar { pub imports: Vec<RustUse>, pub rules: Vec<Rule>, } #[deriving(Clone)] pub enum RustUse { RustUseSimple(String), RustUseGlob(String), RustUseList(String, Vec<String>), } pub struct R...
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
use rustast; use rustast::DUMMY_SP; use rustast::AstBuilder; pub use self::RustUse::*; pub use self::Expr::*; pub struct Grammar { pub imports: Vec<RustUse>, pub rules: Vec<Rule>, } #[deriving(Clone)] pub enum RustUse { RustUseSimple(String), RustUseGlob(String), RustUseList(String, Vec<String>), } pub struct
{ 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
use rustast; use rustast::DUMMY_SP; use rustast::AstBuilder; pub use self::RustUse::*; pub use self::Expr::*; pub struct Grammar { pub imports: Vec<RustUse>, pub rules: Vec<Rule>, } #[deriving(Clone)] pub enum RustUse { RustUseSimple(String), RustUseGlob(String), RustUseList(String, Vec<String>), } pub struct R...
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
from django.http import request from django.shortcuts import render, redirect from home.models import profiles, products, faq from orderapp.models import 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 Passwor...
# 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
from django.http import request from django.shortcuts import render, redirect from home.models import profiles, products, faq from orderapp.models import 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 Passwor...
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
from django.http import request from django.shortcuts import render, redirect from home.models import profiles, products, faq from orderapp.models import 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 Passwor...
(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.http import request from django.shortcuts import render, redirect from home.models import profiles, products, faq from orderapp.models import 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 Passwor...
def logout(request): auth.logout(request) return redirect('/')
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
use std::fs ; use std::collections::HashMap; use std::collections::HashSet; use std::iter::FromIterator; use std::iter::Iterator; use ndarray::Array2; use rayon; use rayon::prelude::*; use flate2::read::GzDecoder; use std::io::prelude::*; use glob::glob; use pyo3::prelude::*; use pyo3::wrap_pyfunction; #[derive(Debug)...
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
use std::fs ; use std::collections::HashMap; use std::collections::HashSet; use std::iter::FromIterator; use std::iter::Iterator; use ndarray::Array2; use rayon; use rayon::prelude::*; use flate2::read::GzDecoder; use std::io::prelude::*; use glob::glob; use pyo3::prelude::*; use pyo3::wrap_pyfunction; #[derive(Debug)...
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
use std::fs ; use std::collections::HashMap; use std::collections::HashSet; use std::iter::FromIterator; use std::iter::Iterator; use ndarray::Array2; use rayon; use rayon::prelude::*; use flate2::read::GzDecoder; use std::io::prelude::*; use glob::glob; use pyo3::prelude::*; use pyo3::wrap_pyfunction; #[derive(Debug)...
(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
use std::fs ; use std::collections::HashMap; use std::collections::HashSet; use std::iter::FromIterator; use std::iter::Iterator; use ndarray::Array2; use rayon; use rayon::prelude::*; use flate2::read::GzDecoder; use std::io::prelude::*; use glob::glob; use pyo3::prelude::*; use pyo3::wrap_pyfunction; #[derive(Debug)...
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
use ash::extensions::khr::{Swapchain, XlibSurface}; use ash::extensions::{ext::DebugUtils, khr::Surface}; use ash::version::{DeviceV1_0, EntryV1_0, InstanceV1_0}; use ash::{vk, vk_make_version, Entry}; use std::convert::TryInto; use std::ffi::{CStr, CString}; use std::os::raw::{c_char, c_void}; use std::path::Path; us...
fn create_render_pass(device: &ash::Device) -> vk::RenderPass { // our render pass has a single image, so only one attachment description is // necessary let attachment_descs = [vk::AttachmentDescription::builder() .format(SWAPCHAIN_FORMAT) .samples(vk::SampleCountFlags::TYPE_1) .l...
{ 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
use ash::extensions::khr::{Swapchain, XlibSurface}; use ash::extensions::{ext::DebugUtils, khr::Surface}; use ash::version::{DeviceV1_0, EntryV1_0, InstanceV1_0}; use ash::{vk, vk_make_version, Entry}; use std::convert::TryInto; use std::ffi::{CStr, CString}; use std::os::raw::{c_char, c_void}; use std::path::Path; us...
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
use ash::extensions::khr::{Swapchain, XlibSurface}; use ash::extensions::{ext::DebugUtils, khr::Surface}; use ash::version::{DeviceV1_0, EntryV1_0, InstanceV1_0}; use ash::{vk, vk_make_version, Entry}; use std::convert::TryInto; use std::ffi::{CStr, CString}; use std::os::raw::{c_char, c_void}; use std::path::Path; us...
( message_severity: vk::DebugUtilsMessageSeverityFlagsEXT, message_type: vk::DebugUtilsMessageTypeFlagsEXT, p_callback_data: *const vk::DebugUtilsMessengerCallbackDataEXT, _p_user_data: *mut c_void, ) -> vk::Bool32 { let severity = match message_severity { vk::DebugUtilsMessageSeverityFlagsE...
vulkan_debug_utils_callback
identifier_name
hydrophoneApi.go
package api import ( "context" "encoding/json" "errors" "fmt" "net/http" "net/url" "runtime" "strings" "time" "github.com/mdblp/tide-whisperer-v2/v3/client/tidewhisperer" log "github.com/sirupsen/logrus" "github.com/gorilla/mux" "github.com/microcosm-cc/bluemonday" "github.com/nicksnyder/go-i18n/v2/i1...
//find and validate the token func (a *Api) token(res http.ResponseWriter, req *http.Request) *token.TokenData { td := a.auth.Authenticate(req) if td == nil { statusErr := &status.StatusError{Status: status.NewStatus(http.StatusUnauthorized, STATUS_NO_TOKEN)} a.sendModelAsResWithStatus(res, statusErr, http.Sta...
{ 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
package api import ( "context" "encoding/json" "errors" "fmt" "net/http" "net/url" "runtime" "strings" "time" "github.com/mdblp/tide-whisperer-v2/v3/client/tidewhisperer" log "github.com/sirupsen/logrus" "github.com/gorilla/mux" "github.com/microcosm-cc/bluemonday" "github.com/nicksnyder/go-i18n/v2/i1...
return results } } //Generate a notification from the given confirmation,write the error if it fails func (a *Api) createAndSendNotification(req *http.Request, conf *models.Confirmation, content map[string]string, lang string) bool { log.Printf("trying notification with template '%s' to %s with language '%s'", co...
{ if err = a.addProfile(ctx, results[i]); err != nil { //report and move on log.Println("Error getting profile", err.Error()) } }
conditional_block
hydrophoneApi.go
package api import ( "context" "encoding/json" "errors" "fmt" "net/http" "net/url" "runtime" "strings" "time" "github.com/mdblp/tide-whisperer-v2/v3/client/tidewhisperer" log "github.com/sirupsen/logrus" "github.com/gorilla/mux" "github.com/microcosm-cc/bluemonday" "github.com/nicksnyder/go-i18n/v2/i1...
switch conf.Type { case models.TypePasswordReset: templateName = models.TemplateNamePasswordReset case models.TypePatientPasswordReset: templateName = models.TemplateNamePatientPasswordReset case models.TypePatientPasswordInfo: templateName = models.TemplateNamePatientPasswordInfo case models.TypeCar...
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
package api import ( "context" "encoding/json" "errors" "fmt" "net/http" "net/url" "runtime" "strings" "time" "github.com/mdblp/tide-whisperer-v2/v3/client/tidewhisperer" log "github.com/sirupsen/logrus" "github.com/gorilla/mux" "github.com/microcosm-cc/bluemonday" "github.com/nicksnyder/go-i18n/v2/i1...
(req *http.Request, conf *models.Confirmation, content map[string]string, lang string) bool { 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 te...
createAndSendNotification
identifier_name
mod.rs
// Copyright (c) The XPeer Core Contributors // SPDX-License-Identifier: Apache-2.0 //! Protocol for fire-and-forget style message delivery to a peer //! //! DirectSend protocol takes advantage of [muxers] and [substream negotiation] to build a simple //! best effort message delivery protocol. Concretely, //! //! 1. E...
( 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
// Copyright (c) The XPeer Core Contributors // SPDX-License-Identifier: Apache-2.0 //! Protocol for fire-and-forget style message delivery to a peer //! //! DirectSend protocol takes advantage of [muxers] and [substream negotiation] to build a simple //! best effort message delivery protocol. Concretely, //! //! 1. E...
//! 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
// Copyright (c) The XPeer Core Contributors // SPDX-License-Identifier: Apache-2.0 //! Protocol for fire-and-forget style message delivery to a peer //! //! DirectSend protocol takes advantage of [muxers] and [substream negotiation] to build a simple //! best effort message delivery protocol. Concretely, //! //! 1. E...
; 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
package app import ( "os" "strings" "time" "github.com/gdamore/tcell/v2" "github.com/joakim-ribier/gttp/actions" "github.com/joakim-ribier/gttp/components" "github.com/joakim-ribier/gttp/controllers" "github.com/joakim-ribier/gttp/models" "github.com/joakim-ribier/gttp/services" "github.com/joakim-ribier/gt...
() models.Output { return output } // Log displays UI message to user. func log(message string, status string) { if message != "" { logEventTextPrmt.SetText(utils.FormatLog(message, status)) } } func switchPage(page string) { switch page { case "ExpertRequestView": pages.SwitchToPage("RequestExpertModeViewPa...
getOutput
identifier_name
app.go
package app import ( "os" "strings" "time" "github.com/gdamore/tcell/v2" "github.com/joakim-ribier/gttp/actions" "github.com/joakim-ribier/gttp/components" "github.com/joakim-ribier/gttp/controllers" "github.com/joakim-ribier/gttp/models" "github.com/joakim-ribier/gttp/services" "github.com/joakim-ribier/gt...
func getOutput() models.Output { return output } // Log displays UI message to user. func log(message string, status string) { if message != "" { logEventTextPrmt.SetText(utils.FormatLog(message, status)) } } func switchPage(page string) { switch page { case "ExpertRequestView": pages.SwitchToPage("Request...
{ treeAPICpnt.Refresh() }
identifier_body
app.go
package app import ( "os" "strings" "time" "github.com/gdamore/tcell/v2" "github.com/joakim-ribier/gttp/actions" "github.com/joakim-ribier/gttp/components" "github.com/joakim-ribier/gttp/controllers" "github.com/joakim-ribier/gttp/models" "github.com/joakim-ribier/gttp/services" "github.com/joakim-ribier/gt...
func refreshingTreeAPICpn() { treeAPICpnt.Refresh() } func getOutput() models.Output { return output } // Log displays UI message to user. func log(message string, status string) { if message != "" { logEventTextPrmt.SetText(utils.FormatLog(message, status)) } } func switchPage(page string) { switch page { c...
ctx.PrintTrace("App.refreshingContext." + key) value(output.Context) } }
random_line_split
app.go
package app import ( "os" "strings" "time" "github.com/gdamore/tcell/v2" "github.com/joakim-ribier/gttp/actions" "github.com/joakim-ribier/gttp/components" "github.com/joakim-ribier/gttp/controllers" "github.com/joakim-ribier/gttp/models" "github.com/joakim-ribier/gttp/services" "github.com/joakim-ribier/gt...
if strings.Contains(value, "config") { refreshingConfig() } if strings.Contains(value, "ctx") { refreshingContext() } if strings.Contains(value, "request") { refreshMRDAllViews() } } } func getRootPrmt() *tview.Pages { return rootPrmt }
{ refreshingTreeAPICpn() }
conditional_block
test_1.rs
const USAGE: &str = " Usage: test_1 [--dt N] [--plots] test_1 --help A template for DEM spherical particles modelling. This benchmark is taken from author: XXXX paper: XXXX link: XXXX Description: ----------- Describe the test in a few lines. Method: -------- What specific DEM model is used to model the...
{ 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
const USAGE: &str = " Usage: test_1 [--dt N] [--plots] test_1 --help A template for DEM spherical particles modelling. This benchmark is taken from author: XXXX paper: XXXX link: XXXX Description: ----------- Describe the test in a few lines. Method: -------- What specific DEM model is used to model the...
{ // -------------------------------------- // 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
const USAGE: &str = " Usage: test_1 [--dt N] [--plots] test_1 --help A template for DEM spherical particles modelling. This benchmark is taken from author: XXXX paper: XXXX link: XXXX Description: ----------- Describe the test in a few lines. Method: -------- What specific DEM model is used to model the...
; // ---------------------------------------- // 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
const USAGE: &str = " Usage: test_1 [--dt N] [--plots] test_1 --help A template for DEM spherical particles modelling. This benchmark is taken from author: XXXX paper: XXXX link: XXXX Description: ----------- Describe the test in a few lines. Method: -------- What specific DEM model is used to model the...
// let px = 1000; // fg.save_to_png( // &format!( // "{}/chung_test_4_incident_angle_vs_rebound_angle.png", // &dir_name // ), // px, // px, // ) // .unwrap(); // if args.flag_plots { // fg.show().unwrap(); // } // -------------...
// &[Caption("Al oxide"), Color("blue")], // );
random_line_split
mqtt_dev.py
""" sensor_data_ingest_mqtt_dev """ import argparse import json import random import sys import threading import time from uuid import uuid4 from awscrt import auth, http, io, mqtt from awsiot import mqtt_connection_builder from .topic_config import read_config # setup: received_count = 0 received_all_event = threa...
"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
""" sensor_data_ingest_mqtt_dev """ import argparse import json import random import sys import threading import time from uuid import uuid4 from awscrt import auth, http, io, mqtt from awsiot import mqtt_connection_builder from .topic_config import read_config # setup: received_count = 0 received_all_event = threa...
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
""" sensor_data_ingest_mqtt_dev """ import argparse import json import random import sys import threading import time from uuid import uuid4 from awscrt import auth, http, io, mqtt from awsiot import mqtt_connection_builder from .topic_config import read_config # setup: received_count = 0 received_all_event = threa...
def mqtt_sub(): """ Subscribe and echo messages from the broker using a user-provided topic filter string """ global args args = parse_args() init(args) mqtt_connection = setup_connection(args) connect_future = mqtt_connection.connect() # Future.result() waits until a result is a...
""" 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
""" sensor_data_ingest_mqtt_dev """ import argparse import json import random import sys import threading import time from uuid import uuid4 from awscrt import auth, http, io, mqtt from awsiot import mqtt_connection_builder from .topic_config import read_config # setup: received_count = 0 received_all_event = threa...
(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
import requests from itertools import zip_longest from bs4 import BeautifulSoup from .kana import hiragana, katakana, small_characters, hira2eng, kata2eng import re import urllib import html import json ONYOMI_LOCATOR_SYMBOL = 'On' KUNYOMI_LOCATOR_SYMBOL = 'Kun' JISHO_API = 'https://jisho.org/api/v1/search/words' SCR...
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
import requests from itertools import zip_longest from bs4 import BeautifulSoup from .kana import hiragana, katakana, small_characters, hira2eng, kata2eng import re import urllib import html import json ONYOMI_LOCATOR_SYMBOL = 'On' KUNYOMI_LOCATOR_SYMBOL = 'Kun' JISHO_API = 'https://jisho.org/api/v1/search/words' SCR...
"""Take the meanings list from the DOM and clean out non-informative meanings.""" index = self._get_meaning_cutoff_index(meanings_list) if index: return [m for i, m in enumerate(meanings_list) if i < index] else: return meanings_list def _get_meaning_cutof...
, meanings_list):
identifier_name
jisho.py
import requests from itertools import zip_longest from bs4 import BeautifulSoup from .kana import hiragana, katakana, small_characters, hira2eng, kata2eng import re import urllib import html import json ONYOMI_LOCATOR_SYMBOL = 'On' KUNYOMI_LOCATOR_SYMBOL = 'Kun' JISHO_API = 'https://jisho.org/api/v1/search/words' SCR...
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
import requests from itertools import zip_longest from bs4 import BeautifulSoup from .kana import hiragana, katakana, small_characters, hira2eng, kata2eng import re import urllib import html import json ONYOMI_LOCATOR_SYMBOL = 'On' KUNYOMI_LOCATOR_SYMBOL = 'Kun' JISHO_API = 'https://jisho.org/api/v1/search/words' SCR...
= "deep": for r in results: fmtd_results.append(self._extract_dictionary_information(r)) # If there are more than 20 results on the page, there is no "More Words" link more = self.html.select_one(".more") while more: link = more.get(...
lf._extract_dictionary_information(r)) elif depth =
conditional_block
main_window_test.py
# Created By: Eric Mc Sween # Created On: 2008-07-12 # Copyright 2014 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "BSD" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.hardcoded.net/licens...
# 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
# Created By: Eric Mc Sween # Created On: 2008-07-12 # Copyright 2014 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "BSD" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.hardcoded.net/licens...
(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
# Created By: Eric Mc Sween # Created On: 2008-07-12 # Copyright 2014 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "BSD" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.hardcoded.net/licens...
# 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
# Created By: Eric Mc Sween # Created On: 2008-07-12 # Copyright 2014 Hardcoded Software (http://www.hardcoded.net) # # This software is licensed under the "BSD" License as described in the "LICENSE" file, # which should be included with this package. The terms are also available at # http://www.hardcoded.net/licens...
@with_app(app_one_transaction) def test_show_account_when_in_ttable(app): app.show_account() app.check_current_pane(PaneType.Account, 'first')
app.show_account('first') app.show_account() app.check_current_pane(PaneType.Account, 'second')
identifier_body
cnn_model.py
from __future__ import print_function from .layers import MoleculeConv from keras.models import Sequential from keras.layers.core import Dense from keras.optimizers import RMSprop, Adam import numpy as np import theano.tensor as T from keras import initializations from keras.utils.visualize_util import plot import jso...
logging.info ('...saved history') logging.info('...saved model to {}.[json, h5, png]'.format(fpath)) def save_model_history_manual(loss, val_loss, fpath): """ 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') l...
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
from __future__ import print_function from .layers import MoleculeConv from keras.models import Sequential from keras.layers.core import Dense from keras.optimizers import RMSprop, Adam import numpy as np import theano.tensor as T from keras import initializations from keras.utils.visualize_util import plot import jso...
def write_loss_report(mean_loss, mean_inner_val_loss, mean_outer_val_loss, mean_test_loss, fpath): """ Write training, validation and test mean loss """ loss_report = open(fpath, 'a') print("{:50} {}".format("Training loss (mse):", mean_loss), file=loss_report) print("{:50} {}".format("Inner Validation loss (m...
""" 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
from __future__ import print_function from .layers import MoleculeConv from keras.models import Sequential from keras.layers.core import Dense from keras.optimizers import RMSprop, Adam import numpy as np import theano.tensor as T from keras import initializations from keras.utils.visualize_util import plot import jso...
(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
from __future__ import print_function from .layers import MoleculeConv from keras.models import Sequential from keras.layers.core import Dense from keras.optimizers import RMSprop, Adam import numpy as np import theano.tensor as T from keras import initializations from keras.utils.visualize_util import plot import jso...
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
//! An incomplete wrapper over the WinRT toast api //! //! Tested in Windows 10 and 8.1. Untested in Windows 8, might work. //! //! Todo: //! //! * Add support for Adaptive Content //! * Add support for Actions //! //! Known Issues: //! //! * Will not work for Windows 7. //! * Will not build when targeting the 32-bit g...
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
//! An incomplete wrapper over the WinRT toast api //! //! Tested in Windows 10 and 8.1. Untested in Windows 8, might work. //! //! Todo: //! //! * Add support for Adaptive Content //! * Add support for Actions //! //! Known Issues: //! //! * Will not work for Windows 7. //! * Will not build when targeting the 32-bit g...
{ /// 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
//! An incomplete wrapper over the WinRT toast api //! //! Tested in Windows 10 and 8.1. Untested in Windows 8, might work. //! //! Todo: //! //! * Add support for Adaptive Content //! * Add support for Actions //! //! Known Issues: //! //! * Will not work for Windows 7. //! * Will not build when targeting the 32-bit g...
cfg(test)] mod tests { use crate::*; use std::path::Path; #[test] fn simple_toast() { let toast = Toast::new(Toast::POWERSHELL_APP_ID); toast .hero( &Path::new(env!("CARGO_MANIFEST_DIR")).join("resources/test/flower.jpeg"), "flower", ...
//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
"""Base test cases for RBTools unit tests.""" import os import re import shutil import sys import tempfile import unittest from contextlib import contextmanager from typing import Dict, Iterator, List, Optional, Union import kgb from rbtools.api.client import RBClient from rbtools.testing.api.transport import URLMap...
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
"""Base test cases for RBTools unit tests.""" import os import re import shutil import sys import tempfile import unittest from contextlib import contextmanager from typing import Dict, Iterator, List, Optional, Union import kgb from rbtools.api.client import RBClient from rbtools.testing.api.transport import URLMap...
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
"""Base test cases for RBTools unit tests.""" import os import re import shutil import sys import tempfile import unittest from contextlib import contextmanager from typing import Dict, Iterator, List, Optional, Union import kgb from rbtools.api.client import RBClient from rbtools.testing.api.transport import URLMap...
def precreate_tempdirs(self, count): """Pre-create a specific number of temporary directories. This will call :py:func:`~rbtools.utils.filesystem.make_tempdir` the specified number of times, returning the list of generated temp paths, and will then spy that function to return thos...
"""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
"""Base test cases for RBTools unit tests.""" import os import re import shutil import sys import tempfile import unittest from contextlib import contextmanager from typing import Dict, Iterator, List, Optional, Union import kgb from rbtools.api.client import RBClient from rbtools.testing.api.transport import URLMap...
(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
import itertools import os import random import six import numpy as np import cv2 import tensorflow as tf try: from tqdm import tqdm except ImportError: print("tqdm not found, disabling progress bars") def tqdm(iter): return iter from keras_segmentation.models.config import IMAGE_ORDERING from ....
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
import itertools import os import random import six import numpy as np import cv2 import tensorflow as tf try: from tqdm import tqdm except ImportError: print("tqdm not found, disabling progress bars") def tqdm(iter): return iter from keras_segmentation.models.config import IMAGE_ORDERING from ....
(X, y): def create_gen(): train_len = X.shape[0] def generator(): k = 0 while True: yield X[k%train_len, ...], y[k%train_len, ...] k += 1 return generator get_shp = lambda item : item.shape[1:] ...
create_pipeline
identifier_name
data_loader.py
import itertools import os import random import six import numpy as np import cv2 import tensorflow as tf try: from tqdm import tqdm except ImportError: print("tqdm not found, disabling progress bars") def tqdm(iter): return iter from keras_segmentation.models.config import IMAGE_ORDERING from ....
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
import itertools import os import random import six import numpy as np import cv2 import tensorflow as tf try: from tqdm import tqdm except ImportError: print("tqdm not found, disabling progress bars") def tqdm(iter): return iter from keras_segmentation.models.config import IMAGE_ORDERING from ....
def get_segmentation_array(image_input, nClasses, width, height, no_reshape=False, loss_type=0): """ Load segmentation array from input """ seg_labels = np.zeros((height, width, nClasses)) if type(image_input) is np.ndarray: # It is already an array, use it as it is ...
""" 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
use rocket::{Request, Outcome}; use rocket::response::{Redirect, Flash}; use rocket::request::{FromRequest, FromForm, FormItems, FormItem}; use rocket::http::{Cookie, Cookies}; use std::collections::HashMap; use std::marker::Sized; use sanitization::*; #[derive(Debug, Clone)] pub struct UserQuery { pub user: Str...
<'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
use rocket::{Request, Outcome}; use rocket::response::{Redirect, Flash}; use rocket::request::{FromRequest, FromForm, FormItems, FormItem}; use rocket::http::{Cookie, Cookies}; use std::collections::HashMap; use std::marker::Sized; use sanitization::*; #[derive(Debug, Clone)] pub struct UserQuery { pub user: Stri...
/// // 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
use rocket::{Request, Outcome}; use rocket::response::{Redirect, Flash}; use rocket::request::{FromRequest, FromForm, FormItems, FormItem}; use rocket::http::{Cookie, Cookies}; use std::collections::HashMap; use std::marker::Sized; use sanitization::*; #[derive(Debug, Clone)] pub struct UserQuery { pub user: Str...
, // _ => {}, a => { // extras.insert( a.to_string(), A::clean_extras( &value.url_decode().unwrap_or(String::new()) ) ); extras.insert( a.to_string(), value.url_decode().unwrap_or(String::new()) ); }, } } ...
{ pass = A::clean_password(&value.url_decode().unwrap_or(String::new())); }
conditional_block
authorization.rs
use rocket::{Request, Outcome}; use rocket::response::{Redirect, Flash}; use rocket::request::{FromRequest, FromForm, FormItems, FormItem}; use rocket::http::{Cookie, Cookies}; use std::collections::HashMap; use std::marker::Sized; use sanitization::*; #[derive(Debug, Clone)] pub struct UserQuery { pub user: Str...
} /// ## 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
// Copyright 2021 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use { crate::{ capability::{ CapabilityProvider, CapabilitySource, ComponentCapability, InternalCapability, OptionalTas...
}
{ 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
// Copyright 2021 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use { crate::{ capability::{ CapabilityProvider, CapabilitySource, ComponentCapability, InternalCapability, OptionalTas...
#[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
// Copyright 2021 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use { crate::{ capability::{ CapabilityProvider, CapabilitySource, ComponentCapability, InternalCapability, OptionalTas...
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