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
nc_read_functions.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ''' Set of auxliary functions for the WRF_read script author: Roberto Chavez <roberto.chavez@ul.com> march/2020 ''' import numpy as np import pandas as pd import datetime from scipy.spatial import cKDTree import utm from wrf import extract_dim, ll_to_xy, xy_to_ll d...
(ncfid, iTimes, iBT, iSN, iWE): ''' Memory efficient function to extract the height (averaged in time) of WRF output The height is provided in 3D (i.e. bottom-top, north-south, west-east) Parameters ---------- ncfid : file id file of the netcdf. iTimes : int, logic index of the times to extract form the ...
get_nc_coordinates
identifier_name
nc_read_functions.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ''' Set of auxliary functions for the WRF_read script author: Roberto Chavez <roberto.chavez@ul.com> march/2020 ''' import numpy as np import pandas as pd import datetime from scipy.spatial import cKDTree import utm from wrf import extract_dim, ll_to_xy, xy_to_ll d...
class nc_results: ''' Class (lean version) to query any given point or set of points in from a previously created WRF dictionary ''' def __init__(self, timesSim, zagl): ''' Initialize the class ''' self.times = timesSim # Reference Time for the netcdf files self.refe...
lat = ncfid.variables.get('XLAT')[0, :, 0] lon = ncfid.variables.get('XLONG')[0, 0, :] # makes sure central box coordinates lie inside wrf domain box if (min(abs(lat - lat_s)) > max(np.diff(lat))) | (min(abs(lon - lon_s)) > max(np.diff(lon))): raise Exception("ERROR: lat | lon chosen is outside wrf...
identifier_body
nc_read_functions.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ''' Set of auxliary functions for the WRF_read script author: Roberto Chavez <roberto.chavez@ul.com> march/2020 ''' import numpy as np import pandas as pd import datetime from scipy.spatial import cKDTree import utm from wrf import extract_dim, ll_to_xy, xy_to_ll d...
elif iStr.startswith('west'): logicSlices.append(iWE) # Extract and unstager the data varData = varObj[logicSlices] if (len(ncDims) == 3) and (stageredDim > 0): if stageredDim == 1: varData = (varData[:, 0:-1, :] + varData[:, 1:, :]) * 0.5 elif stag...
logicSlices.append(iSN)
conditional_block
nc_read_functions.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ''' Set of auxliary functions for the WRF_read script author: Roberto Chavez <roberto.chavez@ul.com> march/2020 ''' import numpy as np import pandas as pd import datetime from scipy.spatial import cKDTree import utm from wrf import extract_dim, ll_to_xy, xy_to_ll d...
iWE : int CENTERED (i.e. unstaggered) indexes of desired weast-east coordinates. Returns ------- out : ndarray numpy array with the height above sea level ''' nz = len(iBT) + 1 ltmp = getVarEff(ncfid, 'XLAT', iTimes, iBT, iSN, iWE).mean(axis=0) LAT = np.tile(ltmp, (nz, 1, 1)) ltmp = getVarE...
iSN : int CENTERED (i.e. unstaggered) indexes of desired south-north coordinates.
random_line_split
types.rs
use crate::{encode_section, Encode, Section, SectionId}; /// Represents a subtype of possible other types in a WebAssembly module. #[derive(Debug, Clone)] pub struct SubType { /// Is the subtype final. pub is_final: bool,
pub structural_type: StructuralType, } /// Represents a structural type in a WebAssembly module. #[derive(Debug, Clone)] pub enum StructuralType { /// The type is for a function. Func(FuncType), /// The type is for an array. Array(ArrayType), /// The type is for a struct. Struct(StructType)...
/// The list of supertype indexes. As of GC MVP, there can be at most one supertype. pub supertype_idx: Option<u32>, /// The structural type of the subtype.
random_line_split
types.rs
use crate::{encode_section, Encode, Section, SectionId}; /// Represents a subtype of possible other types in a WebAssembly module. #[derive(Debug, Clone)] pub struct SubType { /// Is the subtype final. pub is_final: bool, /// The list of supertype indexes. As of GC MVP, there can be at most one supertype. ...
{ /// The `i8` type. I8, /// The `i16` type. I16, /// A value type. Val(ValType), } /// The type of a core WebAssembly value. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Ord, PartialOrd)] pub enum ValType { /// The `i32` type. I32, /// The `i64` type. I64, /// The `f3...
StorageType
identifier_name
types.rs
use crate::{encode_section, Encode, Section, SectionId}; /// Represents a subtype of possible other types in a WebAssembly module. #[derive(Debug, Clone)] pub struct SubType { /// Is the subtype final. pub is_final: bool, /// The list of supertype indexes. As of GC MVP, there can be at most one supertype. ...
/// Define an explicit subtype in this type section. pub fn subtype(&mut self, ty: &SubType) -> &mut Self { // In the GC spec, supertypes is a vector, not an option. let st = match ty.supertype_idx { Some(idx) => vec![idx], None => vec![], }; if ty.is_fi...
{ self.bytes.push(0x5f); fields.len().encode(&mut self.bytes); for f in fields.iter() { self.field(&f.element_type, f.mutable); } self.num_added += 1; self }
identifier_body
bid.rs
//! Auctions and bidding during the first phase of the deal. use std::fmt; use std::str::FromStr; use serde::{Deserialize, Serialize}; use strum_macros::EnumIter; use super::cards; use super::deal; use super::pos; /// Goal set by a contract. /// /// Determines the winning conditions and the score on success. #[deriv...
(&self) -> &Vec<cards::Hand> { &self.players } /// The current player passes his turn. /// /// Returns the new auction state : /// /// * `AuctionState::Cancelled` if all players passed /// * `AuctionState::Over` if 5 players passed in a row /// * The previous state otherwise ...
hands
identifier_name
bid.rs
//! Auctions and bidding during the first phase of the deal. use std::fmt; use std::str::FromStr; use serde::{Deserialize, Serialize}; use strum_macros::EnumIter; use super::cards; use super::deal; use super::pos; /// Goal set by a contract. /// /// Determines the winning conditions and the score on success. #[deriv...
Ok(()) } fn get_player_status(&self, pos: pos::PlayerPos) -> BidStatus { self.players_status[pos.to_n()] } fn set_player_status(&mut self, pos: pos::PlayerPos, status: BidStatus) { self.players_status[pos.to_n()] = status; } /// Returns the player that is expected to...
{ if target.multiplier() <= contract.target.multiplier() { return Err(BidError::NonRaisedTarget); } }
conditional_block
bid.rs
//! Auctions and bidding during the first phase of the deal. use std::fmt; use std::str::FromStr; use serde::{Deserialize, Serialize}; use strum_macros::EnumIter; use super::cards; use super::deal; use super::pos; /// Goal set by a contract. /// /// Determines the winning conditions and the score on success. #[deriv...
} impl Auction { /// Starts a new auction, starting with the player `first`. pub fn new(first: pos::PlayerPos) -> Self { let count = first.count as usize; let (hands, dog) = super::deal_hands(count); Auction { contract: None, players_status: vec![BidStatus::Todo...
{ match *self { BidError::AuctionClosed => write!(f, "auctions are closed"), BidError::TurnError => write!(f, "invalid turn order"), BidError::NonRaisedTarget => write!(f, "bid must be higher than current contract"), BidError::AuctionRunning => write!(f, "the auct...
identifier_body
bid.rs
//! Auctions and bidding during the first phase of the deal. use std::fmt; use std::str::FromStr; use serde::{Deserialize, Serialize}; use strum_macros::EnumIter; use super::cards; use super::deal; use super::pos; /// Goal set by a contract. /// /// Determines the winning conditions and the score on success. #[deriv...
let contract = Contract::new(pos, target, slam); self.contract = Some(contract); self.set_player_status(pos, BidStatus::Bid); // If we're all the way to the top, there's nowhere else to go if self.no_player_left() || target == Target::GardeContre { self.state = Auct...
// Reset previous bidder status if let Some(contract) = self.contract.clone() { self.set_player_status(contract.author, BidStatus::Todo); }
random_line_split
bot.py
import discord from discord.ext import commands import datetime import time import sys import asyncio import os from cogs.utils import launcher import json import logging import random from cogs.utils.paginator import Pages import io import textwrap import traceback from contextlib import redirect_stdout logger = logg...
(ctx, body): if body.startswith('```') and body.endswith('```'): content = '\n'.join(body.split('\n')[1:-1]) else: content = body.strip('`') await bot.edit_message(ctx.message, '```py\n'+content+'```') @bot.command(pass_context=True, name='eval') @is_owner() async def...
to_code_block
identifier_name
bot.py
import discord from discord.ext import commands import datetime import time import sys import asyncio import os from cogs.utils import launcher import json import logging import random from cogs.utils.paginator import Pages import io import textwrap import traceback from contextlib import redirect_stdout logger = logg...
kats = bot.get_channel('313863292126756864') if member.server.id == '294262760752152576': await bot.send_message(kats, '{0.mention} Welcome to **Dragons and Kats**! Have a great time here and enjoy yourselves!!!:wink: !'.format(member)) else: print('Member joined {}, but message not sent'.forma...
await bot.send_message(darkness, 'Welcome {0.mention} to {}. Please read #info-and-rules and enjoy your stay. Do d.help to check out the bot'.format(member, server))
conditional_block
bot.py
import discord from discord.ext import commands import datetime import time import sys import asyncio import os from cogs.utils import launcher import json import logging import random from cogs.utils.paginator import Pages import io import textwrap import traceback from contextlib import redirect_stdout logger = logg...
await bot.add_reaction(x, '\U0001f535') except: pass else: try: await bot.add_reaction(ctx.message, '\U0001f535') except: pass else: try: x = aw...
x = await bot.say('```py\n%s\n```' % value) except: x = await bot.say('```py\n\'Result was too long.\'```') try:
random_line_split
bot.py
import discord from discord.ext import commands import datetime import time import sys import asyncio import os from cogs.utils import launcher import json import logging import random from cogs.utils.paginator import Pages import io import textwrap import traceback from contextlib import redirect_stdout logger = logg...
@bot.command(pass_context = True) async def dm(ctx, user: discord.Member, *, msg: str): if ctx.message.author.id == '300396755193954306': await bot.send_message(user, '{}'.format(msg)) await bot.delete_message(ctx.message) else: message = await bot.say('Only t...
dev = '@-= shadeyg56™ =-#1702' user = ctx.message.author await bot.send_message(dev, '{} sent the following message: {}'.format(user, msg)) await bot.say('Your message has been sent. It will be checked by the dev asap. If your message was a troll or you keep resending/spamming a message you will be blacklis...
identifier_body
trigger.go
/* Copyright 2018 The Knative Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, soft...
(trigger *v1alpha1.Trigger) (*v1alpha1.Trigger, error) { ctx := context.TODO() objectKey := client.ObjectKey{Namespace: trigger.Namespace, Name: trigger.Name} latestTrigger := &v1alpha1.Trigger{} if err := r.client.Get(ctx, objectKey, latestTrigger); err != nil { return nil, err } triggerChanged := false if...
updateStatus
identifier_name
trigger.go
/* Copyright 2018 The Knative Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, soft...
// getChannel returns the Broker's channel if it exists, otherwise it returns an error. func (r *reconciler) getChannel(ctx context.Context, b *v1alpha1.Broker, ls labels.Selector) (*v1alpha1.Channel, error) { list := &v1alpha1.ChannelList{} opts := &runtimeclient.ListOptions{ Namespace: b.Namespace, LabelS...
{ return r.getChannel(ctx, b, labels.SelectorFromSet(broker.IngressChannelLabels(b))) }
identifier_body
trigger.go
/* Copyright 2018 The Knative Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, soft...
// Watch Triggers. if err = c.Watch(&source.Kind{Type: &v1alpha1.Trigger{}}, &handler.EnqueueRequestForObject{}); err != nil { return nil, err } // Watch all the resources that the Trigger reconciles. for _, t := range []runtime.Object{&corev1.Service{}, &istiov1alpha3.VirtualService{}, &v1alpha1.Subscription...
{ return nil, err }
conditional_block
trigger.go
/* Copyright 2018 The Knative Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, soft...
logging.FromContext(ctx).Error("Error reconciling Trigger", zap.Error(reconcileErr)) r.recorder.Eventf(trigger, corev1.EventTypeWarning, triggerReconcileFailed, "Trigger reconciliation failed: %v", reconcileErr) } else { logging.FromContext(ctx).Debug("Trigger reconciled") r.recorder.Event(trigger, corev1.Even...
if reconcileErr != nil {
random_line_split
mod.rs
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. //! Parsing and serialization of Internet Control Message Protocol (ICMP) packets. #[macro_use] mod macros; mod common; mod icmpv4; mod icmpv6; pub mod ml...
c.add_bytes(&[header.prefix.msg_type, header.prefix.code]); c.add_bytes(&header.prefix.checksum); c.add_bytes(header.message.as_bytes()); for p in message_body.iter_fragments() { c.add_bytes(p); } Some(c.checksum()) } impl<I: IcmpIpExt, B: ByteSlice, M: IcmpMessage<I, B>> IcmpPacket<I,...
{ c.add_bytes(src_ip.bytes()); c.add_bytes(dst_ip.bytes()); let icmpv6_len = mem::size_of::<Header<M>>() + message_body.len(); let mut len_bytes = [0; 4]; NetworkEndian::write_u32(&mut len_bytes, icmpv6_len.try_into().ok()?); c.add_bytes(&len_bytes[..]); c.add_byt...
conditional_block
mod.rs
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. //! Parsing and serialization of Internet Control Message Protocol (ICMP) packets. #[macro_use] mod macros; mod common; mod icmpv4; mod icmpv6; pub mod ml...
<S: Into<A>, D: Into<A>>(src_ip: S, dst_ip: D) -> IcmpParseArgs<A> { IcmpParseArgs { src_ip: src_ip.into(), dst_ip: dst_ip.into() } } } impl<B: ByteSlice, I: IcmpIpExt, M: IcmpMessage<I, B>> ParsablePacket<B, ()> for IcmpPacketRaw<I, B, M> { type Error = ParseError; fn parse_metadata(&self) ->...
new
identifier_name
mod.rs
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. //! Parsing and serialization of Internet Control Message Protocol (ICMP) packets. #[macro_use] mod macros; mod common; mod icmpv4; mod icmpv6; pub mod ml...
ParseMetadata::from_packet(self.header.bytes().len(), self.message_body.len(), 0) } fn parse<BV: BufferView<B>>(buffer: BV, args: IcmpParseArgs<I::Addr>) -> ParseResult<Self> { IcmpPacketRaw::parse(buffer, ()).and_then(|p| IcmpPacket::try_from_raw_with(p, args)) } } impl<I: IcmpIpExt, B: B...
{ type Error = ParseError; fn parse_metadata(&self) -> ParseMetadata {
random_line_split
calc_codon_usage.py
# Copyright (C) 2017 William M. Jacobs # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or (at # your option) any later version. # This program is distributed i...
gene_group_labels = ['%05.3f:%05.3f' % (groups[i][0], groups[i][1]) \ if i > 0 else 'ND' for i in range(len(groups))] except IOError: #this is the first run, get general usage info rerun_flag = True groups = ['all'] def get_gene_group(gene): return 0 gene_group_labels = ['all'] except KeyError: ...
if len(seqs[gene]) == 0: return 0 else: x = get_frac_rare(seqs[gene]) for i in range(1, len(groups)): if x >= groups[i][0] and x <= groups[i][1]: return i
identifier_body
calc_codon_usage.py
# Copyright (C) 2017 William M. Jacobs # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or (at # your option) any later version. # This program is distributed i...
abundances = {line.split()[0] : float(line.split()[1]) for line in f if len(line) > 1 and line[0] != '#'} except Exception as e: abundances = {} ''' if gi_index != None: with open(gi_index, 'r') as f: gi_index = {line.split()[0] : ' '.join(line.split()[1:]) \ for line in f if len(line) > 1 and lin...
with open(abundances, 'r') as f:
random_line_split
calc_codon_usage.py
# Copyright (C) 2017 William M. Jacobs # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or (at # your option) any later version. # This program is distributed i...
elif rare_model == 'cmax_norm': if codon_usage[c] / max(codon_usage[cc] for cc in aa_codons[codon_to_aa[c]]) <= rare_threshold: return True else: return False def calc_codon_usage(fasta, abundances=None, output="", rare_model='no_norm', rare_threshold=0.1, max_len_diff=0.2, group_dpercentile=10, wt_gi='gi|...
return False
conditional_block
calc_codon_usage.py
# Copyright (C) 2017 William M. Jacobs # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or (at # your option) any later version. # This program is distributed i...
(codon_usage, rare_model, rare_threshold, c): if rare_model == 'no_norm': if codon_usage[c] <= rare_threshold: return True else: return False elif rare_model == 'cmax_norm': if codon_usage[c] / max(codon_usage[cc] for cc in aa_codons[codon_to_aa[c]]) <= rare_threshold: return True else: return Fal...
israre
identifier_name
remote_cache.rs
use std::collections::{BTreeMap, HashSet, VecDeque}; use std::ffi::OsString; use std::path::Component; use std::sync::Arc; use std::time::Instant; use async_trait::async_trait; use bazel_protos::gen::build::bazel::remote::execution::v2 as remexec; use bazel_protos::require_digest; use fs::RelativePath; use futures::Fu...
else { tree.children.push(directory) } } Ok(Some(tree)) } pub(crate) async fn extract_output_file( root_directory_digest: Digest, file_path: RelativePath, store: &Store, ) -> Result<Option<FileNode>, String> { // Traverse down from the root directory digest to find the dir...
{ tree.root = Some(directory); }
conditional_block
remote_cache.rs
use std::collections::{BTreeMap, HashSet, VecDeque}; use std::ffi::OsString; use std::path::Component; use std::sync::Arc; use std::time::Instant; use async_trait::async_trait; use bazel_protos::gen::build::bazel::remote::execution::v2 as remexec; use bazel_protos::require_digest; use fs::RelativePath; use futures::Fu...
Ok(()) } fn log_cache_error(&self, err: String, err_type: CacheErrorType) { let err_count = { let mut errors_counter = match err_type { CacheErrorType::ReadError => self.read_errors_counter.lock(), CacheErrorType::WriteError => self.write_errors_counter.lock(), }; let cou...
.map_err(status_to_str)?;
random_line_split
remote_cache.rs
use std::collections::{BTreeMap, HashSet, VecDeque}; use std::ffi::OsString; use std::path::Component; use std::sync::Arc; use std::time::Instant; use async_trait::async_trait; use bazel_protos::gen::build::bazel::remote::execution::v2 as remexec; use bazel_protos::require_digest; use fs::RelativePath; use futures::Fu...
(&self, req: &MultiPlatformProcess) -> Option<Process> { self.underlying.extract_compatible_request(req) } }
extract_compatible_request
identifier_name
bare_index.rs
use crate::{Crate, Error, IndexConfig}; use std::marker::PhantomPinned; use std::{ io, path::{Path, PathBuf}, }; /// Access to a "bare" git index that fetches files directly from the repo instead of local checkout /// /// Uses Cargo's cache pub struct BareIndex { path: PathBuf, pub url: String, } impl...
(&mut self) -> Result<(), Error> { { let mut origin_remote = self .rt .repo .find_remote("origin") .or_else(|_| self.rt.repo.remote_anonymous(&self.inner.url))?; origin_remote.fetch( &[ "...
retrieve
identifier_name
bare_index.rs
use crate::{Crate, Error, IndexConfig}; use std::marker::PhantomPinned; use std::{ io, path::{Path, PathBuf}, }; /// Access to a "bare" git index that fetches files directly from the repo instead of local checkout /// /// Uses Cargo's cache pub struct BareIndex { path: PathBuf, pub url: String, } impl...
test_sval(&repo); repo.retrieve().expect("Failed to fetch crates.io index"); test_sval(&repo); } }
{ let krate = repo .crate_("sval") .expect("Could not find the crate sval in the index"); let version = krate .versions() .iter() .find(|v| v.version() == "0.0.1") .expect("Version 0.0.1 of sval does...
identifier_body
bare_index.rs
use crate::{Crate, Error, IndexConfig}; use std::marker::PhantomPinned; use std::{ io, path::{Path, PathBuf}, }; /// Access to a "bare" git index that fetches files directly from the repo instead of local checkout /// /// Uses Cargo's cache pub struct BareIndex { path: PathBuf, pub url: String, } impl...
pub fn with_path(path: PathBuf, url: &str) -> Self { Self { path, url: url.to_owned(), } } /// Creates an index for the default crates.io registry, using the same /// disk location as cargo itself. #[inline] pub fn new_cargo_default() -> Self { //...
/// Creates a bare index at the provided path with the specified repository URL. #[inline]
random_line_split
encode.rs
use std::collections::{HashMap, HashSet, BTreeMap}; use std::fmt; use std::str::FromStr; use regex::Regex; use rustc_serialize::{Encodable, Encoder, Decodable, Decoder}; use package::Package; use package_id::PackageId; use source::SourceId; use util::{CraftResult, Graph, Config, internal, ChainError, CraftError}; use...
{ let source = if id.source_id().is_path() { None } else { Some(id.source_id().with_precise(None)) }; EncodablePackageId { name: id.name().to_string(), version: id.version().to_string(), source: source, } }
identifier_body
encode.rs
use std::collections::{HashMap, HashSet, BTreeMap}; use std::fmt; use std::str::FromStr; use regex::Regex; use rustc_serialize::{Encodable, Encoder, Decodable, Decoder}; use package::Package; use package_id::PackageId; use source::SourceId; use util::{CraftResult, Graph, Config, internal, ChainError, CraftError}; use...
(s: &str) -> CraftResult<EncodablePackageId> { let regex = Regex::new(r"^([^ ]+) ([^ ]+)(?: \(([^\)]+)\))?$").unwrap(); let captures = regex.captures(s).ok_or_else(|| internal("invalid serialized PackageId"))?; let name = captures.at(1).unwrap(); let version = captures.at(2).unwrap(); ...
from_str
identifier_name
encode.rs
use std::collections::{HashMap, HashSet, BTreeMap}; use std::fmt; use std::str::FromStr; use regex::Regex; use rustc_serialize::{Encodable, Encoder, Decodable, Decoder}; use package::Package; use package_id::PackageId; use source::SourceId; use util::{CraftResult, Graph, Config, internal, ChainError, CraftError}; use...
} } } g }; let replacements = { let mut replacements = HashMap::new(); for &(ref id, ref pkg) in live_pkgs.values() { if let Some(ref replace) = pkg.replace { assert!(pkg.dependencies...
for edge in deps.iter() { if let Some(to_depend_on) = lookup_id(edge)? { g.link(id.clone(), to_depend_on);
random_line_split
MCObserver.py
#!/usr/bin/env python3 ########################################################################################################################## # # 2017/03 Thomas Britton # # Options: # MC variation can be changed by supplying "variation=xxxxx" option otherwise default: mc # the number of events to be gen...
if __name__ == "__main__": main(sys.argv[1:])
runnum=0 runmax=-1 spawnNum=10 numOverRide=False if(len(argv) !=0): numOverRide=True numprocesses_running=subprocess.check_output(["echo `ps all -u "+runner_name+" | grep MCObserver.py | grep -v grep | wc -l`"], shell=True) print(int(numprocesses_ru...
identifier_body
MCObserver.py
#!/usr/bin/env python3 ########################################################################################################################## # # 2017/03 Thomas Britton # # Options: # MC variation can be changed by supplying "variation=xxxxx" option otherwise default: mc # the number of events to be gen...
(argv): runnum=0 runmax=-1 spawnNum=10 numOverRide=False if(len(argv) !=0): numOverRide=True numprocesses_running=subprocess.check_output(["echo `ps all -u "+runner_name+" | grep MCObserver.py | grep -v grep | wc -l`"], shell=True) print(in...
main
identifier_name
MCObserver.py
#!/usr/bin/env python3 ########################################################################################################################## # # 2017/03 Thomas Britton # # Options: # MC variation can be changed by supplying "variation=xxxxx" option otherwise default: mc # the number of events to be gen...
print(int(numprocesses_running)) if(int(numprocesses_running) <2 or numOverRide): while(runnum<runmax or runmax==-1): runnum=runnum+1 try: queryosgjobs="SELECT * from Attempts WHERE BatchSystem='OSG' && SubmitHost=\""+MCWR...
if(len(argv) !=0): numOverRide=True numprocesses_running=subprocess.check_output(["echo `ps all -u "+runner_name+" | grep MCObserver.py | grep -v grep | wc -l`"], shell=True)
random_line_split
MCObserver.py
#!/usr/bin/env python3 ########################################################################################################################## # # 2017/03 Thomas Britton # # Options: # MC variation can be changed by supplying "variation=xxxxx" option otherwise default: mc # the number of events to be gen...
except Exception as e: print(e) break dbcnx.close() if __name__ == "__main__": main(sys.argv[1:])
if spawns[i].is_alive(): #print("join "+str(i)) spawns[i].join()
conditional_block
connector.js
connectorInit = function () { var connector = this; var element = connector.getElement(); var appBody = "<div id=\"visualization\"></div>\n"; element.innerHTML = appBody; //Добавляем кастомный стиль выбора элементов // var customSelectionStyle = ".vis-item.vis-selected { box-shadow: 0 0 30px ...
timeline = new vis.Timeline(container); timeline.setOptions(options); timeline.setGroups(groups); timeline.setItems(items); timeline.on("click", (e) => { connector.onClick(e) }); timeline.on("dblclick", (e) => { connector.onDoubleClick(e); }); timeline.on('sel...
}; // create a Timeline var container = document.getElementById("visualization");
random_line_split
connector.js
connectorInit = function () { var connector = this; var element = connector.getElement(); var appBody = "<div id=\"visualization\"></div>\n"; element.innerHTML = appBody; //Добавляем кастомный стиль выбора элементов // var customSelectionStyle = ".vis-item.vis-selected { box-shadow: 0 0 30px ...
var selectedStyle = styletags[i].innerHTML; // console.log(styletags[i].innerHTML) if(selectedStyle.includes(styleName)){ // console.log("Contains" +styletags[i].innerHTML +"||"); return true; } else{ ...
++) {
identifier_name
connector.js
connectorInit = function () { var connector = this; var element = connector.getElement(); var appBody = "<div id=\"visualization\"></div>\n"; element.innerHTML = appBody; //Добавляем кастомный стиль выбора элементов // var customSelectionStyle = ".vis-item.vis-selected { box-shadow: 0 0 30px ...
s = data.usesItems console.log("Items", items); groups = data.usesGroups lastSelectedItem = data.lastSelectedItem windowStartTime = data.windowStartTime windowEndTime = data.windowEndTime console.log("State data: ", data); items.forE...
var selectedStyle = styletags[i].innerHTML; // console.log(styletags[i].innerHTML) if(selectedStyle.includes(styleName)){ // console.log("Contains" +styletags[i].innerHTML +"||"); return true; } else{ // consol...
identifier_body
connector.js
connectorInit = function () { var connector = this; var element = connector.getElement(); var appBody = "<div id=\"visualization\"></div>\n"; element.innerHTML = appBody; //Добавляем кастомный стиль выбора элементов // var customSelectionStyle = ".vis-item.vis-selected { box-shadow: 0 0 30px ...
entHeight - leftHeight); if (targetOffset + height > currentScrollHeight + leftHeight || targetOffset < currentScrollHeight) { animateScroll(currentScrollHeight, offset, duration, timeline); timeline.setSelection(eventId); timeline.focus(eventId); } }; ...
ight + leftHeight) { offset += eventTop(event, group) + height - leftHeight + timeline.itemSet.options.margin.item.vertical; } } offset = Math.min(offset, cont
conditional_block
test_conv_layer.py
import pytest import numpy as np from collections import OrderedDict from contextlib import closing import neon as ng import neon.transformers as ngt from neon.testing import executor from neon.frontend.common import utils from neon.op_graph.axes import IncompatibleAxesError from neon.frontend import Convolution, Decon...
result = activation(result) # expand dimensions from K, time_steps, batch_size to (K, 1, time_steps, 1, batch_size) result = np.expand_dims(np.expand_dims(result, axis=1), axis=3) return result # TODO: Remove these to conftest.py @pytest.fixture(params=[1]) def input_size(request): return request...
for k in range(K): for n in range(batch_size): result[k, t, n] = np.sum(inputs[:, t:t + filter_width, n] * filters[:, :, k])
conditional_block
test_conv_layer.py
import pytest import numpy as np from collections import OrderedDict from contextlib import closing import neon as ng import neon.transformers as ngt from neon.testing import executor from neon.frontend.common import utils from neon.op_graph.axes import IncompatibleAxesError from neon.frontend import Convolution, Decon...
@pytest.mark.xfail(reason='1d conv not supported') def test_axis_preservation(conv1d_placeholder, output_size): """ Test that axes into a conv are the same as axes out""" conv_layer = Convolution((3, output_size), lambda x: 1) output = conv_layer(conv1d_placeholder) assert output.axes == conv1d_place...
""" Test that 'same' always results in out_size = np.ceil(in_size / stride) """ conv_layer = Convolution((3, output_size), lambda x: 1, strides=stride, padding="same") output = conv_layer(conv1d_placeholder) output_width = output.axes.find_by_name("W")[0].length assert output_width == np.ceil(width / fl...
identifier_body
test_conv_layer.py
import pytest import numpy as np from collections import OrderedDict from contextlib import closing import neon as ng import neon.transformers as ngt from neon.testing import executor from neon.frontend.common import utils from neon.op_graph.axes import IncompatibleAxesError from neon.frontend import Convolution, Decon...
(dilation): """Test that the dilated convolution layer output matches expected. This test compares the maximum output value to an expected max output value. The expected value is computed based on the dilation parameter. The test also checks that the output size matches the expected size based on the di...
test_dilated_conv
identifier_name
test_conv_layer.py
import pytest import numpy as np from collections import OrderedDict from contextlib import closing import neon as ng import neon.transformers as ngt from neon.testing import executor from neon.frontend.common import utils from neon.op_graph.axes import IncompatibleAxesError from neon.frontend import Convolution, Decon...
N_filters = 1 image_channels = 3 model = Sequential([Convolution((conv_size, conv_size, N_filters), filter_init=ConstantInit(val=init_val), padding=pad, dilation=dilation)]) X = np.ones(shape=(batch_size, 3, image_size, image_size))...
conv_size = 3 pad = 3
random_line_split
controller.go
package controller import ( "context" "fmt" "math" "time" "github.com/practo/klog/v2" "github.com/prometheus/client_golang/prometheus" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/intstr" utilruntime "k8s.io/api...
).Set(float64(currentWorkers)) workersDesired.WithLabelValues( name, namespace, queueName, ).Set(float64(desiredWorkers)) workersAvailable.WithLabelValues( name, namespace, queueName, ).Set(float64(availableWorkers)) lastScaleTime := workerPodAutoScaler.Status.LastScaleTime.DeepCopy() op := GetScal...
).Set(float64(idleWorkers)) workersCurrent.WithLabelValues( name, namespace, queueName,
random_line_split
controller.go
package controller import ( "context" "fmt" "math" "time" "github.com/practo/klog/v2" "github.com/prometheus/client_golang/prometheus" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/intstr" utilruntime "k8s.io/api...
else if err != nil { return err } currentWorkers = *deployment.Spec.Replicas availableWorkers = deployment.Status.AvailableReplicas } else if replicaSetName != "" { // Get the ReplicaSet with the name specified in WorkerPodAutoScaler.spec replicaSet, err := c.replicaSetLister.ReplicaSets(workerPodAutoSca...
{ return fmt.Errorf("deployment %s not found in namespace %s", deploymentName, workerPodAutoScaler.Namespace) }
conditional_block
controller.go
package controller import ( "context" "fmt" "math" "time" "github.com/practo/klog/v2" "github.com/prometheus/client_golang/prometheus" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/intstr" utilruntime "k8s.io/api...
(ctx context.Context) bool { obj, shutdown := c.workqueue.Get() if shutdown { return false } // We wrap this block in a func so we can defer c.workqueue.Done. err := func(obj interface{}) error { // We call Done here so the workqueue knows we have finished // processing this item. We also must remember to ...
processNextWorkItem
identifier_name
controller.go
package controller import ( "context" "fmt" "math" "time" "github.com/practo/klog/v2" "github.com/prometheus/client_golang/prometheus" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/intstr" utilruntime "k8s.io/api...
// Run will set up the event handlers for types we are interested in, as well // as syncing informer caches and starting workers. It will block until stopCh // is closed, at which point it will shutdown the workqueue and wait for // workers to finish processing their current work items. func (c *Controller) Run(threa...
{ // Create event broadcaster // Add sample-controller types to the default Kubernetes Scheme so Events can be // logged for sample-controller types. utilruntime.Must(samplescheme.AddToScheme(scheme.Scheme)) klog.V(4).Info("Creating event broadcaster") eventBroadcaster := record.NewBroadcaster() eventBroadcaste...
identifier_body
generate.py
import pickle import numpy as np import copy import json import argparse from model import get_language_model folder = "../YouTube2Text/youtubeclips-dataset/" fname = folder + "test.txt" with open(fname) as f: content = f.readlines() test = [x.strip() for x in content] # no_clean_captions = set(['vid1690', 'vi...
return prev_words_input def beam_search(captioning_model, prev_words_input, other_inputs, k): top_k_predictions = [copy.deepcopy(prev_words_input) for _ in range(k)] top_k_score = np.array([[0.0]*top_k_predictions[0].shape[0]]*k) # First Iteration predictions = captioning_model.predict(oth...
predictions = captioning_model.predict(other_inputs + [prev_words_input]) for idx,video in enumerate(test): prev_words_input[idx][itr+1] = np.argmax(predictions[idx])
conditional_block
generate.py
import pickle import numpy as np import copy import json import argparse from model import get_language_model folder = "../YouTube2Text/youtubeclips-dataset/" fname = folder + "test.txt" with open(fname) as f: content = f.readlines() test = [x.strip() for x in content] # no_clean_captions = set(['vid1690', 'vi...
TAG_TYPE = results.tag_type THRESHOLD = results.tag_threshold LSTM_SIZE = results.lstm_size # Load single frame feature vectors and attribute/entity/action vectors if TAG_TYPE == 'predicted': video_entity_vectors = pickle.load(open("../advanced_tag_models/entity_simple_predicted_tags.pickle", "rb")) video_ac...
random_line_split
generate.py
import pickle import numpy as np import copy import json import argparse from model import get_language_model folder = "../YouTube2Text/youtubeclips-dataset/" fname = folder + "test.txt" with open(fname) as f: content = f.readlines() test = [x.strip() for x in content] # no_clean_captions = set(['vid1690', 'vi...
(captioning_model, prev_words_input, other_inputs): for itr in range(NUM_PREV_WORDS-1): predictions = captioning_model.predict(other_inputs + [prev_words_input]) for idx,video in enumerate(test): prev_words_input[idx][itr+1] = np.argmax(predictions[idx]) return prev_words_input ...
greedy_search
identifier_name
generate.py
import pickle import numpy as np import copy import json import argparse from model import get_language_model folder = "../YouTube2Text/youtubeclips-dataset/" fname = folder + "test.txt" with open(fname) as f: content = f.readlines() test = [x.strip() for x in content] # no_clean_captions = set(['vid1690', 'vi...
results_folder = "./" # # Load All Captions fname = folder + "cleaned_descriptions.csv" with open(fname) as f: content = f.readlines() all_captions = [(x.strip().split(",")[0],x.strip().split(",")[1]) for x in content] # # Write correct caption file correct_captions = open(results_folder + "annotations/correct...
preds = np.asarray(preds).astype('float64') preds = np.log(preds) / temperature exp_preds = np.exp(preds) preds = exp_preds / np.sum(exp_preds) probas = np.random.multinomial(1, preds, 1) return np.argmax(probas)
identifier_body
jiayuan.py
# -*- coding:utf-8 -*- ''' Created on 2018年2月28日 @author: ning.lin ''' ''' 大图地址class或id有big字样 的 <div class="pho_big" id="phoBig" style="height: 640px;"> <div class="big_pic fn-clear" id="bigImg"> 小图地址 <div class="pho_small_box fn-clear mt25 " id="phoSmallPic"> ''' import json import time from scrapy ...
item['nation_mate'] = mate_dict['民族'] item['education_mate'] = mate_dict['学历'] item['image_mate'] = mate_dict['相册'] item['marital_status'] = mate_dict['婚姻状况'] item['address_mate'] = mate_dict['居住地'] item['sincerity_mate'] = mate_dict['诚信']#诚信 print("择偶要求",ma...
mate_dict = parse(i.text) item['person_id_mate'] = person_id item['age_mate'] = mate_dict['年龄'] item['height_mate'] = mate_dict['身高']
random_line_split
jiayuan.py
# -*- coding:utf-8 -*- ''' Created on 2018年2月28日 @author: ning.lin ''' ''' 大图地址class或id有big字样 的 <div class="pho_big" id="phoBig" style="height: 640px;"> <div class="big_pic fn-clear" id="bigImg"> 小图地址 <div class="pho_small_box fn-clear mt25 " id="phoSmallPic"> ''' import json import time from scrapy ...
onnectionPool(host='127.0.0.1',port=6379,db=0,decode_responses=True) #427条记录 r = redis.StrictRedis(connection_pool=pool) name = "jiayuan_main" redis_key = 'jiayuan_main:start_urls' url_base = 'http://search.jiayuan.com/v2/index.php?key=&sex=f&stc=&sn=default&sv=1&p=%s&pt=163649&ft=off&f=select&mt...
pool=redis.C
identifier_name
jiayuan.py
# -*- coding:utf-8 -*- ''' Created on 2018年2月28日 @author: ning.lin ''' ''' 大图地址class或id有big字样 的 <div class="pho_big" id="phoBig" style="height: 640px;"> <div class="big_pic fn-clear" id="bigImg"> 小图地址 <div class="pho_small_box fn-clear mt25 " id="phoSmallPic"> ''' import json import time from scrapy ...
127.0.0.1',port=6379,db=0,decode_responses=True) #427条记录 r = redis.StrictRedis(connection_pool=pool) name = "jiayuan_main" redis_key = 'jiayuan_main:start_urls' url_base = 'http://search.jiayuan.com/v2/index.php?key=&sex=f&stc=&sn=default&sv=1&p=%s&pt=163649&ft=off&f=select&mt=d' redis_key =...
identifier_body
jiayuan.py
# -*- coding:utf-8 -*- ''' Created on 2018年2月28日 @author: ning.lin ''' ''' 大图地址class或id有big字样 的 <div class="pho_big" id="phoBig" style="height: 640px;"> <div class="big_pic fn-clear" id="bigImg"> 小图地址 <div class="pho_small_box fn-clear mt25 " id="phoSmallPic"> ''' import json import time from scrapy ...
<class 'str'> 年 龄: 26-29岁之间 身 高: 169-185厘米 民 族: 汉族 学 历: 不限 相 册: ...
=url,cookies=self.cookies,callback=self.get_details)#解析人员详细信息 # yield item def get_details(self,response): '''
conditional_block
wxkfmanager.go
package wxapi import ( "encoding/xml" "fmt" "github.com/gin-gonic/gin" "github.com/mitchellh/mapstructure" "github.com/robfig/cron" "io/ioutil" "net/http" "net/url" ) type WXKfManager interface { //小程序或者公众号授权给第三方平台 HandleCompentAuthEventPush(context * gin.Context,responsehandler ...func(appmsg APPAuthMsg...
Decrptmsg APPAuthMsg, safe bool) { if CheckSign { if len(responsehandler)>0 { responsehandler[0](Decrptmsg) } } }) context.String(http.StatusOK,"success") } //代公众号实现网页授权 /****************代公众号实现业务*******************/ //1.代公众号调用接口 //获取用户信息 func (wx *WXKFManager)GetUserInfo( authorizer...
l, Orignmsg ReqMsg,
identifier_name
wxkfmanager.go
package wxapi import ( "encoding/xml" "fmt" "github.com/gin-gonic/gin" "github.com/mitchellh/mapstructure" "github.com/robfig/cron" "io/ioutil" "net/http" "net/url" ) type WXKfManager interface { //小程序或者公众号授权给第三方平台 HandleCompentAuthEventPush(context * gin.Context,responsehandler ...func(appmsg APPAuthMsg...
ode(resp,&result) fmt.Println("代公众号获取usertoken",resp,result,appid,url) if len(handler)>0 { handler[0](result) } } //代公众号获取网页登录用户信息 func (wx *WXKFManager) getAppAuthuserInfo(auth AuthResp,handler ...func(authuser JsonResponse)) { url :="https://api.weixin.qq.com/sns/userinfo?access_token=" url =url +auth.Access...
AuthResp mapstructure.Dec
conditional_block
wxkfmanager.go
package wxapi import ( "encoding/xml" "fmt" "github.com/gin-gonic/gin" "github.com/mitchellh/mapstructure" "github.com/robfig/cron" "io/ioutil" "net/http" "net/url" ) type WXKfManager interface { //小程序或者公众号授权给第三方平台 HandleCompentAuthEventPush(context * gin.Context,responsehandler ...func(appmsg APPAuthMsg...
identifier_body
wxkfmanager.go
package wxapi import ( "encoding/xml" "fmt" "github.com/gin-gonic/gin" "github.com/mitchellh/mapstructure" "github.com/robfig/cron" "io/ioutil" "net/http" "net/url" ) type WXKfManager interface { //小程序或者公众号授权给第三方平台 HandleCompentAuthEventPush(context * gin.Context,responsehandler ...func(appmsg APPAuthMsg...
//获取授权方选项设置信息 func (wx *WXKFManager) GetCompentAuthOptionInfo(authorizer_appid,option_name string,responsehandler ...func(APPOptionResp)) { url :="https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token=" url =url +wx.Component_access_token POSTJson(url,gin.H{"component_appid": wx.Comp...
random_line_split
technique.rs
use serde::{Deserialize, Serialize}; use serde_json::Value; use crate::error::*; use std::fs; use std::path::Path; use regex::Regex; use lazy_static::lazy_static; use toml; use nom::combinator::*; use nom::sequence::*; use nom::bytes::complete::*; use nom::character::complete::*; use nom::branch::alt; use nom::multi::m...
(json_file: &Path, rl_file: &Path) -> Result<()> { let config_data = fs::read_to_string("data/config.toml").expect("Cannot read config.toml file"); let config: toml::Value = toml::from_str(&config_data).expect("Invalig config.toml file"); // we use if let for error conversion // we don't use match for ...
translate_file
identifier_name
technique.rs
use serde::{Deserialize, Serialize}; use serde_json::Value; use crate::error::*; use std::fs; use std::path::Path; use regex::Regex; use lazy_static::lazy_static; use toml; use nom::combinator::*; use nom::sequence::*; use nom::bytes::complete::*; use nom::character::complete::*; use nom::branch::alt; use nom::multi::m...
fn translate_arg(config: &toml::Value, arg: &str) -> Result<String> { let var = match parse_cfstring(arg) { Err(_) => return Err(Error::User(format!("Invalid variable syntax in '{}'", arg))), Ok((_,o)) => o }; map_strings_results(var.iter(), |x| Ok(format!("\"{}\"",x.to_string()?)), ",") }...
// empty string value(vec![CFStringElt::Static("".into())], not(anychar)), )) )(i) }
random_line_split
html5_player.js
isFullScreen = false; isButtonFullscreen = false; $(document).ready(function() { //INITIALIZE var video = $('#myVideo'); var container = $('.cont'); var test = $(".cont,.myVideo"); var loadmetadata = true; var _pause = false; //showing pause icon by before video load $('.btnPlay').addClass('paused'); at...
function get_current_video_source(object_id) { var video = document.getElementById(object_id); var src = video.currentSrc; return src; } /******CAUTION*****\ DO NOT REMOVE THIS COMMENTED CODE /***website logo***\ /*$('.cont').append('<div><img id="web" src=data:image/png;base64,'+ web +'> </div>'); $('#...
{ //before everything get started video.on('loadedmetadata', function() { video[0].currentTime = start_time; video[0].play(); //set video properties $('.loading').fadeOut(500); $('.init').hide(); }); }
identifier_body
html5_player.js
isFullScreen = false; isButtonFullscreen = false; $(document).ready(function() { //INITIALIZE var video = $('#myVideo'); var container = $('.cont'); var test = $(".cont,.myVideo"); var loadmetadata = true; var _pause = false; //showing pause icon by before video load $('.btnPlay').addClass('paused'); at...
}; $( "#replay_v" ).click(function() { video[0].play(); $('#opacity').hide(); $('#related_1').hide(); $('.control').show(); $('.caption').show(); $('#web').show(); //showing pause icon by before video load $('.btnPlay').addClass('paused'); }); $( "#cancel_v" ).click(fu...
{ $('.init').show(); $('.btnPlay').removeClass('paused'); video[0].pause(); _pause = true; }
conditional_block
html5_player.js
isFullScreen = false; isButtonFullscreen = false; $(document).ready(function() { //INITIALIZE var video = $('#myVideo'); var container = $('.cont'); var test = $(".cont,.myVideo"); var loadmetadata = true; var _pause = false; //showing pause icon by before video load $('.btnPlay').addClass('paused'); at...
() { $(document).on("click", function () { $("#rightcmenu").hide(500); // To hide the context menu $('.cont').off("click"); }); } $(".clip").click(function(event) { window.open(homepath, '_blank'); }); $(".about").click(function(event) { window.open(homepath, ...
startFocusOut
identifier_name
html5_player.js
isFullScreen = false; isButtonFullscreen = false; $(document).ready(function() { //INITIALIZE var video = $('#myVideo'); var container = $('.cont'); var test = $(".cont,.myVideo"); var loadmetadata = true; var _pause = false; //showing pause icon by before video load $('.btnPlay').addClass('paused'); at...
video.attr('src',jsonData["240"]); $('#li_240').addClass('selected_player'); } else $('#li_360').addClass('selected_player'); $.each(jsonData, function (key, data) { $('#li_' + key).on('mouseenter', function(){ $(this).css({'background-color':'#000'}); }); $('#li_' + key)....
if(!jsonData["360"]) {
random_line_split
SignalDef.rs
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless ...
} return 64 } pub fn MakeSignalSet(sigs: &[Signal]) -> Self { let mut res = Self::default(); for sig in sigs { res.Add(*sig) } return res; } pub fn ForEachSignal(&self, mut f: impl FnMut(Signal)) { for i in 0..64 { if s...
{ return idx }
conditional_block
SignalDef.rs
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless ...
(sig: Signal) -> Self { return SignalSet(1 << sig.Index()) } pub fn Add(&mut self, sig: Signal) { self.0 |= 1 << sig.Index() } pub fn Remove(&mut self, sig: Signal) { self.0 &= !(1 << sig.0) } pub fn TailingZero(&self) -> usize { for i in 0..64 { le...
New
identifier_name
SignalDef.rs
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless ...
pub rsp: u64, pub ss: u64, /* top of stack page */ } impl PtRegs { pub fn Set(&mut self, ctx: &SigContext) { self.r15 = ctx.r15; self.r14 = ctx.r14; self.r13 = ctx.r13; self.r12 = ctx.r12; self.rbp = ctx.rbp; self.rbx = ctx.rbx; self.r11 = ctx.r11...
pub cs: u64, pub eflags: u64,
random_line_split
SignalDef.rs
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless ...
pub const SIGNAL_SET_SIZE: usize = 8; pub fn UnblockableSignals() -> SignalSet { return SignalSet::MakeSignalSet(&[Signal(Signal::SIGKILL), Signal(Signal::SIGSTOP)]); } pub fn CopyInSigSet(task: &Task, sigSetAddr: u64, size: usize) -> Result<SignalSet> { if size != SIGNAL_SET_SIZE { return Err(Error...
{ let mask : SigMask = task.CopyInObj(addr)?; return Ok((mask.addr, mask.len)) }
identifier_body
api-put-object-multipart.go
/* * MinIO Go Library for Amazon S3 Compatible Cloud Storage * Copyright 2015-2017 MinIO, 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/L...
// Initiate a new multipart upload. uploadID, err := c.newUploadID(ctx, bucketName, objectName, opts) if err != nil { return UploadInfo{}, err } delete(opts.UserMetadata, "X-Amz-Checksum-Algorithm") defer func() { if err != nil { c.abortMultipartUpload(ctx, bucketName, objectName, uploadID) } }() /...
{ if opts.UserMetadata == nil { opts.UserMetadata = make(map[string]string, 1) } opts.UserMetadata["X-Amz-Checksum-Algorithm"] = "CRC32C" }
conditional_block
api-put-object-multipart.go
/* * MinIO Go Library for Amazon S3 Compatible Cloud Storage * Copyright 2015-2017 MinIO, 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/L...
(ctx context.Context, bucketName, objectName string, reader io.Reader, opts PutObjectOptions) (info UploadInfo, err error) { // Input validation. if err = s3utils.CheckValidBucketName(bucketName); err != nil { return UploadInfo{}, err } if err = s3utils.CheckValidObjectName(objectName); err != nil { return Uplo...
putObjectMultipartNoStream
identifier_name
api-put-object-multipart.go
/* * MinIO Go Library for Amazon S3 Compatible Cloud Storage * Copyright 2015-2017 MinIO, 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/L...
if resp != nil { if resp.StatusCode != http.StatusOK { return UploadInfo{}, httpRespToErrorResponse(resp, bucketName, objectName) } } // Read resp.Body into a []bytes to parse for Error response inside the body var b []byte b, err = io.ReadAll(resp.Body) if err != nil { return UploadInfo{}, err } // D...
defer closeResponse(resp) if err != nil { return UploadInfo{}, err }
random_line_split
api-put-object-multipart.go
/* * MinIO Go Library for Amazon S3 Compatible Cloud Storage * Copyright 2015-2017 MinIO, 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/L...
func (c *Client) putObjectMultipartNoStream(ctx context.Context, bucketName, objectName string, reader io.Reader, opts PutObjectOptions) (info UploadInfo, err error) { // Input validation. if err = s3utils.CheckValidBucketName(bucketName); err != nil { return UploadInfo{}, err } if err = s3utils.CheckValidObjec...
{ info, err = c.putObjectMultipartNoStream(ctx, bucketName, objectName, reader, opts) if err != nil { errResp := ToErrorResponse(err) // Verify if multipart functionality is not available, if not // fall back to single PutObject operation. if errResp.Code == "AccessDenied" && strings.Contains(errResp.Message,...
identifier_body
manager.go
// Copyright 2018 The Operator-SDK Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or ...
return nil }) } func createPatch(existing runtime.Object, expected *resource.Info) ([]byte, apitypes.PatchType, error) { existingJSON, err := json.Marshal(existing) if err != nil { return nil, apitypes.StrategicMergePatchType, err } expectedJSON, err := json.Marshal(expected.Object) if err != nil { return...
{ return fmt.Errorf("patch error: %w", err) }
conditional_block
manager.go
// Copyright 2018 The Operator-SDK Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or ...
func (m manager) getDeployedRelease() (*rpb.Release, error) { deployedRelease, err := m.storageBackend.Deployed(m.releaseName) if err != nil { if strings.Contains(err.Error(), "has no deployed releases") { return nil, driver.ErrReleaseNotFound } return nil, err } return deployedRelease, nil } func (m ma...
{ return err != nil && strings.Contains(err.Error(), "not found") }
identifier_body
manager.go
// Copyright 2018 The Operator-SDK Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or ...
() string { return m.releaseName } func (m manager) IsInstalled() bool { return m.isInstalled } func (m manager) IsUpgradeRequired() bool { return m.isUpgradeRequired } // Sync ensures the Helm storage backend is in sync with the status of the // custom resource. func (m *manager) Sync(ctx context.Context) error ...
ReleaseName
identifier_name
manager.go
// Copyright 2018 The Operator-SDK Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or ...
// the response even when it doesn't record the release in its release // store (e.g. when there is an error rendering the release manifest). // In that case the rollback will fail with a not found error because // there was nothing to rollback. // // Only log a message about a rollback failure if the...
uninstall := action.NewUninstall(m.actionConfig) _, uninstallErr := uninstall.Run(m.releaseName) // In certain cases, InstallRelease will return a partial release in
random_line_split
player.go
package proxy import ( "context" "crypto/rand" "encoding/binary" "encoding/hex" "encoding/json" "errors" "go.minekube.com/common/minecraft/component" "go.minekube.com/common/minecraft/component/codec/legacy" "go.minekube.com/gate/pkg/command"
"go.minekube.com/gate/pkg/edition/java/proto/packet/title" "go.minekube.com/gate/pkg/edition/java/proto/util" "go.minekube.com/gate/pkg/edition/java/proto/version" "go.minekube.com/gate/pkg/edition/java/proxy/message" "go.minekube.com/gate/pkg/edition/java/proxy/player" "go.minekube.com/gate/pkg/gate/proto" "go....
"go.minekube.com/gate/pkg/edition/java/forge" "go.minekube.com/gate/pkg/edition/java/modinfo" "go.minekube.com/gate/pkg/edition/java/profile" "go.minekube.com/gate/pkg/edition/java/proto/packet" "go.minekube.com/gate/pkg/edition/java/proto/packet/plugin"
random_line_split
player.go
package proxy import ( "context" "crypto/rand" "encoding/binary" "encoding/hex" "encoding/json" "errors" "go.minekube.com/common/minecraft/component" "go.minekube.com/common/minecraft/component/codec/legacy" "go.minekube.com/gate/pkg/command" "go.minekube.com/gate/pkg/edition/java/forge" "go.minekube.com/ga...
() bool { return p.onlineMode } func (p *connectedPlayer) GameProfile() profile.GameProfile { return *p.profile } var ( ErrNoBackendConnection = errors.New("player has no backend server connection yet") ErrTooLongChatMessage = errors.New("server bound chat message can not exceed 256 characters") ) func (p *conn...
OnlineMode
identifier_name
player.go
package proxy import ( "context" "crypto/rand" "encoding/binary" "encoding/hex" "encoding/json" "errors" "go.minekube.com/common/minecraft/component" "go.minekube.com/common/minecraft/component/codec/legacy" "go.minekube.com/gate/pkg/command" "go.minekube.com/gate/pkg/edition/java/forge" "go.minekube.com/ga...
ctedPlayer) connectedServer() *serverConnection { p.mu.RLock() defer p.mu.RUnlock() return p.connectedServer_ } func (p *connectedPlayer) Username() string { return p.profile.Name } func (p *connectedPlayer) ID() uuid.UUID { return p.profile.ID } func (p *connectedPlayer) Disconnect(reason component.Component) ...
nnectedServer(); cs != nil { return cs } // We must return an explicit nil, not a (*serverConnection)(nil). return nil } func (p *conne
identifier_body
player.go
package proxy import ( "context" "crypto/rand" "encoding/binary" "encoding/hex" "encoding/json" "errors" "go.minekube.com/common/minecraft/component" "go.minekube.com/common/minecraft/component/codec/legacy" "go.minekube.com/gate/pkg/command" "go.minekube.com/gate/pkg/edition/java/forge" "go.minekube.com/ga...
i if s := p.proxy.Server(toTry); s != nil { return s } } return nil } // player's connection is closed at this point, // now need to disconnect backend server connection, if any. func (p *connectedPlayer) teardown() { p.mu.RLock() connInFlight := p.connInFlight connectedServer := p.connectedServer_ p.mu....
} p.tryIndex =
conditional_block
dream.go
package main import ( "bytes" "fmt" "os" "os/exec" "strings" "time" "github.com/TableMountain/goydl" "github.com/gin-gonic/gin" "github.com/sirupsen/logrus" "github.com/skratchdot/open-golang/open" ) var isJob bool var basePath string // Truncate todo func
(t time.Time) time.Time { return t.Truncate(24 * time.Hour) } func now() string { return time.Now().Format(time.Kitchen) } // Dream is exported so it can be an api, haha what fun. Games perhaps? Stock trading? Some real time video effect? func Dream(c *gin.Context) { start := time.Now() defer func() { elapsed :...
Truncate
identifier_name
dream.go
package main import ( "bytes" "fmt" "os" "os/exec" "strings" "time" "github.com/TableMountain/goydl" "github.com/gin-gonic/gin" "github.com/sirupsen/logrus" "github.com/skratchdot/open-golang/open" ) var isJob bool var basePath string // Truncate todo func Truncate(t time.Time) time.Time { return t.Trunc...
} else { // if no youtube, then get file from form upload file, err := c.FormFile("file") if err != nil { Log.Error("failed to get file", err) //although this might not be an error as we support ytdl now return } name = strings.Split(file.Filename, ".")[0] fullName = file.Filename ext = strings.Spli...
} }
random_line_split
dream.go
package main import ( "bytes" "fmt" "os" "os/exec" "strings" "time" "github.com/TableMountain/goydl" "github.com/gin-gonic/gin" "github.com/sirupsen/logrus" "github.com/skratchdot/open-golang/open" ) var isJob bool var basePath string // Truncate todo func Truncate(t time.Time) time.Time
func now() string { return time.Now().Format(time.Kitchen) } // Dream is exported so it can be an api, haha what fun. Games perhaps? Stock trading? Some real time video effect? func Dream(c *gin.Context) { start := time.Now() defer func() { elapsed := fmt.Sprintf("%s %s", now(), time.Since(start)) elapsed = s...
{ return t.Truncate(24 * time.Hour) }
identifier_body
dream.go
package main import ( "bytes" "fmt" "os" "os/exec" "strings" "time" "github.com/TableMountain/goydl" "github.com/gin-gonic/gin" "github.com/sirupsen/logrus" "github.com/skratchdot/open-golang/open" ) var isJob bool var basePath string // Truncate todo func Truncate(t time.Time) time.Time { return t.Trunc...
break //we got our file, now we move on, we don't need to keep listening for URL } } } else { // if no youtube, then get file from form upload file, err := c.FormFile("file") if err != nil { Log.Error("failed to get file", err) //although this might not be an error as we support ytdl now return ...
{ if err = os.Mkdir(framesDirPath, 0777); err != nil { Log.Error("failed to make a new job dir w/ error: ", err) } Log.Info("frames folder for new job was created at ", framesDirPath) }
conditional_block
buffer.go
package gui import ( "fmt" "io/ioutil" "log" "os" "path" "regexp" "runtime" "strings" "time" "unicode" "github.com/felixangell/go-rope" "github.com/felixangell/phi-editor/cfg" "github.com/felixangell/strife" "github.com/veandco/go-sdl2/sdl" ) var ( timer int64 = 0 reset_timer int64 = 0 shoul...
urrLine := b.contents[b.curs.y] prevLine := b.contents[b.curs.y-1] b.contents[b.curs.y-1] = currLine b.contents[b.curs.y] = prevLine b.moveUp() } return true } func (b *Buffer) swapLineDown() bool { if b.curs.y < len(b.contents) { currLine := b.contents[b.curs.y] nextLine := b.contents[b.curs.y+1] b.c...
> 0 { c
identifier_name
buffer.go
package gui import ( "fmt" "io/ioutil" "log" "os" "path" "regexp" "runtime" "strings" "time" "unicode" "github.com/felixangell/go-rope" "github.com/felixangell/phi-editor/cfg" "github.com/felixangell/strife" "github.com/veandco/go-sdl2/sdl" ) var ( timer int64 = 0 reset_timer int64 = 0 shoul...
) swapLineDown() bool { if b.curs.y < len(b.contents) { currLine := b.contents[b.curs.y] nextLine := b.contents[b.curs.y+1] b.contents[b.curs.y+1] = currLine b.contents[b.curs.y] = nextLine b.moveDown() } return true } func (b *Buffer) scrollUp() { if b.cam.y > 0 { // TODO move the cursor down 45 lines...
s.y] prevLine := b.contents[b.curs.y-1] b.contents[b.curs.y-1] = currLine b.contents[b.curs.y] = prevLine b.moveUp() } return true } func (b *Buffer
conditional_block
buffer.go
package gui import ( "fmt" "io/ioutil" "log" "os" "path" "regexp" "runtime" "strings" "time" "unicode" "github.com/felixangell/go-rope" "github.com/felixangell/phi-editor/cfg" "github.com/felixangell/strife" "github.com/veandco/go-sdl2/sdl" ) var ( timer int64 = 0 reset_timer int64 = 0 shoul...
// my UK macbook key layout. var shiftAlternative = map[rune]rune{ '1': '!', '2': '@', '3': '£', '4': '$', '5': '%', '6': '^', '7': '&', '8': '*', '9': '(', '0': ')', '-': '_', '=': '+', '`': '~', '/': '?', '.': '>', ',': '<', '[': '{', ']': '}', ';': ':', '\'': '"', '\\': '|', ...
} // TODO handle EVERYTHING but for now im handling
random_line_split
buffer.go
package gui import ( "fmt" "io/ioutil" "log" "os" "path" "regexp" "runtime" "strings" "time" "unicode" "github.com/felixangell/go-rope" "github.com/felixangell/phi-editor/cfg" "github.com/felixangell/strife" "github.com/veandco/go-sdl2/sdl" ) var ( timer int64 = 0 reset_timer int64 = 0 shoul...
identifier_body
lib.rs
// Copyright 2021 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. //! This crate implements IEEE Std 802.11-2016 MLME as a library for hardware that supports //! SoftMAC. This is distinct from FullMAC, which is implemente...
const MINSTREL_UPDATE_INTERVAL: std::time::Duration = std::time::Duration::from_millis(100); // Remedy for fxbug.dev/8165 (fxbug.dev/33151) // See |DATA_FRAME_INTERVAL_NANOS| // in //src/connectivity/wlan/testing/hw-sim/test/rate_selection/src/lib.rs // Ensure at least one probe frame (generated every 16 data frames)...
{ mac_sublayer.device.tx_status_report_supported && !mac_sublayer.rate_selection_offload.supported }
identifier_body
lib.rs
// Copyright 2021 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. //! This crate implements IEEE Std 802.11-2016 MLME as a library for hardware that supports //! SoftMAC. This is distinct from FullMAC, which is implemente...
(&mut self, _bytes: &[u8]) -> Result<(), Error> { unimplemented!() } fn handle_scan_complete(&mut self, _status: zx::Status, _scan_id: u64) { unimplemented!() } fn handle_timeout(&mut self, _event_id: common::timer::EventId, _event: Self::TimerEvent) { ...
handle_eth_frame_tx
identifier_name
lib.rs
// Copyright 2021 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. //! This crate implements IEEE Std 802.11-2016 MLME as a library for hardware that supports //! SoftMAC. This is distinct from FullMAC, which is implemente...
}; let channel = zx::Channel::from(mlme_protocol_handle_via_iface_creation); let server = fidl::endpoints::ServerEnd::<fidl_mlme::MlmeMarker>::new(channel); let (mlme_request_stream, control_handle) = match server.into_stream_and_control_handle() { Ok(res) => res, ...
{ // Failure to unwrap indicates a critical failure in the driver init thread. startup_sender.send(Err(anyhow!("device.start failed: {}", e))).unwrap(); return; }
conditional_block
lib.rs
// Copyright 2021 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. //! This crate implements IEEE Std 802.11-2016 MLME as a library for hardware that supports //! SoftMAC. This is distinct from FullMAC, which is implemente...
startup_receiver .try_recv() .unwrap() .expect("Test MLME setup stalled.") .expect("Test MLME setup failed."); MlmeHandle { driver_event_sink, internal: Some(MlmeHandleInternal::Fake { executor, future }), } } asyn...
)); let _ = executor.run_until_stalled(&mut future.as_mut());
random_line_split
io_export_arm.py
# Armory Mesh Exporter # http://armory3d.org/ # # Based on Open Game Engine Exchange # http://opengex.org/ # Export plugin for Blender by Eric Lengyel # Copyright 2015, Terathon Software LLC # # This software is licensed under the Creative Commons # Attribution-ShareAlike 3.0 Unported License: # http://creati...
(obj, fp): if len(obj) <= 15: fp.write(struct.pack("B", 0x80 | len(obj))) elif len(obj) <= 2**16 - 1: fp.write(b"\xde" + struct.pack("<H", len(obj))) elif len(obj) <= 2**32 - 1: fp.write(b"\xdf" + struct.pack("<I", len(obj))) else: raise Exception("huge array") for k...
_pack_map
identifier_name
io_export_arm.py
# Armory Mesh Exporter # http://armory3d.org/ # # Based on Open Game Engine Exchange # http://opengex.org/ # Export plugin for Blender by Eric Lengyel # Copyright 2015, Terathon Software LLC # # This software is licensed under the Creative Commons # Attribution-ShareAlike 3.0 Unported License: # http://creati...
else: raise Exception("unsupported type: %s" % str(type(obj))) def packb(obj): fp = io.BytesIO() pack(obj, fp) return fp.getvalue()
_pack_map(obj, fp)
conditional_block
io_export_arm.py
# Armory Mesh Exporter # http://armory3d.org/ # # Based on Open Game Engine Exchange # http://opengex.org/ # Export plugin for Blender by Eric Lengyel # Copyright 2015, Terathon Software LLC # # This software is licensed under the Creative Commons # Attribution-ShareAlike 3.0 Unported License: # http://creati...
def _pack_string(obj, fp): obj = obj.encode('utf-8') if len(obj) <= 31: fp.write(struct.pack("B", 0xa0 | len(obj)) + obj) elif len(obj) <= 2**8 - 1: fp.write(b"\xd9" + struct.pack("B", len(obj)) + obj) elif len(obj) <= 2**16 - 1: fp.write(b"\xda" + struct.pack("<H", len(obj)) +...
fp.write(b"\xca" + struct.pack("<f", obj))
identifier_body