file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
12.1k
suffix
large_stringlengths
0
12k
middle
large_stringlengths
0
7.51k
fim_type
large_stringclasses
4 values
main.rs
{ None => Err(From::from("expected 1 argument, but got none")), Some(file_path) => Ok(file_path), } } fn read_csv_file3() { let mut rdr = csv::ReaderBuilder::new() .has_headers(false) .delimiter(b';') .double_quote(false) .flexible(true) .comment(Some(b'...
cpu 5.094 total // String からbyteで処理をするように変更した。 fn performance2_read_csv() -> Result<u64, Box<dyn Error>> { let mut reader = csv::Reader::from_reader(io::stdin()); let mut count = 0; for result in reader.byte_records() { let record = result?; if &record[0] == b"us" && &record[3] == b"MA" { ...
identifier_body
main.rs
Err(e) => return Err(From::from(e)), Ok(r) => println!("{:?}", r), } } Ok(()) } fn run_question() -> Result<(), Box<dyn Error>> { let mut rds = csv::Reader::from_reader(io::stdin()); for result in rds.records() { // ?を使うことで可読性が上がる! let a = result?; ...
} // utf-8に変換できない場合の対処法。 // byteで読み込む!!! fn read_and_write_byte_csv() -> Result<(), Box<dyn Error>> { let argss = match env::args().nth(1) { None => return Err(From::from("expected 1 argument, but got none")), Some(argument) => argument, }; // CSVリーダー(stdin)とCSVライター(stdout)を構築する let mu...
} wtr.flush()?; Ok(())
random_line_split
main.rs
(file_path)?; let mut rdr = csv::Reader::from_reader(file); // ここでヘッダーを読み込みたいとする。 // ① clone()する。 // ただし、メモリにコピーをとる代償が伴う。 // let headers = rdr.headers()?.clone(); { // lifetimeのために、この呼び出しはそれ所有スコープでネストされている。 // ② スコープをネストさせる。 // 所有権が奪われて、以降のイテレーションができなくなる。 // <なるほ...
ord[0] == "
identifier_name
__init__.py
print(f'pyatlas_config={config}') return config def get_digest(self): return HTTPDigestAuth(self.public_key,self.private_key) # API def organizations(self): """ Return a list of organzations available to current api user. """ return self.get('{}/orgs'.format(ApiVersion.A1.value)) def...
data = [ { 'ipAddress' : ip_address, 'comment' : 'pyatlas generated whitelist entry' } ] pprint.pprint(data) target = f'{ApiVersion.A1.value}/groups/{self.project_id}/whitelist' print( f'target={target}' ) print( f'data={data}' ) response = self.post(target, body=data) return response ...
def add_whitelist_atlas_project(self, ip_address=None): if ip_address is None: external_ip = urllib.request.urlopen('https://ident.me').read().decode('utf8') print(f'external_ip={external_ip}') ip_address=external_ip
random_line_split
__init__.py
def get_digest(self): return HTTPDigestAuth(self.public_key,self.private_key) # API def organizations(self): """ Return a list of organzations available to current api user. """ return self.get('{}/orgs'.format(ApiVersion.A1.value)) def projects(self): """ Alias for groups() """ ...
config = { Env.PUBLIC_KEY : self.public_key, Env.PRIVATE_KEY : self.private_key, Env.ORG_ID : self.org_id, Env.PROJECT_ID : self.project_id } print(f'pyatlas_config={config}') return config
identifier_body
__init__.py
project_id != '' else self.__project_id return self.get(f'{ApiVersion.A1.value}/groups/{project_id}/databaseUsers') def create_project(self ,name ,org_id=None): if org_id is None: org_id = self.org_id project_data = { "name" : name } if org_id: ...
pending_invoice
identifier_name
__init__.py
pprint.pprint(data) target = f'{ApiVersion.A1.value}/groups/{self.project_id}/whitelist' print( f'target={target}' ) print( f'data={data}' ) response = self.post(target, body=data) return response def add_project_apikey_whitelist(self ,apikey_id ...
sku_summary[item['sku']]= { 'totalPriceCents' : 0 }
conditional_block
planning.rs
Target; use context::CrateContext; use context::WorkspaceContext; use settings::RazeSettings; use settings::GenMode; use std::collections::HashSet; use std::env; use std::fs; use std::ops::Deref; use std::path::Path; use std::str; use util; pub struct PlannedBuild { pub workspace_context: WorkspaceContext, pub cra...
(&mut self, host: String) -> CargoResult<()> { match host.to_url().map(|url| SourceId::for_registry(&url)) { Ok(registry_id) => { self.registry = Some(registry_id); Ok(()) }, Err(value) => Err(CargoError::from(value)) } } pub fn plan_build(&self) -> CargoResult<PlannedBuil...
set_registry_from_url
identifier_name
planning.rs
Target; use context::CrateContext; use context::WorkspaceContext; use settings::RazeSettings; use settings::GenMode; use std::collections::HashSet; use std::env; use std::fs; use std::ops::Deref; use std::path::Path; use std::str; use util; pub struct PlannedBuild { pub workspace_context: WorkspaceContext, pub cra...
else { normal_deps }; crate_contexts.push(CrateContext { pkg_name: id.name().to_owned(), pkg_version: id.version().to_string(), features: features, is_root_dependency: root_direct_deps.contains(&id), metadeps: Vec::n...
{ normal_deps.into_iter() .filter(|d| !s.skipped_deps.contains(&format!("{}-{}", d.name, d.version))) .collect::<Vec<_>>() }
conditional_block
planning.rs
use cargo::ops::Packages; use cargo::ops; use cargo::util::CargoResult; use cargo::util::Cfg; use cargo::util::Config; use cargo::util::ToUrl; use context::BuildDependency; use context::BuildTarget; use context::CrateContext; use context::WorkspaceContext; use settings::RazeSettings; use settings::GenMode; use std::col...
use cargo::core::Resolve; use cargo::core::SourceId; use cargo::core::Workspace; use cargo::core::dependency::Kind;
random_line_split
main.rs
continue; } println!("The value of n is {}", n); if n > 100 { break; } } // for loop println!("-------for loop"); for i in 1..10 { println!("The number is {}", i); } let range = 10..20; for i in range { println!("eleme...
(c: &Color2) { println!("Color - R:{} G:{} B:{}", c.0, c.1, c.2); } print_color(bg); /* print_color(bg); *impossible */ print_color2(&bg2); print_color2(&bg2); print_color2(&bg2); // it is possible to have multile function invocation due to it is called by reference // array...
print_color2
identifier_name
main.rs
continue; } println!("The value of n is {}", n); if n > 100 { break; } } // for loop println!("-------for loop"); for i in 1..10 { println!("The number is {}", i); } let range = 10..20; for i in range { println!("eleme...
else { println!("{} is odd", i); } } } count_to(7); fn is_even(num: u32) -> bool { return num % 2 == 0; } let number = 12; println!("is {} even? {}", number, is_even(number)); // reference println!("-------references"); let mut x = 7; ...
{ println!("{} is even", i); }
conditional_block
main.rs
continue; } println!("The value of n is {}", n); if n > 100 { break; } } // for loop println!("-------for loop"); for i in 1..10 { println!("The number is {}", i); } let range = 10..20; for i in range { println!("eleme...
} let rectangle: Rectangle = Rectangle {height: 30, width: 10, }; rectangle.print_description(); println!("The given rectangle is square? {}", rectangle.is_square()); println!("Area is {} and perimeter is {}", rectangle.area(), rectangle.perimeter()); // Strings println!("-------Strings")...
{ return (self.width + self.height) * 2; }
identifier_body
main.rs
We are heading Left!"), Direction::Right => println!("We are heading Right!") } match player_direction4 { Direction::Up => println!("We are heading Up!"), Direction::Down => println!("We are heading Down!"), Direction::Left => println!("We are heading Left!"), Direction::...
}
random_line_split
main.py
self.pre_parse_page(second_get_res.text), second_get_res.text,args) def pre_parse_page(self, page_source): ''' 用户选择需要检索的页数 ''' reference_num_pattern_compile = re.compile(r'.*?找到&nbsp;(.*?)&nbsp;') reference_num = re.search(reference_num_pattern_compile, ...
is_all_download = 'n' # 将所有数量根据每页20计算多少页 if is_all_download == 'y': page, i = divmod(reference_num_int, 20) if i != 0: page += 1 return page else: count = self.count self.select_download_num = int(count) ...
全部下载(y/n)?')
identifier_name
main.py
\\chromedriver.exe" self.webdriver_path = "D:\\chromedriver.exe" # self.webdriver_path = "D:\\安装包\\phantomjs-2.1.1-windows\\bin\\phantomjs.exe" # options = webdriver.ChromeOptions() chrome_options = Options() # options1 = webdriver.ChromeOptions() chrome_options.add_argum...
(time.time())) self.index = 0 self.cur_page_num = 1 # 保持会话 self.session.get(BASIC_URL, headers=HEADER) self.count=count def get_cookies(self): # self.webdriver_path = "D:\\workspaces\\pythonworks\\webdriver\\chromedriver_win32
identifier_body
main.py
self.ck = self.ck + cookie['name'] + '=' + cookie['value'] + ';' # print(cookie['name'] + '=' + cookie['value'] + ';') return self.ck def search_reference(self, ueser_input,args): ''' 第一次发送post请求 再一次发送get请求,这次请求没有写文献等东西 两次请求来获得文献列表 ''' ...
cookies[cookie['name']] = cookie['value']
random_line_split
main.py
ensW4IQMovwHtwkF4VYPoHbKxJw!!&ot=09/15/2020 16:25:29;cnkiUserKey=700c6580-66f0-d89f-414c-c84f72dc52fa;c_m_expire=2020-09-15 16:25:29;SID_kns8=123106;ASP.NET_SessionId=qag4isl11jbdrt0mjunnyvjr;SID_kns_new=kns123117;Ecp_ClientId=1200915160502413634;Ecp_LoginStuts={"IsAutoLogin":false,"UserName":"NJ0023","ShowName":"%E6%B...
99961800%2C%22https%3A%2F%2Fwww.cnki.net%2F%22%5D; LID=WEEvREcwSlJHSldSdmVqMDh6aS9uaHNiSkpvbExySllXaCs1MkpUR1NCST0=$9A4hF_YAuvQ5obgVAqNKPCYcEj
conditional_block
createKB.py
if __name__ == '__main__': parser = argparse.ArgumentParser(description='Build classifiers and create the PGmine knowledge base') parser.add_argument('--trainingFiles',required=True,type=str,help='3 BioC files (comma-separated) for star_allele, rs and other') parser.add_argument('--selectedChemicals',required=True...
return len(s) == len(s.encode())
identifier_body
createKB.py
terms ) ) pmidToRelevantMeSH = { int(pmid):[t for t in terms if t in pediatricTerms or t in adultTerms] for pmid,terms in relevantMeSH.items() } print("Loaded mesh PMIDs for pediatric/adult terms") # Fix mapping of some popular variants to the correct SNP variantFixes = { 'rs121913377':'rs113488022' # BRAF V600...
random_line_split
createKB.py
(s): #try: # s.decode('ascii') # return True #except UnicodeDecodeError: # return False return len(s) == len(s.encode()) if __name__ == '__main__': parser = argparse.ArgumentParser(description='Build classifiers and create the PGmine knowledge base') parser.add_argument('--trainingFiles',required=True,type=st...
isASCII
identifier_name
createKB.py
dbsnp = {} with open(args.dbsnp) as f: for line in f: rsid,geneInfos = line.strip('\n').split('\t') geneInfos = [ tuple(geneInfo.split(':')) for geneInfo in geneInfos.split('|') ] geneNames = [ geneName for geneName,geneID in geneInfos ] geneIDs = [ geneID for geneName,geneID in geneInfos ] ...
meshID = 'MESH:'+meshID chemMeshIDs.add(meshID) if chem['isCancerDrug']: cancerDrugMeshIDs.add(meshID) meshIDsToChemName[meshID] = chem['name'] meshIDsToDrugBank[meshID] = chem['DrugBank'] if 'PharmGKB' in chem: meshIDsToPharmGKB[meshID] = chem['PharmGKB']
conditional_block
weather_stn_data.py
924','state':'TX','weather_station':'CORPUS CHRISTI INTL AP'}, {'icao_code':'KCRW','row':413,'col':676,'stn_id_cdo':'GHCND:USW00013866','state':'WV','weather_station':'CHARLESTON YEAGER AP'}, {'icao_code':'KDCA','row':452,'col':735,'stn_id_cdo':'GHCND:USW00013743','state':'VA','weather_station':'WASHINGTON REAGAN AP'...
{'icao_code':'KMIA','row':184,'col':804,'stn_id_cdo':'GHCND:USW00012839','state':'FL','weather_station':'MIAMI INTL AP'}, {'icao_code':'KMIE','row':426,'col':610,'stn_id_cdo':'GHCND:USW00094895','state':'IN','weather_station':'MUNCIE DELAWARE CO AP'}, {'icao_code':'KMLI','row':427,'col':531,'stn_id_cdo':'GHCND:USW00...
random_line_split
coverage.py
etc. This function works with chembl_15 upwards. Outputs a list of tuples [(tid, target_type, domain_count, assay_count, act_count),...] """ data = queryDevice.queryDevice(""" SELECT DISTINCT dc.tid, dc.target_type, dc.dc, COUNT(DISTINCT act.assay_id), COUNT(DISTINCT activity_id) FROM a...
#----------------------------------------------------------------------------------------------------------------------- def get_archs(el_targets, pfam_lkp): """Find multi-domain architectures. Inputs: el_targets -- list of eligible targets """ act_lkp = {} arch_lkp = {} dom_lkp = {} ...
"""Read two columns from a tab-separated file into a dictionary. Inputs: path -- filepath key_name -- name of the column holding the key val_name -- name of the column holding the value """ infile = open(path, 'r') lines = infile.readlines() infile.close() lkp = {} els = lines[0]...
identifier_body
coverage.py
etc. This function works with chembl_15 upwards. Outputs a list of tuples [(tid, target_type, domain_count, assay_count, act_count),...] """ data = queryDevice.queryDevice(""" SELECT DISTINCT dc.tid, dc.target_type, dc.dc, COUNT(DISTINCT act.assay_id), COUNT(DISTINCT activity_id) FROM a...
return(arch_lkp, dom_lkp, act_lkp) #----------------------------------------------------------------------------------------------------------------------- def get_doms(tids, params): """Get domains for a list of tids. Inputs: el_targets -- list of eligible targets """ pfam_lkp = {} tidst...
try: dom_lkp[dom] += 1 except KeyError: dom_lkp[dom] = 1
conditional_block
coverage.py
etc. This function works with chembl_15 upwards. Outputs a list of tuples [(tid, target_type, domain_count, assay_count, act_count),...] """ data = queryDevice.queryDevice(""" SELECT DISTINCT dc.tid, dc.target_type, dc.dc, COUNT(DISTINCT act.assay_id), COUNT(DISTINCT activity_id) FROM a...
(lkp, valid_doms): """Get count of architectures and activities covered by the mapping. """ valz = [] for arch in lkp.keys(): valid = False doms = arch.split(', ') for dom in doms: if dom in valid_doms: valid = True break valz.a...
count_valid
identifier_name
coverage.py
etc. This function works with chembl_15 upwards. Outputs a list of tuples [(tid, target_type, domain_count, assay_count, act_count),...] """ data = queryDevice.queryDevice(""" SELECT DISTINCT dc.tid, dc.target_type, dc.dc, COUNT(DISTINCT act.assay_id), COUNT(DISTINCT activity_id) FROM a...
doms = arch.split(', ') if len(doms) <= 1: continue count = arch_lkp[arch] if type(doms) is str: continue for i in range(len(doms)-1): for j in range(i+1, len(doms)): dom_key = ', '.join(sorted([doms[i],doms[j]])) ...
''' lkp = {} for arch in arch_lkp.keys():
random_line_split
fapui-accordion.js
div>" ].join ( "" ); juicer.set ( "cache", true ); juicer.set ( "errorhandling", false ); juicer.set ( "strip", true ); juicer.set ( "detection", false ); }, /** * * @param {*} el */ render : function ( el ) { if ( ! FAPUI.isString ( el ) ) { el.addClass ( "panel-noscroll"...
random_line_split
fapui-accordion.js
内容区域的高度 var items = this.el.children (); var heightSum = 0; $ ( items ).each ( function () { heightSum = heightSum + $ ( "div:first", this ).outerHeight (); } ); h = h - heightSum; var _itemHeight = h; $ ( items ).each ( function () { $ ( this ).children ( "div.accordion-content"...
conditional_block
stoopid.py
4, 4]) self.conv2 = torch.nn.Conv2d(16, 32, [4, 4], [2, 2]) self.dense1 = torch.nn.Linear(self.final_flat, encoding_size) self.dense2 = torch.nn.Linear(encoding_size, output_size) def forward(self, visual_obs: torch.tensor): visual_obs = visual_obs.permute(0, 3, 1, 2) conv_1 = torch.relu(self.con...
done = torch.from_numpy( np.array([ex.done for ex in batch], dtype=np.float32).reshape(-1, 1) ) action = torch.from_numpy(np.stack([ex.action for ex in batch])) next_obs = torch.from_numpy(np.stack([ex.next_obs for ex in batch])) # Use the Bell
""" Performs an update of the Q-Network using the provided optimizer and buffer """ BATCH_SIZE = 1000 NUM_EPOCH = 3 GAMMA = 0.9 batch_size = min(len(buffer), BATCH_SIZE) random.shuffle(buffer) # Split the buffer into batches batches = [ buffer[batch_size * start : batch_size * ...
identifier_body
stoopid.py
to a Policy, and then train the Q-Network with that data.""" from mlagents_envs.environment import ActionTuple, BaseEnv from typing import Dict import random class Trainer: @staticmethod def generate_trajectories( env: BaseEnv, q_net: VisualQNetwork, buffer_size: int, epsilon: float ): """ Given a...
new_exp,_ = Trainer.generate_trajectories(env, qnet, NUM_NEW_EXP, epsilon=0.1) random.shuffle(experiences) if len(experiences) > BUFFER_SIZE: experiences = experiences[:BUFFER_SIZE] experiences.extend(new_exp) Trainer.update_q_net(qnet, optim, experiences, 5) _, rewards = Trainer.generate_trajectories(env...
conditional_block
stoopid.py
4, 4]) self.conv2 = torch.nn.Conv2d(16, 32, [4, 4], [2, 2]) self.dense1 = torch.nn.Linear(self.final_flat, encoding_size) self.dense2 = torch.nn.Linear(encoding_size, output_size) def forward(self, visual_obs: torch.tensor): visual_obs = visual_obs.permute(0, 3, 1, 2) conv_1 = torch.relu(self.con...
( env: BaseEnv, q_net: VisualQNetwork, buffer_size: int, epsilon: float ): """ Given a Unity Environment and a Q-Network, this method will generate a buffer of Experiences obtained by running the Environment with the Policy derived from the Q-Network. :param BaseEnv: The UnityEnvironment used....
generate_trajectories
identifier_name
stoopid.py
, 4]) self.conv2 = torch.nn.Conv2d(16, 32, [4, 4], [2, 2]) self.dense1 = torch.nn.Linear(self.final_flat, encoding_size) self.dense2 = torch.nn.Linear(encoding_size, output_size) def forward(self, visual_obs: torch.tensor): visual_obs = visual_obs.permute(0, 3, 1, 2) conv_1 = torch.relu(self.conv...
for agent_id_terminated in terminal_steps: # Create its last experience (is last because the Agent terminated) last_experience = Experience( obs=dict_last_obs_from_agent[agent_id_terminated].copy(), reward=terminal_steps[agent_id_terminated].reward, done=not terminal_...
# For all Agents with a Terminal Step:
random_line_split
spider.py
", norm_to="PM_PON") ######################################################################################## # .. seealso:: `Normalisation <../geochem/normalization.html>`__ # ######################################################################################## # Basic spider plots are straightforward to produce:...
a.annotate( # label the axes rows "Mode: {}".format(name), xy=(0.1, 1.05), xycoords=a.transAxes, fontsize=8, ha="left", va="bottom", )
conditional_block
spider.py
import pandas as pd # sphinx_gallery_thumbnail_number = 4 ######################################################################################## # Here we'll set up an example which uses EMORB as a starting point. Typically we'll # normalise trace element compositions to a reference composition # to be able to link...
""" import matplotlib.pyplot as plt import numpy as np
random_line_split
types.go
// Exactly one member can be set. type VolumeAttachmentSource struct { // persistentVolumeName represents the name of the persistent volume to attach. // +optional PersistentVolumeName *string `json:"persistentVolumeName,omitempty" protobuf:"bytes,1,opt,name=persistentVolumeName"` // inlineVolumeSpec contains all ...
// VolumeAttachmentSource represents a volume that should be attached. // Right now only PersistenVolumes can be attached via external attacher, // in future we may allow also inline volumes in pods.
random_line_split
DatePicker.ts
-date-picker', providers: [DATE_PICKER_VALUE_ACCESSOR], animations: [ trigger('startDateTextState', [ state( 'startDate', style({ opacity: '1.0', }), ), state( 'endDate', style({ opacity: '0.6', }), ), transition('...
toggleRangeSelect
identifier_name
DatePicker.ts
multi: true, }; @Component({ selector: 'novo-date-picker', providers: [DATE_PICKER_VALUE_ACCESSOR], animations: [ trigger('startDateTextState', [ state( 'startDate', style({ opacity: '1.0', }), ), state( 'endDate', style({ opacity...
fireSelect() { if (this.mode === 'multiple') { this.onSelect.next(this.selection); } else { this.onSelect.next(this.eventData(this.selection[0])); } } fireRangeSelect() { // Make sure the start date is before the end date if (this.selection.filter(Boolean).length === 2) { ...
{ return { year: date.getFullYear(), month: this.labels.formatDateWithFormat(date, { month: 'long' }), day: this.labels.formatDateWithFormat(date, { weekday: 'long' }), date, }; }
identifier_body
DatePicker.ts
[(selected)]="selection" (selectedChange)="updateSelection($event)" [mode]="mode" [numberOfMonths]="numberOfMonths" [weekStartsOn]="weekStart" [disabledDateMessage]="disabledDateMessage" [minDate]="start" [maxDate]="end" ></novo-calendar> <div...
registerOnChange(fn: Function): void { this._onChange = fn;
random_line_split
cluster.go
starting build instance: %s", err) } c.log("Waiting for instance to boot...") if err := buildFlynn(build, commit, merge, c.out); err != nil { build.Kill() return build.Drive("hda").FS, fmt.Errorf("error running build script: %s", err) } if runTests { if err := runUnitTests(build, c.out); err != nil { b...
peers = append(peers, fmt.Sprintf("%s=http://%s:2380", inst.ID, inst.IP)) } var script bytes.Buffer data := hostScriptData{ ID: inst.ID, IP: inst.IP, Peers: strings.Join(peers, ","), EtcdProxy: !inst.initial, } tmpl.Execute(&script, data) c.logf("Starting flynn-host on %s [id: %s]\n",...
{ continue }
conditional_block
cluster.go
(f string, a ...interface{}) (int, error) { return fmt.Fprintf(c.out, strings.Join([]string{"++", time.Now().Format("15:04:05.000"), f}, " "), a...) } func (c *Cluster) BuildFlynn(rootFS, commit string, merge bool, runTests bool) (string, error) { c.log("Building Flynn...") if err := c.setup(); err != nil { retu...
logf
identifier_name
cluster.go
}, }) if err != nil { return build.Drive("hda").FS, err } c.log("Booting build instance...") if err := build.Start(); err != nil { return build.Drive("hda").FS, fmt.Errorf("error starting build instance: %s", err) } c.log("Waiting for instance to boot...") if err := buildFlynn(build, commit, merge, c.out...
{ c.log("Building Flynn...") if err := c.setup(); err != nil { return "", err } uid, gid, err := lookupUser(c.bc.User) if err != nil { return "", err } build, err := c.vm.NewInstance(&VMConfig{ Kernel: c.bc.Kernel, User: uid, Group: gid, Memory: "4096", Cores: 8, Drives: map[string]*VMDriv...
identifier_body
cluster.go
User: uid, Group: gid, Memory: "4096", Cores: 8, Drives: map[string]*VMDrive{ "hda": {FS: rootFS, COW: true, Temp: false}, }, }) if err != nil { return build.Drive("hda").FS, err } c.log("Booting build instance...") if err := build.Start(); err != nil { return build.Drive("hda").FS, fmt.Erro...
build, err := c.vm.NewInstance(&VMConfig{ Kernel: c.bc.Kernel,
random_line_split
electron-oidc.ts
require-imports import electron = require('electron'); const BrowserWindow = electron.BrowserWindow || electron.remote.BrowserWindow; const authoritiesToRefresh: Array<string> = []; const refreshTimeouts: Map<string, any> = new Map(); export default ( config: IOidcConfig, windowParams: BrowserWindowConstructorOpt...
nonce: getRandomString(16), }; const urlToLoad: string = `${authorityUrl}connect/authorize?${queryString.stringify(urlParams)}`; return new Promise((resolve: Function, reject: Function): void => { // Open a new browser window and load the previously constructed url. const authWindow = new BrowserWin...
response_type: config.responseType, scope: config.scope, state: getRandomString(16),
random_line_split
electron-oidc.ts
require-imports import electron = require('electron'); const BrowserWindow = electron.BrowserWindow || electron.remote.BrowserWindow; const authoritiesToRefresh: Array<string> = []; const refreshTimeouts: Map<string, any> = new Map(); export default ( config: IOidcConfig, windowParams: BrowserWindowConstructorOpt...
( tokenObject: ITokenObject, authorityUrl: string, config: IOidcConfig, windowParams: BrowserWindowConstructorOptions, ): Promise<boolean> { const urlParams = { id_token_hint: tokenObject.userId, post_logout_redirect_uri: config.logoutRedirectUri, }; const endSessionUrl = `${authorityUrl}connect/...
logout
identifier_name
electron-oidc.ts
require-imports import electron = require('electron'); const BrowserWindow = electron.BrowserWindow || electron.remote.BrowserWindow; const authoritiesToRefresh: Array<string> = []; const refreshTimeouts: Map<string, any> = new Map(); export default ( config: IOidcConfig, windowParams: BrowserWindowConstructorOpt...
state: getRandomString(16), nonce: getRandomString(16), prompt: 'none', }; const urlToLoad: string = `${authorityUrl}connect/authorize?${queryString.stringify(urlParams)}`; // Open a new browser window and load the previously constructed url. const authWindow = new BrowserWindow({show: false}); ...
{ // Token refresh factor is set as described at https://github.com/manfredsteyer/angular-oauth2-oidc/blob/master/docs-src/silent-refresh.md#automatically-refreshing-a-token-when-before-it-expires-code-flow-and-implicit-flow const tokenRefreshFactor = 0.75; const secondsInMilisecondsFactor = 1000; const tokenRe...
identifier_body
electron-oidc.ts
require-imports import electron = require('electron'); const BrowserWindow = electron.BrowserWindow || electron.remote.BrowserWindow; const authoritiesToRefresh: Array<string> = []; const refreshTimeouts: Map<string, any> = new Map(); export default ( config: IOidcConfig, windowParams: BrowserWindowConstructorOpt...
stopSilentRefreshing(authorityUrl); }; redirectCallback(url, authWindow, config, redirectCallbackResolved, redirectCallbackRejected); }); } function startSilentRefreshing( authorityUrl: string, config: IOidcConfig, tokenObject: ITokenObject, refreshCallback: Function, ): void { authorities...
{ throw error; }
conditional_block
clusterapi_utils.go
BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package clusterapi import ( "fmt" "strconv" "strings" "github.com/pkg/errors" "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s...
(annotations map[string]string) (resource.Quantity, error) { return parseKey(annotations, cpuKey) } func parseMemoryCapacity(annotations map[string]string) (resource.Quantity, error) { return parseKey(annotations, memoryKey) } func parseEphemeralDiskCapacity(annotations map[string]string) (resource.Quantity, error)...
parseCPUCapacity
identifier_name
clusterapi_utils.go
, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package clusterapi import ( "fmt" "strconv" "strings" "github.com/pkg/errors" "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/ap...
return zeroQuantity.DeepCopy(), nil } func parseIntKey(annotations map[string]string, key string) (resource.Quantity, error) { if val, exists := annotations[key]; exists && val != "" { valInt, err := strconv.ParseInt(val, 10, 0) if err != nil { return zeroQuantity.DeepCopy(), fmt.Errorf("value %q from annota...
{ return resource.ParseQuantity(val) }
conditional_block
clusterapi_utils.go
" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package clusterapi import ( "fmt" "strconv" "strings" "github.com/pkg/errors" "k8s.io/apimachinery/pkg/api/resource" metav1 "k8...
// by the CAPI_GROUP env variable, it is initialized here. machineAnnotationKey = getMachineAnnotationKey() // nodeGroupMinSizeAnnotationKey and nodeGroupMaxSizeAnnotationKey are the keys // used in MachineSet and MachineDeployment annotations to specify the limits // for the node group. Because the keys can be a...
// CAPI_GROUP env variable, it is initialized here. machineDeleteAnnotationKey = getMachineDeleteAnnotationKey() // machineAnnotationKey is the annotation used by the cluster-api on Node objects // to specify the name of the related Machine object. Because this can be affected
random_line_split
clusterapi_utils.go
, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package clusterapi import ( "fmt" "strconv" "strings" "github.com/pkg/errors" "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/ap...
// getNodeGroupMaxSizeAnnotationKey returns the key that is used for the // node group maximum size annotation. This function is needed because the user can // change the default group name by using the CAPI_GROUP environment variable. func getNodeGroupMaxSizeAnnotationKey() string { key := fmt.Sprintf("%s/cluster-a...
{ key := fmt.Sprintf("%s/cluster-api-autoscaler-node-group-min-size", getCAPIGroup()) return key }
identifier_body
analysisTools.py
04-rgamma)*xval + rgamma*xval*xval) # add systematic error for SPHEREx photometric extractions (in mag) sysErr = 0.01 ## somewhat arbitrary, but realistic return np.sqrt(err_rand**2 + sysErr**2) # similar to getSPHERExSED, but already has noise-free static model def getObsSED(wavSPH, magTrue, mjd...
return SPHmagAB, SPHeps, SPHalb def getBusAKARIMagCorr(wave, refl, magTot, wavMax): ## compute additive correction to magTot because of a different ## reflectivity curve affecting the scattered flux; the correction ## vanishes at the first wavelength in the SPHEREx standard grid refl0 = refl/refl...
random_line_split
analysisTools.py
return magTrue # no-noise version def getATMmodelMag(SEDfile, Dast, waveSPH): # 1) read wavelength (in m), flux (F_lambda in W/m2/m), emissivity and albedo # 2) correct flux from the fiducial D=1km to Dast # 3) given input wavelength array, compute AB magnitudes # 4) return true AB magnitudes, e...
outfilerootname = './simSPHERExSpecDefault'
conditional_block
analysisTools.py
04-rgamma)*xval + rgamma*xval*xval) # add systematic error for SPHEREx photometric extractions (in mag) sysErr = 0.01 ## somewhat arbitrary, but realistic return np.sqrt(err_rand**2 + sysErr**2) # similar to getSPHERExSED, but already has noise-free static model def getObsSED(wavSPH, magTrue, mjd...
def getBusAKARIMagCorr(wave, refl, magTot, wavMax): ## compute additive correction to magTot because of a different ## reflectivity curve affecting the scattered flux; the correction ## vanishes at the first wavelength in the SPHEREx standard grid refl0 = refl/refl[0] # part 1: emission negligib...
wavelength, flux, epsilon, albedo = np.loadtxt(SEDfile) # 2) correct for Dast and translate flux to AB mags magAB = getABmag(wavelength, flux*Dast**2) # 3) interpolate magAB, epsilon and albedo to waveSPH SPHmagAB = np.interp(waveSPH, 1.0e6*wavelength, magAB) SPHeps = np.interp(waveSPH, 1.0e6*wavele...
identifier_body
analysisTools.py
Taxi!=''): # read reflectivity curve file = BusDIR + "/" + "reflectivity" + BusTaxi + ".dat" refldata = np.loadtxt(file, skiprows=1) waveSPHrefl, reflectivity = refldata.T[0], refldata.T[1] print('read in', file) if (waveSPHrefl.size != waveSPH.size): print(...
getClosest
identifier_name
timer.rs
<u32>, pub task_stop: VolatileCell<u32>, pub task_count: VolatileCell<u32>, pub task_clear: VolatileCell<u32>, pub task_shutdown: VolatileCell<u32>, _reserved0: [VolatileCell<u32>; 11], pub task_capture: [VolatileCell<u32>; 4], // 0x40 _reserved1: [VolatileCell<u32>; 60], // 0x140 pub ev...
(&self, which: u8) { let _ = self.capture(which); } /// Shortcuts can automatically stop or clear the timer on a particular /// compare event; refer to section 18.3 of the nRF reference manual /// for details. Implementation currently provides shortcuts as the /// raw bitmask. pub fn ge...
capture_to
identifier_name
timer.rs
<u32>, pub task_stop: VolatileCell<u32>, pub task_count: VolatileCell<u32>, pub task_clear: VolatileCell<u32>, pub task_shutdown: VolatileCell<u32>, _reserved0: [VolatileCell<u32>; 11], pub task_capture: [VolatileCell<u32>; 4], // 0x40 _reserved1: [VolatileCell<u32>; 60], // 0x140 pub ev...
_ => { self.timer().task_capture[3].set(1); self.timer().cc[3].get() } } } /// Capture the current value to the CC register specified by /// which and do not return the value. pub fn capture_to(&self, which: u8) { let _ = self.cap...
{ self.timer().task_capture[2].set(1); self.timer().cc[2].get() }
conditional_block
timer.rs
<u32>, pub task_stop: VolatileCell<u32>, pub task_count: VolatileCell<u32>, pub task_clear: VolatileCell<u32>, pub task_shutdown: VolatileCell<u32>, _reserved0: [VolatileCell<u32>; 11], pub task_capture: [VolatileCell<u32>; 4], // 0x40 _reserved1: [VolatileCell<u32>; 60], // 0x140 pub ev...
pub fn set_shortcuts(&self, shortcut: u32) { self.timer().shorts.set(shortcut); } pub fn get_cc0(&self) -> u32 { self.timer().cc[0].get() } pub fn set_cc0(&self, val: u32) { self.timer().cc[0].set(val); } pub fn get_cc1(&self) -> u32 { self.timer().cc[1].get...
{ self.timer().shorts.get() }
identifier_body
timer.rs
//! This implementation provides a full-fledged Timer interface to //! timers 0 and 2, and exposes Timer1 as an HIL Alarm, for a Tock //! timer system. It may be that the Tock timer system should be ultimately //! placed on top of the RTC (from the low frequency clock). It's currently //! implemented this way as a demo...
random_line_split
session_data.rs
/// A breakpoint was requested using an instruction address, and usually a result of a user requesting a /// breakpoint while in a 'disassembly' view. InstructionBreakpoint, /// A breakpoint that has a Source, and usually a result of a user requesting a breakpoint while in a 'source' view. SourceBre...
/// The supported breakpoint types #[derive(Clone, Debug, PartialEq)] pub(crate) enum BreakpointType {
random_line_split
session_data.rs
to /// all breakpoints for the Source. #[derive(Clone, Debug, PartialEq)] pub(crate) enum SourceLocationScope { All, Specific(SourceLocation), } /// Provide the storage and methods to handle various [`BreakpointType`] #[derive(Clone, Debug)] pub(crate) struct ActiveBreakpoint { pub(crate) breakpoint_type:...
if let Some(info) = list.first() { Probe::open(info).map_err(DebuggerError::DebugProbe) } else { return Err(DebuggerError::Other(anyhow!( "No probes found. Please check your USB connections." ))); ...
{ return Err(DebuggerError::Other(anyhow!( "Found multiple ({}) probes", list.len() ))); }
conditional_block
session_data.rs
Otherwise, use the default protocol of the probe. if let Some(wire_protocol) = config.wire_protocol { target_probe.select_protocol(wire_protocol)?; } // Set the speed. if let Some(speed) = config.speed { let actual_speed = target_probe.set_speed(speed)?; ...
{ let debug_info = if let Some(binary_path) = &core_configuration.program_binary { DebugInfo::from_file(binary_path).map_err(|error| DebuggerError::Other(anyhow!(error)))? } else { return Err(anyhow!( "Please provide a valid `program_binary` for debug core: {:?}", core_co...
identifier_body
session_data.rs
to /// all breakpoints for the Source. #[derive(Clone, Debug, PartialEq)] pub(crate) enum SourceLocationScope { All, Specific(SourceLocation), } /// Provide the storage and methods to handle various [`BreakpointType`] #[derive(Clone, Debug)] pub(crate) struct
{ pub(crate) breakpoint_type: BreakpointType, pub(crate) address: u64, } /// SessionData is designed to be similar to [probe_rs::Session], in as much that it provides handles to the [CoreHandle] instances for each of the available [probe_rs::Core] involved in the debug session. /// To get access to the [CoreH...
ActiveBreakpoint
identifier_name
render.rs
</span>` pub ins_end: String, /// Html to insert before a span of deleted content /// `<span class="...">` pub del_start: String, /// Html to insert after a span of deleted content /// `</span>` pub del_end: String, } impl Default for DiffStyle { fn default() -> DiffStyle { Diff...
.iter() .map(json_value_to_string) .collect::<Vec<String>>() .join(","); out.write(&csv)?; Ok(()) }, ), ); // // format-date: strftime-like function to reformat date hb.reg...
{ use handlebars::{Context, Helper, HelperResult, Output, RenderContext, RenderError}; // "join-csv" turns array of values into comma-separated list // Converts each value using to_string() hb.register_helper( "join-csv", Box::new( |h: &Helper, _r: &Handlebars, ...
identifier_body
render.rs
/// Html to insert before a span of deleted content /// `<span class="...">` pub del_start: String, /// Html to insert after a span of deleted content /// `</span>` pub del_end: String, } impl Default for DiffStyle { fn default() -> DiffStyle { DiffStyle { ins_start: r#"...
let mut r2 = Renderer::init(&RenderConfig::default()).expect("ok"); r2.set("x".into(), toml::Value::from("xyz")); assert!(true); }
random_line_split
render.rs
</span>` pub ins_end: String, /// Html to insert before a span of deleted content /// `<span class="...">` pub del_start: String, /// Html to insert after a span of deleted content /// `</span>` pub del_end: String, } impl Default for DiffStyle { fn default() -> DiffStyle { Diff...
() -> Self { // unwrap ok because only error condition occurs with templates, and default has none. Self::init(&RenderConfig::default()).unwrap() } } impl<'gen> Renderer<'gen> { /// Initialize handlebars template processor. pub fn init(config: &RenderConfig) -> Result<Self> { let mu...
default
identifier_name
quantity.go
return "" } // OpenAPIV3OneOfTypes is used by the kube-openapi generator when constructing // the OpenAPI v3 spec of this type. func (Quantity) OpenAPIV3OneOfTypes() []string { return []string{"string", "number"} } // CanonicalizeBytes returns the canonical form of q and its suffix (see comment on Quantity). // // N...
{ out := make([]byte, len(q.s)+2) out[0], out[len(out)-1] = '"', '"' copy(out[1:], q.s) return out, nil }
conditional_block
quantity.go
amount.SetString(value); !ok { return Quantity{}, ErrNumeric } // So that no one but us has to think about suffixes, remove it. if base == 10 { amount.SetScale(amount.Scale() + Scale(exponent).infScale()) } else if base == 2 { // numericSuffix = 2 ** exponent numericSuffix := big.NewInt(1).Lsh(bigOne, uin...
Sub
identifier_name
quantity.go
const ( // splitREString is used to separate a number from its suffix; as such, // this is overly permissive, but that's OK-- it will be checked later. splitREString = "^([+-]?[0-9.]+)([eEinumkKMGTP]*[-+]?[0-9]*)$" ) var ( // Errors that could happen while parsing a string. ErrFormatWrong = errors.New("quantiti...
{ q, err := ParseQuantity(str) if err != nil { panic(fmt.Errorf("cannot parse '%v': %v", str, err)) } return q }
identifier_body
quantity.go
+]?[0-9]*)$" ) var ( // Errors that could happen while parsing a string. ErrFormatWrong = errors.New("quantities must match the regular expression '" + splitREString + "'") ErrNumeric = errors.New("unable to parse numeric part of quantity") ErrSuffix = errors.New("unable to parse quantity's suffix") )
// handle leading sign if pos < end { switch str[0] { case '-': positive = false pos++ case '+': pos++ } } // strip leading zeros Zeroes: for i := pos; ; i++ { if i >= end { num = "0" value = num return } switch str[i] { case '0': pos++ default: break Zeroes } } // ...
// parseQuantityString is a fast scanner for quantity values. func parseQuantityString(str string) (positive bool, value, num, denom, suffix string, err error) { positive = true pos := 0 end := len(str)
random_line_split
generate_tiles.py
_data_rasterio def get_files_from_folder(input_dir, extensions=None): """Method to get files from a folder with optional filter on extensions Args: input_dir: input folder extensions (list or tuple): List of extensions to filter files (Default value = None) Returns: List of filepaths ...
return output @click.group() def cli(): pass def _parse_options(options): # this import is needed to correctly run `eval` from rasterio.enums import Resampling assert isinstance(options, str), "Options should be a string" output = {} if len(options) == 0: return output opti...
files = Path(input_dir).rglob("*{}".format(ext)) output.extend([f.as_posix() for f in files if f.is_file()])
conditional_block
generate_tiles.py
def _parse_options(options): # this import is needed to correctly run `eval` from rasterio.enums import Resampling assert isinstance(options, str), "Options should be a string" output = {} if len(options) == 0: return output options = options.split(';') for opt in options: ...
cli.add_command(run_const_size_tiler, name="const_size")
random_line_split
generate_tiles.py
read_data_rasterio def get_files_from_folder(input_dir, extensions=None):
@click.group() def cli(): pass def _parse_options(options): # this import is needed to correctly run `eval` from rasterio.enums import Resampling assert isinstance(options, str), "Options should be a string" output = {} if len(options) == 0: return output options = options.split...
"""Method to get files from a folder with optional filter on extensions Args: input_dir: input folder extensions (list or tuple): List of extensions to filter files (Default value = None) Returns: List of filepaths """ output = [] if extensions is None: extensions = [""] ...
identifier_body
generate_tiles.py
_data_rasterio def
(input_dir, extensions=None): """Method to get files from a folder with optional filter on extensions Args: input_dir: input folder extensions (list or tuple): List of extensions to filter files (Default value = None) Returns: List of filepaths """ output = [] if extensions is...
get_files_from_folder
identifier_name
gridsummary.js
v.afterMethod('render', this.refreshSummary, this); v.afterMethod('refresh', this.refreshSummary, this); v.afterMethod('onColumnWidthUpdated', this.doWidth, this); v.afterMethod('onAllColumnWidthsUpdated', this.doAllWidths, this); v.afterMethod('onColumnHiddenUpdated', this.doHi...
this.toggleGridHScroll(false); }, this, { delay: 10 }); } else { v.afterMethod('render', this.toggleGridHScroll, this); }
random_line_split
gridsummary.js
().on('hiddenchange', this.refreshSummary, this); grid.on('resize', this.refreshSummary, this); if (Ext.isGecko || Ext.isOpera) { // restore gridview's horizontal scroll position when store data is changed // // TODO -- when sorting a column in Opera, the summary row...
if (!this.grid.getGridEl().hasClass('x-grid3-hide-gridsummary')) { // readjust gridview's height only if grid summary row is visible this.scroller.setHeight(vh - this.summaryWrap.getHeight()); } }, // private syncScroll : function(refEl, scrollEl, currX, currY) { ...
{ // handles grid's height:'auto' config return; }
conditional_block
output.rs
Tee, Tee}; use crate::common::Port; /// Describing how dataset tags will be changed when output from an output port. /// /// # Please note! /// Since we've just a few built-in operators manipulating dataset tag, for simplicity /// reasons, in our system, `OutputDelta` is defined on per output perspective and /// again...
} pub fn give_entire_iterator<I: IntoIterator<Item = D>>(&mut self, iter: I) -> IOResult<bool> { let mut count = 0; for datum in iter.into_iter() { count += 1; self.push(datum)?; } Ok(self.update_capacity(count)) } /// pub fn give_batch(&mut...
{ for item in iter { self.push(item)?; } Ok(true) }
conditional_block
output.rs
new(Vec::new())), events_buf: events_buf.clone() } } pub fn add_push<P>(&self, ch_id: ChannelId, local: bool, push: P) where P: Push<DataSet<D>> + 'static { self.shared.borrow_mut().push((Box::new(push), ch_id, local)); } pub fn build_tee(self) -> WrappedTee<DataSet<D>> { ...
Session::new(&mut self.inner, matched, self.batch_size, ca) }
random_line_split
output.rs
Tee, Tee}; use crate::common::Port; /// Describing how dataset tags will be changed when output from an output port. /// /// # Please note! /// Since we've just a few built-in operators manipulating dataset tag, for simplicity /// reasons, in our system, `OutputDelta` is defined on per output perspective and /// again...
#[inline] fn is_closed(&self) -> bool { self.poisoned } } impl<D: Data> OutputHandle<D> { pub fn new(output: WrappedTee<DataSet<D>>, batch: usize, port: Port, delta: OutputDelta) -> Self { OutputHandle { port, delta, inner: output, capac...
{ if !self.poisoned { trace!("Worker[{}], output[{:?}] is closing ...", self.inner.worker, self.port); self.poisoned = true; self.inner.close()?; } Ok(()) }
identifier_body
output.rs
Tee, Tee}; use crate::common::Port; /// Describing how dataset tags will be changed when output from an output port. /// /// # Please note! /// Since we've just a few built-in operators manipulating dataset tag, for simplicity /// reasons, in our system, `OutputDelta` is defined on per output perspective and /// again...
(&mut self) -> &mut dyn Any { self } fn as_any_ref(&self) -> &dyn Any { self } } impl<D: Data> TaggedOutput for OutputHandle<D> { #[inline] fn set_output_capacity(&mut self, capacity: usize) { self.capacity.replace(capacity); } #[inline] fn has_capacity(&self) ...
as_any_mut
identifier_name
main.rs
2) -> f32 { let h = (0.5 - 0.5 * (other + self) / k).max(0.0).min(1.0); mix(*self, -other, h) + k * h * (1.0 - h) } fn smooth_union(&self, k: f32, other: f32) -> f32 { let h = (0.5 + 0.5 * (self - other) / k).max(0.0).min(1.0); mix(*self, other, h) - k * h * (1.0 - h) } } fn mix(a: f32, b: f32, ...
fn add(self, v: Vector3<f32>) -> Self::Output { Tri { v1: self.v1 + v, v2: self.v2 + v, v3: self.v3 + v, } } } impl Mul<Tri> for f32 { type Output = Tri; fn mul(self, tri: Tri) -> Self::Output { Tri { v1: self * tri.v1, v2: self * tri.v2, v3: self * tri.v3, ...
} impl Add<Vector3<f32>> for Tri { type Output = Tri;
random_line_split
main.rs
0, 8.0); let rot = Rotation3::from_axis_angle(&Vector3::z_axis(), rng.gen_range(-PI, PI)) * Rotation3::from_axis_angle(&Vector3::y_axis(), rng.gen_range(-PI, PI)) * Rotation3::from_axis_angle(&Vector3::x_axis(), rng.gen_range(-PI, PI)); let mut projected = triangles .iter() .map(|tri| { ...
{ break; }
conditional_block
main.rs
_range(0.0, 0.1), sd_capsule(p, a, b, max_size * rng.gen_range(0.2, 1.0)), ); } s } } fn make_triangles_from_vertices_indices( vert: &Vec<f32>, idx: &Vec<u32>, ) -> Vec<Tri> { let mut triangles = vec![]; for face in idx.chunks(3) { let i1 = face[0] as usize; let i2 = face[1] as ...
{ let mut inside = false; let mut j = polygon.len() - 1; for i in 0..polygon.len() { let pi = polygon[i]; let pj = polygon[j]; if (pi.1 > p.1) != (pj.1 > p.1) && p.0 < (pj.0 - pi.0) * (p.1 - pi.1) / (pj.1 - pi.1) + pi.0 { inside = !inside; } j = i; } inside }
identifier_body
main.rs
triangles } #[derive(Debug, Clone)] struct Tri { v1: Point3<f32>, v2: Point3<f32>, v3: Point3<f32>, } impl Sub<Vector3<f32>> for Tri { type Output = Tri; fn sub(self, v: Vector3<f32>) -> Self::Output { Tri { v1: self.v1 - v, v2: self.v2 - v, v3: self.v3 - v, } } } impl Add<Vec...
new
identifier_name
gossip.rs
pair: Arc<Keypair>, exit: Arc<AtomicBool>, bank_forks: Arc<RwLock<BankForks>>, ) -> (Arc<ClusterInfo>, GossipService, UdpSocket) { let mut test_node = Node::new_localhost_with_pubkey(&node_keypair.pubkey()); let cluster_info = Arc::new(ClusterInfo::new( test_node.info.clone(), node_keypa...
sleep(Duration::from_secs(1)); } exit.store(true, Ordering::Relaxed); for (_, dr, _) in listen { dr.join().unwrap(); } assert!(done); } /// retransmit messages to a list of nodes fn retransmit_to( peers: &[&ContactInfo], data: &[u8], socket: &UdpSocket, forwarded: b...
{ trace!("not converged {} {} {}", i, total + num, num * num); }
conditional_block
gossip.rs
pair: Arc<Keypair>, exit: Arc<AtomicBool>, bank_forks: Arc<RwLock<BankForks>>, ) -> (Arc<ClusterInfo>, GossipService, UdpSocket) { let mut test_node = Node::new_localhost_with_pubkey(&node_keypair.pubkey()); let cluster_info = Arc::new(ClusterInfo::new( test_node.info.clone(), node_keypa...
10_000, &vote_keypairs, vec![100; vote_keypairs.len()], ); let bank0 = Bank::new_for_tests(&
let vote_keypairs: Vec<_> = (0..num_nodes) .map(|_| ValidatorVoteKeypairs::new_rand()) .collect(); let genesis_config_info = create_genesis_config_with_vote_accounts(
random_line_split
gossip.rs
pair: Arc<Keypair>, exit: Arc<AtomicBool>, bank_forks: Arc<RwLock<BankForks>>, ) -> (Arc<ClusterInfo>, GossipService, UdpSocket) { let mut test_node = Node::new_localhost_with_pubkey(&node_keypair.pubkey()); let cluster_info = Arc::new(ClusterInfo::new( test_node.info.clone(), node_keypa...
() { solana_logger::setup(); run_gossip_topo(50, |listen| { let num = listen.len(); for n in 0..num { let y = n % listen.len(); let x = (n + 1) % listen.len(); let yv = &listen[y].0; let mut d = yv.lookup_contact_info(&yv.id(), |ci| ci.clone()).unw...
gossip_ring
identifier_name
gossip.rs
pair: Arc<Keypair>, exit: Arc<AtomicBool>, bank_forks: Arc<RwLock<BankForks>>, ) -> (Arc<ClusterInfo>, GossipService, UdpSocket)
test_node.sockets.tvu.pop().unwrap(), ) } /// Test that the network converges. /// Run until every node in the network has a full ContactInfo set. /// Check that nodes stop sending updates after all the ContactInfo has been shared. /// tests that actually use this function are below fn run_gossip_topo<F>(...
{ let mut test_node = Node::new_localhost_with_pubkey(&node_keypair.pubkey()); let cluster_info = Arc::new(ClusterInfo::new( test_node.info.clone(), node_keypair, SocketAddrSpace::Unspecified, )); let gossip_service = GossipService::new( &cluster_info, Some(bank_f...
identifier_body
decrypt.py
_decoder.grid(row=2, column=1) resultat=tk.Entry(racine,width = 50, font = ("helvetica", "20")) resultat.grid(row=3,column=0) label_res=tk.Label(racine,font = ("helvetica", "20"), text="Résultat ici.") label_res.grid(row = 3, column=1) # print("La clef est : chr", brute_force_cesar("kd")) # La clé trouvée e...
liste_texte = list(texte)
identifier_name
decrypt.py
_clef] # On ajoute notre alphabet à a for y in range(i): a = [x + j for j in possibilite_clef for x in a] return a def brute_force_cesar(texte_a_trouver): """Trouve une clé longue de 1 et une suite de caractères qui correspondent au texte à trouver. Pas sûr de l'idée.""" ...
ar + a # On ajoute ce qu'on a trouvé à notre liste while texte_test != texte_a_trouver: # Tant qu'on code pas pareil que ce qu'on cherche texte_test = chiffre_deux(str(liste_car[l]), clef) # On teste l'encodage avec le texte et la clef actuels l += 1 # On regarde le caractèr...
alphabet for x in a] # On ajoute chaque caractère à chaque caractère # (pas sûr de cette phrase -_-) liste_car = liste_c
conditional_block
decrypt.py
_clef] # On ajoute notre alphabet à a for y in range(i): a = [x + j for j in possibilite_clef for x in a] return a def brute_force_cesar(texte_a_trouver): """Trouve une clé longue de 1 et une suite de caractères qui correspondent au texte à trouver. Pas sûr de l'idée.""" ...
def substituer_lettre(texte, lettre_initiale, lettre_finale): nouveau_texte = list(texte) i = 0 for lettre in texte: if lettre == lettre_initiale: nouveau_texte[i] = lettre_finale i += 1 nouveau_texte = str_convert(nouveau_texte) return nouveau_texte # print(...
return texte_str # print(substituer(texte2))
random_line_split
decrypt.py
_clef] # On ajoute notre alphabet à a for y in range(i): a = [x + j for j in possibilite_clef for x in a] return a def brute_force_cesar(texte_a_trouver): """Trouve une clé longue de 1 et une suite de caractères qui correspondent au texte à trouver. Pas sûr de l'idée.""" ...
ettre, texte): """Trouve le nombre d'itérations d'une lettre dans un texte""" # Oui le nom porte à confusion compteur = 0 for i in texte: if i == lettre: compteur += 1 return compteur def trouver_frequence_texte(texte): """Applique la fonction précédante pour tou...
te qui contient un texte découpé""" texte_str = "" for a in range(len(liste)): texte_str += str(liste[a]) return texte_str def trouver_frequence_lettre(l
identifier_body
dashboard.go
forceYes); err != nil { return err } warnIfNotLoopback(metabaseListenAddress) if err := disclaimer(&forceYes); err != nil { return err } dockerGroup, err := checkGroups(&forceYes) if err != nil { return err } mb, err := metabase.SetupMetabase(csConfig.API.Server.DbConfig, metabaseLis...
{ return }
conditional_block
dashboard.go
metabaseConfigFolderPath := filepath.Join(csConfig.ConfigPaths.ConfigDir, metabaseConfigFolder) metabaseConfigPath = filepath.Join(metabaseConfigFolderPath, metabaseConfigFile) if err := os.MkdirAll(metabaseConfigFolderPath, os.ModePerm); err != nil { return err } if err := require.DB(csConfig); err !...
() *cobra.Command { var force bool var cmdDashRemove = &cobra.Command{ Use: "remove", Short: "removes the metabase container.", Long: `removes the metabase container using docker.`, Args: cobra.ExactArgs(0), DisableAutoGenTag: true, Example: ` cscli das...
NewDashboardRemoveCmd
identifier_name
dashboard.go
DashboardStartCmd() *cobra.Command { var cmdDashStart = &cobra.Command{ Use: "start", Short: "Start the metabase container.", Long: `Stats the metabase container using docker.`, Args: cobra.ExactArgs(0), DisableAutoGenTag: true, RunE: func(cmd *cobra.Comm...
groupAdd := &exec.Cmd{Path: groupAddCmd, Args: []string{groupAddCmd, crowdsecGroup}} if err := groupAdd.Run(); err != nil { return dockerGroup, fmt.Errorf("unable to add group '%s': %s", dockerGroup, err)
random_line_split
dashboard.go
metabaseConfigFolderPath := filepath.Join(csConfig.ConfigPaths.ConfigDir, metabaseConfigFolder) metabaseConfigPath = filepath.Join(metabaseConfigFolderPath, metabaseConfigFile) if err := os.MkdirAll(metabaseConfigFolderPath, os.ModePerm); err != nil { return err } if err := require.DB(csConfig); err !...
log.Infof("url : http://%s:%s", mb.Config.ListenAddr, mb.Config.ListenPort) return nil }, } cmdDashStart.Flags().BoolVarP(&forceYes, "yes", "y", false, "force yes") return cmdDashStart } func NewDashboardStopCmd() *cobra.Command { var cmdDashStop = &cobra.Command{ Use: "stop", Short: ...
{ var cmdDashStart = &cobra.Command{ Use: "start", Short: "Start the metabase container.", Long: `Stats the metabase container using docker.`, Args: cobra.ExactArgs(0), DisableAutoGenTag: true, RunE: func(cmd *cobra.Command, args []string) error { mb, ...
identifier_body
main.go
pprofile/v1alpha1" secprofnodestatusv1alpha1 "sigs.k8s.io/security-profiles-operator/api/secprofnodestatus/v1alpha1" selinuxprofilev1alpha1 "sigs.k8s.io/security-profiles-operator/api/selinuxprofile/v1alpha1" "sigs.k8s.io/security-profiles-operator/internal/pkg/config" "sigs.k8s.io/security-profiles-operator/intern...
"to manage their seccomp or AppArmor profiles and apply them to Kubernetes' workloads." app.Version = version.Get().Version app.Commands = cli.Commands{ &cli.Command{ Name: "version", Aliases: []string{"v"}, Usage: "display detailed version information", Flags: []cli.Flag{ &cli.BoolFlag{ ...
app.Name = config.OperatorName app.Usage = "Kubernetes Security Profiles Operator" app.Description = "The Security Profiles Operator makes it easier for cluster admins " +
random_line_split
main.go
pprofile/v1alpha1" secprofnodestatusv1alpha1 "sigs.k8s.io/security-profiles-operator/api/secprofnodestatus/v1alpha1" selinuxprofilev1alpha1 "sigs.k8s.io/security-profiles-operator/api/selinuxprofile/v1alpha1" "sigs.k8s.io/security-profiles-operator/internal/pkg/config" "sigs.k8s.io/security-profiles-operator/intern...
(ctx *cli.Context) []controller.Controller { controllers := []controller.Controller{ seccompprofile.NewController(), profilerecorder.NewController(), } if ctx.Bool(selinuxFlag) { controllers = append(controllers, selinuxprofile.NewController()) } return controllers } func runDaemon(ctx *cli.Context) error...
getEnabledControllers
identifier_name
main.go
pprofile/v1alpha1" secprofnodestatusv1alpha1 "sigs.k8s.io/security-profiles-operator/api/secprofnodestatus/v1alpha1" selinuxprofilev1alpha1 "sigs.k8s.io/security-profiles-operator/api/selinuxprofile/v1alpha1" "sigs.k8s.io/security-profiles-operator/internal/pkg/config" "sigs.k8s.io/security-profiles-operator/intern...
if strings.Contains(namespace, ",") { opts.NewCache = cache.MultiNamespacedCacheBuilder(namespaceList) } else { // listen to a specific namespace only opts.Namespace = namespace } } func getEnabledControllers(ctx *cli.Context) []controller.Controller { controllers := []controller.Controller{ seccompprofil...
{ namespace := os.Getenv(config.RestrictNamespaceEnvKey) // listen globally if namespace == "" { opts.Namespace = namespace return } // ensure we listen to our own namespace if !strings.Contains(namespace, config.GetOperatorNamespace()) { namespace = namespace + "," + config.GetOperatorNamespace() } na...
identifier_body
main.go
.io/security-profiles-operator/internal/pkg/daemon/enricher" "sigs.k8s.io/security-profiles-operator/internal/pkg/daemon/metrics" "sigs.k8s.io/security-profiles-operator/internal/pkg/daemon/profilerecorder" "sigs.k8s.io/security-profiles-operator/internal/pkg/daemon/seccompprofile" "sigs.k8s.io/security-profiles-op...
{ return errors.Wrap(err, "SPOd error") }
conditional_block