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 |
|---|---|---|---|---|
demo.py | (modelID):
print "Loading parameters for model", modelID
selection=raw_input('Would you like to download NWB data for model? [Y/N] ')
if selection[0] == 'y' or selection[0] == 'Y':
currModel = Model(modelID, cache_stim = True)
if selection[0] == 'n' or selection[0] == 'N':
currMo... | main | identifier_name | |
demo.py | "Initialized biophysical model", modelID
print '''
Please select from the following options:
1 - Run test pulse on model
2 - Fit model parameter to data
3 - Display static neuron model
4 - Visualize model dynamics
5 - Quit
'''
try:
... |
# if at a branch point or an end of a section, set up a vector to monitor that segment's voltage
type = compartmentNames[n['type']]
sec_index = sectionIndices[n['type']]
if not (len(morphology.children_of(n)) == 1): #either branch pt or end
sec_nam... | tempCol[offset+col_i] = cval
col_i += 1 | conditional_block |
fs.rs | x| Error::from_sys(x))
}
}
impl Drop for File {
fn drop(&mut self) {
let _ = close(self.fd);
}
}
#[derive(Copy, Clone, Eq, PartialEq)]
pub struct FileType {
dir: bool,
file: bool,
}
impl FileType {
pub fn is_dir(&self) -> bool {
self.dir
}
pub fn is_file(&self) -> boo... | {
try!(remove_file(&child.path()));
} | conditional_block | |
fs.rs | from_raw_fd(fd) }).map_err(|x| Error::from_sys(x))
}
/// Duplicate the file
pub fn dup(&self, buf: &[u8]) -> Result<File> {
dup(self.fd, buf).map(|fd| unsafe { File::from_raw_fd(fd) }).map_err(|x| Error::from_sys(x))
}
/// Get information about a file
pub fn metadata(&self) -> Result<M... | self.mode = mode as u16;
}
fn from_mode(mode: u32) -> Self {
Permissions {
mode: mode as u16
}
}
}
pub struct DirEntry {
path: PathBuf,
}
impl DirEntry {
pub fn file_name(&self) -> &Path {
unsafe { mem::transmute(self.path.file_name().unwrap().to_str().... | random_line_split | |
fs.rs | from_raw_fd(fd) }).map_err(|x| Error::from_sys(x))
}
/// Duplicate the file
pub fn dup(&self, buf: &[u8]) -> Result<File> {
dup(self.fd, buf).map(|fd| unsafe { File::from_raw_fd(fd) }).map_err(|x| Error::from_sys(x))
}
/// Get information about a file
pub fn metadata(&self) -> Result<M... |
}
impl FromRawFd for File {
unsafe fn from_raw_fd(fd: RawFd) -> Self {
File {
fd: fd
}
}
}
impl IntoRawFd for File {
fn into_raw_fd(self) -> RawFd {
let fd = self.fd;
mem::forget(self);
fd
}
}
impl Read for File {
fn read(&mut self, buf: &mut [... | {
self.fd
} | identifier_body |
fs.rs | pub fn sync_data(&mut self) -> Result<()> {
fsync(self.fd).and(Ok(())).map_err(|x| Error::from_sys(x))
}
/// Truncates the file
pub fn set_len(&self, size: u64) -> Result<()> {
ftruncate(self.fd, size as usize).and(Ok(())).map_err(|x| Error::from_sys(x))
}
}
impl AsRawFd for File {
... | create_dir_all | identifier_name | |
dnp3.go | File
case 27: // Delete File
case 28: // Get File Info
case 29: // Authenticate File
case 30: // Abort File
case 31: // Activate Config
case 32: // Authentication Request
case 33: // Authentication Error
case 129: // Response
case 130: // Unsolicited Response
case 131: // Authentication Response
}
objType... | var FinalFrame10 byte = 0x80
var OneFrame11 byte = 0xC0
TpFinFir := bytesRead[10] & 0xC0
switch TpFinFir { | random_line_split | |
dnp3.go | 3: "Objects prefixed with 4-octet index",
4: "Objects prefixed with 1-octet object size",
5: "Objects prefixed with 2-octet object size",
6: "Objects prefixed with 4-octet object size",
7: "Reserved",
}
/***************************************************************************/
/* Application Layer Object Prefix... | () gopacket.LayerType {
return gopacket.LayerTypePayload
}
// Payload returns nil, since TLS encrypted payload is inside TLSAppDataRecord
func (d *DNP3) Payload() []byte {
return nil
}
func appObject(bytesRead []byte) {
object := bytesRead[22:]
// indexSize := uint(object[2] & 0x70 >> 4)
// QualifierCode := ui... | NextLayerType | identifier_name |
dnp3.go | 3: "Objects prefixed with 4-octet index",
4: "Objects prefixed with 1-octet object size",
5: "Objects prefixed with 2-octet object size",
6: "Objects prefixed with 4-octet object size",
7: "Reserved",
}
/***************************************************************************/
/* Application Layer Object Prefix... |
func (d *DNP3) DecodeFromBytes(data []byte, df gopacket.DecodeFeedback) error {
// If the data block is too short to be a DNP3 layer, then return an error.
if len(data) < 10 {
df.SetTruncated()
return errDNP3PacketTooShort
}
d.linkLayer(data)
d.transportLayer(data)
d.applicationLayer(data)
return nil
}
... | {
return d.restOfData
} | identifier_body |
dnp3.go | 3: "Objects prefixed with 4-octet index",
4: "Objects prefixed with 1-octet object size",
5: "Objects prefixed with 2-octet object size",
6: "Objects prefixed with 4-octet object size",
7: "Reserved",
}
/***************************************************************************/
/* Application Layer Object Prefix... |
ctlFUNC = ctlFUNC + " (" + ctlFUNCCODE + ")"
d.DNP3DataLinkLayer.Control.FUNC = ctlFUNC
// TODO: make sure 0 to 65535
destination := fmt.Sprintf("%x%x", data[5], data[4])
destinationInt, _ := strconv.Atoi(destination)
d.DNP3DataLinkLayer.Destination = destinationInt
// TODO: make sure 0 to 65535
source := f... | {
ctlFUNC = PfCodes[FUNCCODE]
} | conditional_block |
config.js | UENTD_PORT, 10) || 24224;
internals.Config.nginxHost = process.env.UNMS_NGINX_HOST || '127.0.0.1';
internals.Config.nginxPort = parseInt(process.env.UNMS_NGINX_PORT, 10) || 12345;
internals.Config.defaultInternalHttpPort = 8081;
internals.Config.defaultInternalWsPort = 8082;
internals.Config.defaultHttpsPort = 443;
int... | random_line_split | ||
packet.go | kCidDefaultLength is the length of connection ID we generate.
// TODO: make this configurable.
const kCidDefaultLength = 5
// ConnectionId identifies the connection that a packet belongs to.
type ConnectionId []byte
// String stringifies a connection ID in the natural way.
func (c ConnectionId) String() string {
re... | {
return 0, 0, fmt.Errorf("Buffer too short for packet number (%v < %v)", len(buf), pat.length)
} | conditional_block | |
packet.go | 9 0 1
+-+-+-+-+-+-+-+-+
|0|K|1|1|0|R R R|
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Destination Connection ID (0..144) ...
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Packet Number (8/16/32) ...
+-+-+-+-+-+-+-... | sample_length := 16
if sample_length > len(p)-(hdrlen+1) { | random_line_split | |
packet.go | 2) |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|DCIL(4)|SCIL(4)|
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Destination Connection ID (0/32..144) ...
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| ... | (versions []VersionNumber) *versionNegotiationPacket {
var buf bytes.Buffer
for _, v := range versions {
buf.Write(encodeArgs(v))
}
return &versionNegotiationPacket{buf.Bytes()}
}
/*
We don't use these.
func encodePacket(c ConnectionState, aead Aead, p *Packet) ([]byte, error) {
hdr, err := encode(&p.packetH... | newVersionNegotiationPacket | identifier_name |
packet.go | 2) |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|DCIL(4)|SCIL(4)|
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Destination Connection ID (0/32..144) ...
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| ... |
func (pt packetType) String() string {
switch pt {
case packetTypeInitial:
return "Initial"
case packetTypeRetry:
return "Retry"
case packetTypeHandshake:
return "Handshake"
case packetType0RTTProtected:
return "0-RTT"
case packetTypeProtectedShort:
return "1-RTT"
default:
return fmt.Sprintf("%x", ... | {
if !pt.isLongHeader() {
return true
}
switch pt & 0x7f {
case packetTypeInitial, packetTypeHandshake, packetTypeRetry:
return false
}
return true
} | identifier_body |
TCP_echo_server.py | Error:
search_result = False
except ssl.SSLError:
search_result = False
if search_result:
print('\n用户' + account['username'] + '登陆成功!\n')
writer.write('Login Success'.encode())
await writer.drain()
return True
else:
writer.write('Need Email'.encode())... | identifier_body | ||
TCP_echo_server.py | _connection.decode(), method=False)
if ensure_connection['code'] == 'Accept connection':
try:
connect_success = {'local_addr': local_addr, 'request_addr': dest_addr, 'code': 'Ready'}
connect_success = transfer_json(connect_success, method=True)
... |
print('正在请求:' + str(client_addr) + '请求目的ip:' + str(dest_ip))
find_dest = await connect_dest_server(dest_ip, reader, writer, l_reader, l_writer)
if find_dest:
config_rule['ident'] = 'hi'
config_rule_json = json.dumps(config_rule)
writer.write(config_rule_jso... | random_line_split | |
TCP_echo_server.py | .decode(), method=False)
if ensure_connection['code'] == 'Accept connection':
try:
connect_success = {'local_addr': local_addr, 'request_addr': dest_addr, 'code': 'Ready'}
connect_success = transfer_json(connect_success, method=True)
... | account['password'])
cur.execute(sql)
search_result = cur.fetchall()
except sqlite3.OperationalError:
search_result = False
except ssl.SSLError:
search_result = False
if search_result:
print('\n用户' + account['usern... | identifier_name | |
TCP_echo_server.py | (connect_success.encode())
await local_writer.drain()
print('请求成功:' + str(local_addr) + '正在与' + str(dest_addr) + '通讯...\n')
dest = {'addr': dest_addr, 'Reader': dest_reader, 'Writer': dest_writer}
return dest
except Connecti... | print('用户已断开连接:', client_addr)
writer.close()
s_w | conditional_block | |
localization.rs | .clone()
} else {
let string = fs::read_to_string(&path).unwrap_or_else(|_| {
if (res_id, locale) == ("builtin.ftl", "en-US") {
FALLBACK_STRINGS.to_string()
} else {
error!("missing resouce {}/{}", locale... | {
false
} | conditional_block | |
localization.rs | on things like `Menu`.
/////// A closure that generates a localization value.
type ArgClosure<T> = fn(&T, &Env) -> ArgValue; ////
////type ArgClosure<T> = Arc<dyn Fn(&T, &Env) -> FluentValue<'static> + 'static>;
/// Wraps a closure that generates an argument for localization.
#[derive(Clone)]
struct ArgSource<T>(ArgC... | with_arg | identifier_name | |
localization.rs | Arg = heapless::consts::U2; //// Max number of localized args
type Vec<T> = heapless::Vec::<T, MaxLocalizedArg>; ///
//////NOTE: instead of a closure, at some point we can use something like a lens for this.
//////TODO: this is an Arc so that it can be clone, which is a bound on things like `Menu`.
/////// A closure t... | */ //// | random_line_split | |
localization.rs | "en-US".parse().expect("failed to parse default locale");
let current_locale = Application::get_locale()
.parse()
.unwrap_or_else(|_| default_locale.clone());
let locales = get_available_locales(base_dir).unwrap_or_default();
debug!(
"... | {
// TODO
Ok(())
} | identifier_body | |
cardano_wallet.d.ts | {Uint8Array} salt
* @param {Uint8Array} nonce
* @param {Uint8Array} data
* @returns {any}
*/
export function password_encrypt(password: string, salt: Uint8Array, nonce: Uint8Array, data: Uint8Array): any;
/**
* decrypt the data with the password
*
* @param {string} password
* @param {Uint8Array} encrypted_data
*... | {
free(): void;
static from_hex(hex: string): PublicRedeemKey;
to_hex(): string;
verify(data: Uint8Array, signature: RedeemSignature): boolean;
address(settings: BlockchainSettings): Address;
}
/**
*/
export class RedeemSignature {
free(): void;
static from_hex(hex: string): RedeemSignature;
to_hex(): ... | PublicRedeemKey | identifier_name |
cardano_wallet.d.ts | {Uint8Array} salt
* @param {Uint8Array} nonce
* @param {Uint8Array} data
* @returns {any}
*/
export function password_encrypt(password: string, salt: Uint8Array, nonce: Uint8Array, data: Uint8Array): any;
/**
* decrypt the data with the password
*
* @param {string} password
* @param {Uint8Array} encrypted_data
*... | export class Entropy {
free(): void;
static from_english_mnemonics(mnemonics: string): Entropy;
to_english_mnemonics(): string;
to_array(): any;
}
/**
*/
export class InputSelectionBuilder {
free(): void;
static first_match_first(): InputSelectionBuilder;
static largest_first(): InputSelectionBuilder;
s... | */ | random_line_split |
Upload.js | 500);
}
async readFile(inputFile) {
let readTheData = (ifile, method)=>{
return new Promise((res, rej)=>{
let reader = new FileReader();
reader.onload = (e)=>{
res(e.target.result);
}
reader.onerror = (e)=>{
rej(e);
}
reader.onabort = ()=>{
rej();
}
reader[method](... |
}
this.$('#uploadPreviewAlbum').style.height = this._layouter._height+'px';
this.initScrollBarOn(this.$('.uploadPreview'));
}
swapItems(id1, id2) {
if (id1 == id2) {
return;
}
id1 = id1.split('uploadPreviewItem_').join('');
id2 = id2.split('uploadPreviewItem_').join('');
let toMove1 = null;
... | {
el.style.left = '' + file.pos.left + 'px';
el.style.top = '' + file.pos.top + 'px';
el.style.width = '' + file.pos.width + 'px';
el.style.height = '' + file.pos.height + 'px';
} | conditional_block |
Upload.js | 500);
}
async readFile(inputFile) {
let readTheData = (ifile, method)=>{
return new Promise((res, rej)=>{
let reader = new FileReader();
reader.onload = (e)=>{
res(e.target.result);
}
reader.onerror = (e)=>{
rej(e);
}
reader.onabort = ()=>{
rej();
}
reader[method]... | let title = 'Send '+( (this._files.length > 1) ? this._files.length : '' ) + ' ' + suffix[this._files[0].type] + ( (this._files.length > 1) ? 's' : '' );
this.$('.uploadTitle').innerHTML = title;
}
onAlbumClick(e) {
const base = this.$();
let closest = event.target.closest('.upiRemove');
if (closest && bas... | };
| random_line_split |
Upload.js | () {
this.$('#uploadTop').style.display = 'block';
this.$('.popupOverlay').classList.add('active');
this.loaded();
this.initScrollBarOn(this.$('.uploadPreview'));
}
hide() {
this.$('.popupOverlay').classList.remove('active');
this.$('.popupOverlay').classList.add('fading');
setTimeout(()=>{
this.$('... | show | identifier_name | |
image_utils.py | n_channels == 1:
curr_image = np.reshape(curr_image, [height, width])
s = io.BytesIO()
matplotlib_pyplot().imsave(s, curr_image, format="png")
img_sum = tf.Summary.Image(encoded_image_string=s.getvalue(),
height=height, width=width,
colorspace=n_chann... |
class Image2TextProblem(ImageProblem):
"""Base class for image-to-text problems."""
@property
def is_character_level(self):
raise NotImplementedError()
@property
def vocab_problem(self):
raise NotImplementedError() # Not needed if self.is_character_level.
@property
def target_space_id | yield {
"image/encoded": [enc_image],
"image/format": ["png"],
"image/class/label": [int(label)],
"image/height": [height],
"image/width": [width]
} | conditional_block |
image_utils.py | n_channels == 1:
curr_image = np.reshape(curr_image, [height, width])
s = io.BytesIO()
matplotlib_pyplot().imsave(s, curr_image, format="png")
img_sum = tf.Summary.Image(encoded_image_string=s.getvalue(),
height=height, width=width,
colorspace=n_chann... | target_space_id | identifier_name | |
image_utils.py | n_channels == 1:
curr_image = np.reshape(curr_image, [height, width])
s = io.BytesIO()
matplotlib_pyplot().imsave(s, curr_image, format="png")
img_sum = tf.Summary.Image(encoded_image_string=s.getvalue(),
height=height, width=width,
colorspace=n_chann... | assumes VALID padding, so the original image's height must be divisible
by each resolution's height to return the exact resolution size.
num_channels: Number of channels in image.
Returns:
List of Tensors, one for each resolution with shape given by
[resolutions[i], resolutions[i], num_channe... | image: Tensor of shape [height, height, num_channels].
resolutions: List of heights that image's height is resized to. The function | random_line_split |
image_utils.py | n_channels == 1:
curr_image = np.reshape(curr_image, [height, width])
s = io.BytesIO()
matplotlib_pyplot().imsave(s, curr_image, format="png")
img_sum = tf.Summary.Image(encoded_image_string=s.getvalue(),
height=height, width=width,
colorspace=n_chann... |
def image_generator(images, labels):
"""Generator for images that takes image and labels lists and creates pngs.
Args:
images: list of images given as [width x height x channels] numpy arrays.
labels: list of ints, same length as images.
Yields:
A dictionary representing the images with the follo... | """Yield images encoded as pngs."""
if tf.executing_eagerly():
for image in images:
yield tf.image.encode_png(image).numpy()
else:
(height, width, channels) = images[0].shape
with tf.Graph().as_default():
image_t = tf.placeholder(dtype=tf.uint8, shape=(height, width, channels))
encoded... | identifier_body |
congestion.go | ) {
}
func (cc *CongestionControllerDummy) onAckReceived(acks ackRanges, delay time.Duration) {
}
func (cc *CongestionControllerDummy) bytesAllowedToSend() int {
/* return the the maximum int value */
return int(^uint(0) >> 1)
}
func (cc *CongestionControllerDummy) setLostPacketHandler(handler func(pn uint64)) {
}... | } else {
rttDelta := cc.smoothedRtt - latestRtt
if rttDelta < 0 {
rttDelta = -rttDelta
}
cc.rttVar = time.Duration(int64(cc.rttVar)*3/4 + int64(rttDelta)*1/4)
cc.smoothedRtt = time.Duration(int64(cc.smoothedRtt)*7/8 + int64(latestRtt)*1/8)
}
cc.conn.log(logTypeCongestion, "New RTT estimate: %v, variance... | random_line_split | |
congestion.go | {
}
func (cc *CongestionControllerDummy) onAckReceived(acks ackRanges, delay time.Duration) {
}
func (cc *CongestionControllerDummy) bytesAllowedToSend() int {
/* return the the maximum int value */
return int(^uint(0) >> 1)
}
func (cc *CongestionControllerDummy) setLostPacketHandler(handler func(pn uint64)) {
}
... |
/*
* draft-ietf-quic-recovery congestion controller
*/
type CongestionControllerIetf struct {
// Congestion control related
bytesInFlight int
congestionWindow int
endOfRecovery uint64
sstresh int
// Loss detection related
lossDetectionAlarm int //TODO(ekr@rtfm.com) set this to the right ty... | {
return kMinRTOTimeout
} | identifier_body |
congestion.go | ) {
}
func (cc *CongestionControllerDummy) onAckReceived(acks ackRanges, delay time.Duration) {
}
func (cc *CongestionControllerDummy) bytesAllowedToSend() int {
/* return the the maximum int value */
return int(^uint(0) >> 1)
}
func (cc *CongestionControllerDummy) setLostPacketHandler(handler func(pn uint64)) {
}... | () {
//TODO(ekr@rtfm.com)
}
func (cc *CongestionControllerIetf) detectLostPackets() {
var lostPackets []packetEntry
//TODO(ekr@rtfm.com) implement loss detection different from reorderingThreshold
for _, packet := range cc.sentPackets {
if (cc.largestAckedPacket > packet.pn) &&
(cc.largestAckedPacket-packet.p... | onLossDetectionAlarm | identifier_name |
congestion.go | ) {
}
func (cc *CongestionControllerDummy) onAckReceived(acks ackRanges, delay time.Duration) {
}
func (cc *CongestionControllerDummy) bytesAllowedToSend() int {
/* return the the maximum int value */
return int(^uint(0) >> 1)
}
func (cc *CongestionControllerDummy) setLostPacketHandler(handler func(pn uint64)) {
}... | else {
rttDelta := cc.smoothedRtt - latestRtt
if rttDelta < 0 {
rttDelta = -rttDelta
}
cc.rttVar = time.Duration(int64(cc.rttVar)*3/4 + int64(rttDelta)*1/4)
cc.smoothedRtt = time.Duration(int64(cc.smoothedRtt)*7/8 + int64(latestRtt)*1/8)
}
cc.conn.log(logTypeCongestion, "New RTT estimate: %v, variance: ... | {
cc.smoothedRtt = latestRtt
cc.rttVar = time.Duration(int64(latestRtt) / 2)
} | conditional_block |
Leanote4MD.py | ['Ok']:
return True
else:
print json_object['Msg']
return False
else:
return True
def req_get(url, param = '', type = 'json', token = True):
if token:
if param:
param.update({'token': leanote_token})
else:
param={'toke... | def getNoteDetail(noteId):
param = {
'noteId': noteId,
}
return req_get('note/getNoteAndContent', param)
def getImage(fileId):
param = {
'fileId': fileId,
}
return req_get('file/getImage', param, type = 'image')
def addNotebook(title='Import', parentId='', seq=-1):
param ... | return req_get('note/getNotes', param)
#ret type.NoteContent | random_line_split |
Leanote4MD.py | Ok']:
return True
else:
print json_object['Msg']
return False
else:
return True
def req_get(url, param = '', type = 'json', token = True):
if token:
if param:
param.update({'token': leanote_token})
else:
param={'token'... |
if not meta_flag:
file_content = file_meta
file_meta = ''
if meta_flag:
meta = yaml.load(file_meta)
else:
meta = {}
return file_content, meta
def saveToFile(notes, noteBooks, path = '.'):
unique_noteTitle = set()
for note in not... | if meta_flag:
file_content += line
else:
if line.find('---')>-1:
meta_flag = True
else:
file_meta += line
#print meta | conditional_block |
Leanote4MD.py | Ok']:
return True
else:
print json_object['Msg']
return False
else:
return True
def req_get(url, param = '', type = 'json', token = True):
if token:
if param:
param.update({'token': leanote_token})
else:
param={'token'... |
def addNote(NotebookId, Title, Content, Tags=[], IsMarkdown = True, Abstract= '', Files=[]):
param = {
'NotebookId': NotebookId,
'Title': Title,
'Content': Content,
'Tags[]': Tags,
'IsMarkdown': IsMarkdown,
'Abstract': Abstract,
#'Files' : seq
}
ret... | param = {
'title': title,
'parentNotebookId': parentId,
'seq' : seq
}
return req_post('notebook/addNotebook', param) | identifier_body |
Leanote4MD.py | Ok']:
return True
else:
print json_object['Msg']
return False
else:
return True
def req_get(url, param = '', type = 'json', token = True):
if token:
if param:
param.update({'token': leanote_token})
else:
param={'token'... | (fileId):
param = {
'fileId': fileId,
}
return req_get('file/getImage', param, type = 'image')
def addNotebook(title='Import', parentId='', seq=-1):
param = {
'title': title,
'parentNotebookId': parentId,
'seq' : seq
}
return req_post('notebook/addNotebook', par... | getImage | identifier_name |
AddDoctorForm.js | const doctorImageRef = useRef()
if(!!props.uploadRet){
if(!!props.uploadRet.success){
console.log(props.uploadRet,"props.uploadRet")
props.setImage(props.uploadRet.data)
addToast(props.uploadRet.message, {appearance: 'success', autoDismiss:true})
}else |
props.loadingImageOff()
props.uploadRetClr()
}
if(!!props.addDoctorRet){
if(!!props.addDoctorRet.success){
addToast(props.addDoctorRet.message, {appearance: 'success', autoDismiss:true})
console.log(props.addDoctorRet,"props.addDoctorRet")
props.set_user_info({
...pro... | {
addToast(props.uploadRet.message, {appearance: 'success', autoDismiss:true})
} | conditional_block |
AddDoctorForm.js | const doctorImageRef = useRef()
if(!!props.uploadRet){
if(!!props.uploadRet.success){
console.log(props.uploadRet,"props.uploadRet")
props.setImage(props.uploadRet.data)
addToast(props.uploadRet.message, {appearance: 'success', autoDismiss:true})
}else{
addToast(pr... | <div
onClick = {(e)=>props.handleCloseDay(item,i,e)}
className='circul_rund'>
<label className={item.closed?' | random_line_split | |
io_file_browser_search.py | This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along... |
class FilteredFileSelectOperator(bpy.types.Operator):
bl_idname = "file.filtered_file_select"
bl_label = "Select File"
fname = bpy.props.StringProperty()
fexec = bpy.props.BoolProperty()
def execute(self, context):
context.space_data.params.filename = self.fname
if self.fexec:
... | return fileSearch(self, context) | random_line_split |
io_file_browser_search.py | This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along... | (bpy.types.Operator):
bl_idname = "file.filtered_file_select"
bl_label = "Select File"
fname = bpy.props.StringProperty()
fexec = bpy.props.BoolProperty()
def execute(self, context):
context.space_data.params.filename = self.fname
if self.fexec:
bpy.ops.file.execute('IN... | FilteredFileSelectOperator | identifier_name |
io_file_browser_search.py | "api": 35622,
"location": "File Browser",
"description": "Allows You to find files in File Browser by name.",
"warning": "",
"wiki_url": "http://wiki.blender.org/index.php/User:Sftd/Extensions:2.6/Py/Scripts/Import-Export/File_Browser_Search",
"tracker_url": "http://projects.blender.org/tracker/... | bpy.utils.register_module(__name__)
bpy.types.WindowManager.filtered_search_prop = bpy.props.StringProperty(update=filteredSearchFunc)
bpy.types.WindowManager.last_directory_prop = bpy.props.StringProperty()
bpy.types.Scene.file_autoexecute = bpy.props.BoolProperty(name="Open Automatically", default=True)
... | identifier_body | |
io_file_browser_search.py | This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along... |
if(cf >= maxf):
break
else:
filesList = os.listdir(directory)
for filename in filesList:
if prog.match(filename.lower()) != None:
p = context.window_manager.filtered_files_prop.add()
p.name = filename
if contex... | break | conditional_block |
node_dir_ops.go | err = nametransform.WriteDirIVAt(dirfd2)
syscall.Close(dirfd2)
}
if err != nil {
// Delete inconsistent directory (missing gocryptfs.diriv!)
err2 := syscallcompat.Unlinkat(dirfd, cName, unix.AT_REMOVEDIR)
if err2 != nil {
tlog.Warn.Printf("mkdirWithIv: rollback failed: %v", err2)
}
}
return err
}
// ... |
defer syscall.Close(parentDirFd)
if rn.args.PlaintextNames {
// Unlinkat with AT_REMOVEDIR is equivalent to Rmdir
err := unix.Unlinkat(parentDirFd, cName, unix.AT_REMOVEDIR)
return fs.ToErrno(err)
}
if rn.args.DeterministicNames {
if err := unix.Unlinkat(parentDirFd, cName, unix.AT_REMOVEDIR); err != nil {... | {
return errno
} | conditional_block |
node_dir_ops.go | err = nametransform.WriteDirIVAt(dirfd2)
syscall.Close(dirfd2)
}
if err != nil {
// Delete inconsistent directory (missing gocryptfs.diriv!)
err2 := syscallcompat.Unlinkat(dirfd, cName, unix.AT_REMOVEDIR)
if err2 != nil {
tlog.Warn.Printf("mkdirWithIv: rollback failed: %v", err2)
}
}
return err
}
//... | }
// Unless we are running as root, we need read, write and execute permissions
// to handle gocryptfs.diriv.
permWorkaround := false
var origMode uint32
if !rn.args.PreserveOwner {
var st unix.Stat_t
err := syscallcompat.Fstatat(parentDirFd, cName, &st, unix.AT_SYMLINK_NOFOLLOW)
if err != nil {
return f... | {
rn := n.rootNode()
parentDirFd, cName, errno := n.prepareAtSyscall(name)
if errno != 0 {
return errno
}
defer syscall.Close(parentDirFd)
if rn.args.PlaintextNames {
// Unlinkat with AT_REMOVEDIR is equivalent to Rmdir
err := unix.Unlinkat(parentDirFd, cName, unix.AT_REMOVEDIR)
return fs.ToErrno(err)
}
... | identifier_body |
node_dir_ops.go | (dirfd int, cName string, mode uint32, context *fuse.Context) error {
rn := n.rootNode()
if rn.args.DeterministicNames {
return syscallcompat.MkdiratUser(dirfd, cName, mode, context)
}
// Between the creation of the directory and the creation of gocryptfs.diriv
// the directory is inconsistent. Take the lock t... | mkdirWithIv | identifier_name | |
node_dir_ops.go | err = nametransform.WriteDirIVAt(dirfd2)
syscall.Close(dirfd2)
}
if err != nil { | // Delete inconsistent directory (missing gocryptfs.diriv!)
err2 := syscallcompat.Unlinkat(dirfd, cName, unix.AT_REMOVEDIR)
if err2 != nil {
tlog.Warn.Printf("mkdirWithIv: rollback failed: %v", err2)
}
}
return err
}
// Mkdir - FUSE call. Create a directory at "newPath" with permissions "mode".
//
// Syml... | random_line_split | |
engine.py | * self.margin):
# we use the same coef as the noise coef
#cell.diffusive_mass += val * self.environment.sigma
def log_status(self):
if self.datalog == None:
return
row = []
#row.append(self.iteration)
dm = [cell.diffusive_mass for cel... | if self.attached:
return next_dm
self.age += 1
for cell in self.neighbors: | random_line_split | |
engine.py | .cells[idx] = cell
self.reality_check()
center_pt = self._cell_index((self.size / 2, self.size / 2))
self.cells[center_pt].attach(1)
# fun experiments
#self.cells[center_pt+4].attach(1)
#self.cells[center_pt-4].attach(1)
def _xy_ok(self, xy):
(x, y) = xy
... | self.__neighbors = self.lattice.get_neighbors(self.xy) | conditional_block | |
engine.py |
def step(self, x):
if self.curves == None:
return
for key in self.curves:
self[key] = self.curves[key][x]
@classmethod
def build_env(self, name, steps, min_gamma=0.45, max_gamma=0.85):
curves = {
"beta": (1.3, 2),
"theta": (0.01, 0.0... | if type(state) == dict:
self.update(state)
self.curves = None
self.set_factory_settings()
else:
self.curves = state[0]
self.factory_settings = state[1]
self.update(state[2]) | identifier_body | |
engine.py | cell for cell in self.cells if cell and cell.boundary])
row.append(bcnt)
d = self.snowflake_radius()
row.append(d)
row.append(self.environment.beta)
row.append(self.environment.theta)
row.append(self.environment.alpha)
row.append(self.environment.kappa)
ro... | attachment_step | identifier_name | |
rcparser.py |
class DialogDef:
name = ""
id = 0
style = 0
styleEx = None
caption = ""
font = "MS Sans Serif"
fontSize = 8
x = 0
y = 0
w = 0
h = 0
template = None
def __init__(self, n, i):
self.name = n
self.id = i
self.styles = []
self.stylesEx = []... | (self):
self.token = self.lex.get_token()
self.debug("getToken returns:", self.token)
if self.token=="":
self.token = None
return self.token
def getCommaToken(self):
tok = self.getToken()
assert tok == ",", "Token '%s' should be a comma!" % tok
def loa... | getToken | identifier_name |
rcparser.py |
class DialogDef:
name = ""
id = 0
style = 0
styleEx = None
caption = ""
font = "MS Sans Serif"
fontSize = 8
x = 0
y = 0
w = 0
h = 0
template = None
def __init__(self, n, i):
self.name = n
self.id = i
self.styles = []
self.stylesEx = []... |
self.dialogs[name] = dlg.createDialogTemplate()
def dialogStyle(self, dlg):
dlg.style, dlg.styles = self.styles( [], win32con.WS_VISIBLE | win32con.DS_SETFONT)
def dialogExStyle(self, dlg):
self.getToken()
dlg.styleEx, dlg.stylesEx = self.styles( [], 0)
def styles(self, defa... | if self.token=="STYLE":
self.dialogStyle(dlg)
elif self.token=="EXSTYLE":
self.dialogExStyle(dlg)
elif self.token=="CAPTION":
self.dialogCaption(dlg)
elif self.token=="FONT":
self.dialogFont(dlg)
elif self.to... | conditional_block |
rcparser.py |
class DialogDef:
name = ""
id = 0
style = 0
styleEx = None
caption = ""
font = "MS Sans Serif"
fontSize = 8
x = 0
y = 0
w = 0
h = 0
template = None
def __init__(self, n, i):
self.name = n
self.id = i
self.styles = []
self.stylesEx = []... |
def dialogFont | if "CAPTION"==self.token:
self.getToken()
self.token = self.token[1:-1]
self.debug("Caption is:",self.token)
if self.gettexted:
dlg.caption = gt_str(self.token)
else:
dlg.caption = self.token
self.getToken() | identifier_body |
rcparser.py | _VISIBLE
class DialogDef:
name = ""
id = 0
style = 0
styleEx = None
caption = ""
font = "MS Sans Serif"
fontSize = 8
x = 0
y = 0
w = 0
h = 0
template = None
def __init__(self, n, i):
self.name = n
self.id = i
self.styles = []
self.style... | label = ""
x = 0
y = 0
w = 0
h = 0
def __init__(self):
self.styles = []
def toString(self):
s = "<Control id:"+self.id+" controlType:"+self.controlType+" subType:"+self.subType\
+" idNum:"+str(self.idNum)+" style:"+str(self.style)+" styles:"+str(self.styles)+" lab... | idNum = 0
style = defaultControlStyle | random_line_split |
ann_interface.py | ]
if i < d_col: #data(speak)の可視化
# 音声Dataがrmsの場合
# set_data:範囲は 0-1
set_data = data[j][i] #self.speakDecibelNorm(data[j][i])
#ON/OFF むちゃくちゃすぎる
#set_data = 1 if set_... | +str(fps)+")")
plt.title("speaker/listener result")
plt.xl | conditional_block | |
ann_interface.py | .txtSepFile.setText('')
# reset
def resetAnno(self):
print "reset Data before:",self.edited_joints.shape, self.edited_annos.shape
self.edited_joints = copy.deepcopy(self.input_joints)
self.edited_speaks = copy.deepcopy(self.input_speaks)
#datalen = self.edited_speaks.shape[1]
... | random_line_split | ||
ann_interface.py | .2)
plt.legend()
plt.show()
"""
print "joints shape:", self.input_joints.shape
print "speaks shape:", self.input_speaks.shape
print "annos shape:", self.input_annos.shape
print "flags shape:", self.input_flags.shape
print "times shape:", self... | ange(2):
#print person[0, ls[l+add]], ls[l+add], l, add
linepoint=self.set_point([data[0,ls[l+add]*3],
data[0,ls[l+add]*3+1],
data[0,ls[l+add]*3+2]],
... | identifier_body | |
ann_interface.py | else:
print "create flags"
self.input_flags = np.zeros((datalen, 1))
if input_data.has_key("times"):
print "load times"
self.input_times = input_data["times"]
else:
print "create times"
self.input_times = np.zeros((datalen,... | identifier_name | ||
index.js | = [];
function next(index) {
if (index < array.length) | else {
resolve(results);
}
}
next(0);
});
}
function findPromise(array, callback, thisArg) {
return new Promise((resolve, reject) => {
function next(index) {
if (index < array.length) {
callback.call(thisArg, array[index], index,... | {
callback.call(thisArg, array[index], index, array).then(result => {
results[index] = result;
next(index + 1);
}).catch(error => {
reject(error);
});
} | conditional_block |
index.js | {Array<String | Array<String>>} paths The property paths to search for.
* @param {*} [defaultValue] The value returned if all paths resolve to undefined values
* @returns {*}
*/
function getFirst(object, paths, defaultValue) {
let result = _(object).at(paths).reject(_.isUndefined).first();
return _.isUndefi... | random_line_split | ||
index.js | , thisArg) {
return new Promise((resolve, reject) => {
function next(index) {
if (index < array.length) {
callback.call(thisArg, array[index], index, array).then(result => {
if (result) {
resolve(array[index]);
} els... | {
string = string.replace('\r\n', '\n');
let frontmatter = null;
let markdown = string;
let frontMatterTypes = [
{
type: 'yaml',
startDelimiter: '---\n',
endDelimiter: '\n---',
parse: (string) => yaml.safeLoad(string, {schema: yaml.JSON_SCHEMA})
... | identifier_body | |
index.js | (array, callback, thisArg) {
return new Promise((resolve, reject) => {
function next(index) {
if (index < array.length) {
callback.call(thisArg, array[index], index, array).then(() => {
next(index + 1);
}).catch(error => {
r... | forEachPromise | identifier_name | |
server.go | server.log[i] = NewConsensusState(len(server.BGsInfo), -1, server)
}
i1, err := strconv.Atoi(server.RPCPort)
common.AssertNil(err, "RPC port cannot be recognized.", logger)
tcpPort := common.CalcTCPPortFromRPCPort(i1)
server.tcpManager = NewTCPManager(strconv.Itoa(tcpPort))
server.tcpManager.SetServer(server)... | }
for i := 0; i < common.MaxCycleNumberInStorage; i++ {
// Fill it with -1 | random_line_split | |
server.go | raft_peers"].([]interface{}) {
server.raftPeers = append(server.raftPeers, s.(string))
}
for _, s := range c["rpc_peers"].([]interface{}) {
server.rpcPeers = append(server.rpcPeers, s.(string))
}
server.resultReceiver = NewBftResultReceiver(server.SBFTReplicaAddressForBFTResult)
server.resultVerifier = NewBft... | (err error) (*grpcpool.Pool, bool) {
errCode := grpc.Code(err)
if errCode == common.NotLeaderErrorCode {
leaderId := grpc.ErrorDesc(err)
s.BGsInfo[s.BGID].UpdateLeader(leaderId)
conn := s.BGsInfo[s.BGID].GetConnection(leaderId).GetConnectionPool()
return conn, true
}
logger.Warningf("Unhandled ERROR: %v", ... | handleRPCError | identifier_name |
server.go | raft_peers"].([]interface{}) {
server.raftPeers = append(server.raftPeers, s.(string))
}
for _, s := range c["rpc_peers"].([]interface{}) {
server.rpcPeers = append(server.rpcPeers, s.(string))
}
server.resultReceiver = NewBftResultReceiver(server.SBFTReplicaAddressForBFTResult)
server.resultVerifier = NewBft... |
func (s *Server) IsBGLeader() bool {
if s.currentBGLeaderSuperLeadId != s.SuperLeafID {
return false
}
return s.IsLeader()
}
func (s *Server) saveLeaderAddress() {
fName := fmt.Sprintf("./leader_%v.log", s.ID)
f, err := os.Create(fName)
if err != nil {
logger.Fatalf("create leader log file error %v", err)... | {
// when the raft leader call getLeaderID, it will return 0
// it only shows in the first time
return int(s.getLeaderID()) == s.RaftID || int(s.getLeaderID()) == 0
} | identifier_body |
server.go | raft_peers"].([]interface{}) {
server.raftPeers = append(server.raftPeers, s.(string))
}
for _, s := range c["rpc_peers"].([]interface{}) {
server.rpcPeers = append(server.rpcPeers, s.(string))
}
server.resultReceiver = NewBftResultReceiver(server.SBFTReplicaAddressForBFTResult)
server.resultVerifier = NewBft... |
leader := s.rpcPeers[id-1]
go s.BGsInfo[s.BGID].UpdateLeader(leader)
logger.Debugf("server %v get leader %v, raft id %v", s.addr, leader, id)
return leader
}
func (s *Server) IsLeader() bool {
// when the raft leader call getLeaderID, it will return 0
// it only shows in the first time
return int(s.getLeaderID... | {
return ""
} | conditional_block |
doom.py | 00
max_steps = 100
batch_size = 64
explore_start = 1.0
explore_stop = .01
decay_rate = 0.0001
gamma = 0.95
pretrain_length = batch_size
memory_size = 1000000
render = True
DQNetwork = None
stack_size = 4
saver = tf.train.Saver()
ap = argparse.ArgumentParser()
ap.add_argument("-m", "--model", required=False, type=bool,... |
if not args['model']:
stacked_frames = deque([np.zeros((84, 84), dtype=np.int) for i in range(stack_size)], maxlen=4)
game, possible_actions = create_environment()
print("Game Environment created")
createnetwork()
print("network created")
memory = mem.Memory(max_size=memory_size)
game.ne... | global game
episodes = 10
for i in range(episodes):
game.new_episode()
while not game.is_episode_finished():
state = game.get_state()
img = state.screen_buffer
misc = state.game_variables
action = random.choice(possible_actions)
print("... | identifier_body |
doom.py | 500
max_steps = 100
batch_size = 64
explore_start = 1.0
explore_stop = .01
decay_rate = 0.0001
gamma = 0.95
pretrain_length = batch_size
memory_size = 1000000
render = True
DQNetwork = None
stack_size = 4
saver = tf.train.Saver()
ap = argparse.ArgumentParser()
ap.add_argument("-m", "--model", required=False, type=bool... |
next_state, stacked_frames = stack_frames(stacked_frames, next_state, False)
state = next_state
env.close()
def predict_action(decay_step, possible_actions, state, sess):
global explore_start
global explore_stop
global decay_rate
exp_exp_tradeoff = np.random.rand()
... | print("Score", total_rewards)
total_test_rewards.append(total_rewards)
break | conditional_block |
doom.py | 00
max_steps = 100
batch_size = 64
explore_start = 1.0
explore_stop = .01
decay_rate = 0.0001
gamma = 0.95
pretrain_length = batch_size
memory_size = 1000000
render = True
DQNetwork = None
stack_size = 4
saver = tf.train.Saver()
ap = argparse.ArgumentParser()
ap.add_argument("-m", "--model", required=False, type=bool,... | (memory):
global stacked_frames
global saver
sess = tf.Session()
sess.run(tf.global_variables_initializer())
decay_step = 0
game.init()
for episode in range(total_episodes):
print("Training on episode: {}".format(episode))
step = 0
episode_rewards = []
game.n... | train | identifier_name |
doom.py | 500
max_steps = 100
batch_size = 64
explore_start = 1.0
explore_stop = .01
decay_rate = 0.0001
gamma = 0.95
pretrain_length = batch_size
memory_size = 1000000
render = True
DQNetwork = None
stack_size = 4
saver = tf.train.Saver()
ap = argparse.ArgumentParser()
ap.add_argument("-m", "--model", required=False, type=bool... | loss, _ = sess.run([DQNetwork.loss, DQNetwork.optimizer],
feed_dict={DQNetwork.inputs_: states_mb,
DQNetwork.target_Q: targets_mb,
DQNetwork.actions_: actions_mb})
# Write TF Summa... | random_line_split | |
dataset3.js | 418531', y: '3.17806176', label: 'C1' },
{ x: '4.28296762', y: '9.39110461', label: 'C2' },
{ x: '0.54567095', y: '1.74704601', label: 'C2' },
{ x: '6.47297586', y: '80.0737218', label: 'C2' },
{ x: '3.56196783', y: '3.46501229', label: 'C1' },
{ x: '4.92110965', y: '3.21782503', label: 'C1' },
{ x: '7.0896... | { x: '4.06277657', y: '3.30054593', label: 'C1' },
{ x: '10.1004059', y: '73.8328052', label: 'C2' },
{ x: '11.9150365', y: '3.37543243', label: 'C1' },
{ x: '2.67113254', y: '5.12725717', label: 'C2' },
{ x: '9.21185949', y: '14.5993617', label: 'C2' },
{ x: '2.59559923', y: '5.1530681', label: 'C2' },
{... | { x: '0.51454207', y: '2.55030179', label: 'C1' },
{ x: '0.1780755', y: '1.52949356', label: 'C2' },
{ x: '0.76631977', y: '2.5589982', label: 'C1' },
{ x: '14.2249825', y: '19.6862421', label: 'C2' }, | random_line_split |
covid19co_pipe.py | -Social/Casos-positivos-de-COVID-19-en-Colombia/gt2j-8ykr)
#
# The number of new cases are increasing day by day around the world.
# This dataset has information about reported cases from 32 Colombia departments.
#
# Also you can get the dataset Google COVID-19 Community Mobility Reports - Colombia.
#
# You can view... | covid19co[attr] = covid19co[attr].transform(lambda value: str(value).title())
# Show dataframe
covid19co.head()
# %%
# Fill NaN Values
if covid19co.isna().sum().sum() > 0:
covid19co.fillna(value='-', inplace=True)
# Show dataframe
covid19co.head()
# %%
# Setup Date Format
def setup_date(value):
try:... |
# %%
# Update texto to title text format
for attr in covid19co.columns:
if covid19co[attr].dtypes == 'object': | random_line_split |
covid19co_pipe.py | and collaborate to the analysis here:
# [colombia_covid_19_analysis](https://www.kaggle.com/sebaxtian/colombia-covid-19-analysis) Kaggle Notebook Kernel.
# %% [markdown]
# ---
# %% [markdown]
# ## Data Sources
# %%
# Input data files are available in the "../input/" directory.
INPUT_DIR = './'
if os.path.split(os.pat... | t_mobility_changes(U | identifier_name | |
covid19co_pipe.py | ocial/Casos-positivos-de-COVID-19-en-Colombia/gt2j-8ykr)
#
# The number of new cases are increasing day by day around the world.
# This dataset has information about reported cases from 32 Colombia departments.
#
# Also you can get the dataset Google COVID-19 Community Mobility Reports - Colombia.
#
# You can view a... | Get URL report | th requests.get('https://www.gstatic.com/covid19/mobility/' + file) as community_mobility_report:
if community_mobility_report.status_code == 200:
return community_mobility_report.url
else:
return np.nan
# | identifier_body |
covid19co_pipe.py | ocial/Casos-positivos-de-COVID-19-en-Colombia/gt2j-8ykr)
#
# The number of new cases are increasing day by day around the world.
# This dataset has information about reported cases from 32 Colombia departments.
#
# Also you can get the dataset Google COVID-19 Community Mobility Reports - Colombia.
#
# You can view a... |
else:
value = '-'
except IndexError:
value = '-'
if len(value) != 10 and len(value) != 1:
value = '-'
return value
# Date Columns
date_columns = list(filter(lambda value: value.find('FECHA') != -1 or value.find('FIS') != -1, covid19co.columns))
# For each date column
for... | value = value[2] + '/' + value[1] + '/' + value[0] | conditional_block |
peermanager.go | .conf.NPAddPeers {
// go-multiaddr implementation does not support recent p2p protocol yet, but deprecated name ipfs.
// This adhoc will be removed when go-multiaddr is patched.
target = strings.Replace(target, "/p2p/", "/ipfs/", 1)
targetAddr, err := ma.NewMultiaddr(target)
if err != nil {
pm.logger.Warn(... | {
return pm.Host.Peerstore()
} | identifier_body | |
peermanager.go | }
func (pm *peerManager) SelfMeta() PeerMeta {
return pm.selfMeta
}
func (pm *peerManager) SelfNodeID() peer.ID {
return pm.selfMeta.ID
}
func (pm *peerManager) RegisterEventListener(listener PeerEventListener) {
pm.mutex.Lock()
defer pm.mutex.Unlock()
pm.eventListeners = append(pm.eventListeners, listener)
}
fu... |
case id := <-pm.removePeerChannel:
if pm.removePeer(id) {
if meta, found := pm.designatedPeers[id]; found {
pm.rm.AddJob(meta)
}
}
case <-addrTicker.C:
pm.checkAndCollectPeerListFromAll()
pm.logPeerMetrics()
case peerMetas := <-pm.fillPoolChannel:
pm.tryFillPool(&peerMetas)
case ... | {
if _, found := pm.designatedPeers[meta.ID]; found {
pm.rm.CancelJob(meta.ID)
}
} | conditional_block |
peermanager.go | {
// add remote node from config
for _, target := range pm.conf.NPAddPeers {
// go-multiaddr implementation does not support recent p2p protocol yet, but deprecated name ipfs.
// This adhoc will be removed when go-multiaddr is patched.
target = strings.Replace(target, "/p2p/", "/ipfs/", 1)
targetAddr, err :=... | Peerstore | identifier_name | |
peermanager.go | , meta.ID.Pretty()).Msg("Failed to handshake")
//pm.sendGoAway(rw, "Failed to handshake")
s.Close()
return false
}
pm.mutex.Lock()
inboundPeer, ok = pm.remotePeers[peerID]
if ok {
if ComparePeerID(pm.selfMeta.ID, meta.ID) <= 0 {
pm.logger.Info().Str(LogPeerID, inboundPeer.meta.ID.Pretty()).Msg("Inbound ... | if pm.hasEnoughPeers() {
return | random_line_split | |
Config.ts | I don't know his lives . // I don't know where he~his lives .
He get to cleaned his son . // He got his~his son~son to:O clean:O the~ room~ .
We wrote down the number . // We wrote the number down~down .
`
.trim()
.split(/\n\n+/gm)
.map(line => ex.apply({}, line.split('//').map(side => side.trim()) as [string, ... |
Their was a problem yesteray . // There was a problem yesterday .
| random_line_split | |
Config.ts | , mountain, etc'},
{label: 'place', desc: ''},
{label: 'region', desc: ''},
{label: 'street_nr', desc: 'street number'},
{label: 'zip_code', desc: ''},
],
},
{
group: 'Institutions',
entries: [
{label: 'school', desc: ''},
{label: 'work', desc: ''},
{label: 'oth... | xonomy_has_label(t | identifier_name | |
Config.ts | desc: string
}[]
}
export type Taxonomy = TaxonomyGroup[]
const extra = 'gen def pl foreign'.split(' ')
const temporary = 'OBS! Cit-FL Com!'.split(' ')
const digits = /^\d+$/
/** An ordered set of label categories. */
export enum LabelOrder {
BASE,
NUM,
EXTRA,
TEMP,
}
/** Maps a label to a category in La... | return 'https://spraakbanken.github.io/swell-project/' + title
}
| identifier_body | |
filesystem.rs | = args[0];
let distributed_filename = args[1];
// Figure out who I am giving this file to
let dest_ids = gen_file_owners(&distributed_filename)?;
// Gossip who has the file now
sender.send(
SendableOperation::for_successors(Box::new(NewFileOwnersOperation {
distributed_filename:... | (filename: &String) -> String {
format!("{}/{}", constants::DATA_DIR, filename)
}
// Returns messages to be gossiped
pub fn handle_failed_node(failed_id: &String) -> BoxedErrorResult<Vec<SendableOperation>> {
match heartbeat::is_master() {
true => {
let mut generated_operations: Vec<Sendabl... | distributed_file_path | identifier_name |
filesystem.rs | = args[0];
let distributed_filename = args[1];
// Figure out who I am giving this file to
let dest_ids = gen_file_owners(&distributed_filename)?;
// Gossip who has the file now
sender.send(
SendableOperation::for_successors(Box::new(NewFileOwnersOperation {
distributed_filename:... |
}
Err(format!("No new owners available for file {}", filename).into())
},
None => Err(format!("No owner found for file {}", filename).into())
}
}
fn distributed_file_path(filename: &String) -> String {
format!("{}/{}", constants::DATA_DIR, filename)
}
// Returns messag... | {
return Ok(potential_owner.clone());
} | conditional_block |
filesystem.rs | = args[0];
let distributed_filename = args[1];
// Figure out who I am giving this file to
let dest_ids = gen_file_owners(&distributed_filename)?;
// Gossip who has the file now
sender.send(
SendableOperation::for_successors(Box::new(NewFileOwnersOperation {
distributed_filename:... |
// TODO: This function makes the entire system assume there are always at least two nodes in the system
// and the file must have an owner or else the operation will not work correctly. This is fine for now
// but it is worth improving sooner rather than later (make distinct Error types to differentiate, e... | random_line_split | |
filesystem.rs | = args[0];
let distributed_filename = args[1];
// Figure out who I am giving this file to
let dest_ids = gen_file_owners(&distributed_filename)?;
// Gossip who has the file now
sender.send(
SendableOperation::for_successors(Box::new(NewFileOwnersOperation {
distributed_filename:... |
async fn handle_connection(mut connection: async_std::net::TcpStream) -> BoxedErrorResult<()> {
let (operation, source) = connection.try_read_operation().await?;
// TODO: Think about what standard we want with these
let _generated_operations = operation.execute(source)?;
Ok(())
}
// Helpers
fn gen_fi... | {
let server = globals::SERVER_SOCKET.read();
let mut incoming = server.incoming();
while let Some(stream) = incoming.next().await {
let connection = stream?;
log(format!("Handling connection from {:?}", connection.peer_addr()));
spawn(handle_connection(connection));
}
Ok(()... | identifier_body |
main.rs | let guid = &item.guid;
items.entry(&guid).or_insert_with(|| Item {
title: item.title.to_owned(),
link: item.link.to_owned(),
content: item.content.to_owned(),
pub_date: item.pub_date.to_owned(),
guid: guid.to_owned()... | ;
}
}
struct Downloader;
impl Actor for Downloader {
type Context = actix::Context<Self>;
}
impl Handler<DownloadFeed> for Downloader {
type Result = <DownloadFeed as Message>::Result;
fn handle(&mut self, msg: DownloadFeed, _: &mut Self::Context) -> Self::Result {
let channel = rss::Channel:... | {
feed.merge(msg.feed)
} | conditional_block |
main.rs | Entry::Occupied(_) => Err("Feed already exists".into()),
std::collections::hash_map::Entry::Vacant(e) => {
debug!("will download {}", &msg.url);
self.downloader.send(DownloadFeed(msg.url))
.wait()
.or_err("Failed to download")?
... | server.listen(l)?
} else {
server.bind("[::1]:8000")?
};
println!("Started HTTP server on {:?}", server.addrs_with_scheme().iter().map(|(a, s)| format!("{}://{}/", s, a)).collect::<Vec<_>>()); | random_line_split | |
main.rs | {
pub title: Option<String>,
pub link: Option<String>,
pub content: Option<String>,
pub pub_date: Option<DateTime<Utc>>,
pub guid: String,
pub unread: bool,
}
#[derive(Clone, Debug, Serialize)]
struct Feed {
pub title: String,
pub last_updated: DateTime<Utc>,
pub items: Vec<Item>,
... | Item | identifier_name | |
sssmc39_scheme.rs | cover_secret(&self.member_shares, self.member_threshold)
}
}
/// Split a master secret into mnemonic shares
/// group_threshold: The number of groups required to reconstruct the master secret
/// groups: A list of (member_threshold, member_count) pairs for each group, where member_count
/// is the number of shares to... | );
Ok(dms)
}
/// Decodes all Mnemonics to a list of shares and performs error checking
fn decode_mnemonics(mnemonics: &[Vec<String>]) -> Result<Vec<GroupShare>, Error> {
let mut shares = vec![];
if mnemonics.is_empty() {
return Err(ErrorKind::Mnemonic(
"List of mnemonics is empty.".to_string(),
))?;
}
let... | &ems.share_value,
passphrase,
ems.iteration_exponent,
ems.identifier, | random_line_split |
sssmc39_scheme.rs | % 2 != 0 {
return Err(ErrorKind::Value(
"The length of the master secret in bytes must be an even number".to_string(),
))?;
}
if group_threshold as usize > groups.len() {
return Err(ErrorKind::Value(format!(
"The requested group threshold ({}) must not exceed the number of groups ({}).",
group_thresh... | {
let master_secret = b"\x0c\x94\x90\xbcn\xd6\xbc\xbf\xac>\xbe}\xeeV\xf2P".to_vec();
// single 3 of 5 test, splat out all mnemonics
println!("Single 3 of 5 Encoded: {:?}", master_secret);
let mns = generate_mnemonics(1, &[(3, 5)], &master_secret, "", 0)?;
for s in &mns {
println!("{}", s);
}
let resul... | identifier_body | |
sssmc39_scheme.rs | _secret(&self.member_shares, self.member_threshold)
}
}
/// Split a master secret into mnemonic shares
/// group_threshold: The number of groups required to reconstruct the master secret
/// groups: A list of (member_threshold, member_count) pairs for each group, where member_count
/// is the number of shares to gene... |
let check_len = mnemonics[0].len();
for m in mnemonics {
if m.len() != check_len {
return Err(ErrorKind::Mnemonic(
"Invalid set of mnemonics. All mnemonics must have the same length.".to_string(),
))?;
}
shares.push(Share::from_mnemonic(m)?);
}
let check_share = shares[0].clone();
for s in shares... | {
return Err(ErrorKind::Mnemonic(
"List of mnemonics is empty.".to_string(),
))?;
} | conditional_block |
sssmc39_scheme.rs | _secret(&self.member_shares, self.member_threshold)
}
}
/// Split a master secret into mnemonic shares
/// group_threshold: The number of groups required to reconstruct the master secret
/// groups: A list of (member_threshold, member_count) pairs for each group, where member_count
/// is the number of shares to gene... | (mnemonics: &[Vec<String>]) -> Result<Vec<GroupShare>, Error> {
let mut shares = vec![];
if mnemonics.is_empty() {
return Err(ErrorKind::Mnemonic(
"List of mnemonics is empty.".to_string(),
))?;
}
let check_len = mnemonics[0].len();
for m in mnemonics {
if m.len() != check_len {
return Err(ErrorKind::M... | decode_mnemonics | identifier_name |
project.py | ", type(d["pick_pose"]), "place_pose", type(d["place_pose"])
data_dict = {"object_list": dict_list}
with open(yaml_filename, 'w') as outfile:
yaml.dump(data_dict, outfile, default_flow_style=False)
def statistical_outlier_removal(cloud):
# Much like the previous filters, we start by creating a fi... | cloud (PointCloud_PointXYZRGB): A point cloud
Returns:
PointCloud_PointXYZRGB: A downsampled point cloud
"""
# Create a VoxelGrid filter object for our input point cloud
vox = cloud.make_voxel_grid_filter()
# Choose a voxel (also known as leaf) size
LEAF_SIZE = 0.0... | """ Voxel Grid filter
Args: | random_line_split |
project.py | _pose", type(d["pick_pose"]), "place_pose", type(d["place_pose"])
data_dict = {"object_list": dict_list}
with open(yaml_filename, 'w') as outfile:
yaml.dump(data_dict, outfile, default_flow_style=False)
def statistical_outlier_removal(cloud):
# Much like the previous filters, we start by creating... | seg.set_distance_threshold(max_distance)
# Call the segment function to obtain set of inlier indices and model coefficients
inliers, coefficients = seg.segment()
return inliers, coefficients
def euclidean_clustering(cloud):
white_cloud = XYZRGB_to_XYZ(cloud)
tree = white_cloud.make_kdtree()
... | """ Segments a cloud using a sac model
Args:
cloud (PointCloud_PointXYZRGB): A point cloud
sacmodel (pcl.SACMODEL): A model points will be fit to
Returns:
A set of inliers and coefficients
"""
# Create the segmentation object
seg = cloud.make_segmenter()... | identifier_body |
project.py | _cluster_point_list.append([white_cloud[indice][0],
white_cloud[indice][1],
white_cloud[indice][2],
rgb_to_float(cluster_color[j])])
#Create new cloud containing all clusters, each... | rospy.spin() | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.