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 |
|---|---|---|---|---|
jsonast.go | // oneOf:
// - External ARM resources
// oneOf:
// allOf:
// $ref: {{ base resource for ARM specific stuff like locks, deployments, etc }}
// oneOf:
// - ARM specific resources. I'm not 100% sure why...
//
// allOf acts like composition which composites each schema from the ch... |
// add documentation
fieldDefinition = fieldDefinition.WithDescription(prop.Description)
// add validations
isRequired := false
for _, required := range schema.Required {
if prop.Property == required {
isRequired = true
break
}
}
if isRequired {
fieldDefinition = fieldDefinition.MakeR... | {
return nil, err
} | conditional_block |
jsonast.go | }}
// oneOf:
// - External ARM resources
// oneOf:
// allOf:
// $ref: {{ base resource for ARM specific stuff like locks, deployments, etc }}
// oneOf:
// - ARM specific resources. I'm not 100% sure why...
//
// allOf acts like composition which composites each schema from th... | if isRequired {
fieldDefinition = fieldDefinition.MakeRequired()
} else {
fieldDefinition = fieldDefinition.MakeOptional()
}
fields = append(fields, fieldDefinition)
}
// see: https://json-schema.org/understanding-json-schema/reference/object.html#properties
if schema.AdditionalProperties == nil {
... | isRequired = true
break
}
}
| random_line_split |
main.js | out blurb, change html, change active state, fade in
$(".pill").on('click', function(event) {
event.preventDefault();
// deactivate all pills
deactivateAll();
// activate THIS one
$(this).addClass("active");
// fade out title and text, change each mid fade
var id = checkId($(this).attr("... |
// Answer is correct, highlight answer label green, change resultBox h4 text to Green "Correct!", fadeTo box
function correct(label) {
$(label).css("background", "rgba(88, 217, 88, 0.6)");
$("#resultBoxTitle").css("color", "green");
$("#resultBoxTitle").removeClass("text-info");
$("#resultBoxTitle... | {
var radios = $("input")
var labels = $("label")
for(var i = 0; i < radios.length; i++){
if(radios[i].checked) {
if ($(radios[i]).hasClass("correct")) {
correct(labels[i]);
solved = true;
} else {
wrong(labels[i]);
... | identifier_body |
main.js | Fade out blurb, change html, change active state, fade in
$(".pill").on('click', function(event) {
event.preventDefault();
// deactivate all pills
deactivateAll();
// activate THIS one
$(this).addClass("active");
// fade out title and text, change each mid fade
var id = checkId($(this).a... | (label) {
$(label).css("background", "rgba(88, 217, 88, 0.6)");
$("#resultBoxTitle").css("color", "green");
$("#resultBoxTitle").removeClass("text-info");
$("#resultBoxTitle").text("Correct!");
$("#resultBoxText").text("");
$("#resultBox").fadeTo(500, 1);
// reveal "next question" button ... | correct | identifier_name |
main.js | else if(id === "links") {
return ["Links", linksText];
}
else if(id === "contact") {
return ["Contact", contactText];
}
else if(id === "legal") {
return ["Legal", legalText];
}
}
// ----------- QUESTION JS -------------
var solved = false;
// Hint Button Click Listene... |
// Total Accuracy Pie Chart
var ctxP = document.getElementById("totalAccuracyPieChart").getContext('2d'); | random_line_split | |
search.py | param word: String
:return: Stemmed word
"""
return stem(word)
def sanitize(text, stop_word_list):
"""
Reads a text, remove stop words, stem the words.
:param text: String
:return: List of words
"""
# convert the text into Unicode
text = unicode(text)
#print(type(te... |
#print("Doc ID: %s \tTF: %d" % (doc, idf_row.get(doc)))
DWij = idf_row.get(doc)
#Njq = q_tf_idf.get(t) * idf_row.get(doc)
if doc_vals.has_key(doc):
vals = doc_vals.get(doc)
vals["DWiq"] += pow(DWiq, 2)
... | continue | random_line_split |
search.py |
def stemm_word(word):
"""
Use Porter stemmer to stem words.
:param word: String
:return: Stemmed word
"""
return stem(word)
def sanitize(text, stop_word_list):
"""
Reads a text, remove stop words, stem the words.
:param text: String
:return: List of words
"""
... | stop_word_list = None
if stop_word_list_file_path == None:
stop_word_list = set(stopwords.words('english'))
else:
fd = open(stop_word_list_file_path, "r")
txt = fd.readlines()
fd.close()
stop_word_list = []
for l in txt:
stop_word_list.append(l.lstri... | identifier_body | |
search.py | word: String
:return: Stemmed word
"""
return stem(word)
def sanitize(text, stop_word_list):
"""
Reads a text, remove stop words, stem the words.
:param text: String
:return: List of words
"""
# convert the text into Unicode
text = unicode(text)
#print(type(text))
... |
# score of all docs for this query
doc_vals = {}
# Wiq denominator in CosSim
DWiq = 0
for t in tf_idf_table:
DWiq = q_tf_idf.get(t)
# if the term is not in query, ignore
if DWiq == None:
continue
#print("Term: %s \t\t Query TF-IDF: %d" % (... | if tf_idf_table.has_key(term):
q_tf_idf[term] = tf.get(term) # * log(N/1)
else:
# if the query term is NOT found in files, set IDF to 0
q_tf_idf[term] = 0 | conditional_block |
search.py | _words = []
for w in words:
# ignore numbers
if w.isnumeric():
continue
# print("Word (Before Punctuation): " + w)
# remove punctuation
# Ref: https://stackoverflow.com/questions/265960/best-way-to-strip-punctuation-from-a-string-in-python
# w = w.trans... | build_graph | identifier_name | |
offline_replica.rs | ::{
Cmd, CmdResponse, CreateRegister, EditRegister, Query, QueryResponse, RegisterCmd,
RegisterQuery, Request, Response, SignedRegisterCreate, SignedRegisterEdit,
},
register::{Action, Entry, EntryHash, Permissions, Policy, Register as RegisterReplica, User},
};
use bincode::serialize;
use std:... | (&mut self, entry: &[u8]) -> Result<()> {
let children = self.register.read();
if children.len() > 1 {
return Err(Error::ContentBranchDetected(children));
}
self.write_atop(entry, children.into_iter().map(|(hash, _)| hash).collect())
}
/// Write a new value onto the... | write | identifier_name |
offline_replica.rs | ::{
Cmd, CmdResponse, CreateRegister, EditRegister, Query, QueryResponse, RegisterCmd,
RegisterQuery, Request, Response, SignedRegisterCreate, SignedRegisterEdit,
},
register::{Action, Entry, EntryHash, Permissions, Policy, Register as RegisterReplica, User},
};
use bincode::serialize;
use std:... |
// If not all were Ok, we will return the first error sent to us.
for resp in responses.iter().flatten() {
if let Response::Cmd | {
return Ok(());
} | conditional_block |
offline_replica.rs | ::{
Cmd, CmdResponse, CreateRegister, EditRegister, Query, QueryResponse, RegisterCmd,
RegisterQuery, Request, Response, SignedRegisterCreate, SignedRegisterEdit,
},
register::{Action, Entry, EntryHash, Permissions, Policy, Register as RegisterReplica, User},
};
use bincode::serialize;
use std:... |
/// Return the number of items held in the register
pub fn size(&self) -> u64 {
self.register.size()
}
/// Return a value corresponding to the provided 'hash', if present.
pub fn get(&self, hash: EntryHash) -> Result<&Entry> {
let entry = self.register.get(hash)?;
Ok(entry... | {
self.register.tag()
} | identifier_body |
offline_replica.rs | messages::{
Cmd, CmdResponse, CreateRegister, EditRegister, Query, QueryResponse, RegisterCmd,
RegisterQuery, Request, Response, SignedRegisterCreate, SignedRegisterEdit,
},
register::{Action, Entry, EntryHash, Permissions, Policy, Register as RegisterReplica, User},
};
use bincode::serialize;... | }
self.write_atop(entry, children.into_iter().map(|(hash, _)| hash).collect())
}
/// Write a new value onto the Register atop latest value.
/// If there are branches of content/entries, it automatically merges them
/// all leaving the new value as a single latest value of the Register.... | /// required to merge/resolve the branches, invoke the `write_merging_branches` API.
pub fn write(&mut self, entry: &[u8]) -> Result<()> {
let children = self.register.read();
if children.len() > 1 {
return Err(Error::ContentBranchDetected(children)); | random_line_split |
scene_test.js | 50, 280, 0, new THREE.Vector3(-500, 360, -2300), new THREE.Quaternion(Math.sin(Math.PI * 0.5), 0, 0, Math.cos(Math.PI * 0.5)), baseMaterialRed);
var cone1 = createCone(400, 250, 0, new THREE.Vector3(500, 175, -1200), quat, baseMaterialRed);
var cone1 = createCone(150, 120, 0, new THREE.Vector3(600, 340, -2700), new... | {
var objThree = rigidBodies[i];
var objPhys = objThree.userData.physicsBody;
var ms = objPhys.getMotionState();
if (ms) {
ms.getWorldTransform(transformAux1);
var p = transformAux1.getOrigin();
var q = transformAux1.getRotation();
objThree.position.set(p.x(), p.y(), p.z());
... | conditional_block | |
scene_test.js | , 30, 30);
light.castShadow = true;
var d = 30;
light.shadow.camera.left = - d;
light.shadow.camera.right = d;
light.shadow.camera.top = d;
light.shadow.camera.bottom = - d;
light.shadow.camera.near = 1; | light.shadow.camera.far = 100;
light.shadow.mapSize.x = 1024;
light.shadow.mapSize.y = 1024;
scene.add(light);
stats = new Stats();
stats.domElement.style.position = 'absolute';
stats.domElement.style.top = '0px';
container.appendChild(stats.domElement);
// cubeCamera for reflection effect
cube... | random_line_split | |
scene_test.js | 00), new THREE.Quaternion(0, Math.sin(-Math.PI * 0.05), 0, Math.cos(-Math.PI * 0.05)), baseMaterialGreen);
// spheres
var sphere0 = createSphere(80, 0, new THREE.Vector3(500, 270, -2000), quat, baseMaterialRed);
var sphere1 = createSphere(100, 0, new THREE.Vector3(-400, 190, -1000), quat, baseMaterialGreen);
v... | {
requestAnimationFrame(animate);
render();
stats.update();
} | identifier_body | |
scene_test.js | .Quaternion();
var baseMaterialRed = new THREE.MeshPhongMaterial({ color: 0xaa0000 });
var baseMaterialYel = new THREE.MeshPhongMaterial({ color: 0xa0a000 });
var baseMaterialGreen = new THREE.MeshPhongMaterial({ color: 0x00a000 });
// boxes of the glsl's quads
var theta = Math.atan(0.1);
var slope = crea... | initInput | identifier_name | |
main.rs | ::TermionBackend;
use tui::Terminal;
// use simplelog::{CombinedLogger, WriteLogger, LevelFilter, Config as LogConfig};
// use std::fs::File;
use std::io::{stdout, BufWriter};
fn main() {
if let Err(e) = run() {
// If an error was raised during an interactive mode call while the alternate screen is in
... | () -> anyhow::Result<()> {
// CombinedLogger::init(
// vec![
// WriteLogger::new(LevelFilter::Debug, LogConfig::default(), File::create("rhc.log").unwrap()),
// ]
// ).unwrap();
let args: Args = Args::from_args();
let output_file = args
.output_file
.map(|pat... | run | identifier_name |
main.rs | backend::TermionBackend;
use tui::Terminal;
// use simplelog::{CombinedLogger, WriteLogger, LevelFilter, Config as LogConfig};
// use std::fs::File;
use std::io::{stdout, BufWriter};
fn main() {
if let Err(e) = run() {
// If an error was raised during an interactive mode call while the alternate screen is ... | match &args.file {
Some(path) => {
let def: RequestDefinition =
load_file(&path, RequestDefinition::new, "request definition")?;
let env_path: Option<PathBuf> = args.environment;
let env: Option<Environment> = env_path
... | // the file names for the request definition that's either provided or selected, as well as the
// environment being used (if any), as these are required for the prompt_for_variables
// function.
let result: anyhow::Result<Option<SelectedValues>> = { | random_line_split |
main.rs | ::TermionBackend;
use tui::Terminal;
// use simplelog::{CombinedLogger, WriteLogger, LevelFilter, Config as LogConfig};
// use std::fs::File;
use std::io::{stdout, BufWriter};
fn main() {
if let Err(e) = run() {
// If an error was raised during an interactive mode call while the alternate screen is in
... |
})?;
// Load the config file using this priority:
// 1. The file specified with the --config arg, if present
// 2. $XDG_CONFIG_HOME/rhc/config.toml, if XDG_CONFIG_HOME is defined
// 3. ~/.config/rhc/config.toml, if present
// If none of the above exist, use the default Config.
let raw_conf... | {
Err(anyhow!("No config file found at `{}`", c.to_string_lossy()))
} | conditional_block |
main.rs | ::TermionBackend;
use tui::Terminal;
// use simplelog::{CombinedLogger, WriteLogger, LevelFilter, Config as LogConfig};
// use std::fs::File;
use std::io::{stdout, BufWriter};
fn main() |
type OurTerminal = Terminal<TermionBackend<AlternateScreen<RawTerminal<Stdout>>>>;
/// Set up/create the terminal for use in interactive mode.
fn get_terminal() -> anyhow::Result<OurTerminal> {
let stdout = std::io::stdout().into_raw_mode()?;
let stdout = AlternateScreen::from(stdout);
let backend = Term... | {
if let Err(e) = run() {
// If an error was raised during an interactive mode call while the alternate screen is in
// use, we have to flush stdout here or the user will not see the error message.
std::io::stdout().flush().unwrap();
// Seems like this initial newline is necessary o... | identifier_body |
jwt.rs | .kid
.as_ref()
.ok_or_else(|| Error::Input("Token does not specify the key id".to_string()))?;
let key = self
.jwks
.find(key_id)
.filter(|key| key.alg == header.alg && key.r#use == "... | jsonwebtoken::decode_header(token).map_err(|err| Error::Input(err.to_string()))?;
let key = match header.alg {
Algorithm::RS256 | Algorithm::RS384 | Algorithm::RS512 => {
let key_id = header | random_line_split | |
jwt.rs | (&self, key_id: &str) -> Option<&Key> {
self.keys.iter().find(|key| key.kid == key_id)
}
}
/// A set of values encoded in a JWT that the issuer claims to be true.
#[derive(Debug, Deserialize)]
struct Claims {
/// Audience (who or that the token is intended for). E.g. "https://api.xsnippet.org".
#[a... | find | identifier_name | |
jwt.rs | }
alg => return Err(Error::Input(format!("Unsupported algorithm: {:?}", alg))),
};
match jsonwebtoken::decode::<Claims>(token, &key, &self.validation) {
Ok(data) => Ok(User::Authenticated {
name: data.claims.sub,
permissions: data.clai... | {
let header =
jsonwebtoken::decode_header(token).map_err(|err| Error::Input(err.to_string()))?;
let key = match header.alg {
Algorithm::RS256 | Algorithm::RS384 | Algorithm::RS512 => {
let key_id = header
.kid
.as_ref()
... | identifier_body | |
stylesheet.js | }
}
};
function StyleSheet(seed, name) {
var head,
node,
sheet,
cssRules = {},
_rules,
_insertRule,
_deleteRule;
// Factory or constructor
if (!(this instanceof arguments.callee)) {
return new arguments.callee(seed,name);
}
... |
// Some selector values can cause IE to hang
if (!StyleSheet.isValidSelector(sel)) {
return this;
}
// Opera throws an error if there's a syntax error in assigned
// cssText. Avoid this using a worker styls collection, then
// as... | {
for (i = multi.length - 1; i >= 0; --i) {
this.set(multi[i], css);
}
return this;
} | conditional_block |
stylesheet.js | }
}
};
function StyleSheet(seed, name) | d.getElementById(seed.replace(/^#/,'')));
if (seed && sheets[seed]) {
return sheets[seed];
} else if (node && sheets[Y.stamp(node)]) {
return sheets[Y.stamp(node)];
}
if (!node || !/^(?:style|link)$/i.test(node.nodeName)) {
node = d.createElement('style');
no... | {
var head,
node,
sheet,
cssRules = {},
_rules,
_insertRule,
_deleteRule;
// Factory or constructor
if (!(this instanceof arguments.callee)) {
return new arguments.callee(seed,name);
}
head = d.getElementsByTagName('head')[0];
if (!head) ... | identifier_body |
stylesheet.js | }
}
};
function | (seed, name) {
var head,
node,
sheet,
cssRules = {},
_rules,
_insertRule,
_deleteRule;
// Factory or constructor
if (!(this instanceof arguments.callee)) {
return new arguments.callee(seed,name);
}
head = d.getElementsByTagName('head')[0];
... | StyleSheet | identifier_name |
stylesheet.js | }
}
};
function StyleSheet(seed, name) {
var head,
node,
sheet,
cssRules = {},
_rules,
_insertRule,
_deleteRule;
// Factory or constructor
if (!(this instanceof arguments.callee)) {
return new arguments.callee(seed,name);
}
... |
if (remove) { // remove the rule altogether
rules = sheet[_rules];
for (i = rules.length - 1; i >= 0; --i) {
if (rules[i] === rule) {
delete cssRules[sel];
_deleteRule... | } | random_line_split |
Puspesh_farmer1.py | last block of the chain.
def get_previous_block(self):
return self.chain[-1]
#It runs a lop and check if hash of new proof^2- previous proof^2 contains 4 leading zeroes.
#if yes,then it returns the new proof otherwise increment the new proof by 1 and iterates again.
def proof_of_work(self, previo... | (self, chain):
previous_block = chain[0]
block_index = 1
while block_index < len(chain):
block = chain[block_index]
if block['previous_hash'] != self.hash(previous_block):
return False
previous_proof = previous_block['proof']
... | is_chain_valid | identifier_name |
Puspesh_farmer1.py | block of the chain.
def get_previous_block(self):
return self.chain[-1]
| #It runs a lop and check if hash of new proof^2- previous proof^2 contains 4 leading zeroes.
#if yes,then it returns the new proof otherwise increment the new proof by 1 and iterates again.
def proof_of_work(self, previous_proof):
new_proof = 1
check_proof = False
while check_proof is ... | random_line_split | |
Puspesh_farmer1.py | _hash'] != self.hash(previous_block):
return False
previous_proof = previous_block['proof']
proof = block['proof']
hash_operation = hashlib.sha256(str(proof**2 - previous_proof**2).encode()).hexdigest()
if hash_operation[:4] != '0000':
... | ode", 400
for no | conditional_block | |
Puspesh_farmer1.py | return self.chain[-1]
#It runs a lop and check if hash of new proof^2- previous proof^2 contains 4 leading zeroes.
#if yes,then it returns the new proof otherwise increment the new proof by 1 and iterates again.
def proof_of_work(self, previous_proof):
new_proof = 1
check_proof = False... | def __init__(self):
self.chain = []
self.farmer_details = []
self.create_block(proof = 1, previous_hash = '0')
self.nodes = set()
#It creates a dictionary block which contains index(length of chain+1),timestamp( by using the module datetime),
#Proof( passes as parameter),previo... | identifier_body | |
main_utils.py | " + "=" * 30)
logger.add_line(str(model))
logger.add_line("=" * 30 + " Parameters " + "=" * 30)
logger.add_line(parameter_description(model))
return model
def distribute_model_to_cuda(models, args, batch_size, num_workers, ngpus_per_node):
squeeze = False
if not i... | else:
raise ValueError('Unknown optimizer.')
scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer, milestones=cfg['lr']['milestones'], gamma=cfg['lr']['gamma'])
if 'warmup' in cfg:
scheduler = GradualWarmupScheduler(optimizer,
multiplier=cfg[... | weight_decay=cfg['weight_decay']
)
| random_line_split |
main_utils.py | _cfg['audio_clip_duration'],
audio_fps=db_cfg['audio_fps'],
spect_fps=db_cfg['spectrogram_fps'],
joint_transform=joint_transform,
video_transform=video_transform,
audio_transform=audio_transforms,
max_offsync_augm=0.,
return_position=True,
return_labels=Fa... | desc += "{:70} | {:10} | {:30} | {}\n".format(
n, 'Trainable' if p.requires_grad else 'Frozen',
' x '.join([str(s) for s in p.size()]), str(np.prod(p.size()))) | conditional_block | |
main_utils.py | _cfg['use_augmentation'],
num_frames=int(db_cfg['video_fps'] * db_cfg['video_clip_duration']),
pad_missing=True,
)
audio_transforms = [
preprocessing.AudioPrep(
mono=db_cfg['audio_input']=='mono',
duration=db_cfg['audio_clip_duration'],
au... | accuracy | identifier_name | |
main_utils.py | as data
import torch.utils.data.distributed
if db_cfg['name'] == 'yt360':
db = build_360_dataset(db_cfg, split_cfg)
else:
db = build_video_dataset(db_cfg, split_cfg)
if distributed:
sampler = torch.utils.data.distributed.DistributedSampler(db)
else:
sampler = None
... | if self.window_size > 0:
self.q = deque(maxlen=self.window_size)
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0 | identifier_body | |
main.go | mode)"`
OutputStripFileExt string ` long:"output-strip-ext" description:"strip file extension from written files (also available in multi file mode)"`
Once string ` long:"once" description:"replace search term only one in a file, keep duplic... | (changesets []changeset) int {
var buffer bytes.Buffer
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
buffer.WriteString(scanner.Text() + "\n")
}
content := parseContentAsTemplate(buffer.String(), changesets)
fmt.Print(content.String())
return 0
}
func actionProcessFiles(changesets []changeset,... | actionProcessStdinTemplate | identifier_name |
main.go | mode)"`
OutputStripFileExt string ` long:"output-strip-ext" description:"strip file extension from written files (also available in multi file mode)"`
Once string ` long:"once" description:"replace search term only one in a file, keep duplic... |
content := parseContentAsTemplate(string(buffer), changesets)
output, status := writeContentToFile(fileitem, content)
return output, status, err
}
func applyChangesetsToLine(line string, changesets []changeset) (string, bool, bool) {
changed := false
skipLine := false
for i, changeset := range changesets {
... | {
return "", false, err
} | conditional_block |
main.go | file mode)"`
OutputStripFileExt string ` long:"output-strip-ext" description:"strip file extension from written files (also available in multi file mode)"`
Once string ` long:"once" description:"replace search term only one in a file, keep d... | regex = "(?i:" + regex + ")"
}
// --verbose
if opts.Verbose {
logMessage(fmt.Sprintf("Using regular expression: %s", regex))
}
// --regex-posix
if opts.RegexPosix {
ret = regexp.MustCompilePOSIX(regex)
} else {
ret = regexp.MustCompile(regex)
}
return ret
}
// handle special cli options
// eg. --he... | if opts.CaseInsensitive { | random_line_split |
main.go | mode)"`
OutputStripFileExt string ` long:"output-strip-ext" description:"strip file extension from written files (also available in multi file mode)"`
Once string ` long:"once" description:"replace search term only one in a file, keep duplic... |
func applyChangesetsToLine(line string, changesets []changeset) (string, bool, bool) {
changed := false
skipLine := false
for i, changeset := range changesets {
// --once, only do changeset once if already applied to file
if opts.Once != "" && changeset.MatchFound {
// --once=unique, skip matching lines
... | {
// try open file
buffer, err := os.ReadFile(fileitem.Path)
if err != nil {
return "", false, err
}
content := parseContentAsTemplate(string(buffer), changesets)
output, status := writeContentToFile(fileitem, content)
return output, status, err
} | identifier_body |
patterns.rs | ES,
SE,
SS,
EE,
Psk,
}
pub type MessagePattern = &'static [Token];
/// Handshake protocol specification.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct HandshakeTokens {
pub(crate) name: &'static str,
pub(crate) initiator: MessagePattern,
pub(crate) responder: MessagePattern,
... |
pattern!( | }); | random_line_split |
patterns.rs | ES,
SE,
SS,
EE,
Psk,
}
pub type MessagePattern = &'static [Token];
/// Handshake protocol specification.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct HandshakeTokens {
pub(crate) name: &'static str,
pub(crate) initiator: MessagePattern,
pub(crate) responder: MessagePattern,
... | (s: &str) -> Result<Self, Self::Err> {
if s.starts_with("psk") {
let n: u8 = s[3..].parse().map_err(|_| PatternError::InvalidPsk)?;
Ok(Self::Psk(n))
} else if s == "fallback" {
Ok(Self::Fallback)
} else {
Err(PatternError::UnsupportedModifier)
... | from_str | identifier_name |
patterns.rs | ES,
SE,
SS,
EE,
Psk,
}
pub type MessagePattern = &'static [Token];
/// Handshake protocol specification.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct HandshakeTokens {
pub(crate) name: &'static str,
pub(crate) initiator: MessagePattern,
pub(crate) responder: MessagePattern,
... |
/// Returns the number of psks used in the handshake.
pub fn number_of_psks(&self) -> usize {
self.modifiers
.0
.iter()
.filter(|modifier| {
if let HandshakeModifier::Psk(_) = modifier {
return true;
}
... | {
&self.pattern
} | identifier_body |
lib.rs | .cmp(b.0));
// Initialize empty huffman tree.
let mut tree = HuffmanTree {
list: Vec::new(),
};
//
let mut old_weight = 0;
let mut counter = 0;
for (weight, value) in self.list {
number_of_bits(max_bits, weight);
}
// Retur... | 3 => {
let did = dec.u32()?;
Some(did)
},
_ => unreachable!(),
};
// Check frame content size.
let window_size: u64 = if let Some(window_size) = window_size {
window_size
} else {
let window_size... | Some(did)
}, | random_line_split |
lib.rs | () -> Self {
Self {
literal: 0,
list: Vec::new(),
}
}
/// Add a weight for the next literal.
pub fn weight(&mut self, weight: u8) {
if weight != 0 {
self.list.push((weight, self.literal));
}
self.literal += 1;
}
// FIXME h... | new | identifier_name | |
gulpfile.js | )
.on(
'error',
notify.onError({
message: '<%= error.message %>',
title: 'PUG Error!',
})
)
.pipe(gulp.dest(outputDir))
.pipe(browserSync.stream({ once: true }));
});
gulp.task('sass', function () {
return gulp
.src([assetsDir + 'sass/**/*.scss', '!' + assetsDir + 'sass/**/_*.scss'])
.pi... | gulp.task('cssLint', function () {
return gulp
.src([
assetsDir + 'sass/**/*.scss',
'!' + assetsDir + 'sass/templates/*.scss',
])
.pipe(
postcss([stylelint(), reporter({ clearMessages: true })], {
syntax: postcss_scss,
})
);
});
gulp.task('set-dev-node-env', function(done) {
productionStatus ... | );
});
| random_line_split |
vr.rs | -> VrMoment {
{
let mut disp = self.disp.borrow_mut();
disp.sync_poses();
}
let mut new_controllers = Vec::new();
for event in self.vrsm.poll_events() {
match event {
VREvent::Display(VRDisplayEvent::Pause(_)) => self.paused = true,
... | pose | identifier_name | |
vr.rs | hardware API.
pub fn retrieve_size(&mut self) -> (u32, u32) {
size_from_data(&self.disp.borrow().data())
}
/// Synchronize with the hardware, returning transient details about the VR
/// system at the specific moment in time. This data can be used directly or
/// to update state variables.
... | proj: right_projection,
clip_offset: 0.5,
clip: Rect {
x: data.left_eye_parameters.render_width as u16,
y: 0,
w: data.right_eye_parameters.render_width as u16,
... | right: EyeParams {
eye: moment.inverse_stage * right_view.try_inverse().unwrap() * Point3::origin(),
view: right_view * moment.stage, | random_line_split |
vr.rs | _stage: na::one(),
exit: self.exit,
paused: self.paused,
new_controllers: new_controllers,
timestamp: 0.,
};
{
let disp = self.disp.borrow();
let data = disp.data();
let state = disp.synced_frame_data(self.near, self.far... | {
self.pose
} | identifier_body | |
mod.rs | ;
//! extern crate signal_hook;
//!
//! use std::io::Error;
//!
//! use signal_hook::consts::signal::*;
//! use signal_hook::iterator::Signals;
//!
//! fn main() -> Result<(), Error> {
//! let mut signals = Signals::new(&[
//! SIGHUP,
//! SIGTERM,
//! SIGINT,
//! SIGQUIT,
//! # ... | /// let handle = signals.handle();
/// thread::spawn(move || {
/// for signal in signals.forever() {
/// match signal {
/// SIGUSR1 => {},
/// SIGUSR2 => {},
/// _ => unreachable!(),
/// }
/// }
/// });
/// handle.cl... | /// use signal_hook::iterator::Signals;
///
/// # fn main() -> Result<(), Error> {
/// let mut signals = Signals::new(&[SIGUSR1, SIGUSR2])?; | random_line_split |
mod.rs | ;
//! extern crate signal_hook;
//!
//! use std::io::Error;
//!
//! use signal_hook::consts::signal::*;
//! use signal_hook::iterator::Signals;
//!
//! fn main() -> Result<(), Error> {
//! let mut signals = Signals::new(&[
//! SIGHUP,
//! SIGTERM,
//! SIGINT,
//! SIGQUIT,
//! # ... | /// Waits for some signals to be available and returns an iterator.
///
/// This is similar to [`pending`][SignalsInfo::pending]. If there are no signals available, it
/// tries to wait for some to arrive. However, due to implementation details, this still can
/// produce an empty iterator.
///
... | loop {
match read.read(&mut [0u8]) {
Ok(num_read) => break Ok(num_read > 0),
// If we get an EINTR error it is fine to retry reading from the stream.
// Otherwise we should pass on the error to the caller.
Err(error) => {
... | identifier_body |
mod.rs | signal_hook::low_level::raise(SIGUSR1).unwrap();
//! 'outer: loop {
//! // Pick up signals that arrived since last time
//! for signal in signals.pending() {
//! match signal as libc::c_int {
//! SIGHUP => {
//! // Reload configuration
//! ... | &se | identifier_name | |
ssd_train.py | 20
"""
import argparse
import datetime
import logging
import os
import time
from pathlib import Path
import torch
from draugr.numpy_utilities import SplitEnum
from draugr.torch_utilities import (
TorchCacheSession,
TorchEvalSession,
TorchTrainSession,
WarmupMultiStepLR,
)
from torch.nn impo... | writer.add_scalar(
"lr", optimiser.param_groups[0]["lr"], global_step=global_step
)
if iteration % kws.save_step == 0:
check_pointer.save(f"model_{iteration:06d}", **arguments)
if (
kws.eval_step > ... | random_line_split | |
ssd_train.py | 20
"""
import argparse
import datetime
import logging
import os
import time
from pathlib import Path
import torch
from draugr.numpy_utilities import SplitEnum
from draugr.torch_utilities import (
TorchCacheSession,
TorchEvalSession,
TorchTrainSession,
WarmupMultiStepLR,
)
from torch.nn impo... | help="Evaluate dataset every eval_step, disabled when eval_step < 0",
)
parser.add_argument("--use_tensorboard", default=True, type=str2bool)
parser.add_argument(
"--skip-test",
dest="skip_test",
help="Do not test the final model",
action="store_true",
)
args ... | """description"""
from configs.mobilenet_v2_ssd320_voc0712 import base_cfg
# from configs.efficient_net_b3_ssd300_voc0712 import base_cfg
# from configs.vgg_ssd300_voc0712 import base_cfg
parser = argparse.ArgumentParser(
description="Single Shot MultiBox Detector Training With PyTorch"
)
... | identifier_body |
ssd_train.py | 20
"""
import argparse
import datetime
import logging
import os
import time
from pathlib import Path
import torch
from draugr.numpy_utilities import SplitEnum
from draugr.torch_utilities import (
TorchCacheSession,
TorchEvalSession,
TorchTrainSession,
WarmupMultiStepLR,
)
from torch.nn impo... | ():
"""description"""
from configs.mobilenet_v2_ssd320_voc0712 import base_cfg
# from configs.efficient_net_b3_ssd300_voc0712 import base_cfg
# from configs.vgg_ssd300_voc0712 import base_cfg
parser = argparse.ArgumentParser(
description="Single Shot MultiBox Detector Training With PyTorch... | main | identifier_name |
ssd_train.py | 20
"""
import argparse
import datetime
import logging
import os
import time
from pathlib import Path
import torch
from draugr.numpy_utilities import SplitEnum
from draugr.torch_utilities import (
TorchCacheSession,
TorchEvalSession,
TorchTrainSession,
WarmupMultiStepLR,
)
from torch.nn impo... |
check_pointer.save("model_final", **arguments)
total_training_time = int(
time.time() - start_training_time
) # compute training time
logger.info(
f"Total training time: {datetime.timedelta(seconds = total_training_time)} ("
f"{total_training_time ... | write_metrics_recursive(
eval_result["metrics"],
"metrics/" + dataset,
writer,
iteration,
) | conditional_block |
controller.go | // Check for and handle deletion of cluster. Return early if it is being
// deleted or there was an error.
if result, err := r.handleDelete(ctx, cluster); err != nil {
span.RecordError(err)
log.Error(err, "deleting")
return reconcile.Result{}, err
} else if result != nil {
if log := log.V(1); log.Enabled()... | monitoringSecret, err = r.reconcileMonitoringSecret(ctx, cluster)
}
| conditional_block | |
controller.go | // ControllerName is the name of the PostgresCluster controller
ControllerName = "postgrescluster-controller"
)
// Reconciler holds resources for the PostgresCluster reconciler
type Reconciler struct {
Client client.Client
Owner client.FieldOwner
Recorder record.EventRecorder
Tracer trace.Trac... |
const ( | random_line_split | |
controller.go | clusterConfigMap *corev1.ConfigMap
clusterReplicationSecret *corev1.Secret
clusterPodService *corev1.Service
clusterVolumes []corev1.PersistentVolumeClaim
instanceServiceAccount *corev1.ServiceAccount
instances *observedInstances
patroniLeaderService *corev1.Se... | if metav1.IsControlledBy(object, cluster) {
uid := object.GetUID()
version := object.GetResourceVersion()
exactly := client.Preconditions{UID: &uid, ResourceVersion: &version}
return r.Client.Delete(ctx, object, exactly)
}
return nil
}
| identifier_body | |
controller.go | (ctx, cluster)
if err != nil || returnEarly {
return patchClusterStatus()
}
}
if err == nil {
clusterVolumes, err = r.observePersistentVolumeClaims(ctx, cluster)
}
if err == nil {
clusterVolumes, err = r.configureExistingPVCs(ctx, cluster, clusterVolumes)
}
if err == nil {
instances, err = r.observeI... | tupWithManager(m | identifier_name | |
TimelineFlameChartNetworkDataProvider.ts | () {
this.#minimumBoundaryInternal = 0;
this.#timeSpan = 0;
this.#events = [];
this.#maxLevel = 0;
this.#networkTrackAppender = null;
this.#traceEngineData = null;
}
setModel(traceEngineData: TraceEngine.Handlers.Migration.PartialTraceData|null): void {
this.#timelineDataInternal = nul... | constructor | identifier_name | |
TimelineFlameChartNetworkDataProvider.ts | this.timelineData();
return !this.#events.length;
}
maxStackDepth(): number {
return this.#maxLevel;
}
timelineData(): PerfUI.FlameChart.FlameChartTimelineData {
if (this.#timelineDataInternal && this.#timelineDataInternal.entryLevels.length !== 0) {
// The flame chart data is built alre... | const end = Math.max(timeToPixel(endTime), finish);
return {sendStart, headersEnd, finish, start, end};
}
/**
* Decorates the entry:
* Draw a waiting time between |sendStart| and |headersEnd|
* By adding a extra transparent white layer
* Draw a whisk between |start| and |sendStart|
... | random_line_split | |
TimelineFlameChartNetworkDataProvider.ts | this.timelineData();
return !this.#events.length;
}
maxStackDepth(): number {
return this.#maxLevel;
}
timelineData(): PerfUI.FlameChart.FlameChartTimelineData {
if (this.#timelineDataInternal && this.#timelineDataInternal.entryLevels.length !== 0) {
// The flame chart data is built alre... |
if (this.#lastSelection && this.#lastSelection.timelineSelection.object === selection.object) {
return this.#lastSelection.entryIndex;
}
if (!TimelineSelection.isSyntheticNetworkRequestDetailsEventSelection(selection.object)) {
return -1;
}
const index = this.#events.indexOf(selectio... | {
return -1;
} | conditional_block |
TimelineFlameChartNetworkDataProvider.ts | Selection.fromTraceEvent(selection.object), index);
}
return index;
}
entryColor(index: number): string {
if (!this.#networkTrackAppender) {
throw new Error('networkTrackAppender should not be empty');
}
return this.#networkTrackAppender.colorForEvent(this.#events[index]);
}
textColo... | if (!this.#priorityToValue) {
this.#priorityToValue = new Map([
[Protocol.Network.ResourcePriority.VeryLow, 1],
[Protocol.Network.ResourcePriority.Low, 2],
[Protocol.Network.ResourcePriority.Medium, 3],
[Protocol.Network.ResourcePriority.High, 4],
[Protocol.Network.Reso... | identifier_body | |
windows.rs | _registry_key(protocol: &str) -> String {
format!(r"SOFTWARE\Classes\{}", protocol)
}
fn get_configuration_registry_key(protocol: &str) -> String {
format!(r"Software\bitSpatter\Hermes\Protocols\{}", protocol)
}
/// Register associations with Windows to handle our protocol, and the command we'll invoke
fn reg... | .get_value("command")
.with_context(|| format!("command not registered when trying to handle url {}", url))?;
let could_send = {
let slot = MailslotName::local(&format!(r"bitSpatter\Hermes\{}", protocol));
trace!("Attempting to send URL to mailslot {}", slot.to_string());
if... | let protocol_command: Vec<_> = config | random_line_split |
windows.rs | _key(protocol: &str) -> String {
format!(r"SOFTWARE\Classes\{}", protocol)
}
fn get_configuration_registry_key(protocol: &str) -> String {
format!(r"Software\bitSpatter\Hermes\Protocols\{}", protocol)
}
/// Register associations with Windows to handle our protocol, and the command we'll invoke
fn register_com... | rl: &url::Url) -> String {
let mut path = url.path().to_owned();
if let Some(query) = url.query() {
path += "?";
path += query;
}
path
}
/// Dispatch the given URL to the correct mailslot or launch the editor
fn open_url(url: &str) -> Result<()> {
let url = url::Url::parse(url)?;
... | t_path_and_extras(u | identifier_name |
windows.rs | _key(protocol: &str) -> String {
format!(r"SOFTWARE\Classes\{}", protocol)
}
fn get_configuration_registry_key(protocol: &str) -> String {
format!(r"Software\bitSpatter\Hermes\Protocols\{}", protocol)
}
/// Register associations with Windows to handle our protocol, and the command we'll invoke
fn register_com... | lse {
trace!("Could not connect to Mailslot, assuming application is not running");
false
}
};
if !could_send {
let (exe_name, args) = {
debug!(
"registered handler for {}: {:?}",
protocol, protocol_command
);
... | if let Err(error) = client.send_message(full_path.as_bytes()) {
warn!("Could not send mail slot message to {}: {} -- assuming application is shutting down, starting a new one", slot.to_string(), error);
false
} else {
trace!("Delivered using Mailsl... | conditional_block |
lib.rs | 0,
// TSC = 0x40,
TSE = 0x41,
// TSW = 0x42,
// TSR = 0x43,
CDI = 0x50,
// LPD = 0x51,
TCON = 0x60,
TRES = 0x61,
DAM = 0x65,
// REV = 0x70,
// FLG = 0x71,
// AMV = 0x80,
// VV = 0x81,
// VDCS = 0x82,
PWS = 0xE3,
// TSSET = 0xE5,
}
/// An instance of a dis... |
}
/// Displays the contents of the internal buffer to the screen.
///
/// This operation blocks until the contents are completely shown.
pub fn show(&mut self) -> Result<(), ERR> {
self.setup()?;
let ptr = &self.buffer as *const _ as *const u8;
let len = mem::size_of_val(&... | {
*cell = (*cell & 0b11110000) | color as u8;
} | conditional_block |
lib.rs | ///
/// The provided `spi` bus will be used for most of the communication. The `delay` instance
/// is used when waiting for reset and drawing operations to complete. The `reset` pin can be
/// provided to make sure the device is reset before each new draw command. The `busy` pin is
/// used to poll... | {
dc.set_low()?;
spi.write(&[command as u8])?;
if !data.is_empty() {
dc.set_high()?;
for chunk in data.chunks(SPI_CHUNK_SIZE) {
spi.write(chunk)?;
}
}
Ok(())
} | identifier_body | |
lib.rs | 0,
// TSC = 0x40,
TSE = 0x41,
// TSW = 0x42,
// TSR = 0x43,
CDI = 0x50,
// LPD = 0x51,
TCON = 0x60,
TRES = 0x61,
DAM = 0x65,
// REV = 0x70,
// FLG = 0x71,
// AMV = 0x80,
// VV = 0x81,
// VDCS = 0x82,
PWS = 0xE3,
// TSSET = 0xE5,
}
/// An instance of a dis... | {
/// Creates a new display instance.
///
/// The provided `spi` bus will be used for most of the communication. The `delay` instance
/// is used when waiting for reset and drawing operations to complete. The `reset` pin can be
/// provided to make sure the device is reset before each new draw com... | ERR: From<SPI::Error> + From<RESET::Error> + From<BUSY::Error> + From<DC::Error>, | random_line_split |
lib.rs | 0,
// TSC = 0x40,
TSE = 0x41,
// TSW = 0x42,
// TSR = 0x43,
CDI = 0x50,
// LPD = 0x51,
TCON = 0x60,
TRES = 0x61,
DAM = 0x65,
// REV = 0x70,
// FLG = 0x71,
// AMV = 0x80,
// VV = 0x81,
// VDCS = 0x82,
PWS = 0xE3,
// TSSET = 0xE5,
}
/// An instance of a dis... | (&mut self, color: &[Color]) {
for (idx, cell) in color.chunks(2).enumerate() {
self.buffer[idx] = ((cell[0] as u8) << 4) | cell[1] as u8;
}
}
/// Sets a specific pixel color.
pub fn set_pixel(&mut self, x: usize, y: usize, color: Color) {
let cell = &mut self.buffer[y *... | copy_from | identifier_name |
proxy.go | , p.Handler()); err != nil {
log.WithError(err).Error("HTTP server shut down due to error")
}
log.Info("Stopped HTTP server")
graceful.Shutdown()
}
// gRPCServe starts the gRPC server and block until an error is encountered,
// or the server is shutdown.
//
// TODO this doesn't handle SIGUSR2 and SIGHUP on it's ... | ReportRuntimeMetrics | identifier_name | |
proxy.go | //TODO don't overload this
if conf.ConsulForwardServiceName != "" {
p.AcceptingForwards = true
}
}
p.ForwardDestinations = consistent.New()
p.TraceDestinations = consistent.New()
p.ForwardGRPCDestinations = consistent.New()
if conf.ForwardTimeout != "" {
p.ForwardTimeout, err = time.ParseDuration(conf.... |
if p.AcceptingTraces && p.ConsulTraceService != "" {
p.RefreshDestinations(p.ConsulTraceService, p.TraceDestinations, &p.TraceDestinationsMtx)
}
if p.AcceptingGRPCForwards && p.ConsulForwardGRPCService != "" {
p.RefreshDestinations(p.ConsulForwardGRPCService, p.ForwardGRPCDestinations, &p.Forward... | {
p.RefreshDestinations(p.ConsulForwardService, p.ForwardDestinations, &p.ForwardDestinationsMtx)
} | conditional_block |
proxy.go |
p.HTTPClient = &http.Client{
Transport: transport,
}
p.numListeningHTTP = new(int32)
p.enableProfiling = conf.EnableProfiling
p.ConsulForwardService = conf.ConsulForwardServiceName
p.ConsulTraceService = conf.ConsulTraceServiceName
p.ConsulForwardGRPCService = conf.ConsulForwardGrpcServiceName
if p.Consul... | // zero values as of Go 0.10.3
MaxIdleConns: conf.MaxIdleConns,
MaxIdleConnsPerHost: conf.MaxIdleConnsPerHost,
} | random_line_split | |
proxy.go | //TODO don't overload this
if conf.ConsulForwardServiceName != "" {
p.AcceptingForwards = true
}
}
p.ForwardDestinations = consistent.New()
p.TraceDestinations = consistent.New()
p.ForwardGRPCDestinations = consistent.New()
if conf.ForwardTimeout != "" {
p.ForwardTimeout, err = time.ParseDuration(conf.... |
// HTTPServe starts the HTTP server and listens perpetually until it encounters an unrecoverable error.
func | {
done := make(chan struct{}, 2)
go func() {
p.HTTPServe()
done <- struct{}{}
}()
if p.grpcListenAddress != "" {
go func() {
p.gRPCServe()
done <- struct{}{}
}()
}
// wait until at least one of the servers has shut down
<-done
graceful.Shutdown()
p.gRPCStop()
} | identifier_body |
args_info.rs | input);
// Based on the type generate the appropriate code.
let mut output_tokens = match &input.data {
syn::Data::Struct(ds) => {
impl_arg_info_struct(errors, &input.ident, type_attrs, &input.generics, ds)
}
syn::Data::Enum(de) => {
impl_arg_info_enum(errors, &... | commands: the_subcommands,
..Default::default()
}
} // end of get_args_ifo
} // end of impl ArgsInfo
}
}
fn impl_args_info_data<'a>(
name: &proc_macro2::Ident,
errors: &Errors,
type_attrs: &TypeAttrs,
fields: &'a [StructField<'a>],
... | /// A short description of the command's functionality.
description: " enum of subcommands", | random_line_split |
args_info.rs | input);
// Based on the type generate the appropriate code.
let mut output_tokens = match &input.data {
syn::Data::Struct(ds) => {
impl_arg_info_struct(errors, &input.ident, type_attrs, &input.generics, ds)
}
syn::Data::Enum(de) => {
impl_arg_info_enum(errors, &... | // An enum variant like `<name>(<ty>)`. This is used to collect
// the type of the variant for each subcommand.
struct ArgInfoVariant<'a> {
ty: &'a syn::Type,
}
let variants: Vec<ArgInfoVariant<'_>> = de
.variants
.iter()
.filter_map(|variant| {
let name ... | {
// Validate the enum is OK for argh.
check_enum_type_attrs(errors, type_attrs, &de.enum_token.span);
// Ensure that `#[argh(subcommand)]` is present.
if type_attrs.is_subcommand.is_none() {
errors.err_span(
de.enum_token.span,
concat!(
"`#![derive(ArgsI... | identifier_body |
args_info.rs | );
// Based on the type generate the appropriate code.
let mut output_tokens = match &input.data {
syn::Data::Struct(ds) => {
impl_arg_info_struct(errors, &input.ident, type_attrs, &input.generics, ds)
}
syn::Data::Enum(de) => |
syn::Data::Union(_) => {
errors.err(input, "`#[derive(ArgsInfo)]` cannot be applied to unions");
TokenStream::new()
}
};
errors.to_tokens(&mut output_tokens);
output_tokens
}
/// Implement the ArgsInfo trait for a struct annotated with argh attributes.
fn impl_arg_i... | {
impl_arg_info_enum(errors, &input.ident, type_attrs, &input.generics, de)
} | conditional_block |
args_info.rs | input);
// Based on the type generate the appropriate code.
let mut output_tokens = match &input.data {
syn::Data::Struct(ds) => {
impl_arg_info_struct(errors, &input.ident, type_attrs, &input.generics, ds)
}
syn::Data::Enum(de) => {
impl_arg_info_enum(errors, &... | <'a> {
ty: &'a syn::Type,
}
let variants: Vec<ArgInfoVariant<'_>> = de
.variants
.iter()
.filter_map(|variant| {
let name = &variant.ident;
let ty = enum_only_single_field_unnamed_variants(errors, &variant.fields)?;
if VariantAttrs::parse(erro... | ArgInfoVariant | identifier_name |
Ch12_Astrocrash_Game.py | ship in the direction the ship is facing. Since there’s no friction, the ship keeps moving based on all of the thrust the player applies to it.
When the player engages the ship’s engine, the code changes the velocity of the ship based on the ship’s angle (and produces an appropriate sound effect, too)"""
def upd... | # wrap around screen, if necessary | random_line_split | |
Ch12_Astrocrash_Game.py | ):
super(Collider, self).update()
if self.overlapping_sprites:
for sprite in self.overlapping_sprites:
sprite.die() # See its code above
self.die() # See its definition below
# Creating a die() method for the class, since all Collider objects will do the same thing when they die—create an explosion and ... | def update(self):
super(Missile, self).update()
# If the missile's lifetime finishes then destroy the missile
self.lifetime-=1 # decrease the count of lifetime
if self.lifetime==0:
self.destroy()
class Explosion(games.Animation):
| as soon as a missile gets created
"""Where the missile is created depends upon where the ship is located, and how the missile travels depends upon the angle of the ship"""
angle=ship_angle*math.pi/180 # angle is in radians
buffer_x=Missile.BUFFER * math.sin(angle)
buffer_y=Missile.BUFFER * math.cos(angle)
x=s... | identifier_body |
Ch12_Astrocrash_Game.py | ’s velocity components(the Ship object’s dx and dy).
# First convert degrees tro radians
angle=self.angle*math.pi/180
# Use sin=Perp/Hyp and cos=Base/Hyp
self.dx+=Ship.VELOCITY_STEP * math.sin(angle) # x is horizontal so use sin() to find dx(base); Ship's last position is retained to find out next position... | "
# show 'Game | conditional_block | |
Ch12_Astrocrash_Game.py | super(Collider, self).update()
if self.overlapping_sprites:
for sprite in self.overlapping_sprites:
sprite.die() # See its code above
self.die() # See its definition below
# Creating a die() method for the class, since all Collider objects will do the same thing when they die—create an explosion and des... | )
# If the missile's lifetime finishes then destroy the missile
self.lifetime-=1 # decrease the count of lifetime
if self.lifetime==0:
self.destroy()
class Explosion(games.Animation | pdate( | identifier_name |
command.rs | let mut cat = Command::new("cat")
.arg(&self.path)
.stdout(Stdio::piped())
.spawn().expect("fail to execute cat command");
let mut tr = Command::new("tr")
.arg("[:blank:]")
.arg(" ")
.stdin(Stdio::piped())
.stdout(Stdio::piped(... | debug!("{:?}", res);
assert_eq!(
(&mut res.lines()).next().unwrap(),
"高知県\t江川崎"
)
}
fn print_usage(program: &str, opts: Options) {
let brief = format!("Usage: {} FILE [options]", program);
print!("{}", opts.usage(&brief));
}
/// with carg... |
let file1 = parent.join("col1.txt");
let file2 = parent.join("col2.txt");
let res = Commander::merge(&file1, &file2); | random_line_split |
command.rs | let mut cat = Command::new("cat")
.arg(&self.path)
.stdout(Stdio::piped())
.spawn().expect("fail to execute cat command");
let mut tr = Command::new("tr")
.arg("[:blank:]")
.arg(" ")
.stdin(Stdio::piped())
.stdout(Stdio::piped(... |
let res = tr.wait_with_output().unwrap().stdout;
String::from_utf8(res).expect("contain invalid utf-8 character")
}
/// preparation to ch02_12
pub fn extract_row(&self, n: usize) -> String {
let res = Command::new("cut")
.args(&["-f", &format!("{}", n + 1)]) // start at... | {
if let Some(ref mut stdin) = tr.stdin {
let mut buf: Vec<u8> = Vec::new();
stdout.read_to_end(&mut buf).unwrap();
stdin.write_all(&buf).unwrap();
}
} | conditional_block |
command.rs | fie/how_to_pipe_one_process_into_another/
if let Some(ref mut stdout) = cat.stdout {
if let Some(ref mut stdin) = tr.stdin {
let mut buf: Vec<u8> = Vec::new();
stdout.read_to_end(&mut buf).unwrap();
stdin.write_all(&buf).unwrap();
}
... | et args = | identifier_name | |
command.rs | let mut cat = Command::new("cat")
.arg(&self.path)
.stdout(Stdio::piped())
.spawn().expect("fail to execute cat command");
let mut tr = Command::new("tr")
.arg("[:blank:]")
.arg(" ")
.stdin(Stdio::piped())
.stdout(Stdio::piped(... |
/// helper for ch02. 14&15
fn take(&self, n: usize, pos: &str)->String {
let res = Command::new(pos)
.args(&["-n", format!("{}", n).as_str()])
.arg(&self.path)
.output().expect("fail to execute head command");
String::from_utf8_lossy(&res.stdout).trim().to_... | {
let res = Command::new("paste")
.args(&[file1.as_ref(), file2.as_ref()])
.output().expect("fail to execute paste command");
String::from_utf8_lossy(&res.stdout).trim().to_string()
} | identifier_body |
lib.rs |
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT ... | (req: Request<Control>) -> tide::Result {
let addr = req.local_addr().unwrap();
let mut available = "<h3>Available Endpoints:</h3></br>".to_string();
for item in NON_PARAM_ROUTE.iter() {
let route = addr.to_owned() + item;
available = available + &format!("<a href=//{}>{}</a></br>", route, ... | get_all | identifier_name |
lib.rs |
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT ... |
let result_body = Body::from_json(&ResponseBody {
status: 0,
message: "".to_string(),
result: vec![serde_json::to_string(&spec_info).unwrap()],
})?;
let response = Response::builder(200).body(result_body).build();
Ok(response)
}
/// Get sent&received package bytes by peer_id
a... | {
spec_info.package_out = value
} | conditional_block |
lib.rs |
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT ... | extern crate lazy_static;
lazy_static! {
static ref NON_PARAM_ROUTE: Vec<String> = {
vec![
"".to_string(),
"/recv".to_string(),
"/send".to_string(),
"/peer".to_string(),
"/connection".to_string(),
]
};
static ref PARAM_ROUTE: Vec<S... | use std::str::FromStr;
use tide::http::mime;
use tide::{Body, Request, Response, Server};
#[macro_use] | random_line_split |
linux.rs | to `SIGKILL`. And you should keep it that way
/// unless you know what you are doing.
///
/// Particularly you should consider the following choices:
///
/// 1. Instead of setting ``PDEATHSIG`` to some other signal, send signal
/// yourself and wait until child gracefully finishes.
///
... |
/// Reassociate child process with a namespace specified by a file
/// descriptor
///
/// `file` argument is an open file referring to a namespace
///
/// 'ns' is a namespace type
///
/// See `man 2 setns` for further details
///
/// Note: using `unshare` and `setns` for the sa... | {
for ns in iter {
self.config.namespaces |= to_clone_flag(*ns);
}
self
} | identifier_body |
linux.rs | set to `SIGKILL`. And you should keep it that way
/// unless you know what you are doing.
///
/// Particularly you should consider the following choices:
///
/// 1. Instead of setting ``PDEATHSIG`` to some other signal, send signal
/// yourself and wait until child gracefully finishes.
/... | pub fn pivot_root<A: AsRef<Path>, B:AsRef<Path>>(&mut self,
new_root: A, put_old: B, unmount: bool)
-> &mut Command
{
let new_root = new_root.as_ref();
let put_old = put_old.as_ref();
if !new_root.is_absolute() {
panic!("New root must be absolute");
};... | /// # Panics
///
/// Panics if either path is not absolute or new_root is not a prefix of
/// put_old. | random_line_split |
linux.rs | to `SIGKILL`. And you should keep it that way
/// unless you know what you are doing.
///
/// Particularly you should consider the following choices:
///
/// 1. Instead of setting ``PDEATHSIG`` to some other signal, send signal
/// yourself and wait until child gracefully finishes.
///
... | <P: AsRef<Path>>(&mut self, dir: P) -> &mut Command
{
let dir = dir.as_ref();
if !dir.is_absolute() {
panic!("Chroot dir must be absolute");
}
self.chroot_dir = Some(dir.to_path_buf());
self
}
/// Moves the root of the file system to the directory `put_o... | chroot_dir | identifier_name |
linux.rs | to `SIGKILL`. And you should keep it that way
/// unless you know what you are doing.
///
/// Particularly you should consider the following choices:
///
/// 1. Instead of setting ``PDEATHSIG`` to some other signal, send signal
/// yourself and wait until child gracefully finishes.
///
... |
let mut old_cmp = put_old.components();
for (n, o) in new_root.components().zip(old_cmp.by_ref()) {
if n != o {
panic!("The new_root is not a prefix of put old");
}
}
self.pivot_root = Some((new_root.to_path_buf(), put_old.to_path_buf(),
... | {
panic!("The `put_old` dir must be absolute");
} | conditional_block |
router.go | use patterns in the same way they are currently used for routes but in reverse order (params on the left)
// NOTE: You have to use the '$' character instead of ':' for matching host parameters.
// The following patterns works:
/*
admin.example.com will match admin.example.com
$username.blog.com will match m... | {
handler = r.middlewares.BuildHandler(handler)
if !r.isRoot() {
handler = r.parent.buildMiddlewares(handler)
}
return handler
} | identifier_body | |
router.go | r.Handle("POST", pattern, handler)
}
// Put registers an http PUT method receiver with the provided Handler
func (r *Router) Put(pattern string, handler http.Handler) Route {
return r.Handle("PUT", pattern, handler)
}
// Delete registers an http DELETE method receiver with the provided Handler
func (r *Router) Dele... | {
panic("Lion: ServeFile cannot have url parameters")
} | conditional_block | |
router.go | .host
rt.pathMatcher = rm
r.routes = append(r.routes, rt)
}
return rt
}
// ServeHTTP finds the handler associated with the request's path.
// If it is not found it calls the NotFound handler
func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
ctx := r.pool.Get().(*ctx)
ctx.Reset()
ctx.paren... | (pattern string, handler func(Context)) Route {
return r.Handle("POST", pattern, wrap(handler))
}
// PUT registers an http PUT method receiver with the provided contextual Handler
func (r *Router) PUT(pattern string, handler func(Context)) Route {
return r.Handle("PUT", pattern, wrap(handler))
}
// DELETE registers... | POST | identifier_name |
router.go | .host
rt.pathMatcher = rm
r.routes = append(r.routes, rt)
}
return rt
}
// ServeHTTP finds the handler associated with the request's path.
// If it is not found it calls the NotFound handler
func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
ctx := r.pool.Get().(*ctx)
ctx.Reset()
ctx.paren... | }
// Post registers an http POST method receiver with the provided Handler
func (r *Router) Post(pattern string, handler http.Handler) Route {
return r.Handle("POST", pattern, handler)
}
// Put registers an http PUT method receiver with the provided Handler
func (r *Router) Put(pattern string, handler http.Handler) ... | random_line_split | |
viewsets.py | Optional
import toml
from asciinema import asciicast
from asciinema.commands.cat import CatCommand
from django.conf import settings
from django.db.models import F, Q
from django.http import StreamingHttpResponse, Http404
from django.utils.functional import cached_property
from django.views.static import serve
from dj... | elf, request, pk):
instance: Action = self.get_object()
try:
worker = Worker.objects.get(user=request.user)
except Worker.DoesNotExist:
raise ValidationError('User {} is not a worker'.format(request.user))
instance.block_task(worker)
instance.save()
... | ock_task(s | identifier_name |
viewsets.py | Optional
import toml
from asciinema import asciicast
from asciinema.commands.cat import CatCommand
from django.conf import settings
from django.db.models import F, Q
from django.http import StreamingHttpResponse, Http404
from django.utils.functional import cached_property
from django.views.static import serve
from dj... | return queryset
@action(methods=['put'], detail=True)
def worker_upload(self, request, pk):
file_obj = request.data['file']
instance: Action = self.get_object()
directory = os.path.dirname(instance.get_data_directory())
os.makedirs(directory, exist_ok=True)
t = ta... | eryset = queryset.filter(Q(plugin='') | Q(is_last=True))
| conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.