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 |
|---|---|---|---|---|
jsonast.go | /*
* Copyright (c) Microsoft Corporation.
* Licensed under the MIT license.
*/
package jsonast
import (
"context"
"fmt"
"net/url"
"regexp"
"strings"
"k8s.io/klog/v2"
"github.com/Azure/k8s-infra/hack/generator/pkg/astmodel"
"github.com/devigned/tab"
"github.com/xeipuuv/gojsonschema"
)
type (
// SchemaT... |
func arrayHandler(ctx context.Context, scanner *SchemaScanner, schema *gojsonschema.SubSchema) (astmodel.Type, error) {
ctx, span := tab.StartSpan(ctx, "arrayHandler")
defer span.End()
if len(schema.ItemsChildren) > 1 {
return nil, fmt.Errorf("item contains more children than expected: %v", schema.ItemsChildren... | {
ctx, span := tab.StartSpan(ctx, "anyOfHandler")
defer span.End()
// See https://github.com/Azure/k8s-infra/issues/111 for details about why this is treated as oneOf
klog.Warningf("Handling anyOf type as if it were oneOf: %v\n", schema.Ref.GetUrl())
return generateOneOfUnionType(ctx, schema.AnyOf, scanner)
} | identifier_body |
jsonast.go | /*
* Copyright (c) Microsoft Corporation.
* Licensed under the MIT license.
*/
package jsonast
import (
"context"
"fmt"
"net/url"
"regexp"
"strings"
"k8s.io/klog/v2"
"github.com/Azure/k8s-infra/hack/generator/pkg/astmodel"
"github.com/devigned/tab"
"github.com/xeipuuv/gojsonschema"
)
type (
// SchemaT... |
// 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 | /*
* Copyright (c) Microsoft Corporation.
* Licensed under the MIT license.
*/
package jsonast
import (
"context"
"fmt"
"net/url"
"regexp"
"strings"
"k8s.io/klog/v2"
"github.com/Azure/k8s-infra/hack/generator/pkg/astmodel"
"github.com/devigned/tab"
"github.com/xeipuuv/gojsonschema"
)
type (
// SchemaT... | 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 | // ----------- Central JS Aggregate - Currently Only used for Reference ------------- //
// ----------- HOMEPAGE JS -------------
// HTML Content for blurbs
var aboutText = "I just wanna help out!";
var linksText = "Add something here later about links";
var contactText = "Contact stuff";
var legalText = "The infor... |
// 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 | // ----------- Central JS Aggregate - Currently Only used for Reference ------------- //
// ----------- HOMEPAGE JS -------------
// HTML Content for blurbs
var aboutText = "I just wanna help out!";
var linksText = "Add something here later about links";
var contactText = "Contact stuff";
var legalText = "The infor... | (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 | // ----------- Central JS Aggregate - Currently Only used for Reference ------------- //
// ----------- HOMEPAGE JS -------------
// HTML Content for blurbs
var aboutText = "I just wanna help out!";
var linksText = "Add something here later about links";
var contactText = "Contact stuff";
var legalText = "The infor... | var myPieChart = new Chart(ctxP, {
type: 'pie',
data: {
labels: ["Correct", "Incorrect"],
datasets: [{
data: [300, 50],
backgroundColor: ['rgba(105, 0, 132, .2)', 'rgba(0, 137, 132, .2)'],
borderColor: ['rgba(200, 99, 132, .7)', 'rgba(0, 10, 130, .7)']
... |
// Total Accuracy Pie Chart
var ctxP = document.getElementById("totalAccuracyPieChart").getContext('2d'); | random_line_split |
search.py | try:
import cPickle as pickle
except:
import pickle
import collections
import operator
import string
from sets import Set
from stemming.porter import stem
ROUND_DIGITS = 6
EPSILON = 0.8
def loadPickle(pickle_file):
"""
Load the Pickle data from file.
"""
print("Loading pickle data from f... |
#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 | try:
import cPickle as pickle
except:
import pickle
import collections
import operator
import string
from sets import Set
from stemming.porter import stem
ROUND_DIGITS = 6
EPSILON = 0.8
def loadPickle(pickle_file):
"""
Load the Pickle data from file.
"""
print("Loading pickle data from f... |
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 | try:
import cPickle as pickle
except:
import pickle
import collections
import operator
import string
from sets import Set
from stemming.porter import stem
ROUND_DIGITS = 6
EPSILON = 0.8
def loadPickle(pickle_file):
"""
Load the Pickle data from file.
"""
print("Loading pickle data from f... |
# 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 | try:
import cPickle as pickle
except:
import pickle
import collections
import operator
import string
from sets import Set
from stemming.porter import stem
ROUND_DIGITS = 6
EPSILON = 0.8
def loadPickle(pickle_file):
"""
Load the Pickle data from file.
"""
print("Loading pickle data from f... | (link_data, links):
"""
Use the link_data to build a graph of the links.
:param link_data as dictionary of source link with destination links
:param links the links as list for which the graph need to be created
:return graph as dictionary
"""
graph = {}
# add all data... | build_graph | identifier_name |
offline_replica.rs | // Copyright 2023 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under The General Public License (GPL), version 3.
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTI... | (&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 | // Copyright 2023 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under The General Public License (GPL), version 3.
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTI... |
// If not all were Ok, we will return the first error sent to us.
for resp in responses.iter().flatten() {
if let Response::Cmd(CmdResponse::EditRegister(result)) = resp {
result.clone()?;
};
}
// If there were no success or fail to the expected... | {
return Ok(());
} | conditional_block |
offline_replica.rs | // Copyright 2023 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under The General Public License (GPL), version 3.
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTI... |
/// 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 | // Copyright 2023 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under The General Public License (GPL), version 3.
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTI... | }
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 | import * as THREE from '../libs/three.js/build/three.module.js';
import Stats from '../libs/three.js/examples/jsm/libs/stats.module.js';
import { OrbitControls } from '../libs/three.js/examples/jsm/controls/OrbitControls.js';
import * as GEN from './generate.js';
import { DDSLoader } from '../libs/three.js/examples... |
} | {
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 | import * as THREE from '../libs/three.js/build/three.module.js';
import Stats from '../libs/three.js/examples/jsm/libs/stats.module.js';
import { OrbitControls } from '../libs/three.js/examples/jsm/controls/OrbitControls.js';
import * as GEN from './generate.js';
import { DDSLoader } from '../libs/three.js/examples... | 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 | import * as THREE from '../libs/three.js/build/three.module.js';
import Stats from '../libs/three.js/examples/jsm/libs/stats.module.js';
import { OrbitControls } from '../libs/three.js/examples/jsm/controls/OrbitControls.js';
import * as GEN from './generate.js';
import { DDSLoader } from '../libs/three.js/examples... |
function render() {
var deltaTime = clock.getDelta();
updatePhysics(deltaTime);
renderer.render(scene, camera);
}
function updatePhysics(deltaTime) {
// Step world
physicsWorld.stepSimulation(deltaTime, 10);
// Update rigid bodies
for (var i = 0, il = rigidBodies.length; i < il; i++) {
var o... | {
requestAnimationFrame(animate);
render();
stats.update();
} | identifier_body |
scene_test.js | import * as THREE from '../libs/three.js/build/three.module.js';
import Stats from '../libs/three.js/examples/jsm/libs/stats.module.js';
import { OrbitControls } from '../libs/three.js/examples/jsm/controls/OrbitControls.js';
import * as GEN from './generate.js';
import { DDSLoader } from '../libs/three.js/examples... | () {
// keyboard control of arm
window.addEventListener('keydown', function (event) {
switch (event.keyCode) {
// Q
case 81:
armMovement = 1;
break;
// A
case 65:
armMovement = - 1;
break;
// S
case 83:
armMovement = 0;
bre... | initInput | identifier_name |
main.rs | use anyhow::{anyhow, Context};
use atty::Stream;
use rhc::args::Args;
use rhc::config::Config;
use rhc::environment::Environment;
use rhc::files::{get_all_toml_files, load_file};
use rhc::http;
use rhc::interactive;
use rhc::interactive::SelectedValues;
use rhc::keyvalue::KeyValue;
use rhc::request_definition::RequestD... | () -> 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 | use anyhow::{anyhow, Context};
use atty::Stream;
use rhc::args::Args;
use rhc::config::Config;
use rhc::environment::Environment;
use rhc::files::{get_all_toml_files, load_file};
use rhc::http;
use rhc::interactive;
use rhc::interactive::SelectedValues;
use rhc::keyvalue::KeyValue;
use rhc::request_definition::RequestD... | 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 | use anyhow::{anyhow, Context};
use atty::Stream;
use rhc::args::Args;
use rhc::config::Config;
use rhc::environment::Environment;
use rhc::files::{get_all_toml_files, load_file};
use rhc::http;
use rhc::interactive;
use rhc::interactive::SelectedValues;
use rhc::keyvalue::KeyValue;
use rhc::request_definition::RequestD... |
})?;
// 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 | use anyhow::{anyhow, Context};
use atty::Stream;
use rhc::args::Args;
use rhc::config::Config;
use rhc::environment::Environment;
use rhc::files::{get_all_toml_files, load_file};
use rhc::http;
use rhc::interactive;
use rhc::interactive::SelectedValues;
use rhc::keyvalue::KeyValue;
use rhc::request_definition::RequestD... |
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 | use jsonwebtoken::{Algorithm, Validation};
use serde::{Deserialize, Serialize};
use super::{AuthValidator, Error, Permission, Result, User};
use crate::application::Config;
const SUPPORTED_ALGORITHMS: [Algorithm; 3] = [Algorithm::RS256, Algorithm::RS384, Algorithm::RS512];
/// JSON Web Key. A cryptographic key used ... | .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 | use jsonwebtoken::{Algorithm, Validation};
use serde::{Deserialize, Serialize};
use super::{AuthValidator, Error, Permission, Result, User};
use crate::application::Config;
const SUPPORTED_ALGORITHMS: [Algorithm; 3] = [Algorithm::RS256, Algorithm::RS384, Algorithm::RS512];
/// JSON Web Key. A cryptographic key used ... | (&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 | use jsonwebtoken::{Algorithm, Validation};
use serde::{Deserialize, Serialize};
use super::{AuthValidator, Error, Permission, Result, User};
use crate::application::Config;
const SUPPORTED_ALGORITHMS: [Algorithm; 3] = [Algorithm::RS256, Algorithm::RS384, Algorithm::RS512];
/// JSON Web Key. A cryptographic key used ... |
}
#[cfg(test)]
mod tests {
use std::io::BufWriter;
use std::{io::Write, path::Path};
use super::*;
const KID: &str = "test-key";
const AUDIENCE: &str = "xsnippet-api-tests-aud";
const ISSUER: &str = "xsnippet-api-tests-iss";
const N: &str = "qN5dCh1M2RA3aF6ZH4IRXIQYKvaWRG59F7lpQIUyUtkDiU... | {
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 | YUI.add('stylesheet', function(Y) {
var d = Y.config.doc,
p = d.createElement('p'), // Have to hold on to the node (see notes)
style = p.style, // worker style collection
sheets = {},
floatAttr = ('cssFloat' in style) ? 'cssFloat' : 'styleFloat',
_toCssText,
_unsetOpacity,
_unsetProperty;
... |
// 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 | YUI.add('stylesheet', function(Y) {
var d = Y.config.doc,
p = d.createElement('p'), // Have to hold on to the node (see notes)
style = p.style, // worker style collection
sheets = {},
floatAttr = ('cssFloat' in style) ? 'cssFloat' : 'styleFloat',
_toCssText,
_unsetOpacity,
_unsetProperty;
... |
_toCssText = function (css,base) {
var f = css.styleFloat || css.cssFloat || css['float'], prop;
style.cssText = base || '';
if (f && !css[floatAttr]) {
css = Y.merge(css);
delete css.styleFloat; delete css.cssFloat; delete css['float'];
css[floatAttr] = f;
}
for (prop i... | {
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 | YUI.add('stylesheet', function(Y) {
var d = Y.config.doc,
p = d.createElement('p'), // Have to hold on to the node (see notes)
style = p.style, // worker style collection
sheets = {},
floatAttr = ('cssFloat' in style) ? 'cssFloat' : 'styleFloat',
_toCssText,
_unsetOpacity,
_unsetProperty;
... | (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 | YUI.add('stylesheet', function(Y) {
var d = Y.config.doc,
p = d.createElement('p'), // Have to hold on to the node (see notes)
style = p.style, // worker style collection
sheets = {},
floatAttr = ('cssFloat' in style) ? 'cssFloat' : 'styleFloat',
_toCssText,
_unsetOpacity,
_unsetProperty;
... |
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 |
import datetime
import hashlib
import json
from flask import Flask, jsonify, request
import requests
from uuid import uuid4
from urllib.parse import urlparse
from Crypto.PublicKey import RSA
# Part 1 - Building a Blockchain
class Blockchain:
#chain(emptylist) , farmer_details(emptylist), nodes(set), cre... | (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 | import datetime
import hashlib
import json
from flask import Flask, jsonify, request
import requests
from uuid import uuid4
from urllib.parse import urlparse
from Crypto.PublicKey import RSA
# Part 1 - Building a Blockchain
class Blockchain:
#chain(emptylist) , farmer_details(emptylist), nodes(set), creat... | #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 |
import datetime
import hashlib
import json
from flask import Flask, jsonify, request
import requests
from uuid import uuid4
from urllib.parse import urlparse
from Crypto.PublicKey import RSA
# Part 1 - Building a Blockchain
class Blockchain:
#chain(emptylist) , farmer_details(emptylist), nodes(set), cre... | de in nodes:
blockchain.add_node(node)
response = {'message': 'All the nodes are now connected. The puspesh Blockchain now contains the following nodes:',
'total_nodes': list(blockchain.nodes)}
return jsonify(response), 201
# Replacing the chain by the longest chain if needed
#- ... | ode", 400
for no | conditional_block |
Puspesh_farmer1.py |
import datetime
import hashlib
import json
from flask import Flask, jsonify, request
import requests
from uuid import uuid4
from urllib.parse import urlparse
from Crypto.PublicKey import RSA
# Part 1 - Building a Blockchain
class Blockchain:
#chain(emptylist) , farmer_details(emptylist), nodes(set), cre... |
# Part 2 - Mining our Blockchain
# Creating a Web App
app = Flask(__name__)
# Creating an address for the node on Port 5001
node_address = str(uuid4()).replace('-', '')
# Creating a Blockchain
blockchain = Blockchain()
# Mining a new block
#- It access the previous block by calling the function get_... | 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 | import os, sys
from collections import deque
import shutil
import torch
import numpy as np
import torch.distributed as dist
import datetime
from utils.scheduler import GradualWarmupScheduler
def initialize_distributed_backend(args, ngpus_per_node):
if args.distributed:
if args.dist_url == "env://" and arg... | 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 | import os, sys
from collections import deque
import shutil
import torch
import numpy as np
import torch.distributed as dist
import datetime
from utils.scheduler import GradualWarmupScheduler
def initialize_distributed_backend(args, ngpus_per_node):
if args.distributed:
if args.dist_url == "env://" and arg... |
return desc
def synchronize_meters(progress, cur_gpu):
metrics = torch.tensor([m.avg for m in progress.meters]).cuda(cur_gpu)
metrics_gather = [torch.ones_like(metrics) for _ in range(dist.get_world_size())]
dist.all_gather(metrics_gather, metrics)
metrics = torch.stack(metrics_gather).mean(0).c... | 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 | import os, sys
from collections import deque
import shutil
import torch
import numpy as np
import torch.distributed as dist
import datetime
from utils.scheduler import GradualWarmupScheduler
def initialize_distributed_backend(args, ngpus_per_node):
if args.distributed:
if args.dist_url == "env://" and arg... | (output, target, topk=(1,)):
"""Computes the accuracy over the k top predictions for the specified values of k"""
with torch.no_grad():
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(target.view(1... | accuracy | identifier_name |
main_utils.py | import os, sys
from collections import deque
import shutil
import torch
import numpy as np
import torch.distributed as dist
import datetime
from utils.scheduler import GradualWarmupScheduler
def initialize_distributed_backend(args, ngpus_per_node):
if args.distributed:
if args.dist_url == "env://" and arg... |
def update(self, val, n=1):
self.val = val
if self.window_size > 0:
self.q.append((val, n))
self.count = sum([n for v, n in self.q])
self.sum = sum([v * n for v, n in self.q])
else:
self.sum += val * n
self.count += n
self... | 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 | package main
import (
"bufio"
"bytes"
"errors"
"fmt"
"os"
"regexp"
"strings"
flags "github.com/jessevdk/go-flags"
"github.com/remeh/sizedwaitgroup"
)
const (
Author = "webdevops.io"
)
var (
// Git version information
gitCommit = "<unknown>"
gitTag = "<unknown>"
)
type changeset struct {
SearchPlai... | (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 | package main
import (
"bufio"
"bytes"
"errors"
"fmt"
"os"
"regexp"
"strings"
flags "github.com/jessevdk/go-flags"
"github.com/remeh/sizedwaitgroup"
)
const (
Author = "webdevops.io"
)
var (
// Git version information
gitCommit = "<unknown>"
gitTag = "<unknown>"
)
type changeset struct {
SearchPlai... |
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 | package main
import (
"bufio"
"bytes"
"errors"
"fmt"
"os"
"regexp"
"strings"
flags "github.com/jessevdk/go-flags"
"github.com/remeh/sizedwaitgroup"
)
const (
Author = "webdevops.io"
)
var (
// Git version information
gitCommit = "<unknown>"
gitTag = "<unknown>"
)
type changeset struct {
SearchPlai... | 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 | package main
import (
"bufio"
"bytes"
"errors"
"fmt"
"os"
"regexp"
"strings"
flags "github.com/jessevdk/go-flags"
"github.com/remeh/sizedwaitgroup"
)
const (
Author = "webdevops.io"
)
var (
// Git version information
gitCommit = "<unknown>"
gitTag = "<unknown>"
)
type changeset struct {
SearchPlai... |
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 | //! This module contains the data pertaining to Noise handshake patterns. For more information on
//! these patterns, consult the
//! [Noise specification](https://noiseprotocol.org/noise.html#handshake-patterns).
use failure::Fail;
use std::str::FromStr;
use HandshakePattern::*;
/// Role in the handshake process.
#[d... |
pattern!(NK {
[],
[S],
...
[E, ES],
[E, EE],
});
pattern!(NX {
[],
[],
...
[E],
[E, EE, S, ES],
});
pattern!(KN {
[S],
[],
...
[E],
[E, EE, SE],
});
pattern!(KK {
... | }); | random_line_split |
patterns.rs | //! This module contains the data pertaining to Noise handshake patterns. For more information on
//! these patterns, consult the
//! [Noise specification](https://noiseprotocol.org/noise.html#handshake-patterns).
use failure::Fail;
use std::str::FromStr;
use HandshakePattern::*;
/// Role in the handshake process.
#[d... | (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 | //! This module contains the data pertaining to Noise handshake patterns. For more information on
//! these patterns, consult the
//! [Noise specification](https://noiseprotocol.org/noise.html#handshake-patterns).
use failure::Fail;
use std::str::FromStr;
use HandshakePattern::*;
/// Role in the handshake process.
#[d... |
/// 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 | //! ZStandard compression format encoder and decoder implemented in pure Rust
//! without unsafe.
// Reference: https://github.com/facebook/zstd/blob/dev/doc/zstd_compression_format.md#frame_header
#![doc(
html_logo_url = "https://raw.githubusercontent.com/facebook/zstd/dev/doc/images/zstd_logo86.png",
html_f... | 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 | //! ZStandard compression format encoder and decoder implemented in pure Rust
//! without unsafe.
// Reference: https://github.com/facebook/zstd/blob/dev/doc/zstd_compression_format.md#frame_header
#![doc(
html_logo_url = "https://raw.githubusercontent.com/facebook/zstd/dev/doc/images/zstd_logo86.png",
html_f... | () -> 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 | // plugins for development
var gulp = require('gulp'),
rimraf = require('rimraf'),
pug = require('gulp-pug'),
sass = require('gulp-sass'),
gulpSequence = require('gulp-sequence'),
inlineimage = require('gulp-inline-image'),
prefix = require('gulp-autoprefixer'),
plumber = require('gulp-plumber'),
dirSync = requ... | 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 | use nalgebra::{self as na, Similarity3, Transform3, Matrix4, Vector3, Point3, Vector2, Point2, Isometry3, Quaternion, Translation3, Unit};
use webvr::*;
use draw::EyeParams;
use fnv::FnvHashMap;
use gfx::{Rect};
use ::NativeRepr;
const VEL_SMOOTHING: f64 = 1e-90;
/// Provides access to VR hardware.
pub struct VrConte... | (&self) -> Isometry3<f32> {
self.pose
}
}
/// Instantaneous information about a controller. This can be used directly
/// or to update some persistent state.
#[derive(Clone, Debug)]
pub struct ControllerMoment {
id: u32,
/// The textual name of the controller
pub name: String,
/// The locat... | pose | identifier_name |
vr.rs | use nalgebra::{self as na, Similarity3, Transform3, Matrix4, Vector3, Point3, Vector2, Point2, Isometry3, Quaternion, Translation3, Unit};
use webvr::*;
use draw::EyeParams;
use fnv::FnvHashMap;
use gfx::{Rect};
use ::NativeRepr;
const VEL_SMOOTHING: f64 = 1e-90;
/// Provides access to VR hardware.
pub struct VrConte... | 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 | use nalgebra::{self as na, Similarity3, Transform3, Matrix4, Vector3, Point3, Vector2, Point2, Isometry3, Quaternion, Translation3, Unit};
use webvr::*;
use draw::EyeParams;
use fnv::FnvHashMap;
use gfx::{Rect};
use ::NativeRepr;
const VEL_SMOOTHING: f64 = 1e-90;
/// Provides access to VR hardware.
pub struct VrConte... |
}
fn pose_transform(ctr: &VRPose, inverse_stage: &Similarity3<f32>) -> Option<Isometry3<f32>> {
let or = Unit::new_normalize(Quaternion::upgrade(
match ctr.orientation { Some(o) => o, None => return None }));
let pos = Translation3::upgrade(
match ctr.position { Some(o) => o, None => return No... | {
self.pose
} | identifier_body |
mod.rs | //! An iterator over incoming signals.
//!
//! This provides a higher abstraction over the signals, providing
//! the [`SignalsInfo`] structure which is able to iterate over the
//! incoming signals. The structure is parametrized by an
//! [`Exfiltrator`][self::exfiltrator::Exfiltrator], which specifies what informatio... | /// 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 | //! An iterator over incoming signals.
//!
//! This provides a higher abstraction over the signals, providing
//! the [`SignalsInfo`] structure which is able to iterate over the
//! incoming signals. The structure is parametrized by an
//! [`Exfiltrator`][self::exfiltrator::Exfiltrator], which specifies what informatio... | /// 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 | //! An iterator over incoming signals.
//!
//! This provides a higher abstraction over the signals, providing
//! the [`SignalsInfo`] structure which is able to iterate over the
//! incoming signals. The structure is parametrized by an
//! [`Exfiltrator`][self::exfiltrator::Exfiltrator], which specifies what informatio... | lf, fmt: &mut Formatter) -> FmtResult {
fmt.debug_tuple("Signals").field(&self.0).finish()
}
}
impl<'a, E: Exfiltrator> IntoIterator for &'a mut SignalsInfo<E> {
type Item = E::Output;
type IntoIter = Forever<'a, E>;
fn into_iter(self) -> Self::IntoIter {
self.forever()
}
}
/// An ... | &se | identifier_name |
ssd_train.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = "Christian Heider Nielsen"
__doc__ = r"""
Created on 22/03/2020
"""
import argparse
import datetime
import logging
import os
import time
from pathlib import Path
import torch
from draugr.numpy_utilities import SplitEnum
from draugr.to... | 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 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = "Christian Heider Nielsen"
__doc__ = r"""
Created on 22/03/2020
"""
import argparse
import datetime
import logging
import os
import time
from pathlib import Path
import torch
from draugr.numpy_utilities import SplitEnum
from draugr.to... |
if __name__ == "__main__":
main()
| """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 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = "Christian Heider Nielsen"
__doc__ = r"""
Created on 22/03/2020
"""
import argparse
import datetime
import logging
import os
import time
from pathlib import Path
import torch
from draugr.numpy_utilities import SplitEnum
from draugr.to... | ():
"""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 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = "Christian Heider Nielsen"
__doc__ = r"""
Created on 22/03/2020
"""
import argparse
import datetime
import logging
import os
import time
from pathlib import Path
import torch
from draugr.numpy_utilities import SplitEnum
from draugr.to... |
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 | package postgrescluster
/*
Copyright 2021 - 2023 Crunchy Data Solutions, Inc.
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 applicab... | if err == nil {
exporterWebConfig, err = r.reconcileExporterWebConfig(ctx, cluster)
}
if err == nil {
err = r.reconcileInstanceSets(
ctx, cluster, clusterConfigMap, clusterReplicationSecret,
rootCA, clusterPodService, instanceServiceAccount, instances,
patroniLeaderService, primaryCertificate, clusterVol... | monitoringSecret, err = r.reconcileMonitoringSecret(ctx, cluster)
}
| conditional_block |
controller.go | package postgrescluster
/*
Copyright 2021 - 2023 Crunchy Data Solutions, Inc.
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 applicab... | // 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 | package postgrescluster
/*
Copyright 2021 - 2023 Crunchy Data Solutions, Inc.
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 applicab... | // patch sends patch to object's endpoint in the Kubernetes API and updates
// object with any returned content. The fieldManager is set to r.Owner, but
// can be overridden in options.
// - https://docs.k8s.io/reference/using-api/server-side-apply/#managers
func (r *Reconciler) patch(
ctx context.Context, object clie... | 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 | package postgrescluster
/*
Copyright 2021 - 2023 Crunchy Data Solutions, Inc.
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 applicab... | gr manager.Manager) error {
if r.PodExec == nil {
var err error
r.PodExec, err = newPodExecutor(mgr.GetConfig())
if err != nil {
return err
}
}
var opts controller.Options
// TODO(cbandy): Move this to main with controller-runtime v0.9+
// - https://github.com/kubernetes-sigs/controller-runtime/commit... | tupWithManager(m | identifier_name |
TimelineFlameChartNetworkDataProvider.ts | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import * as Common from '../../core/common/common.js';
import * as i18n from '../../core/i18n/i18n.js';
import * as Platform from '../../core/platform/pla... | () {
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 | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import * as Common from '../../core/common/common.js';
import * as i18n from '../../core/i18n/i18n.js';
import * as Platform from '../../core/platform/pla... | 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 | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import * as Common from '../../core/common/common.js';
import * as i18n from '../../core/i18n/i18n.js';
import * as Platform from '../../core/platform/pla... |
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 | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import * as Common from '../../core/common/common.js';
import * as i18n from '../../core/i18n/i18n.js';
import * as Platform from '../../core/platform/pla... | /**
* Sets the minimum time and total time span of a trace using the
* new engine data.
*/
#setTimingBoundsData(newTraceEngineData: TraceEngine.Handlers.Migration.PartialTraceData): void {
const {traceBounds} = newTraceEngineData.Meta;
const minTime = TraceEngine.Helpers.Timing.microSecondsToMillis... | 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 | // Copyright (c) Jørgen Tjernø <jorgen@tjer.no>. All rights reserved.
use anyhow::{anyhow, bail, Context, Result};
use log::{debug, info, trace, warn};
use mail_slot::{MailslotClient, MailslotName};
use simplelog::*;
use std::{
fs::{File, OpenOptions},
io,
path::{Path, PathBuf},
process::{Command, Stdio... | .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 | // Copyright (c) Jørgen Tjernø <jorgen@tjer.no>. All rights reserved.
use anyhow::{anyhow, bail, Context, Result};
use log::{debug, info, trace, warn};
use mail_slot::{MailslotClient, MailslotName};
use simplelog::*;
use std::{
fs::{File, OpenOptions},
io,
path::{Path, PathBuf},
process::{Command, Stdio... | 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 | // Copyright (c) Jørgen Tjernø <jorgen@tjer.no>. All rights reserved.
use anyhow::{anyhow, bail, Context, Result};
use log::{debug, info, trace, warn};
use mail_slot::{MailslotClient, MailslotName};
use simplelog::*;
use std::{
fs::{File, OpenOptions},
io,
path::{Path, PathBuf},
process::{Command, Stdio... | 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 | //! # `uc8159`
//!
//! This is a driver crate for accessing the `uc8159` E-Ink display controller. For now, most of
//! the options are hard-coded for the
//! [Pimoroni Inky Impression](https://shop.pimoroni.com/products/inky-impression) display as that's
//! the only one I own, so proposing changes to add more featur... |
}
/// 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 | //! # `uc8159`
//!
//! This is a driver crate for accessing the `uc8159` E-Ink display controller. For now, most of
//! the options are hard-coded for the
//! [Pimoroni Inky Impression](https://shop.pimoroni.com/products/inky-impression) display as that's
//! the only one I own, so proposing changes to add more featur... |
}
impl Color {
pub fn all() -> [Self; 8] {
[
Color::Black,
Color::White,
Color::Green,
Color::Blue,
Color::Red,
Color::Yellow,
Color::Orange,
Color::Clean,
]
}
pub fn all_significant() -> [Self... | {
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 | //! # `uc8159`
//!
//! This is a driver crate for accessing the `uc8159` E-Ink display controller. For now, most of
//! the options are hard-coded for the
//! [Pimoroni Inky Impression](https://shop.pimoroni.com/products/inky-impression) display as that's
//! the only one I own, so proposing changes to add more featur... | {
/// 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 | //! # `uc8159`
//!
//! This is a driver crate for accessing the `uc8159` E-Ink display controller. For now, most of
//! the options are hard-coded for the
//! [Pimoroni Inky Impression](https://shop.pimoroni.com/products/inky-impression) display as that's
//! the only one I own, so proposing changes to add more featur... | (&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 | package veneur
import (
"errors"
"fmt"
"net/http"
"net/http/pprof"
"net/url"
"os"
"reflect"
"runtime"
"strconv"
"strings"
"sync"
"sync/atomic"
"syscall"
"time"
"golang.org/x/net/context"
"github.com/DataDog/datadog-go/statsd"
raven "github.com/getsentry/raven-go"
"github.com/hashicorp/consul/api"
... | () {
mem := &runtime.MemStats{}
runtime.ReadMemStats(mem)
metrics.ReportBatch(p.TraceClient, []*ssf.SSFSample{
ssf.Gauge("mem.heap_alloc_bytes", float32(mem.HeapAlloc), nil),
ssf.Gauge("gc.number", float32(mem.NumGC), nil),
ssf.Gauge("gc.pause_total_ns", float32(mem.PauseTotalNs), nil),
ssf.Gauge("gc.alloc_h... | ReportRuntimeMetrics | identifier_name |
proxy.go | package veneur
import (
"errors"
"fmt"
"net/http"
"net/http/pprof"
"net/url"
"os"
"reflect"
"runtime"
"strconv"
"strings"
"sync"
"sync/atomic"
"syscall"
"time"
"golang.org/x/net/context"
"github.com/DataDog/datadog-go/statsd"
raven "github.com/getsentry/raven-go"
"github.com/hashicorp/consul/api"
... |
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 | package veneur
import (
"errors"
"fmt"
"net/http"
"net/http/pprof"
"net/url"
"os"
"reflect"
"runtime"
"strconv"
"strings"
"sync"
"sync/atomic"
"syscall"
"time"
"golang.org/x/net/context"
"github.com/DataDog/datadog-go/statsd"
raven "github.com/getsentry/raven-go"
"github.com/hashicorp/consul/api"
... |
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 | package veneur
import (
"errors"
"fmt"
"net/http"
"net/http/pprof"
"net/url"
"os"
"reflect"
"runtime"
"strconv"
"strings"
"sync"
"sync/atomic"
"syscall"
"time"
"golang.org/x/net/context"
"github.com/DataDog/datadog-go/statsd"
raven "github.com/getsentry/raven-go"
"github.com/hashicorp/consul/api"
... |
// HTTPServe starts the HTTP server and listens perpetually until it encounters an unrecoverable error.
func (p *Proxy) HTTPServe() {
var prf interface {
Stop()
}
// We want to make sure the profile is stopped
// exactly once (and only once), even if the
// shutdown pre-hook does not run (which it may not)
p... | {
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 | // Copyright (c) 2023 Google LLC All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
use crate::{
enum_only_single_field_unnamed_variants,
errors::Errors,
help::require_description,
parse_attrs::{check_enum_type_attrs, FieldAttrs,... | 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 | // Copyright (c) 2023 Google LLC All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
use crate::{
enum_only_single_field_unnamed_variants,
errors::Errors,
help::require_description,
parse_attrs::{check_enum_type_attrs, FieldAttrs,... |
fn impl_args_info_data<'a>(
name: &proc_macro2::Ident,
errors: &Errors,
type_attrs: &TypeAttrs,
fields: &'a [StructField<'a>],
) -> TokenStream {
let mut subcommands_iter =
fields.iter().filter(|field| field.kind == FieldKind::SubCommand).fuse();
let subcommand: Option<&StructField<'_... | {
// 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 | // Copyright (c) 2023 Google LLC All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
use crate::{
enum_only_single_field_unnamed_variants,
errors::Errors,
help::require_description,
parse_attrs::{check_enum_type_attrs, FieldAttrs,... |
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 | // Copyright (c) 2023 Google LLC All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
use crate::{
enum_only_single_field_unnamed_variants,
errors::Errors,
help::require_description,
parse_attrs::{check_enum_type_attrs, FieldAttrs,... | <'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 | #The Astrocrash game
"""This game will have features like
1. Ship
It should rotate and thurst forward based on keystrokes from player
It should fire missiles based on keystroke from the player
Wrap arpund screen- That is if boundary crossed then appear at the opposite boundary
If Ship is destroyed GAME IS OVER... | x %= games.screen.width
y %= games.screen.height
# create the asteroid
new_asteroid = Asteroid(game = self,x = x, y = y,size = Asteroid.LARGE)
games.screen.add(new_asteroid)
# display level number
level_message = games.Message(value = "Level " + str(self.level),
size = 40,
c... | # wrap around screen, if necessary | random_line_split |
Ch12_Astrocrash_Game.py | #The Astrocrash game
"""This game will have features like
1. Ship
It should rotate and thurst forward based on keystrokes from player
It should fire missiles based on keystroke from the player
Wrap arpund screen- That is if boundary crossed then appear at the opposite boundary
If Ship is destroyed GAME IS OVER... | 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):
""" Explosion animation. """
sound = games.load_sound("explosion.wav")
ima... | 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 | #The Astrocrash game
"""This game will have features like
1. Ship
It should rotate and thurst forward based on keystrokes from player
It should fire missiles based on keystroke from the player
Wrap arpund screen- That is if boundary crossed then appear at the opposite boundary
If Ship is destroyed GAME IS OVER... | Over' for 5 seconds
end_message = games.Message(value = "Game Over",
size = 90,
color = color.red,
x = games.screen.width/2,
y = games.screen.height/2,
lifetime = 5 * games.screen.fps,
after_death = games.screen.quit,
is_collideable = False)
games.scree... | "
# show 'Game | conditional_block |
Ch12_Astrocrash_Game.py | #The Astrocrash game
"""This game will have features like
1. Ship
It should rotate and thurst forward based on keystrokes from player
It should fire missiles based on keystroke from the player
Wrap arpund screen- That is if boundary crossed then appear at the opposite boundary
If Ship is destroyed GAME IS OVER... | )
# 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):
""" Explosion animation. """
sound = games.load_sound("explosion.wav")
images = ["explosion1.bmp",
"explosion2.bmp",
... | pdate( | identifier_name |
command.rs | use std::process::{Command, Stdio};
use std::io::{BufReader, BufRead, Read, Write}; // Read is used for read_to_string
use std::fs::File;
use std::path::Path;
pub struct Commander {path: String}
impl Commander {
pub fn new<P: AsRef<Path>>(save_path: P) -> Commander {
Commander {
path: save_pat... | 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 | use std::process::{Command, Stdio};
use std::io::{BufReader, BufRead, Read, Write}; // Read is used for read_to_string
use std::fs::File;
use std::path::Path;
pub struct Commander {path: String}
impl Commander {
pub fn new<P: AsRef<Path>>(save_path: P) -> Commander {
Commander {
path: save_pat... |
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 | use std::process::{Command, Stdio};
use std::io::{BufReader, BufRead, Read, Write}; // Read is used for read_to_string
use std::fs::File;
use std::path::Path;
pub struct Commander {path: String}
impl Commander {
pub fn new<P: AsRef<Path>>(save_path: P) -> Commander {
Commander {
path: save_pat... | vec!["program", "-n", "5", "./data/ch02/hightemp.txt"];
let program = args[0].clone();
let mut opts = Options::new();
opts.optopt("n", "num", "set first ${num} rows", "NUMBER");
opts.optflag("h", "help", "print this help menu");
let matches = opts.parse(&args[1..]).unwrap();
... | et args = | identifier_name |
command.rs | use std::process::{Command, Stdio};
use std::io::{BufReader, BufRead, Read, Write}; // Read is used for read_to_string
use std::fs::File;
use std::path::Path;
pub struct Commander {path: String}
impl Commander {
pub fn new<P: AsRef<Path>>(save_path: P) -> Commander {
Commander {
path: save_pat... |
/// 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 | // Copyright 2020 Netwarps Ltd.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, dis... | (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 | // Copyright 2020 Netwarps Ltd.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, dis... |
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 | // Copyright 2020 Netwarps Ltd.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, dis... | 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 | use std::ffi::OsStr;
use std::io;
use std::os::unix::io::AsRawFd;
use std::path::Path;
use nix::sys::signal::{Signal};
use crate::ffi_util::ToCString;
use crate::{Command, Namespace};
use crate::idmap::{UidMap, GidMap};
use crate::stdio::dup_file_cloexec;
use crate::namespace::to_clone_flag;
use crate::caps::Capabili... |
/// 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 | use std::ffi::OsStr;
use std::io;
use std::os::unix::io::AsRawFd;
use std::path::Path;
use nix::sys::signal::{Signal};
use crate::ffi_util::ToCString;
use crate::{Command, Namespace};
use crate::idmap::{UidMap, GidMap};
use crate::stdio::dup_file_cloexec;
use crate::namespace::to_clone_flag;
use crate::caps::Capabili... | 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 | use std::ffi::OsStr;
use std::io;
use std::os::unix::io::AsRawFd;
use std::path::Path;
use nix::sys::signal::{Signal};
use crate::ffi_util::ToCString;
use crate::{Command, Namespace};
use crate::idmap::{UidMap, GidMap};
use crate::stdio::dup_file_cloexec;
use crate::namespace::to_clone_flag;
use crate::caps::Capabili... | <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 | use std::ffi::OsStr;
use std::io;
use std::os::unix::io::AsRawFd;
use std::path::Path;
use nix::sys::signal::{Signal};
use crate::ffi_util::ToCString;
use crate::{Command, Namespace};
use crate::idmap::{UidMap, GidMap};
use crate::stdio::dup_file_cloexec;
use crate::namespace::to_clone_flag;
use crate::caps::Capabili... |
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 | package lion
import (
"log"
"net/http"
"os"
"path"
"strings"
"sync"
"time"
"github.com/fatih/color"
)
// HTTP methods constants
const (
GET = "GET"
HEAD = "HEAD"
POST = "POST"
PUT = "PUT"
DELETE = "DELETE"
TRACE = "TRACE"
OPTIONS = "OPTIONS"
CONNECT = "CONNECT"
PATCH = "PATCH"
)
... |
func (r *Router) isRoot() bool {
return r.parent == nil
}
// HandleFunc wraps a HandlerFunc and pass it to Handle method
func (r *Router) HandleFunc(method, pattern string, fn http.HandlerFunc) Route {
return r.Handle(method, pattern, http.HandlerFunc(fn))
}
// NotFound calls NotFoundHandler() if it is set. Other... | {
handler = r.middlewares.BuildHandler(handler)
if !r.isRoot() {
handler = r.parent.buildMiddlewares(handler)
}
return handler
} | identifier_body |
router.go | package lion
import (
"log"
"net/http"
"os"
"path"
"strings"
"sync"
"time"
"github.com/fatih/color"
)
// HTTP methods constants
const (
GET = "GET"
HEAD = "HEAD"
POST = "POST"
PUT = "PUT"
DELETE = "DELETE"
TRACE = "TRACE"
OPTIONS = "OPTIONS"
CONNECT = "CONNECT"
PATCH = "PATCH"
)
... |
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, path)
})
r.Get(base, handler)
r.Head(base, handler)
}
var (
lionColor = color.New(color.Italic, color.FgHiGreen).SprintFunc()
lionLogger = log.New(os.Stdout, lionColor("[lion]")+" ", log.Ldate|log.Ltime)
)
// R... | {
panic("Lion: ServeFile cannot have url parameters")
} | conditional_block |
router.go | package lion
import (
"log"
"net/http"
"os"
"path"
"strings"
"sync"
"time"
"github.com/fatih/color"
)
// HTTP methods constants
const (
GET = "GET"
HEAD = "HEAD"
POST = "POST"
PUT = "PUT"
DELETE = "DELETE"
TRACE = "TRACE"
OPTIONS = "OPTIONS"
CONNECT = "CONNECT"
PATCH = "PATCH"
)
... | (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 | package lion
import (
"log"
"net/http"
"os"
"path"
"strings"
"sync"
"time"
"github.com/fatih/color"
)
// HTTP methods constants
const (
GET = "GET"
HEAD = "HEAD"
POST = "POST"
PUT = "PUT"
DELETE = "DELETE"
TRACE = "TRACE"
OPTIONS = "OPTIONS"
CONNECT = "CONNECT"
PATCH = "PATCH"
)
... | }
// 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 | import codecs
import glob
import os
import re
import tarfile
from itertools import chain
from typing import Type, Callable, 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 Strea... | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.