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 |
|---|---|---|---|---|
storage_service.go | _, _ = ss.Engine.Get(&user)
userCache[tag] = user
}
list[i].UserId = user.Id
list[i].Tenant = user.UserName
list[i].CpuTotal = user.CpuAll
list[i].MemTotal = int(user.MemAll)
pod := models.Instance{Id: list[i].PodId}
_, _ = ss.Engine.Cols("name").Get(&pod)
list[i].PodName = pod.Name
sc := models... | {
list = make([]models.PersistentVolume, 0)
where := "name like ?"
args := []interface{}{"%" + key + "%"}
// AAAA为root用户可查看所有PV
if userTag != "AAAA" {
where += " AND user_tag = ?"
args = append(args, userTag)
}
err = ss.Engine.Where(where, args...).Limit(pageSize, pageSize*(page-1)).Desc("id").Find(&list)
i... | identifier_body | |
storage_service.go | _id = ?", id).Update(&scUser)
}
} else {
// <userId,index>
dbUsersM := map[int]int{}
for i := range dbUsers {
dbUsersM[dbUsers[i].UserId] = i
}
insertList := make([]models.ScUser, 0)
for i := range userStrList {
if len(userStrList[i]) == 0 {
continue
}
var userId, err = strc... | d by the cluster | conditional_block | |
lib.rs | lattice probe for inventory. Note that these responses are returned
/// through regular (non-queue) subscriptions via a scatter-gather like pattern, so the
/// client is responsible for aggregating many of these replies.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
pub enum InventoryResponse {
/// A ... |
/// Retrieves the list of all capabilities within the lattice (discovery limited by the client timeout period)
pub fn get_capabilities(
&self,
) -> std::result::Result<HashMap<String, Vec<HostedCapability>>, Box<dyn std::error::Error>>
{
let mut host_caps = HashMap::new();
let ... | {
let mut host_actors = HashMap::new();
let sub = self
.nc
.request_multi(self.gen_subject(INVENTORY_ACTORS).as_ref(), &[])?;
for msg in sub.timeout_iter(self.timeout) {
let ir: InventoryResponse = serde_json::from_slice(&msg.data)?;
if let Invent... | identifier_body |
lib.rs | call_timeout: Duration,
namespace: Option<String>,
) -> Self {
Client {
nc,
timeout: call_timeout,
namespace,
}
}
/// Retrieves the list of all hosts running within the lattice. If it takes a host longer
/// than the call timeout perio... | gen_subject | identifier_name | |
lib.rs | pub const INVENTORY_CAPABILITIES: &str = "inventory.capabilities";
pub const EVENTS: &str = "events";
const AUCTION_TIMEOUT_SECONDS: u64 = 5;
/// A response to a lattice probe for inventory. Note that these responses are returned
/// through regular (non-queue) subscriptions via a scatter-gather like pattern, so the
/... |
pub const INVENTORY_ACTORS: &str = "inventory.actors";
pub const INVENTORY_HOSTS: &str = "inventory.hosts";
pub const INVENTORY_BINDINGS: &str = "inventory.bindings"; | random_line_split | |
mod.rs | = FastPaxos::new(
host_addr.clone(),
view.get_membership_size(),
view.get_current_config_id(),
);
Self {
host_addr,
view,
cut_detector,
monitor,
paxos,
alerts: VecDeque::default(),
l... | ,
metadata: Metadata::default(),
})
.collect()
}
// Filter for removing invalid edge update messages. These include messages
// that were for a configuration that the current node is not a part of, and messages
// that violate teh semantics of being a part of a c... | {
EdgeStatus::Up
} | conditional_block |
mod.rs | = FastPaxos::new(
host_addr.clone(),
view.get_membership_size(),
view.get_current_config_id(),
);
Self {
host_addr,
view,
cut_detector,
monitor,
paxos,
alerts: VecDeque::default(),
l... | cluster_metadata: HashMap::new(),
}
};
self.messages
.push_back((from, proto::ResponseKind::Join(response).into()));
}
}
// Invoked by observers of a node for failure detection
fn handle_probe_message(&self) -> Response {
... | sender: self.host_addr.clone(),
status: JoinStatus::ConfigChanged,
config_id: self.view.get_current_config_id(),
endpoints: vec![],
identifiers: vec![], | random_line_split |
mod.rs | !(
message = "Join at seed.",
seed = %self.host_addr,
sender = %join_res.sender,
config = %join_res.config_id,
size = %self.view.get_membership_size()
);
self.messages
.push_back((from, proto::ResponseKind::Join(join_res).into()));... | cancel_failure_detectors | identifier_name | |
mod.rs | = FastPaxos::new(
host_addr.clone(),
view.get_membership_size(),
view.get_current_config_id(),
);
Self {
host_addr,
view,
cut_detector,
monitor,
paxos,
alerts: VecDeque::default(),
l... |
pub fn view(&self) -> Vec<&Endpoint> {
self.view
.get_ring(0)
.expect("There is always a ring!")
.iter()
.collect()
}
pub fn step(&mut self, from: Endpoint, msg: proto::RequestKind) {
use proto::RequestKind::*;
match msg {
... | {
let nodes = self.view.get_ring(0);
nodes
.iter()
.map(|_| NodeStatusChange {
endpoint: self.host_addr.clone(),
status: EdgeStatus::Up,
metadata: Metadata::default(),
})
.collect()
} | identifier_body |
font.rs | ("size", &self.size)
.finish()
}
}
impl Font {
/// Returns a [font builder](support/struct.FontBuilder.html) for font construction.
///
/// # Examples
///
/// ```rust
/// # use radiant_rs::*;
/// # let display = Display::builder().hidden().build().unwrap();
/// # let re... | (context: &Context, font_data: Vec<u8>, size: f32) -> Font {
Font {
data : font_data,
font_id : FONT_COUNTER.fetch_add(1, Ordering::Relaxed),
size : size,
context : context.clone(),
}
}
/// Write text to given layer using given font
fn w... | create | identifier_name |
font.rs | ("size", &self.size)
.finish()
}
}
impl Font {
/// Returns a [font builder](support/struct.FontBuilder.html) for font construction.
///
/// # Examples
///
/// ```rust
/// # use radiant_rs::*;
/// # let display = Display::builder().hidden().build().unwrap();
/// # let re... |
/// Creates a new unique font
fn create(context: &Context, font_data: Vec<u8>, size: f32) -> Font {
Font {
data : font_data,
font_id : FONT_COUNTER.fetch_add(1, Ordering::Relaxed),
size : size,
context : context.clone(),
}
}
/// Wr... | {
if let Some((font_data, _)) = system_fonts::get(&Self::build_property(&info)) {
Ok(Self::create(context, font_data, info.size))
} else {
Err(core::Error::FontError("Failed to get system font".to_string()))
}
} | identifier_body |
font.rs | .finish()
}
}
impl Font {
/// Returns a [font builder](support/struct.FontBuilder.html) for font construction.
///
/// # Examples
///
/// ```rust
/// # use radiant_rs::*;
/// # let display = Display::builder().hidden().build().unwrap();
/// # let renderer = Renderer::ne... | .field("size", &self.size) | random_line_split | |
font.rs | ("size", &self.size)
.finish()
}
}
impl Font {
/// Returns a [font builder](support/struct.FontBuilder.html) for font construction.
///
/// # Examples
///
/// ```rust
/// # use radiant_rs::*;
/// # let display = Display::builder().hidden().build().unwrap();
/// # let re... |
if info.monospace {
property = property.monospace();
}
property.build()
}
}
/// A wrapper around rusttype's font cache.
pub struct FontCache {
cache : Mutex<rusttype::gpu_cache::Cache<'static>>,
queue : Mutex<Vec<(Rect<u32>, Vec<u8>)>>,
dirty : AtomicBool,
}
... | {
property = property.bold();
} | conditional_block |
app.js | ')){
map = new google.maps.Map(document.getElementById('mapPlacement'), {
center: {lat: data.location.lat, lng: data.location.lng},
zoom: 15
})
$.ajax({
method: 'POST',
url: '/api/locations',
data: data,
success: showRestaurants,
... | saveUser | identifier_name | |
app.js | console.log('The DOM body is ready')
console.log('Body parser parsing that body!');
$('.batwich-chat').hide();
$('.hero-chat').hide();
//*****************
//*****************
//Gif Handlebars templates
var sourceOne = $('#selectableGif-template2').html(),
templateGif = Handlebars.compile(sourceOne),
... | // listener for find hero button. hides button to search again until map is moved.
$('.map-section').on('click', '#map-button', function(){
console.log('map button pressed');
$('#hero-map').show();
$('.find-hero-button').hide();
// set default location as Hell Mi
var defaultLocation = {
... | //hide map area when page loads
$('#hero-map').hide();
| random_line_split |
app.js | .log('The DOM body is ready')
console.log('Body parser parsing that body!');
$('.batwich-chat').hide();
$('.hero-chat').hide();
//*****************
//*****************
//Gif Handlebars templates
var sourceOne = $('#selectableGif-template2').html(),
templateGif = Handlebars.compile(sourceOne),
sourc... | else {
activeUser.location = data.location;
console.log(activeUser);
$.ajax({
method: 'POST',
url: '/api/locations',
data: activeUser,
success: appendRestaurants,
error: noRestaurants
})
}
}
function noLocation(data){
... | {
map = new google.maps.Map(document.getElementById('mapPlacement'), {
center: {lat: data.location.lat, lng: data.location.lng},
zoom: 15
})
$.ajax({
method: 'POST',
url: '/api/locations',
data: data,
success: showRestaurants,
err... | conditional_block |
app.js | GifHtml);
})
// this is what populates selectable gifs
function newGifSearchSuccess(json){
console.log('ajax call for gif successful. Gif: ', json);
// empty space to prevent gifs from multiple searches showing at the same time
$('.gifSelectionField2').empty();
json.data.forEach(function(gif){
... | {
console.log('Trying to edit the review below', data);
templateReview({
reviewContent: data.reviewContent2
})
console.log('The review was edited', data);
return templateReview;
window.location.href="../"
} | identifier_body | |
type_checker.rs | );
Ok(ty)
}
pub fn check_def(&mut self, def: &Def) -> Result<Tm, String> {
let mut s = self.save_ctx();
for ext in def.ctx.iter() {
s.extend(ext)?;
}
let ret_ty = s.check_ty(&def.ret_ty)?;
s.check_tm_ty(&def.body, &ret_ty)
}
fn check_let<T, F... | (&mut self, expr: &Expr) -> Result<(Tm, Ty), String> {
let (tm, _) = self.check_tm(expr)?;
let eq_ty = self.model.eq_ty(&tm, &tm);
let refl_tm = self.model.refl(&tm);
Ok((refl_tm, eq_ty))
}
fn true_tm(&mut self) -> (Tm, Ty) {
let cur_ctx_syn = &self.ctxs.last().unwrap().... | refl | identifier_name |
type_checker.rs | _info);
Ok(ty)
}
pub fn check_def(&mut self, def: &Def) -> Result<Tm, String> {
let mut s = self.save_ctx();
for ext in def.ctx.iter() {
s.extend(ext)?;
}
let ret_ty = s.check_ty(&def.ret_ty)?;
s.check_tm_ty(&def.body, &ret_ty)
}
fn check_let... | if let Some(name) = name {
s.ctxs.last_mut().unwrap().defs.push((name.clone(), val, ty));
};
check_body(&mut s, body)
}
pub fn check_ty(&mut self, expr: &Expr) -> Result<Ty, String> {
let cur_ctx_syn = &self.ctxs.last().unwrap().syntax;
match expr {
... | random_line_split | |
type_checker.rs | );
Ok(ty)
}
pub fn check_def(&mut self, def: &Def) -> Result<Tm, String> {
let mut s = self.save_ctx();
for ext in def.ctx.iter() {
s.extend(ext)?;
}
let ret_ty = s.check_ty(&def.ret_ty)?;
s.check_tm_ty(&def.body, &ret_ty)
}
fn check_let<T, F... |
fn true_tm(&mut self) -> (Tm, Ty) {
let cur_ctx_syn = &self.ctxs.last().unwrap().syntax;
let bool_ty = self.model.bool_ty(cur_ctx_syn);
let tm = self.model.true_tm(cur_ctx_syn);
(tm, bool_ty)
}
fn false_tm(&mut self) -> (Tm, Ty) {
let cur_ctx_syn = &self.ctxs.last(... | {
let (tm, _) = self.check_tm(expr)?;
let eq_ty = self.model.eq_ty(&tm, &tm);
let refl_tm = self.model.refl(&tm);
Ok((refl_tm, eq_ty))
} | identifier_body |
app.component.local.ts | { isImageResponse, isHtmlResponse, isXmlResponse, handleHtmlResponse, handleXmlResponse, handleJsonResponse, handleImageResponse, insertHeadersIntoResponseViewer, showResults } from "./response-handlers";
import { saveHistoryToLocalStorage, loadHistoryFromLocalStorage } from "./history";
import { createHeaders, getPar... | {
commonResponseHandler(res, query);
insertHeadersIntoResponseViewer(res.headers);
let errorText;
try {
errorText = res.json();
handleJsonResponse(errorText);
return;
} catch(e) {
errorText = res.text();
}
if (errorText.indexOf("<!DOCTYPE html>") != -1) {
handleHtmlResponse(errorTe... | identifier_body | |
app.component.local.ts | Ref, DoCheck, AfterViewInit } from '@angular/core';
import { Response, Headers } from '@angular/http';
import { ExplorerOptions, RequestType, ExplorerValues, GraphApiCall, GraphRequestHeader, Message, SampleQuery, MessageBarContent, GraphApiVersions, GraphApiVersion } from "./base";
import { GraphExplorerComponent } f... | (query:GraphApiCall) {
let text = "";
if (isSuccessful(query)) {
text += getString(AppComponent.Options, "Success");
} else {
text += getString(AppComponent.Options, "Failure");
}
text += ` - ${getString(AppComponent.Options, "Status Code")} ${query.statu... | createTextSummary | identifier_name |
app.component.local.ts | Ref, DoCheck, AfterViewInit } from '@angular/core';
import { Response, Headers } from '@angular/http';
import { ExplorerOptions, RequestType, ExplorerValues, GraphApiCall, GraphRequestHeader, Message, SampleQuery, MessageBarContent, GraphApiVersions, GraphApiVersion } from "./base";
import { GraphExplorerComponent } f... |
`]
})
export class AppComponent extends GraphExplorerComponent implements OnInit, AfterViewInit {
ngAfterViewInit(): void {
// Headers aren't updated when that tab is hidden, so when clicking on any tab reinsert the headers
if (typeof $ !== "undefined") {
$("#response-viewer-labels .ms-Pivot-li... | padding: 0px;
} | random_line_split |
__init__.py | _json_path)
def _setup_env():
"""Setup the local working environment."""
env.home_path = os.path.expanduser('~')
env.env_path = os.getenv('WORKON_HOME')
if not env.env_path:
warn("You should set the WORKON_HOME environment variable to" \
" the root directory for your virtual envi... |
bucket = _config['deploy'][env_type]['bucket']
warn('YOU ARE ABOUT TO DELETE EVERYTHING IN %s' % bucket)
if not do(prompt("Are you ABSOLUTELY sure you want to do this? (y/n): ").strip()):
abort('Aborting.')
with lcd(env.sites_path):
local('fablib/bin/s3cmd --c... | abort('Could not find "bucket" in deploy.%s" in config file' % env_type) | conditional_block |
__init__.py | _json_path)
def _setup_env():
"""Setup the local working environment."""
env.home_path = os.path.expanduser('~')
env.env_path = os.getenv('WORKON_HOME')
if not env.env_path:
warn("You should set the WORKON_HOME environment variable to" \
" the root directory for your virtual envi... |
@task
def stage():
"""Build/commit/tag/push lib version, copy to local cdn repo"""
_setup_env()
if not 'stage' in _config:
abort('Could not find "stage" in config file')
# Make sure cdn exists
exists(dirname(env.cdn_path), required=True)
# Ask us... | """Build lib version"""
_setup_env()
# Get build config
if not 'build' in _config:
abort('Could not find "build" in config file')
# Check version
if not 'version' in _config:
_config['version'] = datetime.utcnow().strftime('%Y-%m-%d-%H-%M-%S')
... | identifier_body |
__init__.py | _json_path)
def _setup_env():
"""Setup the local working environment."""
env.home_path = os.path.expanduser('~')
env.env_path = os.getenv('WORKON_HOME')
if not env.env_path:
warn("You should set the WORKON_HOME environment variable to" \
" the root directory for your virtual envi... | (env_type):
"""Delete website from S3 bucket. Specify stg|prd as argument."""
_setup_env()
# Activate local virtual environment (for render_templates+flask?)
local('. %s' % env.activate_path)
if not os.path.exists(env.s3cmd_cfg):
abort("Could not find 's3cmd.cfg' r... | undeploy | identifier_name |
__init__.py | config_json_path)
def _setup_env():
"""Setup the local working environment."""
env.home_path = os.path.expanduser('~')
env.env_path = os.getenv('WORKON_HOME')
if not env.env_path:
warn("You should set the WORKON_HOME environment variable to" \
" the root directory for your virtu... | ############################################################
# Static websites deployed to S3
############################################################
if _config and 'deploy' in _config:
@task
def undeploy(env_type):
"""Delete website from S3 bucket. Specify stg|prd as argument."""
_setup_... | random_line_split | |
secp256k1_recover.rs | bytes in length this function returns
/// [`Secp256k1RecoverError::InvalidHash`], though see notes
/// on SBF-specific behavior below.
///
/// If `recovery_id` is not in the range [0, 3] this function returns
/// [`Secp256k1RecoverError::InvalidRecoveryId`].
///
/// If `signature` is not 64 bytes in length this functi... | /// | random_line_split | |
secp256k1_recover.rs | BF-specific behavior below.
///
/// If `recovery_id` is not in the range [0, 3] this function returns
/// [`Secp256k1RecoverError::InvalidRecoveryId`].
///
/// If `signature` is not 64 bytes in length this function returns
/// [`Secp256k1RecoverError::InvalidSignature`], though see notes
/// on SBF-specific behavior be... | secp256k1_recover | identifier_name | |
secp256k1_recover.rs |
pub fn to_bytes(self) -> [u8; 64] {
self.0
}
}
/// Recover the public key from a [secp256k1] ECDSA signature and
/// cryptographically-hashed message.
///
/// [secp256k1]: https://en.bitcoin.it/wiki/Secp256k1
///
/// This function is specifically intended for efficiently implementing
/// Ethereum's [... | {
Self(
<[u8; SECP256K1_PUBLIC_KEY_LENGTH]>::try_from(<&[u8]>::clone(&pubkey_vec))
.expect("Slice must be the same length as a Pubkey"),
)
} | identifier_body | |
VismoController.js | = document.createElement("div");
shape.innerHTML = response;
}
else{
shape = document.createElement('object');
shape.setAttribute('codebase', ... |
var el = e.target;
//var el = e.srcElement;
if(!el) return;
while(el != element){
if(el == element) {
onmousewheel(e);
... | var element = this.wrapper;
if(VismoUtils.browser.isIE) {
document.onmousewheel = function(e){
if(!e)e = window.event; | random_line_split |
VismoController.js | document.createElement("div");
shape.innerHTML = response;
}
else{
shape = document.createElement('object');
shape.setAttribute('codebase', 'h... |
if(!VismoUtils.browser.isIE && !jQuery(that.wrapper).hasClass("panning")){
jQuery(that.wrapper).addClass("panning")
}
if(!that.goodToTransform(e)) {return;}
var pos = VismoClickingUtils.getMouseFromEventRelativeToElement(e,panning_status.clickpos.x,panning_status.clickpos.y,panning_status.elem);
... | {
return;
} | conditional_block |
model.py |
def _find_weights(weights_dir, mode='last'):
"""Find weights path if not provided manually during model initialization"""
if mode == 'last':
file_name = sorted(os.listdir(weights_dir))[-1]
weights_path = os.path.join(weights_dir, file_name)
elif mode == 'best':
raise NotImplemen... | path = os.path.join(*args)
if not os.path.exists(path):
os.makedirs(path)
return path | identifier_body | |
model.py | _path, custom_objects=custom_objects, compile=True)
if mode == 'inference':
try:
model = keras.models.load_model(model_path, custom_objects=custom_objects, compile=False)
except:
model = keras.models.model_from_json(json.dumps(graph))
model.load_weights(weights_pa... | _save_vector_masks | identifier_name | |
model.py | from .standardizer import Standardizer
def _create_dir(*args):
path = os.path.join(*args)
if not os.path.exists(path):
os.makedirs(path)
return path
def _find_weights(weights_dir, mode='last'):
"""Find weights path if not provided manually during model initialization"""
if mode == 'last... | from .config import OrthoSegmModelConfig | random_line_split | |
model.py | auto', graph_path='auto',
weights_path='auto', model_path='auto', custom_objects=None):
if config_path == 'auto':
config_path = os.path.join(model_dir, 'config.json')
if graph_path == 'auto':
graph_path = os.path.join(model_dir, 'graph.json')
if weights_path == 'auto':
... |
if mode == 'inference':
try:
model = keras.models.load_model(model_path, custom_objects=custom_objects, compile=False)
except:
model = keras.models.model_from_json(json.dumps(graph))
model.load_weights(weights_path)
segmentation_model = SegmentationModel(mod... | model = keras.models.load_model(model_path, custom_objects=custom_objects, compile=True) | conditional_block |
run_ERDCA.py | fam_ecc/'
data_path = '/home/eclay/Pfam-A.full'
preprocess_path = '/home/eclay/DCA_ER/biowulf/pfam_ecc/'
#pfam_id = 'PF00025'
pfam_id = sys.argv[1]
cpus_per_job = int(sys.argv[2])
job_id = sys.argv[3]
print("Calculating DI for %s using %d (of %d) threads (JOBID: %s)"%(pfam_id,cpus_per_job-4,cpus_per_job,job_id))
# R... | print(site_pair, score) | conditional_block | |
run_ERDCA.py | _backmapper import sequence_backmapper
from pydca.msa_trimmer import msa_trimmer
from pydca.contact_visualizer import contact_visualizer
from pydca.dca_utilities import dca_utilities
warnings.filterwarnings("error")
warnings.simplefilter('ignore', BiopythonWarning)
warnings.simplefilter('ignore', DeprecationWarning)
w... | print(preprocessed_data_outfile)
print('\n\nPre-Processing MSA with Range PP Seq\n\n')
trimmer = msa_trimmer.MSATrimmer(
erdca_msa_file, biomolecule='PROTEIN',
refseq_file = erdca_ref_file
)
pfam_dict['ref_file'] = erdca_ref_file
try:
preprocessed_data,s_index, cols_removed,s_ipdb,s = trimmer.get_preprocess... | #---------------------------------- PreProcess FASTA Alignment -------------------------------------------------------#
#---------------------------------------------------------------------------------------------------------------------#
preprocessed_data_outfile = preprocess_path+'MSA_%s_PreP... | random_line_split |
buffer.rs | pub fn clear(&mut self) {
self.start_offset = 0;
self.rd_pos = 0;
self.data.truncate(0);
}
/// Truncate this buffer.
pub fn truncate(&mut self, size: usize) {
if size == 0 {
self.clear();
return;
}
if size > self.len() {
p... |
/// Add a string to the buffer.
#[inline]
pub fn put_str(&mut self, s: impl AsRef<str>) {
self.extend_from_slice(s.as_ref().as_bytes());
}
/// Return a reference to this Buffer as an UTF-8 string.
#[inline]
pub fn as_utf8_str(&self) -> Result<&str, std::str::Utf8Error> {
s... | {
self.extend_from_slice(s.as_bytes());
} | identifier_body |
buffer.rs | pub fn clear(&mut self) {
self.start_offset = 0;
self.rd_pos = 0;
self.data.truncate(0);
}
/// Truncate this buffer.
pub fn truncate(&mut self, size: usize) {
if size == 0 {
self.clear();
return;
}
if size > self.len() {
p... |
#[ | #[cfg(test)]
mod tests {
use super::*; | random_line_split |
buffer.rs | pub fn clear(&mut self) {
self.start_offset = 0;
self.rd_pos = 0;
self.data.truncate(0);
}
/// Truncate this buffer.
pub fn | (&mut self, size: usize) {
if size == 0 {
self.clear();
return;
}
if size > self.len() {
panic!("Buffer::truncate(size): size > self.len()");
}
if self.rd_pos > size {
self.rd_pos = size;
}
self.data.truncate(size + ... | truncate | identifier_name |
buffer.rs | pub fn clear(&mut self) {
self.start_offset = 0;
self.rd_pos = 0;
self.data.truncate(0);
}
/// Truncate this buffer.
pub fn truncate(&mut self, size: usize) {
if size == 0 {
self.clear();
return;
}
if size > self.len() {
p... |
}
#[inline]
fn chunk(&self) -> &[u8] {
self.bytes()
}
#[inline]
fn remaining(&self) -> usize {
self.len() - self.rd_pos
}
}
impl Deref for Buffer {
type Target = [u8];
#[inline]
fn deref(&self) -> &[u8] {
self.bytes()
}
}
impl DerefMut for Buffer... | {
// "It is recommended for implementations of advance to
// panic if cnt > self.remaining()"
panic!("read position advanced beyond end of buffer");
} | conditional_block |
udp.rs | 6,
}
struct Packet<B: ByteSlice> {
header: LayoutVerified<B, Header>,
data: B,
}
impl<B: ByteSlice> Packet<B> {
fn parse(bytes: B) -> Option<Packet<B>> {
let (header, data) = LayoutVerified::new_from_prefix(bytes)?;
Some(Self { header, data })
}
#[allow(dead_code)]
fn is_conti... | format!("Could not parse response packet"),
))?;
match response.packet_type() {
Ok(PacketType::Fastboot) => (),
_ => {
return Err(std::io::Error::new(
... | {
// TODO(fxb/78975): unfortunately the Task requires the 'static lifetime so we have to
// copy the bytes and move them into the async block.
let packets = self.create_fastboot_packets(buf).map_err(|e| {
std::io::Error::new(
ErrorKind::Other,
... | conditional_block |
udp.rs | 16,
}
struct Packet<B: ByteSlice> {
header: LayoutVerified<B, Header>,
data: B,
}
impl<B: ByteSlice> Packet<B> {
fn parse(bytes: B) -> Option<Packet<B>> {
let (header, data) = LayoutVerified::new_from_prefix(bytes)?;
Some(Self { header, data })
}
#[allow(dead_code)]
fn is_cont... | format!("Could not create fastboot packets: {}", e),
)
})?;
let socket = self.socket.clone();
self.write_task.replace(Box::pin(async move {
for packet in &packets {
let (out_buf, sz) = send_to_device(&packet, &so... | // TODO(fxb/78975): unfortunately the Task requires the 'static lifetime so we have to
// copy the bytes and move them into the async block.
let packets = self.create_fastboot_packets(buf).map_err(|e| {
std::io::Error::new(
ErrorKind::Other, | random_line_split |
udp.rs | <B, Header>,
data: B,
}
impl<B: ByteSlice> Packet<B> {
fn parse(bytes: B) -> Option<Packet<B>> {
let (header, data) = LayoutVerified::new_from_prefix(bytes)?;
Some(Self { header, data })
}
#[allow(dead_code)]
fn is_continuation(&self) -> bool {
self.header.flags & 0x001 != ... | make_init_packet | identifier_name | |
udp.rs | 6,
}
struct Packet<B: ByteSlice> {
header: LayoutVerified<B, Header>,
data: B,
}
impl<B: ByteSlice> Packet<B> {
fn parse(bytes: B) -> Option<Packet<B>> {
let (header, data) = LayoutVerified::new_from_prefix(bytes)?;
Some(Self { header, data })
}
#[allow(dead_code)]
fn is_conti... |
async fn make_sender_socket(addr: SocketAddr) -> Result<UdpSocket> {
let socket: std::net::UdpSocket = match addr {
SocketAddr::V4(ref _saddr) => socket2::Socket::new(
socket2::Domain::IPV4,
socket2::Type::DGRAM,
Some(socket2::Protocol::UDP),
)
.context(... | {
let mut buf = [0u8; 1500]; // Responses should never get this big.
timeout(REPLY_TIMEOUT, Box::pin(socket.recv(&mut buf[..])))
.await
.map_err(|_| anyhow!("Timed out waiting for reply"))?
.map_err(|e| anyhow!("Recv error: {}", e))
.map(|size| (buf, size))
} | identifier_body |
plate.ts | ertia: IMatrix3Array;
invMomentOfInertia: IMatrix3Array;
center: null | IVec3Array;
hotSpot: {
position: IVec3Array;
force: IVec3Array;
};
fields: ISerializedField[];
adjacentFields: ISerializedField[];
subplate: ISerializedSubplate;
plateGroup: ISerializedPlateGroup | null;
}
export default cl... |
addFieldAt(props: Omit<IFieldOptions, "id" | "plate">, absolutePos: THREE.Vector3) {
const localPos = this.localPosition(absolutePos);
const id = getGrid().nearestFieldId(localPos);
if (!this.fields.has(id)) {
return this.addField({ ...props, id });
}
}
addExistingField(field: Field) {
... | {
const field = new Field({ ...props, plate: this });
this.addExistingField(field);
return field;
} | identifier_body |
plate.ts | ertia: IMatrix3Array;
invMomentOfInertia: IMatrix3Array;
center: null | IVec3Array;
hotSpot: {
position: IVec3Array;
force: IVec3Array;
};
fields: ISerializedField[];
adjacentFields: ISerializedField[];
subplate: ISerializedSubplate;
plateGroup: ISerializedPlateGroup | null;
}
export default cl... | }
setHotSpot(position: THREE.Vector3, force: THREE.Vector3) {
this.hotSpot = { position, force };
}
setDensity(density: number) {
this.density = density;
}
removeUnnecessaryFields() {
this.fields.forEach((f: Field) => {
if (!f.alive) {
this.deleteField(f.id);
}
});
}... | const len = this.hotSpot.force.length();
if (len > 0) {
this.hotSpot.force.setLength(Math.max(0, len - timestep * HOT_SPOT_TORQUE_DECREASE));
} | random_line_split |
plate.ts | Field>;
center: null | THREE.Vector3;
invMomentOfInertia: THREE.Matrix3;
momentOfInertia: THREE.Matrix3;
mass: number;
subplate: Subplate;
quaternion: THREE.Quaternion;
angularVelocity: THREE.Vector3;
fields: Map<number, Field>;
isSubplate = false;
plateGroup: PlateGroup | null;
hotSpot: {
po... | deleteField | identifier_name | |
plate.ts | OfInertia.toArray(),
center: this.center?.toArray() || null,
hotSpot: {
force: this.hotSpot.force.toArray(),
position: this.hotSpot.position.toArray()
},
fields: Array.from(this.fields.values()).map(field => field.serialize()),
adjacentFields: Array.from(this.adjacentFields... | {
dist[adjField.id] = grid.fieldDiameterInKm;
queue.push(adjField);
} | conditional_block | |
utils.py | threading
import shutil
import os
import ftplib
import ftputil
import requests
import logging
import re
import bs4
import string
try:
from cryptography import fernet
except ImportError:
fernet = None
from buchschloss import core, config
class FormattedDate(date):
"""print a datetime.date as specified i... |
def get_book_data(isbn: int):
"""Attempt to get book data via the ISBN from the DB, if that fails,
try the DNB (https://portal.dnb.de)"""
try:
book = next(iter(core.Book.search(('isbn', 'eq', isbn))))
except StopIteration:
pass # actually, I could put the whole rest of the functio... | random_line_split | |
utils.py | threading
import shutil
import os
import ftplib
import ftputil
import requests
import logging
import re
import bs4
import string
try:
from cryptography import fernet
except ImportError:
fernet = None
from buchschloss import core, config
class FormattedDate(date):
"""print a datetime.date as specified i... | ():
"""get the encrypted contents of the database file"""
if fernet is None:
raise RuntimeError('encryption requested, but no cryptography available')
with open(config.core.database_name, 'rb') as f:
plain = f.read()
key = base64.urlsafe_b64encode(config.utils.tasks.secret_key)
ciphe... | get_encrypted_database | identifier_name |
utils.py | threading
import shutil
import os
import ftplib
import ftputil
import requests
import logging
import re
import bs4
import string
try:
from cryptography import fernet
except ImportError:
fernet = None
from buchschloss import core, config
class FormattedDate(date):
"""print a datetime.date as specified i... |
def late_books():
"""Check for late and nearly late books.
Call the functions in late_handlers with arguments (late, warn).
late and warn are sequences of core.Borrow instances.
"""
late = []
warn = []
today = date.today()
for b in core.Borrow.search((
('is_back', 'eq', F... | """Run stuff to do as specified by times set in config"""
while True:
if datetime.now() > core.misc_data.check_date+timedelta(minutes=45):
for stuff in stuff_to_do:
threading.Thread(target=stuff).start()
core.misc_data.check_date = datetime.now() + config.utils.tasks.... | identifier_body |
utils.py | import fernet
except ImportError:
fernet = None
from buchschloss import core, config
class FormattedDate(date):
"""print a datetime.date as specified in config.core.date_format"""
def __str__(self):
return self.strftime(config.core.date_format)
@classmethod
def fromdate(cls, date_: date... | for p in td[1].split('\n'):
g = person_re.search(p)
if g is None:
continue
g = g.groups()
if g[1] == 'Verfasser':
results['author'] = g[0]
else:
res... | conditional_block | |
peer_connection.rs | Claim,
) -> Result<PeerConnection, ConnectionManagerError> {
trace!(
target: LOG_TARGET,
"(Peer={}) Socket successfully upgraded to multiplexed socket",
peer_node_id.short_str()
);
// All requests are request/response, so a channel size of 1 is all that is needed
let (peer_tx, pe... |
#[cfg(feature = "rpc")]
#[tracing::instrument("peer_connection::connect_rpc", level="trace", skip(self), fields(peer_node_id = self.peer_node_id.to_string().as_str()))]
pub async fn connect_rpc<T>(&mut self) -> Result<T, RpcError>
where T: From<RpcClient> + NamedProtocolService {
self.connect_... | {
let substream = self.open_substream(protocol_id).await?;
Ok(framing::canonical(substream.stream, max_frame_size))
} | identifier_body |
peer_connection.rs | : Arc::new(()),
peer_identity_claim: Some(peer_identity_claim),
}
}
/// Should only be used in tests
pub(crate) fn unverified(
id: ConnectionId,
request_tx: mpsc::Sender<PeerConnectionRequest>,
peer_node_id: NodeId,
peer_features: PeerFeatures,
ad... | {
let tracing_id = tracing::Span::current().id();
let span = span!(Level::TRACE, "handle_request");
span.follows_from(tracing_id);
let result = self.open_negotiated_protocol_stream(protocol_id).instrument(span).await;
log_if_error_fmt!(
... | conditional_block | |
peer_connection.rs | Claim,
) -> Result<PeerConnection, ConnectionManagerError> {
trace!(
target: LOG_TARGET,
"(Peer={}) Socket successfully upgraded to multiplexed socket",
peer_node_id.short_str()
);
// All requests are request/response, so a channel size of 1 is all that is needed
let (peer_tx, pe... | (&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
write!(
f,
"Id: {}, Node ID: {}, Direction: {}, Peer Address: {}, Age: {:.0?}, #Substreams: {}, #Refs: {}",
self.id,
self.peer_node_id.short_str(),
self.direction,
self.address... | fmt | identifier_name |
peer_connection.rs | Claim,
) -> Result<PeerConnection, ConnectionManagerError> {
trace!(
target: LOG_TARGET,
"(Peer={}) Socket successfully upgraded to multiplexed socket",
peer_node_id.short_str()
);
// All requests are request/response, so a channel size of 1 is all that is needed
let (peer_tx, pe... | address: Arc<Multiaddr>,
direction: ConnectionDirection,
started_at: Instant,
substream_counter: AtomicRefCounter,
handle_counter: Arc<()>,
peer_identity_claim: Option<PeerIdentityClaim>,
}
impl PeerConnection {
pub(crate) fn new(
id: ConnectionId,
request_tx: mpsc::Sender<P... | peer_features: PeerFeatures,
request_tx: mpsc::Sender<PeerConnectionRequest>, | random_line_split |
web.js | success:function(data){
if(data.error){
return alert(data.error);
}
if(data.html){
if(display){
$(display).html(data.html);
}else{
$("body").append(data.html);
}
}
if(template && display && data && data.length){
var html = _.map(data, function(media){
re... | self.addClass("active"); | random_line_split | |
web.js | ('data-cmd-confirm');
data.payload = new FormData();
$.each(this.attributes, function(){
if(this.name.indexOf('data-payload') != -1){
var attr = this.name.replace('data-payload-', '');
data.payload.append(attr,this.value);
}
});
vod.handleCommand(data);
},
refreshCart: function(checkout){
$.ge... | {
props = JSON.parse(props);
var html = jade.render("listings-subpropfilter",{props:props});
var subprop = $("#listings-subpropfilter");
if(subprop.length){
subprop.html(html);
}else{
$("#sub-contents").prepend("<section id='listings-subpropfilter'>" + html + "</section>");
}
$("#listings-s... | conditional_block | |
web.js | if(vals.username.length != 7){
$("#error-message").text('Incorrect mobile number');
$("#modal-error").modal('show');
return;
}
$.post('/user/register',vals, function(res){
if(res.error){
$("#error-message").text(res.error);
$("#modal-error").modal('show');
}else if(res.message){
$("#erro... | renderFiles | identifier_name | |
web.js | text(res.error);
$("#modal-error").modal('show');
}else if(res.message){
$("#error-message").text(res.message);
$("#modal-error").modal('show');
$('#signup-form').slideUp('fast');
}
});
})
$('body').on('click', '#listings-subpropfilter .btn-group-vertical label', function(){
setTimeout(windo... | {
$("#file-container").html('');
files_container.forEach(function(file, index){
var html = jade.render('file-container',{index:index, file:file.name||file.fileName, size:prettyBytes(file.size||file.fileSize)});
$("#file-container").append(html);
})
} | identifier_body | |
db_explorer.go | int, int) {
q := u.Query()
limit := DEFAULT_LIMIT
offset := DEFAULT_OFFSET
limitParam, _ := q["limit"]
if len(limitParam) > 0 {
limitInt, err := strconv.Atoi(limitParam[0])
if err == nil {
limit = limitInt
}
}
offsetParam, _ := q["offset"]
if len(offsetParam) > 0 {
offsetInt, err := strcon... | // skip unknown fields
fields = append(fields, field.Name)
invalidTypeMessage := "field " + field.Name + " have invalid type"
// update auto increment field does not allowed
if field.AutoIncrement {
errorResponse(http.StatusBadRequest, invalidTypeMessage, w)
return
}
switch {
case value == nil && ... | { continue } | conditional_block |
db_explorer.go | int, int) {
q := u.Query()
limit := DEFAULT_LIMIT
offset := DEFAULT_OFFSET
limitParam, _ := q["limit"]
if len(limitParam) > 0 {
limitInt, err := strconv.Atoi(limitParam[0])
if err == nil {
limit = limitInt
}
}
offsetParam, _ := q["offset"]
if len(offsetParam) > 0 {
offsetInt, err := strcon... |
var fields []string
var values []interface{}
for _,field := range table.Fields {
if field.AutoIncrement {
continue
}
fields = append(fields, field.Name)
value, _ := params[field.Name]
if value == nil {
values = append(values, field.Default)
continue
}
values = append(values, value)
... | {
table, err := getTable(r, h)
if err != nil {
errorResponse(http.StatusBadRequest, err.Error(), w)
return
}
body, err := ioutil.ReadAll(r.Body)
defer r.Body.Close()
if err != nil {
errorResponse(http.StatusBadRequest, err.Error(), w)
return
}
var params map[string]interface{}
err = json.Unmarshal(... | identifier_body |
db_explorer.go | int, int) {
q := u.Query()
limit := DEFAULT_LIMIT
offset := DEFAULT_OFFSET
limitParam, _ := q["limit"]
if len(limitParam) > 0 {
limitInt, err := strconv.Atoi(limitParam[0])
if err == nil {
limit = limitInt
}
}
offsetParam, _ := q["offset"]
if len(offsetParam) > 0 {
offsetInt, err := strcon... | return
}
defer rows.Close()
result, err := parseResponse(rows, table)
if err != nil {
InternalServerError(err, w)
return
}
if len(result) == 0 {
errorResponse(http.StatusNotFound, "record not found", w)
return
}
successResponse(http.StatusOK, map[string]interface{}{"record": result[0]}, w)
}
f... | random_line_split | |
db_explorer.go | int, int) {
q := u.Query()
limit := DEFAULT_LIMIT
offset := DEFAULT_OFFSET
limitParam, _ := q["limit"]
if len(limitParam) > 0 {
limitInt, err := strconv.Atoi(limitParam[0])
if err == nil {
limit = limitInt
}
}
offsetParam, _ := q["offset"]
if len(offsetParam) > 0 {
offsetInt, err := strcon... | (w http.ResponseWriter, r *http.Request) {
table, err := getTable(r, h)
if | Delete | identifier_name |
DQN_1.py | .create_rectangle(
origin[0] - 15, origin[1] - 15,
origin[0] + 15, origin[1] + 15,
fill='red')
# pack all
self.canvas.pack()
def reset(self):
self.update()
time.sleep(0.1)
self.canvas.delete(self.rect)
origin = np.array([20, 20])
... | leep(0.01)
self.update()
np.random.seed(1)
tf.set_random_seed(1)
class DeepQNetwork:
# 建立神经网络
def _build_net(self):
# -------------- 创建 eval 神经网络, 及时提升参数 --------------
tf.compat.v1.disable_eager_execution()
self.s = tf.placeholder(tf.float32, [None, self.n_features], name='s... | time.s | identifier_name |
DQN_1.py | .create_rectangle(
origin[0] - 15, origin[1] - 15,
origin[0] + 15, origin[1] + 15,
fill='red')
# pack all
self.canvas.pack()
def reset(self):
self.update()
time.sleep(0.1)
self.canvas.delete(self.rect)
origin = np.array([20, 20])
... | ve(self.rect, base_action[0], base_action[1]) # move agent
next_coords = self.canvas.coords(self.rect) # next state
# reward function
if next_coords == self.canvas.coords(self.oval):
reward = 1
done = True
elif next_coords in [self.canvas.coords(self.hell1)]:
... | self.canvas.mo | conditional_block |
DQN_1.py | lf):
self.canvas = tk.Canvas(self, bg='white',
height=MAZE_H * UNIT,
width=MAZE_W * UNIT)
# create grids
for c in range(0, MAZE_W * UNIT, UNIT):
x0, y0, x1, y1 = c, 0, c, MAZE_H * UNIT
self.canvas.create_lin... | __()
self.action_space = ['u', 'd', 'l', 'r']
self.n_actions = len(self.action_space)
self.n_features = 2
self.title('maze')
self.geometry('{0}x{1}'.format(MAZE_H * UNIT, MAZE_H * UNIT))
self._build_maze()
def _build_maze(se | identifier_body | |
DQN_1.py | .variable_scope('l1'):
w1 = tf.get_variable('w1', [self.n_features, n_l1], initializer=w_initializer, collections=c_names)
b1 = tf.get_variable('b1', [1, n_l1], initializer=b_initializer, collections=c_names)
l1 = tf.nn.relu(tf.matmul(self.s_, w1) + b1)
# tar... | self.learn_step_counter += 1
def plot_cost(self):
import matplotlib.pyplot as plt | random_line_split | |
utils.py | olvers import reverse
from django.test import RequestFactory
class UnAuthorized(Exception):
pass
class NotFound(Exception):
|
class NoBasesFound(Exception):
pass
logger = logging.getLogger(__name__)
class Connection(object):
def __init__(self, dropbox_access_token):
self.client = dropbox.client.DropboxClient(dropbox_access_token)
super(Connection, self).__init__()
def info(self):
account_info = sel... | pass | identifier_body |
utils.py | olvers import reverse
from django.test import RequestFactory
class UnAuthorized(Exception):
pass
class NotFound(Exception):
pass
class NoBasesFound(Exception):
pass
logger = logging.getLogger(__name__)
class Connection(object):
def __init__(self, dropbox_access_token):
self.client = d... | (code, name):
errors = []
class CustomMessage(object):
pass
reporter = modReporter._makeDefaultReporter()
try:
tree = compile(code, name, "exec", _ast.PyCF_ONLY_AST)
except SyntaxError:
value = sys.exc_info()[1]
msg = value.args[0]
(lineno, offset, text) = ... | check_code | identifier_name |
utils.py | .append(base['path'].lstrip('/'))
if len(bases) == 0:
raise NoBasesFound()
return bases
def get_file(self, path):
logger.debug("get file %s" % path)
return self._call('get_file', path)
def get_file_content_and_rev(self, path):
file, metadata = self._call('ge... | return token
def read_jwt(payload, secret): | random_line_split | |
utils.py | olvers import reverse
from django.test import RequestFactory
class UnAuthorized(Exception):
pass
class NotFound(Exception):
pass
class NoBasesFound(Exception):
pass
logger = logging.getLogger(__name__)
class Connection(object):
def __init__(self, dropbox_access_token):
self.client = d... |
if not os.path.exists(fq_file):
f = open(fq_file, 'w')
f.write(content)
f.close()
if sys.platform == "darwin":
os.popen4("echo $(cat %s) > %s" % (fq_file, fq_file))
else:
os.popen4("echo -e $(cat %s) > %s" % (fq_file, fq_file))
return fq_file
de... | os.mkdir(path) | conditional_block |
courses.py | # Go back to course listing.
self.logger.debug('Returning to course list')
ic_action = {'ICAction': return_state}
self._request_page(ic_action)
self.logger.debug('Done department')
except Exception:
... | (func):
"""Execute Selenium task and retry upon failure."""
retries = 0
while retries < 3:
try:
return func()
except Exception as ex:
self.logger.error(
'Selenium error #%s: %s', retries ... | run_selenium_routine | identifier_name |
courses.py | )',
term.text.strip(), term_number)
payload = {
'ICAction': 'DERIVED_SAA_CRS_SSR_PB_GO$3$',
'DERIVED_SAA_CRS_TERM_ALT': term_number,
}
soup = self._... | """Preprocess and reformat course name."""
course_title = soup.find('span', id=regex_title).text.strip()
name_idx = course_title.find('-')
dept_raw, course_code_raw = course_title[:name_idx - 1].split(' ')
course_name = course_title[name_idx + 1:].strip()
de... | identifier_body | |
courses.py | is minimized. "
"Requesting 'View All' for current term...")
payload.update(
{'ICAction': 'CLASS_TBL_VW5$hviewall$0'})
soup = self._request_page(payload)
self.logger.debu... | if descr_raw.find_all('br'):
return descr_raw.find_all('br')[0].previous_sibling
| random_line_split | |
courses.py | # Go back to course listing.
self.logger.debug('Returning to course list')
ic_action = {'ICAction': return_state}
self._request_page(ic_action)
self.logger.debug('Done department')
except Exception:
... | payload.update(
{'ICAction': 'CLASS_TBL_VW5$hviewall$0'})
soup = self._request_page(payload)
self.logger.debug("'View All' request complete.")
sections = self._get_sections(soup)
... | try:
term_number = int(term['value'])
self.logger.debug('Starting term: %s (%s)',
term.text.strip(), term_number)
payload = {
'ICAction': 'DERIVED_SAA_CRS_SSR_PB_GO$3$',
... | conditional_block |
leetcodeFunc.go | temp := nums[i] + jw
if jw > 0 {
jw--
}
if temp >= 10 {
temp = temp - 10
jw++
}
r = append(r, temp)
}
}
} else {
for i := 0; i < lg1; i++ {
if i < lg {
temp := nums[i] + nums1[i] + jw
if jw > 0 {
jw--
}
if temp >= 10 {
temp = temp - 10
j... | mp := nums[i] + nums1[i] + jw
if jw > 0 {
jw--
}
if temp >= 10 {
temp = temp - 10
jw++
}
r = append(r, temp)
} else {
| conditional_block | |
leetcodeFunc.go | if sum >= num {
count++
}
}
}
if k == len(arr) {
if sum >= num {
count++
}
}
return count
}
/**
1330. 翻转子数组得到最大的数组值
使用数轴表示
a-----b
c------d
差值为 |c-b|*2 所以需要 b 最小 c 最大 才能获得最大的值
*/
func maxValueAfterReverse(nums []int) int {
sum := 0
length := len(nums)
a := -100000 //区间小值
b := 100000 //... | 最大二叉树 II
*/
func insertIntoMaxTree(root *TreeNode, val int) *TreeNode {
//right 为空返回 新增又树
if root == nil {
return &TreeNode{
Val: val,
Left: nil,
Right: nil,
}
}
//节点大于树,原树入左侧 ,节点做根
if root.Val < val {
return &TreeNode{
Val: val,
Left: root,
Right: nil,
}
}
root.Right = insertInt... | }
/*
998. | identifier_name |
leetcodeFunc.go | if sum >= num {
count++
}
}
}
if k == len(arr) {
if sum >= num {
count++
}
}
return count
}
/**
1330. 翻转子数组得到最大的数组值
使用数轴表示
a-----b
c------d
差值为 |c-b|*2 所以需要 b 最小 c 最大 才能获得最大的值
*/
func maxValueAfterReverse(nums []int) int {
sum := 0
length := len(nums)
a := -100000 //区间小值
b := 100000 //... | arget 的比较
d := presum + value*k - target
if d >= 0 {
//fmt.Println(d,value,endLen,index)
// c小于等于0.5那么取小 大于0.5 去取上值
c := value - (d+k/2)/k
return c
}
presum += value
}
return arr[length-1]
}
/**
1052. 爱生气的书店老板
*/
func maxSatisfied(customers []int, grumpy []int, X int) int {
count := 0
//默认的值
... | presum := 0
endLen := length
for index, value := range arr {
k := endLen - index
// 条件 未改变的和 + 当前 value*剩余的项 与 t | identifier_body |
leetcodeFunc.go | if sum >= num {
count++
}
}
}
if k == len(arr) {
if sum >= num {
count++
} | 1330. 翻转子数组得到最大的数组值
使用数轴表示
a-----b
c------d
差值为 |c-b|*2 所以需要 b 最小 c 最大 才能获得最大的值
*/
func maxValueAfterReverse(nums []int) int {
sum := 0
length := len(nums)
a := -100000 //区间小值
b := 100000 //区间大值
for i := 0; i < length-1; i++ {
sum += IntAbs(nums[i] - nums[i+1])
a = IntMax(a, IntMin(nums[i], nums[i+1]))
... | }
return count
}
/** | random_line_split |
types.go | specific language governing permissions and
limitations under the License.
*/
package v1alpha1
import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
componentbaseconfigv1alpha1 "k8s.io/component-base/config/v1alpha1"
)
// VolumeConfiguration contains *all* enumerated flags meant to configure all volume
// plugin... | EndpointController EndpointControllerConfiguration
// GarbageCollectorControllerConfiguration holds configuration for
// GarbageCollectorController related features.
GarbageCollectorController GarbageCollectorControllerConfiguration
// NamespaceControllerConfiguration holds configuration for NamespaceController
/... | random_line_split | |
html_tools.py | (out_dir, chapter_dirs, static_host):
build_dir = os.path.dirname(out_dir)
if static_host and not static_host.endswith('/'):
static_host += '/'
for path in _walk(build_dir):
rewrite_file_links(path, out_dir, chapter_dirs, static_host)
def rewrite_file_links(path, root, chapter_dirs, static... |
def recursive_rewrite_links(data_dict, path, root, link_elements, other_elements,
static_host, chapter_dirs, chapter_append, yaml_append, rst_src_path,
lang_key=False, lang=None):
'''Rewrite links in the string values inside the data_dict.'''
# YAML file may have a list or a dictionary in the... | with io.open(file_path, 'w', encoding='utf-8') as f:
f.write(content) | identifier_body |
html_tools.py | (out_dir, chapter_dirs, static_host):
build_dir = os.path.dirname(out_dir)
if static_host and not static_host.endswith('/'):
static_host += '/'
for path in _walk(build_dir):
rewrite_file_links(path, out_dir, chapter_dirs, static_host)
def rewrite_file_links(path, root, chapter_dirs, static... | (content, path, root, link_elements, other_elements,
static_host, chapter_dirs, chapter_append, yaml_append,
rst_src_path=None):
q1 = re.compile(r'^(\w+:|//|#)') # Starts with "https:", "//" or "#".
q2 = re.compile(r'^(' + '|'.join(chapter_dirs) + r')(/|\\)') # Starts wit... | rewrite_links | identifier_name |
html_tools.py | (out_dir, chapter_dirs, static_host):
build_dir = os.path.dirname(out_dir)
if static_host and not static_host.endswith('/'):
static_host += '/'
for path in _walk(build_dir):
rewrite_file_links(path, out_dir, chapter_dirs, static_host)
def rewrite_file_links(path, root, chapter_dirs, static... |
out += content[i:]
return out
def _walk(html_dir):
files = []
for root, dirnames, filenames in os.walk(html_dir):
for filename in fnmatch.filter(filenames, '*.html'):
files.append(os.path.join(root, filename))
for filename in fnmatch.filter(filenames, '*.yaml'):
... | random_line_split | |
html_tools.py | (out_dir, chapter_dirs, static_host):
build_dir = os.path.dirname(out_dir)
if static_host and not static_host.endswith('/'):
static_host += '/'
for path in _walk(build_dir):
rewrite_file_links(path, out_dir, chapter_dirs, static_host)
def rewrite_file_links(path, root, chapter_dirs, static... |
elif isinstance(val, str):
if isinstance(rst_src_path, dict):
lang_rst_src_path = rst_src_path.get(lang if lang else 'en')
else:
lang_rst_src_path = rst_src_path
data_dict[key] = rewrite_links(val, path, root, link_elem... | recursive_rewrite_links(val, path, root, link_elements,
other_elements, static_host, chapter_dirs, chapter_append,
yaml_append, rst_src_path, key.endswith('|i18n'), lang)
# lang_key: if key is, e.g., "title|i18n", then the val dict
# contains keys ... | conditional_block |
common.js | navigator.userAgent.match(/BlackBerry/i)
|| navigator.userAgent.match(/Windows Phone/i)
){
return true;
}
else {
return false;
}
}
function getScroll() {
var data, scrOfX = 0, scrOfY = 0;
if( typeof( window.pageYOffset ) == 'number' ) {
//Netscape compliant
sc... | },
showError: function( name, msg ) { | random_line_split | |
common.js | img.src+')'});
}
syncBg();
$('.overlay').removeClass('show');
}
}
// if mobile
else {
$section.backstretch({url: img.src, alignY: 0});
$bg.backstretch({url: img.src, alignY: 0});
}
}
function syncBg() {
// if no mobile not use alg
if(!detectmob()) {
return false;
}
... |
function initMap(){
// text overlay proto
function TxtOverlay(pos, txt, cls, map) {
this.pos = pos;
this.txt_ = txt;
this.cls_ = cls;
this.map_ = map;
this.div_ = null;
this.setMap(map);
}
TxtOverlay.prototype = new google.maps.OverlayView();
TxtOverlay.prototype.onAdd = function(... | {
var data, scrOfX = 0, scrOfY = 0;
if( typeof( window.pageYOffset ) == 'number' ) {
//Netscape compliant
scrOfY = window.pageYOffset;
scrOfX = window.pageXOffset;
} else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
... | identifier_body |
common.js | ,60,29,60,30,60,31,60,32,60,33,60,34,59,35,59,36,59,37,59,38,59,39,58,40,58,41,58,42,57,43,57,44,57,45,56,46,56,47,55,48,54,49,54,50,53,51,52,52,52,53,51,54,50,55,50,56,49,57,48,58,48,59,47,60,46,61,45,62,45,63,44,64,43,65,43,66,43,67,42,68,41,69,40,70,40,71,39,72,38,73,37,74,36,75,36,76,35,77,34,78,33,79,32,80,31,81,3... | if ($(window).scrollTop() >= this.maxTop) {
obj.removeClass("fix | conditional_block | |
common.js | ('+img.src+')'});
}
syncBg();
$('.overlay').removeClass('show');
}
}
// if mobile
else {
$section.backstretch({url: img.src, alignY: 0});
$bg.backstretch({url: img.src, alignY: 0});
}
}
function syncBg() {
// if no mobile not use alg
if(!detectmob()) {
return false;
}
... | () {
var $section = $('.faq');
if( !$section.length ) return false;
var $i = $('.faq .list');
var $pointer = $('.list-indicator');
var s = getScroll();
var is_top = ($section.offset().top - s.top);
var faq_height = ($section.height() - 100);
var faq_nav_height = $i.height() ;
var f... | listIndicate | identifier_name |
dsm2dtm.py |
def extract_dtm(dsm_path, ground_dem_path, non_ground_dem_path, radius, terrain_slope):
"""
Generates a ground DEM and non-ground DEM raster from the input DSM raster.
Input:
dsm_path: {string} path to the DSM raster
radius: {int} Search radius of kernel in cells.
terrain_slope: {... | np_raster = np.array(gdal.Open(raster_path).ReadAsArray())
return np_raster[np_raster != ignore_value].mean() | identifier_body | |
dsm2dtm.py | to the generated ground DEM raster
non_ground_dem_path: {string} path to the generated non-ground DEM raster
"""
cmd = "saga_cmd grid_filter 7 -INPUT {} -RADIUS {} -TERRAINSLOPE {} -GROUND {} -NONGROUND {}".format(
dsm_path, radius, terrain_slope, ground_dem_path, non_ground_dem_path
)
... | (dsm_path, temp_dir):
# check DSM resolution. Downsample if DSM is of very high resolution to save processing time.
x_res, y_res = get_raster_resolution(dsm_path) # resolutions are in meters
dsm_name = dsm_path.split("/")[-1].split(".")[0]
dsm_crs = get_raster_crs(dsm_path)
if dsm_crs != 4326:
... | get_res_and_downsample | identifier_name |
dsm2dtm.py | to the generated ground DEM raster
non_ground_dem_path: {string} path to the generated non-ground DEM raster
"""
cmd = "saga_cmd grid_filter 7 -INPUT {} -RADIUS {} -TERRAINSLOPE {} -GROUND {} -NONGROUND {}".format(
dsm_path, radius, terrain_slope, ground_dem_path, non_ground_dem_path
)
... |
return np_raster
def get_raster_crs(raster_path):
"""
Returns the CRS (Coordinate Reference System) of the raster
Input:
raster_path: {string} path to the source tif image
"""
raster = rasterio.open(raster_path)
return raster.crs
def get_raster_resolution(raster_path):
raste... | try:
np_raster[i, j] = no_data_value
except:
pass | conditional_block |
dsm2dtm.py | to the generated ground DEM raster
non_ground_dem_path: {string} path to the generated non-ground DEM raster
"""
cmd = "saga_cmd grid_filter 7 -INPUT {} -RADIUS {} -TERRAINSLOPE {} -GROUND {} -NONGROUND {}".format(
dsm_path, radius, terrain_slope, ground_dem_path, non_ground_dem_path
)
... | if x_res < 0.3 or y_res < 0.3:
target_res = 0.3 # downsample to this resolution (in meters)
downsampling_factor = target_res / gdal.Open(dsm_path).GetGeoTransform()[1]
downsampled_dsm_path = os.path.join(temp_dir, dsm_name + "_ds.tif")
# Dowmsampling DSM
... | dsm_crs = get_raster_crs(dsm_path)
if dsm_crs != 4326: | random_line_split |
lib.rs | to more of the underlying
//! details of the WebSocket connection.
//!
//! Another method you will probably want to implement is `on_close`. This method is called anytime
//! the other side of the WebSocket connection attempts to close the connection. Implementing
//! `on_close` gives you a mechanism for informing the... | {
return self.run()
} | conditional_block | |
lib.rs | a message immediately when a WebSocket connection is
//! established, you will need to write a Handler that implements the `on_open` method. For
//! example:
//!
//! ```no_run
//! use ws::{connect, Handler, Sender, Handshake, Result, Message, CloseCode};
//!
//! // Our Handler struct.
//! // Here we explicity indicate... | connect | identifier_name | |
lib.rs | or Response, such as by checking cookies or Auth headers.
//! fn on_open(&mut self, _: Handshake) -> Result<()> {
//! // Now we don't need to call unwrap since `on_open` returns a `Result<()>`.
//! // If this call fails, it will only result in this connection disconnecting.
//! self.out.sen... | where F: Factory
{
/// Create a new WebSocket using the given Factory to create handlers.
pub fn new(mut factory: F) -> Result<WebSocket<F>> {
let max = factory.settings().max_connections; | random_line_split | |
index.ts | a revert error.
let revert: RevertError;
try {
revert = decodeBytesAsRevertError(rawCallResult);
} catch (err) {
// Can't decode it as a revert error, so assume it didn't revert.
return;
}
throw revert;
}
protected static _throwIfThrow... | {
throw new Error(`Undefined Method Input ABI`);
} | conditional_block | |
index.ts | v: T) => TResult | Promise<TResult>,
onRejected?: (reason: any) => Promise<never>,
): Promise<TResult> {
return this._promise.then<TResult>(onFulfilled, onRejected);
}
public catch<TResult>(onRejected?: (reason: any) => Promise<TResult>): Promise<TResult | T> {
return this._promise.c... |
protected static _throwIfCallResultIsRevertError(rawCallResult: string): void {
// Try to decode the call result as a revert error.
let revert: RevertError;
try {
revert = decodeBytesAsRevertError(rawCallResult);
} catch (err) {
// Can't decode it as a revert... | {
const constructorAbiIfExists = abi.find(
(abiDefinition: AbiDefinition) => abiDefinition.type === AbiType.Constructor,
// tslint:disable-next-line:no-unnecessary-type-assertion
) as ConstructorAbi | undefined;
if (constructorAbiIfExists !== undefined) {
retu... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.