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 |
|---|---|---|---|---|
test2.py | :
def __init__(self, master):
self.video = None
self.frame_rate = 0
self.video_length = 0
# The scaled image used for display. Needs to persist for display
self.display_image = None
self.display_ratio = 0
self.awaiting_corners = False
self.corners ... | plt.axvline(x=centroids[0], color="red")
plt.axvline(x=centroids[1], color="red")
plt.axvline(x=centroids[2], color="red")
plt.show()
min = 0
mid = 0
max = 0
for x in range(0, 3):
if centroids[x] < centroids[min]:
min = x
... |
centroids, _ = kmeans(samples, 3) | random_line_split |
test2.py | :
def __init__(self, master):
self.video = None
self.frame_rate = 0
self.video_length = 0
# The scaled image used for display. Needs to persist for display
self.display_image = None
self.display_ratio = 0
self.awaiting_corners = False
self.corners ... |
#plt.hist(differences, bins=400)
plt.title("Frame Difference Historgram")
plt.xlabel("Difference (mean squared error)")
plt.ylabel("Number of Frames")
#plt.show()
time = np.arange(0, self.video_length/self.frame_rate, 1.0/self.frame_rate)
time = time[:len(diffe... | final_video += [current_frame] | conditional_block |
test2.py | :
def __init__(self, master):
self.video = None
self.frame_rate = 0
self.video_length = 0
# The scaled image used for display. Needs to persist for display
self.display_image = None
self.display_ratio = 0
self.awaiting_corners = False
self.corners ... | MainWindow | identifier_name | |
test_install.py |
def _get_logger(filename='test_install.log'):
"""
Convenience function to set-up output and logging.
"""
logger = logging.getLogger('test_install.py')
logger.setLevel(logging.DEBUG)
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.INFO)
file_handler = logging... | random_line_split | ||
test_install.py |
def report(out, name, line, item, value, eps=None, return_item=False,
match_numbers=False):
"""
Check that `item` at `line` of the output string `out` is equal
to `value`. If not, print the output.
"""
try:
if match_numbers:
status = out.split('\n')[line]
el... | """
Run the specified command and capture its outputs.
Returns
-------
out : tuple
The (stdout, stderr) output tuple.
"""
logger.info(cmd)
args = shlex.split(cmd)
p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out = [ii.decode() for ii in p.commu... | identifier_body | |
test_install.py | = out.split('\n')[line].split()
except IndexError:
logger.error(' not enough output from command!')
ok = False
else:
try:
if match_numbers:
pat = '([-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?[jJ]?)'
matches = re.findall(pat, status)
... | ():
parser = ArgumentParser(description=__doc__,
formatter_class=RawDescriptionHelpFormatter)
parser.add_argument('--version', action='version', version='%(prog)s')
parser.parse_args()
fd = open('test_install.log', 'w')
fd.close()
eok = 0
t0 = time.time()
... | main | identifier_name |
test_install.py | = out.split('\n')[line].split()
except IndexError:
logger.error(' not enough output from command!')
ok = False
else:
try:
if match_numbers:
pat = '([-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?[jJ]?)'
matches = re.findall(pat, status)
... |
else:
try:
ok = abs(float(status_item) - float(value)) < eps
except:
ok = False
except IndexError:
ok = False
logger.info(' %s: %s', name, ok)
if not ok:
logger.debug(DEBUG_FMT, out)
if re... | ok = (status_item == value) | conditional_block |
Triangle.js | this;
}
/**
* 设置三角形的顶点坐标为数组中的坐标
* @param {*} points 顶点数组
* @param {*} i0 第一个点的索引
* @param {*} i1 第二个点的索引
* @param {*} i2 第三个点的索引
* @returns
*/
setFromPointsAndIndices( points, i0, i1, i2 ) {
this.a.copy( points[ i0 ] );
this.b.copy( points[ i1 ] );
this.c.copy( points... | identifier_body | ||
Triangle.js | , b );
_v0.subVectors( a, b );
target.cross( _v0 );
const targetLengthSq = target.lengthSq();
if ( targetLengthSq > 0 ) {
// 归一化处理
return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
}
return target.set( 0, 0, 0 );
}
/**
* 用来计算重心坐标的静态/实例方法
* @param {*} point 指... | * @returns
*/
getPlane( target ) {
if ( target === undefined ) {
console.warn( 'THREE.Triangle: .getPlane() target is now required' );
target = new Plane();
}
// 通过空间中三个不共线的三个点确定一个平面
return target.setFromCoplanarPoints( this.a, this.b, this.c );
}
/**
* 计算指定点的重心坐标
* ... | * 获取平面三角形坐在的平面
* @param {*} target | random_line_split |
Triangle.js | b );
_v0.subVectors( a, b );
target.cross( _v0 );
const targetLengthSq = target.lengthSq();
if ( targetLengthSq > 0 ) {
// 归一化处理
return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
}
return target.set( 0, 0, 0 );
}
/**
* 用来计算重心坐标的静态/实例方法
* @param {*} point 指定... | addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
}
/**
* 获取三角面的normal
* @param {*} target
* @returns
*/
getNormal( target ) {
return Triangle.getNormal( this.a, this.b, this.c, target );
}
/**
* 获取平面三角形坐在的平面
* @param {*} target
* @returns
... | et. | identifier_name |
Triangle.js | this;
}
/**
* 设置三角形的顶点坐标为数组中的坐标
* @param {*} points 顶点数组
* @param {*} i0 第一个点的索引
* @param {*} i1 第二个点的索引
* @param {*} i2 第三个点的索引
* @returns
*/
setFromPointsAndIndices( points, i0, i1, i2 ) {
this.a.copy( points[ i0 ] );
this.b.copy( points[ i1 ] );
this.c.copy( points... | conditional_block | ||
daemon.py | 8")
handle_mode(command)
# Define command to handle callback for when MQTT command "temp" arrives.
# Tell us and confirm on MQTT, then call sendtoheatpump to set the new room value.
def on_message_temp(client, userdata, msg):
print("Received temp ")
print(msg.topic + ": " + str(msg.payload))
command = ... | (h1command):
h1response="init"
# Resend command every 0.5s until answer is received
while h1response[:2] != h1command:
print "Writing command: " + h1command
ser.flushOutput()
ser.flushInput()
ser.write(h1command + "\r\n")
h1response=ser.readline()
h1response=r... | sendtoh1 | identifier_name |
daemon.py | 8")
handle_mode(command)
# Define command to handle callback for when MQTT command "temp" arrives.
# Tell us and confirm on MQTT, then call sendtoheatpump to set the new room value.
def on_message_temp(client, userdata, msg):
print("Received temp ")
print(msg.topic + ": " + str(msg.payload))
command = ... |
elif 'Heatpump' == command:
print("Set mode heatpump")
mqttc.publish(mqtttopic + "/status/mode", "Heatpump")
sendtoheatpump('2201', '2')
elif 'Electricity' == command:
print("Set mode electricity")
mqttc.publish(mqtttopic + "/status/mode", "Electricity")
sendtohe... | print("Set mode auto")
mqttc.publish(mqtttopic + "/status/mode", "Auto")
sendtoheatpump('2201', '1') | conditional_block |
daemon.py | 8")
handle_mode(command)
# Define command to handle callback for when MQTT command "temp" arrives.
# Tell us and confirm on MQTT, then call sendtoheatpump to set the new room value.
def on_message_temp(client, userdata, msg):
print("Received temp ")
print(msg.topic + ": " + str(msg.payload))
command = ... |
# Define command for handling heatpump mode commands.
# Respond on MQTT and then call sendtoheatpump.
def handle_mode(command):
if 'Auto' == command:
print("Set mode auto")
mqttc.publish(mqtttopic + "/status/mode", "Auto")
sendtoheatpump('2201', '1')
elif 'Heatpump' == command:
... | print("Received unknown command ")
print(msg.topic + ": " + str(msg.payload)) | identifier_body |
daemon.py | ', int(float(command)))
# Define command to handle callback for when MQTT command "curve" arrives.
def on_message_curve(client, userdata, msg):
print("Received curve ")
print(msg.topic + ": " + str(msg.payload))
command = msg.payload.decode("utf-8").lower()
mqttc.publish(mqtttopic + "/status/curve", in... | # Make H1 send readable labels and regular full updates
sendtoh1("XP")
sendtoh1("XM")
else: | random_line_split | |
worker_actions.rs | No such hobo id")?;
}
validate_ability(db, task.task_type, worker_id, timestamp)?;
let new_task = NewTask {
worker_id: worker_id.num(),
task_type: task.task_type,
x: task.x as i32,
y: task.y as i32,
start_time: Some(timestamp),
... | y | identifier_name | |
worker_actions.rs | // check timing and effect of current task interruption
let mut current_task = db
.current_task(worker.key())
.expect("Must have a current task");
let mut timestamp =
interrupt_task(&mut current_task, &worker).ok_or("Cannot interrupt current task.")?;
worker.x = current_task.x;
... | {
town.state
.register_task_begin(*task.task_type())
.map_err(|e| e.to_string())?;
worker_into_building(town, worker, (task.x() as usize, task.y() as usize))
} | conditional_block | |
worker_actions.rs | };
simulate_begin_task(&new_task, &mut town, &mut worker)?;
let duration = simulate_finish_task(&new_task, &mut town, &mut worker)?;
tasks.push(new_task);
timestamp += duration;
}
Ok(ValidatedTaskList {
new_tasks: tasks,
update_tasks: vec![current_task],
... | {
self.x
} | identifier_body | |
worker_actions.rs | _type(&self) -> &TaskType;
fn target(&self) -> Option<HoboKey>;
}
pub struct ValidatedTaskList {
pub new_tasks: Vec<NewTask>,
pub update_tasks: Vec<Task>,
pub village_id: VillageKey,
}
pub(crate) fn validate_task_list(
db: &DB,
tl: &TaskList,
) -> Result<ValidatedTaskList, Box<dyn std::error::Er... | // Validate target hobo exists if there is one
if let Some(target_id) = task.target {
db.hobo(HoboKey(target_id)).ok_or("No such hobo id")?;
}
validate_ability(db, task.task_type, worker_id, timestamp)?;
let new_task = NewTask {
worker_id: worker_id.num(... | let mut tasks = vec![];
for task in tl.tasks.iter() { | random_line_split |
lockfree.rs | them, need more tests to
// see what the impact of that is
buckets: AtomicBucketList,
/// The default capacity of each bucket
///
/// Invariant: `bucket_capacity` must never be zero
bucket_capacity: AtomicUsize,
memory_usage: AtomicUsize,
max_memory_usage: AtomicUsize,
}
impl Loc... | (&self, requested_mem: usize) -> LassoResult<()> {
if self.memory_usage.load(Ordering::Relaxed) + requested_mem
> self.max_memory_usage.load(Ordering::Relaxed)
{
Err(LassoError::new(LassoErrorKind::MemoryLimitReached))
} else {
self.memory_usage
... | allocate_memory | identifier_name |
lockfree.rs | them, need more tests to
// see what the impact of that is
buckets: AtomicBucketList,
/// The default capacity of each bucket
///
/// Invariant: `bucket_capacity` must never be zero
bucket_capacity: AtomicUsize,
memory_usage: AtomicUsize,
max_memory_usage: AtomicUsize,
}
impl Loc... | // TODO: Push the bucket to the back or something so that we can get it somewhat out
// of the search path, reduce the `n` in the `O(n)` list traversal
self.buckets.push_front(bucket.into_ref());
Ok(allocated_string)
// Otherwise just a... | {
let memory_usage = self.current_memory_usage();
let max_memory_usage = self.get_max_memory_usage();
// If trying to use the doubled capacity will surpass our memory limit, just allocate as much as we can
if memory_usage + next_capacity > max_memory_usage {
... | conditional_block |
lockfree.rs | over them, need more tests to
// see what the impact of that is
buckets: AtomicBucketList,
/// The default capacity of each bucket
///
/// Invariant: `bucket_capacity` must never be zero | memory_usage: AtomicUsize,
max_memory_usage: AtomicUsize,
}
impl LockfreeArena {
/// Create a new Arena with the default bucket size of 4096 bytes
pub fn new(capacity: NonZeroUsize, max_memory_usage: usize) -> LassoResult<Self> {
Ok(Self {
// Allocate one bucket
buckets:... | bucket_capacity: AtomicUsize, | random_line_split |
lockfree.rs | , 0);
self.bucket_capacity.store(capacity, Ordering::Relaxed);
}
/// Doesn't actually allocate anything, but increments `self.memory_usage` and returns `None` if
/// the attempted amount surpasses `max_memory_usage`
// TODO: Make this return a `Result`
fn allocate_memory(&self, requested_me... | {
let arena = LockfreeArena::new(NonZeroUsize::new(1).unwrap(), 1000).unwrap();
unsafe {
assert!(arena.store_str("abcdefghijklmnopqrstuvwxyz").is_ok());
}
} | identifier_body | |
config.rs | ,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case", default, deny_unknown_fields)]
pub struct Carbon {
// TODO: will be used when multiple backends support is implemented
///// Enable sending to carbon protocol backend
//pub enabled: bool,
/// IP and p... | {
let c_action = value_t!(args.value_of("action"), ConsensusAction).expect("bad consensus action");
let l_action = value_t!(args.value_of("leader_action"), LeaderAction).expect("bad leader action");
(system, Command::Query(MgmtCommand::ConsensusCommand(c_action, l_action)... | conditional_block | |
config.rs | all CPU cores
pub w_threads: usize,
/// queue size for single counting thread before packet is dropped
pub task_queue_size: usize,
/// Should we start as leader state enabled or not
pub start_as_leader: bool,
/// How often to gather own stats, in ms. Use 0 to disable (stats are still gathere... | async_sockets: 4,
nodes: Vec::new(),
snapshot_interval: 1000,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case", default, deny_unknown_fields)]
pub struct Consul {
/// Start in disabled leader finding mode
pub start_as: Conse... | buffer_flush_time: 0,
greens: 4, | random_line_split |
config.rs | /// How often to gather own stats, in ms. Use 0 to disable (stats are still gathered, but not included in
/// metric dump)
pub stats_interval: u64,
/// Prefix to send own metrics with
pub stats_prefix: String,
/// Consensus kind to use
pub consensus: ConsensusKind,
}
impl Default for Syst... | Command | identifier_name | |
building.rs | ,
pub address: String,
pub name: Option<NamePerLanguage>,
pub orig_id: osm::OsmID,
/// Where a text label should be centered to have the best chances of being contained within
/// the polygon.
pub label_center: Pt2D,
pub amenities: Vec<Amenity>,
pub bldg_type: BuildingType,
pub parki... |
/// Returns (biking position, sidewalk position). Could fail if the biking graph is
/// disconnected.
pub fn biking_connection(&self, map: &Map) -> Option<(Position, Position)> {
// Easy case: the building is directly next to a usable lane
if let Some(pair) = sidewalk_to_bike(self.sidewalk... | {
let lane = map
.get_parent(self.sidewalk())
.find_closest_lane(self.sidewalk(), |l| PathConstraints::Car.can_use(l, map))?;
// TODO Do we need to insist on this buffer, now that we can make cars gradually appear?
let pos = self
.sidewalk_pos
.equ... | identifier_body |
building.rs | ,
pub address: String,
pub name: Option<NamePerLanguage>,
pub orig_id: osm::OsmID,
/// Where a text label should be centered to have the best chances of being contained within
/// the polygon.
pub label_center: Pt2D,
pub amenities: Vec<Amenity>,
pub bldg_type: BuildingType,
pub parki... | {
Bank,
Bar,
Beauty,
Bike,
Cafe,
CarRepair,
CarShare,
Childcare,
ConvenienceStore,
Culture,
Exercise,
FastFood,
Food,
GreenSpace,
Hotel,
Laundry,
Library,
Medical,
Pet,
Playground,
Pool,
PostOffice,
Religious,
School,
S... | AmenityType | identifier_name |
building.rs | 4,
pub address: String,
pub name: Option<NamePerLanguage>,
pub orig_id: osm::OsmID,
/// Where a text label should be centered to have the best chances of being contained within
/// the polygon.
pub label_center: Pt2D,
pub amenities: Vec<Amenity>,
pub bldg_type: BuildingType,
pub park... | return name;
}
&self.0[&None]
}
pub fn new(tags: &Tags) -> Option<NamePerLanguage> {
let native_name = tags.get(osm::NAME)?;
let mut map = BTreeMap::new();
map.insert(None, native_name.to_string());
for (k, v) in tags.inner() {
if let Some... | random_line_split | |
building.rs | ,
pub address: String,
pub name: Option<NamePerLanguage>,
pub orig_id: osm::OsmID,
/// Where a text label should be centered to have the best chances of being contained within
/// the polygon.
pub label_center: Pt2D,
pub amenities: Vec<Amenity>,
pub bldg_type: BuildingType,
pub parki... |
}
false
}
}
fn sidewalk_to_bike(sidewalk_pos: Position, map: &Map) -> Option<(Position, Position)> {
let lane = map
.get_parent(sidewalk_pos.lane())
.find_closest_lane(sidewalk_pos.lane(), |l| {
!l.biking_blackhole && PathConstraints::Bike.can_use(l, map)
})... | {
return true;
} | conditional_block |
main.go | (key string, addIfMissing, deleteIfPresent bool) *ObjectData {
c.Lock()
defer c.Unlock()
od := c.objects[key]
if od == nil {
od = &ObjectData{}
if addIfMissing {
c.objects[key] = od
}
} else if deleteIfPresent {
delete(c.objects, key)
}
return od
}
func NewController(queue workqueue.RateLimitingInter... | getObjectData | identifier_name | |
main.go | , informer cache.Controller, lister corev1listers.ConfigMapLister, compare bool, csvFilename, myAddr string) *Controller {
createHistogram := prometheus.NewHistogramVec(
prometheus.HistogramOpts{
Namespace: HistogramNamespace,
Subsystem: HistogramSubsystem,
Name: CreateHistogramName,
Help: "Con... |
func (c *Controller) logDequeue(key string) error {
now := time.Now()
namespace, name, err := cache.SplitMetaNamespaceKey(key)
if err != nil {
runtime.HandleError(fmt.Errorf("Failed to split key %q: %v", key, err))
return nil
}
obj, err := c.lister.ConfigMaps(namespace).Get(name)
if err != nil && !apierrors... | {
// Wait until there is a new item in the working queue
key, quit := c.queue.Get()
if quit {
return false
}
// Tell the queue that we are done with processing this key. This unblocks the key for other workers
// This allows safe parallel processing because two objects with the same key are never processed in
... | identifier_body |
main.go | be processed later again.
c.queue.AddRateLimited(key)
return
}
func (c *Controller) Run(threadiness int, stopCh chan struct{}) {
defer runtime.HandleCrash()
// Let the workers stop when we are done
defer c.queue.ShutDown()
klog.Info("Starting Object Logging controller")
csvFile, err := os.Create(c.csvFilenam... | {
if y[k] != v {
return false
}
} | conditional_block | |
main.go | ,%s,%s,%d\n",
formatTime(now), op, key, formatTimeNoMillis(creationTime),
oqd.queuedAdds, oqd.queuedUpdates, oqd.queuedDeletes,
formatTime(oqd.firstEnqueue), formatTime(oqd.lastEnqueue),
diff,
)))
if err != nil {
runtime.HandleError(fmt.Errorf("Error writing to CSV file named %q: %+v", c.csvFilename,... | } else {
klog.Errorf("Failed to parse key from obj %#v: %v\n", newobj, err)
}
},
DeleteFunc: func(obj interface{}) { | random_line_split | |
types.rs | apply_sub_type(&subs, &ty);
}
Ok((im::HashMap::new(), ty))
}
type TypeRes<'a> = (im::HashMap<String, Type>, Type);
pub type Scheme = (im::HashSet<String>, Type);
type Subs<'a> = &'a im::HashMap<String, Type>;
fn apply_sub_type(subs: Subs, ty: &Type) -> Type {
match ty {
Type::TyVar(name) => su... | (subs: Subs, subs2: Subs) -> im::HashMap<String, Type> {
let mut h = im::HashMap::new();
for (key, value) in subs.into_iter() {
h = h.update(key.to_string(), apply_sub_type(subs, &value.clone()));
}
h.union(subs2.clone())
}
fn ftv_ty(ty: &Type) -> im::HashSet<String> {
match ty {
Ty... | compose | identifier_name |
types.rs | apply_sub_type(&subs, &ty);
}
Ok((im::HashMap::new(), ty))
}
type TypeRes<'a> = (im::HashMap<String, Type>, Type);
pub type Scheme = (im::HashSet<String>, Type);
type Subs<'a> = &'a im::HashMap<String, Type>;
fn apply_sub_type(subs: Subs, ty: &Type) -> Type {
match ty {
Type::TyVar(name) => su... |
fn unify(ty1: &Type, ty2: &Type) -> Result<im::HashMap<String, Type>, String> {
match (ty1, ty2) {
(Type::TyArr(l, r), Type::TyArr(l1, r1)) => {
let s1 = unify(l, l1)?;
let s2 = unify(&apply_sub_type(&s1, &r), &apply_sub_type(&s1, &r1))?;
Ok(compose(&s2, &s1))
... | {
let xs = ftv_ty(ty);
let ys = ftv_env(env);
let a = xs.difference(ys);
(a, ty.clone())
} | identifier_body |
types.rs | = apply_sub_type(&subs, &ty);
}
Ok((im::HashMap::new(), ty))
}
type TypeRes<'a> = (im::HashMap<String, Type>, Type);
pub type Scheme = (im::HashSet<String>, Type);
type Subs<'a> = &'a im::HashMap<String, Type>;
fn apply_sub_type(subs: Subs, ty: &Type) -> Type {
match ty {
Type::TyVar(name) => ... | .iter()
.map(|(k, items)| convert_inner(env, k, items))
.flatten()
.collect();
if d.len() == items.len() {
Ok((im::HashMap::new(), Type::Dataset(d)))
} else {
Err("Not ... | let d: im::HashMap<String, Type> = items | random_line_split |
util.rs | simple contains for small str array
// benchmark shows linear scan takes at most 10ns
// while phf or bsearch takes 30ns
const ALLOWED_GLOBALS: &[&str] = make_list![
Infinity,
undefined,
NaN,
isFinite,
isNaN,
parseFloat,
parseInt,
decodeURI,
decodeURIComponent,
encodeURI,
en... | }
type DirFound<'a, E> = PropFound<'a, E, Directive<'a>>;
// sometimes mutable access to the element is not available so
// Borrow is used to refine PropFound so `take` is optional
pub fn dir_finder<'a, E, P>(elem: E, pat: P) -> PropFinder<'a, E, P, Directive<'a>>
where
E: Borrow<Element<'a>>,
P: PropPattern,... | {
pub fn take(mut self) -> M {
// TODO: avoid O(n) behavior
M::take(self.elem.borrow_mut().properties.remove(self.pos))
} | random_line_split |
util.rs | (tag: &str) -> bool {
tag == "component" || tag == "Component"
}
pub const fn yes(_: &str) -> bool {
true
}
pub const fn no(_: &str) -> bool {
false
}
pub fn get_vnode_call_helper(v: &VNodeIR<BaseConvertInfo>) -> RuntimeHelper {
use RuntimeHelper as RH;
if v.is_block {
return if v.is_compo... | {
PropFinder::new(elem, pat)
} | identifier_body | |
util.rs | simple contains for small str array
// benchmark shows linear scan takes at most 10ns
// while phf or bsearch takes 30ns
const ALLOWED_GLOBALS: &[&str] = make_list![
Infinity,
undefined,
NaN,
isFinite,
isNaN,
parseFloat,
parseInt,
decodeURI,
decodeURIComponent,
encodeURI,
en... |
}
impl<'a> PropMatcher<'a> for ElemProp<'a> {
fn get_name_and_exp(prop: &ElemProp<'a>) -> NameExp<'a> {
match prop {
ElemProp::Attr(Attribute { name, value, .. }) => {
let exp = value.as_ref().map(|v| v.content);
Some((name, exp))
}
ElemP... | {
None
} | conditional_block |
util.rs | simple contains for small str array
// benchmark shows linear scan takes at most 10ns
// while phf or bsearch takes 30ns
const ALLOWED_GLOBALS: &[&str] = make_list![
Infinity,
undefined,
NaN,
isFinite,
isNaN,
parseFloat,
parseInt,
decodeURI,
decodeURIComponent,
encodeURI,
en... | <'a, E, M>
where
E: Borrow<Element<'a>>,
M: PropMatcher<'a>,
{
elem: E,
pos: usize,
m: PhantomData<&'a M>,
}
impl<'a, E, M> PropFound<'a, E, M>
where
E: Borrow<Element<'a>>,
M: PropMatcher<'a>,
{
fn new(elem: E, pos: usize) -> Option<Self> {
Some(Self {
elem,
... | PropFound | identifier_name |
lib.rs | windres.exe and ar.exe.
/// This could be something like: "C:\Program Files\mingw-w64\x86_64-5.3.0-win32-seh-rt_v4-rev0\mingw64\bin"
///
/// For MSVC the Windows SDK has to be installed. It comes with the resource compiler rc.exe.
/// This should be set to the root directory of the Windows SDK, e.g., "C:\Progr... |
/// Sets the icon to use on the window. Currently only used on Windows.
#[must_use]
pub fn windows_attributes(mut self, windows_attributes: WindowsAttributes) -> Self {
self.windows_attributes = windows_attributes;
self
}
}
/// Run all build time helpers for your Tauri Application.
///
/// The curren... | {
Self::default()
} | identifier_body |
lib.rs | put windres.exe and ar.exe.
/// This could be something like: "C:\Program Files\mingw-w64\x86_64-5.3.0-win32-seh-rt_v4-rev0\mingw64\bin"
///
/// For MSVC the Windows SDK has to be installed. It comes with the resource compiler rc.exe.
/// This should be set to the root directory of the Windows SDK, e.g., "C:\P... | (mut self, windows_attributes: WindowsAttributes) -> Self {
self.windows_attributes = windows_attributes;
self
}
}
/// Run all build time helpers for your Tauri Application.
///
/// The current helpers include the following:
/// * Generates a Windows Resource file when targeting Windows.
///
/// # Platforms
... | windows_attributes | identifier_name |
lib.rs | -json5")]
println!("cargo:rerun-if-changed=tauri.conf.json5");
#[cfg(feature = "config-toml")]
println!("cargo:rerun-if-changed=Tauri.toml");
let target_os = std::env::var("CARGO_CFG_TARGET_OS").unwrap();
let mobile = target_os == "ios" || target_os == "android";
cfg_alias("desktop", !mobile);
cfg_alias(... | {
config
.tauri
.features()
.into_iter()
.map(|f| f.to_string())
.collect::<Vec<String>>()
} | conditional_block | |
lib.rs | _manifest: Option<String>,
}
impl WindowsAttributes {
/// Creates the default attribute set.
pub fn new() -> Self {
Self::default()
}
/// Sets the icon to use on the window. Currently only used on Windows.
/// It must be in `ico` format. Defaults to `icons/icon.ico`.
#[must_use]
pub fn window_icon_p... | .tauri
.bundle | random_line_split | |
main.rs | 210317")
.about("Enables services that service consumers want to use on Google Cloud Platform, lists the available or enabled services, or disables services that service consumers no longer use.")
.after_help("All documentation details can be found at <TODO figure out URL>")
.arg(Arg... | {
// TODO: set homedir afterwards, once the address is unmovable, or use Pin for the very first time
// to allow a self-referential structure :D!
let _home_dir = dirs::config_dir()
.expect("configuration directory can be obtained")
.join("google-service-cli");
let outer = Outer::default_... | identifier_body | |
main.rs | , 'b>,
}
struct HeapApp<'a, 'b> {
app: App<'a, 'b>,
}
impl<'a, 'b> Default for HeapApp<'a, 'b> {
fn default() -> Self {
let mut app = App::new("serviceusage1_beta1")
.setting(clap::AppSettings::ColoredHelp)
.author("Sebastian Thiel <byronimo@gmail.com>")
.version("0... | {
let mcmd = SubCommand::with_name("create").about("Creates a consumer override. A consumer override is applied to the consumer on its own authority to limit its own quota usage. Consumer overrides cannot be used to grant more quota than would be allowed by admin overrides, producer overrides, or th... | let mut consumer_overrides3 = SubCommand::with_name("consumer_overrides")
.setting(AppSettings::ColoredHelp)
.about("methods: create, delete, list and patch"); | random_line_split |
main.rs | 'b>,
}
struct | <'a, 'b> {
app: App<'a, 'b>,
}
impl<'a, 'b> Default for HeapApp<'a, 'b> {
fn default() -> Self {
let mut app = App::new("serviceusage1_beta1")
.setting(clap::AppSettings::ColoredHelp)
.author("Sebastian Thiel <byronimo@gmail.com>")
.version("0.1.0-20210317")
... | HeapApp | identifier_name |
v3.go | (core.Volume{
Name: secret.Source,
VolumeSource: vSrc,
})
serviceContainer.VolumeMounts = append(serviceContainer.VolumeMounts, core.VolumeMount{
Name: secret.Source,
MountPath: target,
})
}
for _, c := range composeServiceConfig.Configs {
target := c.Target
if target =... | {
probe := core.Probe{}
if len(composeHealthCheck.Test) > 1 {
probe.Handler = core.Handler{
Exec: &core.ExecAction{
// docker/cli adds "CMD-SHELL" to the struct, hence we remove the first element of composeHealthCheck.Test
Command: composeHealthCheck.Test[1:],
},
}
} else {
logrus.Warnf("Could n... | identifier_body | |
v3.go |
}
return config, nil
}
// ConvertToIR loads an v3 compose file into IR
func (c *V3Loader) ConvertToIR(composefilepath string, serviceName string) (irtypes.IR, error) {
logrus.Debugf("About to load configuration from docker compose file at path %s", composefilepath)
config, err := ParseV3(composefilepath)
if err ... | },
}
if secret.Mode != nil {
mode := cast.ToInt32(*secret.Mode)
vSrc.Secret.DefaultMode = &mode
}
serviceConfig.AddVolume(core.Volume{
Name: secret.Source,
VolumeSource: vSrc,
})
serviceContainer.VolumeMounts = append(serviceContainer.VolumeMounts, core.VolumeMount{
... | SecretName: secret.Source,
Items: []core.KeyToPath{{
Key: secret.Source,
Path: src,
}}, | random_line_split |
v3.go | if restart == "unless-stopped" {
logrus.Warnf("Restart policy 'unless-stopped' in service %s is not supported, convert it to 'always'", name)
serviceConfig.RestartPolicy = core.RestartPolicyAlways
}
// replicas:
if composeServiceConfig.Deploy.Replicas != nil {
serviceConfig.Replicas = int(*composeServic... | {
splits := strings.Split(port, "/")
portValue = splits[0]
} | conditional_block | |
v3.go |
}
return config, nil
}
// ConvertToIR loads an v3 compose file into IR
func (c *V3Loader) ConvertToIR(composefilepath string, serviceName string) (irtypes.IR, error) {
logrus.Debugf("About to load configuration from docker compose file at path %s", composefilepath)
config, err := ParseV3(composefilepath)
if err ... | (filedir string, composeObject types.Config, serviceName string) (irtypes.IR, error) {
ir := irtypes.IR{
Services: map[string]irtypes.Service{},
}
//Secret volumes transformed to IR
ir.Storages = c.getSecretStorages(composeObject.Secrets)
//ConfigMap volumes transformed to IR
ir.Storages = append(ir.Storages,... | convertToIR | identifier_name |
fmt.rs | return Err(err);
}
let result = func(writer);
writer.reset()?;
result
}
/// Adapter struct implementing [Write] over types implementing [WriteColor]
pub struct Termcolor<W>(pub W);
impl<W> Write for Termcolor<W>
where
W: WriteColor,
{
fn write_str(&mut self, elements: &MarkupElements,... | const INPUT: &str = "t\tes t\r\n\u{202D}t\0es\x07t\u{202E}\nt\u{200B}es🐛t";
const OUTPUT: &str = "t\tes t\r\n\u{FFFD}t\u{FFFD}es\u{FFFD}t\u{FFFD}\nt\u{FFFD}es🐛t";
let mut buffer = Vec::new();
| random_line_split | |
fmt.rs | impl FnMut(&'a [MarkupElement])) {
if let Self::Node(parent, elem) = self {
parent.for_each(func);
func(elem);
}
}
}
pub trait Write {
fn write_str(&mut self, elements: &MarkupElements, content: &str) -> io::Result<()>;
fn write_fmt(&mut self, elements: &MarkupEleme... |
/// Write a piece of markup into this formatter
pub fn write_markup(&mut self, markup: Markup) -> io::Result<()> {
for node in markup.0 {
let mut fmt = self.with_elements(node.elements);
node.content.fmt(&mut fmt)?;
}
Ok(())
}
/// Write a slice of text... | {
Formatter {
state: MarkupElements::Node(&self.state, elements),
writer: self.writer,
}
} | identifier_body |
fmt.rs | mut impl FnMut(&'a [MarkupElement])) {
if let Self::Node(parent, elem) = self {
parent.for_each(func);
func(elem);
}
}
}
pub trait Write {
fn write_str(&mut self, elements: &MarkupElements, content: &str) -> io::Result<()>;
fn write_fmt(&mut self, elements: &MarkupEl... | else {
// SanitizeAdapter can only fail if the underlying
// writer returns an error
unreachable!()
}
}
}
})
}
fn write_fmt(&mut self, elements: &MarkupElements, content: fmt::Argume... | {
adapter.error
} | conditional_block |
fmt.rs | mut impl FnMut(&'a [MarkupElement])) {
if let Self::Node(parent, elem) = self {
parent.for_each(func);
func(elem);
}
}
}
pub trait Write {
fn write_str(&mut self, elements: &MarkupElements, content: &str) -> io::Result<()>;
fn write_fmt(&mut self, elements: &MarkupEl... | (&mut self, content: &str) -> fmt::Result {
let mut buffer = [0; 4];
for item in content.chars() {
// Replace non-whitespace, zero-width characters with the Unicode replacement character
let is_whitespace = item.is_whitespace();
let is_zero_width = UnicodeWidthChar::... | write_str | identifier_name |
serial.rs | {
fn eq(&self, other: &Self) -> bool
{
self.id == other.id
}
}
impl fmt::Debug for SerialQueue
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result
{
write!(f, "SerialQueue ({})", self.id)
}
}
unsafe impl Send for SerialQueue
{}
unsafe impl Sync for SerialQueue
{}
impl Seria... | {
self.queue.sync(move || operation(unsafe { self.binding.get_mut() }))
} | identifier_body | |
serial.rs | this task is running before...");
/// });
/// main.sync(|| {
/// println!("...this task and...");
/// assert_eq!(future_one.get() + future_two.get(), 138);
/// });
/// println!("...this is running last");
/// });
/// ```
pub struct SerialQueue
{
id: usize,
tx: MailboxOuterEnd<Com... | <R, F>(&self, operation: F) -> Future<R>
where R: Send + 'static,
F: FnOnce() -> R + Send + 'static
{
let (tx, rx) = mailbox();
let operation: Box<FnBox() + Send + 'static> = Stack::assemble(self, move || {
tx.send(operation());
});
debug!("Queue ({... | async | identifier_name |
serial.rs | this task is running before...");
/// });
/// main.sync(|| {
/// println!("...this task and...");
/// assert_eq!(future_one.get() + future_two.get(), 138);
/// });
/// println!("...this is running last");
/// });
/// ```
pub struct SerialQueue
{
id: usize,
tx: MailboxOuterEnd<Com... | {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result
{
write!(f, "SerialQueue ({})", self.id)
}
}
unsafe impl Send for SerialQueue
{}
unsafe impl Sync for SerialQueue
{}
impl SerialQueue
{
/// Create a new SerialQueue and assign it to the global thread pool
pub fn new() -> SerialQueue
... |
impl fmt::Debug for SerialQueue | random_line_split |
paths.py | ,
"PathSpec", # TODO(user): recursive definition.
]
@classmethod
def OS(cls, **kwargs):
|
@classmethod
def TSK(cls, **kwargs):
return cls(pathtype=PathSpec.PathType.TSK, **kwargs)
@classmethod
def NTFS(cls, **kwargs):
return cls(pathtype=PathSpec.PathType.NTFS, **kwargs)
@classmethod
def Registry(cls, **kwargs):
return cls(pathtype=PathSpec.PathType.REGISTRY, **kwargs)
@classm... | return cls(pathtype=PathSpec.PathType.OS, **kwargs) | identifier_body |
paths.py | ,
"PathSpec", # TODO(user): recursive definition.
]
@classmethod
def OS(cls, **kwargs):
return cls(pathtype=PathSpec.PathType.OS, **kwargs)
@classmethod
def TSK(cls, **kwargs):
return cls(pathtype=PathSpec.PathType.TSK, **kwargs)
@classmethod
def NTFS(cls, **kwargs):
return cls(patht... | (rdf_structs.RDFProtoStruct):
"""A sub-part of a GlobExpression with examples."""
protobuf = flows_pb2.GlobComponentExplanation
# Grouping pattern: e.g. {test.exe,foo.doc,bar.txt}
GROUPING_PATTERN = re.compile("{([^}]+,[^}]+)}")
_VAR_PATTERN = re.compile("(" + "|".join([r"%%\w+%%", r"%%\w+\.\w+%%"]) + ")")
_REG... | GlobComponentExplanation | identifier_name |
paths.py |
@classmethod
def OS(cls, **kwargs):
return cls(pathtype=PathSpec.PathType.OS, **kwargs)
@classmethod
def TSK(cls, **kwargs):
return cls(pathtype=PathSpec.PathType.TSK, **kwargs)
@classmethod
def NTFS(cls, **kwargs):
return cls(pathtype=PathSpec.PathType.NTFS, **kwargs)
@classmethod
def R... | rdf_deps = [
rdfvalue.ByteSize,
"PathSpec", # TODO(user): recursive definition.
] | random_line_split | |
paths.py | .__class__()
nested_proto.SetRawData(self.GetRawData())
# Replace ourselves with the new object.
self.SetRawData(rdfpathspec.GetRawData())
# Append the temp copy to the end.
self.last.nested_path = nested_proto
else:
previous = self[index - 1]
rdfpathspec.last.nested_path... | return GROUPING_PATTERN.sub(self._ReplaceRegExGrouping, part) | conditional_block | |
images.go | I: %v", err)
}
aciFile, err := os.Open(acis[0])
if err != nil {
return nil, nil, nil, fmt.Errorf("error opening squashed ACI file: %v", err)
}
return nil, aciFile, nil, nil
}
// attempt to automatically fetch the public key in case it is available on a TLS connection.
if globalFlags.TrustKeysFromHttp... |
if err := out.Sync(); err != nil { | random_line_split | |
images.go | ); err != nil {
if _, ok := err.(pgperrors.SignatureError); !ok {
return nil, nil, nil, err
}
}
}
var aciFile *os.File
if u.Scheme == "file" {
aciFile, err = os.Open(u.Path)
if err != nil {
return nil, nil, nil, fmt.Errorf("error opening ACI file: %v", err)
}
} else {
aciFile, err = f.s.TmpF... | getMaxAge | identifier_name | |
images.go | File *os.File, latest bool) (string, error) {
return f.fetchImageFrom(appName, ep.ACIEndpoints[0].ACI, ep.ACIEndpoints[0].ASC, "", ascFile, latest)
}
func (f *fetcher) fetchImageFromURL(imgurl string, scheme string, ascFile *os.File, latest bool) (string, error) {
return f.fetchImageFrom("", imgurl, ascURLFromImgURL... | {
aciFile, err = os.Open(u.Path)
if err != nil {
return nil, nil, nil, fmt.Errorf("error opening ACI file: %v", err)
}
} | conditional_block | |
images.go | rem.BlobKey = key
rem.DownloadTime = time.Now()
if cd != nil {
rem.ETag = cd.etag
rem.CacheMaxAge = cd.maxAge
}
err = f.s.WriteRemote(rem)
if err != nil {
return "", err
}
}
return key, nil
}
// fetch opens/downloads and verifies the remote ACI.
// If appName is not "", it will be used to check... | {
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
options := make(http.Header)
// Send credentials only over secure channel
if req.URL.Scheme == "https" {
if hostOpts, ok := f.headers[req.URL.Host]; ok {
options = hostOpts.Header()
}
}
for k, v := range options {
for _,... | identifier_body | |
query.go | &queryCommandeer{
rootCommandeer: rootCommandeer,
}
cmd := &cobra.Command{
Aliases: []string{"get"},
Use: "query [<metrics>] [flags]",
Short: "Query a TSDB instance",
Long: `Query a TSDB instance (table).`,
Example: `The examples assume that the endpoint of the web-gateway service, the login cr... | {
return errors.Wrap(err, "Failed to parse aggregation window")
} | conditional_block | |
query.go | series (*_all) aggregates, but not both in the same query.
Arguments:
<metrics> (string) Comma-separated list of metric names to query. If you don't set this argument, you must
provide a query filter using the -f|--filter flag.`,
RunE: func(cmd *cobra.Command, args []string) error {
// Sav... | return errors.Wrapf(err, "Failed to start formatter '%s'.", qc.output)
}
| random_line_split | |
query.go | *RootCommandeer
name string
filter string
to string
from string
last string
functions string
step string
output string
oldQuerier bool
groupBy st... | newQuery | identifier_name | |
query.go | "github.com/v3io/v3io-tsdb/pkg/pquerier"
"github.com/v3io/v3io-tsdb/pkg/utils"
)
type queryCommandeer struct {
cmd *cobra.Command
rootCommandeer *RootCommandeer
name string
filter string
to string
from string
la... | if err != nil {
return err
}
// Set start & end times
to := time.Now().Unix() * 1000
if qc.to != "" {
to, err = utils.Str2unixTime(qc.to)
if err != nil {
return err
}
}
from := to - 1000*3600 // Default start time = one hour before the end time
if qc.from != "" {
from, err = utils.Str2unixTime(qc... | {
if qc.name == "" && qc.filter == "" {
return errors.New("the query command must receive either a metric-name parameter (<metrics>) or a query filter (set via the -f|--filter flag)")
}
if qc.last != "" && (qc.from != "" || qc.to != "") {
return errors.New("the -l|--last flag cannot be set together with the -b... | identifier_body |
main0.rs | mut arr[..]);
// let data = vec![0x83, b'c', b'a', b't'];
// let aa: String = rlp::decode(&data).unwrap();
// println!("aa = {:?}", aa);
// let pk = hex::decode("ee5495585eff78f2fcf95bab21ef1a598c54d1e3c672e23b3bb97a4fc7490660").unwrap();
let private_key = SecretKey::parse_slice(&arr[0..arr.len()]... |
} else if message_type == 0x02 {
// got a pong message
let from_peer = PeerInfo::decode_rlp(&rlp.at(0)?)?;
let hash_bytes = rlp.at(1)?.data()?;
... | println!("pong bytes is {:?}", bytes.len());
send_queue.push_back(bytes);
// send_queue | random_line_split |
main0.rs | mut send_queue: VecDeque<Vec<u8>> = VecDeque::new();
let mut client = TcpStream::connect(addr)?;
let mut status_sent = false;
poll.registry().register(&mut client, CLIENT, Interest::READABLE | Interest::WRITABLE)?;
poll.registry().register(&mut udp_socket, SENDER, Interest::READABLE | Interest::WRITA... | {
println!("write ok");
} | conditional_block | |
main0.rs | },
}
}
fn main() -> Result<(), Box<dyn Error>> {
let mut arr = [0u8; 32];
thread_rng().fill(&mut arr[..]);
// let data = vec![0x83, b'c', b'a', b't'];
// let aa: String = rlp::decode(&data).unwrap();
// println!("aa = {:?}", aa);
// let pk = hex::decode("ee5495585eff78f2fcf95bab21... | {
match message_type {
0x01 => {
println!("ping message");
},
0x02 => {
println!("pong message");
},
0x03 => {
println!("find neighbours message");
},
0x04 => {
println!("neighbours message");
},
... | identifier_body | |
main0.rs | () -> Result<(), Box<dyn Error>> {
let mut arr = [0u8; 32];
thread_rng().fill(&mut arr[..]);
// let data = vec![0x83, b'c', b'a', b't'];
// let aa: String = rlp::decode(&data).unwrap();
// println!("aa = {:?}", aa);
// let pk = hex::decode("ee5495585eff78f2fcf95bab21ef1a598c54d1e3c672e23b3bb97... | main | identifier_name | |
csvload.go | String
}
s = strings.TrimSpace(s)
if len(s) == 0 {
return Unknown
}
var hasNonDigit bool
var dotCount int
var length int
_ = strings.Map(func(r rune) rune {
length++
if r == '.' {
dotCount++
} else if !hasNonDigit {
hasNonDigit = !('0' <= r && r <= '9')
}
return -1
},
s)
if !hasNonDigit... | err
}
if _, err | conditional_block | |
csvload.go | %s.", n, inserted, src, tbl, dur)
return err
}
func typeOf(s string) Type {
if ForceString {
return String
}
s = strings.TrimSpace(s)
if len(s) == 0 {
return Unknown
}
var hasNonDigit bool
var dotCount int
var length int
_ = strings.Map(func(r rune) rune {
length++
if r == '.' {
dotCount++
} e... | Write | identifier_name | |
csvload.go | ns(*flagConcurrency)
tbl := strings.ToUpper(flag.Arg(0))
src := flag.Arg(1)
if ForceString {
err = cfg.OpenVolatile(flag.Arg(1))
} else {
err = cfg.Open(flag.Arg(1))
}
if err != nil {
return err
}
defer cfg.Close()
rows := make(chan dbcsv.Row)
ctx, cancel := context.WithCancel(context.Background())
... | return tx.Commit()
})
}
var n int64
var headerSeen bool
chunk := (*(chunkPool.Get().(*[][]string)))[:0]
if err = cfg.ReadRows(ctx,
func(_ string, row dbcsv.Row) error {
if err = ctx.Err(); err != nil {
chunk = chunk[:0]
return err
}
if !headerSeen {
headerSeen = true
return nil
... | }
}
return err
} | random_line_split |
csvload.go | [:0]
chunkPool.Put(&z)
}
if err == nil {
atomic.AddInt64(&inserted, int64(len(chunk)))
continue
}
err = errors.Wrapf(err, "%s", qry)
log.Println(err)
rowsR := make([]reflect.Value, len(rowsI))
rowsI2 := make([]interface{}, len(rowsI))
for j, I := range rowsI {
rowsR[... | aType == "DATE" || c.Type == Date {
res := make([]time.Time, len(ss))
for i, s := range ss {
if s == "" {
continue
}
var err error
if res[i], err = time.Parse(dateFormat[:len(s)], s); err != nil {
return res, errors.Wrapf(err, "%d. %q", i, s)
}
}
return res, nil
}
if strings.HasPrefix(... | identifier_body | |
prediction.py | dir_4[(ww_dir > 45) & (ww_dir < 135)] = 1
dir_4[(ww_dir > 225) & (ww_dir < 315)] = 3
if ship_dir in ("W"):
dir_4 = np.full((len(ww_dir), 1), 2)
dir_4[(ww_dir > 45) & (ww_dir < 135)] = 3
dir_4[(ww_dir > 225) & (ww_dir < 315)] = 1
if ship_dir in ("S"):
dir_4 = np.fu... | """
determine relative wind direction for ships going north, east, south or west
Parameters
----------
ship_dir : str, in ("N", "E", "S", "W")
direction the ship is going
ww_dir : array, float
array of relative wind directions [0 - 360]
"""
if ship_dir not in ("N", "E", "S", "W"... | identifier_body | |
prediction.py | (url, user, passwd, ftp_path, filename):
with ftplib.FTP(url) as ftp:
try:
ftp.login(user, passwd)
# Change directory
ftp.cwd(ftp_path)
# Download file (if there is not yet a local copy)
if os.path.isfile(filename):
print("There ... | download | identifier_name | |
prediction.py |
try:
ftp.login(user, passwd)
# Change directory
ftp.cwd(ftp_path)
# Download file (if there is not yet a local copy)
if os.path.isfile(filename):
print("There is already a local copy for this date ({})".format(filename))
... |
def download(url, user, passwd, ftp_path, filename):
with ftplib.FTP(url) as ftp: | random_line_split | |
prediction.py | ww_dir : array, float
array of relative wind directions [0 - 360]
"""
if ship_dir not in ("N", "E", "S", "W"):
raise Exception("Direction not accepted.")
ww_360 = ww_dir
ww_360[ww_360 < 0] = 360 + ww_dir[0]
if ship_dir in ("N"):
dir_4 = np.full((len(ww_dir), 1), 2)
... |
if ship_dir in ("S"):
dir_4 = np.full((len(ww_dir), 1), 2)
dir_4[(ww_dir < 45) | (ww_dir > 315)] = 3
dir_4[(ww_dir > 135) & (ww_dir < 225)] = 1
return dir_4
def concatenate_cmems(cm_wave, cm_phy, ship_param, ship_dir):
"""
concatenate the variables from cmems wave and physics ... | dir_4 = np.full((len(ww_dir), 1), 2)
dir_4[(ww_dir > 45) & (ww_dir < 135)] = 3
dir_4[(ww_dir > 225) & (ww_dir < 315)] = 1 | conditional_block |
iconnect.js | (obj) {
var _key = typeof obj == "number" ? obj : obj[custEventAttribute];
if (_key && custEventCache[_key]) {
if (type) {
type = [].concat(type);
for (var i = 0; i < type.length; i++) {
if (type[i] in custEventCache[_key]) delete custEventCache[_key][type[i]];
}
} el... | identifier_name | ||
iconnect.js | }
};
var that = {
/**
* 对象自定义事件的定义 未定义的事件不得绑定
* @method define
* @static
* @param {Object|number} obj 对象引用或获取的下标(key); 必选
* @param {String|Array} type 自定义事件名称; 必选
* @return {number} key 下标
*/
define: function define(obj, type) {
if (obj && type) {
var _key = typeof ob... | }
return _cache.key;
} | random_line_split | |
iconnect.js | .getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z' : null;
};
String.prototype.toJSON = Number.prototype.toJSON = Boolean.prototype.toJSON = function (key) {
return this.valueOf();
};
}
var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-... | ow.parent.postMessage) {
window.parent.post | conditional_block | |
iconnect.js | for (var i = 0; i < _obj.length && _obj[i].fn !== fn; i++);
var i = 0;
while (_obj[i]) {
if (_obj[i].fn === fn) {
break;
}
i++;
}
_obj.splice(i, 1);
} else {
_obj.splice(0, _obj.length);
}
} else {
for (var i in _obj... | oolean':
case 'null':
// If the value is a boolean or null, convert it to a string. Note:
// typeof null does not produce 'null'. The case is included here in
// the remote chance that this gets fixed someday.
return String(value);
// If the type is 'object', we might be dealing with... | identifier_body | |
binary.go | returns -1.
func Size(v interface{}) int {
return dataSize(reflect.Indirect(reflect.ValueOf(v)))
}
// dataSize returns the number of bytes the actual data represented by v occupies in memory.
// For compound structures, it sums the sizes of the elements. Thus, for instance, for a slice
// it returns the length of th... | intDataSize | identifier_name | |
binary.go | Endian" }
// Read reads structured binary data from r into data.
// Data must be a pointer to a fixed-size value or a slice
// of fixed-size values.
// Bytes read from r are decoded using the specified byte order
// and written to successive fields of the data.
// When reading into structs, the field data for fields w... | {
switch t.Kind() {
case reflect.Array:
if s := sizeof(t.Elem()); s >= 0 {
return s * t.Len()
}
case reflect.Struct:
sum := 0
for i, n := 0, t.NumField(); i < n; i++ {
s := sizeof(t.Field(i).Type)
if s < 0 {
return -1
}
sum += s
}
return sum
case reflect.Uint8, reflect.Uint16, refle... | identifier_body | |
binary.go | := io.ReadFull(r, d.buf); err != nil {
return err
}
d.value(v)
return nil
}
// Write writes the binary representation of data into w.
// Data must be a fixed-size value or a slice of fixed-size
// values, or a pointer to such data.
// Bytes written to w are encoded using the specified byte order
// and read from... | {
d.value(v)
} | conditional_block | |
binary.go | func (littleEndian) Uint32(b []byte) uint32 {
return uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24
}
func (littleEndian) PutUint32(b []byte, v uint32) {
b[0] = byte(v)
b[1] = byte(v >> 8)
b[2] = byte(v >> 16)
b[3] = byte(v >> 24)
}
func (littleEndian) Uint64(b []byte) uint64 {
return uint... | }
| random_line_split | |
tx.rs | (op1, op2) {
(Some(op1), Some(op2)) => {
if op1 != op2 {
panic!("Conflicting prevout information in input.");
}
op1
}
(Some(op), None) => op,
(None, Some(op)) => op,
(None, None) => panic!("No previous output provided in input."),
}
}
fn bytes_32(bytes: &[u8]) -> Option<[u8; 32]> {
if bytes.l... | }
fn create_script_pubkey(spk: OutputScriptInfo, used_network: &mut Option<Network>) -> Script {
if spk.type_.is_some() {
warn!("Field \"type\" of output is ignored.");
}
if let Some(hex) = spk.hex {
if spk.asm.is_some() {
warn!("Field \"asm\" of output is ignored.");
}
if spk.address.is_some() {
wa... | {
let has_issuance = input.has_issuance.unwrap_or(input.asset_issuance.is_some());
let is_pegin = input.is_pegin.unwrap_or(input.pegin_data.is_some());
let prevout = outpoint_from_input_info(&input);
TxIn {
previous_output: prevout,
script_sig: input.script_sig.map(create_script_sig).unwrap_or_default(),
seq... | identifier_body |
tx.rs | (input: &InputInfo) -> OutPoint {
let op1: Option<OutPoint> =
input.prevout.as_ref().map(|ref op| op.parse().expect("invalid prevout format"));
let op2 = match input.txid {
Some(txid) => match input.vout {
Some(vout) => Some(OutPoint {
txid: txid,
vout: vout,
}),
None => panic!("\"txid\" field gi... | outpoint_from_input_info | identifier_name | |
tx.rs | serialize(&pd.mainchain_tx_hex.0),
serialize(&pd.merkle_proof.0),
]
}
fn convert_outpoint_to_btc(p: elements::OutPoint) -> bitcoin::OutPoint {
bitcoin::OutPoint {
txid: bitcoin::Txid::from_inner(p.txid.into_inner()),
vout: p.vout,
}
}
fn create_input_witness(
info: Option<InputWitnessInfo>,
pd: Option<Peg... | ::std::io::stdout().write_all(&tx_bytes).unwrap(); | random_line_split | |
RHD_Load_Filter.py | _data_blocks):
read_one_data_block(data, header, indices, fid)
# Increment indices
indices['amplifier'] += header['num_samples_per_data_block']
indices['aux_input'] += int(header['num_samples_per_data_block'] / 4)
indices['supply_voltage'] += 1
in... | t.figure()
plt.plot(time_vector,cmr_signals[i])
plt.title(rf'channel {int(selected_channels[i])}')
| conditional_block | |
RHD_Load_Filter.py | ['board_dig_out'] += header['num_samples_per_data_block']
fraction_done = 100 * (1.0 * i / num_data_blocks)
if fraction_done >= percent_done:
print('{}% done...'.format(percent_done))
percent_done = percent_done + print_increment
# Make sure ... | random_line_split | ||
RHD_Load_Filter.py | of data blocks')
num_data_blocks = int(bytes_remaining / bytes_per_block)
num_amplifier_samples = header['num_samples_per_data_block'] * num_data_blocks
num_aux_input_samples = int((header['num_samples_per_data_block'] / 4) * num_data_blocks)
num_supply_voltage_samples = 1 * num_data_blocks
num_b... | (n):
"""Utility function to optionally pluralize words based on the value of n.
"""
if n == 1:
return ''
else:
return 's'
path="//equipe2-nas1/Gilles.DELBECQ/Data/ePhy/Février2023/Test_Gustave/raw/raw intan/Test | plural | identifier_name |
RHD_Load_Filter.py | of data blocks')
num_data_blocks = int(bytes_remaining / bytes_per_block)
num_amplifier_samples = header['num_samples_per_data_block'] * num_data_blocks
num_aux_input_samples = int((header['num_samples_per_data_block'] / 4) * num_data_blocks)
num_supply_voltage_samples = 1 * num_data_blocks
num_b... |
path="//equipe2-nas1/Gilles.DELBECQ/Data/ePhy/Février2023/Test_Gustave/raw/raw intan/Test | """Utility function to optionally pluralize words based on the value of n.
"""
if n == 1:
return ''
else:
return 's' | identifier_body |
term_gui.rs | of the server, since the server
// might run on a different machine than the client - and certainly in a different
// directory.
let current_dir = env::current_dir().unwrap();
let rpc = try!(client.call("list_files", &swiboe::plugin::list_files::ListFilesRequest {
directory... |
fn draw(&mut self, buffer_view: &buffer_views::BufferView, rustbox: &rustbox::RustBox) {
let mut row = 0;
let top_line_index = buffer_view.top_line_index as usize;
self.cursor_id = buffer_view.cursor.id().to_string();
let mut cursor_drawn = false;
while row < rustbox.height... | cursor_id: String::new(),
}
} | random_line_split |
term_gui.rs | {
self.rpc.take().unwrap().cancel().unwrap();
if self.results.is_empty() {
CompleterState::Canceled
} else {
clamp(0, self.results.len() as isize - 1, &mut self.selection_index);
CompleterState::Selected(self.re... | {
self.config_file_runner.keymap_handler.key_down(
delta_t_in_seconds, keymap_handler::Key::Down);
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.