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 |
|---|---|---|---|---|
main.rs | extern crate csv;
extern crate serde;
// This lets us write `#[derive(Deserialize)]`.
#[macro_use]
extern crate serde_derive;
use std::collections::HashMap;
use std::env;
use std::fs::File;
use std::io;
use std::{error::Error, ffi::OsString, process};
// fn main_not_recover() {
// println!("Hello, world!");
// ... | リにアロケーションする。読み込まれるたびに上書きされていくため、高速化する。
let mut record = csv::ByteRecord::new();
let mut count = 0;
while reader.read_byte_record(&mut record)? {
if &record[0] == b"us" && &record[3] == b"MA" {
count += 1;
}
}
Ok(count)
}
#[derive(Debug, Deserialize)]
#[serde(rename_all... | 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 | extern crate csv;
extern crate serde;
// This lets us write `#[derive(Deserialize)]`.
#[macro_use]
extern crate serde_derive;
use std::collections::HashMap;
use std::env;
use std::fs::File;
use std::io;
use std::{error::Error, ffi::OsString, process};
// fn main_not_recover() {
// println!("Hello, world!");
// ... | }
// 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 | extern crate csv;
extern crate serde;
// This lets us write `#[derive(Deserialize)]`.
#[macro_use]
extern crate serde_derive;
use std::collections::HashMap;
use std::env;
use std::fs::File;
use std::io;
use std::{error::Error, ffi::OsString, process};
// fn main_not_recover() {
// println!("Hello, world!");
// ... | us" && &record[3] == "MA" {
count += 1;
}
}
Ok(count)
}
// ./csv_example < worldcitiespop.csv 1.69s user 0.05s system 34% cpu 5.094 total
// String からbyteで処理をするように変更した。
fn performance2_read_csv() -> Result<u64, Box<dyn Error>> {
let mut reader = csv::Reader::from_reader(io::stdin());
... | ord[0] == " | identifier_name |
__init__.py | import logging
import pprint
import os
import requests
import collections
import json
from datetime import *
from dateutil.relativedelta import *
from enum import Enum
import string
import random
from requests.auth import HTTPDigestAuth
import urllib.request
import kubernetes
# These two lines enable debugging at http... | 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 | import logging
import pprint
import os
import requests
import collections
import json
from datetime import *
from dateutil.relativedelta import *
from enum import Enum
import string
import random
from requests.auth import HTTPDigestAuth
import urllib.request
import kubernetes
# These two lines enable debugging at http... |
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 | import logging
import pprint
import os
import requests
import collections
import json
from datetime import *
from dateutil.relativedelta import *
from enum import Enum
import string
import random
from requests.auth import HTTPDigestAuth
import urllib.request
import kubernetes
# These two lines enable debugging at http... | (self,org_id=None):
""" Return the pending invoice for this organization id.
"""
if org_id is None:
org_id = self.org_id
return self.get('{}/orgs/{}/invoices/pending'.format(ApiVersion.A1.value,org_id))
def invoice_items(self,org_id=None,query={}):
""" Return the line items posted for the
... | pending_invoice | identifier_name |
__init__.py | import logging
import pprint
import os
import requests
import collections
import json
from datetime import *
from dateutil.relativedelta import *
from enum import Enum
import string
import random
from requests.auth import HTTPDigestAuth
import urllib.request
import kubernetes
# These two lines enable debugging at http... |
c = sku_summary[ item['sku'] ]['totalPriceCents'] + item['totalPriceCents']
si = { 'totalPriceCents' : c,
'sku' : item['sku'],
'endDate' : item['endDate'] }
sku_summary[ item['sku'] ] = si
return sku_summary
def project_by_name(self,project_name=''):
""" Return... | sku_summary[item['sku']]= { 'totalPriceCents' : 0 } | conditional_block |
planning.rs | use cargo::CargoError;
use cargo::core::Dependency;
use cargo::core::Package as CargoPackage;
use cargo::core::PackageId;
use cargo::core::PackageSet;
use cargo::core::Resolve;
use cargo::core::SourceId;
use cargo::core::Workspace;
use cargo::core::dependency::Kind;
use cargo::ops::Packages;
use cargo::ops;
use cargo::... | (&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 | use cargo::CargoError;
use cargo::core::Dependency;
use cargo::core::Package as CargoPackage;
use cargo::core::PackageId;
use cargo::core::PackageSet;
use cargo::core::Resolve;
use cargo::core::SourceId;
use cargo::core::Workspace;
use cargo::core::dependency::Kind;
use cargo::ops::Packages;
use cargo::ops;
use cargo::... | 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::CargoError;
use cargo::core::Dependency;
use cargo::core::Package as CargoPackage;
use cargo::core::PackageId;
use cargo::core::PackageSet; | 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 | fn main() {
// defining a variable
println!("-------defining a variable");
println!("Hello, Hooman!");
let mut x = 45; // all variables initially are immutable otherwise it is mentioned
println!("The value of x is {}", x);
x = 10;
println!("The value of x is {}", x);
let y: i64;
y =... | (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 | fn main() {
// defining a variable
println!("-------defining a variable");
println!("Hello, Hooman!");
let mut x = 45; // all variables initially are immutable otherwise it is mentioned
println!("The value of x is {}", x);
x = 10;
println!("The value of x is {}", x);
let y: i64;
y =... | 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 | fn main() {
// defining a variable
println!("-------defining a variable");
println!("Hello, Hooman!");
let mut x = 45; // all variables initially are immutable otherwise it is mentioned
println!("The value of x is {}", x);
x = 10;
println!("The value of x is {}", x);
let y: i64;
y =... |
}
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 | fn main() {
// defining a variable
println!("-------defining a variable");
println!("Hello, Hooman!");
let mut x = 45; // all variables initially are immutable otherwise it is mentioned
println!("The value of x is {}", x);
x = 10;
println!("The value of x is {}", x);
let y: i64;
y =... | } | random_line_split | |
main.py | # -*- coding: UTF-8 -*-
import urllib
import json
import requests
import re
import time, os, shutil, logging
from .GetConfig import config
from .CrackVerifyCode import crack
from .GetPageDetail import page_detail
# 引入字节编码
from urllib.parse import quote
# 引入beautifulsoup
from bs4 import BeautifulSoup
import shutil
from ... | 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 | # -*- coding: UTF-8 -*-
import urllib
import json
import requests
import re
import time, os, shutil, logging
from .GetConfig import config
from .CrackVerifyCode import crack
from .GetPageDetail import page_detail
# 引入字节编码
from urllib.parse import quote
# 引入beautifulsoup
from bs4 import BeautifulSoup
import shutil
from ... | \\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 | # -*- coding: UTF-8 -*-
import urllib
import json
import requests
import re
import time, os, shutil, logging
from .GetConfig import config
from .CrackVerifyCode import crack
from .GetPageDetail import page_detail
# 引入字节编码
from urllib.parse import quote
# 引入beautifulsoup
from bs4 import BeautifulSoup
import shutil
from ... | 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 | # -*- coding: UTF-8 -*-
import urllib
import json
import requests
import re
import time, os, shutil, logging
from .GetConfig import config
from .CrackVerifyCode import crack
from .GetPageDetail import page_detail
# 引入字节编码
from urllib.parse import quote
# 引入beautifulsoup
from bs4 import BeautifulSoup
import shutil
from ... | KensW4IQMovwHtwkF4VYPoHbKxJw!!; Ecp_session=1; Ecp_LoginStuts={"IsAutoLogin":false,"UserName":"NJ0023","ShowName":"%E6%B2%B3%E6%B5%B7%E5%A4%A7%E5%AD%A6","UserType":"bk","BUserName":"","BShowName":"","BUserType":"","r":"5BEo2M"}; ASP.NET_SessionId=xer0y025pdahbeg1pdbooazq; SID_kns8=123110; c_m_LinID=LinID=WEEvREcwSlJHSl... | 99961800%2C%22https%3A%2F%2Fwww.cnki.net%2F%22%5D; LID=WEEvREcwSlJHSldSdmVqMDh6aS9uaHNiSkpvbExySllXaCs1MkpUR1NCST0=$9A4hF_YAuvQ5obgVAqNKPCYcEj | conditional_block |
createKB.py | import kindred
import argparse
from collections import defaultdict
import sys
import json
import re
import utils
import gzip
def isASCII(s):
#try:
# s.decode('ascii')
# return True
#except UnicodeDecodeError:
# return False
|
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 | import kindred
import argparse
from collections import defaultdict
import sys
import json
import re
import utils
import gzip
def isASCII(s):
#try:
# s.decode('ascii')
# return True
#except UnicodeDecodeError:
# return False
return len(s) == len(s.encode())
if __name__ == '__main__':
parser = argparse.Argument... | corresponding_rsids = [ x for x in variant_metadata if re.match(r'rs\d+',x) ]
corresponding_genes = [ x for x in variant_metadata if re.match(r'CorrespondingGene:(?P<id>\d+)',x) ]
variant_id = ''
genes,gene_names,gene_ids = [],'',''
if len(corresponding_rsids) == 1:
variant_id = correspo... | random_line_split | |
createKB.py | import kindred
import argparse
from collections import defaultdict
import sys
import json
import re
import utils
import gzip
def | (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 | import kindred
import argparse
from collections import defaultdict
import sys
import json
import re
import utils
import gzip
def isASCII(s):
#try:
# s.decode('ascii')
# return True
#except UnicodeDecodeError:
# return False
return len(s) == len(s.encode())
if __name__ == '__main__':
parser = argparse.Argument... |
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 | # weather_stn_data.py - Used by extract_numbers.py, get_info_from_mshr.py, get_past_observations_cdo.py, get_daily_normals_cdo.py
# Location of each of the following numbers in the image corresponds to a city (or weather station) in the continental U.S.
# Location of (lower-left pixel of) first character of numbe... | {'icao_code':'KOKC','row':290,'col':447,'stn_id_cdo':'GHCND:USW00013967','state':'OK','weather_station':'OKLAHOMA CITY WILL ROGERS AP'},
{'icao_code':'KORF','row':424,'col':765,'stn_id_cdo':'GHCND:USW00013737','state':'VA','weather_station':'NORFOLK INTL AP'},
{'icao_code':'KP60','row':462,'col':254,'stn_id_cdo':'GH... | {'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 | """
Script: coverage.py
Identifies domains that only occur in multi-domain proteins. The main
script is master.
--------------------
Felix A Kruger
momo.sander@ebi.ac.uk
"""
####
#### import modules.
####
import queryDevice
import operator
import yaml
import time
####
#### Load parameters.
####... |
#-----------------------------------------------------------------------------------------------------------------------
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 | """
Script: coverage.py
Identifies domains that only occur in multi-domain proteins. The main
script is master.
--------------------
Felix A Kruger
momo.sander@ebi.ac.uk
"""
####
#### import modules.
####
import queryDevice
import operator
import yaml
import time
####
#### Load parameters.
####... |
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 | """
Script: coverage.py
Identifies domains that only occur in multi-domain proteins. The main
script is master.
--------------------
Felix A Kruger
momo.sander@ebi.ac.uk
"""
####
#### import modules.
####
import queryDevice
import operator
import yaml
import time
####
#### Load parameters.
####... | (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 | """
Script: coverage.py
Identifies domains that only occur in multi-domain proteins. The main
script is master.
--------------------
Felix A Kruger
momo.sander@ebi.ac.uk
"""
####
#### import modules.
####
import queryDevice
import operator
import yaml
import time
####
#### Load parameters.
####... | 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 | /**
* UI组件
* @module widgets
*/
/**
*定义FAPUI.Layout.AccordionLayout布局组件
*<p>以下代码将演示如何使用AccordionLayout组件</p>
define(function(require) {
require("jquery");
require("widgets/fapui-accordion");
require("widgets/fapui-panel");
$(function () {
var a = new FAPUI.Layout.AccordionLayout({
renderTo: "ab",//要渲染的位... | */
removeItem : function ( index ) {
var me = this;
var comp;
if ( FAPUI.isNumber ( index ) ) {
comp = $ ( me.el.children ( "div[index=\"" + index + "\"]" )[ 0 ] );
} else {
comp = $ ( me.el.children ( "div[itemId=\"" + index + "\"]" )[ 0 ] );
index = parseInt ( comp.attr ( "index... | random_line_split | |
fapui-accordion.js | /**
* UI组件
* @module widgets
*/
/**
*定义FAPUI.Layout.AccordionLayout布局组件
*<p>以下代码将演示如何使用AccordionLayout组件</p>
define(function(require) {
require("jquery");
require("widgets/fapui-accordion");
require("widgets/fapui-panel");
$(function () {
var a = new FAPUI.Layout.AccordionLayout({
renderTo: "ab",//要渲染的位... | conditional_block | ||
stoopid.py |
import torch
from typing import Tuple
from math import floor
class VisualQNetwork(torch.nn.Module):
def __init__(
self,
input_shape: Tuple[int, int, int],
encoding_size: int,
output_size: int
):
"""
Creates a neural network that takes as input a batch of images (3
dimensional tensors... |
"""### Run Training"""
# Commented out IPython magic to ensure Python compatibility.
# -----------------
# This code is used to close an env that might not have been closed before
try:
env.close()
except:
pass
# -----------------
from mlagents_envs.registry import default_registry
from mlagents_envs.environment... | """
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 |
import torch
from typing import Tuple
from math import floor
class VisualQNetwork(torch.nn.Module):
def __init__(
self,
input_shape: Tuple[int, int, int],
encoding_size: int,
output_size: int
):
"""
Creates a neural network that takes as input a batch of images (3
dimensional tensors... |
env.close()
# Show the training graph
plt.plot(range(NUM_TRAINING_STEPS), cumulative_rewards)
| 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 |
import torch
from typing import Tuple
from math import floor
class VisualQNetwork(torch.nn.Module):
def __init__(
self,
input_shape: Tuple[int, int, int],
encoding_size: int,
output_size: int
):
"""
Creates a neural network that takes as input a batch of images (3
dimensional tensors... | (
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 | import torch
from typing import Tuple
from math import floor
class VisualQNetwork(torch.nn.Module):
def __init__(
self,
input_shape: Tuple[int, int, int],
encoding_size: int,
output_size: int
):
"""
Creates a neural network that takes as input a batch of images (3
dimensional tensors)... | 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 | """
Spiderplots & Density Spiderplots
==================================
"""
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# sphinx_gallery_thumbnail_number = 4
########################################################################################
# Here we'll set up an example which uses E... |
ax = ax.flat
for mix, (m, name, args, kwargs) in enumerate(modes):
normdf.pyroplot.spider(
mode=m,
ax=ax[mix],
vmin=0.05, # minimum percentile
fontsize=8,
unity_line=True,
index_order="incompatibility",
*args,
**kwargs
)
plt.tight_layout()
#####... | 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 | """
Spiderplots & Density Spiderplots
================================== | 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 | /*
Copyright 2017 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, ... | // 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 | // NG2
import { animate, state, style, transition, trigger } from '@angular/animations';
import { ChangeDetectorRef, Component, ElementRef, EventEmitter, forwardRef, HostBinding, Input, OnInit, Output } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import { DomSanitizer... | (range: rangeSelectModes): void {
this.rangeSelectMode = range;
if (range === 'startDate' && this.selection.length) {
this.updateView(this.selection[0]);
}
if (range === 'endDate' && this.selection.length === 2) {
this.updateView(this.selection[1]);
}
}
modelToSelection(model: model... | toggleRangeSelect | identifier_name |
DatePicker.ts | // NG2
import { animate, state, style, transition, trigger } from '@angular/animations';
import { ChangeDetectorRef, Component, ElementRef, EventEmitter, forwardRef, HostBinding, Input, OnInit, Output } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import { DomSanitizer... |
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 | // NG2
import { animate, state, style, transition, trigger } from '@angular/animations';
import { ChangeDetectorRef, Component, ElementRef, EventEmitter, forwardRef, HostBinding, Input, OnInit, Output } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import { DomSanitizer... | }
registerOnTouched(fn: Function): void {
this._onTouched = fn;
}
} | registerOnChange(fn: Function): void {
this._onChange = fn; | random_line_split |
cluster.go | package cluster
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"os/exec"
"os/user"
"strconv"
"strings"
"sync"
"text/template"
"time"
"github.com/flynn/flynn/cli/config"
"github.com/flynn/flynn/discoverd/client"
"github.com/flynn/flynn/pkg/iotool"
"github.com/flynn/flynn/pkg/random"
)
type... |
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 | package cluster
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"os/exec"
"os/user"
"strconv"
"strings"
"sync"
"text/template"
"time"
"github.com/flynn/flynn/cli/config"
"github.com/flynn/flynn/discoverd/client"
"github.com/flynn/flynn/pkg/iotool"
"github.com/flynn/flynn/pkg/random"
)
type... | (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 | package cluster
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"os/exec"
"os/user"
"strconv"
"strings"
"sync"
"text/template"
"time"
"github.com/flynn/flynn/cli/config"
"github.com/flynn/flynn/discoverd/client"
"github.com/flynn/flynn/pkg/iotool"
"github.com/flynn/flynn/pkg/random"
)
type... |
type BootResult struct {
ControllerDomain string
ControllerPin string
ControllerKey string
Instances []*Instance
}
func (c *Cluster) Boot(typ ClusterType, count int, dumpLogs io.Writer, killOnFailure bool) (res *BootResult, err error) {
if err := c.setup(); err != nil {
return nil, err
}
defer... | {
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 | package cluster
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"os/exec"
"os/user"
"strconv"
"strings"
"sync"
"text/template"
"time"
"github.com/flynn/flynn/cli/config"
"github.com/flynn/flynn/discoverd/client"
"github.com/flynn/flynn/pkg/iotool"
"github.com/flynn/flynn/pkg/random"
)
type... | 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 | import queryString from 'querystring';
import fetch from 'node-fetch';
import nodeUrl from 'url';
import {BrowserWindowConstructorOptions, Event as ElectronEvent} from 'electron';
import crypto from 'crypto';
import Bluebird from 'bluebird';
import {IOidcConfig, ITokenObject} from '../src/contracts/index';
// eslint-... | 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 | import queryString from 'querystring';
import fetch from 'node-fetch';
import nodeUrl from 'url';
import {BrowserWindowConstructorOptions, Event as ElectronEvent} from 'electron';
import crypto from 'crypto';
import Bluebird from 'bluebird';
import {IOidcConfig, ITokenObject} from '../src/contracts/index';
// eslint-... | (
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 | import queryString from 'querystring';
import fetch from 'node-fetch';
import nodeUrl from 'url';
import {BrowserWindowConstructorOptions, Event as ElectronEvent} from 'electron';
import crypto from 'crypto';
import Bluebird from 'bluebird';
import {IOidcConfig, ITokenObject} from '../src/contracts/index';
// eslint-... |
function startSilentRefreshing(
authorityUrl: string,
config: IOidcConfig,
tokenObject: ITokenObject,
refreshCallback: Function,
): void {
authoritiesToRefresh.push(authorityUrl);
silentRefresh(authorityUrl, config, tokenObject, refreshCallback);
}
function stopSilentRefreshing(authorityUrl: string): vo... | {
// 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 | import queryString from 'querystring';
import fetch from 'node-fetch';
import nodeUrl from 'url';
import {BrowserWindowConstructorOptions, Event as ElectronEvent} from 'electron';
import crypto from 'crypto';
import Bluebird from 'bluebird';
import {IOidcConfig, ITokenObject} from '../src/contracts/index';
// eslint-... |
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 | /*
Copyright 2020 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, ... | (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 | /*
Copyright 2020 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, ... |
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 | /*
Copyright 2020 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, ... | // 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 | /*
Copyright 2020 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, ... |
// 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 | import numpy as np
import os
# importing local tools:
import plottingTools as pt
# read ATM SED file
def getSED(SEDfile):
# 1) read wavelength (in m), flux (F_lambda in W/m2/m), emissivity and albedo
# 2) return wavelength in micron, flux (F_lambda in W/m2/micron), emissivity and albedo
wavelength, flux... | 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 | import numpy as np
import os
# importing local tools:
import plottingTools as pt
# read ATM SED file
def getSED(SEDfile):
# 1) read wavelength (in m), flux (F_lambda in W/m2/m), emissivity and albedo
# 2) return wavelength in micron, flux (F_lambda in W/m2/micron), emissivity and albedo
wavelength, flux... |
ABmin, ABmax = ABrange
destfiles = []
## SPHEREx standard wavelengths and expected m5 depths for static sources
wavSPH, m5static = getSPHERExSensitivity(dataDIR)
## noise-free SED computed by ATM and corrected for the Bus emissivity
magTrue = getATMBusSED(SEDfile, wavSPH, BusTaxi[0], Dast, rAU... | outfilerootname = './simSPHERExSpecDefault' | conditional_block |
analysisTools.py | import numpy as np
import os
# importing local tools:
import plottingTools as pt
# read ATM SED file
def getSED(SEDfile):
# 1) read wavelength (in m), flux (F_lambda in W/m2/m), emissivity and albedo
# 2) return wavelength in micron, flux (F_lambda in W/m2/micron), emissivity and albedo
wavelength, flux... |
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 | import numpy as np
import os
# importing local tools:
import plottingTools as pt
# read ATM SED file
def getSED(SEDfile):
# 1) read wavelength (in m), flux (F_lambda in W/m2/m), emissivity and albedo
# 2) return wavelength in micron, flux (F_lambda in W/m2/micron), emissivity and albedo
wavelength, flux... | (list1, list2):
zipped_pairs = zip(list1, list2)
return sorted(zipped_pairs)
def dumpSPHERExSED(MJD, wavelength, mag, magErr, dmVarOff, randNoise, filename):
np.savetxt(filename, (MJD, wavelength, mag, magErr, dmVarOff, randNoise))
return
def simSPHERExSpec(Dast, rAU, SEDfile, dataDIR, BusTaxi, LC, ... | getClosest | identifier_name |
timer.rs | //! The nRF51822 timer system operates off of the high frequency clock
//! (HFCLK) and provides three timers from the clock. Timer0 is tied
//! to the radio through some hard-coded peripheral linkages (e.g., there
//! are dedicated PPI connections between Timer0's compare events and
//! radio tasks, its capture tasks a... | (&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 | //! The nRF51822 timer system operates off of the high frequency clock
//! (HFCLK) and provides three timers from the clock. Timer0 is tied
//! to the radio through some hard-coded peripheral linkages (e.g., there
//! are dedicated PPI connections between Timer0's compare events and
//! radio tasks, its capture tasks a... |
_ => {
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 | //! The nRF51822 timer system operates off of the high frequency clock
//! (HFCLK) and provides three timers from the clock. Timer0 is tied
//! to the radio through some hard-coded peripheral linkages (e.g., there
//! are dedicated PPI connections between Timer0's compare events and
//! radio tasks, its capture tasks a... |
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 | //! The nRF51822 timer system operates off of the high frequency clock
//! (HFCLK) and provides three timers from the clock. Timer0 is tied
//! to the radio through some hard-coded peripheral linkages (e.g., there
//! are dedicated PPI connections between Timer0's compare events and
//! radio tasks, its capture tasks a... | //! 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 | use super::{
configuration::{self, CoreConfig, SessionConfig},
core_data::{CoreData, CoreHandle},
};
use crate::cmd::dap_server::{
debug_adapter::{
dap::adapter::DebugAdapter, dap::dap_types::Source, protocol::ProtocolAdapter,
},
DebuggerError,
};
use anyhow::{anyhow, Result};
use probe_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 | use super::{
configuration::{self, CoreConfig, SessionConfig},
core_data::{CoreData, CoreHandle},
};
use crate::cmd::dap_server::{
debug_adapter::{
dap::adapter::DebugAdapter, dap::dap_types::Source, protocol::ProtocolAdapter,
},
DebuggerError,
};
use anyhow::{anyhow, Result};
use probe_rs::... |
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 | use super::{
configuration::{self, CoreConfig, SessionConfig},
core_data::{CoreData, CoreHandle},
};
use crate::cmd::dap_server::{
debug_adapter::{
dap::adapter::DebugAdapter, dap::dap_types::Source, protocol::ProtocolAdapter,
},
DebuggerError,
};
use anyhow::{anyhow, Result};
use probe_rs::... | {
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 | use super::{
configuration::{self, CoreConfig, SessionConfig},
core_data::{CoreData, CoreHandle},
};
use crate::cmd::dap_server::{
debug_adapter::{
dap::adapter::DebugAdapter, dap::dap_types::Source, protocol::ProtocolAdapter,
},
DebuggerError,
};
use anyhow::{anyhow, Result};
use probe_rs::... | {
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 | //! HTML generation
//!
use crate::{Result, TomlMap};
use chrono::DateTime;
use handlebars::Handlebars;
use serde_json::Value as JsonValue;
use std::collections::HashMap;
use toml::value::Value as TomlValue;
/// Html to insert before and after diff chunks
pub struct DiffStyle {
/// Html to insert before a span of ... |
/// Generate diff between two text segments.
/// Enclose additions with <span class="add_style">...</span>
/// and deletions with <span class="del_style">
/// add_style, e.g., "bg-green 100 text-gray-500"
///
pub fn generate_diff(first: &str, second: &str, style: &DiffStyle) -> Result<String> {
use dissimilar::Ch... | {
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 generation
//!
use crate::{Result, TomlMap};
use chrono::DateTime;
use handlebars::Handlebars;
use serde_json::Value as JsonValue;
use std::collections::HashMap;
use toml::value::Value as TomlValue;
/// Html to insert before and after diff chunks
pub struct DiffStyle {
/// Html to insert before a span of ... | /// Test template processor
#[test]
fn test_html_page() {
use crate::render::Renderer;
const TEST_TEMPLATE: &str = "<html><body><h1>{{title}}</h1>{{content}}</body></html>";
let mut map = TomlMap::new();
map.insert("title".into(), "Abc".into());
// simulate processing
let expected = TEST_TEMPL... | let mut r2 = Renderer::init(&RenderConfig::default()).expect("ok");
r2.set("x".into(), toml::Value::from("xyz"));
assert!(true);
}
| random_line_split |
render.rs | //! HTML generation
//!
use crate::{Result, TomlMap};
use chrono::DateTime;
use handlebars::Handlebars;
use serde_json::Value as JsonValue;
use std::collections::HashMap;
use toml::value::Value as TomlValue;
/// Html to insert before and after diff chunks
pub struct DiffStyle {
/// Html to insert before a span of ... | () -> 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 | /*
Copyright 2014 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, ... |
result := make([]byte, int64QuantityExpectedBytes)
result[0] = '"'
number, suffix := q.CanonicalizeBytes(result[1:1])
// if the same slice was returned to us that we passed in, avoid another allocation by copying number into
// the source slice and returning that
if len(number) > 0 && &number[0] == &result[1] &&... | {
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 | /*
Copyright 2014 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, ... | (y Quantity) {
q.s = ""
if q.IsZero() {
q.Format = y.Format
}
if q.d.Dec == nil && y.d.Dec == nil && q.i.Sub(y.i) {
return
}
q.ToDec().d.Dec.Sub(q.d.Dec, y.AsDec())
}
// Cmp returns 0 if the quantity is equal to y, -1 if the quantity is less than y, or 1 if the
// quantity is greater than y.
func (q *Quantit... | Sub | identifier_name |
quantity.go | /*
Copyright 2014 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, ... |
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 | /*
Copyright 2014 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, ... |
// 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 | import sys
from pathlib import Path
from functools import partial
from multiprocessing import Pool
from datetime import datetime
import click
import rasterio as rio
from rasterio.windows import Window
from tiling.const_stride import ConstStrideTiles
from tiling.const_size import ConstSizeTiles
from dataflow.io_utils... |
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 | import sys
from pathlib import Path
from functools import partial
from multiprocessing import Pool
from datetime import datetime
import click
import rasterio as rio
from rasterio.windows import Window
from tiling.const_stride import ConstStrideTiles
from tiling.const_size import ConstSizeTiles
from dataflow.io_utils... | if __name__ == "__main__":
cli() | cli.add_command(run_const_size_tiler, name="const_size")
| random_line_split |
generate_tiles.py | import sys
from pathlib import Path
from functools import partial
from multiprocessing import Pool
from datetime import datetime
import click
import rasterio as rio
from rasterio.windows import Window
from tiling.const_stride import ConstStrideTiles
from tiling.const_size import ConstSizeTiles
from dataflow.io_utils... |
@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 | import sys
from pathlib import Path
from functools import partial
from multiprocessing import Pool
from datetime import datetime
import click
import rasterio as rio
from rasterio.windows import Window
from tiling.const_stride import ConstStrideTiles
from tiling.const_size import ConstSizeTiles
from dataflow.io_utils... | (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 | Ext.ns('Ext.ux.grid');
Ext.ux.grid.GridSummary = function(config) {
Ext.apply(this, config);
};
Ext.extend(Ext.ux.grid.GridSummary, Ext.util.Observable, {
// configurable scrollbar width (used only in the event the Ext.getScrollBarWidth() method is not available)
scrollBarWidth : 17,
// private
i... |
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 | Ext.ns('Ext.ux.grid');
Ext.ux.grid.GridSummary = function(config) {
Ext.apply(this, config);
};
Ext.extend(Ext.ux.grid.GridSummary, Ext.util.Observable, {
// configurable scrollbar width (used only in the event the Ext.getScrollBarWidth() method is not available)
scrollBarWidth : 17,
// private
i... |
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 | //
//! Copyright 2020 Alibaba Group Holding Limited.
//!
//! Licensed under the Apache License, Version 2.0 (the "License");
//! you may not use this file except in compliance with the License.
//! You may obtain a copy of the License at
//!
//! http://www.apache.org/licenses/LICENSE-2.0
//!
//! Unless required ... |
}
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 | //
//! Copyright 2020 Alibaba Group Holding Limited.
//!
//! Licensed under the Apache License, Version 2.0 (the "License");
//! you may not use this file except in compliance with the License.
//! You may obtain a copy of the License at
//!
//! http://www.apache.org/licenses/LICENSE-2.0
//!
//! Unless required ... | } | Session::new(&mut self.inner, matched, self.batch_size, ca)
} | random_line_split |
output.rs | //
//! Copyright 2020 Alibaba Group Holding Limited.
//!
//! Licensed under the Apache License, Version 2.0 (the "License");
//! you may not use this file except in compliance with the License.
//! You may obtain a copy of the License at
//!
//! http://www.apache.org/licenses/LICENSE-2.0
//!
//! Unless required ... |
#[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 | //
//! Copyright 2020 Alibaba Group Holding Limited.
//!
//! Licensed under the Apache License, Version 2.0 (the "License");
//! you may not use this file except in compliance with the License.
//! You may obtain a copy of the License at
//!
//! http://www.apache.org/licenses/LICENSE-2.0
//!
//! Unless required ... | (&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 | use clap::*;
use gre::*;
use isosurface::{marching_cubes::MarchingCubes, source::Source};
use kiss3d::nalgebra::{Perspective3, Point3, Rotation3, Vector3};
use rand::prelude::*;
use std::f32::consts::PI;
use std::ops::{Add, Mul, Sub};
use svg::node::element::path::Data;
use svg::node::element::*;
#[derive(Parser)]
#[c... | 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 | use clap::*;
use gre::*;
use isosurface::{marching_cubes::MarchingCubes, source::Source};
use kiss3d::nalgebra::{Perspective3, Point3, Rotation3, Vector3};
use rand::prelude::*;
use std::f32::consts::PI;
use std::ops::{Add, Mul, Sub};
use svg::node::element::path::Data;
use svg::node::element::*;
#[derive(Parser)]
#[c... |
}
route.push((x, y));
route
}
| {
break;
} | conditional_block |
main.rs | use clap::*;
use gre::*;
use isosurface::{marching_cubes::MarchingCubes, source::Source};
use kiss3d::nalgebra::{Perspective3, Point3, Rotation3, Vector3};
use rand::prelude::*;
use std::f32::consts::PI;
use std::ops::{Add, Mul, Sub};
use svg::node::element::path::Data;
use svg::node::element::*;
#[derive(Parser)]
#[c... |
fn is_inside_polygons(p: (f64, f64), polygons: &Vec<Vec<(f64, f64)>>) -> bool {
for polygon in polygons {
if is_inside_a_polygon(p, polygon) {
return true;
}
}
false
}
fn main() {
let opts: Opts = Opts::parse();
let groups = art(&opts);
let mut document = base_document("yellow", opts.width,... | {
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 | use clap::*;
use gre::*;
use isosurface::{marching_cubes::MarchingCubes, source::Source};
use kiss3d::nalgebra::{Perspective3, Point3, Rotation3, Vector3};
use rand::prelude::*;
use std::f32::consts::PI;
use std::ops::{Add, Mul, Sub};
use svg::node::element::path::Data;
use svg::node::element::*;
#[derive(Parser)]
#[c... | (precision: f64, width: f64, height: f64) -> Self {
let wi = (width / precision).ceil() as usize;
let hi = (height / precision).ceil() as usize;
let counters = vec![0; wi * hi];
Passage {
precision,
width,
height,
counters,
}
}
fn index(self: &Self, (x, y): (f64, f64)) -... | new | identifier_name |
gossip.rs | #![allow(clippy::arithmetic_side_effects)]
#[macro_use]
extern crate log;
use {
rayon::iter::*,
solana_gossip::{
cluster_info::{ClusterInfo, Node},
contact_info::{LegacyContactInfo as ContactInfo, Protocol},
crds::Cursor,
gossip_service::GossipService,
},
solana_perf::pa... |
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 | #![allow(clippy::arithmetic_side_effects)]
#[macro_use]
extern crate log;
use {
rayon::iter::*,
solana_gossip::{
cluster_info::{ClusterInfo, Node},
contact_info::{LegacyContactInfo as ContactInfo, Protocol},
crds::Cursor,
gossip_service::GossipService,
},
solana_perf::pa... | 10_000,
&vote_keypairs,
vec![100; vote_keypairs.len()],
);
let bank0 = Bank::new_for_tests(&genesis_config_info.genesis_config);
let bank_forks = Arc::new(RwLock::new(BankForks::new(bank0)));
let nodes: Vec<_> = vote_keypairs
.into_iter()
.map(|keypairs| {
... |
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 | #![allow(clippy::arithmetic_side_effects)]
#[macro_use]
extern crate log;
use {
rayon::iter::*,
solana_gossip::{
cluster_info::{ClusterInfo, Node},
contact_info::{LegacyContactInfo as ContactInfo, Protocol},
crds::Cursor,
gossip_service::GossipService,
},
solana_perf::pa... | () {
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 | #![allow(clippy::arithmetic_side_effects)]
#[macro_use]
extern crate log;
use {
rayon::iter::*,
solana_gossip::{
cluster_info::{ClusterInfo, Node},
contact_info::{LegacyContactInfo as ContactInfo, Protocol},
crds::Cursor,
gossip_service::GossipService,
},
solana_perf::pa... |
/// 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>(num: usize, topo: F)
where
F: Fn(&Vec<(Arc<Cluster... | {
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 | import tkinter as tk
texte1 = "kd oqnbgzhm ehbghdq ztqz tm bncd ozq rtarshstshnm zkogzadshptd: bgzptd kdssqd drs qdlokzbdd ozq tmd ztsqd. tshkhrdq kz eqdptdmbd cdr kdssqdr ontq cdbncdq kd ldrrzfd."
texte2 = "gx qosvlnkd wkvlkxo xiu vscx qno yd fsu cx qniix cx unkggx kdvsddyx xu vsdukxdu g'kdckvx. gxi gxuuoxi cy fsu... | liste_clef = list(clef)
a = 0
alphabet = "abcdefghijklmnopqrstuvwxyz"
alphabet_liste = list(alphabet)
for i in range(len(liste_texte)):
if liste_texte[i] in alphabet:
if position_lettre(liste_texte[i])+position_lettre(liste_clef[a]) < 0:
liste_texte[i] = alph... | liste_texte = list(texte)
| identifier_name |
decrypt.py | import tkinter as tk
texte1 = "kd oqnbgzhm ehbghdq ztqz tm bncd ozq rtarshstshnm zkogzadshptd: bgzptd kdssqd drs qdlokzbdd ozq tmd ztsqd. tshkhrdq kz eqdptdmbd cdr kdssqdr ontq cdbncdq kd ldrrzfd."
texte2 = "gx qosvlnkd wkvlkxo xiu vscx qno yd fsu cx qniix cx unkggx kdvsddyx xu vsdukxdu g'kdckvx. gxi gxuuoxi cy fsu... | 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 | import tkinter as tk
texte1 = "kd oqnbgzhm ehbghdq ztqz tm bncd ozq rtarshstshnm zkogzadshptd: bgzptd kdssqd drs qdlokzbdd ozq tmd ztsqd. tshkhrdq kz eqdptdmbd cdr kdssqdr ontq cdbncdq kd ldrrzfd."
texte2 = "gx qosvlnkd wkvlkxo xiu vscx qno yd fsu cx qniix cx unkggx kdvsddyx xu vsdukxdu g'kdckvx. gxi gxuuoxi cy fsu... |
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 | import tkinter as tk
texte1 = "kd oqnbgzhm ehbghdq ztqz tm bncd ozq rtarshstshnm zkogzadshptd: bgzptd kdssqd drs qdlokzbdd ozq tmd ztsqd. tshkhrdq kz eqdptdmbd cdr kdssqdr ontq cdbncdq kd ldrrzfd."
texte2 = "gx qosvlnkd wkvlkxo xiu vscx qno yd fsu cx qniix cx unkggx kdvsddyx xu vsdukxdu g'kdckvx. gxi gxuuoxi cy fsu... | 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 | package main
import (
"fmt"
"math"
"os"
"os/exec"
"os/user"
"path/filepath"
"strconv"
"strings"
"unicode"
"github.com/AlecAivazis/survey/v2"
"github.com/pbnjay/memory"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/crowdsecurity/crowdsec/pkg/metabase"
"github.com/crowdsecurity/... |
log.Warnf("You are potentially exposing your metabase port to the internet (addr: %s), please consider using a reverse proxy", addr)
}
func disclaimer(forceYes *bool) error {
if !*forceYes {
var answer bool
prompt := &survey.Confirm{
Message: "CrowdSec takes no responsibility for the security of your metabas... | {
return
} | conditional_block |
dashboard.go | package main
import (
"fmt"
"math"
"os"
"os/exec"
"os/user"
"path/filepath"
"strconv"
"strings"
"unicode"
"github.com/AlecAivazis/survey/v2"
"github.com/pbnjay/memory"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/crowdsecurity/crowdsec/pkg/metabase"
"github.com/crowdsecurity/... | () *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 | package main
import (
"fmt"
"math"
"os"
"os/exec"
"os/user"
"path/filepath"
"strconv"
"strings"
"unicode"
"github.com/AlecAivazis/survey/v2"
"github.com/pbnjay/memory"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/crowdsecurity/crowdsec/pkg/metabase"
"github.com/crowdsecurity/... | }
dockerGroup, err = user.LookupGroup(crowdsecGroup)
if err != nil {
return dockerGroup, fmt.Errorf("unable to lookup '%s' group: %+v", dockerGroup, err)
}
}
intID, err := strconv.Atoi(dockerGroup.Gid)
if err != nil {
return dockerGroup, fmt.Errorf("unable to convert group ID to int: %s", err)
}
if er... |
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 | package main
import (
"fmt"
"math"
"os"
"os/exec"
"os/user"
"path/filepath"
"strconv"
"strings"
"unicode"
"github.com/AlecAivazis/survey/v2"
"github.com/pbnjay/memory"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/crowdsecurity/crowdsec/pkg/metabase"
"github.com/crowdsecurity/... |
func NewDashboardStopCmd() *cobra.Command {
var cmdDashStop = &cobra.Command{
Use: "stop",
Short: "Stops the metabase container.",
Long: `Stops the metabase container using docker.`,
Args: cobra.ExactArgs(0),
DisableAutoGenTag: true,
RunE: func(cmd *cob... | {
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 | /*
Copyright 2020 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, ... | "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 | /*
Copyright 2020 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, ... | (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 | /*
Copyright 2020 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, ... |
func getEnabledControllers(ctx *cli.Context) []controller.Controller {
controllers := []controller.Controller{
seccompprofile.NewController(),
profilerecorder.NewController(),
}
if ctx.Bool(selinuxFlag) {
controllers = append(controllers, selinuxprofile.NewController())
}
return controllers
}
func runDa... | {
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 | /*
Copyright 2020 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, ... |
setupLog.Info("ending daemon")
return nil
}
func runLogEnricher(ctx *cli.Context) error {
const component = "log-enricher"
printInfo(component)
return enricher.New(ctrl.Log.WithName(component)).Run()
}
func runNonRootEnabler(ctx *cli.Context) error {
const component = "non-root-enabler"
printInfo(component)
... | {
return errors.Wrap(err, "SPOd error")
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.