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 |
|---|---|---|---|---|
livestream.rs | use std::collections::{HashMap, BTreeMap};
use tokio::sync::mpsc::*;
use std::{thread, fs};
use crate::camera::CameraProvider;
use std::sync::Arc;
use std::cell::RefCell;
use tokio::sync::mpsc::error::TrySendError;
use tokio::sync::mpsc::error::ErrorKind;
use std::io::Write;
use std::sync::mpsc as bchan;
pu... | ()->Self{
LiveStream{
next_client_id: 0,
clients: BTreeMap::new(),
cached_frames: RingBuffer::new(20),
channel: channel(5),
first_frame: None
}
}
pub fn get_sender(&self)->Sender<IncomingMessage>{
self.channel.0.clone(... | new | identifier_name |
livestream.rs | use std::collections::{HashMap, BTreeMap};
use tokio::sync::mpsc::*;
use std::{thread, fs};
use crate::camera::CameraProvider;
use std::sync::Arc;
use std::cell::RefCell;
use tokio::sync::mpsc::error::TrySendError;
use tokio::sync::mpsc::error::ErrorKind;
use std::io::Write;
use std::sync::mpsc as bchan;
pu... | data: v,
size,
start: 0,
end: 0,
offset: 0,
next_index: 0
}
}
pub fn info(&self){
println!("<RingBuffer size={}, start={}, end={}, offset={}, next_index={}>", self.size, self.start, self.end, self.offset, self.next_... | v.push(None);
}
RingBuffer{
| random_line_split |
create_tumor_dataset.py | import argparse
import dicom
import nibabel as nib
import numpy as np
import os
import pickle
from matplotlib import pyplot as plt
"""
The goal of this code is to loop through all the patients and show their PET images
(plots will only appear if line ~247, with function 'plot_pet_volume' is not commented)
and their r... | (pet_image, pixel_shape, pixel_spacing, mask=None, patient="?", mask_name="?"):
"""
The transparent option makes all zeros transparent, and all ones red (expects image with only
1s and 0s)
"""
# create axis for plotting
pixel_shape = pet_image.shape
x = np.arange(0.0, (pixel_shape[1] + 1) * ... | plot_pet_volume | identifier_name |
create_tumor_dataset.py | import argparse
import dicom
import nibabel as nib
import numpy as np
import os
import pickle
from matplotlib import pyplot as plt
"""
The goal of this code is to loop through all the patients and show their PET images
(plots will only appear if line ~247, with function 'plot_pet_volume' is not commented)
and their r... |
plt.ioff()
if args.plot:
all_pixel_spacing = np.array(all_pixel_spacing)
plt.plot(all_pixel_spacing[:, 0], label="width (x)")
plt.plot(all_pixel_spacing[:, 1], label="lenght (y)")
plt.plot(all_pixel_spacing[:, 2], label="height (z)")
plt.legend()
plt.title("Dime... | ignored_patients[patient] = "No valid MTV contour found"
num_ignored_patients += 1
print("Patient", patient, "has no MTV contour. \nThis patient will be ignored!\n")
if patient in volumes:
volumes.pop(patient) | conditional_block |
create_tumor_dataset.py | import argparse
import dicom
import nibabel as nib
import numpy as np
import os
import pickle
from matplotlib import pyplot as plt
"""
The goal of this code is to loop through all the patients and show their PET images
(plots will only appear if line ~247, with function 'plot_pet_volume' is not commented)
and their r... |
def plot_pet_image(pet_image, yz_slice_pos, xz_slice_pos, xy_slice_pos, pixel_shape,
pixel_spacing, mask=None):
"""
The transparent option makes all zeros transparent, and all ones red (expects image with only
1s and 0s)
"""
# create axis for plotting
x = np.arange(0.0, (pi... | """
Plot pet_medians and project mask. median can be 0, 1 or 2
"""
# create axis for plotting
pixel_shape = pet_image.shape
x = np.arange(0.0, (pixel_shape[1] + 1) * pixel_spacing[0], pixel_spacing[0])
y = np.arange(0.0, (pixel_shape[0] + 1) * pixel_spacing[1], pixel_spacing[1])
z = np.arang... | identifier_body |
create_tumor_dataset.py | import argparse
import dicom
import nibabel as nib
import numpy as np
import os
import pickle
from matplotlib import pyplot as plt
"""
The goal of this code is to loop through all the patients and show their PET images
(plots will only appear if line ~247, with function 'plot_pet_volume' is not commented)
and their r... | for y in range(h):
for z in range(d):
centroid[0] += image[x, y, z] * x
centroid[1] += image[x, y, z] * y
centroid[2] += image[x, y, z] * z
cumulative += image[x, y, z]
centroid = centroid[0] / cumulative... | centroid = [0, 0, 0]
for x in range(w): | random_line_split |
variants.ts | //****************************
// sheet processing magic
//****************************
import warning from 'warning';
export * from './animations/index';
export * from './mediaq';
export * from './when-used';
//****************************
// TYPINGS
//****************************
// consts
export const enum Const... | return sheet
}
export const mergeSheetsAndFinish = (sheet: SheetWithAddIns, modifiers: SheetWithAddIns[], onFinishAddInClasses: FinishAddIns, canModify?: boolean) => {
// deep merge
sheet = mergeSheets(sheet, modifiers, canModify)
sheet = finishAddInsClasses(sheet, onFinishAddInClasses, canModify)
nameRuleset... | random_line_split | |
DLModeler.py | from processing.DLDataEngineering import DLDataEngineering
from sklearn.preprocessing import OneHotEncoder
import pandas as pd
import numpy as np
import h5py
import os
from scipy.ndimage import gaussian_filter
#Deep learning packages
import tensorflow as tf
#from tensorflow import keras
from tensorflow.keras... | (self,member,trainX,trainY,validX,validY):
model_file = self.model_path + f'/{member}_{self.model_args}_{self.model_type}.h5'
'''
if os.path.exists(model_file):
del trainX,trainY,validX,validY
unet = tf.keras.models.load_model(model_file,compile=False)
... | train_UNET | identifier_name |
DLModeler.py | from processing.DLDataEngineering import DLDataEngineering
from sklearn.preprocessing import OneHotEncoder
import pandas as pd
import numpy as np
import h5py
import os
from scipy.ndimage import gaussian_filter
#Deep learning packages
import tensorflow as tf
#from tensorflow import keras
from tensorflow.keras... |
def train_CNN(self,member,input_data):
"""
Function to train a convolutional neural net (CNN) for random
training data and associated labels.
Args:
member (str): Ensemble member
trainX (tuple): Tuple of (train data, train labels,
... | model_file = self.model_path + f'/{member}_{self.model_args}_{self.model_type}.h5'
'''
if os.path.exists(model_file):
del trainX,trainY,validX,validY
unet = tf.keras.models.load_model(model_file,compile=False)
print(f'\nOpening {model_file}\n')
#s... | identifier_body |
DLModeler.py | from processing.DLDataEngineering import DLDataEngineering
from sklearn.preprocessing import OneHotEncoder
import pandas as pd
import numpy as np
import h5py
import os
from scipy.ndimage import gaussian_filter
#Deep learning packages
import tensorflow as tf
#from tensorflow import keras
from tensorflow.keras... |
self.predictors = np.array(long_predictors)
#Class to read data and standardize
self.dldataeng = DLDataEngineering(self.model_path,self.hf_path,
self.num_examples,self.class_percentages,self.predictors,
self.model_args)
return
... | if "_" in predictor:
predictor_name = predictor.split('_')[0].upper() + predictor.split('_')[-1]
elif " " in predictor:
predictor_name = ''.join([v[0].upper() for v in predictor.split()])
else: predictor_name = predictor
long_predictors.append(predic... | conditional_block |
DLModeler.py | from processing.DLDataEngineering import DLDataEngineering
from sklearn.preprocessing import OneHotEncoder
import pandas as pd
import numpy as np
import h5py
import os
from scipy.ndimage import gaussian_filter
#Deep learning packages
import tensorflow as tf
#from tensorflow import keras
from tensorflow.keras... | total_count = 0
##################
#Extract forecast data (#hours, #patches, nx, ny, #variables)
##################
forecast_data = self.dldataeng.read_files('forecast',member,date,[None],[None])
if forecast_data is None:
prin... | return
prob_thresh = 0 #pd.read_csv(threshold_file).loc[0,'size_threshold']+0.05
print(prob_thresh) | random_line_split |
nodes.ts | import { CachedTransform, IsNaN, emptyArray, ToJSON, AsObj } from 'js-vextensions';
import { GetData, SplitStringBySlash_Cached, SlicePath, GetDataAsync, CachedTransform_WithStore } from 'Utils/FrameworkOverrides';
import { PathSegmentToNodeID } from 'Store/main/mapViews';
import { GetNodeL2, GetNodeL3 } from './nodes/... | }
export function ForDelete_GetError(userID: string, node: MapNodeL2, subcommandInfo?: {asPartOfMapDelete?: boolean, childrenToIgnore?: string[]}) {
const baseText = `Cannot delete node #${node._key}, since `;
if (!IsUserCreatorOrMod(userID, node)) return `${baseText}you are not the owner of this node. (or a mod)`;
... | if (!asPartOfCut && (node.parents || {}).VKeys(true).length <= 1) return `${baseText}doing so would orphan it. Try deleting it instead.`;
if (IsRootNode(node)) return `${baseText}it's the root-node of a map.`;
if (IsNodeSubnode(node)) return `${baseText}it's a subnode. Try deleting it instead.`;
return null; | random_line_split |
nodes.ts | import { CachedTransform, IsNaN, emptyArray, ToJSON, AsObj } from 'js-vextensions';
import { GetData, SplitStringBySlash_Cached, SlicePath, GetDataAsync, CachedTransform_WithStore } from 'Utils/FrameworkOverrides';
import { PathSegmentToNodeID } from 'Store/main/mapViews';
import { GetNodeL2, GetNodeL3 } from './nodes/... | (parentID: string, newChild: Pick<MapNode, '_key' | 'type'>, permissions: PermissionGroupSet, newHolderType?: HolderType) {
if (!CanGetBasicPermissions(permissions)) return "You're not signed in, or lack basic permissions.";
const parent = GetNode(parentID);
if (parent == null) return 'Parent data not found.';
// c... | ForNewLink_GetError | identifier_name |
nodes.ts | import { CachedTransform, IsNaN, emptyArray, ToJSON, AsObj } from 'js-vextensions';
import { GetData, SplitStringBySlash_Cached, SlicePath, GetDataAsync, CachedTransform_WithStore } from 'Utils/FrameworkOverrides';
import { PathSegmentToNodeID } from 'Store/main/mapViews';
import { GetNodeL2, GetNodeL3 } from './nodes/... |
export function GetNodes(): MapNode[] {
const nodeMap = GetNodeMap();
return CachedTransform('GetNodes', [], nodeMap, () => (nodeMap ? nodeMap.VValues(true) : []));
}
export function GetNodesL2(): MapNodeL2[] {
const nodes = GetNodes();
return CachedTransform('GetNodes', [], nodes, () => nodes.map(a => GetNodeL2(a... | {
return GetData('nodes');
} | identifier_body |
mod.rs | mod expr;
mod static_init;
mod stmt;
use std::collections::{HashMap, VecDeque};
use std::convert::TryFrom;
use crate::data::{prelude::*, types::FunctionType, Initializer, Scope, StorageClass};
use cranelift::codegen::{
self,
ir::{
entities::StackSlot,
function::Function,
stackslot::{St... | (
&mut self,
params: Vec<Symbol>,
func_start: Block,
location: &Location,
builder: &mut FunctionBuilder,
) -> CompileResult<()> {
// Cranelift requires that all block params are declared up front
let ir_vals: Vec<_> = params
.iter()
.ma... | store_stack_params | identifier_name |
mod.rs | mod expr;
mod static_init;
mod stmt;
use std::collections::{HashMap, VecDeque};
use std::convert::TryFrom;
use crate::data::{prelude::*, types::FunctionType, Initializer, Scope, StorageClass};
use cranelift::codegen::{
self,
ir::{
entities::StackSlot,
function::Function,
stackslot::{St... | location,
}))
};
let data = StackSlotData {
kind,
size,
offset: None,
};
let stack_slot = builder.create_stack_slot(data);
self.scope.insert(decl.symbol.id, Id::Local(stack_slot));
if let Some(init) = decl.in... | data: "cannot store items on the stack that are more than 4 GB, it will overflow the stack".into(), | random_line_split |
mod.rs | mod expr;
mod static_init;
mod stmt;
use std::collections::{HashMap, VecDeque};
use std::convert::TryFrom;
use crate::data::{prelude::*, types::FunctionType, Initializer, Scope, StorageClass};
use cranelift::codegen::{
self,
ir::{
entities::StackSlot,
function::Function,
stackslot::{St... |
}
self.scope.exit();
builder.seal_all_blocks();
builder.finalize();
let flags = settings::Flags::new(settings::builder());
if self.debug {
println!("{}", func);
}
if let Err(err) = codegen::verify_function(&func, &flags) {
panic... | {
// void function, return nothing
builder.ins().return_(&[]);
} | conditional_block |
mod.rs | mod expr;
mod static_init;
mod stmt;
use std::collections::{HashMap, VecDeque};
use std::convert::TryFrom;
use crate::data::{prelude::*, types::FunctionType, Initializer, Scope, StorageClass};
use cranelift::codegen::{
self,
ir::{
entities::StackSlot,
function::Function,
stackslot::{St... |
fn compile_func(
&mut self,
id: InternedStr,
func_type: FunctionType,
sc: StorageClass,
stmts: Vec<Stmt>,
location: Location,
) -> CompileResult<()> {
let signature = func_type.signature(self.module.isa());
let func_id = self.declare_func(id.clone... | {
// Cranelift requires that all block params are declared up front
let ir_vals: Vec<_> = params
.iter()
.map(|param| {
let ir_type = param.ctype.as_ir_type();
Ok(builder.append_block_param(func_start, ir_type))
})
.collect:... | identifier_body |
main.py | """An endpoint to run the speed benchmarks from."""
import numpy as np
import scipy as sp
import scipy.sparse
import matplotlib.pyplot as plt
import os
import argparse
import itertools
from contexttimer import Timer
from csindexer import indexer as csindexer
# Use absolute paths to avoid any issues.
project_dir = o... |
if __name__ == "__main__":
# Dependent variable gets plotted on x-axis, all others are separate lines
# on the plot.
# Get the list of separate models to be plotted.
if config['n'] != []:
# Override the rows and cols using n (so the sparse matrix is square).
variables = ['sort', 'n_... | """A function for timing our cxindexer and scipy indexer. It first creates
sparse matrices, sorts if necessary, runs indexers on both and returns
the times."""
if debug:
print("Benchmarking:\n\tSORT = %s\n\tN_THREADS = %s\n\tSPARSE_FORMAT ="
" %s\n\tROWS = %s\n\tCOLS = %s\n\tNNZ = %s\n... | identifier_body |
main.py | """An endpoint to run the speed benchmarks from."""
import numpy as np
import scipy as sp
import scipy.sparse
import matplotlib.pyplot as plt
import os
import argparse
import itertools
from contexttimer import Timer
from csindexer import indexer as csindexer
# Use absolute paths to avoid any issues.
project_dir = o... | (sort, n_threads, sparse_format, rows, cols, nnz, n_indexers,
search_type, operation, debug):
"""A function for timing our cxindexer and scipy indexer. It first creates
sparse matrices, sorts if necessary, runs indexers on both and returns
the times."""
if debug:
print("Benchmarki... | index_time | identifier_name |
main.py | """An endpoint to run the speed benchmarks from."""
import numpy as np
import scipy as sp
import scipy.sparse
import matplotlib.pyplot as plt
import os
import argparse
import itertools
from contexttimer import Timer
from csindexer import indexer as csindexer
# Use absolute paths to avoid any issues.
project_dir = o... |
elif sparse_format == 'CSC':
M = sp.sparse.csc_matrix(M)
else:
raise Exception("sparse_format must be either CSR or CSC.")
if debug:
print("\tTime to convert sparse matrix: %s" % t.elapsed)
# Sort.
with Timer() as t:
if sort:
if sparse_f... | M = sp.sparse.csr_matrix(M) | conditional_block |
main.py | """An endpoint to run the speed benchmarks from."""
import numpy as np
import scipy as sp
import scipy.sparse
import matplotlib.pyplot as plt
import os
import argparse
import itertools
from contexttimer import Timer
from csindexer import indexer as csindexer
# Use absolute paths to avoid any issues.
project_dir = o... | elif sparse_format == 'CSC':
M = sp.sparse.csc_matrix(M)
else:
raise Exception("sparse_format must be either CSR or CSC.")
if debug:
print("\tTime to convert sparse matrix: %s" % t.elapsed)
# Sort.
with Timer() as t:
if sort:
if sparse_fo... | M = sp.sparse.csr_matrix(M) | random_line_split |
feature-select.py | import os
import sys
import pandas as pd
import numpy as np
# from sklearn.model_selection import train_test_split
# from sklearn.svm import SVC
from sklearn import preprocessing
# from sklearn.externals import joblib
import seaborn
import matplotlib.pyplot as plt
import tensorflow as tf
def stop():
... | cat( [temp, data_list[count]], axis = 0)
temp = temp.reset_index() #重设索引
temp.drop(['index'],axis=1,inplace=True) #去除多余索引
return temp
def get_next_batch(all_data,batch_size,step):
row_num = all_data.shape[0]
batch_num = row_num/batch_size
batch_count = step%batch_... | ],axis=1,inplace=True) #去除多余索引
def pack_data_list(data_list):
temp = data_list[0]
row_num = len(data_list)
for count in range(1,row_num):
temp = pd.con | conditional_block |
feature-select.py | import os
import sys
import pandas as pd
import numpy as np
# from sklearn.model_selection import train_test_split
# from sklearn.svm import SVC
from sklearn import preprocessing
# from sklearn.externals import joblib
import seaborn
import matplotlib.pyplot as plt
import tensorflow as tf
def stop():
... | um[2]], initializer=tf.constant_initializer(0.0))
layer3 = tf.nn.tanh(tf.matmul(layer2, weights3) + biases3)
weights_out = get_weight_variable("weights_out",[layer_node_num[2], output_num], regularizer)
biases_out = tf.get_variable("biases_out", [output_num], initializer=tf.constant_initializer(0.0))
layer_out = ... | .nn.relu(tf.matmul(layer1, weights2) + biases2)
weights3 = get_weight_variable("weights3", [layer_node_num[1], layer_node_num[2]],regularizer)
biases3 = tf.get_variable("biases3", [layer_node_n | identifier_body |
feature-select.py | import os
import sys
import pandas as pd
import numpy as np
# from sklearn.model_selection import train_test_split
# from sklearn.svm import SVC
from sklearn import preprocessing
# from sklearn.externals import joblib
import seaborn
import matplotlib.pyplot as plt
import tensorflow as tf
def stop():
... | g='ISO-8859-1')
drop_list = [] #去除字符串形式的数据
for col in base_dataset:
if base_dataset.loc[:,col].dtype == 'object':
drop_list.append(col)
base_dataset.drop(drop_list,axis=1,inplace=True)
drop_index_rule(base_dataset, np.isnan(base_dataset.family_income)) #去除缺省行
base_datase... | e.csv",encodin | identifier_name |
feature-select.py | import os
import sys
import pandas as pd
import numpy as np
# from sklearn.model_selection import train_test_split
# from sklearn.svm import SVC
from sklearn import preprocessing
# from sklearn.externals import joblib
import seaborn
import matplotlib.pyplot as plt
import tensorflow as tf
def stop():
... |
with tf.control_dependencies([train_step, variables_averages_op]):
train_op = tf.no_op(name='train')
saver = tf.train.Saver()
with tf.Session() as sess:
writer = tf.summary.FileWriter("logs/", sess.graph)
tf.global_variables_initializer().run()
plt.ion() # 开启一个画图的窗... | # AdamOptimizer
# FtrlOptimizer
# RMSPropOptimizer
# train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss, global_step=global_step)
train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss, global_step=global_step)
| random_line_split |
misc.py | import copy
import os
import re
import time
from contextlib import contextmanager
from typing import *
import numpy as np
from heapdict import heapdict
__all__ = [
'PatternType',
'Singleton', 'NOT_SET',
'format_duration', 'ETA', 'minibatch_slices_iterator',
'optional_apply', 'validate_enum_arg',
... |
if not skip_incomplete and start < length:
yield slice(start, length, 1)
def optional_apply(f, value):
"""
If `value` is not None, return `f(value)`, otherwise return None.
>>> optional_apply(int, None) is None
True
>>> optional_apply(int, '123')
123
Args:
f: The fun... | yield slice(start, start + batch_size, 1)
start += batch_size | conditional_block |
misc.py | import copy
import os
import re
import time
from contextlib import contextmanager
from typing import *
import numpy as np
from heapdict import heapdict
__all__ = [
'PatternType',
'Singleton', 'NOT_SET',
'format_duration', 'ETA', 'minibatch_slices_iterator',
'optional_apply', 'validate_enum_arg',
... |
def optional_apply(f, value):
"""
If `value` is not None, return `f(value)`, otherwise return None.
>>> optional_apply(int, None) is None
True
>>> optional_apply(int, '123')
123
Args:
f: The function to apply on `value`.
value: The value, maybe None.
"""
if value... | """
Iterate through all the mini-batch slices.
>>> arr = np.arange(10)
>>> for batch_s in minibatch_slices_iterator(len(arr), batch_size=4):
... print(arr[batch_s])
[0 1 2 3]
[4 5 6 7]
[8 9]
>>> for batch_s in minibatch_slices_iterator(
... len(arr), batch_size=4, skip_i... | identifier_body |
misc.py | import copy
import os
import re
import time
from contextlib import contextmanager
from typing import *
import numpy as np
from heapdict import heapdict
__all__ = [
'PatternType',
'Singleton', 'NOT_SET',
'format_duration', 'ETA', 'minibatch_slices_iterator',
'optional_apply', 'validate_enum_arg',
... | self._nodes.append(this_node)
self._topo_sorted = None
self._values[type_] = value
def __getitem__(self, type_: type) -> TValue:
if self._topo_sorted is None:
self._topo_sort()
for t in reversed(self._topo_sorted):
if t is type_ or issubclass(... | for node in self._nodes:
if issubclass(type_, node.type):
node.add_child(this_node)
elif issubclass(node.type, type_):
this_node.add_child(node) | random_line_split |
misc.py | import copy
import os
import re
import time
from contextlib import contextmanager
from typing import *
import numpy as np
from heapdict import heapdict
__all__ = [
'PatternType',
'Singleton', 'NOT_SET',
'format_duration', 'ETA', 'minibatch_slices_iterator',
'optional_apply', 'validate_enum_arg',
... | (self):
return 'NOT_SET'
NOT_SET = NotSet()
def format_duration(seconds: Union[float, int],
short_units: bool = True,
keep_zeros: bool = False):
"""
Format specified time duration as human readable text.
>>> format_duration(0)
'0s'
>>> format_dura... | __repr__ | identifier_name |
cube_reader.py | import os
import re
import file_writer
import numpy as np
from numpy import unravel_index
import datetime
import matplotlib
import matplotlib.pyplot as plt
from matplotlib import rc
from scipy import signal
import peakutils
from lmfit import minimize, Parameters, Model
from astropy.io import fits
import warning... | header = fits_file[0].header
image_data = fits_file[1].data
segmentation_data = fits_file[2].data
header_keywords = {'CRVAL3': 0, 'CRPIX3': 0, 'CD3_3': 0}
# clause to differentiate between CDELT3 and CD3_3
for hdr_key, hdr_value in header_keywords.items():
# finding required header va... | random_line_split | |
cube_reader.py | import os
import re
import file_writer
import numpy as np
from numpy import unravel_index
import datetime
import matplotlib
import matplotlib.pyplot as plt
from matplotlib import rc
from scipy import signal
import peakutils
from lmfit import minimize, Parameters, Model
from astropy.io import fits
import warning... |
spectra_stacker(file_name)
# one figure to rule them all
main_fig = plt.figure(1)
# calling data once will be enough
im_coll_data = image_collapser(file_name)
spectra_data = spectrum_creator(file_name)
sr = wavelength_solution(file_name)
gs_data = spectra_analysis(file_name, sky_fil... | s.mkdir(data_dir)
| conditional_block |
cube_reader.py | import os
import re
import file_writer
import numpy as np
from numpy import unravel_index
import datetime
import matplotlib
import matplotlib.pyplot as plt
from matplotlib import rc
from scipy import signal
import peakutils
from lmfit import minimize, Parameters, Model
from astropy.io import fits
import warning... |
ot_fig = plt.figure(6)
# plotting the data for the cutout [OII] region
ot_x = df_data['x_region']
ot_y = df_data['y_region']
plt.plot(ot_x, ot_y, linewidth=1.5, color="#000000")
## plotting the standard deviation region in the [OII] section
std_x = df_... | phs_otwo_region(): | identifier_name |
cube_reader.py | import os
import re
import file_writer
import numpy as np
from numpy import unravel_index
import datetime
import matplotlib
import matplotlib.pyplot as plt
from matplotlib import rc
from scipy import signal
import peakutils
from lmfit import minimize, Parameters, Model
from astropy.io import fits
import warning... |
def spectrum_creator(file_name):
""" creating a spectra from the area as defined in the segementation area """
file_data = read_file(file_name)
image_data = file_data[1]
segmentation_data = file_data[2]
collapsed_data = image_collapser(file_name)
# spectrum for central pixel
cp_brig... | """ collapses image data so it can be passed as a heatmap """
file_data = read_file(file_name)
header_data = file_data[0]
image_data = file_data[1]
data_shape = np.shape(image_data)
ra_axis = data_shape[2]
dec_axis = data_shape[1]
wl_axis = data_shape[0]
image_median... | identifier_body |
route_import.go | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may ... |
func OpenAPI3ToRoute(swagger *openapi3.Swagger) ([]*entity.Route, error) {
var routes []*entity.Route
paths := swagger.Paths
var upstream *entity.UpstreamDef
var err error
for k, v := range paths {
k = regPathRepeat.ReplaceAllString(k, "")
upstream = &entity.UpstreamDef{}
if up, ok := v.Extensions["x-apisi... | {
var parsed []PathValue
var routes = map[string]*entity.Route{}
for _, value := range values {
value.Value.OperationID = strings.Replace(value.Value.OperationID, value.Method, "", 1)
var eq = false
for _, v := range parsed {
if utils.ValueEqual(v.Value, value.Value) {
eq = true
if routes[v.Method].... | identifier_body |
route_import.go | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may ... | if schema, ok := securitySchemes[name]; ok {
value := schema.Value
if value == nil {
continue
}
// basic auth
if value.Type == "http" && value.Scheme == "basic" {
plugins["basic-auth"] = map[string]interface{}{}
//username, ok := value.Extensions["username"]
//if !ok {
/... | // todo: import consumers
for _, securities := range security {
for name := range securities { | random_line_split |
route_import.go | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may ... |
}
var values []PathValue
if v.Get != nil {
value := PathValue{
Method: http.MethodGet,
Value: v.Get,
}
values = append(values, value)
}
if v.Post != nil {
value := PathValue{
Method: http.MethodPost,
Value: v.Post,
}
values = append(values, value)
}
if v.Head != nil {... | {
return nil, err
} | conditional_block |
route_import.go | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may ... | (val *openapi3.Operation) (*entity.Route, error) {
routeMap := map[string]interface{}{}
for key, val := range val.Extensions {
if strings.HasPrefix(key, "x-apisix-") {
routeMap[strings.TrimPrefix(key, "x-apisix-")] = val
}
}
route := new(entity.Route)
routeJson, err := json.Marshal(routeMap)
if err != nil... | parseExtension | identifier_name |
ml_ex_03.py | #!/usr/bin/python
import sys,os,csv
import pandas
import numpy as np
import math
from sklearn.model_selection import StratifiedKFold
from sklearn import svm as SVM
from sklearn.decomposition import PCA
from sklearn.neighbors import KNeighborsClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.e... |
def getLabels(fileName):
labelData = load_data(dirPath + "/" + fileName)
labels = labelData[:,0].clip(min=0)
return np.array(labels)
def svm_intern_folds(data_train, data_test, labelsTrain, labelsTest):
acxmax = 0
c_max=0
gamma_max=0
for c in [2**(-5), 1, 2**(5), 2**(10)]:
for gam... | lineNum = rawData.shape[0]
colNum = rawData.shape[1]
data = np.array(rawData[0:lineNum, 0:colNum-1])
for i in range(lineNum):
classList.append(rawData[i][colNum - 1])
return [data, np.array(classList) ] | identifier_body |
ml_ex_03.py | #!/usr/bin/python
import sys,os,csv
import pandas
import numpy as np
import math
from sklearn.model_selection import StratifiedKFold
from sklearn import svm as SVM
from sklearn.decomposition import PCA
from sklearn.neighbors import KNeighborsClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.e... | (matrix, percent):
print "\n---- PCA - Choose components number ----"
print "Variance :", percent
mat = np.matrix(matrix) * np.matrix(matrix).transpose()
U,S,V = np.linalg.svd(mat)
#print U.shape, S.shape, V.shape
s_sum_all = sum(S)
totalComponents = matrix.shape[1]
num = totalCompone... | chooseComponentsNumber | identifier_name |
ml_ex_03.py | #!/usr/bin/python
import sys,os,csv
import pandas
import numpy as np
import math
from sklearn.model_selection import StratifiedKFold
from sklearn import svm as SVM
from sklearn.decomposition import PCA
from sklearn.neighbors import KNeighborsClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.e... | c_max = c
gamma_max = gamm
return [acxmax, c_max, gamma_max]
def chooseComponentsNumber(matrix, percent):
print "\n---- PCA - Choose components number ----"
print "Variance :", percent
mat = np.matrix(matrix) * np.matrix(matrix).transpose()
U,S,V = np.linalg.svd(m... | accuracy = svm.score(data_test, labelsTest)
if accuracy > acxmax:
acxmax = accuracy | random_line_split |
ml_ex_03.py | #!/usr/bin/python
import sys,os,csv
import pandas
import numpy as np
import math
from sklearn.model_selection import StratifiedKFold
from sklearn import svm as SVM
from sklearn.decomposition import PCA
from sklearn.neighbors import KNeighborsClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.e... |
final_accuracy = final_accuracy + model_score(alg, params_final,
new_data_train,
new_labels_train,
new_data_test,
... | acx = params[0]
params_final[0] = params[1]
if len(params) > 2:
params_final[1] = params[2] | conditional_block |
fork_resolver.rs | /*
* Copyright 2018 Intel Corporation
*
* 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 agre... | // Delete states for all blocks not in chain
let chain_len_to_delete = chain_head.block_num - cache_block.block_num;
delete_states_upto(
cache_block.block_id,
chain_head.clone().block_id,
... | // Mark all blocks upto common ancestor
// in the chain as invalid. | random_line_split |
fork_resolver.rs | /*
* Copyright 2018 Intel Corporation
*
* 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 agre... | else {
fork_won = if fork_cc < chain_cc { true } else { false };
}
}
}
if fork_won {
info!("Discarding the block in progress.");
service.cancel_block();
pu... | {
fork_won = if get_cert_from(&block).duration_id
< get_cert_from(&chain_head).duration_id
{
true
} else {
false
... | conditional_block |
fork_resolver.rs | /*
* Copyright 2018 Intel Corporation
*
* 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 agre... | (
ancestor: BlockId,
head: BlockId,
delete_len: u64,
service: &mut Poet2Service,
state_store: &mut ConsensusStateStore,
) -> () {
let mut next = head;
let mut count = 0_u64;
loop {
if ancestor == next || count >= delete_len {
break;
}
count += 1;
... | delete_states_upto | identifier_name |
fork_resolver.rs | /*
* Copyright 2018 Intel Corporation
*
* 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 agre... |
fn get_cert_from(block: &Block) -> WaitCertificate {
let payload = block.payload.clone();
debug!("Extracted payload from block: {:?}", payload.clone());
let (wait_certificate, _) = poet2_util::payload_to_wc_and_sig(&payload);
debug!("Serialized wait_cert : {:?}", &wait_certificate);
serde_json::fr... | {
let mut next = head;
let mut count = 0_u64;
loop {
if ancestor == next || count >= delete_len {
break;
}
count += 1;
let state_ = state_store.get(next.clone());
if state_.is_err() {
debug!("State not found. Getting block via service.");
... | identifier_body |
roll.go | // A dice parser and roller library.
package main
import (
"errors"
"fmt"
"math/rand"
"regexp"
"strconv"
"strings"
"time"
"unicode"
"github.com/bwmarrin/discordgo"
"github.com/rs/zerolog/log"
)
/******************
COMMAND HANDLER
******************/
func RollHandler(s *discordgo.Session, m *discordgo.Mes... |
// Satisfies the rule for `Primary => '(' Expr ')' | DIE | NUMBER`
func (p *DiceParser) Primary() AstExpr {
//log.Error().Str("Val", fmt.Sprintf("%v", p.peek())).Bool("Eq?", p.peek().Type == Const).Msg("Fuck")
// If the current token is a Constant value..
if p.check(Const) {
t := p.consume()
// This should n... | {
expr := p.Primary()
for p.check(Factor) {
t := p.consume()
operator := t // A Token
right := p.Primary() // An AstExpr
expr = AstOp{expr, right, operator}
}
return expr
} | identifier_body |
roll.go | // A dice parser and roller library.
package main
import (
"errors"
"fmt"
"math/rand"
"regexp"
"strconv"
"strings"
"time"
"unicode"
"github.com/bwmarrin/discordgo"
"github.com/rs/zerolog/log"
)
/******************
COMMAND HANDLER
******************/
func RollHandler(s *discordgo.Session, m *discordgo.Mes... | left int
right int
}
func (t AstDie) Eval() (int, string) {
var sb strings.Builder
sb.WriteRune('[')
rand.Seed(time.Now().UnixNano())
rolls := make([]int, t.left)
for i := range rolls {
//out[i] = rand.Intn(max-min+1) + min
rolls[i] = rand.Intn(int(t.right)) + 1
sb.WriteString(strconv.Itoa(rolls[i]))
... | return int(c), strconv.Itoa(int(c))
}
// A die's value is rolled, 1-[right] rolled [left] times, then summed.
type AstDie struct { | random_line_split |
roll.go | // A dice parser and roller library.
package main
import (
"errors"
"fmt"
"math/rand"
"regexp"
"strconv"
"strings"
"time"
"unicode"
"github.com/bwmarrin/discordgo"
"github.com/rs/zerolog/log"
)
/******************
COMMAND HANDLER
******************/
func RollHandler(s *discordgo.Session, m *discordgo.Mes... |
// Walk and Resolve the AST
result, work := expr.Eval()
// Send a nice stylish message.
embed := &discordgo.MessageEmbed{
Author: &discordgo.MessageEmbedAuthor{},
Color: 0x00ff00, // Green
Description: strings.Join(args, ""),
Fields: []*discordgo.MessageEmbedField{
{
Name: "Rolls",
... | {
s.ChannelMessageSend(m.ChannelID, fmt.Sprintf("Errs: %v\n", parser.errors))
} | conditional_block |
roll.go | // A dice parser and roller library.
package main
import (
"errors"
"fmt"
"math/rand"
"regexp"
"strconv"
"strings"
"time"
"unicode"
"github.com/bwmarrin/discordgo"
"github.com/rs/zerolog/log"
)
/******************
COMMAND HANDLER
******************/
func | (s *discordgo.Session, m *discordgo.MessageCreate, args []string) {
// If they used !roll, remove that from the args list. Otherwise they used ![expr]
if args[0] == "roll" {
args = args[1:]
}
// Convert the input string into a token stream
tokens, err := tokenizeExpr(strings.Join(args, ""))
if err != nil {
s... | RollHandler | identifier_name |
OlMapView.js | OlMapView = function(){
this.map = null;
this.fromProjection = new OpenLayers.Projection("EPSG:4326");
this.toProjection = new OpenLayers.Projection("EPSG:900913");
this.baseLayer = null;
this.dotLayer = null;
this.contentlensManager = null;
//example
// this.strategy = null;
// this.clusters = null;
th... |
ctx.putImageData(imgd, 0, 0);
evt.tile.imgDiv.removeAttribute("crossorigin");
evt.tile.imgDiv.src = ctx.canvas.toDataURL();
}
}
}
});
this.map.addLayer(this.baseLayer);
// var style = new OpenLayers.Style({
// pointRadius: "${ra... | {
var tmp = (3 * pix[i] + 4 * pix[i + 1] + pix[i + 2]) / 8;
pix[i] = pix[i + 1] = pix[i + 2] = Math.sqrt( tmp / 256.0 ) * 256 * 1.05;
} | conditional_block |
OlMapView.js | OlMapView = function(){
| this.dotLayer = null;
this.contentlensManager = null;
//example
// this.strategy = null;
// this.clusters = null;
this.features = [];
this.tweetsHeatmapManager = null;
// histogramManager = null;
//polygon selection:
this.polygon_layer = null;
this.cachedCenter = [];
this.cachedZoom = null;
};
OlMapVi... | this.map = null;
this.fromProjection = new OpenLayers.Projection("EPSG:4326");
this.toProjection = new OpenLayers.Projection("EPSG:900913");
this.baseLayer = null; | random_line_split |
actions.rs | use crate::{
dkg_contract::{DKG as DKGContract, DKG_ABI},
opts::*,
};
use rand::{CryptoRng, RngCore};
use std::{fs::File, io::Write, sync::Arc};
use dkg_core::{
primitives::{joint_feldman::*, resharing::RDKG, *},
DKGPhase, Phase2Result,
};
use anyhow::Result;
use ethers::prelude::*;
use ethers::provid... |
Err(err) => Err(anyhow::anyhow!("DKG error: {}", err)),
}
}
#[derive(serde::Serialize, Debug)]
struct OutputJson {
#[serde(rename = "publicKey")]
public_key: String,
#[serde(rename = "publicPolynomial")]
public_polynomial: String,
#[serde(rename = "share")]
share: String,
}
async ... | {
println!("Success. Your share and threshold pubkey are ready.");
if let Some(path) = output_path {
let file = File::create(path)?;
write_output(&file, &output)?;
} else {
write_output(std::io::stdout(), &output)?;
}
... | conditional_block |
actions.rs | use crate::{
dkg_contract::{DKG as DKGContract, DKG_ABI},
opts::*,
};
use rand::{CryptoRng, RngCore};
use std::{fs::File, io::Write, sync::Arc};
use dkg_core::{
primitives::{joint_feldman::*, resharing::RDKG, *},
DKGPhase, Phase2Result,
};
use anyhow::Result;
use ethers::prelude::*;
use ethers::provid... |
let contract = DKGContract::new(opts.contract_address, client);
for addr in opts.address {
let tx = contract.allowlist(addr).block(BlockNumber::Pending);
let tx = tx.send().await?.await?;
println!("Sent `allow` tx for {:?} (hash: {:?})", addr, tx);
}
Ok(())
}
pub async fn sta... | let client = Arc::new(client); | random_line_split |
actions.rs | use crate::{
dkg_contract::{DKG as DKGContract, DKG_ABI},
opts::*,
};
use rand::{CryptoRng, RngCore};
use std::{fs::File, io::Write, sync::Arc};
use dkg_core::{
primitives::{joint_feldman::*, resharing::RDKG, *},
DKGPhase, Phase2Result,
};
use anyhow::Result;
use ethers::prelude::*;
use ethers::provid... | <P, C, R, M: Middleware + 'static>(
mut dkg: DKGContract<M>,
phase0: P,
rng: &mut R,
output_path: Option<String>,
) -> Result<()>
where
C: Curve,
// We need to bind the Curve's Point and Scalars to the Scheme
// S: Scheme<Public = <C as Curve>::Point, Private = <C as Curve>::Scalar>,
P: ... | run_dkg | identifier_name |
transaction_verify_centre.rs | //! The `tvu` module implements the Transaction Validation Unit, a
//! multi-stage transaction validation pipeline in software.
//!
//! 1. BlobFetchStage
//! - Incoming blobs are picked up from the TVU sockets and repair socket.
//! 2. RetransmitStage
//! - Blobs are windowed until a contiguous chunk is available. Thi... | .skip_while(|line| line.starts_with("#!"))
.skip_while(|line| line.is_empty())
.take(2)
.map(|s| s.trim_start_matches("# "));
!LICENSE_HEADER.lines().eq(maybe_license)
}
};
if missing_header {
return Err("missing a lice... | random_line_split | |
transaction_verify_centre.rs | //! The `tvu` module implements the Transaction Validation Unit, a
//! multi-stage transaction validation pipeline in software.
//!
//! 1. BlobFetchStage
//! - Incoming blobs are picked up from the TVU sockets and repair socket.
//! 2. RetransmitStage
//! - Blobs are windowed until a contiguous chunk is available. Thi... | {
pub fetch: Vec<UdpSocket>,
pub repair: UdpSocket,
pub retransmit: UdpSocket,
}
impl Tvu {
/// This service receives messages from a leader in the network and processes the transactions
/// on the bank state.
/// # Arguments
/// * `node_group_info` - The node_group_info state.
/// * `... | Sockets | identifier_name |
transaction_verify_centre.rs | //! The `tvu` module implements the Transaction Validation Unit, a
//! multi-stage transaction validation pipeline in software.
//!
//! 1. BlobFetchStage
//! - Incoming blobs are picked up from the TVU sockets and repair socket.
//! 2. RetransmitStage
//! - Blobs are windowed until a contiguous chunk is available. Thi... |
}
impl Service for Tvu {
type JoinReturnType = ();
fn join(self) -> thread::Result<()> {
self.retransmit_stage.join()?;
self.fetch_stage.join()?;
self.storage_stage.join()?;
if self.blockstream_service.is_some() {
self.blockstream_service.unwrap().join()?;
... | {
let keypair: Arc<Keypair> = node_group_info
.read()
.expect("Unable to read from node_group_info during Tvu creation")
.keypair
.clone();
let Sockets {
repair: repair_socket,
fetch: fetch_sockets,
retransmit: retransm... | identifier_body |
transaction_verify_centre.rs | //! The `tvu` module implements the Transaction Validation Unit, a
//! multi-stage transaction validation pipeline in software.
//!
//! 1. BlobFetchStage
//! - Incoming blobs are picked up from the TVU sockets and repair socket.
//! 2. RetransmitStage
//! - Blobs are windowed until a contiguous chunk is available. Thi... |
};
if missing_header {
return Err("missing a license header".into());
}
Ok(())
}
#[cfg(test)]
pub mod tests {
use super::*;
use crate::treasury_stage::create_test_recorder;
use crate::block_buffer_pool::get_tmp_ledger_path;
use crate::node_group_info::{NodeGroupInfo, Node};
... | {
let maybe_license = contents
.lines()
.skip_while(|line| line.starts_with("#!"))
.skip_while(|line| line.is_empty())
.take(2)
.map(|s| s.trim_start_matches("# "));
!LICENSE_HEADER.lines().eq(maybe_license)
... | conditional_block |
process.go | // Copyright 2018 The QOS Authors
package buyad
import (
"encoding/json"
"github.com/QOSGroup/qbase/txs"
qbasetypes "github.com/QOSGroup/qbase/types"
qostxs "github.com/QOSGroup/qos/module/bank/txs"
qostxtype "github.com/QOSGroup/qos/module/bank/types"
qostypes "github.com/QOSGroup/qos/types"
"github.com/QOSGr... | pper(coin.Name) == "QOS" {
ti.QOS = ti.QOS.Add(coin.Amount)
} else {
ti.QSCs = append(ti.QSCs, &coin)
}
}
return ti
}
// RetrieveBuyer 查询购买者
func RetrieveBuyer(cdc *wire.Codec, articleHash string) string {
var result common.Result
result.Code = common.ResultCodeSuccess
buyer, err := jianqian.QueryArti... | if strings.ToU | identifier_name |
process.go | // Copyright 2018 The QOS Authors
package buyad
import (
"encoding/json"
"github.com/QOSGroup/qbase/txs"
qbasetypes "github.com/QOSGroup/qbase/types"
qostxs "github.com/QOSGroup/qos/module/bank/txs"
qostxtype "github.com/QOSGroup/qos/module/bank/types"
qostypes "github.com/QOSGroup/qos/types"
"github.com/QOSGr... | log.Printf("buyad.buyAd QueryArticleBuyer articleBuy:%+v, err:%+v", articleBuy, err)
if err == nil {
if articleBuy.CheckStatus != jianqian.CheckStatusFail {
return nil, HasBeenBuyedErr
}
}
investors, err := jianqian.ListInvestors(config.GetCLIContext().QSCCliContext, cdc, article.ArticleHash)
if err != nil... | random_line_split | |
process.go | // Copyright 2018 The QOS Authors
package buyad
import (
"encoding/json"
"github.com/QOSGroup/qbase/txs"
qbasetypes "github.com/QOSGroup/qbase/types"
qostxs "github.com/QOSGroup/qos/module/bank/txs"
qostxtype "github.com/QOSGroup/qos/module/bank/types"
qostypes "github.com/QOSGroup/qos/types"
"github.com/QOSGr... | Receivers(result)
}
// calculateInvestorRevenue 计算投资者收入
func calculateInvestorRevenue(cdc *wire.Codec, investors jianqian.Investors, amount qbasetypes.BigInt) jianqian.Investors {
log.Printf("buyAd calculateInvestorRevenue investors:%+v", investors)
totalInvest := investors.TotalInvest()
log.Printf("buyAd calculat... | nd(
result,
warpperTransItem(
v.Address,
[]qbasetypes.BaseCoin{{Name: coinsName, Amount: v.Revenue}}))
}
}
return merge | conditional_block |
process.go | // Copyright 2018 The QOS Authors
package buyad
import (
"encoding/json"
"github.com/QOSGroup/qbase/txs"
qbasetypes "github.com/QOSGroup/qbase/types"
qostxs "github.com/QOSGroup/qos/module/bank/txs"
qostxtype "github.com/QOSGroup/qos/module/bank/types"
qostypes "github.com/QOSGroup/qos/types"
"github.com/QOSGr... | chResult(cdc *wire.Codec, heigth1 string, tx1 string) (string, error) {
qstarskey := "heigth:" + heigth1 + ",hash:" + tx1
d, err := config.GetCLIContext().QSCCliContext.QueryStore([]byte(qstarskey), common.QSCResultMapperName)
if err != nil {
return "", err
}
if d == nil {
return "", nil
}
var res []byte
er... | ew(txs.TxStd)
err := cdc.UnmarshalJSON([]byte(txb), ts)
log.Printf("buyad.BuyAdBackground ts:%+v, err:%+v", ts, err)
if err != nil {
return common.InternalError(err.Error()).Marshal()
}
cliCtx := *config.GetCLIContext().QSCCliContext
_, commitresult, err := utils.SendTx(cliCtx, cdc, ts)
log.Printf("buyad.BuyA... | identifier_body |
tensor.rs | use std::collections::HashSet;
use std::io::{Read, Seek};
use std::ops::Range;
use std::str::FromStr;
use std::sync::Mutex;
use crate::model::Model;
use tract_hir::internal::*;
#[derive(Debug, Default, Clone)]
pub struct TensorsValues(pub Vec<TensorValues>);
impl TensorsValues {
pub fn by_name(&self, name: &str)... |
self.by_input_ix_mut(ix).unwrap()
}
pub fn add(&mut self, other: TensorValues) {
let mut tensor = other.input_index.and_then(|ix| self.by_input_ix_mut(ix));
if tensor.is_none() {
tensor = other.name.as_deref().and_then(|ix| self.by_name_mut(ix))
}
if let S... | {
self.add(TensorValues { input_index: Some(ix), ..TensorValues::default() });
} | conditional_block |
tensor.rs | use std::collections::HashSet;
use std::io::{Read, Seek};
use std::ops::Range;
use std::str::FromStr;
use std::sync::Mutex;
use crate::model::Model;
use tract_hir::internal::*;
#[derive(Debug, Default, Clone)]
pub struct TensorsValues(pub Vec<TensorValues>);
impl TensorsValues {
pub fn by_name(&self, name: &str)... | (&mut self, name: &str) -> Option<&mut TensorValues> {
self.0.iter_mut().find(|t| t.name.as_deref() == Some(name))
}
pub fn by_name_mut_with_default(&mut self, name: &str) -> &mut TensorValues {
if self.by_name_mut(name).is_none() {
self.add(TensorValues { name: Some(name.to_string()... | by_name_mut | identifier_name |
tensor.rs | use std::collections::HashSet;
use std::io::{Read, Seek};
use std::ops::Range;
use std::str::FromStr;
use std::sync::Mutex;
use crate::model::Model;
use tract_hir::internal::*;
#[derive(Debug, Default, Clone)]
pub struct TensorsValues(pub Vec<TensorValues>);
impl TensorsValues {
pub fn by_name(&self, name: &str)... | values.iter().map(|v| tensor_for_fact(v.borrow(), None, None).map(|t| t.into())).collect()
}
pub fn make_inputs_for_model(model: &dyn Model) -> TractResult<TVec<TValue>> {
make_inputs(
&model
.input_outlets()
.iter()
.map(|&t| model.outlet_typedfact(t))
.... | }
Ok((0..tmp[0].len()).map(|turn| tmp.iter().map(|t| t[turn].clone()).collect()).collect())
}
fn make_inputs(values: &[impl std::borrow::Borrow<TypedFact>]) -> TractResult<TVec<TValue>> { | random_line_split |
tensor.rs | use std::collections::HashSet;
use std::io::{Read, Seek};
use std::ops::Range;
use std::str::FromStr;
use std::sync::Mutex;
use crate::model::Model;
use tract_hir::internal::*;
#[derive(Debug, Default, Clone)]
pub struct TensorsValues(pub Vec<TensorValues>);
impl TensorsValues {
pub fn by_name(&self, name: &str)... |
#[allow(unused_variables)]
pub fn tensor_for_fact(
fact: &TypedFact,
streaming_dim: Option<usize>,
tv: Option<&TensorValues>,
) -> TractResult<Tensor> {
if let Some(value) = &fact.konst {
return Ok(value.clone().into_tensor());
}
#[cfg(pulse)]
{
if fact.shape.stream_info().... | {
make_inputs(
&model
.input_outlets()
.iter()
.map(|&t| model.outlet_typedfact(t))
.collect::<TractResult<Vec<TypedFact>>>()?,
)
} | identifier_body |
setup.py | from numpy.distutils.core import setup, Extension
import distutils.sysconfig
import sys
import os
import os.path
import re
# Get BUILDTYPE for checking if this is intel-mac
buildtype = os.getenv("BUILDTYPE")
if buildtype:
buildtype = buildtype.strip()
if not buildtype:
raise ValueError("Environment variable BU... |
# HDF5_LIBDIR is only given if the HDF5 and NetCDF libraries are to be statically linked
hdf5_libdir = os.getenv("HDF5_LIBDIR")
if hdf5_libdir:
hdf5_libdir = hdf5_libdir.strip()
# SZ_LIBDIR is the location of the SZ library to be linked in
sz_libdir = os.getenv("SZ_LIBDIR")
if sz_libdir:
sz_libdir = sz_libdir... | random_line_split | |
setup.py | from numpy.distutils.core import setup, Extension
import distutils.sysconfig
import sys
import os
import os.path
import re
# Get BUILDTYPE for checking if this is intel-mac
buildtype = os.getenv("BUILDTYPE")
if buildtype:
buildtype = buildtype.strip()
if not buildtype:
raise ValueError("Environment variable BU... |
# Linking in the rest of the system libraries were moved to addn_link_flags
# in order to make sure the appropriate netcdff, netcdf, hdf5_hl, hdf5, and
# cairo libraries are used.
addn_link_args = [ ]
# Link to the appropriate netcdf libraries.
# The hdf5 libraries are only used to resolve netcdf library function
# ... | lib_list.extend(fer_lib_list)
lib_list.extend(fer_lib_list)
lib_list.extend(fer_lib_list)
lib_list.extend(fer_lib_list) | conditional_block |
viewer.ts | /******************************************************************************
*
* Copyright (c) 2018, the Perspective Authors.
*
* This file is part of the Perspective library, distributed under the terms
* of the Apache License 2.0. The full license can be found in the LICENSE
* file.
*
*/
import type * as... | (themes?: Array<string>): Promise<void> {
await this.load_wasm();
await this.instance.js_reset_themes(themes);
}
/**
* Gets the edit port, the port number for which `Table` updates from this
* `<perspective-viewer>` are generated. This port number will be present
* in the option... | resetThemes | identifier_name |
viewer.ts | /******************************************************************************
*
* Copyright (c) 2018, the Perspective Authors.
*
* This file is part of the Perspective library, distributed under the terms
* of the Apache License 2.0. The full license can be found in the LICENSE
* file.
*
*/
import type * as... |
/**
* Returns the `perspective.Table()` which was supplied to `load()`
*
* @category Data
* @param wait_for_table Whether to await `load()` if it has not yet been
* invoked, or fail immediately.
* @returns A `Promise` which resolves to a `perspective.Table`
* @example <caption>S... | {
await this.load_wasm();
await this.instance.js_set_auto_size(autosize);
} | identifier_body |
viewer.ts | /******************************************************************************
*
* Copyright (c) 2018, the Perspective Authors.
*
* This file is part of the Perspective library, distributed under the terms
* of the Apache License 2.0. The full license can be found in the LICENSE
* file.
*
*/
import type * as... |
}
/**
* Part of the Custom Elements API. This method is called by the browser,
* and should not be called directly by applications.
*
* @ignore
*/
async connectedCallback(): Promise<void> {
await this.load_wasm();
this.instance.connected_callback();
}
/**... | {
this.instance = new PerspectiveViewerElement(this);
} | conditional_block |
viewer.ts | /******************************************************************************
*
* Copyright (c) 2018, the Perspective Authors.
*
* This file is part of the Perspective library, distributed under the terms
* of the Apache License 2.0. The full license can be found in the LICENSE
* file.
*
*/
import type * as... | }
/**
* Register a new plugin via its custom element name. This method is called
* automatically as a side effect of importing a plugin module, so this
* method should only typically be called by plugin authors.
*
* @category Plugin
* @param name The `name` of the custom element ... | this.instance.connected_callback(); | random_line_split |
Toys.py | from datetime import datetime, timedelta
import json
import urllib.request
from enum import Enum
from random import randint, sample, choices
from typing import Optional
from discord.ext import commands, tasks
from discord import Embed, TextChannel
from Code.Cogs.Base import ConfiguredCog
from Code.Data import DataAcces... | # that we randomly picked, we move on to the next one safely.
random_channel_pick_list = sample(ConfiguredCog.config['content']['cookie_hunt_allowed_channels'],
len(ConfiguredCog.config['content']['cookie_hunt_allowed_channels']))
for selected_channel_na... | random_line_split | |
Toys.py | from datetime import datetime, timedelta
import json
import urllib.request
from enum import Enum
from random import randint, sample, choices
from typing import Optional
from discord.ext import commands, tasks
from discord import Embed, TextChannel
from Code.Cogs.Base import ConfiguredCog
from Code.Data import DataAcces... |
discord_user = self.bot.get_user(int(Discord_Id))
if discord_user:
user_name = discord_user.name
else:
user_name = f'Unknown ({Discord_Id})'
user_name = f'{user_name}:'
... | embed = Embed(title='Top Cookie Collectors',
color=ConfiguredCog.convert_color('#8a4b38'))
collectors_displayed = True | conditional_block |
Toys.py | from datetime import datetime, timedelta
import json
import urllib.request
from enum import Enum
from random import randint, sample, choices
from typing import Optional
from discord.ext import commands, tasks
from discord import Embed, TextChannel
from Code.Cogs.Base import ConfiguredCog
from Code.Data import DataAcces... |
def cog_unload(self):
"""Overridden from commands.Cog; stops the automated task."""
self._get_sketch_prompt.cancel()
@staticmethod
def _get_neat_date(date: datetime) -> str:
"""Takes a datetime object and converts the day and month into a cleanly formatted string.
:param ... | """Overridden from commands.Cog; starts the automated task."""
self._get_sketch_prompt.start() | identifier_body |
Toys.py | from datetime import datetime, timedelta
import json
import urllib.request
from enum import Enum
from random import randint, sample, choices
from typing import Optional
from discord.ext import commands, tasks
from discord import Embed, TextChannel
from Code.Cogs.Base import ConfiguredCog
from Code.Data import DataAcces... | (self) -> list:
"""Gets an arbitrarily ordered list of weights mapped to the cookie data dictionary.
:return: A list of weights.
"""
cookie_weights = []
for cookie_type in self.cookie_data:
cookie_weights.append(cookie_type['weight'])
return cookie_weight... | _get_cookie_weights | identifier_name |
rtic-i2s-audio-in-out.rs | //! # I2S example with rtic
//!
//! This application show how to use I2sDriver with interruption. Be careful to you ear, wrong
//! operation can trigger loud noise on the DAC output.
//!
//! # Hardware required
//!
//! * a STM32F411 based board
//! * I2S ADC and DAC, eg PCM1808 and PCM5102 from TI
//! * Audio signal at... |
// processing audio
#[task(binds = SPI5, local = [count: u32 = 0,process_c,process_p])]
fn process(cx: process::Context) {
let count = cx.local.count;
let process_c = cx.local.process_c;
let process_p = cx.local.process_p;
while let Some(mut smpl) = process_c.dequeue() {
... | {
writeln!(cx.local.logs_chan, "{}", message).unwrap();
} | identifier_body |
rtic-i2s-audio-in-out.rs | //! # I2S example with rtic
//!
//! This application show how to use I2sDriver with interruption. Be careful to you ear, wrong
//! operation can trigger loud noise on the DAC output.
//!
//! # Hardware required
//!
//! * a STM32F411 based board
//! * I2S ADC and DAC, eg PCM1808 and PCM5102 from TI
//! * Audio signal at... | (cx: i2s2::Context) {
let frame_state = cx.local.frame_state;
let frame = cx.local.frame;
let adc_p = cx.local.adc_p;
let i2s2_driver = cx.shared.i2s2_driver;
let status = i2s2_driver.status();
// It's better to read first to avoid triggering ovr flag
if status.rx... | i2s2 | identifier_name |
rtic-i2s-audio-in-out.rs | //! # I2S example with rtic
//!
//! This application show how to use I2sDriver with interruption. Be careful to you ear, wrong
//! operation can trigger loud noise on the DAC output.
//!
//! # Hardware required
//!
//! * a STM32F411 based board
//! * I2S ADC and DAC, eg PCM1808 and PCM5102 from TI
//! * Audio signal at... | let gpiob = device.GPIOB.split();
let gpioc = device.GPIOC.split();
let rcc = device.RCC.constrain();
let clocks = rcc
.cfgr
.use_hse(8u32.MHz())
.sysclk(96.MHz())
.hclk(96.MHz())
.pclk1(50.MHz())
.pclk2(100.MHz())
... | let gpioa = device.GPIOA.split(); | random_line_split |
Renderer.ts | /*
* surface -> canvas なレンダラ。
* HTMLCanvasElement もこの層で抽象化する
*/
import * as Util from "./Util";
import * as SDT from "ikagaka-shell-loader/lib/Model/SurfaceDefinitionTree";
import {Canvas, copy} from "./Canvas";
export class Renderer {
// GCの発生を抑えるためバッファを使いまわす
srfCnv: Canvas;
cnv: HTMLCanvasElement;
ctx: ... |
}
this.ctx.putImageData(imgdataA, 0, 0);
}
drawRegions(regions: SDT.SurfaceCollision[], description="notitle"): void {
this.ctx.font = "35px";
this.ctx.lineWidth = 4;
this.ctx.strokeStyle = "white";
this.ctx.strokeText(description, 5, 10);
this.ctx.fillStyle = "black";
this.ctx.fil... | ataB[iB + 3] === 0) dataA[iA + 3] = dataB[iB + 3];
} | conditional_block |
Renderer.ts | /*
* surface -> canvas なレンダラ。
* HTMLCanvasElement もこの層で抽象化する
*/
import * as Util from "./Util";
import * as SDT from "ikagaka-shell-loader/lib/Model/SurfaceDefinitionTree";
import {Canvas, copy} from "./Canvas";
export class Renderer {
// GCの発生を抑えるためバッファを使いまわす
srfCnv: Canvas;
cnv: HTMLCanvasElement;
ctx: ... | hape
this.srfCnv.basePosX += (-left);
}
if(right<0){
this.cnv.width += (-right); // reshape
}
if(top<0){
offsetY = (-top);
this.cnv.height += (-top); // reshape
this.srfCnv.basePosY += (-top);
}
if(bottom<0){
this.cnv.height += (-bottom... | prepareOverlay: reshape occured");
// 現状をtmpcnvへコピー
Util.fastcopy(this.cnv, this.tmpctx);
if(left<0){
offsetX = (-left);
this.cnv.width += (-left); // res | identifier_body |
Renderer.ts | /*
* surface -> canvas なレンダラ。
* HTMLCanvasElement もこの層で抽象化する
*/
import * as Util from "./Util";
import * as SDT from "ikagaka-shell-loader/lib/Model/SurfaceDefinitionTree";
import {Canvas, copy} from "./Canvas";
export class Renderer {
// GCの発生を抑えるためバッファを使いまわす
srfCnv: Canvas;
cnv: HTMLCanvasElement;
ctx: ... | Canvas {
// baseを決定
const bases = elms.filter(({type})=> type === "base");
const others = elms.filter(({type})=> type !== "base");
// element[MAX].base > element0 > element[MIN]
if(bases.length === 0){
// element[MIN]
// elms.length > 0なのでundefinedにはならない…はず。
// お前がbaseになるんだよ
... | }[]): | identifier_name |
Renderer.ts | /*
* surface -> canvas なレンダラ。
* HTMLCanvasElement もこの層で抽象化する
*/
import * as Util from "./Util";
import * as SDT from "ikagaka-shell-loader/lib/Model/SurfaceDefinitionTree";
import {Canvas, copy} from "./Canvas";
export class Renderer {
// GCの発生を抑えるためバッファを使いまわす
srfCnv: Canvas;
cnv: HTMLCanvasElement;
ctx: ... | }
}
let base = bases.slice(-1)[0]; /* last */
this.base(base.canvas);
others.forEach(({canvas, type, x, y})=>{
this.composeElement(canvas, type, x, y);
});
return this.srfCnv;
}
composeElement(canvas: Canvas, type: string, x=0, y=0): void {
switch (type) {
case "overla... | console.warn("SurfaceRenderer#composeElements: base surface not found. failback.", bases, others);
}else{
console.error("SurfaceRenderer#composeElements: cannot decide base surface.", base, others);
return this.srfCnv; | random_line_split |
crypto_box.rs | use crate::internal::rayon::rayon_exec;
use crate::internal::x25519;
use block_padding::Padding;
use crypto_box as lib_crypto_box;
use std::sync::Arc;
/// Length of the crypto box aead nonce.
/// Ideally this would be exposed from upstream but I didn't see a good way to get at it directly.
pub const NONCE_BYTES: usize... |
Err(_) => Ok(None),
}
})
.await
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test(flavor = "multi_thread")]
async fn it_can_encrypt_and_decrypt() {
for input in [
// Empty vec.
vec![],
// Small vec.
vec![0],
... | {
match block_padding::Iso7816::unpad(&decrypted_data) {
// @todo do we want associated data to enforce the originating DHT space?
Ok(unpadded) => Ok(Some(CryptoBoxData {
data: Arc::new(unpadded.to_vec()),
})),
... | conditional_block |
crypto_box.rs | use crate::internal::rayon::rayon_exec;
use crate::internal::x25519;
use block_padding::Padding;
use crypto_box as lib_crypto_box;
use std::sync::Arc;
/// Length of the crypto box aead nonce.
/// Ideally this would be exposed from upstream but I didn't see a good way to get at it directly.
pub const NONCE_BYTES: usize... | ];
to_encrypt.extend(padding_delimiter);
to_encrypt.extend(padding);
let encrypted_data = Arc::new(sender_box.encrypt(
AsRef::<[u8; NONCE_BYTES]>::as_ref(&nonce).into(),
to_encrypt.as_slice(),
)?);
// @todo do we want associated data to enforce t... | BLOCK_PADDING_SIZE
- (data.data.len() + 1) % BLOCK_PADDING_SIZE | random_line_split |
crypto_box.rs | use crate::internal::rayon::rayon_exec;
use crate::internal::x25519;
use block_padding::Padding;
use crypto_box as lib_crypto_box;
use std::sync::Arc;
/// Length of the crypto box aead nonce.
/// Ideally this would be exposed from upstream but I didn't see a good way to get at it directly.
pub const NONCE_BYTES: usize... | (slice: &[u8]) -> Result<Self, Self::Error> {
if slice.len() == NONCE_BYTES {
let mut inner = [0; NONCE_BYTES];
inner.copy_from_slice(slice);
Ok(Self(inner))
} else {
Err(crate::error::LairError::CryptoBoxNonceLength)
}
}
}
impl CryptoBoxNonce... | try_from | identifier_name |
crypto_box.rs | use crate::internal::rayon::rayon_exec;
use crate::internal::x25519;
use block_padding::Padding;
use crypto_box as lib_crypto_box;
use std::sync::Arc;
/// Length of the crypto box aead nonce.
/// Ideally this would be exposed from upstream but I didn't see a good way to get at it directly.
pub const NONCE_BYTES: usize... |
}
impl CryptoBoxData {
/// Length of newtype is length of inner.
pub fn len(&self) -> usize {
AsRef::<[u8]>::as_ref(self).len()
}
/// For clippy.
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}
impl From<Vec<u8>> for CryptoBoxData {
fn from(v: Vec<u8>) -> Self {
... | {
self.data.as_ref()
} | identifier_body |
scoped_signal_handler.rs | // Copyright 2021 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//! Provides a struct for registering signal handlers that get cleared on drop.
use std::convert::TryFrom;
use std::fmt;
use std::io::{Cursor, Write};... |
/// Represents a signal handler that is registered with a set of signals that unregistered when the
/// struct goes out of scope. Prefer a signalfd based solution before using this.
pub struct ScopedSignalHandler {
signals: Vec<Signal>,
}
impl ScopedSignalHandler {
/// Attempts to register `handler` with the... | {
// Make an effort to surface an error.
if catch_unwind(|| H::handle_signal(Signal::try_from(signum).unwrap())).is_err() {
// Note the following cannot be used:
// eprintln! - uses std::io which has locks that may be held.
// format! - uses the allocator which enforces mutual exclusion.... | identifier_body |
scoped_signal_handler.rs | // Copyright 2021 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//! Provides a struct for registering signal handlers that get cleared on drop.
use std::convert::TryFrom;
use std::fmt;
use std::io::{Cursor, Write};... |
line.clear();
}
}
/// Wait for a process to block either in a sleeping or disk sleep state.
fn wait_for_thread_to_sleep(tid: Pid, timeout: Duration) -> result::Result<(), errno::Error> {
let start = Instant::now();
loop {
if thread_is_sleeping(tid)? {
... | {
return Ok(matches!(
stripped.trim_start().chars().next(),
Some('S') | Some('D')
));
} | conditional_block |
scoped_signal_handler.rs | // Copyright 2021 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//! Provides a struct for registering signal handlers that get cleared on drop.
use std::convert::TryFrom;
use std::fmt;
use std::io::{Cursor, Write};... | // format! - uses the allocator which enforces mutual exclusion.
// Get the debug representation of signum.
let signal: Signal;
let signal_debug: &dyn fmt::Debug = match Signal::try_from(signum) {
Ok(s) => {
signal = s;
&signal as &dyn fmt::De... | // eprintln! - uses std::io which has locks that may be held. | random_line_split |
scoped_signal_handler.rs | // Copyright 2021 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//! Provides a struct for registering signal handlers that get cleared on drop.
use std::convert::TryFrom;
use std::fmt;
use std::io::{Cursor, Write};... | ;
/// # Safety
/// Safe because handle_signal is async-signal safe.
unsafe impl SignalHandler for EmptySignalHandler {
fn handle_signal(_: Signal) {}
}
/// Blocks until SIGINT is received, which often happens because Ctrl-C was pressed in an
/// interactive terminal.
///
/// Note: if you are using a multi-threaded... | EmptySignalHandler | identifier_name |
twitter.go | package core
import (
"context"
"errors"
"fmt"
"net/url"
"strings"
"github.com/iwataka/anaconda"
"github.com/iwataka/mybot/data"
"github.com/iwataka/mybot/models"
"github.com/iwataka/mybot/oauth"
"github.com/iwataka/mybot/utils"
"github.com/slack-go/slack"
)
// TwitterAPI is a wrapper of anaconda.TwitterA... |
func (a *TwitterAPI) GetSearch(query string, url url.Values) (anaconda.SearchResponse, error) {
return a.api.GetSearch(query, url)
}
func (a *TwitterAPI) GetUserSearch(searchTerm string, v url.Values) ([]anaconda.User, error) {
return a.api.GetUserSearch(searchTerm, v)
}
func (a *TwitterAPI) GetFavorites(vals url... | {
self, err := a.GetSelf()
if err != nil {
return utils.WithStack(err)
}
list, err := a.api.GetCollectionListByUserId(self.Id, nil)
if err != nil {
return utils.WithStack(err)
}
exists := false
var id string
for i, t := range list.Objects.Timelines {
if collection == t.Name {
exists = true
id = i
... | identifier_body |
twitter.go | package core
import (
"context"
"errors"
"fmt"
"net/url"
"strings"
"github.com/iwataka/anaconda"
"github.com/iwataka/mybot/data"
"github.com/iwataka/mybot/models"
"github.com/iwataka/mybot/oauth"
"github.com/iwataka/mybot/utils"
"github.com/slack-go/slack"
)
// TwitterAPI is a wrapper of anaconda.TwitterA... | (auth oauth.OAuthCreds, config Config, cache data.Cache) *TwitterAPI {
at, ats := auth.GetCreds()
var api models.TwitterAPI
if len(at) > 0 && len(ats) > 0 {
api = anaconda.NewTwitterApi(at, ats)
}
return NewTwitterAPI(api, config, cache)
}
func NewTwitterAPI(api models.TwitterAPI, config Config, cache data.Cach... | NewTwitterAPIWithAuth | identifier_name |
twitter.go | package core
import (
"context"
"errors"
"fmt"
"net/url"
"strings"
"github.com/iwataka/anaconda"
"github.com/iwataka/mybot/data"
"github.com/iwataka/mybot/models"
"github.com/iwataka/mybot/oauth"
"github.com/iwataka/mybot/utils"
"github.com/slack-go/slack"
)
// TwitterAPI is a wrapper of anaconda.TwitterA... | else {
users, err := a.api.GetUsersLookup(usernames, nil)
if err != nil {
return nil, utils.WithStack(err)
}
userids := []string{}
for _, u := range users {
userids = append(userids, u.IdStr)
}
v.Set("follow", strings.Join(userids, ","))
stream := a.api.PublicStreamFilter(v)
return &TwitterUser... | {
return nil, errors.New("No user specified")
} | conditional_block |
twitter.go | package core
import (
"context"
"errors"
"fmt"
"net/url"
"strings"
"github.com/iwataka/anaconda"
"github.com/iwataka/mybot/data"
"github.com/iwataka/mybot/models"
"github.com/iwataka/mybot/oauth"
"github.com/iwataka/mybot/utils"
"github.com/slack-go/slack"
)
// TwitterAPI is a wrapper of anaconda.TwitterA... | if err != nil {
return nil, nil, utils.WithStack(err)
}
}
return processedTweets, processedActions, nil
}
func (a *TwitterAPI) processTweet(
t anaconda.Tweet,
action data.Action,
slack *SlackAPI,
) error {
if action.Twitter.Retweet && !t.Retweeted {
var id int64
if t.RetweetedStatus == nil {
id = t... | random_line_split | |
wavelet_tree_pointer.rs | use bio::data_structures::rank_select::RankSelect;
use bv::BitVec;
use bv::BitsMut;
use itertools::Itertools;
use serde::{Deserialize, Serialize};
use snafu::{ensure, Snafu};
use std::fmt::Debug;
use std::hash::Hash;
use std::ops::Index;
///custom errors for the tree with pointer
#[derive(Debug, Snafu)]
pub enum Error... | + Clone + Ord + Debug>(alphabet: &[E], sequence: Vec<E>) -> BinNode {
let count = sequence.len();
if alphabet.len() <= 1 {
let value = BitVec::new_fill(true, count as u64);
BinNode {
value: RankSelect::new(value, 1),
left: None,
rig... | de<E: Hash | identifier_name |
wavelet_tree_pointer.rs | use bio::data_structures::rank_select::RankSelect;
use bv::BitVec;
use bv::BitsMut;
use itertools::Itertools;
use serde::{Deserialize, Serialize};
use snafu::{ensure, Snafu};
use std::fmt::Debug;
use std::hash::Hash;
use std::ops::Index;
///custom errors for the tree with pointer
#[derive(Debug, Snafu)]
pub enum Error... | nts a non-consuming Iterator for the WaveletTree
impl<'de, T> IntoIterator for &'de WaveletTree<T>
where
T: Hash + Clone + Ord + Debug + Copy + Serialize + Deserialize<'de>,
{
type Item = T;
type IntoIter = Iterhelper<'de, T>;
fn into_iter(self) -> Self::IntoIter {
Iterhelper {
posit... | f.value.bits().len()
}
}
///Impleme | identifier_body |
wavelet_tree_pointer.rs | use bio::data_structures::rank_select::RankSelect;
use bv::BitVec;
use bv::BitsMut;
use itertools::Itertools;
use serde::{Deserialize, Serialize};
use snafu::{ensure, Snafu};
use std::fmt::Debug;
use std::hash::Hash;
use std::ops::Index;
///custom errors for the tree with pointer
#[derive(Debug, Snafu)]
pub enum Error... | Iterhelper {
position: 0,
tree: self,
}
}
}
impl<'de, T> Iterator for Iterhelper<'de, T>
where
T: Hash + Clone + Ord + Debug + Copy + Serialize + Deserialize<'de>,
{
type Item = T;
fn next(&mut self) -> Option<Self::Item> {
self.position += 1;
let... | type Item = T;
type IntoIter = Iterhelper<'de, T>;
fn into_iter(self) -> Self::IntoIter { | random_line_split |
wavelet_tree_pointer.rs | use bio::data_structures::rank_select::RankSelect;
use bv::BitVec;
use bv::BitsMut;
use itertools::Itertools;
use serde::{Deserialize, Serialize};
use snafu::{ensure, Snafu};
use std::fmt::Debug;
use std::hash::Hash;
use std::ops::Index;
///custom errors for the tree with pointer
#[derive(Debug, Snafu)]
pub enum Error... | None
}
}
}
| conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.