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 |
|---|---|---|---|---|
instance.rs | .len()]))?;
val /= CHARS.len();
}
Ok(())
}
}
#[derive(Debug)]
struct ParsedEdgeHandler {
edge_incidences: Vec<SkipVec<(NodeIdx, EntryIdx)>>,
node_degrees: Vec<usize>,
}
impl ParsedEdgeHandler {
fn handle_edge(&mut self, node_indices: impl IntoIterator<Item = Result<usize>>)... | (&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 | 64)
buf = array.array('b', [0] * 64)
ioctl(jsdev, 0x80006a13 + (0x10000 * len(buf)), buf) # JSIOCGNAME(len)
js_name = buf.tostring()
print('Device name: %s' % js_name)
# Get number of axes and buttons.
buf = array.array('B', [0])
ioctl(jsdev, 0x80016a11, buf) ... |
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 | 64)
buf = array.array('b', [0] * 64)
ioctl(jsdev, 0x80006a13 + (0x10000 * len(buf)), buf) # JSIOCGNAME(len)
js_name = buf.tostring()
print('Device name: %s' % js_name)
# Get number of axes and buttons.
buf = array.array('B', [0])
ioctl(jsdev, 0x80016a11, buf) ... | if event_type & 0x01:
button = button_map[number]
if button:
button_states[button] = value
haveJoystickEvent = True
if event_type & 0x02:
selected_axis... | 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 | lastCharge = charge
charge = value
if not charge == lastCharge:
motorSpeed = int(85 + charge * (105 - 85) / 100)
print("DUCK motor speed: " + str(motorSpeed) + " charge:" + str(charge))
# moveServo(13, motorSpeed)
pyros.publish("servo/13", str(motorSpeed))
def addCharge(am... | calcRoverSpeed | identifier_name | |
jcontroller_service.py | :
# print("shooting ducks")
# if tr:
# pyros.publish("servo/9", "115")
# else:
# pyros.publish("servo/9", "175")
#
# if tl and not lastTL:
# target_charge = 100
# print("charging")
# elif not tl and lastTL:
# ... | 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::runtime::Runtime;
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! {
... |
let jh = self.runtime.spawn(async move {
| {
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::runtime::Runtime;
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! {
... |
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 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::runtime::Runtime;
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! {
... | {
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 | , 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 environment
agent: RLC chess agent
gamma: discount factor
search_time: maximu... |
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 |
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 | 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 environment
agent: RLC chess agent
gamma: discount factor
search_time: maxim... | 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 | (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 | (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 | ([], limit=1)
if record:
for name, fld in record._fields.items():
domain += insert_missing(fld, record)
action = {
'name': _('Translate view'),
'type': 'ir.actions.act_window',
'res_model': 'ir.translation',
'view_mode': 'tree'... | '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 | ir.ui.view']
# If we have no view_id to inherit from, it's because we are adding
# fields to the default view of a new model. We will materialize the
# default view as a true view so we can keep using our xpath mechanism.
if view_id:
view = View.browse(view_id)
else:
... | xml_node = etree.Element('attribute', {'name': key})
xml_node.text = new_attr
xpath_node.insert(0, xml_node) | conditional_block | |
main.py | ([], limit=1)
if record:
for name, fld in record._fields.items():
domain += insert_missing(fld, record)
action = {
'name': _('Translate view'),
'type': 'ir.actions.act_window',
'res_model': 'ir.translation',
'view_mode': 'tree'... | # View Base: <field name="x"/><field name="y"/>
# View Standard inherits Base: <field name="x" position="after"><field name="z"/></field>
# View Custo inherits Base: <field name="x" position="after"><field name="x2"/></field>
# We want x,x2,z,y, because that's what we did... | 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 | be set in Asset<TextureAtlas>.
//! let texture_atlas_handle = Handle::weak(HandleId::random::<TextureAtlas>());
//!
//! let mut tilemap = Tilemap::new(texture_atlas_handle, 32, 32);
//!
//! // There are two ways to create a new chunk. Either directly...
//!
//! tilemap.insert_chunk((0, 0));
//!
//! // Or indirectly...... | 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 | be set in Asset<TextureAtlas>.
//! let texture_atlas_handle = Handle::weak(HandleId::random::<TextureAtlas>());
//!
//! let mut tilemap = Tilemap::new(texture_atlas_handle, 32, 32);
//!
//! // There are two ways to create a new chunk. Either directly...
//!
//! tilemap.insert_chunk((0, 0));
//!
//! // Or indirectly...... |
/// 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 | { point, sprite_index, ..Default::default() };
//! tilemap.insert_tile(tile);
//!
//! ```
//!
//! # Specifying what kind of chunk
//! ```
//! use bevy_asset::{prelude::*, HandleId};
//! use bevy_sprite::prelude::*;
//! use bevy_tilemap::prelude::*;
//!
//! // This must be set in Asset<TextureAtlas>.
//! let texture_at... | get_tile_mut | identifier_name | |
mod.rs | must be set in Asset<TextureAtlas>.
//! let texture_atlas_handle = Handle::weak(HandleId::random::<TextureAtlas>());
//!
//! let mut tilemap = Tilemap::new(texture_atlas_handle, 32, 32);
//!
//! // There are two ways to create a new chunk. Either directly...
//!
//! tilemap.insert_chunk((0, 0));
//!
//! // Or indirect... |
/// | } | random_line_split |
process.rs | specified, UV_READABLE_PIPE and UV_WRITABLE_PIPE determine the
/// direction of flow, from the child process' perspective. Both flags may be specified to
/// create a duplex data stream.
const READABLE_PIPE = uv::uv_stdio_flags_UV_READABLE_PIPE as _;
const WRITABLE_PIPE = uv::uv_stdio_f... | {
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 | /// 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 | specified, UV_READABLE_PIPE and UV_WRITABLE_PIPE determine the
/// direction of flow, from the child process' perspective. Both flags may be specified to
/// create a duplex data stream.
const READABLE_PIPE = uv::uv_stdio_flags_UV_READABLE_PIPE as _;
const WRITABLE_PIPE = uv::uv_stdio_f... | }
// 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 | 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 | raise MatrixError
x = numpy.ascontiguousarray(other.T, dtype=self.dtype)
y = numpy.empty(x.shape[:-1] + self.shape[:1], dtype=self.dtype)
if other.ndim == 1:
self.mkl_('csrgemv', 'N', byref(c_int(self.shape[0])),
self.data.ctypes, self.rowptr.ctypes, self.colid... | mtype = dict(f=-2, c=6) | conditional_block | |
_mkl.py | :
'''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 | 4) # handle to data structure
self.maxfct = c_int(1)
self.mnum = c_int(1)
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... |
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 | return [n for n in self if n.anchored]
def add_edge(self, t1, t2, key=None, attr_dict=None, **attrs):
"""Add annotation to the graph between times t1 and t2
Parameters
----------
t1, t2: float, str or None
data : dict, optional
{annotation_type: annotation_valu... | add existing | conditional_block | |
transcription.py | nbunch=[drifting_t], data=True, keys=True
):
self.add_edge(another_t, t, key=key, attr_dict=data)
# remove drifting_t node (as it was replaced by another_t)
self.remove_node(drifting_t)
def anchor(self, drifting_t, anchored_t):
"""
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~... | 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 | in self if n.drifting]
def anchored(self):
"""Get list of anchored times"""
return [n for n in self if n.anchored]
def add_edge(self, t1, t2, key=None, attr_dict=None, **attrs):
"""Add annotation to the graph between times t1 and t2
Parameters
----------
t1, t... | random_line_split | ||
transcription.py | ):
self.add_edge(another_t, t, key=key, attr_dict=data)
# remove drifting_t node (as it was replaced by another_t)
self.remove_node(drifting_t)
def anchor(self, drifting_t, anchored_t):
"""
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
o -- [ D ] -- o ... | from note | identifier_name | |
ccm.rs | ///
/// MUST NOT modify the plaintext buffer.
fn encrypt(&mut self);
}
pub struct | <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 | ///
/// MUST NOT modify the plaintext buffer.
fn encrypt(&mut self);
}
pub struct CCM<Block, Nonce> {
block: Block,
tag_size: usize,
length_size: usize,
nonce: Nonce,
}
impl<Block: BlockCipherBuffer, Nonce: AsRef<[u8]>> CCM<Block, Nonce> {
///
/// Arguments:
/// - block:
/// -... | 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 | 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;
assert_eq!(nonce_size, nonce.as_ref().len());
... | {
assert_eq!(key.len(), KEY_SIZE);
Self {
cipher: AESBlockCipher::create(key).unwrap(),
plaintext: [0u8; BLOCK_SIZE],
ciphertext: [0u8; BLOCK_SIZE],
}
} | identifier_body | |
ccm.rs | ///
/// MUST NOT modify the plaintext buffer.
fn encrypt(&mut self);
}
pub struct CCM<Block, Nonce> {
block: Block,
tag_size: usize,
length_size: usize,
nonce: Nonce,
}
impl<Block: BlockCipherBuffer, Nonce: AsRef<[u8]>> CCM<Block, Nonce> {
/// | /// - 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 | ::{
Multiaddr, PublicKey,
upgrade::{InboundUpgrade, OutboundUpgrade, UpgradeInfo, Negotiated}
};
use log::{debug, trace};
use protobuf::Message as ProtobufMessage;
use protobuf::parse_from_bytes as protobuf_parse_from_bytes;
use protobuf::RepeatedField;
use std::convert::TryFrom;
use std::io::{Error as IoError,... | (&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 | ify::new();
message.set_agentVersion(info.agent_version);
message.set_protocolVersion(info.protocol_version);
message.set_publicKey(pubkey_bytes);
message.set_listenAddrs(listen_addrs);
message.set_observedAddr(observed_addr.to_vec());
message.set_protocols(RepeatedField:... | "/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 | ::{
Multiaddr, PublicKey,
upgrade::{InboundUpgrade, OutboundUpgrade, UpgradeInfo, Negotiated}
};
use log::{debug, trace};
use protobuf::Message as ProtobufMessage;
use protobuf::parse_from_bytes as protobuf_parse_from_bytes;
use protobuf::RepeatedField;
use std::convert::TryFrom;
use std::io::{Error as IoError,... |
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 | type Stream struct {
CommunityID string `db:"community_id"`
PublicKey string `db:"public_key"`
Operations Operations `db:"operations"`
StreamID string
Token string
Device *Device
}
// Operation is a type used to capture the data around the operations to be
// applied to a Stream.
type Operation s... | err = rows.StructScan(&d)
if err != nil {
return errors.Wrap(err, "failed to scan row into Device struct")
}
devices = append(devices, | {
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 | type Stream struct {
CommunityID string `db:"community_id"`
PublicKey string `db:"public_key"`
Operations Operations `db:"operations"`
StreamID string
Token string
Device *Device
}
// Operation is a type used to capture the data around the operations to be
// applied to a Stream.
type Operation s... | (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 | Stream struct {
CommunityID string `db:"community_id"`
PublicKey string `db:"public_key"`
Operations Operations `db:"operations"`
StreamID string
Token string
Device *Device
}
// Operation is a type used to capture the data around the operations to be
// applied to a Stream.
type Operation struc... |
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 | type Stream struct {
CommunityID string `db:"community_id"`
PublicKey string `db:"public_key"`
Operations Operations `db:"operations"`
StreamID string
Token string
Device *Device
}
// Operation is a type used to capture the data around the operations to be
// applied to a Stream.
type Operation s... | // 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 | width={1}
>
<Box padding="0 1em">
<FullScreen />
</Box>
<Box padding="1em">
<Progress />
</Box>
</FlexBox>
);
// SPECTACLE_CLI_TEMPLATE_END
const cssTricksCodeBlock = indentNormalizer(`
img:not([alt]),
img[alt=""] {
border: 5px dashed red;
}
`)
const Presentation = () => ... | </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 | width={1}
>
<Box padding="0 1em">
<FullScreen />
</Box>
<Box padding="1em">
<Progress />
</Box>
</FlexBox>
);
// SPECTACLE_CLI_TEMPLATE_END
const cssTricksCodeBlock = indentNormalizer(`
img:not([alt]),
img[alt=""] {
border: 5px dashed red;
}
`)
const Presentation = () => ... | .\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 | passes the most commonly used USB descriptors.
func WithIPPUSBDescriptors() Option {
return WithDescriptors("ippusb_printer.json")
}
// WithDescriptors sets the required descriptors.
func WithDescriptors(path string) Option {
return func(o *config) error {
if len(path) == 0 {
return errors.New("empty descripto... |
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 | passes the most commonly used USB descriptors.
func WithIPPUSBDescriptors() Option {
return WithDescriptors("ippusb_printer.json")
}
// WithDescriptors sets the required descriptors.
func WithDescriptors(path string) Option {
return func(o *config) error {
if len(path) == 0 {
return errors.New("empty descripto... |
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 | passes the most commonly used USB descriptors.
func WithIPPUSBDescriptors() Option {
return WithDescriptors("ippusb_printer.json")
}
// WithDescriptors sets the required descriptors.
func WithDescriptors(path string) Option {
return func(o *config) error {
if len(path) == 0 {
return errors.New("empty descripto... | (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 | passes the most commonly used USB descriptors.
func WithIPPUSBDescriptors() Option {
return WithDescriptors("ippusb_printer.json")
}
// WithDescriptors sets the required descriptors.
func WithDescriptors(path string) Option {
return func(o *config) error {
if len(path) == 0 {
return errors.New("empty descripto... | 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 | _client.platform
# ......dart_server.platform
# ......dart_shared.platform
# ......_internal/
#.........spec.sum
#.........strong.sum
#.........dev_compiler/
# ......analysis_server/
# ......analyzer/
# ......async/
# ......collection/
# ......convert/
# ......core/
# ......front_end/
# ......html/
# ......internal/
# ... | (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 | ......kernel/
# ......math/
# ......mirrors/
# ......typed_data/
# ......api_readme.md
# ....util/
# ......(more will come here)
import optparse
import os
import re
import sys
import subprocess
import utils
HOST_OS = utils.GuessOS()
# TODO(dgrove): Only import modules following Google style guide.
from os.path i... | copytree(join(HOME, 'sdk', 'lib', library), join(LIB, library),
ignore=ignore_patterns('*.svn', 'doc', '*.py', '*.gypi', '*.sh',
'.gitignore')) | conditional_block | |
create_sdk.py | _client.platform
# ......dart_server.platform
# ......dart_shared.platform
# ......_internal/
#.........spec.sum
#.........strong.sum
#.........dev_compiler/
# ......analysis_server/
# ......analyzer/
# ......async/
# ......collection/
# ......convert/
# ......core/
# ......front_end/
# ......html/
# ......internal/
# ... | 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 | _client.platform
# ......dart_server.platform
# ......dart_shared.platform
# ......_internal/
#.........spec.sum
#.........strong.sum
#.........dev_compiler/
# ......analysis_server/
# ......analyzer/
# ......async/
# ......collection/
# ......convert/
# ......core/
# ......front_end/
# ......html/
# ......internal/
# ... |
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 | istretto::{CompressedRistretto, RistrettoPoint},
scalar::Scalar,
};
use merlin::{Transcript, TranscriptRng};
use rand_core::{CryptoRng, RngCore};
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
use zeroize::Zeroize;
use codec::{Decode, Encode, Error as CodecError, Input, Output};
use sp_std::convert... |
}
#[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 | istretto::{CompressedRistretto, RistrettoPoint},
scalar::Scalar,
};
use merlin::{Transcript, TranscriptRng};
use rand_core::{CryptoRng, RngCore};
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
use zeroize::Zeroize;
use codec::{Decode, Encode, Error as CodecError, Input, Output};
use sp_std::convert... | <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 | istretto::{CompressedRistretto, RistrettoPoint},
scalar::Scalar,
};
use merlin::{Transcript, TranscriptRng};
use rand_core::{CryptoRng, RngCore};
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
use zeroize::Zeroize;
use codec::{Decode, Encode, Error as CodecError, Input, Output};
use sp_std::convert... | /// 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 | (),
});
let (sc_desc, swap_chain) = Self::create_swap_chain(&device, size, &surface);
let (
size3d,
diffuse_texture,
diffuse_buffer,
diffuse_sampler,
diffuse_texture_view,
diffuse_bind_group,
texture_bind_group_... | resize | identifier_name | |
main.rs | ] = &[2, 1, 0, 3, 2, 0];
struct State {
surface: wgpu::Surface,
device: wgpu::Device,
queue: wgpu::Queue,
swap_chain: wgpu::SwapChain,
sc_desc: wgpu::SwapChainDescriptor,
render_pipeline: wgpu::RenderPipeline,
vertex_buffer: wgpu::Buffer,
index_buffer: wgpu::Buffer,
num_indices: u3... | 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 | = &[2, 1, 0, 3, 2, 0];
struct State {
surface: wgpu::Surface,
device: wgpu::Device,
queue: wgpu::Queue,
swap_chain: wgpu::SwapChain,
sc_desc: wgpu::SwapChainDescriptor,
render_pipeline: wgpu::RenderPipeline,
vertex_buffer: wgpu::Buffer,
index_buffer: wgpu::Buffer,
num_indices: u32... | width: dimensions.0,
height: dimensions.1,
depth: 1,
};
let diffuse_texture = device.create_texture(&wgpu::TextureDescriptor {
size: size3d,
array_layer_count: 1,
mip_level_count: 1,
sample_count: 1,
dimensio... | {
//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 | =None, label=None):
"""
guid: Unique id for the example.
text_a: string. The untokenized text of the first sequence. For single
sequence tasks, only this sequence must be specified.
text_b: (Optional) string. The untokenized text of the second sequence.
... | (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 | =None, label=None):
"""
guid: Unique id for the example.
text_a: string. The untokenized text of the first sequence. For single
sequence tasks, only this sequence must be specified.
text_b: (Optional) string. The untokenized text of the second sequence.
... | 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 | =None, label=None):
"""
guid: Unique id for the example.
text_a: string. The untokenized text of the first sequence. For single
sequence tasks, only this sequence must be specified.
text_b: (Optional) string. The untokenized text of the second sequence.
... |
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 | =None, label=None):
"""
guid: Unique id for the example.
text_a: string. The untokenized text of the first sequence. For single
sequence tasks, only this sequence must be specified.
text_b: (Optional) string. The untokenized text of the second sequence.
... |
@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 | authors{
name
picture
score
}
}
}
`
}
})
// const mySocialData=[
// {
// "author" : {
// ... | {
return axios({
method: "POST",
url: "http://localhost:4000/graphql",
data: {
query: `
{
authorDetails {
popularity
isTrending
title
descr... | identifier_body | |
getSocialInformation.js | () {
return axios({
method: "POST",
url: "http://localhost:4000/graphql",
data: {
query: `
{
authorDetails {
popularity
isTrending
title
de... | getSocialInformation | identifier_name | |
getSocialInformation.js | // "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 | entry.classesinheritsfrom:
self.result += "%s <|- %s\n" % (parentclass, self.aclass)
# aggregation relationships showing class dependency and composition relationships
for attrobj in self.classentry.attrs:
compositescreated = self._GetCompositeCreatedClassesF... | (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 | To(self, outpath=None): # Override and redefine Template method entirely
"""
"""
globbed = self.directories
self.p = PySourceAsPlantUml()
self.p.optionModuleAsClass = self.optionModuleAsClass
self.p.verbose = self.verbose
for f in globbed:
self.p.Pa... | 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 | .classentry.classesinheritsfrom:
self.result += "%s <|- %s\n" % (parentclass, self.aclass)
# aggregation relationships showing class dependency and composition relationships
for attrobj in self.classentry.attrs:
compositescreated = self._GetCompositeCreatedCl... | 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 | line = "..>"
cardinality = ""
if cardinality:
connector = '%s "%s"' % (line, cardinality)
else:
connector = line
self.result += "%s %s %s : %s\n" % (self.aclass, co... | with open(output_filename, "wb") as fp:
fp.write(response.content) | conditional_block | |
update.go | .RFC3339Nano))
default:
newRuntime.State = updateEvent.State()
}
cachedJob := p.jobFactory.AddJob(taskInfo.GetJobId())
// Update task start and completion timestamps
if newRuntime.GetState() == pb_task.TaskState_RUNNING {
if updateEvent.State() != taskInfo.GetRuntime().GetState() {
// StartTime is set at ... | V1Events(e | identifier_name | |
update.go | .GetState() == pb_task.TaskState_RUNNING {
if updateEvent.State() != taskInfo.GetRuntime().GetState() {
// StartTime is set at the time of first RUNNING event
// CompletionTime may have been set (e.g. task has been set),
// which could make StartTime larger than CompletionTime.
// Reset CompletionTime eve... | client.Start()
}
| conditional_block | |
update.go | 0Event is the callback function notifying an event
func (p *statusUpdate) OnV0Event(event *pb_eventstream.Event) {
log.WithField("event_offset", event.Offset).Debug("JobMgr received v0 event")
if event.GetType() != pbeventstream.Event_HOST_EVENT {
p.applier.addV0Event(event)
}
}
|
// 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 | updateEvent.TaskID(),
"db_task_runtime": taskInfo.GetRuntime(),
"task_status_event": updateEvent.MesosTaskStatus(),
}).Info("reschedule lost task if needed")
newRuntime.State = pb_task.TaskState_LOST
newRuntime.Message = "Task LOST: " + updateEvent.StatusMsg()
newRuntime.Reason = updateEvent.Reason()
... | // 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 | () 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 | adjustedReq := MetricRequest{
Metric: r[i].Metric,
From: r[i].From - bootstrapInterval,
Until: r[i].Until,
}
r = append(r, adjustedReq)
}
case "movingAverage", "movingMedian", "movingMin", "movingMax", "movingSum", "exponentialMovingAverage":
if len(e.args) < 2 {
return nil
}
... | 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 | adjustedReq := MetricRequest{
Metric: r[i].Metric,
From: r[i].From - bootstrapInterval,
Until: r[i].Until,
}
r = append(r, adjustedReq)
}
case "movingAverage", "movingMedian", "movingMin", "movingMax", "movingSum", "exponentialMovingAverage":
if len(e.args) < 2 {
return nil
}
... |
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 |
}
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 | griddle or non-stick pan over medium heat until hot. Put a pad of butter and one tablespoon vegetable oil onto the griddle, and swirl it around...'},
{text: 'Wipe the griddle clean with paper towels, add more butter and oil, and repeat with the remaining batter. Serve the pancakes while still hot with maple syrup,... | {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 | '))
self.KLdiv= np.load(os.path.join(self.directory, self.prefix+'_KLdiv.npy'))
self.qualityBackUp= self.deletion.copy()
self.confidenceBackUp= self.confidence.copy()
self.dwiNode= userDWInode
self.decisionLabel= label
self.summaryLabel= summary
# Write out algorithm summary
self.summa... | (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 | '))
self.KLdiv= np.load(os.path.join(self.directory, self.prefix+'_KLdiv.npy'))
self.qualityBackUp= self.deletion.copy()
self.confidenceBackUp= self.confidence.copy()
self.dwiNode= userDWInode
self.decisionLabel= label
self.summaryLabel= summary
# Write out algorithm summary
self.summa... |
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 |
arrX= vtk.vtkStringArray( )
arrX.SetName("Gradient #")
table.AddColumn(arrX)
arrY1 = vtk.vtkStringArray()
arrY1.SetName("Decision")
table.AddColumn(arrY1)
arrY2 = vtk.vtkStringArray()
arrY2.SetName("Confidence")
table.AddColumn(arrY2)
arrY3 = vtk.vtkStringArray()
arrY3.Se... | 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 | '))
self.KLdiv= np.load(os.path.join(self.directory, self.prefix+'_KLdiv.npy'))
self.qualityBackUp= self.deletion.copy()
self.confidenceBackUp= self.confidence.copy()
self.dwiNode= userDWInode
self.decisionLabel= label
self.summaryLabel= summary
# Write out algorithm summary
self.summa... |
# 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 | (velocity, true);
// Change the rotation of the rigid body according to current yaw. These lines responsible for
// left-right rotation.
let mut position = *body.position();
position.rotation =
UnitQuaternion::from_axis_angle(&Vector3::y_axis(), self.controller.yaw.to_radian... | let clock = time::Instant::now();
let mut elapsed_time = 0.0;
event_loop.run(move |event, _, control_flow| { | random_line_split | |
main.rs |
.get_mut(&self.rigid_body)
.unwrap();
// Keep only vertical velocity, and drop horizontal.
let mut velocity = Vector3::new(0.0, body.linvel().y, 0.0);
// Change the velocity depending on the keys pressed.
if self.controller.move_forward {
// If we m... | main | identifier_name | |
main.rs | Mode::ClampToEdge);
}
skybox
}
fn create_bullet_impact(
graph: &mut Graph,
resource_manager: ResourceManager,
pos: Vector3<f32>,
orientation: UnitQuaternion<f32>,
) -> Handle<Node> {
// Create sphere emitter first.
let emitter = SphereEmitterBuilder::new(
BaseEmitterBuilder::ne... | .build(&mut scene.graph);
weapon_pivot
}]),
)
.with_skybox(create_skybox(resource_manager).await)
.build(&mut scene.graph);
camera
}])
.build(&mut s... | {
// 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 | to look at packets on the
/// network. `source` is a string that specifies the network device to open.
pub fn new(source: &str) -> Result<Pcap> {
let pcap_t = pcap_create(source)?;
Ok(Pcap { pcap_t })
}
/// Create a capture handle for reading packets from given savefile.
///
//... | packets_received | identifier_name | |
lib.rs | /// Use it to set required options for the capture and then call
/// `PcapBuider::activate()` to activate the capture.
///
/// Then `Pcap::capture()` can be used to start an iterator for capturing
/// packets.
pub struct Pcap {
pcap_t: PcapT,
}
impl Pcap {
/// Create a live capture handle
///
/// This ... | 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 | , debugging information
will be retained in the 'dt_debug' field of each document. This parameter
can be either list of original id's to retain debugging information for or
a True, which will retain debugging information for all documents.
:type... | res_id_strct.add(left, re.sub(self.from_regex, self.to_regex, right)) | conditional_block | |
datatransform.py | _types = self._parse_output_types(output_types)
self.id_priority_list = id_priority_list or []
self.skip_on_failure = skip_on_failure
self.skip_on_success = skip_on_success
if skip_w_regex and not isinstance(skip_w_regex, str):
raise ValueError("skip_w_regex must be a strin... |
def edge_lookup(self, keylookup_obj, id_strct, debug=False):
# pylint: disable=E1102, R0201, W0613 | random_line_split | |
datatransform.py | (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 |
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 | Urgh. Let's re-cast it as the correct kind of slice.
let vip_path = unsafe {
std::slice::from_raw_parts(
pathinfo.pvi_cdir.vip_path.as_ptr() as *const u8,
libc::MAXPATHLEN as usize,
)
};
let nul = vip_path.iter().position(|&c| c == 0)?;
... | 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. `.position()`
// will return None if we run off the end.
if let Some(not_nul) =... | {
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 | Urgh. Let's re-cast it as the correct kind of slice.
let vip_path = unsafe {
std::slice::from_raw_parts(
pathinfo.pvi_cdir.vip_path.as_ptr() as *const u8,
libc::MAXPATHLEN as usize,
)
};
let nul = vip_path.iter().position(|&c| c == 0)?;
... | }
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 | Urgh. Let's re-cast it as the correct kind of slice.
let vip_path = unsafe {
std::slice::from_raw_parts(
pathinfo.pvi_cdir.vip_path.as_ptr() as *const u8,
libc::MAXPATHLEN as usize,
)
};
let nul = vip_path.iter().position(|&c| c == 0)?;
... | (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 internal address xpriv
fn calc_xkeys(
seed: &[u8],
) -> (bip32::ExtendedPrivKey, bip32::ExtendedPrivKey, bip32::ExtendedPrivKey) {
// Network isn't of importance here.
let master_xpriv =
bip32::ExtendedPrivKey::new_master(BNetwork::Bitcoin, &seed[..]).unwrap();
... | 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 | -bitcoincore-rpc once bitcoin::Amount lands
let mut args = vec![Value::Null, json!(min_conf), json!(true)];
#[cfg(feature = "liquid")]
{
if let NetworkId::Elements(net) = self.network.id() {
args.push(coins::liq::asset_hex(net).into());
}
}
... | _make_fee_estimates | identifier_name | |
wallet.rs | : u32) -> Result<Value, Error> {
//TODO(stevenroose) implement in rust-bitcoincore-rpc once bitcoin::Amount lands
let mut args = vec![Value::Null, json!(min_conf), json!(true)];
#[cfg(feature = "liquid")]
{
if let NetworkId::Elements(net) = self.network.id() {
... | {
None
} | conditional_block | |
wallet.rs | 0).unwrap()),
tip: None,
last_tx: None,
cached_fees: (Value::Null, Instant::now() - FEE_ESTIMATES_TTL * 2),
};
wallet.save_persistent_state()?;
Ok(wallet)
}
/// Login to an existing [Wallet].
pub fn login(network: &'static Network, mnemonic: &str)... | {
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 | |
main.py | float(args[10])
dGt3 = float(args[11])
out_file = args[12]
all_file = args[13]
all_kept_mutants = []
all_mutants_tried = []
output_dict = {}
count = 0
initialize_output_files(out_file, all_... |
print("runing folx analyze complex")
pyros.runFoldxAnalyzeComplex(new_mutant_name[0:-4] + '_complex', [old_mutant_name, new_mutant_name])
proceed = pyros.checkOutputAnalyzeComplex(new_mutant_name[0:-4])
#See if we got the files we needed from Analyze Complex
... | prefix, count, all_kept_mutants, all_mutants_tried, exists = does_file_exist(prefix, i, count, all_kept_mutants, all_mutants_tried)
if not exists:
continue
if available_mutations == 'random':
(mutation_code, site) = generate_mutation_code(prefix, which_chain)
... | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.