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 |
|---|---|---|---|---|
main.rs | Snafu {
version_str: version_lock,
})?;
// Convert back to semver::Version
let semver_version_lock =
friendly_version_lock
.try_into()
.context(error::BadVersionSnafu {
version_str: version_lock,
... | random_line_split | ||
main.rs | Snafu {
version_str: version_lock,
})?;
// Convert back to semver::Version
let semver_version_lock =
friendly_version_lock
.try_into()
.context(error::BadVersionSnafu {
version_str: version_lock,
... | () -> Result<()> {
let mut gpt_state = State::load().context(error::PartitionTableReadSnafu)?;
gpt_state.cancel_upgrade();
gpt_state.write().context(error::PartitionTableWriteSnafu)?;
Ok(())
}
fn set_common_query_params(
query_params: &mut QueryParams,
current_version: &Version,
config: &Co... | revert_update_flags | identifier_name |
main.rs | reboot = true;
}
"-a" | "--all" => {
all = true;
}
// Assume any arguments not prefixed with '-' is a subcommand
s if !s.starts_with('-') => {
if subcommand.is_some() {
usage();
}
... | {
// A manifest with a single update whose version exceeds the max version.
// update in manifest has
// - version: 1.25.0
// - max_version: 1.20.0
let path = "tests/data/regret.json";
let manifest: Manifest = serde_json::from_reader(File::open(path).unwrap()).unwrap();
... | identifier_body | |
main.go | (w http.ResponseWriter, r *http.Request) {
fmt.Println("ENTRE")
/* fmt.Fprintf(w, "Welcome to the HomePage!") //IMPRIME EN LA WEB
fmt.Println("Endpoint Hit: homePage")*/ //IMPRIMIR EN CONSOLA AL
b, err := ioutil.ReadFile("mockram.json")
if err != nil { //nil es contrario a null por asi decirlo
fmt.Println("pri... | obtenerram | identifier_name | |
main.go | memorialibre)
ramtotal, err1 := strconv.Atoi(memoriatotal)
ramlibre, err2 := strconv.Atoi(memorialibre)
if err1 == nil && err2 == nil {
ramtotalmb := ramtotal / 1024
ramlibremb := ramlibre / 1024
porcentajeram := ((ramtotalmb - ramlibremb) * 100) / ramtotalmb
//obtengo hora
v1 := time.Now().Format("01-0... |
//c fmt.Println("la memoria libre es ", respuestamem)
//conver := string(crearj)
// fmt.Println("EL indice es ", index)
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.WriteHeader(http.StatusOK)
w.Write(crearj)
// convertir_a_cadena := string(jso... | {
fmt.Println("HAY UN ERROR")
http.Error(w, errorjson.Error(), http.StatusInternalServerError)
return
} | conditional_block |
main.go | index = 60
}*/
if errorjson != nil {
fmt.Println("HAY UN ERROR")
http.Error(w, errorjson.Error(), http.StatusInternalServerError)
return
}
//c fmt.Println("la memoria libre es ", respuestamem)
//conver := string(crearj)
// fmt.Println("EL indice es ", index)
w.Header().Set("Content-Type", "app... | {
fmt.Println("==============================")
fmt.Println("ENTRE A REPLY")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Credentials", "true")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorizat... | identifier_body | |
main.go | memorialibre)
ramtotal, err1 := strconv.Atoi(memoriatotal)
ramlibre, err2 := strconv.Atoi(memorialibre)
if err1 == nil && err2 == nil {
ramtotalmb := ramtotal / 1024
ramlibremb := ramlibre / 1024
porcentajeram := ((ramtotalmb - ramlibremb) * 100) / ramtotalmb
//obtengo hora
v1 := time.Now().Format("01-0... | hayram:=true;
nombre:="";
for _,salto:= range splitsalto{
splitpuntos:=strings.Split(salto,":");
if(splitpuntos[0]=="Name"){
//fmt.Printf("El nombre del proceso con id: %s es: %s\n",nombreArchivo,splitpuntos[1])
textocompleto+=archivo.Name()+",";
aux:=strings.ReplaceAll(splitpuntos[1],"\... | if err != nil {
fmt.Printf("Error leyendo archivo: %v", err)
}
contenido := string(bytesLeidos)
splitsalto:=strings.Split(contenido,"\n"); | random_line_split |
PIL_ext.py | assert np.all(im.size==size for im in X)
# return size
def get_images(files=None, folder=None, op=None, exts=('.jpg','.jpeg','.png')):
"""[summary]
[description]
Keyword Arguments:
files {List[Path]} -- jpg or jpeg files (default: {None})
folder {Path} -- the ... |
def hstack(images, height=None):
'''Stack images horizontally
Arguments:
images {[Image]} -- list of images
Keyword Arguments:
height {Int} -- the common height of images (default: {None})
Returns:
Image -- the result of image stacking
'''
i... | random_line_split | |
PIL_ext.py | np.all(im.size==size for im in X)
# return size
def get_images(files=None, folder=None, op=None, exts=('.jpg','.jpeg','.png')):
"""[summary]
[description]
Keyword Arguments:
files {List[Path]} -- jpg or jpeg files (default: {None})
folder {Path} -- the folder ... | and f.suffix in exts:
im = Image.open(f)
images.append(im)
else:
raise LookupError('Invalid file name %s' % f)
if op:
images = [op(image) for image in images]
return images
def lrmerge(im1, im2, loc=None):
'''Merge left part of `im1` and r... | ))
break
elif f.exists() | conditional_block |
PIL_ext.py | (images, way='row'):
# image -> matrix
if way in {'r', 'row'}:
return np.row_stack([tovector(image) for image in images])
elif way in {'c', 'col', 'column'}:
return np.column_stack([tovector(image) for image in images])
def toimage(vector, size, mode='RGB'):
# vector -> image
... | tomatrix | identifier_name | |
PIL_ext.py | np.all(im.size==size for im in X)
# return size
def get_images(files=None, folder=None, op=None, exts=('.jpg','.jpeg','.png')):
"""[summary]
[description]
Keyword Arguments:
files {List[Path]} -- jpg or jpeg files (default: {None})
folder {Path} -- the folder ... |
assert len(images) == 9, 'exactly 9 images'
return tile([imags[:3], images[3:6], images[6:9]])
def center_paste(image, other):
# put other onto the center of the image
width1, height1 = image.size
width2, height2 = other.size
image.paste(other, ((width1-width2)//2, (height1-height2)/... | ==1:
return images[0]
if n is None:
n = int(np.ceil(np.sqrt(N)))
layout = []
k = 0
while True:
if k+n<N:
layout.append(images[k:k+n])
elif k+n >= N:
layout.append(images[k:])
break
k += n
return tile(layout)
... | identifier_body |
app.py | = True)
producto_id = db.Column(db.Integer, db.ForeignKey('producto.id'))
usuario_id = db.Column(db.Integer, db.ForeignKey('usuario.id'))
cantidad = db.Column(db.Integer)
precio_uni = db.Column(db.Float)
precio_total = db.Column(db.Float)
estado = db.Column(db.String(20))
def __init__(self... | _prods = Producto.query.all()
result = productos_schema.dump(all_prods)
#print(result)
return jsonify(result)
| identifier_body | |
app.py |
usuario_schema = UsuarioSchema() #permite interactuar con un usuario a la vez
usuarios_schema = UsuarioSchema(many=True) #con varios
class ProductoSchema(ma.Schema):
class Meta:
fields = ("id", "nombreProd", "precio", "cantidad", "categoria", "descripcion", "imagen")
producto_schema = ProductoSchema()
pro... | #/////////////////////////////////////// | random_line_split | |
app.py | = Usuario.query.all() #devuelve todos los usuarios
#print("ALL_USERS: ",type(all_users))
#result = usuarios_schema.dump(all_users) #graba la lista de usuario recuperados
#print("RESULT: ",type(result))
#print(result)
#return jsonify(result) #devulve el resultado al cliente en formato JSON
retu... | on.pop("user")
| conditional_block | |
app.py | self, nombreProd, precio, cantidad, categoria, descripcion, imagen):
self.nombreProd = nombreProd
self.precio = precio
self.cantidad = cantidad
self.categoria = categoria
self.descripcion = descripcion
self.imagen = imagen
class Pedido(db.Model):
id = db.Column(db.I... |
form = ProductForm()
if request.method == "GET":
return render_template("AgregarProducto.html",form=form)
else:
if form.validate_on_submit():
nuevo_producto=Producto(nombreProd=form.nombreProd.data, precio=form.precio.data, cantidad=form.cantidad.data, categoria=form.categoria.d... | ate_product(): | identifier_name |
Python3_original.rs | info!("got buffer");
if let Ok(buf_lines) = buffer.get_lines(&mut rvi, 0, -1, false) {
info!("got lines in buffer");
v = buf_lines;
errored = false;
}
}
}
if errored {
retu... | (&self, line: &str, code: &str) -> bool {
info!(
"checking for python module usage: line {} in code {}",
line, code
);
if line.contains('*') {
return true;
}
if line.contains(" as ") {
if let Some(name) = line.split(' ').last() {
... | module_used | identifier_name |
Python3_original.rs | info!("got buffer");
if let Ok(buf_lines) = buffer.get_lines(&mut rvi, 0, -1, false) {
info!("got lines in buffer");
v = buf_lines;
errored = false;
}
}
}
if errored {
return Err(SniprunE... |
}
}
impl Interpreter for Python3_original {
fn new_with_level(data: DataHolder, level: SupportLevel) -> Box<Python3_original> {
//create a subfolder in the cache folder
let rwd = data.work_dir.clone() + "/python3_original";
let mut builder = DirBuilder::new();
builder.recursive... | {
if let Some(venv_array_config) = Python3_original::get_interpreter_option(&self.get_data(), "venv") {
if let Some(actual_vec_of_venv) = venv_array_config.as_array() {
for possible_venv in actual_vec_of_venv.iter() {
if let Some(possible_venv_str)... | conditional_block |
Python3_original.rs | info!("got buffer");
if let Ok(buf_lines) = buffer.get_lines(&mut rvi, 0, -1, false) {
info!("got lines in buffer");
v = buf_lines;
errored = false;
}
}
}
if errored {
retu... | self.code = self.data.current_line.clone();
} else {
self.code = String::from("");
}
Ok(())
}
fn add_boilerplate(&mut self) -> Result<(), SniprunError> {
if !self.imports.is_empty() {
let mut indented_imports = String::new();
for i... | } else if !self.data.current_line.replace(" ", "").is_empty()
&& self.get_current_level() >= SupportLevel::Line
{ | random_line_split |
Python3_original.rs | info!("got buffer");
if let Ok(buf_lines) = buffer.get_lines(&mut rvi, 0, -1, false) {
info!("got lines in buffer");
v = buf_lines;
errored = false;
}
}
}
if errored {
return Err(SniprunE... |
fn get_name() -> String {
String::from("Python3_original")
}
fn behave_repl_like_default() -> bool {
false
}
fn has_repl_capability() -> bool {
true
}
fn default_for_filetype() -> bool {
true
}
fn get_supported_languages() -> Vec<String> {
... | {
// All cli arguments are sendable to python
// Though they will be ignored in REPL mode
Ok(())
} | identifier_body |
launch_fishbowl.py | .coords + self.v
if not self.inside_sphere(self.coords) or self.first:
if not self.first:
forbidden_dirs = [self.pvdi - 1 if self.pvdi != 0 else len(self.allowed_dirs) - 1,
self.pvdi,
self.pvdi + 1 if self.pvdi != len(self.allowed_dirs) - 1 else 0]
available_dirs = np.delete(self.... |
class Enemy(NPC):
def __init__(self, diameter, fishbowl_diameter):
super().__init__(diameter, fishbowl_diameter)
self.original_color = Qt.red
self.color = Qt.red
class Player(NPC):
"""
https://keon.io/deep-q-learning/
"""
def __init__(self, diameter, fishbowl_diameter, state_size):
super().__init__(di... | r -= self.d/2
dist = np.sqrt(np.sum(np.array(p) ** 2))
if dist > r:
return False
else:
return True | identifier_body |
launch_fishbowl.py | ))
# choose an action
action = np.squeeze(self.model.predict(state))
# update player coords
self.coords = self.coords + (action - 1) * 0.002
if not self.inside_sphere(self.coords):
self.coords = self.spherical_clip(self.coords)
# compute reward
reward = 1 / np.min([self.dist(self.coords, x) for x in en... | start_animation | identifier_name | |
launch_fishbowl.py | .coords + self.v
if not self.inside_sphere(self.coords) or self.first:
if not self.first:
forbidden_dirs = [self.pvdi - 1 if self.pvdi != 0 else len(self.allowed_dirs) - 1,
self.pvdi,
self.pvdi + 1 if self.pvdi != len(self.allowed_dirs) - 1 else 0]
available_dirs = np.delete(self.... |
self.first = False
self.v = self.dir * np.random.randint(low=40, high=100, size=2) * 0.00002
self.coords = self.spherical_clip(self.coords)
def check_killed_by(self, player):
p = player.coords
e = self.coords
dist = self.dist(e, p)
if dist < self.d:
self.dead = True
self.color = Qt.gray
@... | chosen_dir = np.random.randint(low=0, high=len(self.allowed_dirs))
self.dir = self.allowed_dirs[chosen_dir, :]
self.pvdi = chosen_dir | conditional_block |
launch_fishbowl.py | .coords
e = self.coords
dist = self.dist(e, p)
if dist < self.d:
self.dead = True
self.color = Qt.gray
@staticmethod
def dist(a, b):
return np.sqrt((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2)
def revive(self):
self.color = self.original_color
self.coords = np.array([0, 0])
self.v = np.array([0, 0]... |
# draw dead enemies
for i, enemy in enumerate([x for x in self.enemies if x.dead]):
qp.setBrush(QBrush(enemy.color, Qt.SolidPattern))
qp.drawEllipse(c + QPoint(*self.scale_point(enemy.coords)), *([self.npc_size] * 2)) | random_line_split | |
frameworks.rs | 02694,
ParametricEQ = 1886217585,
Distortion = 1684632436,
Delay = 1684368505,
SampleDelay = 1935961209,
GraphicEQ = 1735550321,
MultiBandCompressor = 1835232624,
MatrixReverb = 1836213622,
Pitch = 1953329268,
AUFilter = 1718185076,
NetSend = 1853058660,
RogerBeep = 191990360... | MIDIEventList | identifier_name | |
frameworks.rs |
pub const kAudioUnitManufacturer_Apple: u32 = 1634758764;
#[repr(C)] pub struct OpaqueAudioComponent([u8; 0]);
pub type CAudioComponent = *mut OpaqueAudioComponent;
#[repr(C)] pub struct ComponentInstanceRecord([u8; 0]);
pub type CAudioComponentInstance = *mut ComponentInstanceRecord;
pub type CAudioUnit = CAudioCo... | }
};
// CORE AUDIO | random_line_split | |
models.py |
def set_status(self, event, status, detail, level=Level.INFO):
self.status = status
self.save()
self.history.create(event=event, status=status,
status_detail=detail, level=level)
def get_driver_hosts_map(self, host_ids=None):
"""
Stacks are ... | return u'{0} (id={1})'.format(self.title, self.id) | identifier_body | |
models.py | _file.path, 'w') as f:
f.write(pillar_file_yaml)
def generate_global_pillar_file(self, update_formulas=False):
# Import here to not cause circular imports
from stackdio.api.formulas.models import FormulaVersion
from stackdio.api.formulas.tasks import update_formula
... | formula_components | identifier_name | |
models.py | = {}
for account in accounts:
# Target the stack_id and cloud account
target = 'G@stack_id:{0} and G@cloud_account:{1}'.format(
self.id,
account.slug)
groups = {}
for component in account.formula_components.all():
... | # The command to be run (for custom actions)
command = models.TextField('Command')
# The output from the action | random_line_split | |
models.py | event, status, detail, level=Level.INFO):
self.status = status
self.save()
self.history.create(event=event, status=status,
status_detail=detail, level=level)
def get_driver_hosts_map(self, host_ids=None):
"""
Stacks are comprised of multiple host... |
return result
def get_hosts(self, host_ids=None):
"""
Quick way of getting all hosts or a subset for this stack.
@host_ids (list); list of primary keys of hosts in this stack
@returns (QuerySet);
"""
if not host_ids:
return self.hosts.all()
... | result[account.get_driver()] = host_queryset.filter(id__in=[h.id for h in hosts]) | conditional_block |
download_data.py | ': 'La Rioja',
'Madrid': 'Madrid',
'Melilla': 'Melilla',
'Murcia': 'Murcia',
'Navarra': 'Navarra',
'Pais Vasco': 'Pais Vasco'}
#communities_geojson = read_communites_geojson("spain-communites-v2")
def correspondence_string(string, list_to_match):
current_ratio = 0
return_string = None
for string_from... | population = pd.read_csv(f"./data/population/{name}", sep=";")
#population = population[population["Periodo"] == 2019]
#population = population[population["Sexo"] == "Total"]
population.drop(columns=['Periodo', 'Sexo'], inplace=True)
population['Comunidades y Ciudades Autónomas'] = [clean_name_pop(name... | " in pop:
return int(pop.replace(".",""))
| identifier_body |
download_data.py | ': 'La Rioja',
'Madrid': 'Madrid',
'Melilla': 'Melilla',
'Murcia': 'Murcia',
'Navarra': 'Navarra',
'Pais Vasco': 'Pais Vasco'}
#communities_geojson = read_communites_geojson("spain-communites-v2")
def correspondence_string(string, list_to_match):
current_ratio = 0
return_string = None
for string_from... | lat_sum, lon_sum):
# For moving Canary Islands near Spain.
# l is the list of list of lists .... of coordinates
if isinstance(l, list) and isinstance(l[0], float) and isinstance(l[1], float):
return l[0] + lat_sum, l[1] + lon_sum
return [add_to_list(sub, lat_sum, lon_sum) for sub in l]
def red... | to_list(l, | identifier_name |
download_data.py | ': 'La Rioja',
'Madrid': 'Madrid',
'Melilla': 'Melilla',
'Murcia': 'Murcia',
'Navarra': 'Navarra',
'Pais Vasco': 'Pais Vasco'}
#communities_geojson = read_communites_geojson("spain-communites-v2")
def correspondence_string(string, list_to_match):
current_ratio = 0
return_string = None
for string_from... | return result
#download_all_datasets()
def add_to_list(l, lat_sum, lon_sum):
# For moving Canary Islands near Spain.
# l is the list of list of lists .... of coordinates
if isinstance(l, list) and isinstance(l[0], float) and isinstance(l[1], float):
return l[0] + lat_sum, l[1] + lon_su... | lt.append(start_date.strftime(date_format))
start_date += step
| conditional_block |
download_data.py | ': 'La Rioja',
'Madrid': 'Madrid',
'Melilla': 'Melilla',
'Murcia': 'Murcia',
'Navarra': 'Navarra',
'Pais Vasco': 'Pais Vasco'}
#communities_geojson = read_communites_geojson("spain-communites-v2")
def correspondence_string(string, list_to_match):
current_ratio = 0
return_string = None
for string_from... | r'% Población fallecida total'],
inplace = True,
axis = 1)
dfs_desacumulado.sort_values(by = "Día", inplace = True)
return dfs_desacumulado
def correct_names():
def read_population_dataset_custom(name = 'spain-communities-2020.csv... | r'% Población contagiada total', | random_line_split |
lib.rs | mod hasher;
pub mod offchain;
pub mod sr25519;
pub mod testing;
#[cfg(feature = "std")]
pub mod traits;
pub mod uint;
#[cfg(feature = "bls-experimental")]
pub use bls::{bls377, bls381};
pub use self::{
hash::{convert_hash, H160, H256, H512},
uint::{U256, U512},
};
#[cfg(feature = "full_crypto")]
pub use crypto::{By... | (s: &str) -> Result<Self, Self::Err> {
bytes::from_hex(s).map(Bytes)
}
}
/// Stores the encoded `RuntimeMetadata` for the native side as opaque type.
#[derive(Encode, Decode, PartialEq, TypeInfo)]
pub struct OpaqueMetadata(Vec<u8>);
impl OpaqueMetadata {
/// Creates a new instance with the given metadata blob.
p... | from_str | identifier_name |
lib.rs | #[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
use sp_runtime_interface::pass_by::{PassByEnum, PassByInner};
use sp_std::{ops::Deref, prelude::*};
pub use sp_debug_derive::RuntimeDebug;
#[cfg(feature = "serde")]
pub use impl_serde::serialize as bytes;
#[cfg(feature = "full_crypto")]
pub mod hashing;
... | #[cfg(feature = "serde")]
pub use serde; | random_line_split | |
lib.rs | mod hasher;
pub mod offchain;
pub mod sr25519;
pub mod testing;
#[cfg(feature = "std")]
pub mod traits;
pub mod uint;
#[cfg(feature = "bls-experimental")]
pub use bls::{bls377, bls381};
pub use self::{
hash::{convert_hash, H160, H256, H512},
uint::{U256, U512},
};
#[cfg(feature = "full_crypto")]
pub use crypto::{By... |
}
impl codec::WrapperTypeEncode for Bytes {}
impl codec::WrapperTypeDecode for Bytes {
type Wrapped = Vec<u8>;
}
#[cfg(feature = "std")]
impl sp_std::str::FromStr for Bytes {
type Err = bytes::FromHexError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
bytes::from_hex(s).map(Bytes)
}
}
/// Stores the en... | {
&self.0[..]
} | identifier_body |
api.rs | resigning.
#[derive(PartialEq, Debug, Clone, Copy)]
pub enum Move {
Stone(Vertex),
Pass,
Resign
}
/// Represents a move associated with a player.
#[derive(PartialEq, Debug, Clone, Copy)]
pub struct ColouredMove {
pub player: Colour,
pub mov: Move
}
/// The status of a stone : alive, dead or seki.... | fn komi(&mut self, komi: f32) -> ();
/// Sets the board size.
/// Returns `Err(InvalidBoardSize)` if the size is not supported.
/// The protocol cannot handle board sizes > 25x25.
fn boardsize(&mut self, size: usize) -> Result<(), GTPError>;
/// Plays the provided move on the board.
/// Re... | /// Clears the board, can never fail.
fn clear_board(&mut self) -> ();
/// Sets the komi, can never fail, must accept absurd values. | random_line_split |
api.rs | ing.
#[derive(PartialEq, Debug, Clone, Copy)]
pub enum Move {
Stone(Vertex),
Pass,
Resign
}
/// Represents a move associated with a player.
#[derive(PartialEq, Debug, Clone, Copy)]
pub struct ColouredMove {
pub player: Colour,
pub mov: Move
}
/// The status of a stone : alive, dead or seki.
#[deri... | // eliminate 'I'
let number = u8::from_str(&text[1..]);
let mut y: u8 = 0;
match number {
Ok(num) => y = num,
_ => (),
}
if y == 0 || y > 25 {
return None;
}
Some(Vertex{x: x, y: y})
}
/// Returns a tuple of coordinates... |
x -= 1;
} | conditional_block |
api.rs | resigning.
#[derive(PartialEq, Debug, Clone, Copy)]
pub enum Move {
Stone(Vertex),
Pass,
Resign
}
/// Represents a move associated with a player.
#[derive(PartialEq, Debug, Clone, Copy)]
pub struct ColouredMove {
pub player: Colour,
pub mov: Move
}
/// The status of a stone : alive, dead or seki.... | (&self, status: StoneStatus) -> Result<Vec<Vertex>, GTPError> {
Err(GTPError::NotImplemented)
}
/// Computes the bot's calculation of the final score.
/// If it is a draw, float value must be 0 and colour is not important.
/// Can fail with èErr(CannotScore)`.
fn final_score(&self) -> Resul... | final_status_list | identifier_name |
my.rs | {
pub moves: Vec<(i8, i8)>, // (dx, dy)
pub nowater: Vec<Pt>, // (x, y) sorted
pub noobstacles: Vec<Pt>, // (x, y) sorted
pub xmin: i32,
pub xmax: i32,
pub ymin: i32,
pub ymax: i32,
}
#[derive(Debug)]
pub struct Paths {
pub paths: HashMap... | Path | identifier_name | |
my.rs | pub struct Paths {
pub paths: HashMap<usize, HashMap<(i32, i32), Vec<Path>>>,
}
}
struct BallPaths {
count: usize,
ball: usize,
paths: Vec<(paths_builder::Path,usize)>
}
struct Main {
width : usize,
height: usize,
field : Vec<u8>,
holes : Vec<Pt>,
balls : Vec<(Pt, u8)>,... | pub ymax: i32,
}
#[derive(Debug)] | random_line_split | |
my.rs | obstacles : HashSet<Pt>,
ball_paths : Vec<BallPaths>,
}
impl Main {
fn new(width: i32, height: i32) -> Self {
eprintln!("field size: {} x {}", width, height);
Self {
width: width as usize,
height: height as usize,
field: vec![0u8; (width * height) as usize],... |
for pt in path.noobstacles.iter().chain(path.nowater.iter()) {
if used_points.contains(pt) {
continue 'outer;
}
}
if is_leaf {
let mut s : Vec<(usize, Path)> = Vec::new();
s.push((paths.ball, path.cl... | {
continue;
} | conditional_block |
FireBehaviorForecaster.js | flameLength'],
['configure.fire.lengthToWidthRatio', 'lengthToWidthRatio']
])
this.dag.select([
'surface.primary.fuel.model.behave.parms.cured.herb.fraction', // ratio
'surface.primary.fuel.fire.effectiveWindSpeed', // ft/min
'surface.primary.fuel.fire.flameResidenceTime', // min
... | (parms, wxArray) {
wxArray.forEach(wx => {
const input = {
fuel: parms.fuel,
curedHerb: 0.01 * parms.cured,
month: +(wx.date).substr(5, 2),
hour: +(wx.time).substr(0, 2),
elevDiff: parms.elevdiff,
aspect: parms.aspect,
slope: 0.01 * parms.slope,
... | addFireBehavior | identifier_name |
FireBehaviorForecaster.js | inp Array of fire behavior input values
* @returns {object} Fire behavior object
*/
run (inp) {
this.dag.input([
['surface.primary.fuel.model.catalogKey', [inp.fuel]],
['surface.primary.fuel.model.behave.parms.cured.herb.fraction', [inp.curedHerb]], // fraction
['site.date.month', [inp.m... | {
// configure the time frame up to 6 hours back and 15 days out
const now = moment.utc()
parms.start = moment.utc(now).startOf('hour').toISOString() // "2019-03-20T14:09:50Z"
parms.end = moment.utc(now).add(48, 'hours').toISOString()
// First get elevation, slope, and aspect and add it to the parm... | identifier_body | |
FireBehaviorForecaster.js | Array of fire behavior input values
* @returns {object} Fire behavior object
*/
run (inp) {
this.dag.input([
['surface.primary.fuel.model.catalogKey', [inp.fuel]],
['surface.primary.fuel.model.behave.parms.cured.herb.fraction', [inp.curedHerb]], // fraction
['site.date.month', [inp.month]... | {
_wx = getWeatherapi(parms.lat, parms.lon, 1, 'fire')
} | conditional_block | |
FireBehaviorForecaster.js | flameLength'],
['configure.fire.lengthToWidthRatio', 'lengthToWidthRatio']
])
this.dag.select([
'surface.primary.fuel.model.behave.parms.cured.herb.fraction', // ratio
'surface.primary.fuel.fire.effectiveWindSpeed', // ft/min
'surface.primary.fuel.fire.flameResidenceTime', // min
... | 'surface.primary.fuel.fire.heatPerUnitArea', // btu/ft2 |
'surface.primary.fuel.fire.reactionIntensity', // btu/ft2/min
'surface.fire.ellipse.axis.lengthToWidthRatio', // ratio
'surface.fire.ellipse.back.firelineIntensity', // Btu/ft/s
'surface.fire.ellipse.back.flameLength', // ft
'... | 'surface.primary.fuel.fire.heading.fromNorth', // degrees | random_line_split |
slack.go | -ma": "Arabic",
"flag-mc": "French",
"flag-md": "Romanian",
"flag-mg": "Malagasy",
"flag-mh": "Marshallese",
"flag-mk": "Macedonian",
"flag-ml": "French",
"flag-mm": "Burmese",
"flag-mn": "Mongolian",
"flag-mo": "Chinese Traditional",
"flag-mp": "English",
"flag-mq": "French",
"flag-mr": "Arabic",
"flag-ms... | {
params := &slack.GetConversationRepliesParameters{}
params.ChannelID = id
params.Timestamp = ts
params.Inclusive = true
params.Limit = 1
// get slack messages
msg, _, _, err := c.client.GetConversationReplies(params)
if err != nil {
log.Println("[Error] failed to get slack messages: ", err)
return nil, e... | identifier_body | |
slack.go | "Arabic",
"flag-ky": "English",
"flag-kz": "Kazakh",
"flag-la": "Lao",
"flag-lb": "Arabic",
"flag-lc": "English",
"flag-li": "German",
"flag-lk": "Sinhala",
"flag-lr": "English",
"flag-ls": "Sesotho",
"flag-lt": "Lithuanian",
"flag-lu": "Luxembourgish",
"flag-lv": "Latvian",
"flag-ly": "Arabic",
"flag-ma... | getMessage | identifier_name | |
slack.go | ",
"flag-kp": "Korean",
"flag-kr": "Korean",
"flag-kw": "Arabic",
"flag-ky": "English",
"flag-kz": "Kazakh",
"flag-la": "Lao",
"flag-lb": "Arabic",
"flag-lc": "English",
"flag-li": "German",
"flag-lk": "Sinhala",
"flag-lr": "English",
"flag-ls": "Sesotho",
"flag-lt": "Lithuanian",
"flag-lu": "Luxembourgis... | {
log.Println("[Error] failed to post slack messages: ", err)
return err
} | conditional_block | |
slack.go | 482.000119"
},
"type": "event_callback",
"event_id": "Ev97FS5N0Y",
"event_time": 1518507482,
"authed_users": [
"U0G9QF9C6"
]
}
*/
// flag emoji to language
var flagMap = map[string]string{
"flag-ac": "English",
"flag-ad": "Catalan",
"flag-ae": "Arabic",
"flag-af": "Pashto",
"flag-a... | "flag-sh": "English",
"flag-si": "Slovenian",
"flag-sj": "Norwegian",
"flag-sk": "Slovak",
"flag-sl": "English",
"flag-sm": "Italian",
"flag-sn": "French",
"flag-so": "Somali",
"flag-sr": "Dutch",
"flag-ss": "English",
"flag-st": "Portuguese",
" | random_line_split | |
c01_mainChangeover.py | 0
lMinFitness = [10000000000, 'START', [],[],""]
lMinFitness_history = [10000000000]
lFitness_history=[]
lIllegal_history=[]
######################################### 1 DATA IMPORT #########################################
### 1.1 Get Material Family Data
# for now based on excel; check c13_ImportFromSQL.py for SQL... |
#open file to track usage history
filePopulationHistory = open(os.path.join(glob.sPathToExcels, "90_populationHistory.txt"), "w", encoding="utf-8")
fileFitnessHistory_runs = open(os.path.join(glob.sPathToExcels, "91_fitnessRuns.txt"), "a", encoding="utf-8")
######################################### 2 GA SETUP #####... | dMaterialCO[row.materialRel] = row["timeCO"]
glob.lMaterialAtlas_0.append(row["materialAtlas"]) | conditional_block |
c01_mainChangeover.py | 0
lMinFitness = [10000000000, 'START', [],[],""]
lMinFitness_history = [10000000000]
lFitness_history=[]
lIllegal_history=[]
######################################### 1 DATA IMPORT #########################################
### 1.1 Get Material Family Data
# for now based on excel; check c13_ImportFromSQL.py for SQ... | # append calculated fitness for new lowest level
lMinFitness_history.append(fMinFitness)
# create table and calculate selection probabilities
lFitness_sorted = gak.udf_sortByFitness(lFitness)
# initialize population arrays
lPopulation_new = []
lPopulation_new_names = []
dPopulation_new ={}
# select parents... | if lMinFitness[0] <= fMinFitness:
fMinFitness = lMinFitness[0]
| random_line_split |
lib.rs | agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! # gl_generator
//!
//! `gl_genera... | (&self) -> Option<::syntax::util::small_vector::SmallVector<::std::gc::Gc<Item>>> {
Some(::syntax::util::small_vector::SmallVector::many(self.content.clone()))
}
}
// handler for generate_gl_bindings!
fn macro_handler(ecx: &mut ExtCtxt, span: Span, token_tree: &[TokenTree]) -> Box<MacResult+'static> {
... | make_items | identifier_name |
lib.rs | agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! # gl_generator
//!
//! `gl_genera... | Path::new(ecx.codemap().span_to_filename(span)).display().to_string(), content);
// getting all the items defined by the bindings
let mut items = Vec::new();
loop {
match parser.parse_item_with_outer_attributes() {
None => break,
Some(i) => items.push(i)
}
... | return DummyResult::any(span)
}
};
let mut parser = ::syntax::parse::new_parser_from_source_str(ecx.parse_sess(), ecx.cfg(), | random_line_split |
lib.rs | agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! # gl_generator
//!
//! `gl_genera... | }
};
let filter = Some(Filter {
extensions: extensions,
profile: profile,
version: version,
api: api,
});
// generating the registry of all bindings
let reg = {
use std::io::BufReader;
use std::task;
let result = task::try(proc() {
... | {
// getting the arguments from the macro
let (api, profile, version, generator, extensions) = match parse_macro_arguments(ecx, span.clone(), token_tree) {
Some(t) => t,
None => return DummyResult::any(span)
};
let (ns, source) = match api.as_slice() {
"gl" => (Gl, khronos_api:... | identifier_body |
mdx15_print_gerber.py | < (n-2) :
if px >= (self.levelingData[i][j][0]-self.epsilon) and px < self.levelingData[i+1][j][0] : break
i = i+1
while j < (n-2) :
if py >= (self.levelingData[i][j][1]-self.epsilon) and py < self.levelingData[i][j+1][1] : break
j = j+1
# interpolate values
px0 = self.levelingData[i][j][... | time.sleep(travelTime)
#print('move done')
def run(self):
print('If the green light next to the VIEW button is lit, please press the VIEW button.')
print('Usage:')
print('\th - send to home')
print('\tz - Set Z zero')
print('\tZ - send to zero')
print('\twasd - move on the XY plane (+shift for ... | if self.x < 0.0 : self.x = 0.0
if self.x > self.X_MAX : self.x = self.X_MAX
if self.y < 0.0 : self.y = 0.0
if self.y > self.Y_MAX : self.y = self.Y_MAX
#print('Moving to {:.0f},{:.0f},{:.0f}'.format(self.x,self.y,self.z))
spindle = '1' if self.spindleEnabled else '0'
# The esoteric syntax was borrowed fro... | identifier_body |
mdx15_print_gerber.py | = j+1
# interpolate values
px0 = self.levelingData[i][j][0]
px1 = self.levelingData[i+1][j][0]
fx = (px - px0) / (px1 - px0)
h00 = self.levelingData[i][j][2]
h10 = self.levelingData[i+1][j][2]
h0 = h00 + (h10 - h00) * fx
h01 = self.levelingData[i][j+1][2]
h11 = self.levelingData[i+1][j+... | random_line_split | ||
mdx15_print_gerber.py | ),self.x,self.y,self.z))
self.manual_leveling_points.append( (self.x,self.y,self.z) )
def getManualLevelingPoints(self):
return self.manual_leveling_points
def moveTo(self,x,y,z,wait=False):
self.x = x
self.y = y
self.z = z
self.sendMoveCommand(wait)
def getAutolevelingData(self, cam, steps=1, height... | import subprocess
shelloutput = subprocess.check_output('powershell -Command "(Get-WmiObject Win32_Printer -Filter \\"Name=\'{}\'\\").PortName"'.format(options.printerName))
if len(shelloutput)>0 :
try :
serialport = shelloutput.decode('utf-8').split(':')[0]
print( 'Found {} printer driver ({})'.format(o... | conditional_block | |
mdx15_print_gerber.py | :
# stateful variables
inputConversionFactor = 1.0 # mm units
X = 0.0
Y = 0.0
Z = 0.0
speedmode = None
feedrate = 0.0
isFirstCommand = True
offset_x = 0.0
offset_y = 0.0
feedspeedfactor = 1.0
# Backlash compensation related
backlashX = 0
backlashY = 0
backlashZ = 0
last_x = 0
last_y = 0
last_z = 0
... | GCode2RmlConverter | identifier_name | |
core.go | vs := <-e.vserverChan:
if _, ok := e.vservers[svs.Name]; !ok {
log.Infof("Received vserver snapshot for unconfigured vserver %s, ignoring", svs.Name)
break
}
log.V(1).Infof("Updating vserver snapshot for %s", svs.Name)
e.vserverLock.Lock()
e.vserverSnapshots[svs.Name] = svs
e.vserverLock.Unloc... | get | identifier_name | |
core.go | )
e.initNetwork()
n, err := config.NewNotifier(e.config)
if err != nil {
log.Fatalf("config.NewNotifier() failed: %v", err)
}
e.notifier = n
if e.config.AnycastEnabled {
go e.bgpManager.run()
}
go e.hcManager.run()
go e.syncClient.run()
go e.syncServer.run()
go e.syncRPC()
go e.engineIPC()
go e.gr... | else {
e.haManager.disable()
}
node, | {
e.haManager.enable()
} | conditional_block |
core.go | e.initNetwork()
n, err := config.NewNotifier(e.config)
if err != nil {
log.Fatalf("config.NewNotifier() failed: %v", err)
}
e.notifier = n
if e.config.AnycastEnabled {
go e.bgpManager.run()
}
go e.hcManager.run()
go e.syncClient.run()
go e.syncServer.run()
go e.syncRPC()
go e.engineIPC()
go e.gratu... |
// haConfig returns the HAConfig for an engine.
func (e *Engine) haConfig() (*seesaw.HAConfig, error) {
n, err := e.thisNode()
if err != nil {
return nil, err
}
// TODO(jsing): This does not allow for IPv6-only operation.
return &seesaw.HAConfig{
Enabled: n.State != spb.HaState_DISABLED,
LocalAddr: e.c... | {
select {
case e.haManager.statusChan <- status:
default:
return fmt.Errorf("status channel if full")
}
return nil
} | identifier_body |
core.go | log.Infof("Seesaw Engine starting for %s", e.config.ClusterName)
e.initNetwork()
n, err := config.NewNotifier(e.config)
if err != nil {
log.Fatalf("config.NewNotifier() failed: %v", err)
}
e.notifier = n
if e.config.AnycastEnabled {
go e.bgpManager.run()
}
go e.hcManager.run()
go e.syncClient.run()
g... | random_line_split | ||
lib.rs | : String,
quote: String,
color: String,
background_color: String,
) -> CorgiDTO {
let owner = env::predecessor_account_id();
let deposit = env::attached_deposit();
if deposit != MINT_FEE {
panic!("Deposit must be MINT_FEE but was {}", deposit)
}
... | let (key, mut bids, auction_ends) = self.get_auction(&token_id);
let corgi = {
let corgi = self.corgis.get(&key);
assert!(corgi.is_some());
corgi.unwrap()
};
let owner = corgi.owner.clone();
let end_auction = |it, bidder, price| {
i... | identifier_body | |
lib.rs | Corgi`s that have been created.
/// Number of `Corgi`s returned is limited by `PAGE_LIMIT`.
pub fn get_global_corgis(&self) -> Vec<CorgiDTO> {
let mut result = Vec::new();
for (key, corgi) in &self.corgis {
if result.len() >= PAGE_LIMIT as usize {
break;
}... | random_line_split | ||
lib.rs | structure to store auctions for a given corgi.
/// It is a mapping from `CorgiKey` to a tuple.
/// The first component of the tuple is a `Dict`, which represents the bids for that corgi.
/// Each entry in this `Dict` maps the bidder (`AccountId`) to the bid price and bidding timestamp.
/// The seconds ... | -> Self {
env::log(format!("init v{}", env!("CARGO_PKG_VERSION")).as_bytes());
Self {
corgis: Dict::new(CORGIS.to_vec()),
corgis_by_owner: UnorderedMap::new(CORGIS_BY_OWNER.to_vec()),
auctions: UnorderedMap::new(AUCTIONS.to_vec()),
}
}
}
#[near_bindgen]
... | fault() | identifier_name |
index.js | 'use strict';
import React, { Component } from 'react';
import { Image, View, Switch, TouchableOpacity, Platform ,TextInput} from 'react-native';
import { connect } from 'react-redux';
import {Actions} from 'react-native-router-flux';
import { Container, Header, Content, Text, Button, Icon, Thumbnail, InputGroup, Inpu... | if(email === '') {
if(!message) {
message = 'Email không được để trống'
} else {
message += '\nEmail không được để trống';
}
}
if (user.memberInfo.member.facebook.name
&& objUpdate.name.trim() === _.get(user, 'memberInfo.member.name', '')
... | message += 'Họ và tên không được để trống';
} | random_line_split |
index.js | 'use strict';
import React, { Component } from 'react';
import { Image, View, Switch, TouchableOpacity, Platform ,TextInput} from 'react-native';
import { connect } from 'react-redux';
import {Actions} from 'react-native-router-flux';
import { Container, Header, Content, Text, Button, Icon, Thumbnail, InputGroup, Inpu... |
updateProfile(objUpdate) {
var {dispatch,user} = this.props;
dispatch(UserActions_MiddleWare.updateProfile(objUpdate))
.then(()=>{
globalVariableManager.rootView.showToast('Cập nhật thông tin thành công');
dispatch(UserActions_MiddleWare.get())
.then(() => {
if(... | {
super(props);
let {user} = this.props;
this.state = {};
this.handleUpdateProfile = this.handleUpdateProfile.bind(this);
this.userInfo={
Username: _.get(user, 'memberInfo.member.name', ''),
email: _.get(user, 'memberInfo.member.email', ''),
phone: _.get(user, 'mem... | identifier_body |
index.js | 'use strict';
import React, { Component } from 'react';
import { Image, View, Switch, TouchableOpacity, Platform ,TextInput} from 'react-native';
import { connect } from 'react-redux';
import {Actions} from 'react-native-router-flux';
import { Container, Header, Content, Text, Button, Icon, Thumbnail, InputGroup, Inpu... | (objUpdate) {
var {dispatch,user} = this.props;
dispatch(UserActions_MiddleWare.updateProfile(objUpdate))
.then(()=>{
globalVariableManager.rootView.showToast('Cập nhật thông tin thành công');
dispatch(UserActions_MiddleWare.get())
.then(() => {
if(this.forceUpdate) {... | updateProfile | identifier_name |
index.js | 'use strict';
import React, { Component } from 'react';
import { Image, View, Switch, TouchableOpacity, Platform ,TextInput} from 'react-native';
import { connect } from 'react-redux';
import {Actions} from 'react-native-router-flux';
import { Container, Header, Content, Text, Button, Icon, Thumbnail, InputGroup, Inpu... | if(!message) {
message = 'Email không được để trống'
} else {
message += '\nEmail không được để trống';
}
}
if (user.memberInfo.member.facebook.name
&& objUpdate.name.trim() === _.get(user, 'memberInfo.member.name', '')
&& objUpdate.email.trim() ==... | e += 'Họ và tên không được để trống';
}
if(email === '') {
| conditional_block |
main.rs | 1);
let pred_file = File::open(pred_path)?;
let mut pred_reader = Reader::new(BufReader::new(pred_file));
let mut deprel_confusion = Confusion::<String>::new("Deprels");
let mut distance_confusion = Confusion::<usize>::new("Dists");
let skip_punct = matches.is_present(SKIP_PUNCTUATION);
let ... |
impl<V> Confusion<V> where V: ToString {
fn write_accuracies(&self, mut w: impl Write) -> Result<(), Error> {
for (idx, item) in self.numberer.idx2val.iter().map(V::to_string).enumerate() {
let row = &self.confusion[idx];
let correct = row[idx];
let total = row.iter().s... | } | random_line_split |
main.rs | 1);
let pred_file = File::open(pred_path)?;
let mut pred_reader = Reader::new(BufReader::new(pred_file));
let mut deprel_confusion = Confusion::<String>::new("Deprels");
let mut distance_confusion = Confusion::<usize>::new("Dists");
let skip_punct = matches.is_present(SKIP_PUNCTUATION);
let ... |
Ok(())
}
static DEFAULT_CLAP_SETTINGS: &[AppSettings] = &[
AppSettings::DontCollapseArgsInUsage,
AppSettings::UnifiedHelpMessage,
];
// Argument constants
static VALIDATION: &str = "VALIDATION";
static PREDICTION: &str = "PREDICTION";
static DEPREL_CONFUSION: &str = "deprel_confusion";
static DEPREL_ACCU... | {
let out = File::create(file_name).unwrap();
let mut writer = BufWriter::new(out);
distance_confusion.write_accuracies(&mut writer).unwrap();
} | conditional_block |
main.rs | unct {
if val_token.pos().expect("Validation token missing POS").starts_with("PUNCT") {
continue
}
}
let idx = idx+1 ;
let val_triple = val_sentence.dep_graph().head(idx).unwrap();
let val_head = val_triple.head();
... | Numberer | identifier_name | |
main.rs | ::abs(val_head as i64 - idx as i64) as usize;
let val_rel = val_triple.relation().unwrap();
let pred_triple = pred_sentence.dep_graph().head(idx).unwrap();;
let pred_head = pred_triple.head();
let pred_dist = i64::abs(pred_head as i64 - idx as i64) as usize;
l... | {
Numberer {
val2idx: HashMap::new(),
idx2val: Vec::new(),
}
} | identifier_body | |
bundle.js | centerPadding: '15%'
}
}, {
breakpoint: 370,
settings: {
slidesToShow: 1,
slidesToScroll: 1,
centerMode: true,
dots: true,
centerPadding: '12%'
}
}, {
breakpoint: 340,
sett... |
if ($('body').hasClass('logged')) {
$.each(openedTasksArray, function (i, item) {
$('.item-event[data-taskID=' + item + ']').removeClass('disabled');
});
}
$('.item-event').on('click', function (e) {
var logged = $('body').hasClass('logged');
var disabled = ... | {
openedTasksArray = JSON.parse(cookieTasks);
} | conditional_block |
bundle.js | if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function getScrollbarWidth() {
var outer = document.createElement("div");
outer.style.visibility = "hidden";
outer.style.width = "100px";
outer.style.msOverflowStyle = "scrollbar"; // needed for WinJS apps... | random_line_split | ||
bundle.js | (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + exdays * 24 * 60 * 60 * 1000);
var expires = "expires=" + d.toUTCString();
document.cookie = ... | _classCallCheck | identifier_name | |
bundle.js | centerPadding: '15%'
}
}, {
breakpoint: 370,
settings: {
slidesToShow: 1,
slidesToScroll: 1,
centerMode: true,
dots: true,
centerPadding: '12%'
}
}, {
breakpoint: 340,
sett... |
(function () {
var $window = $(window);
var $document = $(document);
var $body = $('body');
var $html = $('html');
var Android = navigator.userAgent.match(/Android/i) && !navigator.userAgent.match(/(Windows\sPhone)/i) ? true : false;
var App = function App() {
var _this = this;
_classCallCheck(... | {
if (mq === 'desktop') {
firstFunc();
} else if (mq === 'tablet') {
otherFunc();
} else if (mq === 'mobile') {
secFunc();
}
// console.log('staticInit:' + mq);
} | identifier_body |
session.rs | (&rec_tid).cloned()
}
/// NOTE: Method is simply called Session::find task() in rr
fn find_task_from_task_uid(&self, tuid: TaskUid) -> Option<TaskSharedPtr> {
self.find_task_from_rec_tid(tuid.tid())
}
/// Return the thread group whose unique ID is `tguid`, or None if no such
/// thread... | {
let start = m.map.start();
let data_size: usize;
let num_byes_addr =
RemotePtr::<u32>::cast(remote_ptr_field!(start, syscallbuf_hdr, num_rec_bytes));
if read_val_mem(
clone_leader,
remote_ptr_field!(start, syscallbuf_hdr, locked),
None,
) != 0u8
{
// The... | identifier_body | |
session.rs | boolean methods. Use the `as_*` methods that return Option<> instead.
fn is_recording(&self) -> bool {
self.as_record().is_some()
}
fn is_replaying(&self) -> bool {
self.as_replay().is_some()
}
fn is_diversion(&self) -> bool {
self.as_diversion().is_some()
}
fn new_... | else if m.local_addr.is_some() {
ed_assert_eq!(
clone_leader,
m.map.start(),
AddressSpace::preload_thread_locals_start()
);
} else if m.recorded_map.flags().contains(M... | {
group
.captured_memory
.push((m.map.start(), capture_syscallbuf(&m, &**clone_leader)));
} | conditional_block |
session.rs | boolean methods. Use the `as_*` methods that return Option<> instead.
fn is_recording(&self) -> bool {
self.as_record().is_some()
}
fn is_replaying(&self) -> bool {
self.as_replay().is_some()
}
fn is_diversion(&self) -> bool {
self.as_diversion().is_some()
}
fn new_... | (&self, vmuid: AddressSpaceUid) -> Option<AddressSpaceSharedPtr> {
self.finish_initializing();
// If the weak ptr was found, we _must_ be able to upgrade it!;
self.vm_map().get(&vmuid).map(|a| a.upgrade().unwrap())
}
/// Return a copy of `tg` with the same mappings.
/// NOTE: Called... | find_address_space | identifier_name |
session.rs | this boolean methods. Use the `as_*` methods that return Option<> instead.
fn is_recording(&self) -> bool {
self.as_record().is_some()
}
fn is_replaying(&self) -> bool {
self.as_replay().is_some()
}
fn is_diversion(&self) -> bool {
self.as_diversion().is_some()
}
fn... | for k in shared_maps_to_clone {
remap_shared_mmap(&mut remote, emu_fs, dest_emu_fs, k);
}
for t in vm.task_set().iter() {
if Rc::ptr_eq(&group_leader, &t) {
continue;
}
... | shared_maps_to_clone.push(k);
}
}
// Do this in a separate loop to avoid iteration invalidation issues | random_line_split |
data.js | QU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXY5g8dcZ/AAY/AsAlWFQ+AAAAAElFTkSuQmCC";
var darkGray = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXY3B0cPoPAANMAcOba1BlAAAAAElFTkSuQmCC";
// Each of ... | beforeSend: function (jqXHR, settings) {
if (typeof this.data === 'string') {
this.data = this.data.replace(/%[0-1][0-9a-f]/g, '%20');
this.data += '&access_token=' + localStorage['access_token'];
} else if (typeof this.data === 'object') {
... | identifier_name | |
data.js | nQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXY5g8dcZ/AAY/AsAlWFQ+AAAAAElFTkSuQmCC";
var darkGray = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXY3B0cPoPAANMAcOba1BlAAAAAElFTkSuQmCC";
// Each of... | data.forEach(function (item) {//to do rebuild
// Each of these sample items should have a reference to a particular group.
item.group = Groups[0];//通过上面的ajax请求获取到的都是laiwang主墙信息,所以取Groups数组中的第0项:laiwang
//item.key = item.id;
item.itemPubl... | gi, '<br/>');
}
| conditional_block |
data.js | QU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXY5g8dcZ/AAY/AsAlWFQ+AAAAAElFTkSuQmCC";
var darkGray = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXY3B0cPoPAANMAcOba1BlAAAAAElFTkSuQmCC";
// Each of ... | }
for (var index in data) {
data[index].content = data[index].content.replace(/\n/gi, '<br/>');
}
data.forEach(function (item) {//to do rebuild
// Each of these sample items should have a reference to a particular g... | ost/incoming/list',
// group: '/feed/post/circle/list'
//};
var postData = {
'cursor': 0,
'size': __LENGTH__,
'access_token': localStorage['access_token']
};
$.ajax({
global: false,
url: __API_DOMAIN__ + '/feed/post/m... | identifier_body |
data.js |
// These three strings encode placeholder images. You will want to set the backgroundImage property in your real data to be URLs to images.
var lightGray = "../images/item_bac01.jpg"; //"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZc... | var __DOMAIN__ = 'http://laiwang.com';
var __API_DOMAIN__ = 'http://api.laiwang.com/v1';
var __LENGTH__ = 25;
| random_line_split | |
integration.go | return nil
},
}
// integrationCreateCmd represents the create sub-command inside the integration command
integrationCreateCmd = &cobra.Command{
Use: "create",
Short: "create an external integrations",
Args: cobra.NoArgs,
Long: `Creates an external integration in your account through an interactive ... | for key, value := range m {
if s, ok := value.(string); ok { | random_line_split | |
integration.go | )
var (
// integrationCmd represents the integration command
integrationCmd = &cobra.Command{
Use: "integration",
Aliases: []string{"int"},
Short: "manage external integrations",
Long: `Manage external integrations with the Lacework platform`,
}
// integrationListCmd represents the list sub-comma... | []string{"CLIENT EMAIL", iData.Credentials.ClientEmail},
[]string{"PRIVATE KEY ID | {
switch raw.Type {
case api.GcpCfgIntegration.String(),
api.GcpAuditLogIntegration.String():
var iData api.GcpIntegrationData
err := mapstructure.Decode(raw.Data, &iData)
if err != nil {
cli.Log.Debugw("unable to decode integration data",
"integration_type", raw.Type,
"raw_data", raw.Data,
"... | identifier_body |
integration.go | Args: cobra.NoArgs,
Long: `Creates an external integration in your account through an interactive session.`,
RunE: func(_ *cobra.Command, _ []string) error {
if !cli.InteractiveMode() {
return errors.New("interactive mode is disabled")
}
lacework, err := api.NewClient(cli.Account,
api.WithLogLeve... | {
if s, ok := value.(string); ok {
out[key] = s
} else {
deepMap := deepKeyValueExtract(value)
for deepK, deepV := range deepMap {
out[deepK] = deepV
}
}
} | conditional_block | |
integration.go | )
var (
// integrationCmd represents the integration command
integrationCmd = &cobra.Command{
Use: "integration",
Aliases: []string{"int"},
Short: "manage external integrations",
Long: `Manage external integrations with the Lacework platform`,
}
// integrationListCmd represents the list sub-comma... | (lacework *api.Client) error {
var (
integration = ""
prompt = &survey.Select{
Message: "Choose an integration type to create: ",
Options: []string{
"Docker Hub",
"AWS Config",
"AWS CloudTrail",
"GCP Config",
"GCP Audit Log",
"Azure Config",
"Azure Activity Log",
//"Docke... | promptCreateIntegration | identifier_name |
validation_host.rs | timeout in seconds;
#[cfg(debug_assertions)]
pub const EXECUTION_TIMEOUT_SEC: u64 = 30;
#[cfg(not(debug_assertions))]
pub const EXECUTION_TIMEOUT_SEC: u64 = 5;
enum Event {
CandidateReady = 0,
ResultReady = 1,
WorkerReady = 2,
}
#[derive(Clone)]
struct TaskExecutor(ThreadPool);
impl TaskExecutor {
fn new() -... | (&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "ValidationHostMemory")
}
}
impl std::ops::Deref for ValidationHostMemory {
type Target = SharedMem;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl std::ops::DerefMut for ValidationHostMemory {
fn deref_mut(&mut self) -> &mut Self::Ta... | fmt | identifier_name |
validation_host.rs | {
ThreadPool::new().map_err(|e| e.to_string()).map(Self)
}
}
impl SpawnNamed for TaskExecutor {
fn spawn_blocking(&self, _: &'static str, future: futures::future::BoxFuture<'static, ()>) {
self.0.spawn_ok(future);
}
fn spawn(&self, _: &'static str, future: futures::future::BoxFuture<'static, ()>) {
self.0... | validation_code: &[u8],
params: ValidationParams,
binary: &PathBuf,
args: &[&str],
) -> Result<ValidationResult, ValidationError> { | random_line_split | |
validation_host.rs | ValidationError> {
for host in self.hosts.iter() {
if let Some(mut host) = host.try_lock() {
return host.validate_candidate(validation_code, params, command, args)
}
}
// all workers are busy, just wait for the first one
self.hosts[0].lock().validate_candidate(validation_code, params, command, args)... | {} | conditional_block | |
auth.pb.go |
func (m *AuthenticationRule) XXX_DiscardUnknown() {
xxx_messageInfo_AuthenticationRule.DiscardUnknown(m)
}
var xxx_messageInfo_AuthenticationRule proto.InternalMessageInfo
func (m *AuthenticationRule) GetSelector() string {
if m != nil {
return m.Selector
}
return ""
}
func (m *AuthenticationRule) GetOauth() ... | {
return xxx_messageInfo_AuthenticationRule.Size(m)
} | identifier_body | |
auth.pb.go |
return nil
}
func (m *Authentication) GetProviders() []*AuthProvider {
if m != nil {
return m.Providers
}
return nil
}
// Authentication rules for the service.
//
// By default, if a method has any authentication requirements, every request
// must include a valid credential matching one of the requirements.
/... | {
return m.Rules
} | conditional_block | |
auth.pb.go | if m != nil {
return m.AllowWithoutCredential
}
return false
}
func (m *AuthenticationRule) GetRequirements() []*AuthRequirement {
if m != nil {
return m.Requirements
}
return nil
}
// Configuration for an authentication provider, including support for
// [JSON Web Token
// (JWT)](https://tools.ietf.org/htm... | //
// The list of JWT
// [audiences](https://tools.ietf.org/html/draft-ietf-oauth-json-web-token-32#section-4.1.3).
// that are allowed to access. A JWT containing any of these audiences will
// be accepted. When this setting is absent, only JWTs with audience
// "https://[Service_name][google.api.Service.name]/[... | ProviderId string `protobuf:"bytes,1,opt,name=provider_id,json=providerId,proto3" json:"provider_id,omitempty"`
// NOTE: This will be deprecated soon, once AuthProvider.audiences is
// implemented and accepted in all the runtime components. | random_line_split |
auth.pb.go | m != nil {
return m.AllowWithoutCredential
}
return false
}
func (m *AuthenticationRule) GetRequirements() []*AuthRequirement {
if m != nil {
return m.Requirements
}
return nil
}
// Configuration for an authentication provider, including support for
// [JSON Web Token
// (JWT)](https://tools.ietf.org/html/d... | (b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_AuthProvider.Marshal(b, m, deterministic)
}
func (dst *AuthProvider) XXX_Merge(src proto.Message) {
xxx_messageInfo_AuthProvider.Merge(dst, src)
}
func (m *AuthProvider) XXX_Size() int {
return xxx_messageInfo_AuthProvider.Size(m)
}
func (m *Aut... | XXX_Marshal | identifier_name |
info.py | + print_variants.__doc__),
("--no-versions", "do not " + print_versions.__doc__),
("--phases", print_phases.__doc__),
("--tags", print_tags.__doc__),
("--tests", print_tests.__doc__),
("--virtuals", print_virtuals.__doc__),
]
for opt, help_comment in options:
sub... |
self.column_widths = (
max(self.column_widths[0], candidate_max_widths[0]),
max(self.column_widths[1], candidate_max_widths[1]),
max(self.column_widths[2], candidate_max_widths[2]),
max(self.column_widths[3], candidate_max_widths[3]),
... | self.variants = variants
self.headers = ("Name [Default]", "When", "Allowed values", "Description")
# Formats
fmt_name = "{0} [{1}]"
# Initialize column widths with the length of the
# corresponding headers, as they cannot be shorter
# than that
self.column_widt... | identifier_body |
info.py | + print_variants.__doc__),
("--no-versions", "do not " + print_versions.__doc__),
("--phases", print_phases.__doc__),
("--tags", print_tags.__doc__),
("--tests", print_tests.__doc__),
("--virtuals", print_virtuals.__doc__),
]
for opt, help_comment in options:
sub... | (self, v):
s = "on" if v.default is True else "off"
if not isinstance(v.default, bool):
s = v.default
return s
@property
def lines(self):
if not self.variants:
yield " None"
else:
yield " " + self.fmt % self.headers
u... | default | identifier_name |
info.py | True else "off"
if not isinstance(v.default, bool):
s = v.default
return s
@property
def lines(self):
if not self.variants:
yield " None"
else:
yield " " + self.fmt % self.headers
underline = tuple([w * "=" for w in self.col... | color.cprint(" None") | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.