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
simulation2_01.py
#Built-in Libraries import math from random import uniform from random import randrange import argparse import os import string import ctypes #external libraries import numpy import ogr import osr import matplotlib.pyplot as plt import matplotlib.animation as animation import matplotlib.cm as cm import Image from matp...
for job in jobs: job.start() for job in jobs: job.join() create_shapefile(xarr, yarr, args.multi) else: #Visualization - setup the plot fig = plt.figure(figsize=(15,10)) ax1 = fig.add_subplot(1,2,1) #Points that hit underlying topography pt, = ax1.plot([], [],'ro', markersize=3) xdata, ...
p = multiprocessing.Process(target=strom_multi, args=(xarr,yarr,slice(i, i+step)), ) jobs.append(p)
conditional_block
simulation2_01.py
#Built-in Libraries import math from random import uniform from random import randrange import argparse import os import string import ctypes #external libraries import numpy import ogr import osr import matplotlib.pyplot as plt import matplotlib.animation as animation import matplotlib.cm as cm import Image from matp...
def calc_height(distance, ejectionangle, g, ejectionvelocity): ''' height@x = initital_height + distance(tan(theta)) - ((g(x^2))/(2(v(cos(theta))^2)) initial_height = 0, a planar surface is fit to some reference elevation. distance is in meters angle is in radians ''' trajectory = numpy.linspace(0,distance,...
for index in range(len(xarr[i])): #distance and coordinates distance, angle, elevation = calc_distance() azimuth = random_azimuth() Xcoordinate = distance * math.sin(azimuth * math.pi/180) #Conversion to radians Ycoordinate = distance * math.cos(azimuth* math.pi/180) #The WAC visible spectrum data is 10...
identifier_body
simulation2_01.py
#Built-in Libraries import math from random import uniform from random import randrange import argparse import os import string import ctypes #external libraries import numpy import ogr import osr import matplotlib.pyplot as plt import matplotlib.animation as animation import matplotlib.cm as cm import Image from matp...
(data): if data == False: density(m2,xdata, ydata, args.shapefile, args.ppg) else: #x, y are in degrees from the false origin 0,0 x,y, angle, azimuth, elevation, distance = data rand_index = randrange(0,10) #Randomly select the origin point along the linear vent xorigin, yorigin = (xpt[ran...
run
identifier_name
graph.go
package main import ( "fmt" "math" "strconv" ) // 逻辑不是很严谨 越界的没考虑-- scanf // 边节点结构 type EdgeTableNode struct { index int // 顶点索引 weight int // 权重 edgeTableNode *EdgeTableNode // 下一个临界点的指针 } // 顶点的数据信息 type VertInfo struct { value int name string } // 顶点节点 type VertNod...
node := this.head this.head = this.head.next return node } type Queue struct { link *linkedList } func NewQueue() *Queue { return &Queue{link: NewLinkList()} } //加入队列 func (this *Queue) Put(value MapParent) { this.link.Add(value) } //pop出队列 func (this *Queue) Pop() *linkNode { return this.link.Delete() } ...
}
identifier_name
graph.go
package main import ( "fmt" "math" "strconv" ) // 逻辑不是很严谨 越界的没考虑-- scanf // 边节点结构 type EdgeTableNode struct { index int // 顶点索引 weight int // 权重 edgeTableNode *EdgeTableNode // 下一个临界点的指针 } // 顶点的数据信息 type VertInfo struct { value int name string } // 顶点节点 type VertNod...
{ fmt.Println("打印环") for _, sli := range this.allCircle { fmt.Println(sli) } } // 遍历整个图使用深度优先算法 func (this *Graph) Dfs(v int) { if this.visted[v] == 1 { return } this.visted[v] = 1 edge := this.vertNode[v].edgeTableNode for edge != nil { this.Dfs(edge.index) edge = edge.edgeTableNode } } // 遍历图 fun...
.Itoa(i) fmt.Println(*vert) this.vertNode = append(this.vertNode, vert) } // 边初始化 var startVert int var endVert int var weight int var n int for i := 0; i < this.edgeNum; i++ { n, _ = fmt.Scanf("%d %d %d", &startVert, &endVert, &weight) fmt.Printf("%d %d %d\n", startVert, endVert, n) var edgeNode ...
identifier_body
graph.go
package main import ( "fmt" "math" "strconv" ) // 逻辑不是很严谨 越界的没考虑-- scanf // 边节点结构 type EdgeTableNode struct { index int // 顶点索引 weight int // 权重 edgeTableNode *EdgeTableNode // 下一个临界点的指针 } // 顶点的数据信息 type VertInfo struct { value int name string } // 顶点节点 type VertNod...
} } return minCostIndex } func (this *Graph) Dijkstra(start, end int) []int { if start >= this.vertNum || start < 0 || end >= this.vertNum || end < 0 { return nil } // 除起点外所有要到达的节点的对应权重 mapCosts := make(map[int]float64) // 从哪个节点到这个节点的映射关系 // key值与上面的mapCosts一样 mapParent := make(map[int]float64) // 匿名函数初...
random_line_split
graph.go
package main import ( "fmt" "math" "strconv" ) // 逻辑不是很严谨 越界的没考虑-- scanf // 边节点结构 type EdgeTableNode struct { index int // 顶点索引 weight int // 权重 edgeTableNode *EdgeTableNode // 下一个临界点的指针 } // 顶点的数据信息 type VertInfo struct { value int name string } // 顶点节点 type VertNod...
for !stack.IsEmpty() { elemet := stack.Get() node := this.vertNode[elemet.(int)].edgeTableNode for node != nil && this.visted[node.index] == 1 { node = node.edgeTableNode } if node != nil && this.visted[node.index] == 0 { this.visted[node.index] = 1 stack.Push(node.index) } else { ...
this.visted[i] = 1
conditional_block
lesson2-rf_interpretation.py
# **Important: This notebook will only work with fastai-0.7.x. Do not try to run any fastai-1.x code from this path in the repository because it will load fastai-0.7.x** # # Random Forest Model interpretation # %load_ext autoreload # %autoreload 2 # + # %matplotlib inline from fastai.imports import * from fastai.st...
def get_scores(m, config=None): res = { 'config': [config], 'rmse_train': [rmse(m.predict(X_train), y_train)], 'rmse_dev': [rmse(m.predict(X_valid), y_valid)], 'r2_train': [m.score(X_train, y_train)], 'r2_dev': [m.score(X_valid, y_valid)], 'r2_oob': [None], ...
return math.sqrt(((x-y)**2).mean())
identifier_body
lesson2-rf_interpretation.py
# **Important: This notebook will only work with fastai-0.7.x. Do not try to run any fastai-1.x code from this path in the repository because it will load fastai-0.7.x** # # Random Forest Model interpretation # %load_ext autoreload # %autoreload 2 # + # %matplotlib inline from fastai.imports import * from fastai.st...
def plot_pdp_old(feat, clusters=None, feat_name=None): feat_name = feat_name or feat p = pdp.pdp_isolate(m, x, feat) return pdp.pdp_plot(p, feat_name, plot_lines=True, cluster=clusters is not None, n_cluster_centers=clusters) def plot_pdp(feat, clusters = N...
x = get_sample(X_train[X_train.YearMade>1930], 500)
random_line_split
lesson2-rf_interpretation.py
# **Important: This notebook will only work with fastai-0.7.x. Do not try to run any fastai-1.x code from this path in the repository because it will load fastai-0.7.x** # # Random Forest Model interpretation # %load_ext autoreload # %autoreload 2 # + # %matplotlib inline from fastai.imports import * from fastai.st...
(m, config=None): res = { 'config': [config], 'rmse_train': [rmse(m.predict(X_train), y_train)], 'rmse_dev': [rmse(m.predict(X_valid), y_valid)], 'r2_train': [m.score(X_train, y_train)], 'r2_dev': [m.score(X_valid, y_valid)], 'r2_oob': [None], 'n_trees':[m.n_e...
get_scores
identifier_name
lesson2-rf_interpretation.py
# **Important: This notebook will only work with fastai-0.7.x. Do not try to run any fastai-1.x code from this path in the repository because it will load fastai-0.7.x** # # Random Forest Model interpretation # %load_ext autoreload # %autoreload 2 # + # %matplotlib inline from fastai.imports import * from fastai.st...
return pd.DataFrame(res) # - df_raw # # Confidence based on tree variance # For model interpretation, there's no need to use the full dataset on each tree - using a subset will be both faster, and also provide better interpretability (since an overfit model will not provide much variance across trees). set_r...
res['r2_oob'][0] = m.oob_score_
conditional_block
app.js
function appViewModel() { var self = this; var map, city, infowindow; var meetupLocations = []; this.meetupEvents = ko.observableArray([]); //initial list of events this.filteredList = ko.observableArray([]); //list filtered by search keyword this.mapMarkers = ko.observableArray([]); //holds all map marke...
//Manages the toggling of the list view, location centering, and search bar on a mobile device. this.mobileShow = ko.observable(false); this.searchBarShow = ko.observable(true); this.mobileToggleList = function() { if(self.mobileShow() === false) { self.mobileShow(true); } else { self....
$.each(self.mapMarkers(), function(key, value) { value.marker.setMap(null); }); self.mapMarkers([]); }
identifier_body
app.js
function appViewModel() { var self = this; var map, city, infowindow; var meetupLocations = []; this.meetupEvents = ko.observableArray([]); //initial list of events this.filteredList = ko.observableArray([]); //list filtered by search keyword this.mapMarkers = ko.observableArray([]); //holds all map marke...
if(self.mobileShow() === false) { self.mobileShow(true); } else { self.mobileShow(false); } }; this.searchToggle = function() { if(self.searchBarShow() === true) { self.searchBarShow(false); } else { self.searchBarShow(true); } }; //Re-center map to current...
random_line_split
app.js
function appViewModel() { var self = this; var map, city, infowindow; var meetupLocations = []; this.meetupEvents = ko.observableArray([]); //initial list of events this.filteredList = ko.observableArray([]); //list filtered by search keyword this.mapMarkers = ko.observableArray([]); //holds all map marke...
lse { self.searchStatus(''); map.panTo(cityCenter); map.setZoom(10); } }; mapInitialize(); } //custom binding highlights the search text on focus ko.bindingHandlers.selectOnFocus = { update: function (element) { ko.utils.registerEventHandler(element, 'focus', function (e...
self.searchStatus('Map is already centered.'); } e
conditional_block
app.js
function appViewModel() { var self = this; var map, city, infowindow; var meetupLocations = []; this.meetupEvents = ko.observableArray([]); //initial list of events this.filteredList = ko.observableArray([]); //list filtered by search keyword this.mapMarkers = ko.observableArray([]); //holds all map marke...
ocation) { var meetupUrl = "https://api.meetup.com/find/groups?key=6f4c634b253677752b591d6a67327&"; var order = "&order=members"; var query = meetupUrl + location + order; $.ajax({ url: query, dataType: 'jsonp', success: function(data) { console.log(data); var le...
tMeetups(l
identifier_name
Router.js
import { HashRouter, Route, Switch, Redirect, withRouter, Link } from 'react-router-dom' import React, { Component } from 'react'; import locales from './locales'; import Bundle from "./lazyload"; import { Icon } from "../src"; import Logo from "./assets/logo.svg"; import ScrollToTop from 'react-scroll-up'; /* eslint ...
istener("hashchange", () => { this.setPage(); }, false); } getLocale(key) { const map = locales[this.state.locale] || {}; return key.split('.').reduce((a, b) => { const parent = map[a]; if (b) { return (parent || {})[b]; } return parent; }); } setPage(fn) { ...
te.locale) { this.setLocale(localStorage.getItem('WUI_LANG') || 'cn'); } }); } componentWillMount() { window.addEventL
identifier_body
Router.js
import { HashRouter, Route, Switch, Redirect, withRouter, Link } from 'react-router-dom' import React, { Component } from 'react'; import locales from './locales'; import Bundle from "./lazyload"; import { Icon } from "../src"; import Logo from "./assets/logo.svg"; import ScrollToTop from 'react-scroll-up'; /* eslint ...
if (routes) { return routes[3] || routes[4]; } return 'quick-start'; } const getLangName = () => localStorage.getItem('WUI_LANG') || 'cn'; const renderMenuLi = (item, idx) => { if (!item.path) return null; if (getPageName(window.location.href) === getPageName(item.path)) { return <li key={`${idx}`} ...
const getPageName = (location) => { const routes = location.match(/(?:\/(.+))?(\/(.+)\?|\/(.+))/);
random_line_split
Router.js
import { HashRouter, Route, Switch, Redirect, withRouter, Link } from 'react-router-dom' import React, { Component } from 'react'; import locales from './locales'; import Bundle from "./lazyload"; import { Icon } from "../src"; import Logo from "./assets/logo.svg"; import ScrollToTop from 'react-scroll-up'; /* eslint ...
super(props); this.state = {}; } componentDidMount() { this.setPage(() => { if (!this.state.locale) { this.setLocale(localStorage.getItem('WUI_LANG') || 'cn'); } }); } componentWillMount() { window.addEventListener("hashchange", () => { this.setPage(); }, false); ...
) {
identifier_name
Router.js
import { HashRouter, Route, Switch, Redirect, withRouter, Link } from 'react-router-dom' import React, { Component } from 'react'; import locales from './locales'; import Bundle from "./lazyload"; import { Icon } from "../src"; import Logo from "./assets/logo.svg"; import ScrollToTop from 'react-scroll-up'; /* eslint ...
const RoutersContainer = withRouter(({ history, location, ...props }) => { const prefixCls = 'w-docs'; return ( <div className={`${prefixCls}`}> <div className={`${prefixCls}-menu-warpper`}> <div className={`${prefixCls}-menu-content`}> <div className={`${prefixCls}-logo`}> ...
<ul key={`${e}`}> <li className="title">{getLang(`category.${e}`)}</li> {_obj[a][e].map((item, item_idx) => renderMenuLi(item, item_idx))} </ul> ) } } } } return html }
conditional_block
mod.rs
//! Storage for span data shared by multiple [`Layer`]s. //! //! ## Using the Span Registry //! //! This module provides the [`Registry`] type, a [`Subscriber`] implementation //! which tracks per-span data and exposes it to [`Layer`]s. When a `Registry` //! is used as the base `Subscriber` of a `Layer` stack, the //! ...
/// Returns a static reference to the span's metadata. pub fn metadata(&self) -> &'static Metadata<'static> { self.data.metadata() } /// Returns the span's name, pub fn name(&self) -> &'static str { self.data.metadata().name() } /// Returns a list of [fields] defined by the...
self.data.id() }
identifier_body
mod.rs
//! Storage for span data shared by multiple [`Layer`]s. //! //! ## Using the Span Registry //! //! This module provides the [`Registry`] type, a [`Subscriber`] implementation //! which tracks per-span data and exposes it to [`Layer`]s. When a `Registry` //! is used as the base `Subscriber` of a `Layer` stack, the //! ...
self) -> Extensions<'_> { self.data.extensions() } /// Returns a mutable reference to this span's `Extensions`. /// /// The extensions may be used by `Layer`s to store additional data /// describing the span. pub fn extensions_mut(&self) -> ExtensionsMut<'_> { self.data.extensio...
tensions(&
identifier_name
mod.rs
//! Storage for span data shared by multiple [`Layer`]s. //! //! ## Using the Span Registry //! //! This module provides the [`Registry`] type, a [`Subscriber`] implementation //! which tracks per-span data and exposes it to [`Layer`]s. When a `Registry` //! is used as the base `Subscriber` of a `Layer` stack, the //! ...
pub use sharded::Registry; /// Provides access to stored span data. /// /// Subscribers which store span data and associate it with span IDs should /// implement this trait; if they do, any [`Layer`]s wrapping them can look up /// metadata via the [`Context`] type's [`span()`] method. /// /// [`Layer`]: ../layer/trait...
#[cfg_attr(docsrs, doc(cfg(feature = "registry")))]
random_line_split
manualtest.py
import os import yaml import sys import random import shutil import openpyxl import yaml import audioanalysis as aa import numpy as np import argparse import logging """ manualtest.py Script to create a listeneing test. The output, test case directory and answer_key.yml file, can be found in the root directory. ma...
sys.exit() switch_A_B = random.randint(0,1) #If one then A and B are switched. This is so scenario one and two alternate thier A and B positions roughly 50% of the time # add the wav files # pick one to duplicate x_answer=random.randint(0,1) if switch_A_B: ...
except FileExistsError: logging.debug("Could not create test case directory at {} - encountered FileExistsError".format(test_case_path)) print("Could not create test case directory at {} - encountered FileExistsError".format(test_case_path))
random_line_split
manualtest.py
import os import yaml import sys import random import shutil import openpyxl import yaml import audioanalysis as aa import numpy as np import argparse import logging """ manualtest.py Script to create a listeneing test. The output, test case directory and answer_key.yml file, can be found in the root directory. m...
(root_directory, scenario_one, scenario_two): logging.info("Enter: _create_temp_dir") # Will create exact copies of both directories specified so files may be altered later adjusted_file_path = os.path.join(root_directory, ADJUSTED_AUDIO_SUBDIR) scenario_one_temp = os.path.join(adjusted_file_path, SCENA...
_create_temp_dir
identifier_name
manualtest.py
import os import yaml import sys import random import shutil import openpyxl import yaml import audioanalysis as aa import numpy as np import argparse import logging """ manualtest.py Script to create a listeneing test. The output, test case directory and answer_key.yml file, can be found in the root directory. m...
def create_manual_tests(): logging.info("Enter: create_manual_tests") global root_directory scenario_one, scenario_two, output_base_path=_collect_locations() output_path = _create_output_directory(output_base_path) # Confirm another answer key does not already exist if os.path.exists(...
""" Method to create A_B_X testing directories and return the corresponding answer key An A file is chosen from either the scenario one or two with a 50/50 probability. The B file is then from the scenario not chosen for A. An X file is then created with a 50/50 probability of being either a duplicate ...
identifier_body
manualtest.py
import os import yaml import sys import random import shutil import openpyxl import yaml import audioanalysis as aa import numpy as np import argparse import logging """ manualtest.py Script to create a listeneing test. The output, test case directory and answer_key.yml file, can be found in the root directory. m...
test_case_path = os.path.join(output_path, str(case_num)) try: os.mkdir(test_case_path) except FileExistsError: logging.debug("Could not create test case directory at {} - encountered FileExistsError".format(test_case_path)) print("Could not create test case ...
logging.info("The amount of cases has exceeded 25. Please note that " "the accompanying excel sheet only has 25 answer slots and that it will need to " "be restructured") print("The amount of cases has exceeded 25. Please note that " "the accompanying excel sheet only ha...
conditional_block
docker_compose.rs
//! Provides utility functions for [ServerPlugin] and [ServerHandle] implementations that use Docker Compose. //! //! These functions all assume that the server has a dedicated directory, which contains a custom shell //! script that wraps `docker-compose` with any setup, environment variables, etc. needed to run thing...
(&self) -> Result<String> { let server_plugin = server_plugin_downcast(self); match run_docker_compose(server_plugin, &["logs", "--no-color"]).with_context(|| { format!( "Running '{} up --detach' failed.", server_plugin .server_script() ...
emit_logs
identifier_name
docker_compose.rs
//! Provides utility functions for [ServerPlugin] and [ServerHandle] implementations that use Docker Compose. //! //! These functions all assume that the server has a dedicated directory, which contains a custom shell //! script that wraps `docker-compose` with any setup, environment variables, etc. needed to run thing...
// Wait (up to a timeout) for the server to be ready. match wait_for_ready(app_state, &server_handle).await { Err(err) => { server_handle.emit_logs_info()?; Err(err) } Ok(_) => { let server_handle: Box<dyn ServerHandle> = Box::new(server_handle); ...
let server_handle = DockerComposeServerHandle { server_plugin: server_plugin.clone(), http_client, };
random_line_split
docker_compose.rs
//! Provides utility functions for [ServerPlugin] and [ServerHandle] implementations that use Docker Compose. //! //! These functions all assume that the server has a dedicated directory, which contains a custom shell //! script that wraps `docker-compose` with any setup, environment variables, etc. needed to run thing...
} /// Runs the specified Docker Compose subcommand with the specified argument, for the specified FHIR Server /// implementation. /// /// Parameters: /// * `server_plugin`: the [DockerComposeServerPlugin] that represents the FHIR Server implementation to run /// the command for/against /// * `args`: the Docker Comp...
{ launch_server(app_state, self).await }
identifier_body
common.go
package common import ( "time" v1 "k8s.io/api/core/v1" ) // Common types and constants used by the importer and controller. // TODO: maybe the vm cloner can use these common values const ( // CDILabelKey provides a constant for CDI PVC labels CDILabelKey = "app" // CDILabelValue provides a constant for CDI PV...
// SyncUploadFormPaths are paths to POST CDI uploads as form data var SyncUploadFormPaths = []string{ UploadFormSync, "/v1alpha1/upload-form", } // AsyncUploadFormPaths are paths to POST CDI uploads as form data in async mode var AsyncUploadFormPaths = []string{ UploadFormAsync, "/v1alpha1/upload-form-async", }
}
random_line_split
zsum_mulcov_rate.py
# SPDX-License-Identifier: AGPL-3.0-or-later # SPDX-FileCopyrightText: University of Washington <https://www.washington.edu> # SPDX-FileContributor: 2014-23 Bradley M. Bell # ---------------------------------------------------------------------------- # {xrst_begin user_zsum_mulcov_rate.py} # {xrst_comment_ch #} # # Co...
{ # smooth_rate_subgroup 'name': 'smooth_rate_subgroup', 'age_id': [ 0 ], 'time_id': [ 0, 1 ], 'fun': fun_rate_subgroup },{ # smooth_rate_parent 'name': 'smooth_rate_p...
} ] # ---------------------------------------------------------------------- # smooth table smooth_table = [
random_line_split
zsum_mulcov_rate.py
# SPDX-License-Identifier: AGPL-3.0-or-later # SPDX-FileCopyrightText: University of Washington <https://www.washington.edu> # SPDX-FileContributor: 2014-23 Bradley M. Bell # ---------------------------------------------------------------------------- # {xrst_begin user_zsum_mulcov_rate.py} # {xrst_comment_ch #} # # Co...
def fun_rate_parent(a, t) : return ('prior_rate_parent', None, 'prior_gauss_diff') import dismod_at # ---------------------------------------------------------------------- # age list age_list = [ 0.0, 50.0, 100.0 ] # # time list time_list = [ 1990.0, 2010.0 ] # # integrand ...
return ('prior_rate_subgroup', None, 'prior_gauss_diff')
identifier_body
zsum_mulcov_rate.py
# SPDX-License-Identifier: AGPL-3.0-or-later # SPDX-FileCopyrightText: University of Washington <https://www.washington.edu> # SPDX-FileContributor: 2014-23 Bradley M. Bell # ---------------------------------------------------------------------------- # {xrst_begin user_zsum_mulcov_rate.py} # {xrst_comment_ch #} # # Co...
import dismod_at # # change into the build/example/user directory if not os.path.exists('build/example/user') : os.makedirs('build/example/user') os.chdir('build/example/user') # ------------------------------------------------------------------------ python_seed = int( time.time() ) random.seed( python_seed ) # --...
sys.path.insert(0, local_dir)
conditional_block
zsum_mulcov_rate.py
# SPDX-License-Identifier: AGPL-3.0-or-later # SPDX-FileCopyrightText: University of Washington <https://www.washington.edu> # SPDX-FileContributor: 2014-23 Bradley M. Bell # ---------------------------------------------------------------------------- # {xrst_begin user_zsum_mulcov_rate.py} # {xrst_comment_ch #} # # Co...
(file_name) : def fun_rate_subgroup(a, t) : return ('prior_rate_subgroup', None, 'prior_gauss_diff') def fun_rate_parent(a, t) : return ('prior_rate_parent', None, 'prior_gauss_diff') import dismod_at # ---------------------------------------------------------------------- # age list age_...
example_db
identifier_name
lookup.rs
use crate::utils::{f64_compare, TValue, TValueType}; use super::*; /// Functionality relating to looking up properties of the `Bezier` or points along the `Bezier`. impl Bezier { /// Convert a euclidean distance ratio along the `Bezier` curve to a parametric `t`-value. pub fn euclidean_to_parametric(&self, ratio: f...
/// Convert a [TValue] to a parametric `t`-value. pub(crate) fn t_value_to_parametric(&self, t: TValue) -> f64 { match t { TValue::Parametric(t) => { assert!((0.0..=1.).contains(&t)); t } TValue::Euclidean(t) => { assert!((0.0..=1.).contains(&t)); self.euclidean_to_parametric(t, DEFAULT_E...
{ if ratio < error { return 0.; } if 1. - ratio < error { return 1.; } let mut low = 0.; let mut mid = 0.; let mut high = 1.; let total_length = self.length(None); while low < high { mid = (low + high) / 2.; let test_ratio = self.trim(TValue::Parametric(0.), TValue::Parametric(mid)).leng...
identifier_body
lookup.rs
use crate::utils::{f64_compare, TValue, TValueType}; use super::*; /// Functionality relating to looking up properties of the `Bezier` or points along the `Bezier`. impl Bezier { /// Convert a euclidean distance ratio along the `Bezier` curve to a parametric `t`-value. pub fn
(&self, ratio: f64, error: f64) -> f64 { if ratio < error { return 0.; } if 1. - ratio < error { return 1.; } let mut low = 0.; let mut mid = 0.; let mut high = 1.; let total_length = self.length(None); while low < high { mid = (low + high) / 2.; let test_ratio = self.trim(TValue::Parame...
euclidean_to_parametric
identifier_name
lookup.rs
use crate::utils::{f64_compare, TValue, TValueType}; use super::*; /// Functionality relating to looking up properties of the `Bezier` or points along the `Bezier`. impl Bezier { /// Convert a euclidean distance ratio along the `Bezier` curve to a parametric `t`-value. pub fn euclidean_to_parametric(&self, ratio: f...
} mid } /// Convert a [TValue] to a parametric `t`-value. pub(crate) fn t_value_to_parametric(&self, t: TValue) -> f64 { match t { TValue::Parametric(t) => { assert!((0.0..=1.).contains(&t)); t } TValue::Euclidean(t) => { assert!((0.0..=1.).contains(&t)); self.euclidean_to_parametri...
{ high = mid; }
conditional_block
lookup.rs
use crate::utils::{f64_compare, TValue, TValueType}; use super::*; /// Functionality relating to looking up properties of the `Bezier` or points along the `Bezier`. impl Bezier { /// Convert a euclidean distance ratio along the `Bezier` curve to a parametric `t`-value. pub fn euclidean_to_parametric(&self, ratio: f...
} else { convergence_count = 0; } } final_t } } #[cfg(test)] mod tests { use super::*; #[test] fn test_evaluate() { let p1 = DVec2::new(3., 5.); let p2 = DVec2::new(14., 3.); let p3 = DVec2::new(19., 14.); let p4 = DVec2::new(30., 21.); let bezier1 = Bezier::from_quadratic_dvec2(p1, p2, p...
convergence_count += 1;
random_line_split
error_handle.py
from typing import Tuple import bpy import os import sys import re from pathlib import Path import traceback import subprocess from . import fn def get_last_traceback(to_clipboad=False) -> Tuple[int, str]: '''Get last traceback error details summed in string return a tuple''' import sys message = '' ...
else: print() return (1, 'No error traceback found by sys module') if hasattr(sys, "last_type") and sys.last_type: error_type = str(sys.last_type) error_type = error_type.replace("<class '", "").replace("'>","") message = f'type {error_type}\n{message}' if hasattr(...
frame = '\n'.join(frame.split(', ')[1:3]) message += f'{frame}\n'
random_line_split
error_handle.py
from typing import Tuple import bpy import os import sys import re from pathlib import Path import traceback import subprocess from . import fn def get_last_traceback(to_clipboad=False) -> Tuple[int, str]: '''Get last traceback error details summed in string return a tuple''' import sys message = '' ...
if not message : print() return (1, 'No message to display') if message and to_clipboad: bpy.context.window_manager.clipboard = message return (0, message) def get_traceback_stack(tb=None): if tb is None: tb = sys.last_traceback stack = [] if tb and tb.tb_fr...
print('use "last_value" line num') message += f'line {str(sys.last_value.lineno)}\n'
conditional_block
error_handle.py
from typing import Tuple import bpy import os import sys import re from pathlib import Path import traceback import subprocess from . import fn def
(to_clipboad=False) -> Tuple[int, str]: '''Get last traceback error details summed in string return a tuple''' import sys message = '' linum = '' if hasattr(sys, "last_traceback") and sys.last_traceback: i = 0 last=sys.last_traceback.tb_next tbo = None while last...
get_last_traceback
identifier_name
error_handle.py
from typing import Tuple import bpy import os import sys import re from pathlib import Path import traceback import subprocess from . import fn def get_last_traceback(to_clipboad=False) -> Tuple[int, str]: '''Get last traceback error details summed in string return a tuple''' import sys message = '' ...
def execute(self, context): if self.path_line: return {"FINISHED"} return {"FINISHED"} def help_error_top_bar(self, context): layout = self.layout if hasattr(sys, 'last_traceback') and sys.last_traceback: region = context.region if region.alignment == 'RIGHT': ...
layout = self.layout col = layout.column() for item in self.error_list: path, line = item[0], item[1] # print(path, ' ', line) goto_line = f'{path}:{line}' box = col.box() boxcol = box.column() boxcol.alignment = '...
identifier_body
assembler.py
# Template by Bruce A. Maxwell, 2015 # implements a simple assembler for the following assembly language # # - One instruction or label per line. # # - Blank lines are ignored. # # - Comments start with a # as the first character and all subsequent # - characters on the line are ignored. # # - Spaces delimit instructi...
# - Negative immediate values must have a preceeding '-' with no space # - between it and the number. # # Language definition: # # LOAD D A - load from address A to destination D # LOADA D A - load using the address register from address A + RE to destination D # STORE S A - store value in S to address A # STOREA S...
#
random_line_split
assembler.py
# Template by Bruce A. Maxwell, 2015 # implements a simple assembler for the following assembly language # # - One instruction or label per line. # # - Blank lines are ignored. # # - Comments start with a # as the first character and all subsequent # - characters on the line are ignored. # # - Spaces delimit instructi...
else: exit() elif token[0]=='add': # Execute C <= A + B, where A, B, C are registers if token[1] in table_e and token[2] in table_e and token[3] in table_b: ass_txt+='1000'+table_e[token[1]]+table_e[token[2]]+'000'+table_b[token[3]] else: exit() elif token[0]=='sub': # Execute C <= A - B...
ass_txt+='0111'+table_d[token[1]]+'0000000000'
conditional_block
assembler.py
# Template by Bruce A. Maxwell, 2015 # implements a simple assembler for the following assembly language # # - One instruction or label per line. # # - Blank lines are ignored. # # - Comments start with a # as the first character and all subsequent # - characters on the line are ignored. # # - Spaces delimit instructi...
# reads through the file and returns a dictionary of all location # labels with their line numbers def pass1( tokens ): # figure out what line number corresponds to each symbol # function variables tkns = [] # actual instructions dict = {} index = 0 print "branching addresses" for t in tokens: # check sy...
tokens = [] # start of the file fp.seek(0) lines = fp.readlines() # strip white space and comments from each line for line in lines: ls = line.strip() uls = '' for c in ls: if c != '#': uls = uls + c else: break # skip blank lines if len(uls) == 0: continue # split on white space ...
identifier_body
assembler.py
# Template by Bruce A. Maxwell, 2015 # implements a simple assembler for the following assembly language # # - One instruction or label per line. # # - Blank lines are ignored. # # - Comments start with a # as the first character and all subsequent # - characters on the line are ignored. # # - Spaces delimit instructi...
( d, linenum ): if d > 0: l = d.bit_length() v = "00000000" v = v[0:8-l] + format( d, 'b' ) elif d == 0: v = "00000000" else: print 'Invalid address on line %d: value is negative' % (linenum) exit() return v # Tokenizes the input data, discarding white space and comments # returns the tokens as a lis...
dec2bin8
identifier_name
agreement.rs
// Copyright 2015-2017 Brian Smith. // // Permission to use, copy, modify, and/or distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAI...
/// The private key. pub fn private_key(&self) -> &PrivateKey<U> { &self.private_key } /// The public key. pub fn public_key(&self) -> &PublicKey { &self.public_key } /// Split the key pair apart. pub fn split(self) -> (PrivateKey<U>, PublicKey) { (self.private_key, self.public_key) } } ///...
{ // NSA Guide Step 1. let private_key = ec::PrivateKey::generate(&alg.curve, rng)?; let mut public_key = PublicKey { bytes: [0; PUBLIC_KEY_MAX_LEN], alg, }; private_key.compute_public_key(&alg.curve, &mut public_key.bytes)?; Ok(Self { ...
identifier_body
agreement.rs
// Copyright 2015-2017 Brian Smith. // // Permission to use, copy, modify, and/or distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAI...
{ bytes: [u8; ec::ELEM_MAX_BYTES], len: usize, } mod sealed { pub trait Sealed {} } impl InputKeyMaterial { /// Calls `kdf` with the raw key material and then returns what `kdf` /// returns, consuming `Self` so that the key material can only be used /// once. pub fn derive<F, R>(self, kdf...
InputKeyMaterial
identifier_name
agreement.rs
// Copyright 2015-2017 Brian Smith. // // Permission to use, copy, modify, and/or distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAI...
}; self.private_key .compute_public_key(&self.alg.curve, &mut public_key.bytes)?; Ok(public_key) } /// Performs a key agreement with an private key and the given public key. /// /// Since `self` is consumed, it will not be usable after calling `agree`. /// //...
alg: self.alg,
random_line_split
agreement.rs
// Copyright 2015-2017 Brian Smith. // // Permission to use, copy, modify, and/or distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAI...
// NSA Guide Prerequisite 2, regarding which KDFs are allowed, is delegated // to the caller. // NSA Guide Prerequisite 3, "Prior to or during the key-agreement process, // each party shall obtain the identifier associated with the other party // during the key-agreement scheme," is delegated to ...
{ return Err(error::Unspecified); }
conditional_block
transformer_dynsparse.py
# Copyright (c) 2020 Graphcore Ltd. All rights reserved. import sys import numpy as np import tensorflow.compat.v1 as tf from tensorflow.compat.v1.initializers import glorot_normal as init_glorot from tensorflow.compat.v1.initializers import variance_scaling from tensorflow.python import ipu from .transformer_baseclass...
def embedding(self, x, src, compute_dense_grad=False, sparse_embeddings=False): # x[batch_size*sequence_length] -> x[batch_size*sequence_length, embedding_length] inshape = x.shape.as_list() assert len(inshape) == 2, f"Input to embedding lookup has shape {inshape}, but should be a 2D tensor" ...
self.encoder_k = None self.encoder_v = None # Dynsparse transformer is both a transformer and a sparse model Transformer.__init__(self, params, *args, **kwargs) SparseModel.__init__(self, params, *args, **kwargs)
identifier_body
transformer_dynsparse.py
# Copyright (c) 2020 Graphcore Ltd. All rights reserved. import sys import numpy as np import tensorflow.compat.v1 as tf from tensorflow.compat.v1.initializers import glorot_normal as init_glorot from tensorflow.compat.v1.initializers import variance_scaling from tensorflow.python import ipu from .transformer_baseclass...
compute_dense_grad, use_bias=self.include_projection_bias, disable_outlining=True) else: x = self.applySparseLinear(x, self.sparse_projection, self.target_vocab_length, ...
# The look-up table is shared with the dense embedding layer if sparse_embeddings: if self.exclude_embedding: x = self.sparseLinear(x, self.sparsity, self.target_vocab_length,
random_line_split
transformer_dynsparse.py
# Copyright (c) 2020 Graphcore Ltd. All rights reserved. import sys import numpy as np import tensorflow.compat.v1 as tf from tensorflow.compat.v1.initializers import glorot_normal as init_glorot from tensorflow.compat.v1.initializers import variance_scaling from tensorflow.python import ipu from .transformer_baseclass...
# Extract heads and transpose [B, S, heads, qkv_len] -> [B, heads, S, qkv_len] batch_size, sequence_length, _ = in_q.shape.as_list() with self.namescope('q'): q = tf.reshape(q, [batch_size, sequence_length, self.attention_heads, self.qkv_length]) q = tf.transpose(q, pe...
with self.namescope('qkv'): # Prepend (head) dimension in_qkv_r = tf.expand_dims(in_q, axis=-2) qkv = self.sparseLinear(in_qkv_r, self.sparsity, 3 * b_shape, compute_dense_grad, use_bias) # Extract q, k and v q, k, v = tf.split(qkv, 3, axis...
conditional_block
transformer_dynsparse.py
# Copyright (c) 2020 Graphcore Ltd. All rights reserved. import sys import numpy as np import tensorflow.compat.v1 as tf from tensorflow.compat.v1.initializers import glorot_normal as init_glorot from tensorflow.compat.v1.initializers import variance_scaling from tensorflow.python import ipu from .transformer_baseclass...
(self, x): # -> x with self.namescope('layernorm'): param_initializers = { "beta": tf.initializers.constant(0.0, x.dtype), "gamma": tf.initializers.constant(0.1, x.dtype) } x = ipu.normalization_ops.group_norm(x, groups=1, param_initializers=p...
norm
identifier_name
read.rs
use std::{ collections::{HashMap, hash_map::Entry}, fmt, fs::File, hash::{Hash, Hasher}, marker::PhantomData, io, path::Path, }; use byteorder::{ByteOrder, LittleEndian, ReadBytesExt}; use crate::{ prelude::*, handle::hsize, io::{ Error, parse::{self, ParseBuf, ...
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("Reader") .field("buf", &self.buf) .field("solid_name", &self.solid_name) .field("is_binary", &self.triangle_count.is_some()) .field("triangle_count", &self.triangle_count) .fini...
} impl<R: io::Read, U: UnifyingMarker> fmt::Debug for Reader<R, U> {
random_line_split
read.rs
use std::{ collections::{HashMap, hash_map::Entry}, fmt, fs::File, hash::{Hash, Hasher}, marker::PhantomData, io, path::Path, }; use byteorder::{ByteOrder, LittleEndian, ReadBytesExt}; use crate::{ prelude::*, handle::hsize, io::{ Error, parse::{self, ParseBuf, ...
<F>(self, triangle_count: u32, mut add_triangle: F) -> Result<(), Error> where F: FnMut(RawTriangle) -> Result<(), Error>, { const BYTES_PER_TRI: usize = 4 * 3 * 4 + 2; let mut buf = self.buf; // We attempt to read as many triangles as specified. If the // specified nu...
read_raw_binary
identifier_name
read.rs
use std::{ collections::{HashMap, hash_map::Entry}, fmt, fs::File, hash::{Hash, Hasher}, marker::PhantomData, io, path::Path, }; use byteorder::{ByteOrder, LittleEndian, ReadBytesExt}; use crate::{ prelude::*, handle::hsize, io::{ Error, parse::{self, ParseBuf, ...
// Read the all triangles into the raw result self.read_raw(|tri| { out.triangles.push(tri); Ok(()) })?; Ok(out) } /// Reads the whole file, passing each triangle to the `add_triangle` /// callback. /// /// This is a low level building bloc...
{ out.triangles.reserve(tri_count as usize); }
conditional_block
hostmon_server.go
// // Host monitor data collection server // Sean Caron scaron@umich.edu // package main import ( "os" "fmt" "strings" "strconv" "bufio" "math" "database/sql" _ "github.com/go-sql-driver/mysql" "net/smtp" "bytes" "log" "time" "encoding/json" "net/http" ) type Message struct { Timestamp...
// For each host, run checks and send notifications for c, _ := range htt { rss, err := dbconn.Query("SELECT * FROM reports WHERE hostname = '" + htt[c] + "' ORDER BY timestamp DESC LIMIT 2") if (err != nil) { log.Fatalf("Fatal attempting to scan and notify 1") } var f0, f1, ...
{ er = rs.Scan(&hh) if (er != nil) { log.Fatalf("Fatal compiling list for scan and notify") } htt = append(htt, hh) }
conditional_block
hostmon_server.go
// // Host monitor data collection server // Sean Caron scaron@umich.edu // package main import ( "os" "fmt" "strings" "strconv" "bufio" "math" "database/sql" _ "github.com/go-sql-driver/mysql" "net/smtp" "bytes" "log" "time" "encoding/json" "net/http" ) type Message struct { Timestamp...
() { //var bindaddr, conffile string var conffile string if (len(os.Args) != 5) { log.Fatalf("Usage: %s -b bindaddr -f configfile", os.Args[0]) } for i := 1; i < len(os.Args); i++ { switch os.Args[i] { //case "-b": //bindaddr = os.Args[i+1] case "-f": conffile = os.Args[i...
main
identifier_name
hostmon_server.go
// // Host monitor data collection server // Sean Caron scaron@umich.edu // package main import ( "os" "fmt" "strings" "strconv" "bufio" "math" "database/sql" _ "github.com/go-sql-driver/mysql" "net/smtp" "bytes" "log" "time" "encoding/json" "net/http" ) type Message struct { Timestamp...
{ eMailConn, eMailErr := smtp.Dial("localhost:25") if eMailErr != nil { log.Printf("SMTP server connection failure sending notification\n") } eMailConn.Mail(g_eMailFrom) eMailConn.Rcpt(g_eMailTo) wc, eMailErr := eMailConn.Data() if eMailErr != nil { log.Printf("Failure initiating DATA stage send...
identifier_body
hostmon_server.go
// // Host monitor data collection server // Sean Caron scaron@umich.edu // package main import ( "os" "fmt" "strings" "strconv" "bufio" "math" "database/sql" _ "github.com/go-sql-driver/mysql" "net/smtp" "bytes" "log" "time" "encoding/json" "net/http" ) type Message struct { Timestamp...
// // Read in the configuration file. // haveParam := make(map[string]bool) confFile, err := os.Open(conffile) if err != nil { log.Fatalf("Failed opening configuration file for reading\n") } inp := bufio.NewScanner(confFile) for inp.Scan() { line := inp.Text() if (len(line) > 0) { ...
} } log.Printf("Host monitor data server starting up\n")
random_line_split
index.ts
'use strict;' import {EditCell, Item} from "/item.js"; import {AppDB} from "/appdb.js"; // Overview section const overviewUI = document.getElementById('overview-main'); // Overview Table element const overviewTable: HTMLTableElement = document.getElementById('overview'); // Setup UI const blankSetup = document.getEle...
enterInitialLoadState() { overviewTable.addEventListener('click', (event) => this.handleTableEventClick(event)); overviewTable.addEventListener('save-edit', this); overviewTable.addEventListener('cancel-edit', this); itemDB.getAll().then(res => { if (res.length === 0)...
{ this.items = new Map(); }
identifier_body
index.ts
'use strict;' import {EditCell, Item} from "/item.js"; import {AppDB} from "/appdb.js"; // Overview section const overviewUI = document.getElementById('overview-main'); // Overview Table element const overviewTable: HTMLTableElement = document.getElementById('overview'); // Setup UI const blankSetup = document.getEle...
fAddItem.querySelector('#add-name').focus(); // Setup form submission handling fAddItem.addEventListener('submit', e => { e.preventDefault(); new FormData(fAddItem); }, {once: true}); fAddItem.addEventListener('formdata', (e) => { this.handle...
// focus form name
random_line_split
index.ts
'use strict;' import {EditCell, Item} from "/item.js"; import {AppDB} from "/appdb.js"; // Overview section const overviewUI = document.getElementById('overview-main'); // Overview Table element const overviewTable: HTMLTableElement = document.getElementById('overview'); // Setup UI const blankSetup = document.getEle...
() { // hide add item form console.log('entered transition Setup -> Normal fn'); console.log(fAddItem); blankSetup.classList.add('hide'); this.enterNormalState(); } enterNormalState() { this.populateInitialTable(); addItem.addEventListener('click', e => ...
transitionFromSetupToNormal
identifier_name
index.ts
'use strict;' import {EditCell, Item} from "/item.js"; import {AppDB} from "/appdb.js"; // Overview section const overviewUI = document.getElementById('overview-main'); // Overview Table element const overviewTable: HTMLTableElement = document.getElementById('overview'); // Setup UI const blankSetup = document.getEle...
else if (e.type == 'cancel-edit') { console.log("handling cancel edit request event"); this.refreshView(); } } handleTableEventClick(e) { console.log("table click event got") console.log(`event type: ${e.type}`); console.log("event target:"); ...
{ this.handleSaveEdit(e); }
conditional_block
setup_groupsched.py
#! /bin/env python """setup_groupsched.py @author: Dillon Hicks @summary: This script wraps the old setup script with the new setup_module.py.tpl template. This allow there to be extra arguments to the distutils scripts without too much extra ad hoc code. For example, you can specify extra directories (CMak...
(): # Global level params class instance was # created before calling main(). We make it # global so that other code can access the set # of Parameters, simply by accessing the Params # instance. Here, however, we call the parse() # method to actually get the arguments, s...
main
identifier_name
setup_groupsched.py
#! /bin/env python """setup_groupsched.py @author: Dillon Hicks @summary: This script wraps the old setup script with the new setup_module.py.tpl template. This allow there to be extra arguments to the distutils scripts without too much extra ad hoc code. For example, you can specify extra directories (CMak...
) # sdf_seq_module = Extension('_sdf_seq', # sources=[source_dir+'/libgsched/sdf_seq_wrap.c', # source_dir+'/libgsched/sdf_seq.c'], # include_dirs = [source_dir+'/include'], ...
libraries = ['gsched'], extra_compile_args = ['-fPIC'], library_dirs = [build_dir, source_dir],
random_line_split
setup_groupsched.py
#! /bin/env python """setup_groupsched.py @author: Dillon Hicks @summary: This script wraps the old setup script with the new setup_module.py.tpl template. This allow there to be extra arguments to the distutils scripts without too much extra ad hoc code. For example, you can specify extra directories (CMak...
## ## if not Params.kernel_path: ## # Forcing a check for the kernel path variable. ## # Obvisouly used when making something that needs to compile ## # specifically against the kernel. ## # ## print "Must define the kernel path --kernel=<kernel-path>" ...
print "Must define the CMake binary directory --cbd=<build-dir>" sys.exit(1)
conditional_block
setup_groupsched.py
#! /bin/env python """setup_groupsched.py @author: Dillon Hicks @summary: This script wraps the old setup script with the new setup_module.py.tpl template. This allow there to be extra arguments to the distutils scripts without too much extra ad hoc code. For example, you can specify extra directories (CMak...
def main(): # Global level params class instance was # created before calling main(). We make it # global so that other code can access the set # of Parameters, simply by accessing the Params # instance. Here, however, we call the parse() # method to actuall...
USAGE = "usage: %prog [options]" def __init__(self): # Create the argument parser and then tell it # about the set of legal arguments for this # command. The parse() method of this class # calls parse_args of the optparse module self.p = optparse....
identifier_body
fs.go
package nfs import ( "fmt" "os" "github.com/tchajed/go-awol" "github.com/tchajed/goose/machine/disk" "github.com/tchajed/go-nfs/balloc" "github.com/tchajed/go-nfs/marshal" ) // file-system layout (on top of logical disk exposed by log): // [ superblock | block bitmaps | inodes | data blocks ] type SuperBlock...
func (fs Fs) Readdir(i Inum) []string { dir := fs.getInode(i) return fs.readDirEntries(dir) } func (fs Fs) Remove(dirI Inum, name string) bool { op := fs.log.Begin() dir := fs.getInode(dirI) i := fs.lookupDir(dir, name) if i == 0 { return false } ino := fs.getInode(i) if ino.Kind == INODE_KIND_FREE { pa...
{ op := fs.log.Begin() ino := fs.getInode(i) if ino.Kind != INODE_KIND_FILE { return false } for boff := off / disk.BlockSize; len(bs) > 0; boff++ { if off%disk.BlockSize != 0 { b := fs.inodeRead(ino, boff) byteOff := off % disk.BlockSize nBytes := disk.BlockSize - byteOff if uint64(len(bs)) < nByt...
identifier_body
fs.go
package nfs import ( "fmt" "os" "github.com/tchajed/go-awol" "github.com/tchajed/goose/machine/disk" "github.com/tchajed/go-nfs/balloc" "github.com/tchajed/go-nfs/marshal" ) // file-system layout (on top of logical disk exposed by log): // [ superblock | block bitmaps | inodes | data blocks ] type SuperBlock...
bs = append(bs, b...) length -= uint64(len(b)) } return bs, true } func (fs Fs) Write(i Inum, off uint64, bs []byte) bool { op := fs.log.Begin() ino := fs.getInode(i) if ino.Kind != INODE_KIND_FILE { return false } for boff := off / disk.BlockSize; len(bs) > 0; boff++ { if off%disk.BlockSize != 0 { ...
{ b = b[:length] }
conditional_block
fs.go
package nfs import ( "fmt" "os" "github.com/tchajed/go-awol" "github.com/tchajed/goose/machine/disk" "github.com/tchajed/go-nfs/balloc" "github.com/tchajed/go-nfs/marshal" ) // file-system layout (on top of logical disk exposed by log): // [ superblock | block bitmaps | inodes | data blocks ] type SuperBlock...
() balloc.Bitmap { bs := make([]disk.Block, fs.sb.NumBlockBitmaps) for i := 0; i < len(bs); i++ { bs[i] = fs.log.Read(fs.sb.blockAllocBase + uint64(i)) } return balloc.Open(bs) } func (fs Fs) flushBalloc(op *awol.Op, bm balloc.Bitmap) { bm.Flush(op, fs.sb.blockAllocBase) } // btoa translates an offset in an in...
readBalloc
identifier_name
fs.go
package nfs import ( "fmt" "os" "github.com/tchajed/go-awol" "github.com/tchajed/goose/machine/disk" "github.com/tchajed/go-nfs/balloc" "github.com/tchajed/go-nfs/marshal" ) // file-system layout (on top of logical disk exposed by log): // [ superblock | block bitmaps | inodes | data blocks ] type SuperBlock...
de := decodeDirEnt(fs.inodeRead(dir, b)) if !de.Valid { continue } if de.Name == name { fs.inodeWrite(op, dir, b, encodeDirEnt(&DirEnt{ Valid: false, Name: "", I: 0, })) return true } } return false } func (fs Fs) isDirEmpty(dir *inode) bool { if dir.Kind != INODE_KIND_DIR { ...
panic("remove on non-dir inode") } blocks := dir.NBytes / disk.BlockSize for b := uint64(0); b < blocks; b++ {
random_line_split
pop-AP-var-v0.1.1-20190805.py
""" Created on Jul. 30, 2019 @author: whyang """ # -*- coding: utf-8 -*- import os import csv # deal with csv file import pandas as pd import numpy as np from cippackage.popAPvar import cipFacetGrid # the Analytic package for the data of CIP's population ###############################################################...
nd) ### # read into the amount of aboriginal peoples' population # with open(datadir+'\\'+'population-sum-ETL.csv', 'r', encoding='utf-8', newline='') as csvfile: df = pd.read_csv( csvfile, header = 0, usecols = ['日期', '身分', '區域別', '總計', '阿美族', '泰雅族', ...
wrong doing of input process print(ybeg, '~', ye
conditional_block
pop-AP-var-v0.1.1-20190805.py
""" Created on Jul. 30, 2019 @author: whyang """ # -*- coding: utf-8 -*- import os import csv # deal with csv file import pandas as pd import numpy as np from cippackage.popAPvar import cipFacetGrid # the Analytic package for the data of CIP's population ###############################################################...
(df): # trim whitespace from ends of each value across all series in dataframe trim_strings = lambda x: x.strip() if isinstance(x, str) else x return df.applymap(trim_strings) ### # set output figure and input data directories # pathdir = '.\\figure' # directory of output folder if not os.path.isdir(path...
trim_all_cells
identifier_name
pop-AP-var-v0.1.1-20190805.py
""" Created on Jul. 30, 2019 @author: whyang """ # -*- coding: utf-8 -*- import os import csv # deal with csv file import pandas as pd import numpy as np from cippackage.popAPvar import cipFacetGrid # the Analytic package for the data of CIP's population ###############################################################...
df = pd.read_csv( csvfile, header = 0, usecols = ['日期', '身分', '區域別', '總計', '阿美族', '泰雅族', '排灣族', '布農族', '魯凱族', '卑南族', '鄒族', '賽夏族', '雅美族', '邵族', '噶瑪蘭族', '太魯閣族', '撒奇萊雅族', '賽德克族', '拉阿魯哇族', '卡那卡那富族', ...
with open(datadir+'\\'+'population-sum-ETL.csv', 'r', encoding='utf-8', newline='') as csvfile:
random_line_split
pop-AP-var-v0.1.1-20190805.py
""" Created on Jul. 30, 2019 @author: whyang """ # -*- coding: utf-8 -*- import os import csv # deal with csv file import pandas as pd import numpy as np from cippackage.popAPvar import cipFacetGrid # the Analytic package for the data of CIP's population ###############################################################...
### # set output figure and input data directories # pathdir = '.\\figure' # directory of output folder if not os.path.isdir(pathdir): os.mkdir(pathdir) datadir = '.\\data' # directory of input data folder if not os.path.isdir(datadir): os.mkdir(datadir) ### # given the comparison period (from the year...
trim_strings = lambda x: x.strip() if isinstance(x, str) else x return df.applymap(trim_strings)
identifier_body
viastitching_dialog.py
#!/usr/bin/env python # ViaStitching for pcbnew # This is the plugin WX dialog # (c) Michele Santucci 2019 # import random from json import JSONDecodeError import wx import pcbnew import gettext import math from .viastitching_gui import viastitching_gui numpy_available = False try: import num...
elif isinstance(point, list): self.x = point[0] self.y = point[1] def __sub__(self, other: pcbnew.wxPoint): return aVector([self.x - float(other.x), self.y - float(other.y)]) def __mul__(self, other): return aVector([self.x * float(other), self.y * flo...
self.x = float(point.x) self.y = float(point.y)
conditional_block
viastitching_dialog.py
#!/usr/bin/env python # ViaStitching for pcbnew # This is the plugin WX dialog # (c) Michele Santucci 2019 # import random from json import JSONDecodeError import wx import pcbnew import gettext import math from .viastitching_gui import viastitching_gui numpy_available = False try: import num...
(self): """Collect overlapping items. Every bounding box of any item found is a candidate to be inspected for overlapping. """ area_bbox = self.area.GetBoundingBox() if hasattr(self.board, 'GetModules'): modules = self.board.GetModules() else: ...
GetOverlappingItems
identifier_name
viastitching_dialog.py
#!/usr/bin/env python # ViaStitching for pcbnew # This is the plugin WX dialog # (c) Michele Santucci 2019 # import random from json import JSONDecodeError import wx import pcbnew import gettext import math from .viastitching_gui import viastitching_gui numpy_available = False try: import num...
if item.GetBoundingBox().Intersects(via.GetBoundingBox()): return True elif type(item) is pcbnew.PCB_TRACK: if item.GetBoundingBox().Intersects(via.GetBoundingBox()): width = item.GetWidth() dist, _ = pnt2line(v...
random_line_split
viastitching_dialog.py
#!/usr/bin/env python # ViaStitching for pcbnew # This is the plugin WX dialog # (c) Michele Santucci 2019 # import random from json import JSONDecodeError import wx import pcbnew import gettext import math from .viastitching_gui import viastitching_gui numpy_available = False try: import num...
def CheckOverlap(self, via): """Check if via overlaps or interfere with other items on the board. Parameters: via (pcbnew.VIA): Via to be checked Returns: bool: True if via overlaps with an item, False otherwise. """ for item in self.o...
"""Check if position specified by p1 comply with given clearance in area. Parameters: p1 (wxPoint): Position to test area (pcbnew.ZONE_CONTAINER): Area clearance (int): Clearance value Returns: bool: True if p1 position comply with clearance valu...
identifier_body
difev_adversarial.py
""" Various attack methods against inception v3 using differential evolution Based on: https://github.com/sarathknv/adversarial-examples-pytorch """ import os import sys import torch from torchvision import datasets, transforms import numpy as np from scipy.optimize import differential_evolution import classify import...
pickle.dump(new, open(results_path + 'results.pkl', 'wb')) def plot_results(): import math results_path = '/data/figs/lesions-adversarial/difev/' # results_path = '/data/figs/lesions-adversarial/fgsm/' results = pickle.load(open(results_path + 'results.temp.pkl', 'rb')) # select = 'color' ...
if k.find('color') == -1: new[k] = v
conditional_block
difev_adversarial.py
""" Various attack methods against inception v3 using differential evolution Based on: https://github.com/sarathknv/adversarial-examples-pytorch """ import os import sys import torch from torchvision import datasets, transforms import numpy as np from scipy.optimize import differential_evolution import classify import...
def get_basenames(self, img_path): basenames = [] dirname = os.path.dirname(img_path) for alias_ in self.list_alias: dirname = dirname.replace(alias_[0], alias_[1]) olddir = '' while dirname != '' and dirname != '/' and olddir != dirname: if ('lesion...
for j, dx_ in enumerate(self.main_dx): if dx_ == self.list_dx[i]: return self.main_dx2[j] return ""
identifier_body
difev_adversarial.py
""" Various attack methods against inception v3 using differential evolution Based on: https://github.com/sarathknv/adversarial-examples-pytorch """ import os import sys import torch from torchvision import datasets, transforms import numpy as np from scipy.optimize import differential_evolution import classify import...
# return self.loader1(image) def normalize_totensor(self, image): """ Input PIL image output cuda tensor """ x = self.loader2(image) x = x.repeat(1, 1, 1, 1) if is_cuda: x = x.cuda() return x def load_image(self, filename): # L...
# """
random_line_split
difev_adversarial.py
""" Various attack methods against inception v3 using differential evolution Based on: https://github.com/sarathknv/adversarial-examples-pytorch """ import os import sys import torch from torchvision import datasets, transforms import numpy as np from scipy.optimize import differential_evolution import classify import...
: """ Change the color balance and try to defeat the classifier """ def __init__(self): # v = (0.47,0.53) v = (0.9, 1.1) self.bounds = [v, v, v] self.name = 'color' @staticmethod def perturb(x): global difev_vars adv_image = np.array(difev_vars.i...
ColorAttack
identifier_name
rsync.rs
use std::{ fs::File, io::{BufReader, Read}, path::{Path, PathBuf}, }; use anyhow::{anyhow, Context, Result}; use filetime::{set_file_mtime, FileTime}; use log::{info, warn}; use rpki::{ repository::{sigobj::SignedObject, Cert, Crl, Manifest, Roa}, rrdp::ProcessSnapshot, }; use serde::{Deserialize,...
( rrdp_state: &RrdpState, changed: bool, config: &Config, ) -> Result<()> { // Check that there is a current snapshot, if not, there is no work if rrdp_state.snapshot_path().is_none() { return Ok(()); } // We can assume now that there is a snapshot and unwrap things for it let s...
update_from_rrdp_state
identifier_name
rsync.rs
use std::{ fs::File, io::{BufReader, Read}, path::{Path, PathBuf}, }; use anyhow::{anyhow, Context, Result}; use filetime::{set_file_mtime, FileTime}; use log::{info, warn}; use rpki::{ repository::{sigobj::SignedObject, Cert, Crl, Manifest, Roa}, rrdp::ProcessSnapshot, }; use serde::{Deserialize,...
"Renaming the rsync directory for previous revision to: {}", current_preserve_path.display() ); std::fs::rename(&current_path, &current_preserve_path).with_context(|| { format!( "Could not rename current rsync dir from '{}' to '...
random_line_split
rsync.rs
use std::{ fs::File, io::{BufReader, Read}, path::{Path, PathBuf}, }; use anyhow::{anyhow, Context, Result}; use filetime::{set_file_mtime, FileTime}; use log::{info, warn}; use rpki::{ repository::{sigobj::SignedObject, Cert, Crl, Manifest, Roa}, rrdp::ProcessSnapshot, }; use serde::{Deserialize,...
.map_err(|_| anyhow!("Cannot parse object at: {} to derive mtime", path_str))?; let mtime = FileTime::from_unix_time(time.timestamp(), 0); set_file_mtime(&path, mtime).map_err(|e| { anyhow!( "Cannot modify mtime for object at: {}, error: {}", path_str, e ...
{ // Try to parse this as a generic RPKI signed object SignedObject::decode(data, false).map(|signed| signed.cert().validity().not_before()) }
conditional_block
tcp.rs
//! # TCP handling //! //! This file contains the TCP handling for `clobber`. The loop here is that we connect, write, //! and then read. If the client is in repeat mode then it will repeatedly write/read while the //! connection is open. //! //! ## Performance Notes //! //! ### Perform allocations at startup //! //! T...
}
{ let addr = echo_server().unwrap(); let input = "test\n\r\n".as_bytes(); let want = input.len(); let result = async_std::task::block_on(async move { let mut stream = connect(&addr).await?; let mut read_buffer = [0u8; 1024]; let _ = write(&mut stream,...
identifier_body
tcp.rs
//! # TCP handling //! //! This file contains the TCP handling for `clobber`. The loop here is that we connect, write, //! and then read. If the client is in repeat mode then it will repeatedly write/read while the //! connection is open. //! //! ## Performance Notes //! //! ### Perform allocations at startup //! //! T...
() { let result = async_std::task::block_on(async { let addr = echo_server().unwrap(); let result = connect(&addr).await; result }); assert!(result.is_ok()); } #[test] fn test_write() { let addr = echo_server().unwrap(); let inpu...
test_connect
identifier_name
tcp.rs
//! # TCP handling //! //! This file contains the TCP handling for `clobber`. The loop here is that we connect, write, //! and then read. If the client is in repeat mode then it will repeatedly write/read while the //! connection is open. //! //! ## Performance Notes //! //! ### Perform allocations at startup //! //! T...
} #[cfg(test)] mod tests { use super::*; use crate::server::echo_server; #[test] fn test_connect() { let result = async_std::task::block_on(async { let addr = echo_server().unwrap(); let result = connect(&addr).await; result }); assert!(res...
// todo: Do something with the read_buffer? // todo: More verbose logging; dump to stdout, do post-run analysis on demand
random_line_split
epoll_file.rs
use std::any::Any; use std::collections::{HashMap, VecDeque}; use std::fmt; use std::mem::{self, MaybeUninit}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Weak; use std::time::Duration; use atomic::Atomic; use super::epoll_waiter::EpollWaiter; use super::host_file_epoller::HostFileEpoller; use super...
fn update_host_events(&self, ready: &IoEvents, mask: &IoEvents, trigger_notifier: bool) { self.host_events.update(ready, mask, Ordering::Release); if trigger_notifier { self.notifier.broadcast(ready); } } fn as_any(&self) -> &dyn Any { self } } impl Drop ...
{ Some(self.host_file_epoller.host_fd()) }
identifier_body
epoll_file.rs
use std::any::Any; use std::collections::{HashMap, VecDeque}; use std::fmt; use std::mem::{self, MaybeUninit}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Weak; use std::time::Duration; use atomic::Atomic; use super::epoll_waiter::EpollWaiter; use super::host_file_epoller::HostFileEpoller; use super...
(&self) -> Result<&EpollFile> { self.as_any() .downcast_ref::<EpollFile>() .ok_or_else(|| errno!(EBADF, "not an epoll file")) } } #[derive(Debug)] struct EpollEntry { fd: FileDesc, file: FileRef, inner: SgxMutex<EpollEntryInner>, // Whether the entry is in the ready ...
as_epoll_file
identifier_name
epoll_file.rs
use std::any::Any; use std::collections::{HashMap, VecDeque}; use std::fmt; use std::mem::{self, MaybeUninit}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Weak; use std::time::Duration; use atomic::Atomic; use super::epoll_waiter::EpollWaiter; use super::host_file_epoller::HostFileEpoller; use super...
EpollCtl::Del(fd) => { self.del_interest(*fd)?; } EpollCtl::Mod(fd, event, flags) => { self.mod_interest(*fd, *event, *flags)?; } } Ok(()) } pub fn wait( &self, revents: &mut [MaybeUninit<EpollEvent...
{ self.add_interest(*fd, *event, *flags)?; }
conditional_block
epoll_file.rs
use std::any::Any; use std::collections::{HashMap, VecDeque}; use std::fmt; use std::mem::{self, MaybeUninit}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Weak; use std::time::Duration; use atomic::Atomic; use super::epoll_waiter::EpollWaiter; use super::host_file_epoller::HostFileEpoller; use super...
// process, then this EpollFile still has connection with the parent process's // file table, which is problematic. /// A file that provides epoll API. /// /// Conceptually, we maintain two lists: one consists of all interesting files, /// which can be managed by the epoll ctl commands; the other are for ready files, ...
// with the current process's file table by regitering itself as an observer // to the file table. But if an EpollFile is cloned or inherited by a child
random_line_split
lib.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the root directory of this source tree. //! This crate contains Winterfell STARK prover and verifier. //! //! A STARK is a novel proof-of-computation scheme to create efficiently...
//! # //! # fn evaluate_transition<E: FieldElement + From<Self::BaseElement>>( //! # &self, //! # frame: &EvaluationFrame<E>, //! # _periodic_values: &[E], //! # result: &mut [E], //! # ) { //! # let current_state = &frame.current()[0]; //! # let next_state = curr...
//! # } //! # }
random_line_split
secrets.pb.go
// Code generated by protoc-gen-gogo. DO NOT EDIT. // source: lorawan-stack/api/secrets.proto package ttnpb import ( bytes "bytes" fmt "fmt" io "io" math "math" math_bits "math/bits" reflect "reflect" strings "strings" _ "github.com/envoyproxy/protoc-gen-validate/validate" _ "github.com/gogo/protobuf/gogopr...
return "nil" } s := strings.Join([]string{`&Secret{`, `KeyID:` + fmt.Sprintf("%v", this.KeyID) + `,`, `Value:` + fmt.Sprintf("%v", this.Value) + `,`, `}`, }, "") return s } func valueToStringSecrets(v interface{}) string { rv := reflect.ValueOf(v) if rv.IsNil() { return "nil" } pv := reflect.Indirect(...
} func (this *Secret) String() string { if this == nil {
random_line_split
secrets.pb.go
// Code generated by protoc-gen-gogo. DO NOT EDIT. // source: lorawan-stack/api/secrets.proto package ttnpb import ( bytes "bytes" fmt "fmt" io "io" math "math" math_bits "math/bits" reflect "reflect" strings "strings" _ "github.com/envoyproxy/protoc-gen-validate/validate" _ "github.com/gogo/protobuf/gogopr...
() (n int) { if m == nil { return 0 } var l int _ = l l = len(m.KeyID) if l > 0 { n += 1 + l + sovSecrets(uint64(l)) } l = len(m.Value) if l > 0 { n += 1 + l + sovSecrets(uint64(l)) } return n } func sovSecrets(x uint64) (n int) { return (math_bits.Len64(x|1) + 6) / 7 } func sozSecrets(x uint64) (n i...
Size
identifier_name
secrets.pb.go
// Code generated by protoc-gen-gogo. DO NOT EDIT. // source: lorawan-stack/api/secrets.proto package ttnpb import ( bytes "bytes" fmt "fmt" io "io" math "math" math_bits "math/bits" reflect "reflect" strings "strings" _ "github.com/envoyproxy/protoc-gen-validate/validate" _ "github.com/gogo/protobuf/gogopr...
intStringLen := int(stringLen) if intStringLen < 0 { return ErrInvalidLengthSecrets } postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthSecrets } if postIndex > l { return io.ErrUnexpectedEOF } m.KeyID = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex...
{ if shift >= 64 { return ErrIntOverflowSecrets } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } }
conditional_block
secrets.pb.go
// Code generated by protoc-gen-gogo. DO NOT EDIT. // source: lorawan-stack/api/secrets.proto package ttnpb import ( bytes "bytes" fmt "fmt" io "io" math "math" math_bits "math/bits" reflect "reflect" strings "strings" _ "github.com/envoyproxy/protoc-gen-validate/validate" _ "github.com/gogo/protobuf/gogopr...
func init() { proto.RegisterType((*Secret)(nil), "ttn.lorawan.v3.Secret") golang_proto.RegisterType((*Secret)(nil), "ttn.lorawan.v3.Secret") } func init() { proto.RegisterFile("lorawan-stack/api/secrets.proto", fileDescriptor_8c9d796b7f7ca235) } func init() { golang_proto.RegisterFile("lorawan-stack/api/secrets.p...
{ if m != nil { return m.Value } return nil }
identifier_body