file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
instance.rs
use crate::{ create_idx_struct, data_structures::{cont_idx_vec::ContiguousIdxVec, skipvec::SkipVec}, small_indices::SmallIdx, }; use anyhow::{anyhow, ensure, Error, Result}; use log::{info, trace}; use serde::Deserialize; use std::{ fmt::{self, Display, Write as _}, io::{BufRead, Write}, mem, ...
write!(writer, "v{}", CompressedIlpName(node))?; } writeln!(writer, " >= 1")?; } writeln!(writer, "Binaries")?; write!(writer, " v{}", CompressedIlpName(self.nodes()[0]))?; for &node in &self.nodes()[1..] { write!(writer, " v{}", Com...
{ write!(writer, " + ")?; }
conditional_block
instance.rs
use crate::{ create_idx_struct, data_structures::{cont_idx_vec::ContiguousIdxVec, skipvec::SkipVec}, small_indices::SmallIdx, }; use anyhow::{anyhow, ensure, Error, Result}; use log::{info, trace}; use serde::Deserialize; use std::{ fmt::{self, Display, Write as _}, io::{BufRead, Write}, mem, ...
(&mut self, edge: EdgeIdx) { trace!("Restoring edge {}", edge); for (_idx, (node, entry_idx)) in self.edge_incidences[edge.idx()].iter().rev() { self.node_incidences[node.idx()].restore(entry_idx.idx()); } self.edges.restore(edge.idx()); } /// Deletes all edges incid...
restore_edge
identifier_name
jcontroller_service.py
#!/usr/bin/env python3 # # Copyright 2016-2017 Games Creators Club # # MIT License # import array import math import socket import struct import threading import time import traceback from enum import Enum from fcntl import ioctl import pyroslib as pyros DEBUG_AXES = False DEBUG_BUTTONS = False DEBUG_JOYSTICK = Fal...
for axis in buf[:num_axes]: axis_name = axis_names.get(axis, '0x%02x' % axis) axis_map.append(axis_name) axis_states[axis_name] = 0.0 # Get the button map. buf = array.array('H', [0] * 200) ioctl(jsdev, 0x80406a34, buf) # JSIOCGBTNMAP for b...
num_buttons = buf[0] # Get the axis map. buf = array.array('B', [0] * 0x40) ioctl(jsdev, 0x80406a32, buf) # JSIOCGAXMAP
random_line_split
jcontroller_service.py
#!/usr/bin/env python3 # # Copyright 2016-2017 Games Creators Club # # MIT License # import array import math import socket import struct import threading import time import traceback from enum import Enum from fcntl import ioctl import pyroslib as pyros DEBUG_AXES = False DEBUG_BUTTONS = False DEBUG_JOYSTICK = Fal...
def readUDPEvents(): global haveJoystickEvent s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind(('', JCONTROLLER_UDP_PORT)) s.settimeout(10) print(" Started receive thread...") while True: try: data...
global haveJoystickEvent reconnect = True noError = True while True: if reconnect: connected = connectToJoystick(noError) if connected: reconnect = False noError = True else: noError = False time.sleep(...
identifier_body
jcontroller_service.py
#!/usr/bin/env python3 # # Copyright 2016-2017 Games Creators Club # # MIT License # import array import math import socket import struct import threading import time import traceback from enum import Enum from fcntl import ioctl import pyroslib as pyros DEBUG_AXES = False DEBUG_BUTTONS = False DEBUG_JOYSTICK = Fal...
(speed): global fullSpeed spd = speed if boost or lunge_back_time > 0 or fullSpeed: # spd = int(speed * topSpeed * 2) # if spd > 300: if speed > 0: spd = 300 elif speed < 0: spd = -300 else: spd = 0 else: spd = int(spee...
calcRoverSpeed
identifier_name
jcontroller_service.py
#!/usr/bin/env python3 # # Copyright 2016-2017 Games Creators Club # # MIT License # import array import math import socket import struct import threading import time import traceback from enum import Enum from fcntl import ioctl import pyroslib as pyros DEBUG_AXES = False DEBUG_BUTTONS = False DEBUG_JOYSTICK = Fal...
# Main event loop def loop(): global wobble_alpha wobble_alpha += 1 processButtons() if haveJoystickEvent: processJoysticks() if __name__ == "__main__": try: print("Starting jcontroller service...") pyros.subscribe("sensor/gyro", handleGyroData) pyros.subscribe(...
split = message.split(":") d = float(split[1]) print("d: " + str(d)) if d >= 0: sensorDistance = d orbitDistance = sensorDistance if prepareToOrbit: prepareToOrbit = False
conditional_block
lib.rs
use tokio::time::delay_for; use core::time::Duration; use anyhow::{anyhow, Result}; use channels::AGENT_CHANNEL; use comm::{AgentEvent, Hub}; use config::Config; use tokio::sync::RwLock; use tokio::sync::RwLockReadGuard; use tokio::sync::RwLockWriteGuard; use crossbeam_channel::{Receiver, Sender}; use log::{debug, inf...
} pub type FeatureHandle = Arc<tokio::sync::RwLock<dyn Feature>>; #[async_trait] pub trait Feature: Send + Sync { async fn init(&mut self, agent: AgentController); async fn on_event(&mut self, event: AgentEvent); fn name(&self) -> String; }
{ if self.state == AgentState::Stopped { info!("Agent stopped, Not running workload {}. Work will be deferred until the agent starts.", workload.id); let work_handle = Arc::new(tokio::sync::RwLock::new(WorkloadHandle { id: workload.id, join_handle: None, ...
identifier_body
lib.rs
use tokio::time::delay_for; use core::time::Duration; use anyhow::{anyhow, Result}; use channels::AGENT_CHANNEL; use comm::{AgentEvent, Hub}; use config::Config; use tokio::sync::RwLock; use tokio::sync::RwLockReadGuard; use tokio::sync::RwLockWriteGuard; use crossbeam_channel::{Receiver, Sender}; use log::{debug, inf...
AgentCommand::Stop => { self.state = AgentState::Stopped; channel.sender.send(AgentEvent::Stopped).unwrap(); } } } /// Run a workload in the agent /// This will capture the statistics of the workload run and store it in /// the agent. ...
{}
conditional_block
lib.rs
use tokio::time::delay_for; use core::time::Duration; use anyhow::{anyhow, Result}; use channels::AGENT_CHANNEL; use comm::{AgentEvent, Hub}; use config::Config; use tokio::sync::RwLock; use tokio::sync::RwLockReadGuard; use tokio::sync::RwLockWriteGuard; use crossbeam_channel::{Receiver, Sender}; use log::{debug, inf...
use work::{Workload, WorkloadHandle, WorkloadStatus}; use async_trait::async_trait; pub mod cfg; pub mod comm; pub mod plugins; pub mod prom; pub mod threads; pub mod work; pub mod channels { pub const AGENT_CHANNEL: &'static str = "Agent"; } // Configuration lazy_static! { static ref SETTINGS: RwLock<Confi...
use tokio::runtime::Runtime;
random_line_split
lib.rs
use tokio::time::delay_for; use core::time::Duration; use anyhow::{anyhow, Result}; use channels::AGENT_CHANNEL; use comm::{AgentEvent, Hub}; use config::Config; use tokio::sync::RwLock; use tokio::sync::RwLockReadGuard; use tokio::sync::RwLockWriteGuard; use crossbeam_channel::{Receiver, Sender}; use log::{debug, inf...
{ Start, Schedule(Schedule, Workload), Stop, } #[derive(Debug, Clone)] pub struct FeatureConfig { pub bind_address: [u8; 4], pub bind_port: u16, pub settings: HashMap<String, String>, } #[derive(Clone)] pub struct AgentController { pub agent: Arc<RwLock<Agent>>, pub signal: Option<Send...
AgentCommand
identifier_name
learn.py
import numpy as np import time from RLC.real_chess.tree import Node import math import gc def softmax(x, temperature=1): return np.exp(x / temperature) / np.sum(np.exp(x / temperature)) def sigmoid(x): return 1 / (1 + math.exp(-x)) class TD_search(object): def __init__(self, env, agent, gamma=0.9, se...
episode_end, reward = self.env.step(move) if episode_end: successor_state_value = 0 else: successor_state_value = np.squeeze( self.agent.model.predict(np.expand_dims(self.env.layer_board, axis=0)) ) c...
node.children[move] = Node(self.env.board, parent=node)
conditional_block
learn.py
import numpy as np import time from RLC.real_chess.tree import Node import math import gc def softmax(x, temperature=1):
def sigmoid(x): return 1 / (1 + math.exp(-x)) class TD_search(object): def __init__(self, env, agent, gamma=0.9, search_time=1, memsize=2000, batch_size=256, temperature=1): """ Chess algorithm that combines bootstrapped monte carlo tree search with Q Learning Args: env...
return np.exp(x / temperature) / np.sum(np.exp(x / temperature))
identifier_body
learn.py
import numpy as np import time from RLC.real_chess.tree import Node import math import gc def softmax(x, temperature=1): return np.exp(x / temperature) / np.sum(np.exp(x / temperature)) def sigmoid(x): return 1 / (1 + math.exp(-x)) class TD_search(object): def __init__(self, env, agent, gamma=0.9, se...
Args: prioritized: Returns: """ if prioritized: sampling_priorities = np.abs(self.mem_error) + 1e-9 else: sampling_priorities = np.ones(shape=self.mem_error.shape) sampling_probs = sampling_priorities / np.sum(sampling_priorities) ...
def get_minibatch(self, prioritized=True): """ Get a mini batch of experience
random_line_split
learn.py
import numpy as np import time from RLC.real_chess.tree import Node import math import gc def softmax(x, temperature=1): return np.exp(x / temperature) / np.sum(np.exp(x / temperature)) def
(x): return 1 / (1 + math.exp(-x)) class TD_search(object): def __init__(self, env, agent, gamma=0.9, search_time=1, memsize=2000, batch_size=256, temperature=1): """ Chess algorithm that combines bootstrapped monte carlo tree search with Q Learning Args: env: RLC chess en...
sigmoid
identifier_name
main.py
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from lxml import etree from StringIO import StringIO from odoo import http, _ from odoo.http import content_disposition, request from odoo.exceptions import UserError, AccessError from odoo.addons.web_studio.controllers ...
(self, model, **kwargs): return { 'name': _('Search Filters'), 'type': 'ir.actions.act_window', 'res_model': 'ir.filters', 'views': [[False, 'list'], [False, 'form']], 'target': 'current', 'domain': [], 'context': {'search_defau...
_get_studio_action_filters
identifier_name
main.py
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from lxml import etree from StringIO import StringIO from odoo import http, _ from odoo.http import content_disposition, request from odoo.exceptions import UserError, AccessError from odoo.addons.web_studio.controllers ...
'inherit_id': view.id, 'mode': 'extension', 'priority': 99, 'arch': new_arch, 'name': "Odoo Studio: %s customization" % (view.name), }) fields_view = request.env[view.model].with_context({'studio': True}).fields_view_ge...
# would first resolve in x,x2,y, then resolve "Standard" with x,z,x2,y as result. studio_view = request.env['ir.ui.view'].create({ 'type': view.type, 'model': view.model,
random_line_split
main.py
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from lxml import etree from StringIO import StringIO from odoo import http, _ from odoo.http import content_disposition, request from odoo.exceptions import UserError, AccessError from odoo.addons.web_studio.controllers ...
else: xml_node.text = new_attr def _operation_buttonbox(self, arch, operation, model=None): studio_view_arch = arch # The actual arch is the studio view arch # Get the arch of the form view with inherited views applied arch = request.env[model].fields_view_get(...
xml_node = etree.Element('attribute', {'name': key}) xml_node.text = new_attr xpath_node.insert(0, xml_node)
conditional_block
main.py
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from lxml import etree from StringIO import StringIO from odoo import http, _ from odoo.http import content_disposition, request from odoo.exceptions import UserError, AccessError from odoo.addons.web_studio.controllers ...
@http.route('/web_studio/edit_view_arch', type='json', auth='user') def edit_view_arch(self, view_id, view_arch): view = request.env['ir.ui.view'].browse(view_id) if view: view.write({'arch': view_arch}) if view.model: try: fields_v...
view = request.env['ir.ui.view'].browse(view_id) studio_view = self._get_studio_view(view) parser = etree.XMLParser(remove_blank_text=True) arch = etree.parse(StringIO(studio_view_arch), parser).getroot() for op in operations: # Call the right operation handler ...
identifier_body
mod.rs
//! Tiles organised into chunks for efficiency and performance. //! //! Mostly everything in this module is private API and not intended to be used //! outside of this crate as a lot goes on under the hood that can cause issues. //! With that being said, everything that can be used with helping a chunk get //! created ...
else { error!("can not set tile to sprite layer {}", tile.z_order); } } else { error!("sprite layer {} does not exist", tile.z_order); } } /// Removes a tile from a sprite layer with a given index and z order. pub(crate) fn remove_tile(&mut self, ind...
{ let raw_tile = RawTile { index: tile.sprite_index, color: tile.tint, }; layer.inner.as_mut().set_tile(index, raw_tile); }
conditional_block
mod.rs
//! Tiles organised into chunks for efficiency and performance. //! //! Mostly everything in this module is private API and not intended to be used //! outside of this crate as a lot goes on under the hood that can cause issues. //! With that being said, everything that can be used with helping a chunk get //! created ...
/// Removes a layer from the specified layer. pub(crate) fn remove_layer(&mut self, z_order: usize) { self.sprite_layers.get_mut(z_order).take(); } /// Sets the mesh for the chunk layer to use. pub(crate) fn set_mesh(&mut self, z_order: usize, mesh: Handle<Mesh>) { if let Some(lay...
{ // TODO: rename to swap and include it in the greater api if self.sprite_layers.get(to_z).is_some() { error!( "sprite layer {} unexpectedly exists and can not be moved", to_z ); return; } self.sprite_layers.swap(from_...
identifier_body
mod.rs
//! Tiles organised into chunks for efficiency and performance. //! //! Mostly everything in this module is private API and not intended to be used //! outside of this crate as a lot goes on under the hood that can cause issues. //! With that being said, everything that can be used with helping a chunk get //! created ...
(&mut self, z_order: usize, index: usize) -> Option<&mut RawTile> { self.sprite_layers.get_mut(z_order).and_then(|layer| { layer .as_mut() .and_then(|layer| layer.inner.as_mut().get_tile_mut(index)) }) } /// Gets a vec of all the tiles in the layer, i...
get_tile_mut
identifier_name
mod.rs
//! Tiles organised into chunks for efficiency and performance. //! //! Mostly everything in this module is private API and not intended to be used //! outside of this crate as a lot goes on under the hood that can cause issues. //! With that being said, everything that can be used with helping a chunk get //! created ...
/// Gets a reference to a tile from a provided z order and index. pub(crate) fn get_tile(&self, z_order: usize, index: usize) -> Option<&RawTile> { self.sprite_layers.get(z_order).and_then(|layer| { layer .as_ref() .and_then(|layer| layer.inner.as_ref().get_t...
}
random_line_split
process.rs
use crate::{FromInner, HandleTrait, Inner, IntoInner}; use std::convert::TryFrom; use std::ffi::CString; use uv::uv_stdio_container_s__bindgen_ty_1 as uv_stdio_container_data; use uv::{ uv_disable_stdio_inheritance, uv_kill, uv_process_get_pid, uv_process_kill, uv_process_options_t, uv_process_t, uv_spawn, uv_s...
{ handle: *mut uv_process_t, } impl ProcessHandle { /// Create a new process handle pub fn new() -> crate::Result<ProcessHandle> { let layout = std::alloc::Layout::new::<uv_process_t>(); let handle = unsafe { std::alloc::alloc(layout) as *mut uv_process_t }; if handle.is_null() { ...
ProcessHandle
identifier_name
process.rs
use crate::{FromInner, HandleTrait, Inner, IntoInner}; use std::convert::TryFrom; use std::ffi::CString; use uv::uv_stdio_container_s__bindgen_ty_1 as uv_stdio_container_data; use uv::{ uv_disable_stdio_inheritance, uv_kill, uv_process_get_pid, uv_process_kill, uv_process_options_t, uv_process_t, uv_spawn, uv_s...
/// 2). const IGNORE = uv::uv_stdio_flags_UV_IGNORE as _; /// Open a new pipe into `data.stream`, per the flags below. The `data.stream` field must /// point to a PipeHandle object that has been initialized with `new`, but not yet opened /// or connected. const CREATE_PI...
pub struct StdioFlags: u32 { /// No file descriptor will be provided (or redirected to `/dev/null` if it is fd 0, 1 or
random_line_split
process.rs
use crate::{FromInner, HandleTrait, Inner, IntoInner}; use std::convert::TryFrom; use std::ffi::CString; use uv::uv_stdio_container_s__bindgen_ty_1 as uv_stdio_container_data; use uv::{ uv_disable_stdio_inheritance, uv_kill, uv_process_get_pid, uv_process_kill, uv_process_options_t, uv_process_t, uv_spawn, uv_s...
} // CString will ensure we have a terminating null let file = CString::new(options.file)?; // For args, libuv-sys is expecting a "*mut *mut c_char". The only way to get a "*mut // c_char" from a CString is via CString::into_raw() which will "leak" the memory from // rus...
d.exit_cb = options.exit_cb; }
conditional_block
_mkl.py
from ._base import Matrix, MatrixError, BackendNotAvailable from .. import numeric, _util as util, warnings from contextlib import contextmanager from ctypes import c_int, byref, CDLL import treelog as log import os import numpy libmkl_path = os.environ.get('NUTILS_MATRIX_MKL_LIB', None) if libmkl_path: libmkl = C...
self.mtype = c_int(mtype) self.n = c_int(len(ia)-1) self.a = a.ctypes self.ia = ia.ctypes self.ja = ja.ctypes self.perm = None self.iparm = numpy.zeros(64, dtype=numpy.int32) # https://software.intel.com/en-us/mkl-developer-reference-c-pardiso-iparm-parameter ...
self.dtype = a.dtype self.pt = numpy.zeros(64, numpy.int64) # handle to data structure self.maxfct = c_int(1) self.mnum = c_int(1)
random_line_split
_mkl.py
from ._base import Matrix, MatrixError, BackendNotAvailable from .. import numeric, _util as util, warnings from contextlib import contextmanager from ctypes import c_int, byref, CDLL import treelog as log import os import numpy libmkl_path = os.environ.get('NUTILS_MATRIX_MKL_LIB', None) if libmkl_path: libmkl = C...
return Pardiso(mtype=mtype[self.dtype.kind], a=self.data[upper], ia=rowptr, ja=self.colidx[upper], **args) # vim:sw=4:sts=4:et
mtype = dict(f=-2, c=6)
conditional_block
_mkl.py
from ._base import Matrix, MatrixError, BackendNotAvailable from .. import numeric, _util as util, warnings from contextlib import contextmanager from ctypes import c_int, byref, CDLL import treelog as log import os import numpy libmkl_path = os.environ.get('NUTILS_MATRIX_MKL_LIB', None) if libmkl_path: libmkl = C...
: '''Wrapper for libmkl.pardiso. https://www.intel.com/content/www/us/en/develop/documentation/onemkl-developer-reference-c/top/ sparse-solver-routines/onemkl-pardiso-parallel-direct-sparse-solver-iface.html ''' _errorcodes = { -1: 'input inconsistent', -2: 'not enough memory', ...
Pardiso
identifier_name
_mkl.py
from ._base import Matrix, MatrixError, BackendNotAvailable from .. import numeric, _util as util, warnings from contextlib import contextmanager from ctypes import c_int, byref, CDLL import treelog as log import os import numpy libmkl_path = os.environ.get('NUTILS_MATRIX_MKL_LIB', None) if libmkl_path: libmkl = C...
def mkl_(self, name, *args): attr = 'mkl_' + dict(f='d', c='z')[self.dtype.kind] + name return getattr(libmkl, attr)(*args) def convert(self, mat): if not isinstance(mat, Matrix): raise TypeError('cannot convert {} to Matrix'.format(type(mat).__name__)) if self.sha...
assert len(data) == len(colidx) == rowptr[-1]-1 self.data = numpy.ascontiguousarray(data, dtype=numpy.complex128 if data.dtype.kind == 'c' else numpy.float64) self.rowptr = numpy.ascontiguousarray(rowptr, dtype=numpy.int32) self.colidx = numpy.ascontiguousarray(colidx, dtype=numpy.int32) ...
identifier_body
transcription.py
#!/usr/bin/env python # encoding: utf-8 # The MIT License (MIT) # Copyright (c) 2014 CNRS (Hervé BREDIN - http://herve.niderb.fr) # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without re...
edges for t1, t2 in self.edges_iter(): g.add_edge(t1, t2) # connect every pair of anchored times anchored = sorted(self.anchored()) for t1, t2 in itertools.combinations(anchored, 2): g.add_edge(t1, t2) # connect every time with its sucessors _g =...
add existing
conditional_block
transcription.py
#!/usr/bin/env python # encoding: utf-8 # The MIT License (MIT) # Copyright (c) 2014 CNRS (Hervé BREDIN - http://herve.niderb.fr) # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without re...
ook displays =========================================== def _repr_svg_(self): from notebook import repr_transcription return repr_transcription(self)
ata[PYANNOTE_JSON_TRANSCRIPTION]) mapping = {node: T(node) for node in graph} graph = nx.relabel_nodes(graph, mapping) return cls(graph=graph, **graph.graph) # === IPython Noteb
identifier_body
transcription.py
#!/usr/bin/env python # encoding: utf-8 # The MIT License (MIT) # Copyright (c) 2014 CNRS (Hervé BREDIN - http://herve.niderb.fr) # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without re...
for t in self.nodes_iter(): g.add_node(t) # add existing edges for t1, t2 in self.edges_iter(): g.add_edge(t1, t2) # connect every pair of anchored times anchored = sorted(self.anchored()) for t1, t2 in itertools.combinations(anchored, 2): ...
random_line_split
transcription.py
#!/usr/bin/env python # encoding: utf-8 # The MIT License (MIT) # Copyright (c) 2014 CNRS (Hervé BREDIN - http://herve.niderb.fr) # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without re...
book import repr_transcription return repr_transcription(self)
from note
identifier_name
ccm.rs
// Implementation of the AEAD CCM cipher as described in: // https://datatracker.ietf.org/doc/html/rfc3610 // // NOTE: Currently only fixed block sizes are supported. use core::result::Result; use common::ceil_div; use crate::constant_eq; use crate::utils::xor_inplace; /// Number of bytes in an AES-128 key. pub con...
<Block, Nonce> { block: Block, tag_size: usize, length_size: usize, nonce: Nonce, } impl<Block: BlockCipherBuffer, Nonce: AsRef<[u8]>> CCM<Block, Nonce> { /// /// Arguments: /// - block: /// - tag_size: Number of bytes used to store the message authentication /// tag. /// - le...
CCM
identifier_name
ccm.rs
// Implementation of the AEAD CCM cipher as described in: // https://datatracker.ietf.org/doc/html/rfc3610 // // NOTE: Currently only fixed block sizes are supported. use core::result::Result; use common::ceil_div; use crate::constant_eq; use crate::utils::xor_inplace; /// Number of bytes in an AES-128 key. pub con...
else { 0 }) << 6 | ((self.tag_size as u8 - 2) / 2) << 3 | (self.length_size as u8 - 1); if self.length_size == 2 { *array_mut_ref![block, block.len() - 2, 2] = (length as u16).to_be_bytes(); } else { todo!(); } } fn setup_for_ctr_enc(&mu...
{ 1 }
conditional_block
ccm.rs
// Implementation of the AEAD CCM cipher as described in: // https://datatracker.ietf.org/doc/html/rfc3610 // // NOTE: Currently only fixed block sizes are supported. use core::result::Result; use common::ceil_div; use crate::constant_eq; use crate::utils::xor_inplace; /// Number of bytes in an AES-128 key. pub con...
} impl BlockCipherBuffer for AES128BlockEncryptor { fn plaintext(&self) -> &[u8; BLOCK_SIZE] { &self.plaintext } fn plaintext_mut(&mut self) -> &mut [u8; BLOCK_SIZE] { &mut self.plaintext } fn plaintext_mut_ciphertext(&mut self) -> (&mut [u8; B...
{ assert_eq!(key.len(), KEY_SIZE); Self { cipher: AESBlockCipher::create(key).unwrap(), plaintext: [0u8; BLOCK_SIZE], ciphertext: [0u8; BLOCK_SIZE], } }
identifier_body
ccm.rs
// Implementation of the AEAD CCM cipher as described in: // https://datatracker.ietf.org/doc/html/rfc3610 // // NOTE: Currently only fixed block sizes are supported. use core::result::Result; use common::ceil_div; use crate::constant_eq; use crate::utils::xor_inplace; /// Number of bytes in an AES-128 key. pub con...
/// - tag_size: Number of bytes used to store the message authentication /// tag. /// - length_size: Number of bytes used to represent the message length. /// - nonce: pub fn new(block: Block, tag_size: usize, length_size: usize, nonce: Nonce) -> Self { let nonce_size = 15 - length_size; ...
/// Arguments: /// - block:
random_line_split
protocol.rs
// Copyright 2018 Parity Technologies (UK) Ltd. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, mer...
(&self) -> Self::InfoIter { iter::once(b"/ipfs/id/1.0.0") } } impl<C> InboundUpgrade<C> for IdentifyProtocolConfig where C: AsyncRead + AsyncWrite, { type Output = IdentifySender<Negotiated<C>>; type Error = IoError; type Future = FutureResult<Self::Output, IoError>; fn upgrade_inbound...
protocol_info
identifier_name
protocol.rs
// Copyright 2018 Parity Technologies (UK) Ltd. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, mer...
) }); let mut rt = Runtime::new().unwrap(); let _ = rt.block_on(future).unwrap(); }); let transport = TcpConfig::new(); let future = transport.dial(rx.recv().unwrap()) .unwrap() .and_then(|socket| { ...
"/ip6/::1/udp/1000".parse().unwrap(), ], protocols: vec!["proto1".to_string(), "proto2".to_string()], }, &"/ip4/100.101.102.103/tcp/5000".parse().unwrap(),
random_line_split
protocol.rs
// Copyright 2018 Parity Technologies (UK) Ltd. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, mer...
let listen_addrs = { let mut addrs = Vec::new(); for addr in msg.take_listenAddrs().into_iter() { addrs.push(bytes_to_multiaddr(addr)?); } addrs }; let public_key = PublicKey::from_protobuf_encodin...
{ Multiaddr::try_from(bytes) .map_err(|err| IoError::new(IoErrorKind::InvalidData, err)) }
identifier_body
postgres.go
package postgres import ( "context" "database/sql" "database/sql/driver" "encoding/json" "time" kitlog "github.com/go-kit/kit/log" "github.com/google/uuid" "github.com/jmoiron/sqlx" "github.com/lib/pq" "github.com/pkg/errors" "github.com/prometheus/client_golang/prometheus" "golang.org/x/crypto/acme/autoc...
// GetDevice returns a single device identified by device_token, including all streams // for that device. This is used to set up subscriptions for existing records on // application start. func (d *DB) GetDevice(deviceToken string) (_ *Device, err error) { sql := `SELECT id, device_token, longitude, latitude, expos...
{ sql := `SELECT id, device_token FROM devices` tx, err := BeginTX(d.DB) if err != nil { return nil, errors.Wrap(err, "failed to begin transaction") } defer func() { if cerr := tx.CommitOrRollback(); err == nil && cerr != nil { err = cerr } }() devices := []*Device{} mapper := func(rows *sqlx.Rows)...
identifier_body
postgres.go
package postgres import ( "context" "database/sql" "database/sql/driver" "encoding/json" "time" kitlog "github.com/go-kit/kit/log" "github.com/google/uuid" "github.com/jmoiron/sqlx" "github.com/lib/pq" "github.com/pkg/errors" "github.com/prometheus/client_golang/prometheus" "golang.org/x/crypto/acme/autoc...
(stream *Stream) (_ *Device, err error) { sql := `DELETE FROM streams WHERE uuid = :uuid AND pgp_sym_decrypt(token, :encryption_password) = :token RETURNING device_id` mapArgs := map[string]interface{}{ "uuid": stream.StreamID, "encryption_password": d.encryptionPassword, "token": ...
DeleteStream
identifier_name
postgres.go
package postgres import ( "context" "database/sql" "database/sql/driver" "encoding/json" "time" kitlog "github.com/go-kit/kit/log" "github.com/google/uuid" "github.com/jmoiron/sqlx" "github.com/lib/pq" "github.com/pkg/errors" "github.com/prometheus/client_golang/prometheus" "golang.org/x/crypto/acme/autoc...
if streamCount == 0 { // delete the device too sql = `DELETE FROM devices WHERE id = :id RETURNING device_token` mapArgs = map[string]interface{}{ "id": deviceID, } var device Device err = tx.Get(&device, sql, mapArgs) if err != nil { return nil, errors.Wrap(err, "failed to delete device") }...
{ return nil, errors.Wrap(err, "failed to count streams") }
conditional_block
postgres.go
package postgres import ( "context" "database/sql" "database/sql/driver" "encoding/json" "time" kitlog "github.com/go-kit/kit/log" "github.com/google/uuid" "github.com/jmoiron/sqlx" "github.com/lib/pq" "github.com/pkg/errors" "github.com/prometheus/client_golang/prometheus" "golang.org/x/crypto/acme/autoc...
// and write back from the DB. type Operations []*Operation // Value is our implementation of the sql.Valuer interface which converts the // instance into a value that can be written to the database. func (o Operations) Value() (driver.Value, error) { return json.Marshal(o) } // Scan is our implementation of the sql...
// Operations is a type alias for a slice of Operation instance. We add as a // separate type as we implement sql.Valuer and sql.Scanner interfaces to read
random_line_split
index.js
import React from 'react'; import ReactDOM from 'react-dom'; import lareneTweetImg from './img/larene-tweet.png'; import youtubeImg from './img/youtube.png'; import lighthouseImg from './img/lighthouse.png'; import axeImg from './img/axe.png'; import randomImg from './img/random-img.png'; import emulateVisionVideo from...
</Slide> <Slide> <Heading>What do you prefer?</Heading> <CodePane fontSize={18} language="html" autoFillHeight > {indentNormalizer(` <button>Save</button> `)} </CodePane> <Text>OR:</Text> <CodePane fontSize={18} l...
</Link> </ListItem> </UnorderedList>
random_line_split
index.js
import React from 'react'; import ReactDOM from 'react-dom'; import lareneTweetImg from './img/larene-tweet.png'; import youtubeImg from './img/youtube.png'; import lighthouseImg from './img/lighthouse.png'; import axeImg from './img/axe.png'; import randomImg from './img/random-img.png'; import emulateVisionVideo from...
.\S+/.test(input.value) isEmail ? input.className="valid" : input.className="invalid" }}/> </form> </Slide> <Slide> <Heading>Use a screen reader!</Heading> <Text>iOS: VoiceOver</Text> <Text>Windows: NVDA</Text> <Text>Android: Talkback</Text> </Slide> <Slid...
return; } const isEmail = /\S+@\S+\
conditional_block
setup.go
// Copyright 2019 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Package usbprinter provides an interface to configure and attach a virtual // USB printer onto the system to be used for testing. package usbprinter import ( "context" ...
devInfo, deviceName, err := loadPrinterIDs(op.descriptors) if err != nil { return nil, err } cmd, err := launchPrinter(ctx, op) if err != nil { return nil, err } defer func(ctx context.Context) { if err == nil { return } if cleanupErr := cmd.Signal(unix.SIGTERM); cleanupErr != nil { testing.Con...
{ return nil, errors.New("missing required WithDescriptors() option") }
conditional_block
setup.go
// Copyright 2019 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Package usbprinter provides an interface to configure and attach a virtual // USB printer onto the system to be used for testing. package usbprinter import ( "context" ...
func launchPrinter(ctx context.Context, op config) (cmd *testexec.Cmd, err error) { testing.ContextLog(ctx, "Starting virtual printer: ", op.args) launch := testexec.CommandContext(ctx, "stdbuf", op.args...) p, err := launch.StdoutPipe() if err != nil { return nil, err } if err := launch.Start(); err != ni...
{ testing.ContextLogf(ctx, "Terminating virtual-usb-printer with PID %d", cmd.Cmd.Process.Pid) if err := cmd.Signal(unix.SIGTERM); err != nil { return errors.Wrap(err, "failed to send SIGTERM to virtual-usb-printer") } if err := cmd.Wait(); err != nil { // We're expecting the exit status to be non-zero if the p...
identifier_body
setup.go
// Copyright 2019 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Package usbprinter provides an interface to configure and attach a virtual // USB printer onto the system to be used for testing. package usbprinter import ( "context" ...
(ctx context.Context, opts ...Option) (pr *Printer, err error) { // Debugd needs to be running before the USB device shows up so Chrome can add the printer. if err := upstart.EnsureJobRunning(ctx, "debugd"); err != nil { testing.ContextLogf(ctx, "debugd not running: %q", err) return nil, err } op := config{ ...
Start
identifier_name
setup.go
// Copyright 2019 The ChromiumOS Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Package usbprinter provides an interface to configure and attach a virtual // USB printer onto the system to be used for testing. package usbprinter import ( "context" ...
o.args = append(o.args, "--record_doc_path="+record) return nil } } // WithMockPrinterScriptPath sets the mock printer script path. func WithMockPrinterScriptPath(script string) Option { return func(o *config) error { if !path.IsAbs(script) { return errors.Errorf("mock printer script path (%q) is not an abs...
return func(o *config) error { if !path.IsAbs(record) { return errors.Errorf("record path (%q) is not an absolute path", record) }
random_line_split
create_sdk.py
#!/usr/bin/env python # # Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file # for details. All rights reserved. Use of this source code is governed by a # BSD-style license that can be found in the LICENSE file. # # A script which will be invoked from gyp to create an SDK. # # Usage: create_sdk...
(src, dest): copyfile(src, dest) copymode(src, dest) def CopyShellScript(src_file, dest_dir): """Copies a shell/batch script to the given destination directory. Handles using the appropriate platform-specific file extension.""" file_extension = '' if HOST_OS == 'win32': file_extension = '.bat' #...
Copy
identifier_name
create_sdk.py
#!/usr/bin/env python # # Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file # for details. All rights reserved. Use of this source code is governed by a # BSD-style license that can be found in the LICENSE file. # # A script which will be invoked from gyp to create an SDK. # # Usage: create_sdk...
# Copy the platform descriptors. for file_name in ["dart_client.platform", "dart_server.platform", "dart_shared.platform"]: copyfile(join(HOME, 'sdk', 'lib', file_name), join(LIB, file_name)); # Copy libraries.dart to lib/_internal/libraries.dart for backwards # co...
copytree(join(HOME, 'sdk', 'lib', library), join(LIB, library), ignore=ignore_patterns('*.svn', 'doc', '*.py', '*.gypi', '*.sh', '.gitignore'))
conditional_block
create_sdk.py
#!/usr/bin/env python # # Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file # for details. All rights reserved. Use of this source code is governed by a # BSD-style license that can be found in the LICENSE file. # # A script which will be invoked from gyp to create an SDK. # # Usage: create_sdk...
join('_chrome', 'dart2js'), join('_chrome', 'dartium'), join('_internal', 'js_runtime'), join('_internal', 'sdk_library_metadata'), 'async', 'collection', 'convert', 'core', 'developer', 'internal', 'io', 'isolate', ...
random_line_split
create_sdk.py
#!/usr/bin/env python # # Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file # for details. All rights reserved. Use of this source code is governed by a # BSD-style license that can be found in the LICENSE file. # # A script which will be invoked from gyp to create an SDK. # # Usage: create_sdk...
def CopyShellScript(src_file, dest_dir): """Copies a shell/batch script to the given destination directory. Handles using the appropriate platform-specific file extension.""" file_extension = '' if HOST_OS == 'win32': file_extension = '.bat' # If we're copying an SDK-specific shell script, strip of...
copyfile(src, dest) copymode(src, dest)
identifier_body
correctness_proof.rs
//! The proof of correct encryption of the given value. //! For more details see section 5.2 of the whitepaper. use super::errors::{ErrorKind, Fallible}; use crate::asset_proofs::{ encryption_proofs::{ AssetProofProver, AssetProofProverAwaitingChallenge, AssetProofVerifier, ZKPChallenge, ZKProofRes...
} #[derive(PartialEq, Copy, Clone, Debug)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct CorrectnessInitialMessage { a: RistrettoPoint, b: RistrettoPoint, } impl Encode for CorrectnessInitialMessage { fn size_hint(&self) -> usize { 64 } fn encode_to<W: Output>...
{ let scalar = <[u8; 32]>::decode(input)?; let scalar = Scalar::from_canonical_bytes(scalar) .ok_or_else(|| CodecError::from("CorrectnessFinalResponse is invalid"))?; Ok(CorrectnessFinalResponse(scalar)) }
identifier_body
correctness_proof.rs
//! The proof of correct encryption of the given value. //! For more details see section 5.2 of the whitepaper. use super::errors::{ErrorKind, Fallible}; use crate::asset_proofs::{ encryption_proofs::{ AssetProofProver, AssetProofProverAwaitingChallenge, AssetProofVerifier, ZKPChallenge, ZKProofRes...
<I: Input>(input: &mut I) -> Result<Self, CodecError> { let (a, b) = <([u8; 32], [u8; 32])>::decode(input)?; let a = CompressedRistretto(a) .decompress() .ok_or_else(|| CodecError::from("CorrectnessInitialMessage 'a' point is invalid"))?; let b = CompressedRistretto(b) ...
decode
identifier_name
correctness_proof.rs
//! The proof of correct encryption of the given value. //! For more details see section 5.2 of the whitepaper. use super::errors::{ErrorKind, Fallible}; use crate::asset_proofs::{ encryption_proofs::{ AssetProofProver, AssetProofProverAwaitingChallenge, AssetProofVerifier, ZKPChallenge, ZKProofRes...
/// A default implementation used for testing. impl Default for CorrectnessInitialMessage { fn default() -> Self { CorrectnessInitialMessage { a: RISTRETTO_BASEPOINT_POINT, b: RISTRETTO_BASEPOINT_POINT, } } } impl UpdateTranscript for CorrectnessInitialMessage { fn u...
random_line_split
main.rs
use rusttype::{point, Font, Glyph, Scale}; use winit::{ dpi::PhysicalSize, event::*, event_loop::{ControlFlow, EventLoop}, window::{Window, WindowBuilder}, }; #[repr(C)] #[derive(Copy, Clone, Debug)] struct Vertex { position: [f32; 3], tex_coords: [f32; 2], } impl Vertex { fn desc<'a>() -> ...
(&mut self, new_size: winit::dpi::PhysicalSize<u32>) { self.size = new_size; self.sc_desc.width = new_size.width; self.sc_desc.height = new_size.height; self.swap_chain = self.device.create_swap_chain(&self.surface, &self.sc_desc); } fn render(&mut self) { let frame = sel...
resize
identifier_name
main.rs
use rusttype::{point, Font, Glyph, Scale}; use winit::{ dpi::PhysicalSize, event::*, event_loop::{ControlFlow, EventLoop}, window::{Window, WindowBuilder}, }; #[repr(C)] #[derive(Copy, Clone, Debug)] struct Vertex { position: [f32; 3], tex_coords: [f32; 2], } impl Vertex { fn desc<'a>() -> ...
depth_bias: 0, depth_bias_slope_scale: 0.0, depth_bias_clamp: 0.0, }), primitive_topology: wgpu::PrimitiveTopology::TriangleList, color_states: &[wgpu::ColorStateDescriptor { format: sc_desc.format, color...
cull_mode: wgpu::CullMode::Back,
random_line_split
main.rs
use rusttype::{point, Font, Glyph, Scale}; use winit::{ dpi::PhysicalSize, event::*, event_loop::{ControlFlow, EventLoop}, window::{Window, WindowBuilder}, }; #[repr(C)] #[derive(Copy, Clone, Debug)] struct Vertex { position: [f32; 3], tex_coords: [f32; 2], } impl Vertex { fn desc<'a>() -> ...
fn resize(&mut self, new_size: winit::dpi::PhysicalSize<u32>) { self.size = new_size; self.sc_desc.width = new_size.width; self.sc_desc.height = new_size.height; self.swap_chain = self.device.create_swap_chain(&self.surface, &self.sc_desc); } fn render(&mut self) { l...
{ //let diffuse_bytes = include_bytes!("../happy-tree.png"); let font_bytes = include_bytes!("../ttf/JetBrainsMono-Regular.ttf"); let font = Font::from_bytes(font_bytes as &[u8]).expect("Failed to create font"); let glyph = font .glyph('c') .scaled(Scale { x: 50.0...
identifier_body
DataLoader.py
# This python file helps to get the data from the files, format and make it ready for transformers from .tools import * from transformers import BertTokenizer from multiprocessing import Pool, cpu_count import pickle, copy import logging from torch.utils.data import (DataLoader, RandomSampler, SequentialSampler, ...
(self, data_dir): """See base class.""" return self._create_examples( self._read_tsv(os.path.join(data_dir, "dev.tsv")), "dev") def get_test_examples(self, data_dir): """See base class.""" return self._create_examples( self._read_tsv(os.path.join(data_dir, "t...
get_dev_examples
identifier_name
DataLoader.py
# This python file helps to get the data from the files, format and make it ready for transformers from .tools import * from transformers import BertTokenizer from multiprocessing import Pool, cpu_count import pickle, copy import logging from torch.utils.data import (DataLoader, RandomSampler, SequentialSampler, ...
num_labels = len(label_list) num_train_optimization_steps = int( data_len / config.hyperparams.TRAIN_BATCH_SIZE / config.hyperparams.GRADIENT_ACCUMULATION_STEPS) * config.hyperparams.NUM_TRAIN_EPOCHS seq_length = str(config.hyperparams.MAX_SEQ_LENGTH) if source == "trai...
data = self.get_test_examples(config.programsettings.DATA_DIR) data_len = len(data) label_list = self.get_labels() # [0, 1] for binary classification
random_line_split
DataLoader.py
# This python file helps to get the data from the files, format and make it ready for transformers from .tools import * from transformers import BertTokenizer from multiprocessing import Pool, cpu_count import pickle, copy import logging from torch.utils.data import (DataLoader, RandomSampler, SequentialSampler, ...
def convert_example_to_feature(example_row): # return example_row example, max_seq_length, tokenizer = example_row tokens_a = tokenizer.tokenize(example.text_a) tokens_b = None if example.text_b: tokens_b = tokenizer.tokenize(example.text_b) # Modifies `tokens_a` and `tokens_b...
tokens_b.pop()
conditional_block
DataLoader.py
# This python file helps to get the data from the files, format and make it ready for transformers from .tools import * from transformers import BertTokenizer from multiprocessing import Pool, cpu_count import pickle, copy import logging from torch.utils.data import (DataLoader, RandomSampler, SequentialSampler, ...
@classmethod def _read_tsv(cls, input_file, quotechar=None): """Reads a tab separated value file.""" with open(input_file, "r", encoding="utf-8") as f: reader = csv.reader(f, delimiter="\t", quotechar=quotechar) lines = [] for line in reader: ...
report_dir = config.programsettings.REPORTS_DIR # if os.path.exists(report_dir) and os.listdir(report_dir): # report_dir += f'/report_{len(os.listdir(report_dir))}' # os.makedirs(report_dir) output_dir = config.programsettings.OUTPUT_DIR if not os.path.exists(output_dir)...
identifier_body
getSocialInformation.js
import { getClient } from '../apiUtilities/commonRequestUtility'; import axios from 'axios'; export function getSocialInformation()
{ return axios({ method: "POST", url: "http://localhost:4000/graphql", data: { query: ` { authorDetails { popularity isTrending title descr...
identifier_body
getSocialInformation.js
import { getClient } from '../apiUtilities/commonRequestUtility'; import axios from 'axios'; export function
() { return axios({ method: "POST", url: "http://localhost:4000/graphql", data: { query: ` { authorDetails { popularity isTrending title de...
getSocialInformation
identifier_name
getSocialInformation.js
import { getClient } from '../apiUtilities/commonRequestUtility'; import axios from 'axios'; export function getSocialInformation() { return axios({ method: "POST", url: "http://localhost:4000/graphql", data: { query: ` { authorDetails { ...
// "pledgerCount" : 0, // "status" : 0 // }, // { // "author" : { // "name" : "Phyllis Love", // "picture" : "https://images.pexels.com/photos/774909/pexels-photo-774909.jpeg?auto=compress&cs=tinysrgb&dpr=2&w=500", // "score" : 43.0 // }, // ...
// "pledgeGoal" : 200,
random_line_split
gen_plantuml.py
import os import re import requests from .gen_base import ReportGenerator, CmdLineGenerator # from pydbg import dbg import logging from common.logger import config_log import functools from common.url_to_data import url_to_data from common.plantuml import deflate_and_encode import asyncio from async_lru import alru_cac...
(plant_uml_txt: str, plantuml_server_local_url: str) -> str: """Async version of getting image url from plantuml. This does not get the actual image, that is a separate call - unlike in a browser where that second call is done automatically. Uses `url_to_data`, and only returns extracted url, no response ...
plant_uml_create_png_and_return_image_url_async
identifier_name
gen_plantuml.py
import os import re import requests from .gen_base import ReportGenerator, CmdLineGenerator # from pydbg import dbg import logging from common.logger import config_log import functools from common.url_to_data import url_to_data from common.plantuml import deflate_and_encode import asyncio from async_lru import alru_cac...
edge_lookup = { "generalisation" : "--|>", "composition" : "<--", "association" : "..", } # TODO need to persist and represent cardinality, which is in the pmodel after all !! result = "" for node in displaymodel.graph.nodes: if hasattr(node, "comment"): result +...
identifier_body
gen_plantuml.py
import os import re import requests from .gen_base import ReportGenerator, CmdLineGenerator # from pydbg import dbg import logging from common.logger import config_log import functools from common.url_to_data import url_to_data from common.plantuml import deflate_and_encode import asyncio from async_lru import alru_cac...
img.show() print("Done!") @alru_cache(maxsize=32) async def plant_uml_create_png_and_return_image_url_async(plant_uml_txt: str, plantuml_server_local_url: str) -> str: """Async version of getting image url from plantuml. This does not get the actual image, that is a separate call - u...
# This will open the image in your default image viewer. from PIL import Image img = Image.open(outpng)
random_line_split
gen_plantuml.py
import os import re import requests from .gen_base import ReportGenerator, CmdLineGenerator # from pydbg import dbg import logging from common.logger import config_log import functools from common.url_to_data import url_to_data from common.plantuml import deflate_and_encode import asyncio from async_lru import alru_cac...
else: print("ok getting generating uml but error pulling down image") else: print("error calling plantuml server", response.status_code) # New def displaymodel_to_plantuml(displaymodel): # TODO Should use AlsmMgr.calc_plant_uml() edge_lookup = { "generalisation" : "--...
with open(output_filename, "wb") as fp: fp.write(response.content)
conditional_block
update.go
// Copyright (c) 2019 Uber Technologies, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law o...
vents []*v1pbevent.Event) {} // Start starts processing status update events func (p *statusUpdate) Start() { p.applier.start() for _, client := range p.eventClients { client.Start() } log.Info("Task status updater started") for _, listener := range p.listeners { listener.Start() } } // Stop stops processin...
V1Events(e
identifier_name
update.go
// Copyright (c) 2019 Uber Technologies, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law o...
log.Info("Task status updater started") for _, listener := range p.listeners { listener.Start() } } // Stop stops processing status update events func (p *statusUpdate) Stop() { for _, client := range p.eventClients { client.Stop() } log.Info("Task status updater stopped") for _, listener := range p.listener...
client.Start() }
conditional_block
update.go
// Copyright (c) 2019 Uber Technologies, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law o...
// GetEventProgress returns the progress of the event progressing func (p *statusUpdate) GetEventProgress() uint64 { return p.applier.GetEventProgress() } // ProcessStatusUpdate processes the actual task status func (p *statusUpdate) ProcessStatusUpdate( ctx context.Context, updateEvent *statusupdate.Event, ) erro...
// OnV1Event is the callback function notifying an event func (p *statusUpdate) OnV1Event(event *v1pbevent.Event) { log.WithField("event_offset", event.Offset).Debug("JobMgr received v1 event") p.applier.addV1Event(event) }
random_line_split
update.go
// Copyright (c) 2019 Uber Technologies, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law o...
// ProcessListeners is for v0 only as we will remove the eventforwarder in v1. func (p *statusUpdate) ProcessListeners(event *statusupdate.Event) { if event != nil && event.V1() != nil { return } for _, listener := range p.listeners { listener.OnV0Events([]*pb_eventstream.Event{event.V0()}) } } // OnEvents is ...
// Update volume state to be created if task enters RUNNING state. volumeInfo, err := p.volumeStore.GetPersistentVolume(ctx, taskInfo.GetRuntime().GetVolumeID()) if err != nil { log.WithError(err).WithFields(log.Fields{ "job_id": taskInfo.GetJobId().GetValue(), "instance_id": taskInfo.GetInstanc...
identifier_body
parser.go
package parser import ( "bytes" "fmt" "github.com/go-graphite/carbonapi/expr/holtwinters" "regexp" "strconv" "strings" "time" "unicode" "unicode/utf8" "github.com/ansel1/merry" ) // expression parser type expr struct { target string etype ExprType val float64 valStr string args [...
() string { return e.target } func (e *expr) FloatValue() float64 { return e.val } func (e *expr) StringValue() string { return e.valStr } func (e *expr) SetValString(value string) { e.valStr = value } func (e *expr) MutateValString(value string) Expr { e.SetValString(value) return e } func (e *expr) RawArgs...
Target
identifier_name
parser.go
package parser import ( "bytes" "fmt" "github.com/go-graphite/carbonapi/expr/holtwinters" "regexp" "strconv" "strings" "time" "unicode" "unicode/utf8" "github.com/ansel1/merry" ) // expression parser type expr struct { target string etype ExprType val float64 valStr string args [...
func (e *expr) GetFloatArgDefault(n int, v float64) (float64, error) { if len(e.args) <= n { return v, nil } return e.args[n].doGetFloatArg() } func (e *expr) GetFloatNamedOrPosArgDefault(k string, n int, v float64) (float64, error) { if a := e.getNamedArg(k); a != nil { return a.doGetFloatArg() } return e...
random_line_split
parser.go
package parser import ( "bytes" "fmt" "github.com/go-graphite/carbonapi/expr/holtwinters" "regexp" "strconv" "strings" "time" "unicode" "unicode/utf8" "github.com/ansel1/merry" ) // expression parser type expr struct { target string etype ExprType val float64 valStr string args [...
func (e *expr) GetIntArgs(n int) ([]int, error) { if len(e.args) < n { return nil, ErrMissingArgument } ints := make([]int, 0, len(e.args)-n) for i := n; i < len(e.args); i++ { a, err := e.GetIntArg(i) if err != nil { return nil, err } ints = append(ints, a) } return ints, nil } func (e *expr) ...
{ if len(e.args) <= n { return 0, ErrMissingArgument } return e.args[n].doGetIntArg() }
identifier_body
parser.go
package parser import ( "bytes" "fmt" "github.com/go-graphite/carbonapi/expr/holtwinters" "regexp" "strconv" "strings" "time" "unicode" "unicode/utf8" "github.com/ansel1/merry" ) // expression parser type expr struct { target string etype ExprType val float64 valStr string args [...
} return r2 case "holtWintersForecast": bootstrapInterval, err := e.GetIntervalNamedOrPosArgDefault("bootstrapInterval", 1, 1, holtwinters.DefaultBootstrapInterval) if err != nil { return nil } for i := range r { r[i].From -= bootstrapInterval } case "holtWintersConfidenceBands", "ho...
{ fromNew := v.From + i*int64(offs) untilNew := v.Until + i*int64(offs) r2 = append(r2, MetricRequest{ Metric: v.Metric, From: fromNew, Until: untilNew, }) }
conditional_block
02a-instructions.js
exports.seed = function(knex) { return knex('instructions').insert([ {text: 'Whisk the eggs, flour, sugar and salt until combined. Gradually add the milk and whisk until you get a smooth batter. Let stand for 15 minutes.'}, {text: 'In a small skillet over medium heat, melt the butter. Use a ladle to pour and ...
{text: 'Preheat the oven to 350°C.'}, {text: 'In a bowl whisk the flour with the eggs then add in the milk and the water and mix until well combined.'}, {text: 'Add salt and butter and beat until smooth.'}, {text: 'Grease a cupcake pan with butter. Pour the batter into the holes.'}, {text: 'Bake for...
{text: 'Mix the flour, baking powder, maple syrup, caster sugar and a pinch of salt together in a large bowl...'}, {text: 'Heat a small knob of butter and 1 tsp of oil in a large, non-stick frying pan over a medium heat...'}, {text: 'Serve your pancakes stacked up on a plate with a drizzle of maple syrup a...
random_line_split
slicerUserInteraction.py
import slicer import vtk import os import sys from diffusionqclib.dwi_attributes import dwi_attributes from diffusionqclib.saveResults import saveResults import numpy as np FAIL= '\tFail' # \t is for visually separating fail gradients UNSURE= '\tUnsure' # \t is for visually separating Unsure gradients class slicerG...
(self): # Return only if pushbutton save is pressed hdr, mri, grad_axis, _, _, _ = dwi_attributes(self.dwiPath) saveResults(self.prefix, self.directory, self.deletion, None, None, hdr, mri, grad_axis, True) # Getting specific point ID from graph # Switching among slices def sliceUpdate(self,_,dataP...
finishInteraction
identifier_name
slicerUserInteraction.py
import slicer import vtk import os import sys from diffusionqclib.dwi_attributes import dwi_attributes from diffusionqclib.saveResults import saveResults import numpy as np FAIL= '\tFail' # \t is for visually separating fail gradients UNSURE= '\tUnsure' # \t is for visually separating Unsure gradients class slicerG...
axialView.SetSliceOffset(offset) def discardGradient(self): arr = self.dwiNode.GetDiffusionWeightedVolumeDisplayNode() # Mark the corresponding gradient as fail diffusion_index= arr.GetDiffusionComponent() self.deletion[diffusion_index]= 0 # bad ones are marked with 0 table = ...
offset= res*slice_index+org
conditional_block
slicerUserInteraction.py
import slicer import vtk import os import sys from diffusionqclib.dwi_attributes import dwi_attributes from diffusionqclib.saveResults import saveResults import numpy as np FAIL= '\tFail' # \t is for visually separating fail gradients UNSURE= '\tUnsure' # \t is for visually separating Unsure gradients class slicerG...
def finishInteraction(self): # Return only if pushbutton save is pressed hdr, mri, grad_axis, _, _, _ = dwi_attributes(self.dwiPath) saveResults(self.prefix, self.directory, self.deletion, None, None, hdr, mri, grad_axis, True) # Getting specific point ID from graph # Switching among slices de...
self.dwiPath= userDWIpath self.prefix = os.path.basename(self.dwiPath.split('.')[0]) self.directory = os.path.dirname(os.path.abspath(self.dwiPath)) self.deletion= np.load(os.path.join(self.directory, self.prefix+'_QC.npy')) self.confidence= np.load(os.path.join(self.directory, self.prefix+'_confidence....
identifier_body
slicerUserInteraction.py
import slicer import vtk import os import sys from diffusionqclib.dwi_attributes import dwi_attributes from diffusionqclib.saveResults import saveResults import numpy as np FAIL= '\tFail' # \t is for visually separating fail gradients UNSURE= '\tUnsure' # \t is for visually separating Unsure gradients class slicerG...
# Switch to a layout that contains a plot view to create a plot widget layoutManager = slicer.app.layoutManager() layoutWithPlot = slicer.modules.plots.logic().GetLayoutWithPlot(layoutManager.layout) layoutManager.setLayout(layoutWithPlot) # Properly set the plot chart interaction mode # Sele...
plotChartNode.SetYAxisTitle('KL div')
random_line_split
main.rs
use crate::{message::Message, weapon::Weapon}; use rg3d::{ core::{ algebra::{UnitQuaternion, Vector3}, color::Color, color_gradient::{ColorGradient, GradientPoint}, math::ray::Ray, numeric_range::NumericRange, pool::{Handle, Pool}, }, engine::{ resourc...
game.player.process_input_event(&event); match event { Event::MainEventsCleared => { // This main game loop - it has fixed time step which means that game // code will run at fixed speed even if renderer can't give you desired // 60 fps. ...
let clock = time::Instant::now(); let mut elapsed_time = 0.0; event_loop.run(move |event, _, control_flow| {
random_line_split
main.rs
use crate::{message::Message, weapon::Weapon}; use rg3d::{ core::{ algebra::{UnitQuaternion, Vector3}, color::Color, color_gradient::{ColorGradient, GradientPoint}, math::ray::Ray, numeric_range::NumericRange, pool::{Handle, Pool}, }, engine::{ resourc...
() { // Configure main window first. let window_builder = WindowBuilder::new().with_title("3D Shooter Tutorial"); // Create event loop that will be used to "listen" events from the OS. let event_loop = EventLoop::new(); // Finally create an instance of the engine. let mut engine = GameEngine::n...
main
identifier_name
main.rs
use crate::{message::Message, weapon::Weapon}; use rg3d::{ core::{ algebra::{UnitQuaternion, Vector3}, color::Color, color_gradient::{ColorGradient, GradientPoint}, math::ray::Ray, numeric_range::NumericRange, pool::{Handle, Pool}, }, engine::{ resourc...
fn update(&mut self, scene: &mut Scene) { // Set pitch for the camera. These lines responsible for up-down camera rotation. scene.graph[self.camera].local_transform_mut().set_rotation( UnitQuaternion::from_axis_angle(&Vector3::x_axis(), self.controller.pitch.to_radians()), ); ...
{ // Create a pivot and attach a camera to it, move it a bit up to "emulate" head. let camera; let weapon_pivot; let pivot = BaseBuilder::new() .with_children(&[{ camera = CameraBuilder::new( BaseBuilder::new() .with...
identifier_body
lib.rs
#![deny( future_incompatible, nonstandard_style, rust_2018_compatibility, rust_2018_idioms, unused, missing_docs )] //! # luomu-libpcap //! //! Safe and mostly sane Rust bindings for [libpcap](https://www.tcpdump.org/). //! //! We are split in two different crates: //! //! * `luomu-libpcap-sy...
(&self) -> u32 { self.stats.ps_recv } /// Return number of packets dropped because there was no room in the /// operating system's buffer when they arrived, because packets weren't /// being read fast enough. pub fn packets_dropped(&self) -> u32 { self.stats.ps_drop } /// R...
packets_received
identifier_name
lib.rs
#![deny( future_incompatible, nonstandard_style, rust_2018_compatibility, rust_2018_idioms, unused, missing_docs )] //! # luomu-libpcap //! //! Safe and mostly sane Rust bindings for [libpcap](https://www.tcpdump.org/). //! //! We are split in two different crates: //! //! * `luomu-libpcap-sy...
pub fn capture(&self) -> PcapIter<'_> { PcapIter::new(&self.pcap_t) } /// Transmit a packet pub fn inject(&self, buf: &[u8]) -> Result<usize> { pcap_inject(&self.pcap_t, buf) } /// activate a capture /// /// This is used to activate a packet capture to look at packets o...
random_line_split
datatransform.py
""" DataTransform Module - IDStruct - DataTransform (superclass) """ # pylint: disable=E0401, E0611 import re from functools import wraps from biothings.utils.common import is_str, iter_n from biothings.utils.loggers import get_logger from .histogram import Histogram class IDStruct(object): """ IDStruct - i...
return res_id_strct def nested_lookup(doc, field): """ Performs a nested lookup of doc using a period (.) delimited list of fields. This is a nested dictionary lookup. :param doc: document to perform lookup on :param field: period delimited list of fields :return: """ value =...
res_id_strct.add(left, re.sub(self.from_regex, self.to_regex, right))
conditional_block
datatransform.py
""" DataTransform Module - IDStruct - DataTransform (superclass) """ # pylint: disable=E0401, E0611 import re from functools import wraps from biothings.utils.common import is_str, iter_n from biothings.utils.loggers import get_logger from .histogram import Histogram class IDStruct(object): """ IDStruct - i...
""" virtual method for edge lookup. Each edge class is responsible for its own lookup procedures given a keylookup_obj and an id_strct :param keylookup_obj: :param id_strct: - list of tuples (orig_id, current_id) :return: """ yield NotImplemented(...
def edge_lookup(self, keylookup_obj, id_strct, debug=False): # pylint: disable=E1102, R0201, W0613
random_line_split
datatransform.py
""" DataTransform Module - IDStruct - DataTransform (superclass) """ # pylint: disable=E0401, E0611 import re from functools import wraps from biothings.utils.common import is_str, iter_n from biothings.utils.loggers import get_logger from .histogram import Histogram class IDStruct(object): """ IDStruct - i...
(self, other): """object += additional, which combines lists""" if not isinstance(other, IDStruct): raise TypeError("other is not of type IDStruct") for left, right in other: self.add(left, right) # retain debug information self.transfer_debug(left...
__iadd__
identifier_name
datatransform.py
""" DataTransform Module - IDStruct - DataTransform (superclass) """ # pylint: disable=E0401, E0611 import re from functools import wraps from biothings.utils.common import is_str, iter_n from biothings.utils.loggers import get_logger from .histogram import Histogram class IDStruct(object): """ IDStruct - i...
def __iter__(self): """iterator overload function""" for key in self.forward: for val in self.forward[key]: yield key, val def add(self, left, right): """add a (original_id, current_id) pair to the list""" if not left or not right: retur...
"""initialze _id_tuple_lst""" for doc in doc_lst: value = nested_lookup(doc, field) if value: self.add(value, value)
identifier_body
macos.rs
#![cfg(target_os = "macos")] use super::*; use std::ffi::{OsStr, OsString}; use std::os::unix::ffi::{OsStrExt, OsStringExt}; impl From<u32> for LocalProcessStatus { fn from(s: u32) -> Self { match s { 1 => Self::Idle, 2 => Self::Run, 3 => Self::Sleep, 4 => Se...
#[cfg(test)] mod tests { use std::path::Path; use super::parse_exe_and_argv_sysctl; #[test] fn test_trailing_zeros() { // Example data generated from running 'sleep 5' on the commit author's local machine, let buf = vec![ 2, 0, 0, 0, 47, 98, 105, 110, 47, 115, 108, 101, 1...
{ use libc::c_int; // The data in our buffer is laid out like this: // argc - c_int // exe_path - NUL terminated string // argv[0] - NUL terminated string // argv[1] - NUL terminated string // ... // argv[n] - NUL terminated string // envp[0] - NUL terminated string // ... ...
identifier_body
macos.rs
#![cfg(target_os = "macos")] use super::*; use std::ffi::{OsStr, OsString}; use std::os::unix::ffi::{OsStrExt, OsStringExt}; impl From<u32> for LocalProcessStatus { fn from(s: u32) -> Self { match s { 1 => Self::Idle, 2 => Self::Run, 3 => Self::Sleep, 4 => Se...
} fn exe_for_pid(pid: libc::pid_t) -> PathBuf { LocalProcessInfo::executable_path(pid as _).unwrap_or_else(PathBuf::new) } let procs: Vec<_> = all_pids().into_iter().filter_map(info_for_pid).collect(); fn build_proc(info: &libc::proc_bsdinfo, procs: &[libc::proc_bs...
parse_exe_and_argv_sysctl(buf)
random_line_split
macos.rs
#![cfg(target_os = "macos")] use super::*; use std::ffi::{OsStr, OsString}; use std::os::unix::ffi::{OsStrExt, OsStringExt}; impl From<u32> for LocalProcessStatus { fn from(s: u32) -> Self { match s { 1 => Self::Idle, 2 => Self::Run, 3 => Self::Sleep, 4 => Se...
(ptr: &mut &[u8]) -> Option<String> { // Parse to the end of a null terminated string let nul = ptr.iter().position(|&c| c == 0)?; let s = String::from_utf8_lossy(&ptr[0..nul]).to_owned().to_string(); *ptr = ptr.get(nul + 1..)?; // Find the position of the first non null byte. `...
consume_cstr
identifier_name
wallet.rs
//! The wallet module. //! //! Since this wallet implementation is supposed to work on top of both a //! Bitcoin Core node as an Elements or Liquid node, we avoid using the //! specialized bitcoincore-rpc and liquid-rpc client interfaces, but use //! general call methods so we can leverage the common parts of the raw /...
error!("Address is labeled with unknown master xpriv fingerprint: {:?}", fp); return Err(Error::CorruptNodeData); }; let privkey = xpriv.derive_priv(&SECP, &[child])?.private_key; Ok(privkey.key) } pub fn updates(&mut self) -> Result<Vec<Value>, Error> { ...
self.external_xpriv } else if fp == self.internal_xpriv.fingerprint(&SECP) { self.internal_xpriv } else {
random_line_split
wallet.rs
//! The wallet module. //! //! Since this wallet implementation is supposed to work on top of both a //! Bitcoin Core node as an Elements or Liquid node, we avoid using the //! specialized bitcoincore-rpc and liquid-rpc client interfaces, but use //! general call methods so we can leverage the common parts of the raw /...
(&self) -> Result<Value, Error> { let mempoolinfo: Value = self.rpc.call("getmempoolinfo", &[])?; let minrelayfee = json!(btc_to_usat(mempoolinfo["minrelaytxfee"].as_f64().req()? / 1000.0)); let mut estimates: Vec<Value> = (2u16..25u16) .map(|target| { let est: rpcjs...
_make_fee_estimates
identifier_name
wallet.rs
//! The wallet module. //! //! Since this wallet implementation is supposed to work on top of both a //! Bitcoin Core node as an Elements or Liquid node, we avoid using the //! specialized bitcoincore-rpc and liquid-rpc client interfaces, but use //! general call methods so we can leverage the common parts of the raw /...
else { Some(&self.cached_fees.0) } } pub fn _make_fee_estimates(&self) -> Result<Value, Error> { let mempoolinfo: Value = self.rpc.call("getmempoolinfo", &[])?; let minrelayfee = json!(btc_to_usat(mempoolinfo["minrelaytxfee"].as_f64().req()? / 1000.0)); let mut esti...
{ None }
conditional_block
wallet.rs
//! The wallet module. //! //! Since this wallet implementation is supposed to work on top of both a //! Bitcoin Core node as an Elements or Liquid node, we avoid using the //! specialized bitcoincore-rpc and liquid-rpc client interfaces, but use //! general call methods so we can leverage the common parts of the raw /...
pub fn sign_transaction(&self, details: &Value) -> Result<String, Error> { debug!("sign_transaction(): {:?}", details); let change_address = self.next_address(&self.internal_xpriv, &self.next_internal_child)?; // If we don't have any inputs, we can fail early. let unspent: Vec<Val...
{ debug!("create_transaction(): {:?}", details); let unfunded_tx = match self.network.id() { NetworkId::Bitcoin(..) => coins::btc::create_transaction(&self.rpc, details)?, NetworkId::Elements(..) => coins::liq::create_transaction(&self.rpc, details)?, }; debug!("...
identifier_body