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 |
|---|---|---|---|---|
api.go | := ctx.Args().Get(0)
action := ctx.Args().Get(1)
return c.client.ChangeAPIStatus(id, wso2am.APIAction(action))
},
}
}
func (c *CLI) apiDelete() cli.Command {
return cli.Command{
Name: "delete",
Aliases: []string{"del", "rm"},
Usage: "Delete the API",
Flags: []cli.Flag{
cli.BoolFlag{
Name... | random_line_split | ||
api.go | },
},
Action: func(ctx *cli.Context) error {
var query = ctx.String("query")
return list(func(entryc chan<- interface{}, errc chan<- error, done <-chan struct{}) {
c.client.SearchAPIsRaw(query, entryc, errc, done)
}, func(table *TableFormatter) {
table.Header("ID", "Name", "Version", "Description",... | () cli.Command {
return cli.Command{
Name: "thumbnail",
Usage: "Download the thumbnail",
Action: func(ctx *cli.Context) error {
if ctx.NArg() != 1 {
return errors.New("ID is required")
}
id := ctx.Args().Get(0)
return c.client.Thumbnail(id, os.Stdout)
},
}
}
func (c *CLI) apiUploadThumbnail(... | apiThumbnail | identifier_name |
main.rs | _selected = Some(ts);
}
Err(e) => {
error!("{}", Report::from_error(e));
if fail_first {
let _ = scu.abort();
std::process::exit(-2);
}
}
}
}
let progress_bar;
if !verbose {
... | check_presentation_contexts | identifier_name | |
main.rs | exit(-2);
});
}
fn run() -> Result<(), Error> {
let App {
addr,
files,
verbose,
message_id,
calling_ae_title,
called_ae_title,
max_pdu_length,
fail_first,
} = App::parse();
tracing::subscriber::set_global_default(
tracing_subscrib... | {
error!("Unexpected SCP response: {:?}", pdu);
let _ = scu.abort();
std::process::exit(-2);
} | conditional_block | |
main.rs | ,
/// Storage SOP Class UID
sop_class_uid: String,
/// Storage SOP Instance UID
sop_instance_uid: String,
/// File Transfer Syntax
file_transfer_syntax: String,
/// Transfer Syntax selected
ts_selected: Option<String>,
/// Presentation Context selected
pc_selected: Option<dicom_u... | let nbytes = cmd_data.len() + object_data.len();
if verbose {
info!(
"Sending file {} (~ {} kB), uid={}, sop={}, ts={}",
file.file.display(),
nbytes / 1_000,
&file.sop_instance_uid,
... | .whatever_context("Unsupported file transfer syntax")?;
dicom_file
.write_dataset_with_ts(&mut object_data, ts_selected)
.whatever_context("Could not write object dataset")?;
| random_line_split |
args.rs | {
/// Add dependency to a Cargo.toml manifest file.
#[structopt(name = "add")]
#[structopt(
after_help = "This command allows you to add a dependency to a Cargo.toml manifest file. If <crate> is a github
or gitlab repository URL, or a local path, `cargo add` will try to automatically get the crate ... | Command | identifier_name | |
args.rs | 2.0.0'). By default, `cargo add` will use this format, as it is the one that the
crates.io registry suggests. One goal of `cargo add` is to prevent you from using wildcard
dependencies (version set to '*')."
)]
Add(Args),
}
#[derive(Debug, StructOpt)]
pub struct Args {
/// Crates to be added.
#[structo... | None
};
if self.git.is_none() && self.path.is_none() && self.vers.is_none() {
let dep = get_latest_dependency(
crate_name.name(),
self.allow_prerelease,
&find(&self.manifest_path)?,
&... | {
assert_eq!(self.git.is_some() && self.vers.is_some(), false);
assert_eq!(self.git.is_some() && self.path.is_some(), false);
assert_eq!(self.git.is_some() && self.registry.is_some(), false);
assert_eq!(self.path.is_some() && self.registry.is_some(), false);
... | conditional_block |
args.rs | 2.0.0'). By default, `cargo add` will use this format, as it is the one that the
crates.io registry suggests. One goal of `cargo add` is to prevent you from using wildcard
dependencies (version set to '*')."
)]
Add(Args),
}
#[derive(Debug, StructOpt)]
pub struct Args {
/// Crates to be added.
#[structo... | .set_optional(self.optional)
.set_features(self.features.clone())
.set_default_features(!self.no_default_features);
if let Some(ref rename) = self.rename {
x = x.set_rename(rename);
}
... | {
if self.crates.len() > 1
&& (self.git.is_some() || self.path.is_some() || self.vers.is_some())
{
return Err(ErrorKind::MultipleCratesWithGitOrPathOrVers.into());
}
if self.crates.len() > 1 && self.rename.is_some() {
return Err(ErrorKind::MultipleCra... | identifier_body |
args.rs | 2.0.0'). By default, `cargo add` will use this format, as it is the one that the
crates.io registry suggests. One goal of `cargo add` is to prevent you from using wildcard
dependencies (version set to '*')."
)]
Add(Args),
}
#[derive(Debug, StructOpt)]
pub struct Args {
/// Crates to be added.
#[structo... | #[structopt(long = "target", conflicts_with = "dev", conflicts_with = "build")]
pub target: Option<String>,
/// Add as an optional dependency (for use in features).
#[structopt(long = "optional", conflicts_with = "dev", conflicts_with = "build")]
pub optional: bool,
/// Path to the manifest to... |
/// Add as dependency to the given target platform. | random_line_split |
DOMHelper.ts | E extends never
? O extends never
? (Element | null)
: ReturnType<O> | null
: O extends never
? (ReturnType<E> | null)
: ReturnType<O> | ReturnType<E> {
const element = document.querySelector(selector)
if (element) {
return existCallback ? existCallback(element as EE) : element
}
return oth... | * change inner text of copy file button to give feedback
* @param {element} copyFileBtn
* @param {string} text
*/
function setTempCopyFileBtnText(copyFileBtn: HTMLButtonElement, text: string) {
copyFileBtn.innerText = text
window.setTimeout(() => (copyFileBtn.innerText = 'Copy file'), 1000)
}
... | /** | random_line_split |
DOMHelper.ts | = '.branch-select-menu .select-menu-list > div .select-menu-item-text'
const branchElements = Array.from(document.querySelectorAll(branchSelector))
return branchElements.map(element => element.innerHTML.trim())
}
function getCurrentBranch() {
const selectedBranchButtonSelector = '.repository-content .branch-sel... | if (currentCodeSnippetElement !== target) {
currentCodeSnippetElement = target
/**
* <article>
* <pre></pre> <!-- case A -->
* <div class="highlight">
* <pre></pre> <!-- case B -->
* <... | conditional_block | |
DOMHelper.ts | E extends never
? O extends never
? (Element | null)
: ReturnType<O> | null
: O extends never
? (ReturnType<E> | null)
: ReturnType<O> | ReturnType<E> {
const element = document.querySelector(selector)
if (element) {
return existCallback ? existCallback(element as EE) : element
}
return oth... | if (getCurrentPageType() === PAGE_TYPES.RAW_TEXT) {
const btnGroupSelector = [
// the button group next to navigation bar
'.repository-content .file-navigation.js-zeroclipboard-container .BtnGroup',
// the button group in file content header
'.repository-content .file .file-header .file-ac... | copyFileBtn.innerText = text
window.setTimeout(() => (copyFileBtn.innerText = 'Copy file'), 1000)
}
| identifier_body |
DOMHelper.ts | SpanElement = branchButtonElement.querySelector('span')
if (branchNameSpanElement) {
const partialBranchNameFromInnerText = branchNameSpanElement.innerText
if (!partialBranchNameFromInnerText.includes('…')) return partialBranchNameFromInnerText
}
const defaultTitle = 'Switch branches or tags'
... | cusFileExplorer() | identifier_name | |
libvirt_driver.py | # Libcloud v2.7.0
"""
Start a stopped node.
:param node: Node which should be used
:type node: :class:`Node`
:rtype: ``bool``
"""
return self.start_node(node=node)
def ex_shutdown_node(self, node):
# NOTE: This method is here for backward compat... | continue | conditional_block | |
libvirt_driver.py | # no state
1: NodeState.RUNNING, # domain is running
2: NodeState.PENDING, # domain is blocked on resource
3: NodeState.TERMINATED, # domain is paused by user
4: NodeState.TERMINATED, # domain is being shut down
5: NodeState.TERMINATED, # domain is shut off
6: Node... |
def reboot_node(self, node):
domain = self._get_domain_for_node(node=node)
return domain.reboot(flags=0) == 0
def destroy_node(self, node):
domain = self._get_domain_for_node(node=node)
return domain.destroy() == 0
def start_node(self, node):
domain = self._get_do... | domains = self.connection.listAllDomains()
nodes = self._to_nodes(domains=domains)
return nodes | identifier_body |
libvirt_driver.py | uri, key=None, secret=None):
"""
:param uri: Hypervisor URI (e.g. vbox:///session, qemu:///system,
etc.).
:type uri: ``str``
:param key: the username for a remote libvirtd server
:type key: ``str``
:param secret: the password for a remote li... | random_line_split | ||
libvirt_driver.py | # no state
1: NodeState.RUNNING, # domain is running
2: NodeState.PENDING, # domain is blocked on resource
3: NodeState.TERMINATED, # domain is paused by user
4: NodeState.TERMINATED, # domain is being shut down
5: NodeState.TERMINATED, # domain is shut off
6: Node... | (self, name):
"""
Retrieve Node object for a domain with a provided name.
:param name: Name of the domain.
:type name: ``str``
"""
domain = self._get_domain_for_name(name=name)
node = self._to_node(domain=domain)
return node
def ex_take_node_scree... | ex_get_node_by_name | identifier_name |
cache.rs | {
use directories::ProjectDirs;
use log::{debug, warn};
use spin::Once;
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
struct Config {
pub cache_enabled: bool,
pub cache_dir: PathBuf,
pub compression_level: i32,
}
... | (dir: &Path, compression_level: i32) -> Self {
// On Windows, if we want long paths, we need '\\?\' prefix, but it doesn't work
// with relative paths. One way to get absolute path (the only one?) is to use
// fs::canonicalize, but it requires that given path exists. The extra advant... | new_step2 | identifier_name |
cache.rs | {
use directories::ProjectDirs;
use log::{debug, warn};
use spin::Once;
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
struct Config {
pub cache_enabled: bool,
pub cache_dir: PathBuf,
pub compression_level: i32,
}
... | mod_dbg = if generate_debug_info { ".d" } else { "" },
);
Some(
conf::cache_directory()
.join(isa.triple().to_string())
.join(compiler_dir)
.join(mod_filename),
)
} else {
... | {
let mod_cache_path = if conf::cache_enabled() {
let hash = Sha256Hasher::digest(module, function_body_inputs);
let compiler_dir = if cfg!(debug_assertions) {
format!(
"{comp_name}-{comp_ver}-{comp_mtime}",
comp_name = compiler_nam... | identifier_body |
cache.rs | {
use directories::ProjectDirs;
use log::{debug, warn};
use spin::Once;
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering}; | }
// Private static, so only internal function can access it.
static CONFIG: Once<Config> = Once::new();
static INIT_CALLED: AtomicBool = AtomicBool::new(false);
static DEFAULT_COMPRESSION_LEVEL: i32 = 0; // 0 for zstd means "use default level"
/// Returns true if and only if the cache is enab... |
struct Config {
pub cache_enabled: bool,
pub cache_dir: PathBuf,
pub compression_level: i32, | random_line_split |
analyze_sample_captures.py | baseband-sig-canvas-')],
[sg.Text("Extracted Frames: ")],
[sg.Multiline(size=(140, 10), key='--CONSOLE_TEXT--', autoscroll=True)]
]
data = None
layout = [
[sg.Text("Capture File: "), sg.Input(key='_CAPTURE_FILE_'), sg.FilesBrowse(), sg.Button... |
window['--Valid-capture-indexs--'].update(values=frames_detected_capture_indxs)
device_info_string = "Capture time stamp: %s.\n"%(data['cature_time_stamp'])
device_info_string += "Downlink performance => FER: %.3f, Frames detected: %d, Failed Frames: %d. ... | raw_samples_fig = None
time_sync_fig = None
time_sync_const_fig = None
baseband_sig_fig = None
while True:
event, values = window.read()
if event == '--FRAME_NUM--' or event == '_CAPTURE_FILE_LOAD_':
if event == '_CAPTURE_FILE_LOAD_':
... | conditional_block |
analyze_sample_captures.py | baseband-sig-canvas-')],
[sg.Text("Extracted Frames: ")],
[sg.Multiline(size=(140, 10), key='--CONSOLE_TEXT--', autoscroll=True)]
]
data = None
layout = [
[sg.Text("Capture File: "), sg.Input(key='_CAPTURE_FILE_'), sg.FilesBrowse(), sg.Button... |
window = sg.Window('Sample Captures Analyzer', layout, default_element_size=(40,40), finalize=True)
frames_detected_capture_indxs = []
if __name__ == '__main__':
raw_samples_fig = None
time_sync_fig = None
time_sync_const_fig = None
baseband_sig_fig = None
while True:
eve... | figure_canvas_agg = FigureCanvasTkAgg(figure, canvas)
figure_canvas_agg.draw()
figure_canvas_agg.get_tk_widget().pack(side='top', fill='both', expand=1)
return figure_canvas_agg | identifier_body |
analyze_sample_captures.py | baseband-sig-canvas-')],
[sg.Text("Extracted Frames: ")],
[sg.Multiline(size=(140, 10), key='--CONSOLE_TEXT--', autoscroll=True)]
]
data = None
layout = [
[sg.Text("Capture File: "), sg.Input(key='_CAPTURE_FILE_'), sg.FilesBrowse(), sg.Button... | data = pickle.load(fileHandler)
fileHandler.close()
# Find capture indexs where the frames were detected.
for capture_idx, frames in enumerate(data['frame_detection']):
if len(frames) > 0:
frames... | if event == '--FRAME_NUM--' or event == '_CAPTURE_FILE_LOAD_':
if event == '_CAPTURE_FILE_LOAD_':
fileHandler = open(values['_CAPTURE_FILE_'], "rb") | random_line_split |
analyze_sample_captures.py | baseband-sig-canvas-')],
[sg.Text("Extracted Frames: ")],
[sg.Multiline(size=(140, 10), key='--CONSOLE_TEXT--', autoscroll=True)]
]
data = None
layout = [
[sg.Text("Capture File: "), sg.Input(key='_CAPTURE_FILE_'), sg.FilesBrowse(), sg.Button... | (canvas, figure):
figure_canvas_agg = FigureCanvasTkAgg(figure, canvas)
figure_canvas_agg.draw()
figure_canvas_agg.get_tk_widget().pack(side='top', fill='both', expand=1)
return figure_canvas_agg
window = sg.Window('Sample Captures Analyzer', layout, default_element_size=(40,40), finalize=True)
frame... | draw_figure | identifier_name |
app2mosaic_full_display.py | ():
print """usage: app2mosaic_full_display file
Arguments:
-d id [-point-size ps] Choose dataset (and plot point size)
-node [-inter-node-only] Display node-to-node mosaic
-node-summary Display summary of off/on-node communications
-display-output file Filename used to ou... | help | identifier_name | |
app2mosaic_full_display.py | = int(m.group(1))
data_2d = np.zeros((nranks,nranks))
continue
m = re_data_table.match(line)
if m:
inside_P2P_table = True
data_label = m.group(1)
"""
m = re_coll_data_table.match(line)
if m:
inside_P2P_table = True
data_label = m.group(1)... | def calculate_network_distances():
global nranks
global pe_node_xyz
global pe_node_id
global data_dict
data_2d = np.zeros((nranks,nranks))
counts_2d = data_dict["Data_P2P_Count"]
for i in range(nranks):
for j in range(nranks):
if counts_2d[i,j] == 0:
continue
dx,dy,dz... | random_line_split | |
app2mosaic_full_display.py | = int(m.group(1))
data_2d = np.zeros((nranks,nranks))
continue
m = re_data_table.match(line)
if m:
inside_P2P_table = True
data_label = m.group(1)
"""
m = re_coll_data_table.match(line)
if m:
inside_P2P_table = True
data_label = m.group(1)... |
repeat = 1
for val in row_data[1::]:
if val[0] == '*':
repeat = int(val[1:])
continue
v = int(val)
for ij in range(repeat):
pe_node_id[j] = v
if v not in node_ids:
node_ids.append(v)
j += 1
... | row_data += line.rstrip().split(' ') | conditional_block |
app2mosaic_full_display.py | = int(m.group(1))
data_2d = np.zeros((nranks,nranks))
continue
m = re_data_table.match(line)
if m:
inside_P2P_table = True
data_label = m.group(1)
"""
m = re_coll_data_table.match(line)
if m:
inside_P2P_table = True
data_label = m.group(1)... | data_2d[i,j] = 3
elif dz > 0:
# pes communicate over rank 1 network (backplane)
data_2d[i,j] = 2
elif pe_node_id[i] != pe_node_id[j]:
# pes are on same blade
data_2d[i,j] = 2
else:
# pes are on same node
data_2d[i,j] = 1
data_dict["Dat... | global nranks
global pe_node_xyz
global pe_node_id
global data_dict
data_2d = np.zeros((nranks,nranks))
counts_2d = data_dict["Data_P2P_Count"]
for i in range(nranks):
for j in range(nranks):
if counts_2d[i,j] == 0:
continue
dx,dy,dz = dist_xyz(pe_node_xyz[i], pe_node_x... | identifier_body |
main.rs | )]
#![recursion_limit="512"]
// starting doc {{{
//! ARES: Automatic REcord System.
//!
//! A Kubernetes-native system to automatically create and manage DNS records
//! meant to run in parallel with External DNS.
//!
//! Configuration is managed through the ares-secret Secret, typically in the
//! default namespace... | () -> Result<()> {
let opts: cli::Opts = cli::Opts::parse();
let decorator = slog_term::TermDecorator::new().build();
let drain = slog_term::FullFormat::new(decorator).build().fuse();
let drain = slog_async::Async::new(drain).build().fuse();
let root_logger = slog::Logger::root(
drain,
... | main | identifier_name |
main.rs | )]
#![recursion_limit="512"]
// starting doc {{{
//! ARES: Automatic REcord System.
//!
//! A Kubernetes-native system to automatically create and manage DNS records
//! meant to run in parallel with External DNS.
//!
//! Configuration is managed through the ares-secret Secret, typically in the
//! default namespace... |
info!(sub_logger, "Finished syncing");
info!(sub_logger, "Spawning watcher");
let res = collector.watch_values(&record.metadata, &sub_ac.provider,
&mut builder).await;
... | {
crit!(sub_logger, "Error! {}", e);
break
} | conditional_block |
main.rs | _docs)]
#![recursion_limit="512"]
// starting doc {{{
//! ARES: Automatic REcord System.
//!
//! A Kubernetes-native system to automatically create and manage DNS records
//! meant to run in parallel with External DNS.
//!
//! Configuration is managed through the ares-secret Secret, typically in the
//! default name... | //! ```yaml
//! apiVersion: v1
//! kind: Pod
//! metadata:
//! name: nginx-hello-world
//! app: nginx
//! spec:
//! containers:
//! - name: nginx
//! image: nginxdemos/hello
//! ---
//! apiVersion: syntixi.io/v1alpha1
//! kind: Record
//! metadata:
//! name: example-selector
//! spec:
//! fqdn: selector... | //! however, useful for making SPF records point to an outbound mail record,
//! where the mail can be sent from one of many Nodes.
//! | random_line_split |
main.rs | )]
#![recursion_limit="512"]
// starting doc {{{
//! ARES: Automatic REcord System.
//!
//! A Kubernetes-native system to automatically create and manage DNS records
//! meant to run in parallel with External DNS.
//!
//! Configuration is managed through the ares-secret Secret, typically in the
//! default namespace... | let config_content = config_data
.get(opts.secret_key.as_str())
.ok_or(anyhow!("Unable to get key from Secret"))?
.clone().0;
debug!(root_logger, "Configuration loaded from Secret");
let config: Vec<Arc<AresConfig>> =
serde_yaml::from_str::<Vec<_>>(std::str::from_utf8(&confi... | {
let opts: cli::Opts = cli::Opts::parse();
let decorator = slog_term::TermDecorator::new().build();
let drain = slog_term::FullFormat::new(decorator).build().fuse();
let drain = slog_async::Async::new(drain).build().fuse();
let root_logger = slog::Logger::root(
drain,
o!("secret" =>... | identifier_body |
core.rs | ) -> std::fmt::Result {
write!(f, "{}, {}", self.inner, self.token)
}
}
macro_rules! token_predicate {
($token:expr) => ($token);
($token1:expr, $token2:expr $(, $tokens:expr)*) => (
TokenPredicate::new(token_predicate!($token2 $(, $tokens)*), $token1)
);
}
// TODO: Document this!
pub ... | try_ident | identifier_name | |
core.rs | , R: FnMut(&mut P, bool)> {
match_func: M,
recover_func: R,
desc: &'static str,
_marker: PhantomData<P>,
}
impl<P, M, R> Predicate<P> for FuncPredicate<P, M, R>
where
P: Parser,
M: FnMut(&mut P) -> bool,
R: FnMut(&mut P, bool),
{
fn matches(&mut self, p: &mut P) -> bool {
(self.... | Ok(x) => v.push(x),
Err(_) => {
term.recover(p, false);
return Err(Recovered);
}
}
}
Ok(v)
}
/// Parse a list of items separated with a specific token, until a terminator
/// oktne has been reached. The terminator is not consumed.
pub ... | match parse(p) { | random_line_split |
core.rs | , R: FnMut(&mut P, bool)> {
match_func: M,
recover_func: R,
desc: &'static str,
_marker: PhantomData<P>,
}
impl<P, M, R> Predicate<P> for FuncPredicate<P, M, R>
where
P: Parser,
M: FnMut(&mut P) -> bool,
R: FnMut(&mut P, bool),
{
fn matches(&mut self, p: &mut P) -> bool {
(self.... |
}
impl<P, T> Predicate<P> for TokenPredicate<P, T>
where
P: Parser,
T: Predicate<P>,
{
fn matches(&mut self, p: &mut P) -> bool {
self.inner.matches(p) || p.peek(0).value == self.token
}
fn recover(&mut self, p: &mut P, consume: bool) {
self.inner.recover(p, consume)
}
}
impl... | {
TokenPredicate {
inner: inner,
token: token,
_marker: PhantomData,
}
} | identifier_body |
core.rs | , R: FnMut(&mut P, bool)> {
match_func: M,
recover_func: R,
desc: &'static str,
_marker: PhantomData<P>,
}
impl<P, M, R> Predicate<P> for FuncPredicate<P, M, R>
where
P: Parser,
M: FnMut(&mut P) -> bool,
R: FnMut(&mut P, bool),
{
fn matches(&mut self, p: &mut P) -> bool {
(self.... |
}
/// Consume a specific token, or emit an error if the next token in the stream
/// does not match the expected one.
pub fn require<P: Parser>(p: &mut P, expect: Token) -> ReportedResult<()> {
let Spanned {
value: actual,
span,
} = p.peek(0);
if actual == expect {
p.bump();
... | {
false
} | conditional_block |
bot.py | import discord
from discord.ext import commands, menus
import config
from cogs.help import HelpCommand
from utils.jsonfile import JSONList, JSONDict
from utils.context import Context
from collections import Counter
import datetime
from contextlib import suppress
import traceback
import re
import os
exte... |
async def on_message(self, message):
if message.guild is None:
return
await self.process_commands(message)
async def on_message_edit(self, before, after):
if before.content != after.content:
await self.on_message(after)
async def process_command... | if self.launched_at is None:
self.launched_at = datetime.datetime.utcnow()
for guild in self.guilds:
for channel in guild.voice_channels:
await self.on_voice_leave(channel)
print('Logged in as', self.user) | identifier_body |
bot.py | import discord
from discord.ext import commands, menus
import config
from cogs.help import HelpCommand
from utils.jsonfile import JSONList, JSONDict
from utils.context import Context
from collections import Counter
import datetime
from contextlib import suppress
import traceback
import re
import os
exte... | return
else:
ctx.command.reset_cooldown(ctx)
if isinstance(error, commands.CommandInvokeError) and not isinstance(error.original, menus.MenuError):
error = error.original
traceback.print_exception(error.__class__.__name__, error, error.__t... | if guild.id in self.blacklist:
await guild.leave()
async def on_command_error(self, ctx, error):
if isinstance(error, commands.CommandNotFound):
| random_line_split |
bot.py | import discord
from discord.ext import commands, menus
import config
from cogs.help import HelpCommand
from utils.jsonfile import JSONList, JSONDict
from utils.context import Context
from collections import Counter
import datetime
from contextlib import suppress
import traceback
import re
import os
exte... | (self, message):
ctx = await self.get_context(message, cls=Context)
if ctx.command is None:
return
if ctx.author.id in self.blacklist:
return
if not ctx.channel.permissions_for(ctx.guild.me).send_messages:
return
bucket = self.text_spam... | process_commands | identifier_name |
bot.py | import discord
from discord.ext import commands, menus
import config
from cogs.help import HelpCommand
from utils.jsonfile import JSONList, JSONDict
from utils.context import Context
from collections import Counter
import datetime
from contextlib import suppress
import traceback
import re
import os
exte... |
else:
settings = self.configs[str(channel.id)]
name = settings.get('name', '@user')
limit = settings.get('limit', 0)
bitrate = settings.get('bitrate', 64000)
top = settings.get('top', False)
try:
category = member.g... | self.voice_spam_counter[member.id] += 1
if self.voice_spam_counter[member.id] >= 5:
del self.text_spam_counter[member.id]
self.blacklist.append(member.id)
await self.blacklist.save()
with suppress(discord.Forbidden):
await mem... | conditional_block |
entity_test.go | Body string
switch i {
case 0:
expectedType = "text/plain"
expectedBody = "Text part"
case 1:
expectedType = "text/html"
expectedBody = "<p>HTML part</p>"
}
if mediaType := p.Header.Get("Content-Type"); mediaType != expectedType {
t.Errorf("Expected part Content-Type to be %q, got %q", expecte... |
if !IsUnknownCharset(err) {
t.Fatal("New(unknown charset): expected an error that verifies IsUnknownCharset")
}
if b, err := ioutil.ReadAll(e.Body); err != nil {
t.Error("Expected no error while reading entity body, got", err)
} else if s := | {
t.Fatal("New(unknown charset): expected an error")
} | conditional_block |
entity_test.go | () *Entity {
var h1 Header
h1.Set("Content-Type", "text/plain")
r1 := strings.NewReader("Text part")
e1, _ := New(h1, r1)
var h2 Header
h2.Set("Content-Type", "text/html")
r2 := strings.NewReader("<p>HTML part</p>")
e2, _ := New(h2, r2)
var h Header
h.Set("Content-Type", "multipart/alternative; boundary=IMT... | testMakeMultipart | identifier_name | |
entity_test.go | want: &ReadOptions{MaxHeaderBytes: math.MaxInt64},
wantErr: false,
},
{
name: "custom header value",
original: &ReadOptions{MaxHeaderBytes: 128},
want: &ReadOptions{MaxHeaderBytes: 128},
wantErr: true,
},
}
for _, test := range tests {
raw := "Subject: " + strings.Repeat("A", 40... | } | random_line_split | |
entity_test.go | Body string
switch i {
case 0:
expectedType = "text/plain"
expectedBody = "Text part"
case 1:
expectedType = "text/html"
expectedBody = "<p>HTML part</p>"
}
if mediaType := p.Header.Get("Content-Type"); mediaType != expectedType {
t.Errorf("Expected part Content-Type to be %q, got %q", expecte... | if s := b.String(); s != expected {
t.Errorf("Expected written entity to be:\n%s\nbut got:\n%s", expected, s)
}
}
func TestEntity_WriteTo_multipart(t *testing.T) {
e := testMakeMultipart()
var b bytes.Buffer
if err := e.WriteTo(&b); err != nil {
t.Fatal("Expected no error while writing entity, got", err)
}... | {
var h Header
h.Set("Content-Type", "text/plain; charset=utf-8")
h.Set("Content-Transfer-Encoding", "base64")
r := strings.NewReader("Qm9uam91ciDDoCB0b3Vz")
e, _ := New(h, r)
e.Header.Set("Content-Transfer-Encoding", "quoted-printable")
var b bytes.Buffer
if err := e.WriteTo(&b); err != nil {
t.Fatal("Expe... | identifier_body |
main.py | grid(domain_values, domain_values,
domain_values, indexing='ij')
n = len(domain_values)
num_slices = u.shape[0]
# We only want to plot the first, middle, and last time slices.
slices = [0, num_slices//2, num_slices-1]
titles = [f'{description}: slice {slice}' for slice in slices]
num... | ut_slice_cube = np.reshape(u_denoised[row, :], (n, n, n))
argmax = np.argmax(np.abs(ut_slice_cube))
[index_x, index_y, index_z] = np.unravel_index(argmax, (n, n, n))
marble_path[row][0] = domain_values[index_x]
marble_path[row][1] = domain_values[index_y]
marble_path[row][2] = do... | conditional_block | |
main.py | points in
frequency domain.
"""
# Time or spatial domain discretization.
# Since we have periodic boundary conditions, the first and last points
# are the same. So we consider only the first n points in the time domain.
t_shifted = np.linspace(-domain_limit, domain_limit, n+1)[0:-1]
# ... | return np.abs(my_array)/np.max(np.abs(my_array))
def plot_spatial_isosurfaces(description: str, domain_values: np.ndarray,
u: np.ndarray, filename: str) -> None:
"""
Plots a few slices of the the data using isosurfaces.
"""
print(f'Plotting spatial isosurfaces: {description}...')
(x_gri... | """
| random_line_split |
main.py | points in
frequency domain.
"""
# Time or spatial domain discretization.
# Since we have periodic boundary conditions, the first and last points
# are the same. So we consider only the first n points in the time domain.
t_shifted = np.linspace(-domain_limit, domain_limit, n+1)[0:-1]
# ... | (omega_x: float, omega_y: float,
omega_z: float) -> None:
"""
Prints the peak frequency.
"""
print(f'The peak frequency is: ({omega_x}, {omega_y}, {omega_z})')
def get_filter(omega_x: float, omega_y: float, omega_z: float,
omega: np.ndarray) -> np.ndarray:
"""
Creates the filter used... | print_peak_frequency | identifier_name |
main.py | for s in range(len(slices)):
u_slice = np.reshape(u[slices[s],:], (n, n, n))
fig.add_trace(
go.Isosurface(
x=x_grid.flatten(),
y=y_grid.flatten(),
z=z_grid.flatten(),
value=normalize(u_slice).flatten(),
isomi... | """
Plots the 3D path of the marble.
"""
print(f'Plotting marble path...')
fig = go.Figure()
fig.add_trace(
go.Scatter3d(
x=marble_path[:, 0], y=marble_path[:, 1], z=marble_path[:, 2],
mode="lines+markers",
line_color=COLOR1,
line_width=3,
... | identifier_body | |
ship_parser.rs | (ApAmmo::new(
ammo["bulletDiametr"].as_f64().expect("Couldn't find bulletDiametr"),
ammo["alphaDamage"].as_f64().expect("Couldn't find alphaDamage"),
ammo["bulletDetonator"].as_f64().expect("Couldn't find bulletDetonator"),
ammo["bulletDetonatorThreshold"]... | (faces: &Vec<ArmorFace>) -> [f64; 3] {
let mins = [
faces.iter().map(|face| { face.vertices.iter() }).flatten().map(|p| {p.x}).fold(1./0., f64::min),
faces.iter().map(|face| { face.vertices.iter() }).flatten().map(|p| {p.y}).fold(1./0., f64::min),
faces.iter().map(|face| { face.vertices.iter... | find_size | identifier_name |
ship_parser.rs | Ap(ApAmmo::new(
ammo["bulletDiametr"].as_f64().expect("Couldn't find bulletDiametr"),
ammo["alphaDamage"].as_f64().expect("Couldn't find alphaDamage"),
ammo["bulletDetonator"].as_f64().expect("Couldn't find bulletDetonator"),
ammo["bulletDetonatorThreshold... | }
faces
}
fn find_size(faces: &Vec<ArmorFace>) -> [f64; 3] {
let mins = [
faces.iter().map(|face| { face.vertices.iter() }).flatten().map(|p| {p.x}).fold(1./0., f64::min),
faces.iter().map(|face| { face.vertices.iter() }).flatten().map(|p| {p.y}).fold(1./0., f64::min),
faces.iter().... | } | random_line_split |
ship_parser.rs | else if ammotype == "AP" {
Ammo::new(
AmmoType::Ap(ApAmmo::new(
ammo["bulletDiametr"].as_f64().expect("Couldn't find bulletDiametr"),
ammo["alphaDamage"].as_f64().expect("Couldn't find alphaDamage"),
ammo["bulletDetonator"].as_f64().expect("Couldn't f... | {
Ammo::new(
AmmoType::He(HeAmmo::new(
ammo["alphaDamage"].as_f64().expect("Couldn't find alphaDamage"),
ammo["alphaPiercingHE"].as_f64().expect("Couldn't find alphaPiercingHE"),
)),
ballistics,
)
} | conditional_block | |
ship_parser.rs | (ApAmmo::new(
ammo["bulletDiametr"].as_f64().expect("Couldn't find bulletDiametr"),
ammo["alphaDamage"].as_f64().expect("Couldn't find alphaDamage"),
ammo["bulletDetonator"].as_f64().expect("Couldn't find bulletDetonator"),
ammo["bulletDetonatorThreshold"]... | ammo,
)
}).collect()
}
#[derive(Deserialize)]
struct ArmorMaterial {
#[serde(alias = "type")]
armor_type: usize,
thickness: usize, // mm
}
#[derive(Deserialize)]
struct ArmorGroup {
material: String,
indices: Vec<usize>,
}
#[derive(Deserialize)]
struct ArmorObject {
v... | {
//debug!("{:#?}", artillery_spec);
let guns = artillery_spec["guns"].as_object().unwrap();
/*for (key,gun) in guns {
debug!("{}: {:?}", key, gun);
}*/
let dispersion = Dispersion::new(
artillery_spec["minDistH"].as_f64().expect("Couldn't find horizontal"),
artillery_spec["minDi... | identifier_body |
main.py | i.isnumeric() and previous_character.isnumeric():
newword += i
else:
groups.append(newword)
newword = i
previous_character = i
if x == len(string) - 2:
groups.append(newword)
newword = ''
buf=[]
next_idx=0
... |
def Start_function(self):
#init variables
elements=[]
formulas=[]
fromulas_processed=[]
nums_custom_formulas=0
#----------------------------
self.log_listWidget.addItem("--INFO-- Files checking")
#set temperatures
try:
... | source_path = QFileDialog.getOpenFileName(self, "Select Source File", "", "Text Files (*.txt *.csv)")
if source_path[0]!="":
source_path=source_path[0]
self.Source_file_lineEdit.setText(source_path) | identifier_body |
main.py | i.isnumeric() and previous_character.isnumeric():
newword += i
else:
groups.append(newword)
newword = i
previous_character = i
if x == len(string) - 2:
groups.append(newword)
newword = ''
buf=[]
next_idx=0
... |
csv_chemestry_table.close()
except FileNotFoundError:
self.error_flag=True
self.log_listWidget.addItem("--ERROR-- Progam can not find file with chemestry table.")
self.log_listWidget.addItem("--ERROR-- File PTE_adapted.txt must be in defalut folder.")
... | read_row = next(reader_chemestry_table)
for j in range(len(read_row)):
read_row[j]=float(read_row[j])
elements.append(read_row) | conditional_block |
main.py | (string):
previous_character = string[0]
groups = []
newword = string[0]
for x, i in enumerate(string[1:]):
if i.isalpha() and previous_character.isalpha():
newword += i
elif i.isnumeric() and previous_character.isnumeric():
newword += i
else:
... | seperate_string_number | identifier_name | |
main.py | elif i.isnumeric() and previous_character.isnumeric():
newword += i
else:
groups.append(newword)
newword = i
previous_character = i
if x == len(string) - 2:
groups.append(newword)
newword = ''
buf=[]
next_i... |
try:
result_path=str(self.Result_path_lineEdit.text())
result_cs_writer=open(result_path, 'a', newline='')
result_writer = csv.writer(result_cs_writer, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)
except FileNotFoundError:
self.error_fla... | random_line_split | |
LoginForm.js | ').width;
const ANIMATION_DURATION = 500;
class LoginForm extends Component {
constructor(props) {
super(props);
this.emailRef = this.updateRef.bind(this, 'email');
this.passwordRef = this.updateRef.bind(this, 'password');
const buttonOpacityValue = new Animated.Value(0); // declare animated value
... | }}
>
<Text style={titleTextStyle}>
is a journey
</Text>
</Animated.View>
</View>
<View style={loginCardStyle}>
<TextField
ref={this.emailRef}
label='Email address'
value={email}
... | random_line_split | |
LoginForm.js | width;
const ANIMATION_DURATION = 500;
class LoginForm extends Component {
constructor(props) {
super(props);
this.emailRef = this.updateRef.bind(this, 'email');
this.passwordRef = this.updateRef.bind(this, 'password');
const buttonOpacityValue = new Animated.Value(0); // declare animated value
... | (nextProps) {
const {error} = this.props;
if (nextProps.error && nextProps.error !== error) {
this.dropdown.alertWithType('error', 'Error' , nextProps.error);
}
}
// Text Input handlers
updateRef(name, ref) {
this[name] = ref;
}
onMailChangeText(text) {
this.props.emailChanged(tex... | componentWillReceiveProps | identifier_name |
LoginForm.js | width;
const ANIMATION_DURATION = 500;
class LoginForm extends Component {
constructor(props) {
super(props);
this.emailRef = this.updateRef.bind(this, 'email');
this.passwordRef = this.updateRef.bind(this, 'password');
const buttonOpacityValue = new Animated.Value(0); // declare animated value
... |
onPasswordChangeText(text) {
this.props.passwordChanged(text);
this.onChangeText(text);
}
onChangeText(text) {
['email', 'password']
.map((name) => ({ name, ref: this[name] }))
.forEach(({ name, ref }) => {
if (ref.isFocused()) {
this.setState({ [name]: text });
... | {
this.props.emailChanged(text);
this.onChangeText(text);
} | identifier_body |
LoginForm.js | width;
const ANIMATION_DURATION = 500;
class LoginForm extends Component {
constructor(props) {
super(props);
this.emailRef = this.updateRef.bind(this, 'email');
this.passwordRef = this.updateRef.bind(this, 'password');
const buttonOpacityValue = new Animated.Value(0); // declare animated value
... |
return (
<KeyboardAwareScrollView
style={{ backgroundColor: primaryWhiteColor }}
resetScrollToCoords={{ x: 0, y: 0 }}
contentContainerStyle={pageStyle}
scrollEnabled={true}
>
<SafeAreaView style={{flex: 1, backgroundColor: '#fff'}}>
<View style={logoStyle}>... | {
(children.profile && children.profile.journey) ? Actions.main(): Actions.journey();
return (<View />);
} | conditional_block |
provision.go | return err
}
if err := p.checkAndDeployProxy(authProxyName, customizedProxy, p.forceProxyInstall, verbosef); err != nil {
return errors.Wrapf(err, "deploying runtime proxy %s", authProxyName)
}
// Deploy remote-token proxy
if p.IsGCPManaged {
customizedProxy, err = getCustomizedProxy(tempDir, remoteTokenPr... | {
client, err := p.createAuthorizedClient(config)
if err != nil {
return err
}
var verifyErrors error
if p.IsLegacySaaS || p.IsOPDK {
verbosef("verifying internal proxy...")
verifyErrors = p.verifyInternalProxy(client, verbosef)
}
verbosef("verifying remote-service proxy...")
verifyErrors = errorset.Ap... | identifier_body | |
provision.go | != "" {
newVH = newVH + fmt.Sprintf(virtualHostReplacementFmt, vh)
}
}
// remove all "secure" virtualhost
bytes = []byte(strings.ReplaceAll(string(bytes), virtualHostDeleteText, ""))
// replace the "default" virtualhost
bytes = []byte(strings.Replace(string(bytes), virtualHostReplaceText, newVH, 1))
... | privateKey, err = server.LoadPrivateKey([]byte(strings.ReplaceAll(pkStr, `\n`, "\n")))
if err != nil {
return
}
| random_line_split | |
provision.go | default" virtualhost
bytes = []byte(strings.Replace(string(bytes), virtualHostReplaceText, newVH, 1))
if err := os.WriteFile(proxiesFile, bytes, 0); err != nil {
return errors.Wrapf(err, "writing file %s", proxiesFile)
}
return nil
}
replaceInFile := func(file, old, new string) error {
bytes, err := os.... | createAuthorizedClient | identifier_name | |
provision.go | ee SaaS (sets management and runtime URL)")
c.Flags().BoolVarP(&rootArgs.IsOPDK, "opdk", "", false,
"Apigee opdk")
c.Flags().StringVarP(&rootArgs.Token, "token", "t", "",
"Apigee OAuth or SAML token (overrides any other given credentials)")
c.Flags().StringVarP(&rootArgs.Username, "username", "u", "",
"Apigee... |
// return possible errors if not hybrid
if !p.IsGCPManaged || p.isCloud() {
return verifyErrors
}
// output this warning for hybrid
if p.rotate > 0 {
shared.Errorf("\nIMPORTANT: Provisioned config | {
verbosef("provisioning verified OK")
} | conditional_block |
bighosts.py |
# | ([0-9a-fA-F]{1,4}){0,7}::?([0-9a-fA-F]{1,4}) # ipv6
# ''',re.VERBOSE)
def __init__(self, a, h):
'''The address parameter is checked against the format
regexp. self.hostnames is a list but the hostname parameter
can be given as a list of strings or a simple ... |
class Hosts(dict):
'''This class features two dictionnaries addresses and hostnames
pointing to Address instances. The dict accessors are overriden
for the object to appear as a dictionnary which can be accessed
both ways, depending on whether the parameter matches the address
format'''
... | '''Common /etc/hosts start the hostname columns at the 24th
character and separate the two columns by as much tabs as
needed'''
sep="\t"*((col1width*8-1-len(self.address))/8+1)
return repr("%s%s%s\n" % ( self.address, sep, self.hostnames )) | identifier_body |
bighosts.py |
# | ([0-9a-fA-F]{1,4}){0,7}::?([0-9a-fA-F]{1,4}) # ipv6
# ''',re.VERBOSE)
def __init__(self, a, h):
'''The address parameter is checked against the format
regexp. self.hostnames is a list but the hostname parameter
can be given as a list of strings or a simple ... |
else: h, a = item, value
if not a in self.addresses and ( not h in self.hostnames or h=='~del~' ):
# New address and new hostname
# Create an instance, and 2 references
new=Address(a,h)
self.addresses[a] = new
self.hostnames[h] = new
e... | a, h = item, value | conditional_block |
bighosts.py |
# | ([0-9a-fA-F]{1,4}){0,7}::?([0-9a-fA-F]{1,4}) # ipv6
# ''',re.VERBOSE)
def __init__(self, a, h):
'''The address parameter is checked against the format
regexp. self.hostnames is a list but the hostname parameter
can be given as a list of strings or a simple ... |
# else:
# f.write(l)
# if a and h:
# i=[ i for i in h.split(), a if i in c and c[i]!='~del~'].pop():
# if i:
# f.write( self.line.sub( repr(c.hostnames[i])[:-1], l ))
# ... | # if a in c.addresses:
# if c[a][0]!='~del~':
# f.write( self.__address.sub( repr(c.addresses[a])[:-1], l ))
# del c[a] | random_line_split |
bighosts.py |
# | ([0-9a-fA-F]{1,4}){0,7}::?([0-9a-fA-F]{1,4}) # ipv6
# ''',re.VERBOSE)
def __init__(self, a, h):
'''The address parameter is checked against the format
regexp. self.hostnames is a list but the hostname parameter
can be given as a list of strings or a simple ... | (self,item):
'''Removes a whole line 'address - hostnames'. Can be called
by address or hostname'''
if self.__address.match(item):
a, h = item, self.addresses[item].hostnames
else:
a, h = self.hostnames[item].address, self.hostnames[item].hostnames
# The... | __delitem__ | identifier_name |
ReturnRefundFooter.js | import HeaderSearchComponent from './HeaderSearchComponent'
import PickerLocation from './PickerLocation'
class ReturnRefundFooter extends Component {
constructor () {
super()
this.state = {
selectedAddress: 'Tambah alamat penjemputan',
addressName: '',
name: '',
phone: '',
post... | () {
const { showData, totalItemSelected, address } = this.props
const { name, selectedAddress, addressName, phone, postalCode, fullAddress, selectedProvince, selectedCity, selectedKecamatan } = this.state
let obj = {
province: {
province_id: selectedProvince
},
city: {
ci... | render | identifier_name |
ReturnRefundFooter.js | import HeaderSearchComponent from './HeaderSearchComponent'
import PickerLocation from './PickerLocation'
class ReturnRefundFooter extends Component {
constructor () {
super()
this.state = {
selectedAddress: 'Tambah alamat penjemputan',
addressName: '',
name: '',
phone: '',
post... | random_line_split | ||
ReturnRefundFooter.js | HeaderSearchComponent from './HeaderSearchComponent'
import PickerLocation from './PickerLocation'
class ReturnRefundFooter extends Component {
constructor () {
super()
this.state = {
selectedAddress: 'Tambah alamat penjemputan',
addressName: '',
name: '',
phone: '',
postalCode... |
}
})
let itemQtyIndex = itemQty.findIndex(qtyData => qtyData.salesOrderItemId === invoices[data.invoiceIndex].items[data.itemIndex].sales_order_item_id)
let qty = 1
if (itemQtyIndex >= 0) {
qty = itemQty[itemQtyIndex].qty
}
if (!isEmpty(invoices[data.invoiceIndex])) ... | {
shippingCost.shippingAmount += invoices[data.invoiceIndex].items[data.itemIndex].shipping_amount * qtyData.qty
shippingCost.handlingFee += invoices[data.invoiceIndex].items[data.itemIndex].handling_fee_adjust * qtyData.qty
} | conditional_block |
decode_test.go | 1544864, 333731851, 333731852, 333731850, 333731855,
333731858, 333731854, 108047, 769984352, 21544864},
Tags: map[string]string{
"area": "yes",
"highway": "pedestrian",
"name": "Fitzroy Square",
},
Info: Info{
Version: 7,
Timestamp: parseTime("2013-08-07T12:08:39Z"),
Changeset: 17253... | BenchmarkDecode | identifier_name | |
decode_test.go |
var (
IDsExpectedOrder = []string{
// Start of dense nodes.
"node/44", "node/47", "node/52", "node/58", "node/60",
"node/79", // Just because way/79 is already there
"node/2740703694", "node/2740703695", "node/2740703697",
"node/2740703699", "node/2740703701",
// End of dense nodes.
// Start of ways.
... | {
t, err := time.Parse(time.RFC3339, s)
if err != nil {
panic(err)
}
return t
} | identifier_body | |
decode_test.go | "name": "Fitzroy Square",
},
Info: Info{
Version: 7,
Timestamp: parseTime("2013-08-07T12:08:39Z"),
Changeset: 17253164,
Uid: 1016290,
User: "Amaroussi",
Visible: true,
},
}
er = &Relation{
ID: 7677,
Members: []Member{
{ID: 4875932, Type: WayType, Role: "outer"},
... |
b.ResetTimer()
for i := 0; i < b.N; i++ {
if _, err = f.Seek(0, 0); err != nil {
b.Fatal(err) | random_line_split | |
decode_test.go | 45428", "way/268745431", "way/268745434", "way/268745436",
"way/268745439",
// End of ways.
// Start of relations.
"relation/69", "relation/94", "relation/152", "relation/245",
"relation/332", "relation/3593436", "relation/3595575",
"relation/3595798", "relation/3599126", "relation/3599127",
// End of re... |
}
func checkHeader(a *Header) bool {
if a == nil || a.BoundingBox == nil || a.RequiredFeatures == nil {
return false
}
// check bbox
if a.BoundingBox.Right != eh.BoundingBox.Right || a.BoundingBox.Left != eh.BoundingBox.Left || a.BoundingBox.Top != eh.BoundingBox.Top || a.BoundingBox.Bottom != eh.BoundingBox.B... | {
t.Fatal(err)
} | conditional_block |
satAverage.py | nodd=0
for i in range(0, len(lines)):
if i%2:
nodd+=1
oddf.write(lines[i])
else:
neven+=1
evenf.write(lines[i])
evenf.close()
oddf.close()
if neven>0:
self.makeClassAverages(evenfile, self.params['evenstack'], classdata, maskrad)
if nodd>0:
self.makeClassAverages(oddfile, self.p... | random_line_split | ||
satAverage.py | ineq = appiondata.ApRefineIterData()
refineq['refineRun'] = refinerundata
refineq['iteration'] = iteration
refinedata = refineq.query(results=1)
if not refinedata:
apDisplay.printError("Could not find refinedata for reconrun id="
+str(reconid)+" iter="+str(iteration))
refinepartq=appiondata.Ap... |
#=====================
def start(self):
self.rootname = self.params['stackname'].split(".")[0]
self.params['outputstack'] = os.path.join(self.params['rundir'], self.params['stackname'])
if os.path.isfile(self.params['outputstack']):
apFile.removeStack(self.params['outputstack'])
if self.params['eotest']... | refdata = appiondata.ApRefineRunData.direct_query(self.params['reconid'])
if not refdata:
apDisplay.printError("reconid "+str(self.params['reconid'])+" does not exist in the database")
refpath = refdata['path']['path']
rundir = os.path.join(refpath, "../../satEuler/sat-recon%d/volumes"%(self.params['reconid'])... | identifier_body |
satAverage.py | ineq = appiondata.ApRefineIterData()
refineq['refineRun'] = refinerundata
refineq['iteration'] = iteration
refinedata = refineq.query(results=1)
if not refinedata:
apDisplay.printError("Could not find refinedata for reconrun id="
+str(reconid)+" iter="+str(iteration))
refinepartq=appiondata.Ap... | (self):
"""
Removes particles by reading a list of particle numbers generated externally.
Requirements:
the input file has one particle per line
the first piece of data is the particle number from the db
"""
keeplist = []
f = open(self.params['keeplist'], 'r')
lines = f.readlines()
f.close()
fo... | procKeepList | identifier_name |
satAverage.py | ineq = appiondata.ApRefineIterData()
refineq['refineRun'] = refinerundata
refineq['iteration'] = iteration
refinedata = refineq.query(results=1)
if not refinedata:
apDisplay.printError("Could not find refinedata for reconrun id="
+str(reconid)+" iter="+str(iteration))
refinepartq=appiondata.Ap... |
class_stats['meanquality']=quality.mean()
class_stats['stdquality']=quality.std()
class_stats['max']=quality.max()
class_stats['min']=quality.min()
apDisplay.printMsg("sorted %d particles into %d classes"%(len(particles), len(classes)))
### print stats
print "-- quality factor stats --"
print ("mean/st... | quality[partnum] = particles[partnum]['quality_factor']
key = ("%.3f_%.3f"%(particles[partnum]['euler1'], particles[partnum]['euler2']))
if key not in classes.keys():
classes[key]={}
classes[key]['particles']=[]
classes[key]['euler1'] = particles[partnum]['euler1']
classes[key]['euler2'] = particl... | conditional_block |
editor.rs | ()
.map(|(color_id, hex)| (color_id as u8, hex_string_to_rgb(hex).unwrap()));
// Get the xterm color with the minimum Euclidean distance to the target color
// i.e. distance = √ (r2 - r1)² + (g2 - g1)² + (b2 - b1)²
let distances = colors.map(|(color_id, (r, g, b))| {
let r_delta: u32 = (ma... | style_stack.pop(); | random_line_split | |
editor.rs | {
pub ansi: ansi_term::Style,
pub css: Option<String>,
}
#[derive(Debug)]
pub struct Theme {
pub styles: Vec<Style>,
pub highlight_names: Vec<String>,
}
#[derive(Default, Deserialize, Serialize)]
pub struct ThemeConfig {
#[serde(default)]
pub theme: Theme,
}
impl Theme {
/* pub fn load(p... | Style | identifier_name | |
editor.rs | ": 239,
"punctuation.delimiter": 239,
"string.special": 30,
"string": 28,
"tag": 18,
"type": 23,
"type.builtin": {"color": 23, "bold": true},
"variable.builtin": {"bold": true},
"variable.parameter": {"underl... | self.backing[0].1
}
| identifier_body | |
calendar_appointment.py | ][0] - tolerance:
return -1
if end_dt >= intervals[-1][1] + tolerance:
return -1
return recursive_find_index(0, len(intervals) - 1)
if not intervals:
return False
tolerance = timedelta(minutes=1)
... | _name = "calendar.appointment.answer"
_description = "Online Appointment : Answers"
question_id = fields.Many2many('calendar.appointment.question', 'calendar_appointment_question_answer_rel', 'answer_id', 'question_id', string='Questions')
name = fields.Char('Answer', translate=True, required=True) | identifier_body | |
calendar_appointment.py | help="Timezone where appointment take place")
employee_ids = fields.Many2many('hr.employee', 'website_calendar_type_employee_rel', domain=[('user_id', '!=', False)], string='Employees')
assignation_method = fields.Selection([
('random', 'Random'),
('chosen', 'Chosen by the Customer')], s... |
slot_weekday = [int(weekday) - 1 for weekday in self.slot_ids.mapped('weekday')]
for day in rrule.rrule(rrule.DAILY,
dtstart=first_day.date() + timedelta(days=1),
until=last_day.date(),
byweekday=slot_weekday):... | if slot.hour > first_day.hour + first_day.minute / 60.0:
append_slot(first_day.date(), slot) | conditional_block |
calendar_appointment.py | ,
help="Timezone where appointment take place")
employee_ids = fields.Many2many('hr.employee', 'website_calendar_type_employee_rel', domain=[('user_id', '!=', False)], string='Employees')
assignation_method = fields.Selection([
('random', 'Random'),
('chosen', 'Chosen by the Customer')],... | (self, slots, first_day, last_day, employee=None):
""" Fills the slot stucture with an available employee
:param slots: slots structure generated by _slots_generate
:param first_day: start datetime in UTC
:param last_day: end datetime in UTC
:param employee: if s... | _slots_available | identifier_name |
calendar_appointment.py | ,
help="Timezone where appointment take place")
employee_ids = fields.Many2many('hr.employee', 'website_calendar_type_employee_rel', domain=[('user_id', '!=', False)], string='Employees')
assignation_method = fields.Selection([
('random', 'Random'),
('chosen', 'Chosen by the Customer')],... | index = (upper_bound + lower_bound) // 2
if intervals[index][0] <= start_dt:
return recursive_find_index(index, upper_bound)
else:
return recursive_find_index(lower_bound, index)
if start_dt <= i... | return lower_bound | random_line_split |
graphs.py |
class egde:
def __init__(self,x,y):
self.v1 = x
self.v2 = y
def add_edge(self,u,v):
#for directed graphs
self.graph[u].append(v)
#for undirected graphs
#self.graph[u].append(v)
#self.graph[v].append(u)
#e = edge(... | self.graph = defaultdict(list)
self.V = vertices
self.E = edges | identifier_body | |
graphs.py | #Application of DFS
#1.Topological Sort -> Normal DFS with a stack that pushes the leaf node.
#2. Cycle in a directed graph
#3. Count number of forests in a graph
#4. Shortest Path in Directed Acyclic Graph using topological sort
# Applications of BFS
# 1) Shortest Path and Minimum Spanning Tree for unweighted g... | numIslands | identifier_name | |
graphs.py | . Perform a topological sort on the graph
# 3. Process the vertices in topological sort and and for each vertex , update its adjacent vertex with the weight of the edge
#
dist = [float("inf")]*len(graph)
dist[s] = 0
while(stack):
node = stack.pop()
for next,weight in graph[nod... | #Naive implementations take O(n)
#parents list should maintain tuples (parent,rank) for each index(which is the vertex)
#parents = [(-1,0)] for _ in range(len(self.graph))] will initialse each vertex's parent as itself and rank as 0
def find_parent_pc(parents,v):
if parents[v][0] == -1:
return v
else... | random_line_split | |
graphs.py | . Perform a topological sort on the graph
# 3. Process the vertices in topological sort and and for each vertex , update its adjacent vertex with the weight of the edge
#
dist = [float("inf")]*len(graph)
dist[s] = 0
while(stack):
node = stack.pop()
for next,weight in graph[nod... |
# After collection of the x coordinates in rows (which by the nature of collection are in sorted order) and y in cols(need to be sorted,
# we take the median of the two as the origin
row = rows[len(rows//2)]
cols.sort()
col = cols[len(cols//2)]
# the point they should meet on is the median o... | for j in range(len(grid2D[0])):
if grid2D[i][j] == 1:
rows.append(i)
cols.append(j) | conditional_block |
restconf.py | Systems, Inc.
"""
import os
import re
import logging
import json
import subprocess
import datetime
import lxml.etree as et
from jinja2 import Template, Environment, FileSystemLoader
from collections import OrderedDict
from explorer.utils.admin import ModuleAdmin
def get_op(keyvalue, mode):
'''
Return option ... |
def add_list(seg, msg):
kdict = OrderedDict()
for key in seg.keys:
kdict[key.name] = set_type(key)
for leaf in seg.leaves:
kdict[leaf.name] = set_type(leaf)
return kdict
def build_msg(segs, msg=OrderedDict()):
for seg in segs:
if seg.type == 'container':
cont... | cont = OrderedDict()
if seg.presence == 'true':
return cont
for leaf in seg.leaves:
cont[leaf.name] = set_type(leaf)
return cont | identifier_body |
restconf.py | Cisco Systems, Inc.
"""
import os
import re
import logging
import json
import subprocess
import datetime
import lxml.etree as et
from jinja2 import Template, Environment, FileSystemLoader
from collections import OrderedDict
from explorer.utils.admin import ModuleAdmin
def get_op(keyvalue, mode):
'''
Return o... | if not isinstance(val, (str, unicode)):
return val
return val.replace("/", "%2F").replace(":", "%3A").replace(" ", "%20")
def set_type(val):
'''
Using json.dumps() to convert dict to JSON strings requires that
actual Python values are correct in dict
TODO: Not sure if all correct datat... | ''' | random_line_split |
restconf.py | Systems, Inc.
"""
import os
import re
import logging
import json
import subprocess
import datetime
import lxml.etree as et
from jinja2 import Template, Environment, FileSystemLoader
from collections import OrderedDict
from explorer.utils.admin import ModuleAdmin
def | (keyvalue, mode):
'''
Return option and path depth of option to use for URL.
URL should extend to where option is placed and message body
should contain everything beyond.
'''
for child in keyvalue:
op = child.attrib.get("option", "")
if mode in ["get", "get-config"]:
... | get_op | identifier_name |
restconf.py | Systems, Inc.
"""
import os
import re
import logging
import json
import subprocess
import datetime
import lxml.etree as et
from jinja2 import Template, Environment, FileSystemLoader
from collections import OrderedDict
from explorer.utils.admin import ModuleAdmin
def get_op(keyvalue, mode):
'''
Return option ... |
return False
def __str__(self):
return self.name
def parse_url(username, request, mode):
'''
Main function that creates a URL and message body that uses the cxml (lxml)
Element nodes from a defined test from the YangExplorer GUI
Rules:
https://tools.ietf.org/html/draft-ietf-... | return self.name == x.attrib.get('name') | conditional_block |
invsim.py | old['extra_inventory'] + excess
return {'supply' : supply, 'inventory' : new_inv, 'shortage' : shortage,
'reward_' : new_csupply, 'missed_reward' : new_cshortage,
'extra_inventory' : new_cexcess}
def partial_order_supply_step(self):
old = {k : get_largest_key_val(self.logs[k])[1]
for k in self... | steps['p_step'] = self.ROP_production_step(ROP, ROO, delay)
return steps
else:
raise ValueError("exiting parse_steps() : invalid argument steps")
def get_strategy_desc(self):
try:
strat = self.strategy
self.strategy_desc = ' '.join(strat.split('_'))
if 'ROP' in self.strategy: self.strategy_d... | strategy = kwargs.pop('strategy', None)
if strategy is None:
raise ValueError("exiting parse_steps() : no strategy or steps given")
elif isinstance(strategy, str):
strategy = ' '.join(strategy.split('_'))
if strategy == 'simple strategy':
self.I0 = kwargs.pop('I0', self.I0)
steps = default_s... | conditional_block |
invsim.py | ['extra_inventory'] + excess
return {'supply' : supply, 'inventory' : new_inv, 'shortage' : shortage,
'reward_' : new_csupply, 'missed_reward' : new_cshortage,
'extra_inventory' : new_cexcess}
def partial_order_supply_step(self):
old = {k : get_largest_key_val(self.logs[k])[1]
for k in self.log... | def func():
old = {k : get_largest_key_val(self.logs[k])[1]
for k in self.logs.keys()}
current_inv = old['inventory']
if int(self.timer)%delay==0:
if current_inv >= self.I0:
new_inv, production = current_inv, 0
else:
new_inv, production = self.I0, self.I0 - current_inv
return ... | new_inv, production = self.I0, self.I0 - current_inv
return {'inventory' : new_inv, 'production' : production}
def bulk_production_step(self, delay): | random_line_split |
invsim.py | (self):
d = self.d_gen()
return {'demand' : d}
def all_or_nothing_supply_step(self):
old = {k : get_largest_key_val(self.logs[k])[1]
for k in self.logs.keys()}
if old['inventory'] >= old['demand']:
supply = old['demand']
new_inv = old['inventory'] - old['demand']
shortage = 0
excess = old... | simple_demand_step | identifier_name | |
invsim.py | fig.savefig(savepath)
print('\t\tsaved', savepath)
#################### plot 1 thing on an axis #####################################
def single_histogram(ax, data_dict, label, to_remove = {}, logscale = False, **kwargs):
col = kwargs.pop('col', 'k')
bins = kwargs.pop('bins', 50)
figsize = kwargs.pop('figsize... | t = float("{0:.2f}".format(t))
r = float("{0:.2f}".format(r))
res = float("{0:.10f}".format((t%1)-r))
return res == 0.0 | identifier_body | |
lib.rs | pub result: String,
}
impl fmt::Display for LayerResult {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{} | {}", self.layer, self.result)
}
}
/// A Transition is the LayerResult of running the command on the lower layer
/// and of running the command on the higher layer. No-op tr... | <T>(layers: Vec<Layer>, action: &T) -> Result<Vec<Transition>, Error>
where
T: ContainerAction + 'static,
{
let first_layer = layers.first().expect("no first layer");
let last_layer = layers.last().expect("no last layer");
let first_image_name: String = first_layer.image_name.clone();
let last_imag... | get_changes | identifier_name |
lib.rs | pub result: String,
}
impl fmt::Display for LayerResult {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{} | {}", self.layer, self.result)
}
}
/// A Transition is the LayerResult of running the command on the lower layer
/// and of running the command on the higher layer. No-op tr... | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match &self.before {
Some(be) => write!(f, "({} -> {})", be, self.after),
None => write!(f, "-> {}", self.after),
}
}
}
/// Starts the bisect operation. Calculates highest and lowest layer result and if they have
///... |
impl fmt::Display for Transition { | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.