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 |
|---|---|---|---|---|
index.ts | function | (url: string, container: Element, options?: IEmbeddOptions): Promise<Glue> {
const state: {
glue?: Glue;
beforeInitResolve?: (value?: unknown) => void;
beforeInitReject?: (reason?: unknown) => void;
retryTimer?: ReturnType<typeof setTimeout>;
} = {};
return new Promise((resolve, reject) => {
// Add defau... | embed | identifier_name |
index.ts | function embed(url: string, container: Element, options?: IEmbeddOptions): Promise<Glue> {
const state: {
glue?: Glue;
beforeInitResolve?: (value?: unknown) => void;
beforeInitReject?: (reason?: unknown) => void;
retryTimer?: ReturnType<typeof setTimeout>;
} = {};
return new Promise((resolve, reject) => {... | }
frame.addEventListener('load', () => {
if (state.glue) {
delete state.glue;
}
if (options && options.timeout) {
state.retryTimer = setTimeout(() => {
if (!state.glue) {
retry();
}
}, options.timeout);
} else {
reject(new Error('glue timeout'));
}
});
append();
}... | }, 1000); // NOTE(longsleep): Retry time hardcoded - is it needed to have a configuration? | random_line_split |
index.ts | function embed(url: string, container: Element, options?: IEmbeddOptions): Promise<Glue> {
const state: {
glue?: Glue;
beforeInitResolve?: (value?: unknown) => void;
beforeInitReject?: (reason?: unknown) => void;
retryTimer?: ReturnType<typeof setTimeout>;
} = {};
return new Promise((resolve, reject) => {... | };
// Validate origin.
const expectedOrigin = getGlueParameter('origin');
if (expectedOrigin) {
if (expectedOrigin !== window.origin) {
// Validate white list if cross origin.
if (!options || !options.origins || !options.origins.includes('expectedOrigin')) {
throw new Error('glue origin is not ... | {
return new Promise((resolve, reject) => {
if (!sourceWindow) {
sourceWindow = window.parent;
}
// Get glue mode.
const mode = getGlueParameter('mode');
if (sourceWindow === self || mode === null) {
// Return empty Glue API if we are self, or glue mode is not set. It
// this means Glue is not act... | identifier_body |
day_14.rs | maps, one for the data and one for the mask, as
/// these are used separately.
///
/// ## Memory Updates
/// Whilst the two parts use the mask to modify where/what actually gets written `mem[8] = 11`
/// should be interpreted as address = 8, value = 11.
///
/// # Examples from Tests
/// ```
/// assert_eq!(
/// Left... | let mut new_addresses = HashSet::new();
| random_line_split | |
day_14.rs | > 1 overwrites the corresponding bit in the value, while an X leaves the bit in the value
/// > unchanged.
///
/// # Example from Tests
/// ```
/// let mut expected: HashMap<usize, usize> = HashMap::new();
///
/// let program_1 = "mask = XXXXXXXXXXXXXXXXXXXXXXXXXXXXX1XXXX0X\nmem[8] = 11";
///
/// expected.insert(8, 73... | {
let mut expected: HashMap<usize, usize> = HashMap::new();
let program_1 = "mask = XXXXXXXXXXXXXXXXXXXXXXXXXXXXX1XXXX0X\nmem[8] = 11";
expected.insert(8, 73);
assert_eq!(expected, run_program_v1(program_1));
let program_2 = "mask = XXXXXXXXXXXXXXXXXXXXXXXXXXXXX1XXXX0X
mem[8] =... | identifier_body | |
day_14.rs | ` it
/// should be treated a raw data that will in someway override other input, and `X` will be used as
/// the mask. It is easier to store this as two bitmaps, one for the data and one for the mask, as
/// these are used separately.
///
/// ## Memory Updates
/// Whilst the two parts use the mask to modify where/what ... | (line: &str) -> Either<Mask, Mem> {
let mut parts = line.split(" = ");
let inst = parts.next().expect("Invalid line");
let value = parts.next().expect("Invalid line");
if inst == "mask" {
let (mask, data) =
value.chars().fold(
(0usize, 0usize),
|(mask... | parse_line | identifier_name |
day_14.rs | ` it
/// should be treated a raw data that will in someway override other input, and `X` will be used as
/// the mask. It is easier to store this as two bitmaps, one for the data and one for the mask, as
/// these are used separately.
///
/// ## Memory Updates
/// Whilst the two parts use the mask to modify where/what ... | else {
let re = Regex::new(r"^mem\[(\d+)]$").unwrap();
match re.captures(inst) {
Some(cap) => Right(Mem {
address: cap.get(1).unwrap().as_str().parse::<usize>().unwrap(),
value: value.parse::<usize>().unwrap(),
}),
None => panic!("Inv... | {
let (mask, data) =
value.chars().fold(
(0usize, 0usize),
|(mask, data), char| (
mask << 1 | if char == 'X' { 1 } else { 0 },
data << 1 | if char == '1' { 1 } else { 0 }
),
);
Left(Mask { ma... | conditional_block |
schedule.rs | the
/// type is both `Send` and `Sync`.
///
/// This is automatically implemented for all types that implement `Runnable` which meet the requirements.
pub trait Schedulable: Runnable + Send + Sync {}
impl<T> Schedulable for T where T: Runnable + Send + Sync {}
/// Describes which archetypes a system declares access t... | let mut component_mutated = HashMap::<ComponentTypeId, Vec<usize>>::with_capacity(64);
for (i, system) in systems.iter().enumerate() {
log::debug!("Building dependency: {}", system.name());
let (read_res, read_comp) = system.reads();
let (write_r... | random_line_split | |
schedule.rs |
/// type is both `Send` and `Sync`.
///
/// This is automatically implemented for all types that implement `Runnable` which meet the requirements.
pub trait Schedulable: Runnable + Send + Sync {}
impl<T> Schedulable for T where T: Runnable + Send + Sync {}
/// Describes which archetypes a system declares access to.
p... | (&mut self, world: &mut World) {
self.systems.iter_mut().for_each(|system| {
system.run(world);
});
// Flush the command buffers of all the systems
self.systems.iter().for_each(|system| {
system.command_buffer_mut().write(world);
});
}
/// Execut... | execute | identifier_name |
edge.rs | : usize, to: usize);
}
impl Graph {
fn edge_is_active(&self, e: usize) -> bool {
self.active_edges[e].active
}
pub fn is_short(&self, from: &Vertex, to: &Vertex) -> bool {
let length = distance(from, to);
length < from.local_mean - self.mean_std_deviation
}
pub fn is_long(&self, from: &Vertex, to: &Vertex)... |
pub fn calculate_connected_components(&mut self) {
let mut cc_index = 1;
while let Some(v) = self
.verticies
.iter_mut()
.position(|x| !x.edges.is_empty() && x.label == 0)
{
self.build_connected_component(v, cc_index);
cc_index += 1;
}
let groups = self.calculate_cc_sizes();
for (label, s... | {
if self.verticies[vertex_index].label != label {
self.verticies[vertex_index].label = label;
for i in 0..self.verticies[vertex_index].edges.len() {
let edge_index = self.verticies[vertex_index].edges[i];
if self.edge_is_active(edge_index)
&& self.verticies[self.active_edges[edge_index].other(vert... | identifier_body |
edge.rs | from: usize, to: usize);
}
impl Graph {
fn edge_is_active(&self, e: usize) -> bool {
self.active_edges[e].active
}
pub fn is_short(&self, from: &Vertex, to: &Vertex) -> bool {
let length = distance(from, to);
length < from.local_mean - self.mean_std_deviation
}
pub fn is_long(&self, from: &Vertex, to: &Ve... | }
}
}
}
pub fn restore_edges(&mut self) {
struct LabelReference {
size: usize,
label: usize,
edge_index: usize,
};
let mut cc_sizes = self.calculate_cc_sizes();
let mut reassign_map: HashMap<usize, usize> = HashMap::new();
for i in 0..self.verticies.len() {
let short_edges: Vec<&Edge> ... | self.active_edges[edge].active = true;
}
if self.verticies[other].label != label {
self.active_edges[edge].active = false; | random_line_split |
edge.rs | : usize, to: usize);
}
impl Graph {
fn edge_is_active(&self, e: usize) -> bool {
self.active_edges[e].active
}
pub fn is_short(&self, from: &Vertex, to: &Vertex) -> bool {
let length = distance(from, to);
length < from.local_mean - self.mean_std_deviation
}
pub fn is_long(&self, from: &Vertex, to: &Vertex)... |
}
pub fn calculate_connected_components(&mut self) {
let mut cc_index = 1;
while let Some(v) = self
.verticies
.iter_mut()
.position(|x| !x.edges.is_empty() && x.label == 0)
{
self.build_connected_component(v, cc_index);
cc_index += 1;
}
let groups = self.calculate_cc_sizes();
for (label... | {
self.verticies[vertex_index].label = label;
for i in 0..self.verticies[vertex_index].edges.len() {
let edge_index = self.verticies[vertex_index].edges[i];
if self.edge_is_active(edge_index)
&& self.verticies[self.active_edges[edge_index].other(vertex_index)].label == 0
{
self.build_connect... | conditional_block |
edge.rs | from: usize, to: usize);
}
impl Graph {
fn edge_is_active(&self, e: usize) -> bool {
self.active_edges[e].active
}
pub fn is_short(&self, from: &Vertex, to: &Vertex) -> bool {
let length = distance(from, to);
length < from.local_mean - self.mean_std_deviation
}
pub fn is_long(&self, from: &Vertex, to: &Ve... | {
size: usize,
label: usize,
edge_index: usize,
};
let mut cc_sizes = self.calculate_cc_sizes();
let mut reassign_map: HashMap<usize, usize> = HashMap::new();
for i in 0..self.verticies.len() {
let short_edges: Vec<&Edge> = self.verticies[i]
.edges
.iter()
.filter(|e| self.active_edges[... | LabelReference | identifier_name |
scheme_types.py | TypeError("+ can't be applied between list and "+str(type(right)))
@property
def car(self):
"""Return the first part."""
return self.pair.car
@property
def cdr(self):
"""Return the second part."""
return self.pair.cdr
@car.setter
def car(self, value):
"""... | """Return substring from beg to end."""
require_type(isa(string, str), 'the first parameter of substring must be a string')
if beg < 0 or end >= len(string) or beg > end:
raise IndexError('the index of substring is invalid')
return string[beg:end] | identifier_body | |
scheme_types.py | part when printing."""
if isa(symbol, Pair) or isa(symbol, List):
return ' ' + str(symbol)[1:-1]
# deal with situation where cdr is '()
if self.cdr == []:
return ''
return ' . ' + tostr(symbol)
def update_str(self):
"""Format for printing."""
... | def do_is(op_left, op_right):
"""Judge whether op_left is op_right."""
if isa(op_left, float) and isa(op_right, float):
return op_left == op_right
return op_left is op_right
def do_sqrt(num):
"""Compute square root of the number."""
if num < 0:
from cmath import sqrt
return ... | return result
| random_line_split |
scheme_types.py | root of the number."""
if num < 0:
from cmath import sqrt
return sqrt(num)
from math import sqrt
return sqrt(num)
def is_list(s_list):
"""Judge whether it's a list."""
return isa(s_list, List)
def is_pair(pair):
"""Judge whether it's a pair."""
return isa(pair, Pair) or is... | s_or | identifier_name | |
scheme_types.py | part when printing."""
if isa(symbol, Pair) or isa(symbol, List):
return ' ' + str(symbol)[1:-1]
# deal with situation where cdr is '()
if self.cdr == []:
return ''
return ' . ' + tostr(symbol)
def update_str(self):
"""Format for printing."""
... |
return op_left is op_right
def do_sqrt(num):
"""Compute square root of the number."""
if num < 0:
from cmath import sqrt
return sqrt(num)
from math import sqrt
return sqrt(num)
def is_list(s_list):
"""Judge whether it's a list."""
return isa(s_list, List)
def is_pair(pair... | return op_left == op_right | conditional_block |
User.ts |
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
import { IMQService, expose, profile, IMessageQueue } from '@imqueue/rpc';
import * as mongoose from ... |
else {
return await this.createUser(data, fields);
}
}
/**
* Returns number of cars registered for the user having given id or email
*
* @param {string} idOrEmail
* @return {Promise<number>}
*/
@profile()
@expose()
public async carsCount(idOrEm... | {
return await this.updateUser(data, fields);
} | conditional_block |
User.ts | _ERROR,
INVALID_CAR_ID_ERROR,
} from './errors';
/**
* User service implementation
*/
export class User extends IMQService {
private db: mongoose.Connection;
private UserModel: mongoose.Model<any>;
/**
* Transforms given filters into mongo-specific filters object
*
* @param {UserFilt... | * @param {string} userId - user identifier | random_line_split | |
User.ts |
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
import { IMQService, expose, profile, IMessageQueue } from '@imqueue/rpc';
import * as mongoose from ... | (idOrEmail: string): Promise<number> {
const field = isEmail(idOrEmail) ? 'email' : '_id';
const ObjectId = mongoose.Types.ObjectId;
if (field === '_id') {
idOrEmail = ObjectId(idOrEmail) as any;
}
return ((await this.UserModel.aggregate([
{ $match: { [f... | carsCount | identifier_name |
User.ts | '
};
}
return filters;
}
/**
* Initializes mongo database connection and user schema
*
* @return Promise<any>
*/
@profile()
private async initDb(): Promise<any> {
return new Promise((resolve, reject) => {
mongoose.set('useCreateIndex'... | {
return (await this.UserModel
.findOne({ _id: mongoose.Types.ObjectId(userId) })
.select(['cars._id', 'cars.carId', 'cars.regNumber'])
.exec() || { cars: [] })
.cars
.find((car: UserCarObject) => String(car._id) === carId) || null;
} | identifier_body | |
garmin_util.rs | collect();
let (h, m, s): (i32, i32, f64) = match entries.first() {
Some(h) => match entries.get(1) {
Some(m) => match entries.get(2) {
Some(s) => (h.parse()?, m.parse()?, s.parse()?),
None => (h.parse()?, m.parse()?, 0.),
},
None => (h.par... | #[must_use]
pub fn days_in_year(year: i32) -> i64 {
(Date::from_calendar_date(year + 1, Month::January, 1).unwrap_or(date!(1969 - 01 - 01))
- Date::from_calendar_date(year, Month::January, 1).unwrap_or(date!(1969 - 01 - 01)))
.whole_days()
}
#[must_use]
pub fn days_in_month(year: i32, month: u32) -> i6... | random_line_split | |
garmin_util.rs | ();
let (h, m, s): (i32, i32, f64) = match entries.first() {
Some(h) => match entries.get(1) {
Some(m) => match entries.get(2) {
Some(s) => (h.parse()?, m.parse()?, s.parse()?),
None => (h.parse()?, m.parse()?, 0.),
},
None => (h.parse()?, ... |
#[must_use]
pub fn expected_calories(weight: f64, pace_min_per_mile: f64, distance: f64) -> f64 {
let cal_per_mi = weight
* (0.0395
+ 0.003_27 * (60. / pace_min_per_mile)
+ 0.000_455 * (60. / pace_min_per_mile).pow(2.0)
+ 0.000_801
* ((weight / 154.0) * ... | {
let mut y1 = year;
let mut m1 = month + 1;
if m1 == 13 {
y1 += 1;
m1 = 1;
}
let month: Month = (month as u8).try_into().unwrap_or(Month::January);
let m1: Month = (m1 as u8).try_into().unwrap_or(Month::January);
(Date::from_calendar_date(y1, m1, 1).unwrap_or(date!(1969 - 01... | identifier_body |
garmin_util.rs | ();
let (h, m, s): (i32, i32, f64) = match entries.first() {
Some(h) => match entries.get(1) {
Some(m) => match entries.get(2) {
Some(s) => (h.parse()?, m.parse()?, s.parse()?),
None => (h.parse()?, m.parse()?, 0.),
},
None => (h.parse()?, ... | <T, U, F>(f: T) -> Result<U, Error>
where
T: Fn() -> F,
F: Future<Output = Result<U, Error>>,
{
let mut timeout: f64 = 1.0;
let range = Uniform::from(0..1000);
loop {
match f().await {
Ok(resp) => return Ok(resp),
Err(err) => {
sleep(Duration::from_mil... | exponential_retry | identifier_name |
garmin_util.rs | ();
let (h, m, s): (i32, i32, f64) = match entries.first() {
Some(h) => match entries.get(1) {
Some(m) => match entries.get(2) {
Some(s) => (h.parse()?, m.parse()?, s.parse()?),
None => (h.parse()?, m.parse()?, 0.),
},
None => (h.parse()?, ... |
Ok(())
}
/// # Errors
/// Return error if unzip fails
pub fn extract_zip_from_garmin_connect(
filename: &Path,
ziptmpdir: &Path,
) -> Result<PathBuf, Error> {
extract_zip(filename, ziptmpdir)?;
let new_filename = filename
.file_stem()
.ok_or_else(|| format_err!("Bad filename {}", f... | {
if let Some(mut f) = process.stdout.as_ref() {
let mut buf = String::new();
f.read_to_string(&mut buf)?;
error!("{}", buf);
}
return Err(format_err!("Failed with exit status {exit_status:?}"));
} | conditional_block |
views.py | (response, 'blog/submit-success.html')
def submit(response):
if response.user is not []:
user = response.user
# print(response.POST)
# <QueryDict: {'csrfmiddlewaretoken': ['TyTMLhsydMTLShkiiE2VCBLQPRjME9bbEtdDN2qK87Q7NBSETC137bbpYHXUDGae'], 'start': ['0'], 'duration': ['5'], 'author': ['jack'], 't... | 1>所有直播的播放数已更新</h1>')
def macie_reviewed(response):
clips = []
if response.POST.get('start') is not None:
start = response.POST.get('start')
start = str(start) + "-00:00:00"
start_datetime = datetime.strptime(start, '%m/%d/%Y-%H:%M:%S')
if response.POST.get('end') is not None:
... | ip_view(item)
print("[UPDATE CLIP VIEWS]", count, ' of ', total)
if item.views > 5:
item.rejected = False
item.accepted = False
print("[New Commer!]")
if item.views < 6:
item.rejected = True
print(count, ' has been REJECTED')
it... | conditional_block |
views.py | render(response, 'blog/submit-success.html')
def submit(response):
if response.user is not []:
user = response.user
# print(response.POST)
# <QueryDict: {'csrfmiddlewaretoken': ['TyTMLhsydMTLShkiiE2VCBLQPRjME9bbEtdDN2qK87Q7NBSETC137bbpYHXUDGae'], 'start': ['0'], 'duration': ['5'], 'author': ['jac... | accepted=True, downloaded=False,channel=channel)
return render(response, 'blog/projects-grid-cards.html', {'clips': clips, 'review': False})
def macie_downloaded(response):
clips = []
if response.POST.get('start') is not None:
start = response.POST.get('st... | random_line_split | |
views.py | (response, 'blog/submit-success.html')
def submit(response):
if response.user is not []:
user = response.user
# print(response.POST)
# <QueryDict: {'csrfmiddlewaretoken': ['TyTMLhsydMTLShkiiE2VCBLQPRjME9bbEtdDN2qK87Q7NBSETC137bbpYHXUDGae'], 'start': ['0'], 'duration': ['5'], 'author': ['jack'], 't... | clips = []
if response.POST.get('start') is not None:
start = response.POST.get('start')
start = str(start) + "-00:00:00"
start_datetime = datetime.strptime(start, '%m/%d/%Y-%H:%M:%S')
if response.POST.get('end') is not None:
end = response.POST.get('end')
en... | turn HttpResponse('<h1>Clips Download Started</h1>')
def macie(response):
| identifier_body |
views.py | (response, 'blog/submit-success.html')
def submit(response):
if response.user is not []:
user = response.user
# print(response.POST)
# <QueryDict: {'csrfmiddlewaretoken': ['TyTMLhsydMTLShkiiE2VCBLQPRjME9bbEtdDN2qK87Q7NBSETC137bbpYHXUDGae'], 'start': ['0'], 'duration': ['5'], 'author': ['jack'], 't... | .GET)
if request.GET.get('action') is not None:
action = request.GET.get('action')
if request.GET.get('slug') is not None:
slug = request.GET.get('slug')
if action == 'accept':
clip = Clip.objects.filter(slug=slug)[0]
print('accepting ', clip.t... | nt(request | identifier_name |
main5.py | .append(dev)
dev_states = generate_devs(devices_listing)
toplevel2.destroy()
return dev_states
def generate_devs(dev_in):
dev_states = []
for dev in dev_in:
dev_url = 'http://{}'.format(dev[1].get('ip_address'))
result = pwr_status(dev_url)
dev_status = (result)
... | (dev):
api_call = api_calls.get("active_app")
response = api_req(dev, "get", api_call)
act_app = response.get("active-app").get("app")
return act_app
def dev_status():
dev_states = []
for key,value in dev_list.items():
dev_url = value
result = pwr_status(value)
... | active_app | identifier_name |
main5.py | stream_handler.setFormatter(formatter)
logger.addHandler(file_handler)
logger.addHandler(stream_handler)
def logger_func(orig_func):
import logging
formatter2 = logging.Formatter("%(asctime)s:%(name)s:%(message)s")
file_handler2 = logging.FileHandler("RemoteKu.log")
file_handler2.setFormatter(f... | file_handler = logging.FileHandler("RemoteKu_mainLog.log")
file_handler.setLevel(logging.ERROR)
file_handler.setFormatter(formatter)
stream_handler = logging.StreamHandler()
| random_line_split | |
main5.py |
### This is basics such as variables and holders for devices
global cur_hdmi
stats_counter = 30
counter = 0
running = False
timing = 0
result = "NULL"
msg_box_text = ""
api_port = ":8060"
cur_hdmi = 1
devices_listing = []
root = tkinter.Tk()
root.wm_iconbitmap(default='wicon.ico')
#root.tk_setPalette... | import logging
formatter2 = logging.Formatter("%(asctime)s:%(name)s:%(message)s")
file_handler2 = logging.FileHandler("RemoteKu.log")
file_handler2.setFormatter(formatter2)
logger.addHandler(file_handler2)
def wrapper(*args, **kwargs):
logger.debug("DEBUG log for Func {} with args:{} a... | identifier_body | |
main5.py | .append(dev)
dev_states = generate_devs(devices_listing)
toplevel2.destroy()
return dev_states
def generate_devs(dev_in):
dev_states = []
for dev in dev_in:
dev_url = 'http://{}'.format(dev[1].get('ip_address'))
result = pwr_status(dev_url)
dev_status = (result)
... |
@logger_func
def api_req(dev, api_call):
"""
Function for api GET calls
"""
import xmltodict
import logging
try:
r = requests.get(dev + ':8060' + api_call, timeout=5)
except Exception as exc:
response = ["ERR", exc]
return response[0]
except Co... | print("REQUEST WAS A SUCCESS. DEVICE {} RETURNED: {} ".format(n.get(), str(r)))
r2 = r.text
response = f'{r_code} - OK'
return msg_box(response) | conditional_block |
__init__.py | ournier@gmail.com>
'''
#===============================================================================
# Copyright (c) 2012, Chris Fournier
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# ... |
# If a data file was found
if datafile_found:
# If TSV files were found, load
for name, filepath in files.items():
data[name] = fnc_load(filepath)
else:
# If only dirs were found, recurse
for name, dirpath in dirs.items():
data[name] = load_nested_fol... | path = os.path.join(containing_dir, name)
# Found a directory
if os.path.isdir(path):
dirs[name] = path
# Found a file
elif os.path.isfile(path):
name, ext = os.path.splitext(name)
if len(ext) > 0 and ext.lower() in allowable_extensions:
... | conditional_block |
__init__.py | ournier@gmail.com>
'''
#===============================================================================
# Copyright (c) 2012, Chris Fournier
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# ... | for coder, positions in coder_positions.items():
coder_positions[coder] = convert_positions_to_masses(positions)
# Return
return coder_positions
def input_linear_mass_json(json_filename):
'''
Load a segment mass JSON file.
:param json_filename: path to the mass file containing seg... | coder_positions = input_linear_mass_tsv(tsv_filename, delimiter)
# Convert each segment position to masses | random_line_split |
__init__.py | ournier@gmail.com>
'''
#===============================================================================
# Copyright (c) 2012, Chris Fournier
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# ... | dirs = dict()
# For each filesystem item
for name in os.listdir(containing_dir):
path = os.path.join(containing_dir, name)
# Found a directory
if os.path.isdir(path):
dirs[name] = path
# Found a file
elif os.path.isfile(path):
name, ext = os.pa... | '''
Loads TSV files from a file directory structure, which reflects the
directory structure in nested :func:`dict` with each directory name
representing a key in these :func:`dict`.
:param containing_dir: Root directory containing sub-directories which
contain segmentati... | identifier_body |
__init__.py | ier@gmail.com>
'''
#===============================================================================
# Copyright (c) 2012, Chris Fournier
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Re... | (containing_dir, filetype):
'''
Loads TSV files from a file directory structure, which reflects the
directory structure in nested :func:`dict` with each directory name
representing a key in these :func:`dict`.
:param containing_dir: Root directory containing sub-directories which
... | load_nested_folders_dict | identifier_name |
report.py | saved to tsv if file_as_tsv=True and not replace; saved as file_stem+'_df.csv'.
"""
if file_stem is None or problem is None:
print('file_stem and problem must have a value.')
return
t = '\t'
# input/output file suffixes:
sfx = ['.csv', '_df.csv']
# Try retrieving ... | dflist = []
for f in pfiles:
df, err = get_results_df(f, problem)
if df is not None:
df = df.merge(specs)
df['index'] = df['Searcher'].apply(lambda x: SEARCHES.index(x)+1)
df['index'] = df['index'].astype(int)
df.set_index('index', drop=Tr... | return
| random_line_split |
report.py | saved to tsv if file_as_tsv=True and not replace; saved as file_stem+'_df.csv'.
"""
if file_stem is None or problem is None:
print('file_stem and problem must have a value.')
return
t = '\t'
# input/output file suffixes:
sfx = ['.csv', '_df.csv']
# Try retrieving ... |
else:
print(f'Error from get_results_df:\n\t{err}')
dfout = pd.concat(dflist, ignore_index=False)
dfout.sort_index(inplace=True)
if file_as_tsv:
df2tsv(dfout, fout, replace=replace)
return dfout
def get_results_df(fname, problem):
"""Process csv into... | df = df.merge(specs)
df['index'] = df['Searcher'].apply(lambda x: SEARCHES.index(x)+1)
df['index'] = df['index'].astype(int)
df.set_index('index', drop=True, inplace=True)
dflist.append(df)
del df | conditional_block |
report.py | _rows
top2_fn = fn_cnt[0:2].sum()
pct_top2_fn = top2_fn/n_plans
text = f"Out of {dfa_rows} completed searches, {pct_plans:.0%} ({n_plans}), have {which}-digit or longer PlanLength.<br>"
text += f"In that subset, {top2_fn:d} ({pct_top2_fn:.0%}) involve the search functions `{fn_cnt.index[0]}` and `{fn_c... | """
Wrap an html code str inside a div.
div_style: whatever follows style= within the <div>
Behaviour with `output_string=True`:
The cell is overwritten with the output string (but the cell mode is still in 'code' not 'markdown')
The only thing to do is change the cell mode to Markdown.
If ... | identifier_body | |
report.py | saved to tsv if file_as_tsv=True and not replace; saved as file_stem+'_df.csv'.
"""
if file_stem is None or problem is None:
print('file_stem and problem must have a value.')
return
t = '\t'
# input/output file suffixes:
sfx = ['.csv', '_df.csv']
# Try retrieving ... | (dflist):
"""
Output combined df for complete runs, Actions>0.
"""
dfall = pd.concat(dflist, ignore_index=False)
dfall.reset_index(drop=False, inplace=True)
dfall.rename(columns={'index': 'id'}, inplace=True)
# reduced
drop_cols = dfall.columns[-4:-1].tolist() + ['Problem','Minutes','Goa... | concat_all_dfs | identifier_name |
vpc_controller.go | /controller-runtime/pkg/event"
"sigs.k8s.io/controller-runtime/pkg/predicate"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
"github.com/go-logr/logr"
"k8s.io/apimachinery/pkg/runtime"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
networkv1alpha1 "tencent-cloud-operator/apis... |
}
}
//resource deleted in cloud, update the status
if tencentVpc == nil {
if strings.EqualFold(*vpc.Status.ResourceStatus.Status, "READY") {
*vpc.Status.ResourceStatus.RetryCount = 0
*vpc.Status.ResourceStatus.LastRetry = ""
*vpc.Status.ResourceStatus.Code = ""
*vpc.Status.ResourceStatus.Reason = ""... | {
r.Log.Info("vpc is in error status, and vpc id is empty, retry create")
return r.createVpc(vpc)
} | conditional_block |
vpc_controller.go | /controller-runtime/pkg/event"
"sigs.k8s.io/controller-runtime/pkg/predicate"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
"github.com/go-logr/logr"
"k8s.io/apimachinery/pkg/runtime"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
networkv1alpha1 "tencent-cloud-operator/apis... | // err get resource from cloud, and resource not marked as deleted, something wrong
if err != nil {
log.Printf("error retrive vpc %s status from tencent cloud, just requeue for retry", *vpc.Spec.VpcName)
return err
}
if deleted {
// resource marked as deleted, but status not in deleting or error state, update... | {
// always check for finalizers
deleted := !vpc.GetDeletionTimestamp().IsZero()
pendingFinalizers := vpc.GetFinalizers()
finalizerExists := len(pendingFinalizers) > 0
if !finalizerExists && !deleted && !utils.Contains(pendingFinalizers, common.Finalizer) {
log.Println("Adding finalized &s to resource", common.F... | identifier_body |
vpc_controller.go | /controller-runtime/pkg/event"
"sigs.k8s.io/controller-runtime/pkg/predicate"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
"github.com/go-logr/logr"
"k8s.io/apimachinery/pkg/runtime"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
networkv1alpha1 "tencent-cloud-operator/apis... | (vpc *networkv1alpha1.Vpc) error {
// always check for finalizers
deleted := !vpc.GetDeletionTimestamp().IsZero()
pendingFinalizers := vpc.GetFinalizers()
finalizerExists := len(pendingFinalizers) > 0
if !finalizerExists && !deleted && !utils.Contains(pendingFinalizers, common.Finalizer) {
log.Println("Adding fi... | vpcReconcile | identifier_name |
vpc_controller.go | /controller-runtime/pkg/event"
"sigs.k8s.io/controller-runtime/pkg/predicate"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
"github.com/go-logr/logr"
"k8s.io/apimachinery/pkg/runtime"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
networkv1alpha1 "tencent-cloud-operator/apis... |
func (r *VpcReconciler) createVpc(vpc *networkv1alpha1.Vpc) error {
tencentClient, _ := tcvpc.NewClient(common.GerCredential(), *vpc.Spec.Region, profile.NewClientProfile())
request := tcvpc.NewCreateVpcRequest()
request.VpcName = vpc.Spec.VpcName
request.CidrBlock = vpc.Spec.CidrBlock
request.EnableMulticast = v... | }
return nil
} | random_line_split |
panorama.go | }
func (p *Panorama) updateFrequencyRange() {
if math.IsNaN(float64(p.resolution[p.viewMode])) {
p.setupFrequencyRange()
return
}
var lowerRatio, upperRatio core.Frequency
if p.viewMode == core.ViewFixed && p.frequencyRange.Contains(p.vfo.Frequency) {
lowerRatio = (p.vfo.Frequency - p.frequencyRange.From) /... |
// SetVFO in Hz
func (p *Panorama) SetVFO(vfo core.VFO) {
p.vfo = vfo
if !p.band.Contains(vfo.Frequency) {
band := bandplan.IARURegion1.ByFrequency(vfo.Frequency)
if band.Width() > 0 {
if p.band.Width() > 0 {
p.dbRangeAdjusted = false
}
p.band = band
}
}
log.Printf("vfo %v band %v", p.vfo, p.... | {
return p.frequencyRange.Width()
} | identifier_body |
panorama.go | }
const (
defaultFixedResolution = core.HzPerPx(100)
defaultCenteredResolution = core.HzPerPx(25)
)
// New returns a new instance of panorama.
func New(width core.Px, frequencyRange core.FrequencyRange, vfoFrequency core.Frequency) *Panorama {
result := Panorama{
width: width,
frequencyRange: frequ... | return peakKey(f / 100.0) | random_line_split | |
panorama.go | }
func (p *Panorama) updateFrequencyRange() {
if math.IsNaN(float64(p.resolution[p.viewMode])) {
p.setupFrequencyRange()
return
}
var lowerRatio, upperRatio core.Frequency
if p.viewMode == core.ViewFixed && p.frequencyRange.Contains(p.vfo.Frequency) {
lowerRatio = (p.vfo.Frequency - p.frequencyRange.From) /... | () bool {
return p.signalDetectionActive
}
// ToggleViewMode switches to the other view mode.
func (p *Panorama) ToggleViewMode() {
if p.viewMode == core.ViewFixed {
p.viewMode = core.ViewCentered
} else {
p.viewMode = core.ViewFixed
}
p.updateFrequencyRange()
}
// ViewMode returns the currently active view ... | SignalDetectionActive | identifier_name |
panorama.go | }
func (p *Panorama) updateFrequencyRange() {
if math.IsNaN(float64(p.resolution[p.viewMode])) {
p.setupFrequencyRange()
return
}
var lowerRatio, upperRatio core.Frequency
if p.viewMode == core.ViewFixed && p.frequencyRange.Contains(p.vfo.Frequency) {
lowerRatio = (p.vfo.Frequency - p.frequencyRange.From) /... |
p.zoomTo(p.band.Expanded(1000))
}
func (p *Panorama) zoomTo(frequencyRange core.FrequencyRange) {
p.viewMode = core.ViewFixed
p.frequencyRange = frequencyRange
p.resolution[p.viewMode] = calcResolution(p.frequencyRange, p.width)
}
// ResetZoom to the default of the current view mode
func (p *Panorama) ResetZoom(... | {
return
} | conditional_block |
intrinsicck.rs | ::abi::RustIntrinsic;
use syntax::ast::DefId;
use syntax::ast;
use syntax::ast_map::NodeForeignItem;
use syntax::codemap::Span;
use syntax::parse::token;
use syntax::visit::Visitor;
use syntax::visit;
pub fn check_crate(tcx: &ctxt) {
let mut visitor = IntrinsicCheckingVisitor {
tcx: tcx,
param_envs... | (&self, def_id: DefId) -> bool {
let intrinsic = match ty::lookup_item_type(self.tcx, def_id).ty.sty {
ty::ty_bare_fn(_, ref bfty) => bfty.abi == RustIntrinsic,
_ => return false
};
if def_id.krate == ast::LOCAL_CRATE {
match self.tcx.map.get(def_id.node) {
... | def_id_is_transmute | identifier_name |
intrinsicck.rs | abi::RustIntrinsic;
use syntax::ast::DefId;
use syntax::ast;
use syntax::ast_map::NodeForeignItem;
use syntax::codemap::Span;
use syntax::parse::token;
use syntax::visit::Visitor;
use syntax::visit;
pub fn check_crate(tcx: &ctxt) {
let mut visitor = IntrinsicCheckingVisitor {
tcx: tcx,
param_envs: ... |
}
impl<'a, 'tcx, 'v> Visitor<'v> for IntrinsicCheckingVisitor<'a, 'tcx> {
fn visit_fn(&mut self, fk: visit::FnKind<'v>, fd: &'v ast::FnDecl,
b: &'v ast::Block, s: | {
debug!("Pushing transmute restriction: {}", restriction.repr(self.tcx));
self.tcx.transmute_restrictions.borrow_mut().push(restriction);
} | identifier_body |
intrinsicck.rs | ::abi::RustIntrinsic;
use syntax::ast::DefId;
use syntax::ast; | use syntax::codemap::Span;
use syntax::parse::token;
use syntax::visit::Visitor;
use syntax::visit;
pub fn check_crate(tcx: &ctxt) {
let mut visitor = IntrinsicCheckingVisitor {
tcx: tcx,
param_envs: Vec::new(),
dummy_sized_ty: tcx.types.isize,
dummy_unsized_ty: ty::mk_vec(tcx, tcx.... | use syntax::ast_map::NodeForeignItem; | random_line_split |
beautyleg7_spider.py | .start_urls:
yield scrapy.Request(url)
def parse(self, response):
if self.db_session is None:
self.logger.error("db_session is None")
return None
repeated_count = 0
if response is None:
self.logger.warn("响应为空,不做处理!")
else:
... | identifier_body | ||
beautyleg7_spider.py | itui', 'xingganmeinv', 'weimeixiezhen', 'ribenmeinv']
start_urls = [('http://www.beautyleg7.com/' + category) for category in category_list]
const.REPEATED_THRESHOLD = 10
def __init__(self, name=None, **kwargs):
super().__init__(name=None, **kwargs)
self.db_session = None
self.ge... | self.redis_cmd.setnx(self.album_last_item_redis_unique_key, 0)
for album_node in album_nodes:
album_url = album_node.css('.p a::attr(href)').extract_first().strip()
# 判断当前主题url是否已持久化
is_persisted = self.redis_cmd.get(album_url)
... | se.css('.pic .item')
category = response.css('.sitepath a')[1].css('a::text').extract_first().strip()
# 判断最后一页的最后主题是否被持久化
is_persisted_last_item = self.redis_cmd.get(self.album_last_item_redis_unique_key)
is_last_item_finished = False
if is_persisted_last_ite... | conditional_block |
beautyleg7_spider.py |
import gevent
import requests
import scrapy
from gevent.pool import Pool
from lxml import etree
from scrapy.http import HtmlResponse
from sqlalchemy import create_engine, func
from sqlalchemy.orm import sessionmaker
from ..items import Album, AlbumImageRelationItem, AlbumItem, AlbumImageItem
from ..utils.const import... | import re
from datetime import datetime | random_line_split | |
beautyleg7_spider.py | ameitui', 'xingganmeinv', 'weimeixiezhen', 'ribenmeinv']
start_urls = [('http://www.beautyleg7.com/' + category) for category in category_list]
const.REPEATED_THRESHOLD = 10
def __init__(self, name=None, **kwargs):
super().__init__(name=None, **kwargs)
self.db_session = None
self... | else:
item_title = response.xpath('//div[@class="content"]/h1/text()')[0].strip()
publish_date = response.xpath('//div[@class="tit"]/span/text()')[0].split(":")[1]
image_link_list = response.xpath('//div[@class="contents"]/a/img')
image_link_list = [image_link.attrib['src... | )').extract()
| identifier_name |
output.rs | Always print the default queue at the very top.
if group_only.is_none() {
let tasks = sorted_tasks.get("default").unwrap();
let headline = get_group_headline(
&"default",
&state.groups.get("default").unwrap(),
*state.settings.daemon.groups.get("default").unwrap()... | print_local_log_output | identifier_name | |
output.rs |
pub fn print_error(message: &str) {
let styled = style_text(message, Some(Color::Red), None);
println!("{}", styled);
}
pub fn print_groups(message: GroupResponseMessage) {
let mut text = String::new();
let mut group_iter = message.groups.iter().peekable();
while let Some((name, status)) = group_... | {
println!("{}", message);
} | identifier_body | |
output.rs | in the queue
if state.tasks.is_empty() {
println!("Task list is empty. Add tasks with `pueue add -- [cmd]`");
return;
}
// Sort all tasks by their respective group;
let sorted_tasks = sort_tasks_by_group(&state.tasks);
// Always print the default queue at the very top.
if grou... | if group.eq("default") {
continue;
}
// Skip unwanted groups, if a single group is requested
if let Some(group_only) = &group_only {
if group_only != group {
continue;
}
}
let headline = get_group_headline(
... | while let Some((group, tasks)) = sorted_iter.next() {
// We always want to print the default group at the very top.
// That's why we print it outside of this loop and skip it in here. | random_line_split |
player.rs | None,
);
// FIXME: Due to a bug in physics sim, other player also gets moved
interaction::set(
reg,
"player",
"player",
Some(interaction::Action::PreventOverlap {
rotate_a: false,
rotate_b: false,
}),
None,
);
}
pub const ... | (
world: &mut World,
_inputs: &[(PlayerId, PlayerInput, Entity)],
) -> Result<(), repl::Error> {
hook::run_input_post_sim(&world)?;
world.write::<hook::CurrentInput>().clear();
world.write::<CurrentInput>().clear();
Ok(())
}
pub mod auth {
use super::*;
pub fn create(world: &mut Worl... | run_input_post_sim | identifier_name |
player.rs | None,
);
// FIXME: Due to a bug in physics sim, other player also gets moved
interaction::set(
reg,
"player",
"player",
Some(interaction::Action::PreventOverlap {
rotate_a: false,
rotate_b: false,
}),
None,
);
}
pub const ... |
pub mod auth {
use super::*;
pub fn create(world: &mut World, owner: PlayerId, pos: Point2<f32>) -> (EntityId, Entity) {
let (id, entity) = repl::entity::auth::create(world, owner, "player", |builder| {
builder.with(Position(pos))
});
let mut hooks = [INVALID_ENTITY_ID; N... | {
hook::run_input_post_sim(&world)?;
world.write::<hook::CurrentInput>().clear();
world.write::<CurrentInput>().clear();
Ok(())
} | identifier_body |
player.rs | pub const DASH_SECS: f32 = 0.3;
pub const DASH_COOLDOWN_SECS: f32 = 2.0;
pub const DASH_ACCEL: f32 = 10000.0;
#[derive(Debug, Clone, BitStore)]
pub struct DashedEvent {
/// Different hook colors for drawing.
pub hook_index: u32,
}
impl Event for DashedEvent {
fn class(&self) -> event::Class {
even... | {
state.dash(-forward);
} | conditional_block | |
player.rs | None,
);
// FIXME: Due to a bug in physics sim, other player also gets moved
interaction::set(
reg,
"player",
"player",
Some(interaction::Action::PreventOverlap {
rotate_a: false,
rotate_b: false,
}),
None,
);
}
pub const ... | fn class(&self) -> event::Class {
event::Class::Order
}
}
/// Component that is attached whenever player input should be executed for an entity.
#[derive(Component, Clone, Debug)]
#[storage(BTreeStorage)]
pub struct CurrentInput(pub PlayerInput, [bool; NUM_TAP_KEYS]);
impl CurrentInput {
fn new(in... | impl Event for DashedEvent { | random_line_split |
Index.js | Select.Option;
const {RangePicker} = DatePicker;
message.config({
top: 100,
duration: 3,
});
let customCondition = {};
let applyData = {
size: 40,
current: 1,
ascs: [],
descs: ['createTime'],
condition: customCondition
};
// let params = {
// size: 100,
// current: 1,
// ascs: [],... | ;
// 日期筛选
handleRangePicker = (rangePickerValue, dateString) => {
this.setState({
orderDate: rangePickerValue
});
applyData.current = 1;
customCondition.startTime = parseInt(new Date(new Date(rangePickerValue[0]).toLocaleDateString()).getTime()/1000);
customC... | {
this.getSubjectListFn()
this.getPlatformListFn()
connect(getToken('username'));
} | identifier_body |
Index.js | = Select.Option;
const {RangePicker} = DatePicker;
message.config({
top: 100,
duration: 3,
});
let customCondition = {};
let applyData = {
size: 40,
current: 1,
ascs: [],
descs: ['createTime'],
condition: customCondition
};
// let params = {
// size: 100,
// current: 1,
// ascs: [... | const menus = [
{
path: '/app/dashboard/analysis',
name: '首页'
},
{
path: '#',
name: '线索I/O'
},
{
path: '/app/export/index',
name: '线索I/O'
}
... | spinning
} = this.state;
| random_line_split |
Index.js | = Select.Option;
const {RangePicker} = DatePicker;
message.config({
top: 100,
duration: 3,
});
let customCondition = {};
let applyData = {
size: 40,
current: 1,
ascs: [],
descs: ['createTime'],
condition: customCondition
};
// let params = {
// size: 100,
// current: 1,
// ascs: [... | extends Component {
constructor(props) {
super(props);
this.state = {
orderDate: null,
subjectList: null,
platformList: null,
subjectValue: null,
platformValue: null,
newCampaignNums: 0,
countNums: 0,
newClueNums: 0,
... | exportList | identifier_name |
csv_to_json.py | a file containing one json per line. Careful the output is not a correct json (default=\'False\')')
parser.add_argument("--infer_types", action='store_true', default=False, help='Infer data type based on its value: float, list and date are supported. Carefull, \'config\' will override it if specified. (default=\'F... | (x):
"""
Infer type of a string input.
:param x: input as a string
:return: return x cast to type infered or x itself if no type was infered
"""
str_to_types = [ast.literal_eval,
int,
float,
lambda x: dateutil.parser.parse... | infer_type | identifier_name |
csv_to_json.py | a file containing one json per line. Careful the output is not a correct json (default=\'False\')')
parser.add_argument("--infer_types", action='store_true', default=False, help='Infer data type based on its value: float, list and date are supported. Carefull, \'config\' will override it if specified. (default=\'F... |
else:
if beg:
jsf.write('[\n')
jsf.write(
',\n'.join(json.dumps(i) for i in json_doc)
)
if end:
jsf.write('\n]')
else:
jsf.write(',\n')
def str_to_type(name_type):
"""
Get t... | jsf.write(
'\n'.join(json.dumps(i) for i in json_doc) + '\n'
) | conditional_block |
csv_to_json.py | Dump a file containing one json per line. Careful the output is not a correct json (default=\'False\')')
parser.add_argument("--infer_types", action='store_true', default=False, help='Infer data type based on its value: float, list and date are supported. Carefull, \'config\' will override it if specified. (default... | print(' [INFO] Creating json\'s structure')
jstruct = create_json_structure(header_csv, delimiter)
print(jstruct)
# Read csv line by line and create list of json
print(' [INFO] Filling json')
js_content = []
with open(csv_file, 'r') as f:
reader = csv.DictReader(f, delimiter=co... | """
Create one json for a whole csv
:param csv_file: path to csv file
:param delimiter: delimiter of the nested json (delimiter inside a column)
:param cols_delimiter: delimiter of the columns in the csv
:param keep: if true write None values instead of skipping them
:pa... | identifier_body |
csv_to_json.py | Dump a file containing one json per line. Careful the output is not a correct json (default=\'False\')')
parser.add_argument("--infer_types", action='store_true', default=False, help='Infer data type based on its value: float, list and date are supported. Carefull, \'config\' will override it if specified. (default... | :param name_type: string containing name_type
:return: type or function to cast to specific type
"""
if name_type == 'float' or name_type == 'Float':
return float
if name_type == 'bool':
return bool
if name_type == 'int':
return lambda x: int(float(x... | """
Get type from string
| random_line_split |
proto_utils.go | .Low,
High: i.High,
}
}
func colToVizierCol(col *schemapb.Column) (*vizierpb.Column, error) {
switch c := col.ColData.(type) {
case *schemapb.Column_BooleanData:
return &vizierpb.Column{
ColData: &vizierpb.Column_BooleanData{
BooleanData: &vizierpb.BooleanColumn{
Data: c.BooleanData.Data,
},
... | {
for _, node := range fragment.Nodes {
if node.Op.OpType == planpb.GRPC_SINK_OPERATOR {
grpcSink := node.Op.GetGRPCSinkOp()
outputTableInfo := grpcSink.GetOutputTable()
if outputTableInfo == nil {
continue
}
relation := &schemapb.Relation{
Columns: []*schemapb.Relation_Colum... | conditional_block | |
proto_utils.go |
case *schemapb.Column_Float64Data:
return &vizierpb.Column{
ColData: &vizierpb.Column_Float64Data{
Float64Data: &vizierpb.Float64Column{
Data: c.Float64Data.Data,
},
},
}, nil
case *schemapb.Column_StringData:
b := make([][]byte, len(c.StringData.Data))
for i, s := range c.StringData.Data ... | {
var results []*vizierpb.ExecuteScriptResponse
schemas := OutputSchemaFromPlan(planMap)
for tableName, schema := range schemas {
tableID, present := tableIDMap[tableName]
if !present {
return nil, fmt.Errorf("Table ID for table name %s not found in table map", tableName)
}
convertedRelation := AgentRel... | identifier_body | |
proto_utils.go | = map[statuspb.Code]codes.Code{
statuspb.OK: codes.OK,
statuspb.CANCELLED: codes.Canceled,
statuspb.UNKNOWN: codes.Unknown,
statuspb.INVALID_ARGUMENT: codes.InvalidArgument,
statuspb.DEADLINE_EXCEEDED: codes.DeadlineExceeded,
statuspb.NOT_FOUND: codes.N... | (i *typespb.UInt128) *vizierpb.UInt128 {
return &vizierpb.UInt128{
Low: i.Low,
High: i.High,
}
}
func colToVizierCol(col *schemapb.Column) (*vizierpb.Column, error) {
switch c := col.ColData.(type) {
case *schemapb.Column_BooleanData:
return &vizierpb.Column{
ColData: &vizierpb.Column_BooleanData{
Bo... | UInt128ToVizierUInt128 | identifier_name |
proto_utils.go | },
},
}, nil
case *schemapb.Column_Uint128Data:
b := make([]*vizierpb.UInt128, len(c.Uint128Data.Data))
for i, s := range c.Uint128Data.Data {
b[i] = UInt128ToVizierUInt128(s)
}
return &vizierpb.Column{
ColData: &vizierpb.Column_Uint128Data{
Uint128Data: &vizierpb.UInt128Column{
Data: b,
... | cols = append(cols, newCol)
}
return &vizierpb.Relation{
Columns: cols, | random_line_split | |
setuptool.go | Url")
}
func (e configEditor) addService(term *terminal) {
s := &config.Service{}
serviceEditor{e.c, s}.newSetup(term)
e.c.Services = append(e.c.Services, s)
}
func (e configEditor) editService(term *terminal) {
if len(e.c.Services) == 0 {
fmt.Println("There are no services to edit.")
return
}
fmt.Println... |
func (e oauthServiceCredsEditor) edit(term *terminal) {
takeActionLoop(term,
newAction("Edit Client Id", e.setClientId),
newAction("Edit Client Secret", e.setClientSecret),
newAction("Edit Auth Url", e.setAuthURL),
newAction("Edit Token Url", e.setTokenURL),
newAction("Edit Scopes", e.setScopes),
)
}
fun... | {
e.setClientId(term)
e.setClientSecret(term)
e.setAuthURL(term)
e.setTokenURL(term)
e.setScopes(term)
} | identifier_body |
setuptool.go |
takeActionLoop(term,
newAction("Retrieve Account Key", e.retrieveAccountKey),
newAction("Edit Web Api Gateway Url", e.editUrl),
newAction("Add service", e.addService),
newAction("Edit service (including adding new accounts to an existing service)", e.editService),
newAction("Delete service", e.removeServic... | {
e.editUrl(term)
} | conditional_block | |
setuptool.go | (err)
return
}
fmt.Println()
fmt.Println("Copy and paste everything from (and including) KEYBEGIN to KEYEND")
fmt.Println()
fmt.Println(key)
fmt.Println()
fmt.Println()
}
////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////... | confirmRename | identifier_name | |
setuptool.go | func (e configEditor) retrieveAccountKey(term *terminal) {
fmt.Println("Select which account:")
type accountSpecific struct {
s *config.Service
a *config.Account
}
allAccounts := make([]accountSpecific, 0)
for _, s := range e.c.Services {
for _, a := range s.Accounts {
allAccounts = append(allAccounts,... | encodedAuthCode := term.readSimpleString()
jsonAuthCode, err := base64.StdEncoding.DecodeString(encodedAuthCode)
if err != nil { | random_line_split | |
myAgents.py | denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).
# Student side autograding was added by Brad Miller, Nick Hay, and
# Pieter Abbeel (pabbeel@cs.berkeley.edu).
from game import Agent
from game import Directions
from game import Actions
from searchProblems import PositionSearchProblem
import util
import t... |
def getAction(self, state):
return self.findPathToClosestDot(state)[0]
class AnyFoodSearchProblem(PositionSearchProblem):
"""
A search problem for finding a path to any food.
This search problem is just like the PositionSearchProblem, but has a
different goal test, which you need to fill... | """
Returns a path (a list of actions) to the closest dot, starting from
gameState.
"""
# Here are some useful elements of the startState
startPosition = gameState.getPacmanPosition(self.index)
food = gameState.getFood()
walls = gameState.getWalls()
proble... | identifier_body |
myAgents.py | denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).
# Student side autograding was added by Brad Miller, Nick Hay, and
# Pieter Abbeel (pabbeel@cs.berkeley.edu).
from game import Agent
from game import Directions
from game import Actions
from searchProblems import PositionSearchProblem
import util
import t... | (PositionSearchProblem):
"""
A search problem for finding a path to any food.
This search problem is just like the PositionSearchProblem, but has a
different goal test, which you need to fill in below. The state space and
successor function do not need to be changed.
The class definition abov... | AnyFoodSearchProblem | identifier_name |
myAgents.py | Directions.EAST
west = Directions.WEST
reverse = {north:south, south:north, east:west, west:east}
class MyAgent(Agent):
"""
Implementation of your agent.
"""
customFood = None
foodLeft = 0
specialWalls = {}
finding = []
def getAction(self, state):
"""
Returns the next a... | i += 1
state = fringe.pop()
succ = state[0][0]
act = state[0][1]
cost = state[0][2]
dirList = state[1]
dirList.append(act)
if problem.isGoalState(succ):
return dirList
if problem.isPacman(succ):
followPac.append(dirList.cop... | conditional_block | |
myAgents.py | denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).
# Student side autograding was added by Brad Miller, Nick Hay, and
# Pieter Abbeel (pabbeel@cs.berkeley.edu).
from game import Agent
from game import Directions
from game import Actions
from searchProblems import PositionSearchProblem
import util
import t... | self.path = None
if not self.path and MyAgent.foodLeft > 0:
problem = MySearchProblem(state, self.index, min(foodCount, MyAgent.foodLeft), MyAgent.customFood, MyAgent.specialWalls, MyAgent.finding)
self.path = cbfs(problem)
nx, ny = x, y
... | MyAgent.specialWalls[(x, y)] = self.path[1] | random_line_split |
user_mgt.go | u.request()
req.DisableUser = disabled
if !disabled {
req.ForceSendFields = append(req.ForceSendFields, "DisableUser")
}
return u
}
// DisplayName setter.
func (u *UserToUpdate) DisplayName(name string) *UserToUpdate {
u.request().DisplayName = name
u.displayName = true
return u
}
// Email setter.
func (u *... | random_line_split | ||
user_mgt.go | (ic identitytoolkitCall) {
ic.Header().Set("X-Client-Version", c.version)
}
// UserInfo is a collection of standard profile information for a user.
type UserInfo struct {
DisplayName string
Email string
PhoneNumber string
PhotoURL string
// In the ProviderUserInfo[] ProviderID can be a short domain name... | setHeader | identifier_name | |
user_mgt.go |
}
if u.email {
if err := validateEmail(req.Email); err != nil {
return nil, err
}
}
if u.phoneNumber {
if err := validatePhone(req.PhoneNumber); err != nil {
return nil, err
}
}
if u.photoURL {
if err := validatePhotoURL(req.PhotoUrl); err != nil {
return nil, err
}
}
if req.Password != ""... | {
return nil, err
} | conditional_block | |
user_mgt.go | == "" {
req.DeleteProvider = append(req.DeleteProvider, "phone")
} else if err := validatePhone(req.PhoneNumber); err != nil {
return nil, err
}
}
if u.customClaims {
cc, err := marshalCustomClaims(u.claims)
if err != nil {
return nil, err
}
req.CustomAttributes = cc
}
if req.Password != "" {
... | {
return internal.HasErrorCode(err, userNotFound)
} | identifier_body | |
bagpreparer.go | chan *bagman.IngestHelper
UnpackChannel chan *bagman.IngestHelper
CleanUpChannel chan *bagman.IngestHelper
ResultsChannel chan *bagman.IngestHelper
ProcUtil *bagman.ProcessUtil
largeFile1 string
largeFile2 string
}
func NewBagPreparer(procUtil *bagman.ProcessUtil) (*BagPreparer) {
bagPreparer ... | (message *nsq.Message) error {
message.DisableAutoResponse()
var s3File bagman.S3File
err := json.Unmarshal(message.Body, &s3File)
if err != nil {
bagPreparer.ProcUtil.MessageLog.Error("Could not unmarshal JSON data from nsq:",
string(message.Body))
message.Finish()
return nil
}
// If we're not reproces... | HandleMessage | identifier_name |
bagpreparer.go | chan *bagman.IngestHelper
UnpackChannel chan *bagman.IngestHelper
CleanUpChannel chan *bagman.IngestHelper
ResultsChannel chan *bagman.IngestHelper
ProcUtil *bagman.ProcessUtil
largeFile1 string
largeFile2 string
}
func NewBagPreparer(procUtil *bagman.ProcessUtil) (*BagPreparer) {
bagPreparer ... | } else {
// Got S3 file. Untar it.
// And touch the message, so nsqd knows we're making progress.
result.NsqMessage.Touch()
helper.UpdateFluctusStatus(bagman.StageFetch, bagman.StatusPending)
bagPreparer.UnpackChannel <- helper
}
}
}
}
// -- Step 2 of 5 --
// This runs as a go routine to ... | {
for helper := range bagPreparer.FetchChannel {
result := helper.Result
result.NsqMessage.Touch()
s3Key := result.S3File.Key
// Disk needs filesize * 2 disk space to accomodate tar file & untarred files
err := bagPreparer.ProcUtil.Volume.Reserve(uint64(s3Key.Size * 2))
if err != nil {
// Not enough roo... | identifier_body |
bagpreparer.go |
ProcUtil *bagman.ProcessUtil
largeFile1 string
largeFile2 string
}
func NewBagPreparer(procUtil *bagman.ProcessUtil) (*BagPreparer) {
bagPreparer := &BagPreparer{
ProcUtil: procUtil,
}
// Set up buffered channels
fetcherBufferSize := procUtil.Config.PrepareWorker.NetworkConnections * 4
workerB... | result := helper.Result
if result.ErrorMessage != "" {
// Unpack failed. Go to end. | random_line_split | |
bagpreparer.go | Date,
}
statusRecords, err := bagPreparer.ProcUtil.FluctusClient.ProcessStatusSearch(processStatus, true, true)
if err != nil {
bagPreparer.ProcUtil.MessageLog.Error("Error fetching status info on bag %s " +
"from Fluctus. Will retry in 5 minutes. Error: %v", s3File.Key.Key, err)
message.Requeue(5 * time.Minu... | {
bagPreparer.ProcUtil.MessageLog.Info("Done with largeFile1 %s", result.S3File.Key.Key)
bagPreparer.largeFile1 = ""
} | conditional_block | |
startService.py | 1024 * 1024)]
channel = grpc.insecure_channel('127.0.0.1:23456', options=options)
print("2.新建一个stub,通过这个stub对象可以调用所有服务器提供的接口")
self.stub = perfdog_pb2_grpc.PerfDogServiceStub(channel)
print("3.通过令牌登录,令牌可以在官网申请")
userInfo = self.stub.loginWithToken(
... | 5bd1ec676cbef4b90435234786c1"
uuid = ""
pref = PerfdogService(package,path,token,"Test",uuid)
print(pref)
pref.StopPerf()
| identifier_body | |
startService.py | from enum import Enum
import grpc
from . import perfdog_pb2, perfdog_pb2_grpc
class SaveFormat(Enum):
NONE = 0,
JSON = 1,
PB = 2,
EXCEL = 3,
ALL = 4,
class PerfdogService():
packageName = ''
PerfdogPath = ''
Token = ''
stub = None
device = None
caseName = ''
deviceUu... | import subprocess
import threading
import time
import traceback | random_line_split | |
startService.py |
self.deviceUuid = deviceuuid
self.saveJsonPath = saveJsonPath
self.saveformat = saveFormat
self.uploadServer = UploadServer
def initService(self):
try:
print("0 启动PerfDogService")
# 填入PerfDogService的路径
perfDogService = subprocess.Popen(se... | self.SaveJSON()
else:
print("保存格式为NONE 不保存为文件")
print("13.停止测试")
self.stub.stopTest(perfdog_pb2.StopTestReq(device=self.device))
self.stub.killServer()
print("over")
except Exception as e:
traceback.print_exc()
... | conditional_block | |
startService.py | (Enum):
NONE = 0,
JSON = 1,
PB = 2,
EXCEL = 3,
ALL = 4,
class PerfdogService():
packageName = ''
PerfdogPath = ''
Token = ''
stub = None
device = None
caseName = ''
deviceUuid = ''
saveformat = SaveFormat.ALL
uploadServer = True
saveJsonPath = ''
def __i... | SaveFormat | identifier_name | |
linktypes.rs | 2_11_RADIOTAP: i32 = 127;
/// DLT_ARCNET_LINUX ARCNET Data Packets, as described by the ARCNET Trade Association standard ATA 878.1-1999, but without the Starting Delimiter, Information Length, or Frame Check Sequence fields, with only the first ISU of the Destination Identifier, and with an extra two-ISU "offset" fiel... | /// DLT_AX25_KISS AX.25 packet, with a 1-byte KISS header containing a type indicator.
pub const AX25_KISS: i32 = 202;
/// DLT_LAPD Link Access Procedures on the D Channel (LAPD) frames, as specified by ITU-T Recommendation Q.920 and ITU-T Recommendation Q.921, starting with the address field, with no pseudo-header.
pu... | pub const ERF: i32 = 197;
/// DLT_BLUETOOTH_HCI_H4_WITH_PHDR Bluetooth HCI UART transport layer; the frame contains a 4-byte direction field, in network byte order (big-endian), the low-order bit of which is set if the frame was sent from the host to the controller and clear if the frame was received by the host from t... | random_line_split |
storage.rs | type of all `RaftStorage` interfaces.
pub type StorageResult<T> = Result<T, StorageError>;
//////////////////////////////////////////////////////////////////////////////
// GetInitialState ///////////////////////////////////////////////////////////
/// An actix message type for requesting Raft state information from... | /// state record; and the index of the last log applied to the state machine.
pub struct GetInitialState;
impl Message for GetInitialState {
type Result = StorageResult<InitialState>;
}
/// A struct used to represent the initial state which a Raft node needs when first starting.
pub struct InitialState {
/// ... | /// The storage impl may need to look in a few different places to accurately respond to this
/// request. That last entry in the log for `last_log_index` & `last_log_term`; the node's hard | random_line_split |
storage.rs | (pub Box<dyn Fail>);
/// The result type of all `RaftStorage` interfaces.
pub type StorageResult<T> = Result<T, StorageError>;
//////////////////////////////////////////////////////////////////////////////
// GetInitialState ///////////////////////////////////////////////////////////
/// An actix message type for re... | StorageError | identifier_name | |
hh.js | new Error('open match error');
currentNode = tokens.pop();
currentNode.nodeType = 4;//衔接节点
currentNode.hp = newNode;
newNode.nodeType = 2;
tokens.push(currentNode);
begin = forward + 1;
... | place(/\n/g, '\\n') + "'";
};
};
})();
////////////////////////////////////////////////////////////////////////
// 辅助方法集合
var _helpers = template.helpers = {
$include: template.render,
$string: function (value, type) {
if (typeof value !== 'string') {
type = typeof valu... | identifier_body | |
hh.js |
try {
var Render = _compile(id, source); //编译时错误
} catch (e) {
e.id = id || source;
e.name = 'Syntax Error';
_debug(e);
throw(e);
}
function render (data) {
try {
return new Render(dat... | {
source = params[0];
id = anonymous;
} | conditional_block | |
hh.js | return render;
},
render: function (id, data) {
var cache = template.get(id) || _debug({
id: id,
name: 'Render Error',
message: 'No Template'
});
return cache(data);
},
mapFn: function(func) {
var partialTpl = '';
... | }
| random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.