file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
test2.py | import os, sys
import Tkinter
import tkFileDialog
import PIL
from PIL import ImageTk, Image
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib.path as path
import cv2
from scipy.cluster.vq import kmeans
from skimage import data, img_as_float
#from skimage.measure i... | 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 | import os, sys
import Tkinter
import tkFileDialog
import PIL
from PIL import ImageTk, Image
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib.path as path
import cv2
from scipy.cluster.vq import kmeans
from skimage import data, img_as_float
#from skimage.measure i... |
#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 | import os, sys
import Tkinter
import tkFileDialog
import PIL
from PIL import ImageTk, Image
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib.path as path
import cv2
from scipy.cluster.vq import kmeans
from skimage import data, img_as_float
#from skimage.measure i... | :
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 | #!/usr/bin/env python
"""
Simple script for testing various SfePy functionality, examples not
covered by tests, and running the tests.
The script just runs the commands specified in its main() using the
`subprocess` module, captures the output and compares one or more key
words to the expected ones.
The output of fai... |
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 | #!/usr/bin/env python
"""
Simple script for testing various SfePy functionality, examples not
covered by tests, and running the tests.
The script just runs the commands specified in its main() using the
`subprocess` module, captures the output and compares one or more key
words to the expected ones.
The output of fai... |
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 | #!/usr/bin/env python
"""
Simple script for testing various SfePy functionality, examples not
covered by tests, and running the tests.
The script just runs the commands specified in its main() using the
`subprocess` module, captures the output and compares one or more key
words to the expected ones.
The output of fai... | ():
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 | #!/usr/bin/env python
"""
Simple script for testing various SfePy functionality, examples not
covered by tests, and running the tests.
The script just runs the commands specified in its main() using the
`subprocess` module, captures the output and compares one or more key
words to the expected ones.
The output of fai... |
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 | import { Vector3 } from './Vector3.js';
import { Plane } from './Plane.js';
const _v0 = /*@__PURE__*/ new Vector3();
const _v1 = /*@__PURE__*/ new Vector3();
const _v2 = /*@__PURE__*/ new Vector3();
const _v3 = /*@__PURE__*/ new Vector3();
const _vab = /*@__PURE__*/ new Vector3();
const _vac = /*@__PURE__*/ new Vecto... | identifier_body | ||
Triangle.js | import { Vector3 } from './Vector3.js';
import { Plane } from './Plane.js';
const _v0 = /*@__PURE__*/ new Vector3();
const _v1 = /*@__PURE__*/ new Vector3();
const _v2 = /*@__PURE__*/ new Vector3();
const _v3 = /*@__PURE__*/ new Vector3();
const _vab = /*@__PURE__*/ new Vector3();
const _vac = /*@__PURE__*/ new Vecto... | * @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 | import { Vector3 } from './Vector3.js';
import { Plane } from './Plane.js';
const _v0 = /*@__PURE__*/ new Vector3();
const _v1 = /*@__PURE__*/ new Vector3();
const _v2 = /*@__PURE__*/ new Vector3();
const _v3 = /*@__PURE__*/ new Vector3();
const _vab = /*@__PURE__*/ new Vector3();
const _vac = /*@__PURE__*/ new Vecto... | 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 | import { Vector3 } from './Vector3.js';
import { Plane } from './Plane.js';
const _v0 = /*@__PURE__*/ new Vector3();
const _v1 = /*@__PURE__*/ new Vector3();
const _v2 = /*@__PURE__*/ new Vector3();
const _v3 = /*@__PURE__*/ new Vector3();
const _vab = /*@__PURE__*/ new Vector3();
const _vac = /*@__PURE__*/ new Vecto... | conditional_block | ||
daemon.py | #!/usr/bin/env python
import time
import serial
import re
from subprocess import call
import os.path
import paho.mqtt.client as mqtt
import urllib2
# ---------------------------------
# Initialize variables and settings
# ---------------------------------
# First global variables. We might need them early.
wantvalue... | (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 | #!/usr/bin/env python
import time
import serial
import re
from subprocess import call
import os.path
import paho.mqtt.client as mqtt
import urllib2
# ---------------------------------
# Initialize variables and settings
# ---------------------------------
# First global variables. We might need them early.
wantvalue... |
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 | #!/usr/bin/env python
import time
import serial
import re
from subprocess import call
import os.path
import paho.mqtt.client as mqtt
import urllib2
# ---------------------------------
# Initialize variables and settings
# ---------------------------------
# First global variables. We might need them early.
wantvalue... |
# 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 | #!/usr/bin/env python
import time
import serial
import re
from subprocess import call
import os.path
import paho.mqtt.client as mqtt
import urllib2
# ---------------------------------
# Initialize variables and settings
# ---------------------------------
# First global variables. We might need them early.
wantvalue... | # If the data line is full expected length, work with it.
# Call parse and send MQTT/HTTP command. Returns what data was actually used.
parseresult = parseandsend(line)
# Check if the data we found is waiting to be confirmed in "wantvalue" dictionary.
... | # Make H1 send readable labels and regular full updates
sendtoh1("XP")
sendtoh1("XM")
else: | random_line_split |
worker_actions.rs | //! Tasks and task execution of workes
//!
//! Note: This module and submodules will sooner or later need some refactoring.
//! For now, I am still don't really know how I want it to look like.
mod worker_abilities;
mod worker_updates;
use crate::db::DB;
use crate::game_master::event::*;
use crate::game_master::town_... | (&self) -> i32 {
self.y
}
fn task_type(&self) -> &TaskType {
&self.task_type
}
fn target(&self) -> Option<HoboKey> {
self.target_hobo_id.map(HoboKey)
}
}
impl WorkerAction for Task {
fn x(&self) -> i32 {
self.x
}
fn y(&self) -> i32 {
self.y
}
... | y | identifier_name |
worker_actions.rs | //! Tasks and task execution of workes
//!
//! Note: This module and submodules will sooner or later need some refactoring.
//! For now, I am still don't really know how I want it to look like.
mod worker_abilities;
mod worker_updates;
use crate::db::DB;
use crate::game_master::event::*;
use crate::game_master::town_... |
TaskType::WelcomeAbility => {
if let Some(mana) = &mut worker.mana {
let cost = AbilityType::Welcome.mana_cost();
if *mana >= cost {
*mana = *mana - cost;
Ok(())
} else {
Err("Not enough mana... | {
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 | //! Tasks and task execution of workes
//!
//! Note: This module and submodules will sooner or later need some refactoring.
//! For now, I am still don't really know how I want it to look like.
mod worker_abilities;
mod worker_updates;
use crate::db::DB;
use crate::game_master::event::*;
use crate::game_master::town_... |
fn y(&self) -> i32 {
self.y
}
fn task_type(&self) -> &TaskType {
&self.task_type
}
fn target(&self) -> Option<HoboKey> {
self.target_hobo_id.map(HoboKey)
}
}
| {
self.x
} | identifier_body |
worker_actions.rs | //! Tasks and task execution of workes
//!
//! Note: This module and submodules will sooner or later need some refactoring.
//! For now, I am still don't really know how I want it to look like.
mod worker_abilities;
mod worker_updates;
use crate::db::DB;
use crate::game_master::event::*;
use crate::game_master::town_... | // 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 | use crate::{
arenas::atomic_bucket::{AtomicBucket, AtomicBucketList},
Capacity, LassoError, LassoErrorKind, LassoResult, MemoryLimits,
};
use core::{
fmt::{self, Debug},
num::NonZeroUsize,
slice, str,
sync::atomic::{AtomicUsize, Ordering},
};
/// An arena allocator that dynamically grows in siz... | (&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 | use crate::{
arenas::atomic_bucket::{AtomicBucket, AtomicBucketList},
Capacity, LassoError, LassoErrorKind, LassoResult, MemoryLimits,
};
use core::{
fmt::{self, Debug},
num::NonZeroUsize,
slice, str,
sync::atomic::{AtomicUsize, Ordering},
};
/// An arena allocator that dynamically grows in siz... |
}
}
impl Default for LockfreeArena {
fn default() -> Self {
Self::new(
Capacity::default().bytes,
MemoryLimits::default().max_memory_usage,
)
.expect("failed to create default arena")
}
}
impl Debug for LockfreeArena {
fn fmt(&self, f: &mut fmt::Formatt... | {
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 | use crate::{
arenas::atomic_bucket::{AtomicBucket, AtomicBucketList},
Capacity, LassoError, LassoErrorKind, LassoResult, MemoryLimits,
};
use core::{
fmt::{self, Debug},
num::NonZeroUsize,
slice, str,
sync::atomic::{AtomicUsize, Ordering},
};
/// An arena allocator that dynamically grows in siz... | 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 | use crate::{
arenas::atomic_bucket::{AtomicBucket, AtomicBucketList},
Capacity, LassoError, LassoErrorKind, LassoResult, MemoryLimits,
};
use core::{
fmt::{self, Debug},
num::NonZeroUsize,
slice, str,
sync::atomic::{AtomicUsize, Ordering},
};
/// An arena allocator that dynamically grows in siz... |
}
| {
let arena = LockfreeArena::new(NonZeroUsize::new(1).unwrap(), 1000).unwrap();
unsafe {
assert!(arena.store_str("abcdefghijklmnopqrstuvwxyz").is_ok());
}
} | identifier_body |
config.rs | use std::collections::HashMap;
use std::fs::File;
use std::io::Read;
use std::net::SocketAddr;
use std::ops::Range;
use std::time::Duration;
use clap::{app_from_crate, crate_authors, crate_description, crate_name, crate_version, value_t, Arg, SubCommand};
use toml;
use serde_derive::{Deserialize, Serialize};
use raf... | else {
// shold be unreachable
unreachable!("clap bug?")
}
} else {
(system, Command::Daemon)
}
}
}
| {
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 | use std::collections::HashMap;
use std::fs::File;
use std::io::Read;
use std::net::SocketAddr;
use std::ops::Range;
use std::time::Duration;
use clap::{app_from_crate, crate_authors, crate_description, crate_name, crate_version, value_t, Arg, SubCommand};
use toml;
use serde_derive::{Deserialize, Serialize};
use raf... | 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 | use std::collections::HashMap;
use std::fs::File;
use std::io::Read;
use std::net::SocketAddr;
use std::ops::Range;
use std::time::Duration;
use clap::{app_from_crate, crate_authors, crate_description, crate_name, crate_version, value_t, Arg, SubCommand};
use toml;
use serde_derive::{Deserialize, Serialize};
use raf... | {
Daemon,
Query(MgmtCommand, String),
}
impl System {
pub fn load() -> (Self, Command) {
// This is a first copy of args - with the "config" option
let app = app_from_crate!()
.long_version(concat!(crate_version!(), " ", env!("VERGEN_COMMIT_DATE"), " ", env!("VERGEN_SHA_SHORT")... | Command | identifier_name |
building.rs | use std::collections::{BTreeMap, HashSet, VecDeque};
use std::fmt;
use serde::{Deserialize, Serialize};
use strum::IntoEnumIterator;
use strum_macros::{Display, EnumIter, EnumString};
use abstutil::{
deserialize_btreemap, deserialize_usize, serialize_btreemap, serialize_usize, Tags,
};
use geom::{Distance, PolyLi... |
/// 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 | use std::collections::{BTreeMap, HashSet, VecDeque};
use std::fmt;
use serde::{Deserialize, Serialize};
use strum::IntoEnumIterator;
use strum_macros::{Display, EnumIter, EnumString};
use abstutil::{
deserialize_btreemap, deserialize_usize, serialize_btreemap, serialize_usize, Tags,
};
use geom::{Distance, PolyLi... | {
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 | use std::collections::{BTreeMap, HashSet, VecDeque};
use std::fmt;
use serde::{Deserialize, Serialize};
use strum::IntoEnumIterator;
use strum_macros::{Display, EnumIter, EnumString};
use abstutil::{
deserialize_btreemap, deserialize_usize, serialize_btreemap, serialize_usize, Tags,
};
use geom::{Distance, PolyLi... | 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 | use std::collections::{BTreeMap, HashSet, VecDeque};
use std::fmt;
use serde::{Deserialize, Serialize};
use strum::IntoEnumIterator;
use strum_macros::{Display, EnumIter, EnumString};
use abstutil::{
deserialize_btreemap, deserialize_usize, serialize_btreemap, serialize_usize, Tags,
};
use geom::{Distance, PolyLi... |
}
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 | /*
Copyright 2017 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, ... | (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 | /*
Copyright 2017 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, ... |
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 | /*
Copyright 2017 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, ... |
return true
}
| {
if y[k] != v {
return false
}
} | conditional_block |
main.go | /*
Copyright 2017 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, ... | now := time.Now()
klog.V(4).Infof("DELETE %#v @ %#p\n", obj, obj)
controller.ObserveResourceVersion(obj)
// IndexerInformer uses a delta queue, therefore for deletes we have to use this
// key function.
key, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj)
if err == nil {
od := controller... | } else {
klog.Errorf("Failed to parse key from obj %#v: %v\n", newobj, err)
}
},
DeleteFunc: func(obj interface{}) { | random_line_split |
types.rs | use super::parser::{Expr, Literal, Pattern};
#[derive(Eq, PartialEq, Debug, Clone)]
pub enum Type {
Int64,
Int32,
Float,
Dataset(im::HashMap<String, Type>),
/// T -> U
TyArr(Box<Type>, Box<Type>),
/// Type variable
TyVar(String),
// Data type
TyCon(String),
}
static COUNTER: st... | (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 | use super::parser::{Expr, Literal, Pattern};
#[derive(Eq, PartialEq, Debug, Clone)]
pub enum Type {
Int64,
Int32,
Float,
Dataset(im::HashMap<String, Type>),
/// T -> U
TyArr(Box<Type>, Box<Type>),
/// Type variable
TyVar(String),
// Data type
TyCon(String),
}
static COUNTER: st... |
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 | use super::parser::{Expr, Literal, Pattern};
#[derive(Eq, PartialEq, Debug, Clone)]
pub enum Type {
Int64,
Int32,
Float,
Dataset(im::HashMap<String, Type>),
/// T -> U
TyArr(Box<Type>, Box<Type>),
/// Type variable
TyVar(String),
// Data type
TyCon(String),
}
static COUNTER: st... | .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 | use super::{
converter::BaseConvertInfo,
flags::RuntimeHelper,
ir::{JsExpr as Js, VNodeIR},
parser::{Directive, DirectiveArg, ElemProp, Element},
scanner::Attribute,
};
use std::{
borrow::{Borrow, BorrowMut},
cell::UnsafeCell,
marker::PhantomData,
ops::Deref,
};
#[macro_export]
macr... | }
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 | use super::{
converter::BaseConvertInfo,
flags::RuntimeHelper,
ir::{JsExpr as Js, VNodeIR},
parser::{Directive, DirectiveArg, ElemProp, Element},
scanner::Attribute,
};
use std::{
borrow::{Borrow, BorrowMut},
cell::UnsafeCell,
marker::PhantomData,
ops::Deref,
};
#[macro_export]
macr... |
// since std::lazy::Lazy is not stable
// it is not thread safe, not Sync.
// it is Send if F and T is Send
pub struct Lazy<T, F = fn() -> T>(UnsafeCell<Result<T, Option<F>>>)
where
F: FnOnce() -> T;
impl<T, F> Lazy<T, F>
where
F: FnOnce() -> T,
{
pub fn new(f: F) -> Self {
Self(UnsafeCell::new(E... | {
PropFinder::new(elem, pat)
} | identifier_body |
util.rs | use super::{
converter::BaseConvertInfo,
flags::RuntimeHelper,
ir::{JsExpr as Js, VNodeIR},
parser::{Directive, DirectiveArg, ElemProp, Element},
scanner::Attribute,
};
use std::{
borrow::{Borrow, BorrowMut},
cell::UnsafeCell,
marker::PhantomData,
ops::Deref,
};
#[macro_export]
macr... |
}
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 | use super::{
converter::BaseConvertInfo,
flags::RuntimeHelper,
ir::{JsExpr as Js, VNodeIR},
parser::{Directive, DirectiveArg, ElemProp, Element},
scanner::Attribute,
};
use std::{
borrow::{Borrow, BorrowMut},
cell::UnsafeCell,
marker::PhantomData,
ops::Deref,
};
#[macro_export]
macr... | <'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 | // Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
#![cfg_attr(doc_cfg, feature(doc_cfg))]
pub use anyhow::Result;
use cargo_toml::{Dependency, Manifest};
use heck::AsShoutySnakeCase;
use tauri_utils::{
config::Config,
reso... |
/// 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 | // Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
#![cfg_attr(doc_cfg, feature(doc_cfg))]
pub use anyhow::Result;
use cargo_toml::{Dependency, Manifest};
use heck::AsShoutySnakeCase;
use tauri_utils::{
config::Config,
reso... | (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 | // Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
#![cfg_attr(doc_cfg, feature(doc_cfg))]
pub use anyhow::Result;
use cargo_toml::{Dependency, Manifest};
use heck::AsShoutySnakeCase;
use tauri_utils::{
config::Config,
reso... | ;
let diff = features_diff(
&features
.into_iter()
.filter(|f| all_cli_managed_features.contains(&f.as_str()))
.collect::<Vec<String>>(),
&expected,
);
let mut error_message = String::new();
if !diff.remove.is_empty() {
error_message.push_str("remove the `");
error_message.pu... | {
config
.tauri
.features()
.into_iter()
.map(|f| f.to_string())
.collect::<Vec<String>>()
} | conditional_block |
lib.rs | // Copyright 2019-2023 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
#![cfg_attr(doc_cfg, feature(doc_cfg))]
pub use anyhow::Result;
use cargo_toml::{Dependency, Manifest};
use heck::AsShoutySnakeCase;
use tauri_utils::{
config::Config,
reso... | .icon
.iter()
.find(|i| predicate(i))
.cloned()
.unwrap_or_else(|| default.to_string());
icon_path.into()
}
let window_icon_path = attributes
.windows_attributes
.window_icon_path
.unwrap_or_else(|| find_icon(&config, |i| i.ends_with(".ico"), "ico... | .tauri
.bundle | random_line_split |
main.rs | use clap::{App, AppSettings, Arg, SubCommand};
use default_boxed::DefaultBoxed;
#[derive(DefaultBoxed)]
struct Outer<'a, 'b> {
inner: HeapApp<'a, '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("serviceus... | {
// 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 | use clap::{App, AppSettings, Arg, SubCommand};
use default_boxed::DefaultBoxed;
#[derive(DefaultBoxed)]
struct Outer<'a, 'b> {
inner: HeapApp<'a, '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("serviceus... | {
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 | use clap::{App, AppSettings, Arg, SubCommand};
use default_boxed::DefaultBoxed;
#[derive(DefaultBoxed)]
struct Outer<'a, 'b> {
inner: HeapApp<'a, '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 | /*
* Copyright IBM Corporation 2021
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law o... |
func (c *V3Loader) getEnvs(composeServiceConfig types.ServiceConfig) (envs []core.EnvVar) {
for name, value := range composeServiceConfig.Environment {
var env core.EnvVar
if value != nil {
env = core.EnvVar{Name: name, Value: *value}
} else {
env = core.EnvVar{Name: name, Value: "unknown"}
}
envs = ... | {
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 | /*
* Copyright IBM Corporation 2021
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law o... | },
}
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 | /*
* Copyright IBM Corporation 2021
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law o... |
if exist[portValue] {
continue
}
// Forward the port on the k8s service to the k8s pod.
portNumber := cast.ToInt32(portValue)
podPort := networking.ServiceBackendPort{
Number: portNumber,
}
servicePort := networking.ServiceBackendPort{
Number: portNumber,
}
service.AddPortForwarding(serviceP... | {
splits := strings.Split(port, "/")
portValue = splits[0]
} | conditional_block |
v3.go | /*
* Copyright IBM Corporation 2021
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law o... | (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 | use std::{
borrow::Cow,
fmt::{self, Write as _},
io,
time::Duration,
};
use termcolor::{ColorSpec, WriteColor};
use unicode_width::UnicodeWidthChar;
use crate::{markup, Markup, MarkupElement};
/// A stack-allocated linked-list of [MarkupElement] slices
pub enum MarkupElements<'a> {
Root,
Node... | {
let mut adapter = SanitizeAdapter {
writer: &mut buffer,
error: Ok(()),
};
adapter.write_str(INPUT).unwrap();
adapter.error.unwrap();
}
assert_eq!(from_utf8(&buffer).unwrap(), OUTPUT);
}
} | 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 | use std::{
borrow::Cow,
fmt::{self, Write as _},
io,
time::Duration,
};
use termcolor::{ColorSpec, WriteColor};
use unicode_width::UnicodeWidthChar;
use crate::{markup, Markup, MarkupElement};
/// A stack-allocated linked-list of [MarkupElement] slices
pub enum MarkupElements<'a> {
Root,
Node... |
/// 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 | use std::{
borrow::Cow,
fmt::{self, Write as _},
io,
time::Duration,
};
use termcolor::{ColorSpec, WriteColor};
use unicode_width::UnicodeWidthChar;
use crate::{markup, Markup, MarkupElement};
/// A stack-allocated linked-list of [MarkupElement] slices
pub enum MarkupElements<'a> {
Root,
Node... | 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 | use std::{
borrow::Cow,
fmt::{self, Write as _},
io,
time::Duration,
};
use termcolor::{ColorSpec, WriteColor};
use unicode_width::UnicodeWidthChar;
use crate::{markup, Markup, MarkupElement};
/// A stack-allocated linked-list of [MarkupElement] slices
pub enum MarkupElements<'a> {
Root,
Node... | (&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 | // Copyright 2016 taskqueue developers
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according ... |
/// Like `Queue::foreach` but provides a mutable reference to the bound variable
///
/// # Example
///
/// ```
/// # use taskqueue::*;
/// # let queue = SerialQueue::new();
/// let bound = queue.with(|| 2);
/// let doubled: Vec<i32> = bound.foreach_with((0..20), |factor, x| x*facto... | {
self.queue.sync(move || operation(unsafe { self.binding.get_mut() }))
} | identifier_body |
serial.rs | // Copyright 2016 taskqueue developers
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according ... | <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 | // Copyright 2016 taskqueue developers
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according ... | {
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 | #!/usr/bin/env python
"""Pathspecs are methods of specifying the path on the client.
The GRR client has a number of drivers to virtualize access to different objects
to create a Virtual File System (VFS) abstraction. These are called 'VFS
Handlers' and they provide typical file-like operations (e.g. read, seek, tell
a... |
@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 | #!/usr/bin/env python
"""Pathspecs are methods of specifying the path on the client.
The GRR client has a number of drivers to virtualize access to different objects
to create a Virtual File System (VFS) abstraction. These are called 'VFS
Handlers' and they provide typical file-like operations (e.g. read, seek, tell
a... | (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 | #!/usr/bin/env python
"""Pathspecs are methods of specifying the path on the client.
The GRR client has a number of drivers to virtualize access to different objects
to create a Virtual File System (VFS) abstraction. These are called 'VFS
Handlers' and they provide typical file-like operations (e.g. read, seek, tell
a... |
@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 | #!/usr/bin/env python
"""Pathspecs are methods of specifying the path on the client.
The GRR client has a number of drivers to virtualize access to different objects
to create a Virtual File System (VFS) abstraction. These are called 'VFS
Handlers' and they provide typical file-like operations (e.g. read, seek, tell
a... |
else:
return re.escape(part)
def ExplainComponents(self, example_count: int,
knowledge_base) -> Sequence[GlobComponentExplanation]:
"""Returns a list of GlobComponentExplanations with examples."""
parts = _COMPONENT_SPLIT_PATTERN.split(self._value)
components = []
... | return GROUPING_PATTERN.sub(self._ReplaceRegExGrouping, part) | conditional_block |
images.go | // Copyright 2015 The rkt Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to... | return nil, fmt.Errorf("error writing %s: %v", label, err)
}
return cd, nil
}
func ascURLFromImgURL(imgurl string) string {
s := strings.TrimSuffix(imgurl, ".aci")
return s + ".aci.asc"
}
// newDiscoveryApp creates a discovery app if the given img is an app name and
// has a URL-like structure, for example exa... |
if err := out.Sync(); err != nil { | random_line_split |
images.go | // Copyright 2015 The rkt Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to... | (headerValue string) int {
var MaxAge int = 0
if len(headerValue) > 0 {
parts := strings.Split(headerValue, " ")
for i := 0; i < len(parts); i++ {
attr, val := parts[i], ""
if j := strings.Index(attr, "="); j >= 0 {
attr, val = attr[:j], attr[j+1:]
}
lowerAttr := strings.ToLower(attr)
switch ... | getMaxAge | identifier_name |
images.go | // Copyright 2015 The rkt Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to... | else {
aciFile, err = f.s.TmpFile()
if err != nil {
return nil, aciFile, nil, fmt.Errorf("error setting up temporary file: %v", err)
}
defer os.Remove(aciFile.Name())
if cd, err = f.downloadACI(aciURL, aciFile, etag); err != nil {
return nil, nil, nil, fmt.Errorf("error downloading ACI: %v", err)
}
... | {
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 | // Copyright 2015 The rkt Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to... |
func ascURLFromImgURL(imgurl string) string {
s := strings.TrimSuffix(imgurl, ".aci")
return s + ".aci.asc"
}
// newDiscoveryApp creates a discovery app if the given img is an app name and
// has a URL-like structure, for example example.com/reduce-worker.
// Or it returns nil.
func newDiscoveryApp(img string) *di... | {
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 | /*
Copyright 2018 Iguazio Systems Ltd.
Licensed under the Apache License, Version 2.0 (the "License") with
an addition restriction as set forth herein. You may not use this
file except in compliance with the License. You may obtain a copy of
the License at http://www.apache.org/licenses/LICENSE-2.0.
Unless required b... |
var selectParams *pquerier.SelectParams
if strings.HasPrefix(qc.name, "select") {
selectParams, _, err = pquerier.ParseQuery(qc.name)
if err != nil {
return errors.Wrap(err, "failed to parse sql")
}
selectParams.Step = step
selectParams.From = from
selectParams.To = to
selectParams.UseOnlyClientAg... | {
return errors.Wrap(err, "Failed to parse aggregation window")
} | conditional_block |
query.go | /*
Copyright 2018 Iguazio Systems Ltd.
Licensed under the Apache License, Version 2.0 (the "License") with
an addition restriction as set forth herein. You may not use this
file except in compliance with the License. You may obtain a copy of
the License at http://www.apache.org/licenses/LICENSE-2.0.
Unless required b... | err = f.Write(qc.cmd.OutOrStdout(), set)
return err
} | return errors.Wrapf(err, "Failed to start formatter '%s'.", qc.output)
}
| random_line_split |
query.go | /*
Copyright 2018 Iguazio Systems Ltd.
Licensed under the Apache License, Version 2.0 (the "License") with
an addition restriction as set forth herein. You may not use this
file except in compliance with the License. You may obtain a copy of
the License at http://www.apache.org/licenses/LICENSE-2.0.
Unless required b... | (from, to, step int64) error {
qry, err := qc.rootCommandeer.adapter.QuerierV2()
if err != nil {
return errors.Wrap(err, "Failed to initialize the Querier object.")
}
aggregationWindow, err := utils.Str2duration(qc.aggregationWindow)
if err != nil {
return errors.Wrap(err, "Failed to parse aggregation window")... | newQuery | identifier_name |
query.go | /*
Copyright 2018 Iguazio Systems Ltd.
Licensed under the Apache License, Version 2.0 (the "License") with
an addition restriction as set forth herein. You may not use this
file except in compliance with the License. You may obtain a copy of
the License at http://www.apache.org/licenses/LICENSE-2.0.
Unless required b... |
func (qc *queryCommandeer) newQuery(from, to, step int64) error {
qry, err := qc.rootCommandeer.adapter.QuerierV2()
if err != nil {
return errors.Wrap(err, "Failed to initialize the Querier object.")
}
aggregationWindow, err := utils.Str2duration(qc.aggregationWindow)
if err != nil {
return errors.Wrap(err, ... | {
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 | use std::error::Error;
use mio::net::{ TcpListener, TcpStream, UdpSocket};
use mio::{Events, Interest, Poll, Token};
use std::io::{Read, Write};
use hex;
use rand::{thread_rng, Rng};
use keccak_hash::keccak;
use secp256k1::{SecretKey, PublicKey, Message, RecoveryId, Signature, sign, recover};
use rlp::{Rlp, RlpStream};... |
} 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 | use std::error::Error;
use mio::net::{ TcpListener, TcpStream, UdpSocket};
use mio::{Events, Interest, Poll, Token};
use std::io::{Read, Write};
use hex;
use rand::{thread_rng, Rng};
use keccak_hash::keccak;
use secp256k1::{SecretKey, PublicKey, Message, RecoveryId, Signature, sign, recover};
use rlp::{Rlp, RlpStream};... | ,
Err(err) => {
println!("read data error {:?}", err);
}
}
}
println!("client socket is writable");
}
... | {
println!("write ok");
} | conditional_block |
main0.rs | use std::error::Error;
use mio::net::{ TcpListener, TcpStream, UdpSocket};
use mio::{Events, Interest, Poll, Token};
use std::io::{Read, Write};
use hex;
use rand::{thread_rng, Rng};
use keccak_hash::keccak;
use secp256k1::{SecretKey, PublicKey, Message, RecoveryId, Signature, sign, recover};
use rlp::{Rlp, RlpStream};... |
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("ee5495585eff78f2fcf95bab21ef1a598c54d1e3c672e... | {
match message_type {
0x01 => {
println!("ping message");
},
0x02 => {
println!("pong message");
},
0x03 => {
println!("find neighbours message");
},
0x04 => {
println!("neighbours message");
},
... | identifier_body |
main0.rs | use std::error::Error;
use mio::net::{ TcpListener, TcpStream, UdpSocket};
use mio::{Events, Interest, Poll, Token};
use std::io::{Read, Write};
use hex;
use rand::{thread_rng, Rng};
use keccak_hash::keccak;
use secp256k1::{SecretKey, PublicKey, Message, RecoveryId, Signature, sign, recover};
use rlp::{Rlp, RlpStream};... | () -> 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 | // Copyright 2019 Tamás Gulácsi. All rights reserved.
package main
import (
"bytes"
"context"
"database/sql"
"flag"
"fmt"
"io"
"log"
"os"
"reflect"
"runtime"
"runtime/pprof"
"strings"
"sync"
"sync/atomic"
"time"
"unicode"
"github.com/pkg/errors"
"github.com/tgulacsi/go/dbcsv"
"golang.org/x/sync/er... | := io.WriteString(w, qRepl.Replace(s)); err != nil {
return err
}
_, err := w.Write([]byte{'\''})
return err
}
// vim: set fileencoding=utf-8 noet:
| err
}
if _, err | conditional_block |
csvload.go | // Copyright 2019 Tamás Gulácsi. All rights reserved.
package main
import (
"bytes"
"context"
"database/sql"
"flag"
"fmt"
"io"
"log"
"os"
"reflect"
"runtime"
"runtime/pprof"
"strings"
"sync"
"sync/atomic"
"time"
"unicode"
"github.com/pkg/errors"
"github.com/tgulacsi/go/dbcsv"
"golang.org/x/sync/er... | r, s string) error {
if _, err := w.Write([]byte{'\''}); err != nil {
return err
}
if _, err := io.WriteString(w, qRepl.Replace(s)); err != nil {
return err
}
_, err := w.Write([]byte{'\''})
return err
}
// vim: set fileencoding=utf-8 noet:
| Write | identifier_name |
csvload.go | // Copyright 2019 Tamás Gulácsi. All rights reserved.
package main
import (
"bytes"
"context"
"database/sql"
"flag"
"fmt"
"io"
"log"
"os"
"reflect"
"runtime"
"runtime/pprof"
"strings"
"sync"
"sync/atomic"
"time"
"unicode"
"github.com/pkg/errors"
"github.com/tgulacsi/go/dbcsv"
"golang.org/x/sync/er... | 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 | // Copyright 2019 Tamás Gulácsi. All rights reserved.
package main
import (
"bytes"
"context"
"database/sql"
"flag"
"fmt"
"io"
"log"
"os"
"reflect"
"runtime"
"runtime/pprof"
"strings"
"sync"
"sync/atomic"
"time"
"unicode"
"github.com/pkg/errors"
"github.com/tgulacsi/go/dbcsv"
"golang.org/x/sync/er... | olumns(ctx context.Context, db *sql.DB, tbl string) ([]Column, error) {
// TODO(tgulacsi): this is Oracle-specific!
const qry = "SELECT column_name, data_type, data_length, data_precision, data_scale, nullable FROM user_tab_cols WHERE table_name = UPPER(:1) ORDER BY column_id"
rows, err := db.QueryContext(ctx, qry, ... | 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 | # -*- coding: utf-8 -*-
"""prediction.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1lcvaJYf5k-Y0mmlCYAF8kWQlr2P-eTwr
"""
# Load model
from joblib import dump, load
# model_name = "DTR_model"
# model = load('../models/' + model_name + '.joblib... |
def concatenate_cmems(cm_wave, cm_phy, ship_param, ship_dir):
"""
concatenate the variables from cmems wave and physics datasets
Parameters
----------
cm_wave : net4CDF dataset
netcdf file cmems wave
cm_phy : net4CDF dataset
netdcf file cmems physics
ship_param : int
sh... | """
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 | # -*- coding: utf-8 -*-
"""prediction.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1lcvaJYf5k-Y0mmlCYAF8kWQlr2P-eTwr
"""
# Load model
from joblib import dump, load
# model_name = "DTR_model"
# model = load('../models/' + model_name + '.joblib... | (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 | # -*- coding: utf-8 -*-
"""prediction.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1lcvaJYf5k-Y0mmlCYAF8kWQlr2P-eTwr
"""
# Load model
from joblib import dump, load
# model_name = "DTR_model"
# model = load('../models/' + model_name + '.joblib... |
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 | # -*- coding: utf-8 -*-
"""prediction.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1lcvaJYf5k-Y0mmlCYAF8kWQlr2P-eTwr
"""
# Load model
from joblib import dump, load
# model_name = "DTR_model"
# model = load('../models/' + model_name + '.joblib... |
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 | "use strict";
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
/*
* 用于iframe内外通信。
* iconnect.tr... | '\\': '\\\\'
},
rep;
function quote(string) {
// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.
... | identifier_name | |
iconnect.js | "use strict";
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
/*
* 用于iframe内外通信。
* iconnect.tr... | }
};
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 | "use strict";
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
/*
* 用于iframe内外通信。
* iconnect.tr... | Message(msg, '*');
} else {
window.navigator['STK_IFRAME_CONNECT_OUT'](msg);
}
};
var listener = function listener(evt) {
try {
var data = utils.str2json(evt.data);
if (data.cid && data.cid == '_EVENT_') {
cEvt.define(event, data.call);
cEvt.fire(event, data.call, data.rs);
} else... | ow.parent.postMessage) {
window.parent.post | conditional_block |
iconnect.js | "use strict";
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
/*
* 用于iframe内外通信。
* iconnect.tr... | hrow an error.
rep = replacer;
if (replacer && typeof replacer !== 'function' && ((typeof replacer === "undefined" ? "undefined" : _typeof(replacer)) !== 'object' || typeof replacer.length !== 'number')) {
throw new Error('JSON.stringify');
}
// Make a fake root object containing our value under t... | 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 | package common
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package binary implements simple translation between numbers and byte
// sequences and encoding and decoding of varints.
//
// Numbers are t... | (data interface{}) int {
switch data := data.(type) {
case int8, *int8, *uint8:
return 1
case []int8:
return len(data)
case []uint8:
return len(data)
case int16, *int16, *uint16:
return 2
case []int16:
return 2 * len(data)
case []uint16:
return 2 * len(data)
case int32, *int32, *uint32:
return 4
... | intDataSize | identifier_name |
binary.go | package common
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package binary implements simple translation between numbers and byte
// sequences and encoding and decoding of varints.
//
// Numbers are t... |
type coder struct {
order ByteOrder
buf []byte
}
type (
decoder coder
encoder coder
)
func (d *decoder) uint8() uint8 {
x := d.buf[0]
d.buf = d.buf[1:]
return x
}
func (e *encoder) uint8(x uint8) {
e.buf[0] = x
e.buf = e.buf[1:]
}
func (d *decoder) uint16() uint16 {
x := d.order.Uint16(d.buf[0:2])
d.... | {
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 | package common
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package binary implements simple translation between numbers and byte
// sequences and encoding and decoding of varints.
//
// Numbers are t... | else {
d.skip(v)
}
}
case reflect.Slice:
l := v.Len()
for i := 0; i < l; i++ {
d.value(v.Index(i))
}
case reflect.Int8:
v.SetInt(int64(d.int8()))
case reflect.Int16:
v.SetInt(int64(d.int16()))
case reflect.Int32:
v.SetInt(int64(d.int32()))
case reflect.Int64:
v.SetInt(d.int64())
case... | {
d.value(v)
} | conditional_block |
binary.go | package common
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package binary implements simple translation between numbers and byte
// sequences and encoding and decoding of varints.
//
// Numbers are t... | 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 | use std::convert::TryInto;
use std::io::Write;
use clap;
use bitcoin::hashes::Hash;
use bitcoin;
use elements::encode::{deserialize, serialize};
use elements::{
confidential, AssetIssuance, OutPoint, Transaction, TxIn, TxInWitness, TxOut, TxOutWitness,
Script,
};
use elements::secp256k1_zkp::{
Generator, PedersenCo... |
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() {
warn... | {
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 | use std::convert::TryInto;
use std::io::Write;
use clap;
use bitcoin::hashes::Hash;
use bitcoin;
use elements::encode::{deserialize, serialize};
use elements::{
confidential, AssetIssuance, OutPoint, Transaction, TxIn, TxInWitness, TxOut, TxOutWitness,
Script,
};
use elements::secp256k1_zkp::{
Generator, PedersenCo... | (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 | use std::convert::TryInto;
use std::io::Write;
use clap;
use bitcoin::hashes::Hash;
use bitcoin;
use elements::encode::{deserialize, serialize};
use elements::{
confidential, AssetIssuance, OutPoint, Transaction, TxIn, TxInWitness, TxOut, TxOutWitness,
Script,
};
use elements::secp256k1_zkp::{
Generator, PedersenCo... | } else {
print!("{}", hex::encode(&tx_bytes));
}
}
fn cmd_decode<'a>() -> clap::App<'a, 'a> {
cmd::subcommand("decode", "decode a raw transaction to JSON")
.args(&cmd::opts_networks())
.args(&[cmd::opt_yaml(), cmd::arg("raw-tx", "the raw transaction in hex").required(false)])
}
fn exec_decode<'a>(matches: &c... | ::std::io::stdout().write_all(&tx_bytes).unwrap(); | random_line_split |
RHD_Load_Filter.py | # -*- coding: utf-8 -*-
"""
Created on Tue Feb 28 16:06:17 2023
@author: Gilles.DELBECQ
"""
import sys, struct, math, os, time
import numpy as np
import matplotlib.pyplot as plt
import scipy.signal as sp
def read_data(filename):
"""Reads Intan Technologies RHD2000 data file generated by evaluation board GUI.
... |
"""
Spike detection
"""
thresholds=[]
spikes_list=[]
spikes_list_y=[]
wfs=[]
waveforms=[]
for signal in cmr_signals:
# Threshold calculation
noise = signal[0:int(noise_window*sampling_rate)] #noise window taken from individual channel signal
threshold = np.median(noise)+std_threshold*np.std(noise) #thr... | t.figure()
plt.plot(time_vector,cmr_signals[i])
plt.title(rf'channel {int(selected_channels[i])}')
| conditional_block |
RHD_Load_Filter.py | # -*- coding: utf-8 -*-
"""
Created on Tue Feb 28 16:06:17 2023
@author: Gilles.DELBECQ
"""
import sys, struct, math, os, time
import numpy as np
import matplotlib.pyplot as plt
import scipy.signal as sp
def read_data(filename):
"""Reads Intan Technologies RHD2000 data file generated by evaluation board GUI.
... | #Detect the spike indexes
spike_idx, _ = sp.find_peaks(-signal,height=threshold,distance=distance)
#Convert to spike times
spike_times = spike_idx*1./sampling_rate
#Get spikes peak
spike_y = signal[spike_idx]
#Append spikes times to the list of all channels spikes
spikes_list.appen... | random_line_split | |
RHD_Load_Filter.py | # -*- coding: utf-8 -*-
"""
Created on Tue Feb 28 16:06:17 2023
@author: Gilles.DELBECQ
"""
import sys, struct, math, os, time
import numpy as np
import matplotlib.pyplot as plt
import scipy.signal as sp
def read_data(filename):
"""Reads Intan Technologies RHD2000 data file generated by evaluation board GUI.
... | (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_Gustave_15_03_230315_182841/Test_Gustave_15_03_230315_182841.rhd"
reade... | plural | identifier_name |
RHD_Load_Filter.py | # -*- coding: utf-8 -*-
"""
Created on Tue Feb 28 16:06:17 2023
@author: Gilles.DELBECQ
"""
import sys, struct, math, os, time
import numpy as np
import matplotlib.pyplot as plt
import scipy.signal as sp
def read_data(filename):
"""Reads Intan Technologies RHD2000 data file generated by evaluation board GUI.
... |
path="//equipe2-nas1/Gilles.DELBECQ/Data/ePhy/Février2023/Test_Gustave/raw/raw intan/Test_Gustave_15_03_230315_182841/Test_Gustave_15_03_230315_182841.rhd"
reader=read_data(path)
sampling_rate = reader['frequency_parameters']['amplifier_sample_rate']
time_vector=reader['t_amplifier']
signal=reader['amplifier_data... | """Utility function to optionally pluralize words based on the value of n.
"""
if n == 1:
return ''
else:
return 's' | identifier_body |
term_gui.rs | // Copyright (c) The Swiboe development team. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE.txt
// in the project root for license information.
#[macro_use]
extern crate clap;
extern crate rustbox;
extern crate serde_json;
extern crate subsequence_match;
extern crate swiboe;
exter... |
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 | // Copyright (c) The Swiboe development team. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE.txt
// in the project root for license information.
#[macro_use]
extern crate clap;
extern crate rustbox;
extern crate serde_json;
extern crate subsequence_match;
extern crate swiboe;
exter... | ,
rustbox::Key::Left => {
self.config_file_runner.keymap_handler.key_down(
delta_t_in_seconds, keymap_handler::Key::Left);
},
rustbox::Key::Right => {
self.config_file_runner.keymap_handler.key_down(
delta_t_in_s... | {
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.